Skip to content

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

9.4 KB
Raw Blame
//! A server channel's right-click menu, and the channel mute and
//! notification actions it shares with the voice call's bell menu. Items,
//! order and strings follow Discord's web app (read 2026-12-03); Discord's
//! Add to Favorites, Pin Channel to Top, Move to…, Duplicate Channel and
//! Hide Names aren't here yet.

use super::guild_menu::{draw_menu, item, level_label, mute_until_label, sub_path_id, Row, MUTE_TIMES};
use crate::app::RustCord;
use crate::style::icon;
use discord::model::{channel_kind, permissions, Id};
use eframe::egui::{self, Key, Pos2, Rect};
use serde_json::json;

/// Something a channel menu row does.
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum ChannelAct {
    MarkRead,
    Invite,
    CopyLink,
    OpenChat,
    /// Mute for this many seconds (-1: until unmuted).
    Mute(i64),
    Unmute,
    /// 0 all, 1 @mentions, 2 nothing, 3 the category's (or server's) setting.
    Notify(u8),
    Edit,
    /// Create a channel of this kind beside it (0 text, 2 voice).
    Create(u8),
    Delete,
    CopyId,
}

impl RustCord {
    /// Right-click on a channel in the server's channel list.
    pub fn open_channel_menu(&mut self, channel: Id, at: Pos2) {
        self.server_menu = None;
        self.guild_menu = None;
        self.dm_menu = None;
        self.channel_menu = Some((channel, at, self.ctx.cumulative_pass_nr()));
        self.ctx.data_mut(|d| d.remove::<Vec<usize>>(sub_path_id()));
    }

    /// Discord's channel context menu (called every frame).
    pub fn channel_menu_ui(&mut self, ctx: &egui::Context) {
        let Some((ch, at, opened)) = self.channel_menu else { return };
        let Some(rows) = self.channel_menu_rows(ch) else {
            self.channel_menu = None;
            return;
        };
        let t = self.theme.clone();
        let mut picked = None;
        let mut rects = Vec::new();
        draw_menu(ctx, &t, egui::Id::new("channel_menu"), at, &rows, 0, &mut picked, &mut rects);
        let now = ctx.cumulative_pass_nr();
        let outside = now > opened + 1
            && ctx.input(|i| i.pointer.any_pressed() && i.pointer.interact_pos().is_some_and(|p| !rects.iter().any(|r: &Rect| r.contains(p))));
        if picked.is_some() || outside || ctx.input(|i| i.key_pressed(Key::Escape)) {
            self.channel_menu = None;
        }
        if let Some(act) = picked {
            self.channel_act(ch, act);
        }
    }

    /// The menu's rows for `ch`, from your permissions there and your
    /// notification settings. None once the channel is gone.
    fn channel_menu_rows(&self, ch: Id) -> Option<Vec<Row<ChannelAct>>> {
        let c = self.store.channels.get(&ch)?;
        c.guild_id?;
        let voice = channel_kind::is_voice(c.kind);
        let perms = self.store.channel_perms(c).unwrap_or(0);
        let has = |p: u64| perms & p != 0;
        let unread = self.store.is_unread(ch) || self.store.mentions(ch) > 0;
        let mut rows = Vec::new();

        rows.push(Row::Item { glyph: None, label: "Mark As Read".into(), sub: None, act: ChannelAct::MarkRead, danger: false, enabled: unread });
        rows.push(Row::Sep);
        if has(permissions::CREATE_INSTANT_INVITE) {
            rows.push(item(None, if voice { "Invite to Voice" } else { "Invite to Channel" }, ChannelAct::Invite));
        }
        rows.push(item(None, "Copy Link", ChannelAct::CopyLink));
        rows.push(Row::Sep);
        if voice {
            rows.push(item(None, "Open Chat", ChannelAct::OpenChat));
            rows.push(Row::Sep);
        }
        if self.store.muted_channels.contains(&ch) {
            let sub = self.store.channel_mute_until.get(&ch).and_then(|end| mute_until_label(end));
            rows.push(Row::Item { glyph: None, label: "Unmute Channel".into(), sub, act: ChannelAct::Unmute, danger: false, enabled: true });
        } else {
            let times = MUTE_TIMES.iter().map(|(s, l)| item(None, l, ChannelAct::Mute(*s))).collect();
            rows.push(Row::Sub { glyph: None, label: "Mute Channel".into(), sub: None, rows: times });
        }
        // Voice channels have no Notification Settings in Discord's menu.
        if !voice {
            let own = self.store.channel_notify.get(&ch).copied();
            let inherited = self.inherited_notify(ch);
            let mut levels = vec![Row::Radio {
                label: "Use Category Default".into(),
                sub: Some(level_label(inherited).into()),
                on: own.is_none(),
                act: ChannelAct::Notify(3),
            }];
            for (v, label) in [(0u8, "All Messages"), (1, "Only @mentions"), (2, "Nothing")] {
                levels.push(Row::Radio { label: label.into(), sub: None, on: own == Some(v), act: ChannelAct::Notify(v) });
            }
            let current = level_label(own.unwrap_or(inherited));
            rows.push(Row::Sub { glyph: None, label: "Notification Settings".into(), sub: Some(current.into()), rows: levels });
        }
        if has(permissions::MANAGE_CHANNELS) {
            rows.push(Row::Sep);
            rows.push(item(None, "Edit Channel", ChannelAct::Edit));
            let kind = if voice { 2 } else { 0 };
            rows.push(item(None, if voice { "Create Voice Channel" } else { "Create Text Channel" }, ChannelAct::Create(kind)));
            rows.push(Row::Item { glyph: None, label: "Delete Channel".into(), sub: None, act: ChannelAct::Delete, danger: true, enabled: true });
        }
        rows.push(Row::Sep);
        rows.push(item(Some(icon::ID), "Copy Channel ID", ChannelAct::CopyId));
        Some(rows)
    }

