Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

6.7 KB
Raw Blame
//! Discord's "You were in a voice channel last time you left Discord." notice, naming RustCord
//! (its VOICE_CONNECTED_LAST_SESSION nagbar).
//!
//! The call you're in is written to `<config>/last-call.json` and removed when
//! you leave it. A file still there when RustCord starts means the last run
//! closed mid-call (a crash, a kill, or closing the window), so the notice
//! offers to reconnect instead of rejoining on its own, as Discord does.

use crate::app::{RustCord, Screen};
use crate::style::icon;
use discord::model::Id;
use eframe::egui::{self, pos2, vec2, CursorIcon, Frame, Rect, Sense, Stroke, TopBottomPanel};
use std::path::{Path, PathBuf};

/// Discord's notice: 36 px tall under a 1 px border.
pub const HEIGHT: f32 = 37.0;
const MESSAGE: &str = "You were in a voice channel last time you left RustCord.";

/// A call, and whose account it was on.
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct LastCall {
    pub user: u64,
    pub channel: u64,
}

fn path(config: Option<&Path>) -> Option<PathBuf> {
    config.map(|d| d.join("last-call.json"))
}

/// The call the last run was still in when it closed.
pub fn load(config: Option<&Path>) -> Option<LastCall> {
    let text = std::fs::read_to_string(path(config)?).ok()?;
    serde_json::from_str(&text).ok()
}

/// Remember the call you're in (`None`: none, the file goes).
fn save(config: Option<&Path>, call: Option<LastCall>) {
    let Some(file) = path(config) else { return };
    match call {
        None => {
            let _ = std::fs::remove_file(file);
        }
        Some(call) => {
            let Ok(text) = serde_json::to_string(&call) else { return };
            // Written whole then renamed: a crash never leaves half a file.
            let tmp = file.with_extension("json.tmp");
            if std::fs::write(&tmp, text).is_ok() {
                let _ = std::fs::rename(&tmp, &file);
            }
        }
    }
}

impl RustCord {
    /// Keep `last-call.json` in step with the call you're in. Once a call
    /// starts, the last session's notice has done its job.
    pub fn last_call_tick(&mut self) {
        if self.demo {
            return;
        }
        let now = match (self.voice.as_ref(), self.store.me_id()) {
            (Some(v), Some(me)) => Some(LastCall { user: me.0, channel: v.channel.0 }),
            _ => None,
        };
        if now.is_some() {
            self.last_call = None;
        }
        if now != self.last_call_saved {
            save(self.config_dir.as_deref(), now);
            self.last_call_saved = now;
        }
    }

    /// The channel to offer, if the notice should show: it was this account's
    /// call, the channel still exists for you, and you're not in a call.
    fn last_call_channel(&self) -> Option<Id> {
        let call = self.last_call?;
        let mine = self.store.me_id().is_some_and(|me| me.0 == call.user);
        let channel = Id(call.channel);
        (mine && self.screen == Screen::Main && self.voice.is_none() && self.store.channels.contains_key(&channel)).then_some(channel)
    }

    pub fn voice_notice_shown(&self) -> bool {
        self.last_call_channel().is_some()
    }

    /// The bar across the top of the channel list and chat, right of the server list.
    pub fn voice_notice_ui(&mut self, ctx: &egui::Context) {
        let Some(channel) = self.last_call_channel() else { return };
        let t = self.theme.clone();
        let (bg, fg) = t.notice_positive;
        let mut reconnect = false;
        let mut dismiss = false;
        TopBottomPanel::top("voice_notice").exact_height(HEIGHT).show_separator_line(false).frame(Frame::none().fill(bg)).show(ctx, |ui| {
            let bar = ui.max_rect();
            let p = ui.painter();
            // Discord's app-frame border along its top and left edges.
            let border = Stroke::new(1.0_f32, t.border_subtle);
            p.line_segment([pos2(bar.left(), bar.top() + 0.5), pos2(bar.right(), bar.top() + 0.5)], border);
            p.line_segment([pos2(bar.left() + 0.5, bar.top()), pos2(bar.left() + 0.5, bar.bottom())], border);
            let row = Rect::from_min_max(pos2(bar.left() + 1.0, bar.top() + 1.0), bar.max);
            let cy = row.center().y;
            // Text and button centred together between 4 px of padding on the
            // left and 28 on the right (room for the close button).
            let font = crate::style::medium(14.0);
            let text = p.layout_no_wrap(MESSAGE.into(), font.clone(), fg);
            let label = p.layout_no_wrap("Reconnect".into(), font, fg);
            let button_w = (label.size().x + 22.0).round();
            let total = text.size().x + 10.0 + button_w;
            let middle = (row.left() + 4.0 + row.right() - 28.0) / 2.0;
            let x = (middle - total / 2.0).max(row.left() + 4.0);
            p.galley(pos2(x, cy - text.size().y / 2.0), text, fg);
            let button = Rect::from_min_size(pos2((x + total - button_w).round(), cy - 12.0), vec2(button_w, 24.0));
            let b = ui.interact(button, egui::Id::new("voice_notice_reconnect"), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
            if b.hovered() {
                p.rect_filled(button, 3.0, t.bg_hover);
            }
            p.rect_stroke(button.shrink(0.5), 3.0, Stroke::new(1.0_f32, fg));
            p.galley(pos2(button.center().x - label.size().x / 2.0, cy - label.size().y / 2.0), label, fg);
            reconnect = b.clicked();
            // Dismiss: a 36 px square at the right end, an 18 px cross in it.
            let close = Rect::from_min_size(pos2(row.right() - 36.0, row.top()), vec2(36.0, 36.0));
            let c = ui.interact(close, egui::Id::new("voice_notice_dismiss"), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
            let cross = Rect::from_min_size(pos2(close.left(), close.center().y - 9.0), vec2(18.0, 18.0));
            super::paint_icon(p, cross, icon::CLOSE, fg);
            dismiss = c.on_hover_text("Dismiss").clicked();
        });
        if reconnect {
            log::info!("voice: reconnecting to last session's channel {channel}");
            self.last_call = None;
            self.join_voice(channel);
        } else if dismiss {
            self.last_call = None;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_call_is_kept_until_it_ends() {
        let dir = std::env::temp_dir().join(format!("rustcord-last-call-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let call = LastCall { user: 1, channel: 123456789012345678 };
        save(Some(&dir), Some(call));
        assert_eq!(load(Some(&dir)), Some(call));
        save(Some(&dir), None);
        assert_eq!(load(Some(&dir)), None);
        let _ = std::fs::remove_dir_all(dir);
    }
}