From 6bccf59f5b39185fa1e74582a79ee914383c781b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B3zsef=20Sallai?= Date: Thu, 23 Feb 2023 15:23:59 +0200 Subject: [PATCH] improve quick discord RPC updates and prevent crashes --- src/discord/mod.rs | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/src/discord/mod.rs b/src/discord/mod.rs index 8c2ac33..cd47439 100644 --- a/src/discord/mod.rs +++ b/src/discord/mod.rs @@ -1,3 +1,5 @@ +use std::sync::Mutex; + use discord_rich_presence::{ activity::{Activity, Assets, Button}, DiscordIpc, DiscordIpcClient, @@ -23,6 +25,8 @@ pub struct DiscordRPC { max_life: u16, stage_name: String, difficulty: Option, + + can_update: Mutex, } impl DiscordRPC { @@ -37,15 +41,22 @@ impl DiscordRPC { max_life: 0, stage_name: String::new(), difficulty: None, + + can_update: Mutex::new(true), } } pub fn start(&mut self) -> GameResult { log::info!("Starting Discord RPC client..."); + let mut can_update = self.can_update.lock().unwrap(); + *can_update = false; + match self.client.connect() { Ok(_) => { self.ready = true; + *can_update = true; + Ok(()) } Err(e) => Err(GameError::DiscordRPCError(e.to_string())), @@ -53,10 +64,18 @@ impl DiscordRPC { } fn update(&mut self) -> GameResult { - if !self.enabled { + if !self.enabled || !self.ready { return Ok(()); } + let mut can_update = self.can_update.lock().unwrap(); + + if !*can_update { + return Ok(()); + } + + *can_update = false; + let (state, details) = match self.state { DiscordRPCState::Initializing => ("Initializing...".to_owned(), "Just started playing".to_owned()), DiscordRPCState::Idling => ("In the menus".to_owned(), "Idling".to_owned()), @@ -95,9 +114,14 @@ impl DiscordRPC { .buttons(vec![Button::new("doukutsu-rs on GitHub", "https://github.com/doukutsu-rs/doukutsu-rs")]); match self.client.set_activity(activity) { - Ok(_) => Ok(()), - Err(e) => Err(GameError::DiscordRPCError(e.to_string())), - } + Ok(()) => { + *can_update = true; + log::debug!("Discord RPC state updated successfully"); + } + Err(e) => log::error!("Failed to update Discord RPC state: {}", e), + }; + + Ok(()) // whatever } pub fn update_stage(&mut self, stage: &StageData) -> GameResult {