    /// The level a channel without its own setting follows: its category's,
    /// else the server's.
    fn inherited_notify(&self, ch: Id) -> u8 {
        let c = self.store.channels.get(&ch);
        let category = c.and_then(|c| c.parent_id).and_then(|p| self.store.channel_notify.get(&p).copied());
        category.or_else(|| c.and_then(|c| c.guild_id).and_then(|g| self.store.notify_level.get(&g).copied())).unwrap_or(0)
    }

    /// Do what a channel menu row asked.
    fn channel_act(&mut self, ch: Id, act: ChannelAct) {
        let Some(c) = self.store.channels.get(&ch) else { return };
        let (guild, parent, kind) = (c.guild_id, c.parent_id, c.kind);
        match act {
            ChannelAct::MarkRead => self.mark_channel_read(ch),
            ChannelAct::Invite => self.open_invite(ch),
            ChannelAct::CopyLink => {
                let g = guild.map_or_else(|| "@me".to_string(), |g| g.to_string());
                self.ctx.copy_text(format!("https://discord.com/channels/{g}/{ch}"));
                self.toast("Link copied.", false);
            }
            ChannelAct::OpenChat => {
                self.guild_pages.open = None;
                self.select_channel(Some(ch));
                self.golive_ui.chat_open = true;
            }
            ChannelAct::Mute(secs) => self.mute_channel(ch, Some(secs)),
            ChannelAct::Unmute => self.mute_channel(ch, None),
            ChannelAct::Notify(n) => self.set_channel_notify(ch, n),
            ChannelAct::Edit => self.open_channel_settings(ch),
            ChannelAct::Create(kind) => {
                if let Some(guild) = guild {
                    self.server_dialog = Some(crate::features::ServerDialog::CreateChannel { guild, parent, name: String::new(), kind, private: false, category: false });
                }
            }
            ChannelAct::Delete => self.server_dialog = Some(crate::features::ServerDialog::DeleteChannel { channel: ch, category: kind == channel_kind::GUILD_CATEGORY }),
            ChannelAct::CopyId => {
                self.ctx.copy_text(ch.to_string());
                self.toast("Channel ID copied.", false);
            }
        }
    }

    /// Mute a server channel for `secs` seconds (-1: until unmuted), or
    /// unmute it (None), here and on Discord.
    pub fn mute_channel(&mut self, ch: Id, secs: Option<i64>) {
        let Some(g) = self.store.channels.get(&ch).and_then(|c| c.guild_id) else { return };
        let over = match secs {
            None => {
                self.store.muted_channels.remove(&ch);
                self.store.channel_mute_until.remove(&ch);
                json!({ "muted": false })
            }
            Some(secs) => {
                self.store.muted_channels.insert(ch);
                let end = (secs > 0).then(|| (chrono::Utc::now() + chrono::Duration::seconds(secs)).to_rfc3339_opts(chrono::SecondsFormat::Millis, true));
                match &end {
                    Some(e) => self.store.channel_mute_until.insert(ch, e.clone()),
                    None => self.store.channel_mute_until.remove(&ch),
                };
                json!({ "muted": true, "mute_config": { "selected_time_window": secs, "end_time": end } })
            }
        };
        let patch = json!({ "channel_overrides": { ch.to_string(): over } });
        self.backend.send(crate::backend::Command::GuildSettings { guild: g, patch });
    }

    /// A server channel's notification level (3: back to the category's or
    /// server's), here and on Discord.
    pub fn set_channel_notify(&mut self, ch: Id, n: u8) {
        let Some(g) = self.store.channels.get(&ch).and_then(|c| c.guild_id) else { return };
        if n == 3 {
            self.store.channel_notify.remove(&ch);
        } else {
            self.store.channel_notify.insert(ch, n);
        }
        let patch = json!({ "channel_overrides": { ch.to_string(): { "message_notifications": n } } });
        self.backend.send(crate::backend::Command::GuildSettings { guild: g, patch });
    }
}