Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.
Rust desktop-appdiscorddiscord-clienteguielectron-alternativelightweightlinuxmacosnative-apprustwindows
//! User Settings, laid out like Discord's own (2026) settings window: your
//! card and a search box at the top of the sidebar, then General, Billing,
//! Experience, Games & Apps and Other sections, RustCord's own pages
//! (Rencord, Themes, About) and Log Out.
//!
//! Settings that belong to your Discord account are read from and written to
//! `GET/PATCH /users/@me/settings` (so they match the official apps), or, for
//! the ones only Discord's newer store has, `settings-proto/1` (`set_proto`);
//! the per-device ones (zoom, notifications, sounds, Streamer Mode,
//! accessibility…) are saved locally in `prefs.json`.
use super::{paint_avatar, toggle_switch};
use crate::app::{RustCord, SettingsTab};
use crate::style::{bold, icon, icon_font, overlay, Theme};
use eframe::egui::{
self, pos2, vec2, Align, Align2, Button, CollapsingHeader, Color32, ComboBox, FontId, Frame, Grid, Key, Layout, Margin, Order, Rect, RichText,
ScrollArea, Sense, Slider, Stroke, TextEdit, Ui,
};
use discord::model::Id;
use discord::settings_proto::Leaf;
use rencord::{SettingDef, SettingKind, SettingValue};
use serde_json::{json, Value};
const BRAND: Color32 = Color32::from_rgb(0x58, 0x65, 0xf2);
/// Discord's interface languages.
const LOCALES: &[(&str, &str)] = &[
("id", "Bahasa Indonesia"),
("da", "Dansk"),
("de", "Deutsch"),
("en-GB", "English, UK"),
("en-US", "English, USA"),
("es-ES", "Español"),
("es-419", "Español, LATAM"),
("fr", "Français"),
("hr", "Hrvatski"),
("it", "Italiano"),
("lt", "Lietuviškai"),
("hu", "Magyar"),
("nl", "Nederlands"),
("no", "Norsk"),
("pl", "Polski"),
("pt-BR", "Português do Brasil"),
("ro", "Română"),
("fi", "Suomi"),
("sv-SE", "Svenska"),
("vi", "Tiếng Việt"),
("tr", "Türkçe"),
("cs", "Čeština"),
("el", "Ελληνικά"),
("bg", "български"),
("ru", "Русский"),
("uk", "Українська"),
("hi", "हिन्दी"),
("th", "ไทย"),
("zh-CN", "中文"),
("ja", "日本語"),
("zh-TW", "繁體中文"),
("ko", "한국어"),
];
fn value_text(v: &SettingValue) -> String {
match v {
SettingValue::Text(s) => s.clone(),
SettingValue::Number(n) => n.to_string(),
SettingValue::Bool(b) => b.to_string(),
}
}
/// Generic widget for a declarative plugin setting. Returns the new value if changed.
fn setting_widget(ui: &mut Ui, t: &Theme, salt: usize, def: &SettingDef, current: SettingValue) -> Option<SettingValue> {
let mut out = None;
match &def.kind {
SettingKind::Bool { .. } => {
let mut on = matches!(current, SettingValue::Bool(true));
ui.horizontal(|ui| {
if toggle_switch(ui, &mut on, t).changed() {
out = Some(SettingValue::Bool(on));
}
ui.add_space(6.0);
ui.label(RichText::new(def.label).color(t.header_primary));
});
}
SettingKind::Text { multiline, placeholder, .. } => {
ui.label(RichText::new(def.label).color(t.header_primary));
let mut s = value_text(¤t);
let r = if *multiline {
ui.add(TextEdit::multiline(&mut s).hint_text(*placeholder).desired_rows(3).desired_width(f32::INFINITY).code_editor())
} else {
ui.add(TextEdit::singleline(&mut s).hint_text(*placeholder).desired_width(f32::INFINITY))
};
if r.changed() {
out = Some(SettingValue::Text(s));
}
}
SettingKind::Number { min, max, .. } => {
let mut n = match current {
SettingValue::Number(n) => n,
_ => *min,
};
if ui.add(Slider::new(&mut n, *min..=*max).text(def.label)).changed() {
out = Some(SettingValue::Number(n));
}
}
SettingKind::Select { options, .. } => {
let cur = value_text(¤t);
let cur_label = options.iter().find(|(v, _)| *v == cur).map(|(_, l)| *l).unwrap_or(cur.as_str());
ui.horizontal(|ui| {
ui.label(RichText::new(def.label).color(t.header_primary));
ComboBox::from_id_salt(("setting", salt, def.key)).selected_text(cur_label).show_ui(ui, |ui| {
for (value, label) in options.iter() {
if ui.selectable_label(cur == *value, *label).clicked() {
out = Some(SettingValue::Text(value.to_string()));
}
}
});
});
}
}
if !def.description.is_empty() {
ui.label(RichText::new(def.description).size(12.0).color(t.text_muted));
}
ui.add_space(8.0);
out
}
fn swatch(ui: &mut Ui, [r, g, b, a]: [u8; 4]) {
let (rect, _) = ui.allocate_exact_size(vec2(18.0, 18.0), Sense::hover());
ui.painter().rect_filled(rect, 4.0, crate::style::rgba(r, g, b, a));
}
fn strong(size: f32) -> FontId {
FontId::new(size, egui::FontFamily::Name(crate::style::BOLD.into()))
}
/// A 48 px colour-theme circle: the gradient (or `plain`), a blurple ring
/// when picked, the name as a tooltip.
fn color_swatch(ui: &mut Ui, t: &Theme, g: Option<&crate::style::Gradient>, plain: Color32, selected: bool, name: &str) -> egui::Response {
let (rect, resp) = ui.allocate_exact_size(vec2(48.0, 48.0), Sense::click());
let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
let c = rect.center();
let r = 22.0;
match g {
Some(g) => {
let mut mesh = egui::Mesh::default();
mesh.colored_vertex(c, g.color_at(c, rect));
let n = 64u32;
// Rings, so multi-stop gradients bend where they should.
for ring in 1..=4 {
let rr = r * ring as f32 / 4.0;
for i in 0..n {
let a = i as f32 / n as f32 * std::f32::consts::TAU;
let p = c + vec2(a.cos(), a.sin()) * rr;
mesh.colored_vertex(p, g.color_at(p, rect));
}
}
for i in 0..n {
mesh.add_triangle(0, 1 + i, 1 + (i + 1) % n);
}
for ring in 0..3u32 {
let (a0, b0) = (1 + ring * n, 1 + (ring + 1) * n);
for i in 0..n {
let j = (i + 1) % n;
mesh.add_triangle(a0 + i, b0 + i, b0 + j);
mesh.add_triangle(a0 + i, b0 + j, a0 + j);
}
}
ui.painter().add(egui::Shape::mesh(mesh));
}
None => {
ui.painter().circle_filled(c, r, plain);
}
}
let ring = if selected { Stroke::new(2.5_f32, BRAND) } else if resp.hovered() { Stroke::new(1.5_f32, t.interactive_hover) } else { Stroke::new(1.0_f32, t.border_subtle) };
ui.painter().circle_stroke(c, r + if selected { 2.5 } else { 0.5 }, ring);
if selected {
ui.painter().text(c, Align2::CENTER_CENTER, icon::CHECK, icon_font(16.0), Color32::WHITE);
}
resp.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(name)
}
/// A page's big title on RustCord's own pages (Discord's section title style).
pub(super) fn heading(ui: &mut Ui, t: &Theme, text: &str) {
ui.label(RichText::new(text).font(crate::style::medium(24.0)).color(t.header_primary));
ui.add_space(16.0);
}
/// A group label inside a section (Discord: 16 px semibold, e.g. "Default Themes").
fn subheading(ui: &mut Ui, t: &Theme, text: &str) {
ui.add_space(8.0);
ui.label(RichText::new(text).font(strong(16.0)).color(t.header_primary));
ui.add_space(8.0);
}
/// The hairline between two sections.
fn divider(ui: &mut Ui, t: &Theme) {
ui.add_space(32.0);
let y = ui.cursor().top();
ui.painter().hline(ui.max_rect().x_range(), y, Stroke::new(1.0_f32, t.border_subtle));
ui.add_space(32.0);
}
fn jump_id() -> egui::Id {
egui::Id::new("settings_jump")
}
fn tops_id() -> egui::Id {
egui::Id::new("settings_section_tops")
}
/// Start section `i` of the open page (the sidebar lists a page's sections
/// under it: clicking one scrolls here, and scrolling marks the one in view).
pub(super) fn section(ui: &mut Ui, t: &Theme, i: usize, title: &str) {
if i > 0 {
divider(ui, t);
}
let top = ui.cursor().top();
if ui.data(|d| d.get_temp::<usize>(jump_id())) == Some(i) {
ui.scroll_to_rect(Rect::from_min_size(pos2(ui.cursor().left(), top - 24.0), vec2(1.0, 1.0)), Some(Align::TOP));
ui.data_mut(|d| d.remove::<usize>(jump_id()));
}
ui.data_mut(|d| {
let tops = d.get_temp_mut_or_default::<Vec<f32>>(tops_id());
if tops.len() <= i {
tops.resize(i + 1, f32::MAX);
}
tops[i] = top;
});
ui.label(RichText::new(title).font(crate::style::medium(24.0)).color(t.header_primary));
ui.add_space(16.0);
}
/// Discord's switch: blurple when on.
pub(super) fn switch(ui: &mut Ui, t: &Theme, on: &mut bool) -> egui::Response {
let (rect, mut resp) = ui.allocate_exact_size(vec2(40.0, 24.0), Sense::click());
if resp.clicked() {
*on = !*on;
resp.mark_changed();
}
let how = ui.ctx().animate_bool(resp.id, *on);
let off = overlay(0.24);
let bg = Color32::from_rgb(
egui::lerp(off.r() as f32..=BRAND.r() as f32, how) as u8,
egui::lerp(off.g() as f32..=BRAND.g() as f32, how) as u8,
egui::lerp(off.b() as f32..=BRAND.b() as f32, how) as u8,
);
ui.painter().rect_filled(rect, 12.0, if how > 0.0 { bg } else { off });
if !*on {
ui.painter().rect_stroke(rect, 12.0, Stroke::new(1.0_f32, t.border_subtle));
}
let x = egui::lerp((rect.left() + 12.0)..=(rect.right() - 12.0), how);
ui.painter().circle_filled(pos2(x, rect.center().y), 8.0, Color32::WHITE);
super::switch_mark(ui, pos2(x, rect.center().y), *on, if *on { BRAND } else { Color32::from_gray(110) });
resp.on_hover_cursor(egui::CursorIcon::PointingHand)
}
/// A row's left side: title (16 px medium) with the description under it.
fn row_text(ui: &mut Ui, t: &Theme, title: &str, desc: &str, width: f32, dim: bool) {
let fade = |c: Color32| if dim { c.gamma_multiply(0.5) } else { c };
ui.vertical(|ui| {
ui.set_width(width);
ui.add(egui::Label::new(RichText::new(title).font(crate::style::medium(16.0)).color(fade(t.header_primary))).wrap());
if !desc.is_empty() {
ui.add_space(2.0);
ui.add(egui::Label::new(RichText::new(desc).size(14.0).color(fade(t.text_muted))).wrap());
}
});
}
/// Discord's settings row: title, description under it, switch on the right.
/// Returns the new value when flipped.
pub(super) fn toggle_row(ui: &mut Ui, t: &Theme, title: &str, desc: &str, on: bool) -> Option<bool> {
let mut v = on;
let mut changed = false;
ui.horizontal_top(|ui| {
let w = ui.available_width() - 56.0;
row_text(ui, t, title, desc, w, false);
ui.with_layout(Layout::right_to_left(Align::Min), |ui| {
changed = switch(ui, t, &mut v).changed();
});
});
ui.add_space(16.0);
changed.then_some(v)
}
/// Why a row can't be changed here.
#[derive(Clone, Copy, PartialEq)]
enum Locked {
/// An account setting RustCord can't write yet: the tag opens discord.com.
Web,
/// Something the app itself would have to do, which RustCord doesn't yet.
Soon,
/// Always on (Discord shows it greyed too).
Always,
}
/// A row from Discord's settings that RustCord shows but can't change:
/// greyed like Discord's own disabled rows, with why on the right.
fn locked_row(ui: &mut Ui, t: &Theme, title: &str, desc: &str, why: Locked) {
ui.horizontal_top(|ui| {
let w = ui.available_width() - 170.0;
row_text(ui, t, title, desc, w, true);
ui.with_layout(Layout::right_to_left(Align::Min), |ui| match why {
Locked::Web => {
let link = ui
.add(egui::Label::new(RichText::new("Change on discord.com").size(13.0).color(t.text_link)).selectable(false).sense(Sense::click()))
.on_hover_cursor(egui::CursorIcon::PointingHand)
.on_hover_text("Opens Discord in your browser, where you can change this.");
if link.clicked() {
ui.ctx().open_url(egui::OpenUrl::new_tab("https://discord.com/channels/@me"));
}
}
Locked::Soon => {
ui.label(RichText::new("Not in RustCord yet").size(13.0).color(t.text_muted));
}
Locked::Always => {
ui.label(RichText::new("Always on").size(13.0).color(t.text_muted));
}
});
});
ui.add_space(16.0);
}
fn web(ui: &mut Ui, t: &Theme, title: &str, desc: &str) {
locked_row(ui, t, title, desc, Locked::Web);
}
fn soon(ui: &mut Ui, t: &Theme, title: &str, desc: &str) {
locked_row(ui, t, title, desc, Locked::Soon);
}
/// Title and description with a button on the right, centred on the text
/// beside it as Discord's are. True when clicked.
fn button_row(ui: &mut Ui, t: &Theme, title: &str, desc: &str, label: &str, kind: ButtonKind) -> bool {
let size = button_size(ui, label);
let mut clicked = false;
ui.horizontal_top(|ui| {
let right = ui.max_rect().right();
// The text keeps clear of the button, with a 16 px gap.
let w = (ui.available_width() - size.x - 16.0).max(120.0);
let text = ui.scope(|ui| row_text(ui, t, title, desc, w, false)).response.rect;
let top = (text.center().y - size.y / 2.0).max(text.top());
let rect = Rect::from_min_size(pos2(right - size.x, top).round(), size);
let resp = ui.allocate_rect(rect, Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
paint_button(ui, t, &resp, label, kind);
clicked = resp.clicked();
});
ui.add_space(16.0);
clicked
}
/// A radio choice (Discord's: a ring, filled blurple when picked, the label
/// and an optional description). True when clicked.
fn radio_row(ui: &mut Ui, t: &Theme, title: &str, desc: &str, selected: bool) -> bool {
// (The description may wrap: the row is as tall as it needs.)
let desc_galley = (!desc.is_empty()).then(|| ui.painter().layout(desc.to_string(), FontId::proportional(14.0), t.text_muted, ui.available_width() - 32.0));
let h = desc_galley.as_ref().map_or(26.0, |g| 28.0 + g.size().y);
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click());
let c = pos2(rect.left() + 10.0, rect.top() + 13.0);
if selected {
ui.painter().circle_filled(c, 10.0, BRAND);
ui.painter().circle_filled(c, 4.0, Color32::WHITE);
} else {
ui.painter().circle_stroke(c, 9.0, Stroke::new(1.5_f32, if resp.hovered() { t.header_primary } else { t.interactive_normal }));
}
let x = rect.left() + 32.0;
ui.painter().text(pos2(x, rect.top() + 13.0), Align2::LEFT_CENTER, title, FontId::proportional(16.0), t.header_primary);
if let Some(g) = desc_galley {
ui.painter().galley(pos2(x, rect.top() + 26.0), g, t.text_muted);
}
resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked()
}
/// Small grey text under a group.
fn note(ui: &mut Ui, t: &Theme, text: &str) {
ui.add(egui::Label::new(RichText::new(text).size(14.0).color(t.text_muted)).wrap());
ui.add_space(12.0);
}
/// Discord's "Related Settings" card: an icon, a title and what's there, a
/// chevron. True when clicked.
fn related(ui: &mut Ui, t: &Theme, icon_name: &str, title: &str, desc: &str) -> bool {
subheading(ui, t, "Related Settings");
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 56.0), Sense::click());
if resp.hovered() {
ui.painter().rect_filled(rect.expand2(vec2(8.0, 0.0)), 8.0, overlay(0.06));
}
let badge = Rect::from_center_size(pos2(rect.left() + 18.0, rect.center().y), vec2(36.0, 36.0));
ui.painter().circle_filled(badge.center(), 18.0, overlay(0.12));
if let Some(src) = super::settings_icons::icon(icon_name, t.header_primary) {
egui::Image::new(src).paint_at(ui, Rect::from_center_size(badge.center(), vec2(20.0, 20.0)));
}
ui.painter().text(pos2(rect.left() + 48.0, rect.center().y - 10.0), Align2::LEFT_CENTER, title, crate::style::medium(16.0), t.header_primary);
let g = ui.painter().layout_no_wrap(desc.to_string(), FontId::proportional(14.0), t.text_muted);
ui.painter().with_clip_rect(rect.with_max_x(rect.right() - 28.0)).galley(pos2(rect.left() + 48.0, rect.center().y + 2.0), g, t.text_muted);
ui.painter().text(pos2(rect.right() - 10.0, rect.center().y), Align2::CENTER_CENTER, "›", FontId::proportional(22.0), t.interactive_normal);
ui.add_space(8.0);
resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked()
}
/// Discord's slider with marks. Returns the mark picked, when it changed.
fn marks_slider(ui: &mut Ui, t: &Theme, title: &str, desc: &str, marks: &[&str], at: usize) -> Option<usize> {
ui.label(RichText::new(title).font(crate::style::medium(16.0)).color(t.header_primary));
if !desc.is_empty() {
ui.add(egui::Label::new(RichText::new(desc).size(14.0).color(t.text_muted)).wrap());
}
ui.add_space(22.0);
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::click_and_drag());
let track = Rect::from_min_max(pos2(rect.left() + 8.0, rect.center().y - 4.0), pos2(rect.right() - 8.0, rect.center().y + 4.0));
let n = marks.len().max(2) - 1;
let mut picked = None;
if let Some(p) = resp.interact_pointer_pos().filter(|_| resp.dragged() || resp.clicked()) {
let i = (((p.x - track.left()) / track.width()).clamp(0.0, 1.0) * n as f32).round() as usize;
if i != at {
picked = Some(i);
}
}
let at = picked.unwrap_or(at);
ui.painter().rect_filled(track, 4.0, overlay(0.24));
for (i, m) in marks.iter().enumerate() {
let x = track.left() + track.width() * i as f32 / n as f32;
ui.painter().vline(x, (track.top() - 6.0)..=(track.top() - 2.0), Stroke::new(1.0_f32, overlay(0.4)));
ui.painter().text(pos2(x, track.top() - 16.0), Align2::CENTER_CENTER, *m, FontId::proportional(11.0), if i == at { t.header_primary } else { t.text_muted });
}
let x = track.left() + track.width() * at as f32 / n as f32;
ui.painter().rect_filled(Rect::from_min_max(track.min, pos2(x, track.bottom())), 4.0, BRAND);
ui.painter().rect_filled(Rect::from_center_size(pos2(x, rect.center().y), vec2(10.0, 24.0)), 3.0, Color32::WHITE);
if resp.hovered() || resp.dragged() {
ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
}
ui.add_space(20.0);
picked
}
/// Title and description with a dropdown on the right. Returns the option
/// picked, when it changed.
fn choice_row(ui: &mut Ui, t: &Theme, id: &str, title: &str, desc: &str, options: &[&str], current: usize) -> Option<usize> {
let mut pick = None;
ui.horizontal_top(|ui| {
let w = ui.available_width() - 236.0;
row_text(ui, t, title, desc, w, false);
ui.with_layout(Layout::right_to_left(Align::Min), |ui| {
ui.spacing_mut().button_padding = vec2(12.0, 8.0);
ComboBox::from_id_salt(("settings_choice", id)).width(196.0).selected_text(RichText::new(options.get(current).copied().unwrap_or("")).size(14.0).color(t.text_normal)).show_ui(ui, |ui| {
for (i, o) in options.iter().enumerate() {
if ui.selectable_label(i == current, *o).clicked() && i != current {
pick = Some(i);
}
}
});
});
});
ui.add_space(16.0);
pick
}
/// A keyboard key, as Discord's shortcut list draws it.
fn keycap(ui: &mut Ui, t: &Theme, key: &str) {
let g = ui.painter().layout_no_wrap(key.to_string(), strong(12.0), t.header_primary);
let (rect, _) = ui.allocate_exact_size(vec2(g.size().x + 16.0, 26.0), Sense::hover());
ui.painter().rect_filled(rect, 5.0, overlay(0.16));
ui.painter().rect_filled(Rect::from_min_max(pos2(rect.left(), rect.bottom() - 3.0), rect.max), egui::Rounding { nw: 0.0, ne: 0.0, sw: 5.0, se: 5.0 }, overlay(0.12));
ui.painter().galley(rect.center() - g.size() / 2.0 - vec2(0.0, 1.0), g, t.header_primary);
}
/// Discord's button looks (its --control-* tokens).
#[derive(Clone, Copy, PartialEq)]
pub(super) enum ButtonKind {
/// Blurple, white label.
Primary,
/// The translucent grey fill with a faint edge.
Secondary,
/// Solid red, white label ("critical-primary": Delete Account).
Critical,
/// The grey fill with a red label ("critical-secondary": Disable Account).
CriticalSecondary,
}
/// Fills of Discord's solid buttons, the same in every theme: at rest,
/// hovered, pressed.
const BRAND_FILLS: [Color32; 3] = [BRAND, Color32::from_rgb(68, 82, 187), Color32::from_rgb(58, 72, 163)];
const CRITICAL_FILLS: [Color32; 3] = [Color32::from_rgb(210, 45, 57), Color32::from_rgb(169, 35, 46), Color32::from_rgb(151, 29, 40)];
/// Height of Discord's settings buttons, and their side padding.
const BUTTON_H: f32 = 36.0;
const BUTTON_PAD: f32 = 16.0;
/// The size `label` needs as a button.
fn button_size(ui: &Ui, label: &str) -> egui::Vec2 {
let w = ui.painter().layout_no_wrap(label.to_string(), crate::style::medium(14.0), Color32::WHITE).size().x;
vec2((w + 2.0 * BUTTON_PAD).max(60.0), BUTTON_H)
}
/// Paint a button over `resp`'s rect, label centred: 8 px corners, 14 px
/// medium label, Discord's own colours at rest, hovered and pressed.
fn paint_button(ui: &Ui, t: &Theme, resp: &egui::Response, label: &str, kind: ButtonKind) {
let state = if resp.is_pointer_button_down_on() {
2
} else if resp.hovered() {
1
} else {
0
};
let c = &t.controls;
let grey = [overlay(0.12), c.hover, c.active][state];
let (fill, edge, text) = match kind {
ButtonKind::Primary => (BRAND_FILLS[state], Stroke::NONE, Color32::WHITE),
ButtonKind::Critical => (CRITICAL_FILLS[state], Stroke::new(1.0_f32, crate::style::rgba(255, 255, 255, 20)), Color32::WHITE),
ButtonKind::Secondary => (grey, Stroke::new(1.0_f32, c.border), t.header_primary),
ButtonKind::CriticalSecondary => (grey, Stroke::new(1.0_f32, c.border), c.critical_text),
};
let p = ui.painter();
p.rect(resp.rect, 8.0, fill, edge);
let g = p.layout_no_wrap(label.to_string(), crate::style::medium(14.0), text);
// (Whole pixels, a hair up: the font's line box sits low, see `keycap`.)
let at = (resp.rect.center() - g.size() / 2.0 - vec2(0.0, 0.5)).round();
p.galley(at, g, text);
}
/// A button as wide as its label, where the layout puts it.
pub(super) fn action_button(ui: &mut Ui, t: &Theme, label: &str, kind: ButtonKind) -> egui::Response {
let (_, resp) = ui.allocate_exact_size(button_size(ui, label), Sense::click());
let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
paint_button(ui, t, &resp, label, kind);
resp
}
pub(super) fn secondary_button(ui: &mut Ui, t: &Theme, label: &str) -> egui::Response {
action_button(ui, t, label, ButtonKind::Secondary)
}
fn primary_button(ui: &mut Ui, t: &Theme, label: &str) -> egui::Response {
action_button(ui, t, label, ButtonKind::Primary)
}
/// One page of the sidebar: its sections are listed under it while it's open.
struct Page {
tab: SettingsTab,
label: &'static str,
/// A name in `settings_icons`, or a glyph of the icon font.
icon: &'static str,
subs: &'static [&'static str],
}
const fn page(tab: SettingsTab, label: &'static str, icon: &'static str, subs: &'static [&'static str]) -> Page {
Page { tab, label, icon, subs }
}
/// The sidebar, as Discord's (2026): group, pages, each page's sections.
/// System's sections. Discord's General (what the title bar's X does) is
/// left out on macOS, which has no tray icon (see `RustCord::tray_available`).
const SYSTEM_SECTIONS: &[&str] = if cfg!(any(windows, target_os = "linux")) { &["General", "Custom Keybinds", "Default Keybinds"] } else { &["Custom Keybinds", "Default Keybinds"] };
const NAV: &[(&str, &[Page])] = &[
(
"General",
&[
page(SettingsTab::Account, "Account", "account", &["Account Info", "Password & Security", "Account Status", "Family Centre"]),
page(SettingsTab::DataPrivacy, "Data & Privacy", "privacy", &["How Discord Uses My Data", "Profile Privacy"]),
page(SettingsTab::Messaging, "Messaging Permissions", "messaging", &["Content Filters", "Spam Filters", "Direct Messages", "Friend Requests", "Connected Games", "Ignore & Block"]),
page(SettingsTab::Notifications, "Notifications", "notifications", &["Overview", "Sounds", "Badges", "Email", "Advanced"]),
],
),
(
"Billing",
&[
page(SettingsTab::Nitro, "Nitro", "nitro", &[]),
page(SettingsTab::ServerBoost, "Server Boost", "boost", &[]),
page(SettingsTab::Subscriptions, "Subscriptions", "subscriptions", &[]),
page(SettingsTab::GiftInventory, "Gift Inventory", "gift", &["Redeem Codes", "The Gifting Badge", "Gifts I Purchased"]),
page(SettingsTab::Billing, "Billing", "billing", &["Payment Methods", "Transaction History"]),
],
),
(
"Experience",
&[
page(SettingsTab::VoiceVideo, "Voice & Video", "voice", &["Voice", "Camera", "Streaming", "Sounds", "Soundboard", "Advanced"]),
page(SettingsTab::Appearance, "Appearance", "appearance", &["Theme", "App Icon", "Messages", "Chat Box", "Typing Effects", "Search", "Streamer Mode"]),
page(SettingsTab::Accessibility, "Accessibility", "accessibility", &["Text Readability", "Visual Density", "Colour & Contrast", "Reduced Motion", "Audio & Screen Reader"]),
page(SettingsTab::System, "System", "system", SYSTEM_SECTIONS),
page(SettingsTab::Language, "Language & Time", "language", &[]),
],
),
(
"Games & Apps",
&[
page(SettingsTab::ActivityPrivacy, "Activity Privacy", "activity", &["What Activity I Share", "Where I Share Activity", "Activity Joining"]),
page(SettingsTab::Connections, "Connected Apps", "connections", &["Connections", "Authorised Apps"]),
],
),
("Other", &[page(SettingsTab::Developer, "Developer", "developer", &[])]),
(
"RustCord",
&[
page(SettingsTab::Plugins, "Rencord Plugins", icon::PLUGIN, &[]),
page(SettingsTab::Themes, "Themes", "appearance", &[]),
page(SettingsTab::ProcessViewer, "Process Viewer", "developer", &[]),
page(SettingsTab::Experimental, "Experimental", "experimental", &[]),
page(SettingsTab::About, "About", icon::HELP, &[]),
],
),
];
/// A sidebar icon in a 20 px box centred on `c`.
fn nav_icon(ui: &Ui, name: &str, c: egui::Pos2, color: Color32) {
match super::settings_icons::icon(name, color) {
Some(src) => {
egui::Image::new(src).paint_at(ui, Rect::from_center_size(c, vec2(20.0, 20.0)));
}
None => {
ui.painter().text(c, Align2::CENTER_CENTER, name, icon_font(18.0), color);
}
}
}
impl RustCord {
/// A boolean from your Discord settings (`default` until they've loaded).
pub fn discord_setting(&self, key: &str, default: bool) -> bool {
match self.api_results.get("us:settings") {
Some(Ok(v)) => v.get(key).and_then(Value::as_bool).unwrap_or(default),
_ => default,
}
}
fn setting_value(&self, key: &str) -> Option<Value> {
match self.api_results.get("us:settings") {
Some(Ok(v)) => v.get(key).cloned(),
_ => None,
}
}
/// Change one of your Discord settings (shown at once, saved in the background).
fn set_discord_setting(&mut self, key: &str, value: Value) {
if let Some(l) = value.as_str().filter(|_| key == "locale") {
discord::http::set_account_locale(l);
}
if let Some(Ok(v)) = self.api_results.get_mut("us:settings") {
v[key] = value.clone();
}
self.apply_discord_settings();
self.api("us:patch", reqwest::Method::PATCH, "/users/@me/settings", Some(json!({ key: value })));
}
/// Change one of your Discord settings that only exists in Discord's newer
/// settings store (`path`: its field numbers; see `settings_proto`).
fn set_proto(&mut self, path: &[u64], leaf: Leaf) {
match self.account_proto.set(path, leaf) {
Ok(patch) => {
self.apply_proto_settings();
self.api("us:proto", reqwest::Method::PATCH, "/users/@me/settings-proto/1", Some(json!({ "settings": patch })));
}
Err(e) => self.toast(format!("Couldn't change that setting: {e}"), true),
}
}
/// Have your Discord settings arrived (so a switch shows the real value)?
fn proto_ready(&self) -> bool {
self.demo || !self.account_proto.is_empty()
}
/// A switch bound to one of those settings. `invert`: the switch shows the
/// opposite of what's stored ("opted out"); `default`: the stored value
/// while it has never been set; `wrapped`: whether the schema stores it as
/// a BoolValue (most) or a plain bool.
#[allow(clippy::too_many_arguments)]
fn proto_toggle(&mut self, ui: &mut Ui, t: &Theme, path: &[u64], title: &str, desc: &str, invert: bool, default: bool, wrapped: bool) {
if !self.proto_ready() {
locked_row(ui, t, title, desc, Locked::Web);
return;
}
let stored = self.account_proto.bool(path).unwrap_or(default);
if let Some(v) = toggle_row(ui, t, title, desc, stored != invert) {
let store = v != invert;
self.set_proto(path, if wrapped { Leaf::BoolValue(store) } else { Leaf::Bool(store) });
}
}
/// A dropdown bound to one of those settings: `options` are (stored
/// value, label); `default` is the value shown while it was never set.
fn proto_choice(&mut self, ui: &mut Ui, t: &Theme, path: &[u64], title: &str, desc: &str, options: &[(u64, &str)], default: u64) {
if !self.proto_ready() {
locked_row(ui, t, title, desc, Locked::Web);
return;
}
let stored = self.account_proto.uint(path).unwrap_or(default);
let current = options.iter().position(|(v, _)| *v == stored).unwrap_or(0);
let labels: Vec<&str> = options.iter().map(|(_, l)| *l).collect();
let id = path.iter().map(|n| n.to_string()).collect::<Vec<_>>().join(".");
if let Some(i) = choice_row(ui, t, &id, title, desc, &labels, current) {
self.set_proto(path, Leaf::Enum(options[i].0));
}
}
/// Settings RustCord follows itself (animated emoji…).
pub fn apply_discord_settings(&mut self) {
super::ANIMATE_EMOJI.store(self.discord_setting("animate_emoji", true), std::sync::atomic::Ordering::Relaxed);
// Sticker animations: kept for the next launch too (see LocalPrefs).
if let Some(n) = self.sticker_animation() {
let n = n.min(2) as u8;
super::STICKER_ANIM.store(n, std::sync::atomic::Ordering::Relaxed);
if self.prefs.animate_stickers != n {
self.prefs.animate_stickers = n;
self.save_prefs();
}
}
}
/// "Play sticker animations" (0 always, 1 on interaction, 2 never), as
/// Discord keeps it: in your protobuf settings (`text_and_images`,
/// field 15; unset means always), which Discord's apps read. The old
/// JSON settings' copy can be out of date; it's only used until the
/// protobuf ones have arrived.
fn sticker_animation(&self) -> Option<u64> {
if self.account_proto.is_empty() {
self.setting_value("animate_stickers").and_then(|v| v.as_u64())
} else {
Some(self.account_proto.uint(&[6, 15]).unwrap_or(0))
}
}
/// Save the RustCord-only preferences and apply them.
pub(crate) fn save_prefs(&self) {
crate::features::save_prefs(self.config_dir.as_deref(), &self.prefs);
crate::features::apply_prefs(&self.prefs);
}
pub fn settings_window(&mut self, ctx: &egui::Context) {
// Saved settings coming back from Discord.
match self.api_take("us:patch") {
Some(Ok(v)) if v.is_object() => {
self.api_results.insert("us:settings".into(), Ok(v));
self.apply_discord_settings();
}
Some(Err(e)) => {
self.toast(format!("Couldn't save that setting: {e}"), true);
self.api("us:settings", reqwest::Method::GET, "/users/@me/settings", None);
}
_ => {}
}
// A change to the newer settings store: what RustCord shows is already the
// new value, so only a failure needs handling (ask for the real ones).
if let Some(Err(e)) = self.api_take("us:proto") {
self.toast(format!("Couldn't save that setting: {e}"), true);
self.api("us:proto-get", reqwest::Method::GET, "/users/@me/settings-proto/1", None);
}
if let Some(Ok(v)) = self.api_take("us:proto-get") {
if let Some(all) = v["settings"].as_str().and_then(|b| discord::settings_proto::decode(b).ok()) {
self.apply_account_settings(all, false);
}
}
// Opening Settings reads them afresh (another app may have changed them).
let opened_id = egui::Id::new("settings_was_open");
let was_open = ctx.data(|d| d.get_temp::<bool>(opened_id).unwrap_or(false));
if was_open != self.settings_open {
ctx.data_mut(|d| d.insert_temp(opened_id, self.settings_open));
if self.settings_open && !self.demo {
self.api("us:proto-get", reqwest::Method::GET, "/users/@me/settings-proto/1", None);
}
}
if !self.settings_open {
return;
}
self.api_get_once("us:settings", "/users/@me/settings");
self.api_get_once("us:me", "/users/@me");
self.api_get_once("us:connections", "/users/@me/connections");
let t = self.theme.clone();
let screen = ctx.screen_rect();
// (A Connections or Keyboard Shortcuts dialog takes Escape and outside clicks itself.)
let dialog = super::connections::dialog_open(ctx) || self.shortcuts_open;
let mut close = !dialog && ctx.input(|i| i.key_pressed(Key::Escape));
// Dimmed app behind.
egui::Area::new(egui::Id::new("settings_bg")).order(Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| {
let (r, _) = ui.allocate_exact_size(screen.size(), Sense::click());
ui.painter().rect_filled(r, 0.0, Color32::from_black_alpha(170));
});
// Discord: the window sits 40 px inside the app's, 1220 px wide at most.
let inset = if screen.width() < 900.0 { 16.0 } else { 40.0 };
let modal = screen.shrink2(vec2(((screen.width() - 1220.0) / 2.0).max(inset), inset));
let search_id = egui::Id::new("settings_search");
let active_id = egui::Id::new("settings_section_active");
// Clicking off the window (on the dimmed app) closes it.
close |= !dialog && super::pressed_outside(ctx, modal);
egui::Area::new(egui::Id::new("settings_window")).order(Order::Foreground).fixed_pos(modal.min).show(ctx, |ui| {
// (Not while one of its dropdowns is open: that list is a layer of
// its own, and raising the window every frame buried it.)
let me = ui.layer_id();
if !ui.ctx().memory(|m| m.any_popup_open()) {
ui.ctx().move_to_top(me);
} else {
// egui puts a list on top only the first time it's ever shown:
// opened again, it comes back where it was left, under this
// window. Lift whatever is showing below.
let below: Vec<egui::LayerId> = ui.ctx().memory(|m| {
let areas = m.areas();
m.layer_ids().take_while(|l| *l != me).filter(|l| l.order == Order::Foreground && l.id != egui::Id::new("settings_bg") && areas.is_visible(l)).collect()
});
for layer in below {
ui.ctx().move_to_top(layer);
}
}
// Cover the window so the wheel and hover reach this layer (the
// columns are child UIs, which don't grow it).
ui.expand_to_include_rect(modal);
ui.painter().rect_filled(modal, 12.0, t.bg_primary);
let side = Rect::from_min_size(modal.min, vec2(254.0, modal.height()));
ui.painter().rect_filled(side, egui::Rounding { nw: 12.0, sw: 12.0, ne: 0.0, se: 0.0 }, t.bg_secondary);
ui.painter().rect_stroke(modal, 12.0, Stroke::new(1.0_f32, t.border_subtle));
// Your card: avatar, name, "Edit Profiles".
let card = Rect::from_min_size(side.min + vec2(13.0, 12.0), vec2(228.0, 56.0));
if let Some(me) = self.store.me.clone() {
let resp = ui.interact(card, egui::Id::new("settings_card"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
if resp.hovered() || self.settings_tab == SettingsTab::Profiles {
ui.painter().rect_filled(card, 8.0, overlay(0.08));
}
let av = Rect::from_center_size(pos2(card.left() + 28.0, card.center().y), vec2(40.0, 40.0));
paint_avatar(ui, av, Some(me.avatar_or_default(80)), me.display_name());
let x = av.right() + 12.0;
ui.painter().with_clip_rect(card).text(pos2(x, card.center().y - 9.0), Align2::LEFT_CENTER, me.display_name(), strong(16.0), t.header_primary);
let g = ui.painter().layout_no_wrap("Edit Profiles".into(), FontId::proportional(13.0), t.text_normal);
let w = g.size().x;
ui.painter().galley(pos2(x, card.center().y + 3.0), g, t.text_normal);
ui.painter().text(pos2(x + w + 5.0, card.center().y + 11.0), Align2::LEFT_CENTER, icon::EDIT, icon_font(11.0), t.text_normal);
if resp.clicked() {
self.settings_tab = SettingsTab::Profiles;
}
}
// Search: narrows the sidebar to the pages and sections that match.
let search_rect = Rect::from_min_size(pos2(side.left() + 17.0, card.bottom() + 8.0), vec2(220.0, 40.0));
ui.painter().rect_filled(search_rect, 8.0, Color32::from_black_alpha(31));
ui.painter().rect_stroke(search_rect, 8.0, Stroke::new(1.0_f32, overlay(0.2)));
ui.painter().text(pos2(search_rect.left() + 18.0, search_rect.center().y), Align2::CENTER_CENTER, icon::SEARCH, icon_font(15.0), t.interactive_normal);
let mut query: String = ui.data(|d| d.get_temp(search_id)).unwrap_or_default();
let mut qui = ui.new_child(egui::UiBuilder::new().max_rect(Rect::from_min_max(pos2(search_rect.left() + 34.0, search_rect.top()), search_rect.max - vec2(8.0, 0.0))).layout(Layout::left_to_right(Align::Center)));
qui.add(
TextEdit::singleline(&mut query)
.id(egui::Id::new("settings_search_edit"))
.frame(false)
.hint_text(RichText::new("Search").color(t.text_muted))
.font(FontId::proportional(16.0))
.desired_width(f32::INFINITY),
);
ui.data_mut(|d| d.insert_temp(search_id, query.clone()));
let q = query.trim().to_lowercase();
// Pages, grouped; the open page lists its sections.
let active_sub = ui.data(|d| d.get_temp::<usize>(active_id)).unwrap_or(0);
let nav = Rect::from_min_max(pos2(side.left() + 13.0, search_rect.bottom() + 4.0), pos2(side.right() - 4.0, side.bottom() - 1.0));
let mut sui = ui.new_child(egui::UiBuilder::new().max_rect(nav).layout(Layout::top_down(Align::Min)));
let mut logout = false;
ScrollArea::vertical().id_salt("settings_side").auto_shrink([false, false]).show(&mut sui, |ui| {
ui.spacing_mut().item_spacing.y = 0.0;
ui.add_space(8.0);
let mut first = true;
for (group, pages) in NAV {
let hit = |p: &Page| q.is_empty() || p.label.to_lowercase().contains(&q) || p.subs.iter().any(|s| s.to_lowercase().contains(&q));
if !pages.iter().any(hit) {
continue;
}
if !first {
ui.add_space(12.0);
let y = ui.cursor().top();
ui.painter().hline((ui.cursor().left() + 4.0)..=(ui.cursor().left() + 224.0), y, Stroke::new(1.0_f32, t.border_subtle));
ui.add_space(12.0);
}
first = false;
ui.horizontal(|ui| {
ui.add_space(12.0);
ui.label(RichText::new(*group).size(13.0).color(t.text_muted));
});
ui.add_space(6.0);
for p in pages.iter().filter(|p| hit(p)) {
let selected = self.settings_tab == p.tab;
let (row, resp) = ui.allocate_exact_size(vec2(228.0, 36.0), Sense::click());
let row = Rect::from_min_size(row.min + vec2(4.0, 0.0), vec2(220.0, 36.0));
if selected || resp.hovered() {
ui.painter().rect_filled(row, 8.0, overlay(if selected { 0.16 } else { 0.08 }));
}
let fg = if selected || resp.hovered() { t.header_primary } else { t.interactive_normal };
nav_icon(ui, p.icon, pos2(row.left() + 18.0, row.center().y), fg);
ui.painter().text(pos2(row.left() + 40.0, row.center().y), Align2::LEFT_CENTER, p.label, if selected { crate::style::medium(16.0) } else { FontId::proportional(16.0) }, fg);
if resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
if p.tab == SettingsTab::Nitro {
// Like Discord: Nitro is a page of the app, not of settings.
close = true;
self.select_guild(None);
self.open_store_page(crate::features::StorePage::Nitro);
} else {
self.settings_tab = p.tab;
ui.data_mut(|d| d.insert_temp(active_id, 0usize));
}
}
// Its sections: all of them while the page is open,
// the matching ones while searching.
let searching = !q.is_empty() && !p.label.to_lowercase().contains(&q);
if !(selected && q.is_empty()) && !searching && !(selected && !q.is_empty()) {
continue;
}
let subs: Vec<(usize, &str)> = p.subs.iter().copied().enumerate().filter(|(_, s)| !searching || s.to_lowercase().contains(&q)).collect();
if subs.is_empty() {
continue;
}
ui.add_space(4.0);
let top = ui.cursor().top();
for (i, s) in &subs {
let (row, resp) = ui.allocate_exact_size(vec2(228.0, 32.0), Sense::click());
let on = selected && *i == active_sub;
let fg = if on || resp.hovered() { t.header_primary } else { t.interactive_normal };
ui.painter().text(pos2(row.left() + 40.0, row.center().y), Align2::LEFT_CENTER, *s, FontId::proportional(15.0), fg);
if on {
ui.painter().vline(row.left() + 21.5, (row.center().y - 10.0)..=(row.center().y + 10.0), Stroke::new(2.0_f32, t.header_primary));
}
if resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
self.settings_tab = p.tab;
ui.data_mut(|d| {
d.insert_temp(jump_id(), *i);
d.insert_temp(active_id, *i);
});
}
}
ui.painter().vline(ui.cursor().left() + 21.5, (top + 2.0)..=(ui.cursor().top() - 2.0), Stroke::new(1.0_f32, t.border_subtle));
ui.add_space(4.0);
}
}
ui.add_space(12.0);
let y = ui.cursor().top();
ui.painter().hline((ui.cursor().left() + 4.0)..=(ui.cursor().left() + 224.0), y, Stroke::new(1.0_f32, t.border_subtle));
ui.add_space(12.0);
let (row, resp) = ui.allocate_exact_size(vec2(228.0, 36.0), Sense::click());
let row = Rect::from_min_size(row.min + vec2(4.0, 0.0), vec2(220.0, 36.0));
if resp.hovered() {
ui.painter().rect_filled(row, 8.0, t.danger.gamma_multiply(0.15));
}
nav_icon(ui, "logout", pos2(row.left() + 18.0, row.center().y), t.danger);
ui.painter().text(pos2(row.left() + 40.0, row.center().y), Align2::LEFT_CENTER, "Log Out", FontId::proportional(16.0), t.danger);
logout = resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked();
ui.add_space(12.0);
ui.horizontal(|ui| {
ui.add_space(12.0);
ui.label(RichText::new(concat!("RustCord ", env!("CARGO_PKG_VERSION"))).size(12.0).color(t.text_muted));
});
ui.add_space(16.0);
});
if logout {
close = true;
self.logout();
}
// Header: where you are, and the close button.
let title = NAV.iter().flat_map(|(_, pages)| pages.iter()).find(|p| p.tab == self.settings_tab).map_or("Profiles", |p| p.label);
ui.painter().text(pos2(side.right() + 16.0, modal.top() + 25.0), Align2::LEFT_CENTER, title, crate::style::medium(16.0), t.header_primary);
let x = Rect::from_center_size(pos2(modal.right() - 25.0, modal.top() + 25.0), vec2(32.0, 32.0));
let xr = ui.interact(x, egui::Id::new("settings_close"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text("Close (Esc)");
if xr.hovered() {
ui.painter().rect_filled(x, 8.0, overlay(0.08));
}
ui.painter().text(x.center(), Align2::CENTER_CENTER, icon::CLOSE, icon_font(14.0), if xr.hovered() { t.header_primary } else { t.interactive_normal });
close |= xr.clicked();
// The page: a 696 px column, centred, 64 px down.
let content = Rect::from_min_max(pos2(side.right(), modal.top() + 50.0), pos2(modal.right() - 4.0, modal.bottom() - 1.0));
ui.data_mut(|d| d.insert_temp(tops_id(), Vec::<f32>::new()));
let mut cui = ui.new_child(egui::UiBuilder::new().max_rect(content).layout(Layout::top_down(Align::Min)));
ScrollArea::vertical().id_salt(("settings_content", self.settings_tab as u8)).auto_shrink([false, false]).show(&mut cui, |ui| {
let col = 696.0_f32.min(content.width() - 56.0);
let pad = ((content.width() - 12.0 - col) / 2.0).max(16.0);
ui.horizontal_top(|ui| {
ui.add_space(pad);
ui.vertical(|ui| {
ui.set_width(col);
ui.spacing_mut().item_spacing.y = 4.0;
ui.add_space(if content.height() < 520.0 { 24.0 } else { 64.0 });
match self.settings_tab {
SettingsTab::Account => self.account_tab(ui, &t),
SettingsTab::Profiles => self.profiles_tab(ui, &t),
SettingsTab::DataPrivacy => self.data_privacy_tab(ui, &t),
SettingsTab::Messaging => self.messaging_tab(ui, &t),
SettingsTab::Notifications => self.notifications_tab(ui, &t),
SettingsTab::Nitro => {}
SettingsTab::ServerBoost => self.boost_tab(ui, &t),
SettingsTab::Subscriptions => self.subscriptions_tab(ui, &t),
SettingsTab::GiftInventory => self.gifts_tab(ui, &t),
SettingsTab::Billing => self.billing_tab(ui, &t),
SettingsTab::VoiceVideo => self.voice_tab(ui, &t),
SettingsTab::Appearance => self.appearance_tab(ui, &t),
SettingsTab::Accessibility => self.accessibility_tab(ui, &t),
SettingsTab::System => self.system_tab(ui, &t),
SettingsTab::Language => self.language_tab(ui, &t),
SettingsTab::ActivityPrivacy => self.activity_tab(ui, &t),
SettingsTab::Connections => self.connections_tab(ui, &t),
SettingsTab::Developer => self.developer_tab(ui, &t),
SettingsTab::ProcessViewer => self.process_viewer_tab(ui, &t),
SettingsTab::Experimental => self.experimental_tab(ui, &t),
SettingsTab::Plugins => self.plugins_tab(ui, &t),
SettingsTab::Themes => self.themes_tab(ui, &t),
SettingsTab::About => self.about_tab(ui, &t),
}
ui.add_space(64.0);
});
});
});
// The section in view: the last one that starts above the upper
// third (unless a click on one is still scrolling there).
if ui.data(|d| d.get_temp::<usize>(jump_id())).is_none() {
let tops: Vec<f32> = ui.data(|d| d.get_temp(tops_id())).unwrap_or_default();
let line = content.top() + content.height() / 3.0;
let now = tops.iter().rposition(|y| *y <= line).unwrap_or(0);
ui.data_mut(|d| d.insert_temp(active_id, now));
}
});
if close {
self.close_settings(ctx);
}
}
pub(crate) fn close_settings(&mut self, ctx: &egui::Context) {
self.settings_open = false;
ctx.data_mut(|d| {
d.remove::<String>(egui::Id::new("settings_search"));
d.remove::<bool>(egui::Id::new("settings_ptt_recording"));
});
// (Anything typed for an account change is forgotten.)
self.account_edit = Default::default();
}
/// Open another page of settings (a "Related Settings" card).
fn go_settings(&mut self, tab: SettingsTab) {
self.settings_tab = tab;
}
/// A row that only opens the matching page on discord.com.
fn open_discord(&mut self, ui: &Ui, what: &str) {
ui.ctx().open_url(egui::OpenUrl::new_tab("https://discord.com/channels/@me"));
self.toast(format!("Opened discord.com: {what} there."), false);
}
/// "Loading…" / error line while your settings come in. True when ready.
fn settings_ready(&mut self, ui: &mut Ui, t: &Theme) -> bool {
match self.api_results.get("us:settings") {
Some(Ok(_)) => true,
Some(Err(e)) => {
ui.label(RichText::new(format!("Couldn't load your settings: {e}")).color(t.danger));
if ui.button("Try again").on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
self.api("us:settings", reqwest::Method::GET, "/users/@me/settings", None);
}
false
}
None => {
ui.spinner();
false
}
}
}
/// A toggle bound to one of your Discord settings (`invert`: the switch
/// shows the opposite of the stored value).
fn discord_toggle(&mut self, ui: &mut Ui, t: &Theme, key: &str, title: &str, desc: &str, invert: bool, default: bool) {
let stored = self.discord_setting(key, default);
if let Some(v) = toggle_row(ui, t, title, desc, stored != invert) {
self.set_discord_setting(key, Value::Bool(v != invert));
}
}
// ---- General --------------------------------------------------------------
fn account_tab(&mut self, ui: &mut Ui, t: &Theme) {
let me = match self.api_results.get("us:me") {
Some(Ok(v)) => v.clone(),
_ => self.store.me.as_ref().and_then(|u| serde_json::to_value(u).ok()).unwrap_or(Value::Null),
};
if !self.demo {
self.api_get_once("us:sessions", "/auth/sessions");
}
let reveal_id = egui::Id::new("settings_reveal");
// Streamer Mode: your email and phone stay hidden, with no way to show them.
let streaming = self.prefs.streaming_hides(|p| p.streamer_hide_personal);
let reveal = !streaming && ui.data(|d| d.get_temp::<bool>(reveal_id).unwrap_or(false));
section(ui, t, 0, "Account Info");
// Label on the left; value, "Reveal" and a button on the right.
let row = |ui: &mut Ui, label: &str, value: String, reveal_toggle: bool, button: &str| -> bool {
let mut clicked = false;
ui.horizontal(|ui| {
ui.set_height(40.0);
ui.label(RichText::new(label).font(crate::style::medium(16.0)).color(t.header_primary));
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if !button.is_empty() {
clicked = secondary_button(ui, t, button).clicked();
ui.add_space(4.0);
}
if reveal_toggle && !streaming {
if ui.add(egui::Label::new(RichText::new(if reveal { "Hide" } else { "Reveal" }).size(14.0).color(t.text_link)).selectable(false).sense(Sense::click())).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
ui.data_mut(|d| d.insert_temp(reveal_id, !reveal));
}
}
ui.label(RichText::new(value).size(16.0).color(t.text_normal));
});
});
ui.add_space(8.0);
clicked
};
let s = |k: &str| me.get(k).and_then(Value::as_str).unwrap_or("").to_string();
let mask_email = |e: &str| match e.split_once('@') {
Some((name, domain)) if !reveal => format!("{}@{domain}", "*".repeat(name.chars().count())),
_ => e.to_string(),
};
let phone = s("phone");
let mask_phone = |p: &str| if reveal || p.len() < 4 { p.to_string() } else { format!("{}{}", "*".repeat(p.len() - 4), &p[p.len() - 4..]) };
self.account_answer();
let mut open_web = false;
let editing = self.account_edit.kind;
let label = |kind: u8| if editing == kind { "Cancel" } else { "Edit" };
let mut toggle: Option<u8> = None;
if row(ui, "Username", s("username"), false, label(1)) {
toggle = Some(1);
}
self.account_editor(ui, t, 1);
if row(ui, "Email", if s("email").is_empty() { "None".into() } else { mask_email(&s("email")) }, true, label(2)) {
toggle = Some(2);
}
self.account_editor(ui, t, 2);
open_web |= row(ui, "Phone Number", if phone.is_empty() { "None".into() } else { mask_phone(&phone) }, true, "Edit");
let id = s("id");
if row(ui, "User ID", id.clone(), false, "Copy") {
ui.ctx().copy_text(id);
}
section(ui, t, 1, "Password & Security");
if row(ui, "Password", String::new(), false, label(3)) {
toggle = Some(3);
}
self.account_editor(ui, t, 3);
if let Some(kind) = toggle {
self.account_edit = crate::features::AccountEdit { kind: if editing == kind { 0 } else { kind }, ..Default::default() };
}
let mfa = me.get("mfa_enabled").and_then(Value::as_bool).unwrap_or(false);
row(ui, "Multi-Factor Authentication", if mfa { "Enabled".into() } else { "Not enabled".into() }, false, "");
let sessions = match self.api_results.get("us:sessions") {
Some(Ok(v)) => v["user_sessions"].as_array().cloned(),
_ => None,
};
let count = match &sessions {
Some(list) => format!("{} device{}", list.len(), if list.len() == 1 { "" } else { "s" }),
None if self.demo => "1 device".into(),
None => "…".into(),
};
let shown_id = egui::Id::new("settings_devices_open");
let shown = ui.data(|d| d.get_temp::<bool>(shown_id).unwrap_or(false));
if row(ui, "Logged-in Devices", count, false, if shown { "Hide" } else { "Show" }) {
ui.data_mut(|d| d.insert_temp(shown_id, !shown));
}
if shown {
for dev in sessions.iter().flatten() {
let info = &dev["client_info"];
let os = info["os"].as_str().unwrap_or("Unknown device");
let platform = info["platform"].as_str().unwrap_or("");
let place = info["location"].as_str().unwrap_or("");
let hash = dev["id_hash"].as_str().unwrap_or("").to_string();
let name = if platform.is_empty() { os.to_string() } else { format!("{os} · {platform}") };
let mut log_out = false;
Frame::none().fill(overlay(0.04)).rounding(8.0).inner_margin(Margin::symmetric(14.0, 10.0)).show(ui, |ui| {
ui.set_width(ui.available_width());
ui.horizontal(|ui| {
ui.vertical(|ui| {
ui.label(RichText::new(&name).font(crate::style::medium(15.0)).color(t.header_primary));
if !place.is_empty() {
ui.label(RichText::new(place).size(13.0).color(t.text_muted));
}
});
if !hash.is_empty() {
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
log_out = secondary_button(ui, t, "Log Out").clicked();
});
}
});
});
ui.add_space(6.0);
if log_out {
self.account_edit = crate::features::AccountEdit { kind: 4, device: hash.clone(), device_name: name.clone(), ..Default::default() };
}
if self.account_edit.kind == 4 && self.account_edit.device == hash {
self.account_editor(ui, t, 4);
}
}
note(ui, t, "One of these is this RustCord: logging it out signs you out here.");
}
section(ui, t, 2, "Account Status");
web(ui, t, "Age Group", "Some content and settings meant for adults are only available once Discord has confirmed that you're an adult.");
if !self.demo {
self.api_get_once("us:standing", "/safety-hub/@me");
}
let standing = match self.api_results.get("us:standing") {
Some(Ok(v)) => v["account_standing"]["state"].as_u64(),
_ => None,
};
match standing {
Some(state) => {
let (label, about, color) = match state {
100 => ("All good!", "Thanks for keeping Discord's Terms of Service and Community Guidelines. Your account has no active violations.", Color32::from_rgb(0x23, 0xa5, 0x5a)),
200 => ("Limited", "You broke Discord's rules. Some parts of Discord are limited for your account for now.", Color32::from_rgb(0xf0, 0xb2, 0x32)),
300 => ("Very limited", "You broke Discord's rules more than once or severely. More of Discord is limited for your account.", Color32::from_rgb(0xf0, 0x7a, 0x32)),
400 => ("At risk", "Your account is at risk of being suspended if Discord's rules are broken again.", t.danger),
_ => ("Suspended", "Your account is suspended.", t.danger),
};
ui.horizontal_top(|ui| {
let w = ui.available_width() - 150.0;
row_text(ui, t, "Account Standing", about, w, false);
ui.with_layout(Layout::right_to_left(Align::Min), |ui| {
ui.label(RichText::new(label).font(crate::style::medium(15.0)).color(color));
});
});
ui.add_space(16.0);
}
None => web(ui, t, "Account Standing", "Whether any parts of Discord are limited for your account because of rule violations."),
}
section(ui, t, 3, "Family Centre");
if button_row(ui, t, "Set up Family Centre", "Connect with a parent or guardian so they can stay in the loop. Your messages stay private and you'll always see exactly what they see.", "Open on discord.com", ButtonKind::Secondary) {
self.open_discord(ui, "set up Family Centre");
}
ui.add_space(8.0);
// Never done from here: both need your password on discord.com.
if button_row(ui, t, "Disable your account", "Temporarily disable your account.", "Disable Account", ButtonKind::CriticalSecondary) {
self.open_discord(ui, "disable your account");
}
if button_row(ui, t, "Close your account", "Permanently close your account.", "Delete Account", ButtonKind::Critical) {
self.open_discord(ui, "delete your account");
}
if self.demo {
note(ui, t, "You're in demo mode: nothing is sent to Discord.");
}
if open_web {
self.open_discord(ui, "your phone number is changed");
}
}
fn profiles_tab(&mut self, ui: &mut Ui, t: &Theme) {
heading(ui, t, "Profiles");
let Some(me) = self.store.me.clone() else {
ui.spinner();
return;
};
let profile = self.profiles.get(&(me.id, None)).and_then(|r| r.as_ref().ok()).cloned();
self.want_profile(me.id, None);
// Edit buffers live in egui memory until saved.
let id = egui::Id::new("settings_profile_edit");
let mut edit: (String, String, String) = ui.data(|d| d.get_temp(id)).unwrap_or_else(|| {
(
me.global_name.clone().unwrap_or_default(),
profile.as_ref().and_then(|p| p.pronouns()).unwrap_or("").to_string(),
profile.as_ref().and_then(|p| p.bio()).unwrap_or("").to_string(),
)
});
ui.horizontal_top(|ui| {
ui.vertical(|ui| {
ui.set_width(380.0);
let field = |ui: &mut Ui, label: &str, text: &mut String, multiline: bool, max: usize| {
ui.label(RichText::new(label).size(12.0).color(t.header_secondary));
ui.add_space(4.0);
Frame::none().fill(Color32::from_black_alpha(31)).stroke(Stroke::new(1.0_f32, overlay(0.2))).rounding(8.0).inner_margin(Margin::same(10.0)).show(ui, |ui| {
let w = ui.available_width();
if multiline {
ui.add(TextEdit::multiline(text).frame(false).desired_rows(4).desired_width(w).char_limit(max));
} else {
ui.add(TextEdit::singleline(text).frame(false).desired_width(w).char_limit(max));
}
});
ui.add_space(14.0);
};
field(ui, "Display Name", &mut edit.0, false, 32);
field(ui, "Pronouns", &mut edit.1, false, 40);
field(ui, "About Me", &mut edit.2, true, 190);
ui.label(RichText::new("Avatar").size(12.0).color(t.header_secondary));
ui.add_space(4.0);
ui.horizontal(|ui| {
if primary_button(ui, t, "Change Avatar").clicked() {
self.pick_avatar();
}
});
});
ui.add_space(24.0);
ui.vertical(|ui| {
ui.label(RichText::new("Preview").size(12.0).color(t.header_secondary));
ui.add_space(6.0);
let (r, _) = ui.allocate_exact_size(vec2(96.0, 96.0), Sense::hover());
paint_avatar(ui, r, Some(me.avatar_or_default(160)), me.display_name());
ui.add_space(8.0);
let name = if edit.0.trim().is_empty() { me.username.clone() } else { edit.0.clone() };
ui.label(RichText::new(name).font(strong(20.0)).color(t.header_primary));
ui.label(RichText::new(&me.username).size(14.0).color(t.text_normal));
});
});
let original = (
me.global_name.clone().unwrap_or_default(),
profile.as_ref().and_then(|p| p.pronouns()).unwrap_or("").to_string(),
profile.as_ref().and_then(|p| p.bio()).unwrap_or("").to_string(),
);
if edit != original {
ui.add_space(16.0);
Frame::none().fill(t.bg_tertiary).rounding(8.0).inner_margin(Margin::same(10.0)).show(ui, |ui| {
ui.horizontal(|ui| {
ui.label(RichText::new("Careful — you have unsaved changes!").size(15.0).color(t.header_primary));
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
let save = ui.add(Button::new(RichText::new("Save Changes").size(14.0).color(Color32::WHITE)).fill(Color32::from_rgb(0x24, 0x80, 0x46)).rounding(8.0).min_size(vec2(0.0, 32.0)));
if save.clicked() {
if edit.0 != original.0 {
let name = edit.0.trim();
self.api("us:me-patch", reqwest::Method::PATCH, "/users/@me", Some(json!({ "global_name": if name.is_empty() { Value::Null } else { Value::String(name.to_string()) } })));
}
if edit.1 != original.1 || edit.2 != original.2 {
self.api("us:profile-patch", reqwest::Method::PATCH, "/users/@me/profile", Some(json!({ "pronouns": edit.1, "bio": edit.2 })));
}
self.profiles.remove(&(me.id, None));
self.profile_requested.remove(&(me.id, None));
}
if ui.add(egui::Label::new(RichText::new("Reset").size(14.0).color(t.header_primary)).selectable(false).sense(Sense::click())).clicked() {
edit = original.clone();
}
});
});
});
}
for tag in ["us:me-patch", "us:profile-patch", "us:avatar"] {
match self.api_take(tag) {
Some(Ok(v)) => {
if let Ok(u) = serde_json::from_value::<discord::model::User>(v.clone()) {
if !u.username.is_empty() {
self.store.me = Some(u);
}
}
self.toast("Profile saved.", false);
ui.data_mut(|d| d.remove::<(String, String, String)>(id));
return;
}
Some(Err(e)) => self.toast(format!("Couldn't save your profile: {e}"), true),
None => {}
}
}
ui.data_mut(|d| d.insert_temp(id, edit));
}
/// The answer to an account change (see `account_editor`).
fn account_answer(&mut self) {
let Some(result) = self.api_take("us:acct") else { return };
let v = match result {
Err(e) => {
self.account_edit.error = Some(e);
// A refused verification needs a fresh one.
self.account_edit.mfa_data.clear();
return;
}
Ok(v) => v,
};
if let Some(mfa) = v.get("__mfa") {
// The ways RustCord can answer (a security key or a texted code needs discord.com).
let methods: Vec<String> = mfa["methods"].as_array().into_iter().flatten().filter_map(|m| m["type"].as_str()).filter(|k| matches!(*k, "totp" | "password" | "backup")).map(String::from).collect();
if methods.is_empty() {
self.account_edit.error = Some("Discord wants a security key or a texted code for this, which RustCord can't do: make this change on discord.com.".into());
return;
}
self.account_edit.mfa_kind = methods[0].clone();
self.account_edit.mfa_data.clear();
self.account_edit.mfa = Some((mfa["ticket"].as_str().unwrap_or("").to_string(), methods));
self.account_edit.error = None;
return;
}
self.account_edit.mfa = None;
self.account_edit.error = None;
let keep_me = |app: &mut Self, v: &Value| {
if let Ok(u) = serde_json::from_value::<discord::model::User>(v.clone()) {
if !u.username.is_empty() {
app.store.me = Some(u);
app.api_results.insert("us:me".into(), Ok(v.clone()));
}
}
};
match self.account_edit.step {
1 => {
keep_me(self, &v);
self.toast("Username changed.", false);
self.account_edit = Default::default();
}
10 => self.account_edit.email_sent = true,
11 => match v["token"].as_str() {
Some(token) => self.account_edit.email_token = Some(token.to_string()),
None => self.account_edit.error = Some("That code wasn't accepted.".into()),
},
12 => {
keep_me(self, &v);
self.toast("Almost done: confirm the change from the email Discord sent to your new address.", false);
self.account_edit = Default::default();
}
3 => {
self.account_edit = Default::default();
self.toast("Password changed.", false);
// A new password means a new session key: keep it, reconnect with it.
if let Some(token) = v["token"].as_str().filter(|t| !t.is_empty()) {
self.login_with_token(token.to_string());
}
}
4 => {
let gone = std::mem::take(&mut self.account_edit).device;
if let Some(Ok(s)) = self.api_results.get_mut("us:sessions") {
if let Some(list) = s["user_sessions"].as_array_mut() {
list.retain(|d| d["id_hash"].as_str() != Some(gone.as_str()));
}
}
self.toast("That device was logged out.", false);
}
_ => {}
}
}
/// Remember and send one step of an account change.
fn account_send(&mut self, step: u8, method: reqwest::Method, path: &str, body: Option<Value>) {
self.account_edit.step = step;
self.account_edit.error = None;
self.account_edit.mfa = None;
self.account_edit.pending = Some((method, path.to_string(), body));
self.account_request(None);
}
/// The card under an Account row while you change it: what to type, the
/// "verify it's you" step when Discord asks for one, errors, and Done.
fn account_editor(&mut self, ui: &mut Ui, t: &Theme, kind: u8) {
if self.account_edit.kind != kind {
return;
}
let busy = self.api_busy("us:acct");
let mut send: Option<(u8, reqwest::Method, &str, Option<Value>)> = None;
let mut verify = false;
let mut cancel = false;
let e = &mut self.account_edit;
Frame::none().fill(overlay(0.04)).stroke(Stroke::new(1.0_f32, t.border_subtle)).rounding(8.0).inner_margin(Margin::same(16.0)).show(ui, |ui| {
ui.set_width(ui.available_width());
let field = |ui: &mut Ui, label: &str, text: &mut String, secret: bool| {
ui.label(RichText::new(label).size(12.0).color(t.header_secondary));
ui.add_space(4.0);
Frame::none().fill(Color32::from_black_alpha(31)).stroke(Stroke::new(1.0_f32, overlay(0.2))).rounding(8.0).inner_margin(Margin::symmetric(10.0, 8.0)).show(ui, |ui| {
ui.add(TextEdit::singleline(text).password(secret).frame(false).desired_width(ui.available_width()));
});
ui.add_space(12.0);
};
if let Some((_, methods)) = e.mfa.clone() {
// Discord's "verify it's you" before the change goes through.
ui.label(RichText::new("Verify it's you").font(crate::style::medium(16.0)).color(t.header_primary));
ui.add_space(6.0);
if methods.len() > 1 {
for m in &methods {
let title = match m.as_str() {
"totp" => "Authenticator app code",
"backup" => "Backup code",
_ => "Password",
};
if radio_row(ui, t, title, "", e.mfa_kind == *m) && e.mfa_kind != *m {
e.mfa_kind = m.clone();
e.mfa_data.clear();
}
}
ui.add_space(6.0);
}
let (label, secret) = match e.mfa_kind.as_str() {
"totp" => ("6-DIGIT CODE FROM YOUR AUTHENTICATOR APP", false),
"backup" => ("8-DIGIT BACKUP CODE", false),
_ => ("PASSWORD", true),
};
field(ui, label, &mut e.mfa_data, secret);
ui.add_enabled_ui(!busy && !e.mfa_data.trim().is_empty(), |ui| {
verify = primary_button(ui, t, "Confirm").clicked();
});
} else {
match kind {
1 => {
field(ui, "NEW USERNAME", &mut e.value, false);
field(ui, "CURRENT PASSWORD", &mut e.password, true);
ui.add_enabled_ui(!busy && !e.value.trim().is_empty() && !e.password.is_empty(), |ui| {
if primary_button(ui, t, "Done").clicked() {
send = Some((1, reqwest::Method::PATCH, "/users/@me", Some(json!({ "username": e.value.trim().to_lowercase(), "password": e.password }))));
}
});
}
2 if !e.email_sent => {
ui.add(egui::Label::new(RichText::new("To change your email, Discord first sends a verification code to your current address.").size(14.0).color(t.text_normal)).wrap());
ui.add_space(10.0);
ui.add_enabled_ui(!busy, |ui| {
if primary_button(ui, t, "Send Verification Code").clicked() {
send = Some((10, reqwest::Method::PUT, "/users/@me/email", None));
}
});
}
2 if e.email_token.is_none() => {
ui.add(egui::Label::new(RichText::new("Check your current email's inbox and enter the code Discord sent.").size(14.0).color(t.text_normal)).wrap());
ui.add_space(10.0);
field(ui, "VERIFICATION CODE", &mut e.code, false);
ui.add_enabled_ui(!busy && !e.code.trim().is_empty(), |ui| {
if primary_button(ui, t, "Next").clicked() {
send = Some((11, reqwest::Method::POST, "/users/@me/email/verify-code", Some(json!({ "code": e.code.trim() }))));
}
});
}
2 => {
field(ui, "NEW EMAIL", &mut e.value, false);
field(ui, "CURRENT PASSWORD", &mut e.password, true);
ui.add_enabled_ui(!busy && e.value.contains('@') && !e.password.is_empty(), |ui| {
if primary_button(ui, t, "Done").clicked() {
send = Some((12, reqwest::Method::PATCH, "/users/@me", Some(json!({ "email": e.value.trim(), "email_token": e.email_token, "password": e.password }))));
}
});
}
3 => {
field(ui, "CURRENT PASSWORD", &mut e.password, true);
field(ui, "NEW PASSWORD", &mut e.value, true);
field(ui, "CONFIRM NEW PASSWORD", &mut e.confirm, true);
let matches = e.value == e.confirm;
if !e.confirm.is_empty() && !matches {
ui.label(RichText::new("The new passwords don't match.").size(13.0).color(t.danger));
ui.add_space(6.0);
}
ui.add_enabled_ui(!busy && matches && e.value.len() >= 8 && !e.password.is_empty(), |ui| {
if primary_button(ui, t, "Done").clicked() {
send = Some((3, reqwest::Method::PATCH, "/users/@me", Some(json!({ "password": e.password, "new_password": e.value }))));
}
});
ui.add_space(6.0);
ui.label(RichText::new("Changing your password logs your other devices out. RustCord stays signed in.").size(13.0).color(t.text_muted));
}
_ => {
ui.add(egui::Label::new(RichText::new(format!("Log out {}? Discord will ask you to verify it's you.", e.device_name)).size(14.0).color(t.text_normal)).wrap());
ui.add_space(10.0);
ui.horizontal(|ui| {
ui.add_enabled_ui(!busy, |ui| {
if ui.add(Button::new(RichText::new("Log Out").size(14.0).color(Color32::WHITE)).fill(t.danger).rounding(8.0).min_size(vec2(0.0, 36.0))).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
send = Some((4, reqwest::Method::POST, "/auth/sessions/logout", Some(json!({ "session_id_hashes": [e.device] }))));
}
});
cancel = secondary_button(ui, t, "Cancel").clicked();
});
}
}
}
if busy {
ui.add_space(6.0);
ui.spinner();
}
if let Some(err) = &e.error {
ui.add_space(8.0);
ui.add(egui::Label::new(RichText::new(err).size(14.0).color(t.danger)).wrap());
}
});
ui.add_space(12.0);
if cancel {
self.account_edit = Default::default();
}
if let Some((step, method, path, body)) = send {
self.account_send(step, method, path, body);
}
if verify {
if let Some((ticket, _)) = self.account_edit.mfa.clone() {
let (kind, data) = (self.account_edit.mfa_kind.clone(), self.account_edit.mfa_data.trim().to_string());
self.account_edit.error = None;
self.account_request(Some((ticket, kind, data)));
}
}
}
/// Pick a picture and make it your avatar.
fn pick_avatar(&mut self) {
let Some(path) = rfd::FileDialog::new().add_filter("Image", &["png", "jpg", "jpeg", "gif", "webp"]).pick_file() else { return };
let Ok(bytes) = std::fs::read(&path) else { return };
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("png").to_ascii_lowercase();
let mime = match ext.as_str() {
"jpg" | "jpeg" => "image/jpeg",
"gif" => "image/gif",
"webp" => "image/webp",
_ => "image/png",
};
use base64::Engine;
let data = format!("data:{mime};base64,{}", base64::engine::general_purpose::STANDARD.encode(bytes));
self.api("us:avatar", reqwest::Method::PATCH, "/users/@me", Some(json!({ "avatar": data })));
}
/// One of the two data consents (`usage_statistics`, `personalization`).
fn consent_toggle(&mut self, ui: &mut Ui, t: &Theme, key: &str, title: &str, desc: &str) {
let on = match self.api_results.get("us:consent") {
Some(Ok(v)) => v[key]["consented"].as_bool(),
_ => None,
};
let Some(on) = on else {
locked_row(ui, t, title, desc, Locked::Web);
return;
};
if let Some(v) = toggle_row(ui, t, title, desc, on) {
if let Some(Ok(c)) = self.api_results.get_mut("us:consent") {
c[key]["consented"] = Value::Bool(v);
}
let (grant, revoke) = if v { (vec![key], vec![]) } else { (vec![], vec![key]) };
self.api("us:consent-post", reqwest::Method::POST, "/users/@me/consent", Some(json!({ "grant": grant, "revoke": revoke })));
}
}
fn data_privacy_tab(&mut self, ui: &mut Ui, t: &Theme) {
if !self.demo {
self.api_get_once("us:consent", "/users/@me/consent");
}
match self.api_take("us:consent-post") {
Some(Ok(v)) if v.is_object() => {
self.api_results.insert("us:consent".into(), Ok(v));
}
Some(Err(e)) => {
self.toast(format!("Couldn't save that setting: {e}"), true);
self.api("us:consent", reqwest::Method::GET, "/users/@me/consent", None);
}
_ => {}
}
section(ui, t, 0, "How Discord Uses My Data");
locked_row(
ui,
t,
"Use data to make Discord work",
"In order to provide you with the basic Discord service, Discord needs to store and process some data, such as your messages, what servers you're in and your Direct Messages. By using Discord, you allow Discord to provide this basic service. You can stop this by Disabling or Deleting your account.",
Locked::Always,
);
self.consent_toggle(ui, t, "usage_statistics", "Use data to improve Discord", "Allow Discord to use and process my information to understand and improve Discord's services.");
self.consent_toggle(ui, t, "personalization", "Use data to personalise my Discord experience", "Allows Discord to use information, such as who you talk to and what games you play, to personalise Discord for you.");
self.proto_toggle(ui, t, &[8, 18], "Use my Discord activity to personalise Sponsored Content", "Allows Discord to personalise Sponsored Content, like Quests, using your Discord activity, such as the games you play. If you opt out you may still see Quests, but they won't be personalised.", true, false, true);
self.proto_toggle(ui, t, &[8, 30], "Use third-party data to personalise Sponsored Content", "Allows Discord to personalise Sponsored Content, like Quests, using data Discord receives from advertisers and third-party data providers. If you opt out, you may still see Quests, but they won't be personalised using data from third parties.", true, false, true);
self.proto_toggle(ui, t, &[8, 35], "Show my message content from Discoverable channels on web pages", "Allow message content that you send in Discoverable channels to appear on web pages. Admins of Discoverable servers control which channels are Discoverable. These messages will appear as you wrote them, but won't show your username.", true, true, true);
self.proto_toggle(ui, t, &[19, 1], "Allow my voice to be recorded in Clips", "Allows your voice to be included when someone in the same voice channel uses Clips.", false, true, true);
self.data_request(ui, t);
// RustCord's own: the registry behind the RustCord badge.
subheading(ui, t, "RustCord");
let desc = if crate::registry::url().is_some() {
"Shows other RustCord users a RustCord badge on your profile, with how long you've used RustCord and whether you're on it now (not while you're Invisible), and shows you theirs. While on, RustCord tells RustCord's registry server every few minutes that you're using it, and asks it about the profiles you open; the server sees your IP address and a hash of your user ID, which anyone who knows your ID can work out. While off, RustCord doesn't contact it at all."
} else {
"Shows other RustCord users a RustCord badge on your profile, with how long you've used RustCord and whether you're on it now. Badges are off in this build."
};
if let Some(v) = toggle_row(ui, t, "Show that I use RustCord", desc, self.prefs.share_rustcord) {
self.prefs.share_rustcord = v;
self.save_prefs();
self.start_registry(true);
}
section(ui, t, 1, "Profile Privacy");
note(ui, t, "Control who can see your profile info – like your bio and connected accounts.");
if self.settings_ready(ui, t) {
subheading(ui, t, "Share my full profile with");
let vis = self.setting_value("profile_visibility").and_then(|v| v.as_u64()).unwrap_or(3);
for (n, title, desc) in [
(3u64, "Friends & All Servers", "Your full profile is visible to friends and any server you join."),
(2, "Friends & Small Servers Only", "Your full profile is visible to friends and any server you join with 200 or fewer members. Everyone else sees a limited version."),
(1, "Friends Only", "Your full profile is visible to friends. Everyone else sees a limited version."),
] {
if radio_row(ui, t, title, desc, vis == n) && vis != n {
self.set_discord_setting("profile_visibility", json!(n));
}
}
ui.add_space(12.0);
}
self.proto_toggle(ui, t, &[7, 24], "Share when I update my profile", "Allow friends to receive a push notification when you update your profile.", false, true, true);
if related(ui, t, "activity", "Activity Privacy", "Control how your game and app activity is shared – what's visible and who sees it.") {
self.go_settings(SettingsTab::ActivityPrivacy);
}
}
fn messaging_tab(&mut self, ui: &mut Ui, t: &Theme) {
let ready = self.settings_ready(ui, t);
section(ui, t, 0, "Content Filters");
subheading(ui, t, "Sensitive content filters");
note(ui, t, "Choose how you want to see image-based media detected by Discord's sensitive content filters.");
let levels: &[(u64, &str)] = &[(1, "Show"), (2, "Blur"), (3, "Block")];
self.proto_choice(ui, t, &[6, 29, 2], "Direct messages from friends", "Show, blur or block mature sexual and graphic media.", levels, 1);
self.proto_choice(ui, t, &[6, 29, 3], "Direct messages from others", "", levels, 2);
self.proto_choice(ui, t, &[6, 29, 1], "Messages in server channels", "", levels, 1);
if ready {
self.discord_toggle(ui, t, "view_nsfw_commands", "Allow access to age-restricted commands from apps in DMs", "Allows people 18+ to access commands marked as age-restricted in DMs. Applies to all apps.", false, false);
self.discord_toggle(ui, t, "view_nsfw_guilds", "Allow access to age-restricted servers on iOS", "Access age-restricted servers (18+) on iOS devices, after joining them on desktop.", false, false);
}
if related(ui, t, "appearance", "Appearance", "Show/hide media in chat, spoiler content") {
self.go_settings(SettingsTab::Appearance);
}
section(ui, t, 1, "Spam Filters");
self.proto_choice(
ui,
t,
&[6, 27],
"Automatically filter suspected spam messages",
"Discord can filter out some messages that contain spam. These messages go to your Spam inbox.",
&[(3, "Filter all"), (2, "Filter from non-friends"), (1, "Do not filter")],
2,
);
section(ui, t, 2, "Direct Messages");
subheading(ui, t, "Direct Message (DM) Permissions");
if ready {
self.discord_toggle(ui, t, "default_guilds_restricted", "Allow DMs from other server members", "Applies to servers you join from now on. Each server's own setting is under its Privacy Settings.", true, false);
}
self.proto_toggle(ui, t, &[8, 17], "Message requests", "Filter messages from server members you may not know.", false, true, true);
section(ui, t, 3, "Friend Requests");
subheading(ui, t, "Friend Request Permissions");
note(ui, t, "Control who can send you friend requests and how they appear.");
if ready {
let flags = self.setting_value("friend_source_flags").filter(|v| v.is_object());
let get = |k: &str| flags.as_ref().and_then(|f| f.get(k)).and_then(Value::as_bool);
let all = get("all").unwrap_or(flags.is_none());
let (mut ff, mut sm) = (get("mutual_friends").unwrap_or(all), get("mutual_guilds").unwrap_or(all));
let mut every = all;
let mut changed = false;
if let Some(v) = toggle_row(ui, t, "Everyone", "", every) {
every = v;
if v {
ff = true;
sm = true;
}
changed = true;
}
if let Some(v) = toggle_row(ui, t, "Friend of friends", "", ff) {
ff = v;
every = false;
changed = true;
}
if let Some(v) = toggle_row(ui, t, "Server members", "Server members can only send you friend requests from servers where you also allow Direct Messages.", sm) {
sm = v;
every = false;
changed = true;
}
if changed {
let flags = if every { json!({ "all": true }) } else { json!({ "mutual_friends": ff, "mutual_guilds": sm }) };
self.set_discord_setting("friend_source_flags", flags);
}
}
self.proto_toggle(ui, t, &[8, 33], "Show personalised messages", "Show personalised messages on incoming friend requests. If you accept, the message will still appear in your DMs.", true, false, true);
section(ui, t, 4, "Connected Games");
note(ui, t, "These are settings for games that use Discord to power their social experiences. Games you've connected are managed under Connected Apps → Authorised Apps.");
if related(ui, t, "connections", "Authorised Apps", "Manage your games in Authorised Apps") {
self.go_settings(SettingsTab::Connections);
ui.data_mut(|d| d.insert_temp(jump_id(), 1usize));
}
section(ui, t, 5, "Ignore & Block");
let mut blocked: Vec<(discord::model::Id, String, String, Option<String>)> = self
.store
.relationships
.values()
.filter(|r| r.kind == 2)
.map(|r| match &r.user {
Some(u) => (r.id, u.display_name().to_string(), u.username.clone(), Some(u.avatar_or_default(64))),
None => (r.id, r.id.to_string(), String::new(), None),
})
.collect();
blocked.sort_by(|a, b| a.1.to_lowercase().cmp(&b.1.to_lowercase()));
subheading(ui, t, "Blocked accounts");
note(ui, t, &format!("{} account{}", blocked.len(), if blocked.len() == 1 { "" } else { "s" }));
let mut unblock = None;
for (id, name, username, avatar) in &blocked {
ui.horizontal(|ui| {
ui.set_height(48.0);
let (r, _) = ui.allocate_exact_size(vec2(32.0, 32.0), Sense::hover());
paint_avatar(ui, r, avatar.clone(), name);
ui.add_space(4.0);
ui.vertical(|ui| {
ui.add_space(6.0);
ui.label(RichText::new(name).font(crate::style::medium(16.0)).color(t.header_primary));
ui.label(RichText::new(username).size(13.0).color(t.text_muted));
});
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if secondary_button(ui, t, "Unblock").clicked() {
unblock = Some(*id);
}
});
});
}
if let Some(id) = unblock {
self.relationship(id, false, "Friends");
}
ui.add_space(8.0);
let mut ignored: Vec<(String, String, Option<String>)> = self
.store
.relationships
.values()
.filter(|r| r.user_ignored && r.kind != 2)
.map(|r| match &r.user {
Some(u) => (u.display_name().to_string(), u.username.clone(), Some(u.avatar_or_default(64))),
None => (r.id.to_string(), String::new(), None),
})
.collect();
ignored.sort_by(|a, b| a.0.to_lowercase().cmp(&b.0.to_lowercase()));
subheading(ui, t, "Ignored accounts");
note(ui, t, &format!("{} account{}", ignored.len(), if ignored.len() == 1 { "" } else { "s" }));
for (name, username, avatar) in &ignored {
ui.horizontal(|ui| {
ui.set_height(48.0);
let (r, _) = ui.allocate_exact_size(vec2(32.0, 32.0), Sense::hover());
paint_avatar(ui, r, avatar.clone(), name);
ui.add_space(4.0);
ui.vertical(|ui| {
ui.add_space(6.0);
ui.label(RichText::new(name).font(crate::style::medium(16.0)).color(t.header_primary));
ui.label(RichText::new(username).size(13.0).color(t.text_muted));
});
});
}
if !ignored.is_empty() {
note(ui, t, "To stop ignoring someone, open their profile.");
}
}
fn notifications_tab(&mut self, ui: &mut Ui, t: &Theme) {
let ready = self.settings_ready(ui, t);
section(ui, t, 0, "Overview");
if let Some(v) = toggle_row(ui, t, "Enable Desktop Notifications", "A Windows notification for direct messages and mentions while you're not looking at them. If you're looking for per-channel or per-server notifications, right-click the desired server icon and select Notification Settings.", self.prefs.desktop_notifications) {
self.prefs.desktop_notifications = v;
self.save_prefs();
if v {
crate::tray::notify("RustCord", "Notifications are on.");
}
}
subheading(ui, t, "Notify me when...");
if ready {
self.discord_toggle(ui, t, "stream_notifications_enabled", "People I know start streaming in small servers", "", false, true);
}
self.proto_toggle(ui, t, &[7, 14], "A friend and I reach a friendship anniversary", "", false, true, true);
self.proto_toggle(ui, t, &[7, 12], "Friends come online", "", false, false, true);
self.proto_toggle(ui, t, &[7, 22], "A server has an upcoming event", "", false, true, true);
self.proto_toggle(ui, t, &[7, 16], "Friends update their profile", "", false, false, true);
self.proto_choice(ui, t, &[7, 7], "Someone reacts to my messages", "", &[(0, "All Messages"), (1, "Only Direct Messages"), (2, "Never")], 0);
note(ui, t, "These five are for Discord's notifications on your phone and in Discord's official apps.");
section(ui, t, 1, "Sounds");
let mut changed = false;
let p = &mut self.prefs;
for (title, desc, value) in [
("New Message", "A chime for a new direct message or mention.", &mut p.sound_message),
("New Message in the channel I'm currently reading", "", &mut p.sound_current_channel),
("Incoming Ring", "", &mut p.sound_ring),
("Disable All Notification Sounds", "Disables all notification sounds, including voice and video sound effects.", &mut p.sounds_off),
] {
if let Some(v) = toggle_row(ui, t, title, desc, *value) {
*value = v;
changed = true;
}
}
if changed {
self.save_prefs();
if self.prefs.sound_message && self.prefs.sounds_allowed() {
self.audio.cue(crate::audio::Cue::Message, self.voice_ui.prefs.output_volume / 100.0);
}
}
if related(ui, t, "voice", "Voice & Video", "Enable/disable sounds that play when you're in a call, like Mute, Unmute, Deafen and more.") {
self.go_settings(SettingsTab::VoiceVideo);
ui.data_mut(|d| d.insert_temp(jump_id(), 3usize));
}
section(ui, t, 2, "Badges");
if let Some(v) = toggle_row(ui, t, "Enable Unread Message Badge", "Shows a red badge on the app icon when you have unread messages: the number of mentions and direct messages, or a dot for other unread messages.", self.prefs.unread_badge) {
self.prefs.unread_badge = v;
self.save_prefs();
}
section(ui, t, 3, "Email");
if !self.demo {
self.api_get_once("us:email", "/users/@me/email-settings");
}
match self.api_take("us:email-patch") {
Some(Ok(v)) if v["categories"].is_object() => {
self.api_results.insert("us:email".into(), Ok(v));
}
Some(Err(e)) => {
self.toast(format!("Couldn't save that setting: {e}"), true);
self.api("us:email", reqwest::Method::GET, "/users/@me/email-settings", None);
}
_ => {}
}
let emails: [(&str, &str, &str); 5] = [
("communication", "Communication Emails", "Receive emails for missed calls, messages and message digests."),
("social", "Social Emails", "Receive emails for friend requests, new friend suggestions and events in your server."),
("updates_and_announcements", "Announcements and Update Emails", "Receive emails about product updates, our newest features, improvements and bug fixes."),
("tips", "Tip Emails", "Receive emails with helpful advice on how to use Discord and information on lesser-known features."),
("recommendations_and_events", "Recommendation Emails", "Receive emails with recommended servers and suggested events."),
];
let marketing = ["updates_and_announcements", "tips", "recommendations_and_events"];
let mut email_patch: Option<Value> = None;
for (key, title, desc) in emails {
let on = match self.api_results.get("us:email") {
Some(Ok(v)) => v["categories"][key].as_bool(),
_ => None,
};
match on {
Some(on) => {
if let Some(v) = toggle_row(ui, t, title, desc, on) {
email_patch = Some(json!({ key: v }));
}
}
None => web(ui, t, title, desc),
}
}
let any_marketing = match self.api_results.get("us:email") {
Some(Ok(v)) => Some(marketing.iter().any(|k| v["categories"][*k].as_bool() == Some(true))),
_ => None,
};
match any_marketing {
Some(any) => {
if button_row(ui, t, "Unsubscribe from all marketing emails", if any { "Turns off announcement, tip and recommendation emails." } else { "You get no marketing emails." }, "Unsubscribe", ButtonKind::Secondary) && any {
email_patch = Some(json!({ "updates_and_announcements": false, "tips": false, "recommendations_and_events": false }));
}
}
None => web(ui, t, "Unsubscribe from all marketing emails", ""),
}
if let Some(categories) = email_patch {
if let Some(Ok(v)) = self.api_results.get_mut("us:email") {
for (k, on) in categories.as_object().into_iter().flatten() {
v["categories"][k.as_str()] = on.clone();
}
}
self.api("us:email-patch", reqwest::Method::PATCH, "/users/@me/email-settings", Some(json!({ "settings": { "categories": categories } })));
}
section(ui, t, 4, "Advanced");
if ready {
self.discord_toggle(ui, t, "enable_tts_command", "Allow playback and usage of /tts command", "", false, true);
}
if ready {
let secs = self.setting_value("afk_timeout").and_then(|v| v.as_u64()).unwrap_or(600);
let steps: [(u64, &str); 6] = [(60, "1 minute"), (120, "2 minutes"), (180, "3 minutes"), (240, "4 minutes"), (300, "5 minutes"), (600, "10 minutes")];
let current = steps.iter().position(|(s, _)| *s >= secs).unwrap_or(steps.len() - 1);
let labels: Vec<&str> = steps.iter().map(|(_, l)| *l).collect();
if let Some(i) = choice_row(ui, t, "afk_timeout", "Push notification inactive timeout", "How long you have to be away from your computer before your phone gets the notifications instead.", &labels, current) {
self.set_discord_setting("afk_timeout", json!(steps[i].0));
}
}
}
// ---- Billing --------------------------------------------------------------
/// Billing pages show what you have (Boosts, subscriptions, gifts, past
/// payments) and redeem codes. Paying, cancelling and your cards stay on
/// discord.com: a button to the real page.
fn billing_stub(&mut self, ui: &mut Ui, t: &Theme, text: &str, button: &str, what: &str) {
if !text.is_empty() {
note(ui, t, text);
}
if secondary_button(ui, t, button).clicked() {
self.open_discord(ui, what);
}
ui.add_space(8.0);
}
/// A list a billing page shows: `None` while it loads (a spinner or the
/// error is drawn), the rows once it's there. Demo mode has none.
fn billing_list(&mut self, ui: &mut Ui, t: &Theme, tag: &str, path: &str) -> Option<Vec<Value>> {
if self.demo {
return Some(Vec::new());
}
self.api_get_once(tag, path);
match self.api_results.get(tag) {
Some(Ok(Value::Array(a))) => Some(a.clone()),
Some(Ok(_)) => Some(Vec::new()),
Some(Err(e)) => {
ui.label(RichText::new(format!("Couldn't load this: {e}")).color(t.danger));
if ui.button("Try again").on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
self.api(tag, reqwest::Method::GET, path.to_string(), None);
}
None
}
None => {
ui.spinner();
None
}
}
}
fn boost_tab(&mut self, ui: &mut Ui, t: &Theme) {
section(ui, t, 0, "Server Boosts");
note(ui, t, "Boosting a server unlocks perks for everyone in that server.");
if let Some(slots) = self.billing_list(ui, t, "us:boost-slots", "/users/@me/guilds/premium/subscription-slots") {
subheading(ui, t, &format!("Your Boosts — {}", slots.len()));
if slots.is_empty() {
note(ui, t, "You have no Boosts.");
}
for slot in &slots {
let guild = Id::from_value(&slot["premium_guild_subscription"]["guild_id"]);
let name = match guild {
Some(g) => self.store.guilds.get(&g).map_or_else(|| "A server you're no longer in".to_string(), |gs| gs.guild.name.clone()),
None => "Unused Boost".to_string(),
};
let cooldown = slot["cooldown_ends_at"].as_str().and_then(|c| chrono::DateTime::parse_from_rfc3339(c).ok()).filter(|c| *c > chrono::Utc::now());
let mut status = match (guild.is_some(), cooldown) {
(_, Some(c)) => format!("On cooldown until {}", long_date(&c.to_rfc3339())),
(true, None) => "Can be moved to another server".to_string(),
(false, None) => "Ready to use".to_string(),
};
if slot["canceled"].as_bool() == Some(true) {
status.push_str(" · Cancelled");
}
Frame::none().fill(overlay(0.04)).stroke(Stroke::new(1.0_f32, t.border_subtle)).rounding(8.0).inner_margin(Margin::symmetric(16.0, 12.0)).show(ui, |ui| {
ui.set_width(ui.available_width());
ui.label(RichText::new(name).font(crate::style::medium(16.0)).color(t.header_primary));
ui.label(RichText::new(status).size(13.0).color(t.text_muted));
});
ui.add_space(8.0);
}
}
self.billing_stub(ui, t, "Buying, moving and cancelling Boosts happens on Discord (mind the 7-day cooldown).", "Manage Boosts on discord.com", "manage your Boosts");
subheading(ui, t, "Perks");
let perks: &[(&str, [&str; 3])] = &[
("Emoji Slots", ["100", "150", "250"]),
("Sticker Slots", ["15", "30", "60"]),
("Soundboard Slots", ["24", "36", "48"]),
("Stream Quality", ["720p & 60 fps", "1080p & 60 fps", "1080p & 60 fps"]),
("Audio Quality", ["128 kbps", "256 kbps", "384 kbps"]),
("Upload Size Limit", ["10 MB", "50 MB", "100 MB"]),
("Video Stage Seats", ["50", "150", "300"]),
];
Grid::new("boost_perks").num_columns(4).spacing(vec2(28.0, 12.0)).show(ui, |ui| {
ui.label("");
for (level, boosts) in [("Level 1", "2 Boosts"), ("Level 2", "7 Boosts"), ("Level 3", "14 Boosts")] {
ui.vertical(|ui| {
ui.label(RichText::new(level).font(crate::style::medium(15.0)).color(t.header_primary));
ui.label(RichText::new(boosts).size(12.0).color(t.text_muted));
});
}
ui.end_row();
for (name, levels) in perks {
ui.label(RichText::new(*name).size(15.0).color(t.header_primary));
for v in levels {
ui.label(RichText::new(*v).size(15.0).color(t.text_normal));
}
ui.end_row();
}
});
}
fn subscriptions_tab(&mut self, ui: &mut Ui, t: &Theme) {
section(ui, t, 0, "Subscriptions");
if let Some(subs) = self.billing_list(ui, t, "us:subscriptions", "/users/@me/billing/subscriptions?sync_level=1&with_gift_subscription=true") {
if subs.is_empty() {
note(ui, t, "You have no subscriptions.");
}
for sub in &subs {
let plans: Vec<String> = sub["items"]
.as_array()
.into_iter()
.flatten()
.map(|item| {
let name = plan_name(item["plan_id"].as_str().unwrap_or(""));
match item["quantity"].as_u64().unwrap_or(1) {
0 | 1 => name.to_string(),
n => format!("{n} × {name}"),
}
})
.collect();
let title = if plans.is_empty() { "Subscription".to_string() } else { plans.join(" + ") };
let end = sub["current_period_end"].as_str().map(long_date).unwrap_or_default();
let (state, color) = match sub["status"].as_u64().unwrap_or(1) {
1 => ("Active", Color32::from_rgb(0x23, 0xa5, 0x5a)),
2 => ("Payment overdue", t.danger),
3 => ("Cancelled", Color32::from_rgb(0xf0, 0xb2, 0x32)),
4 => ("Ended", t.text_muted),
6 => ("On hold", Color32::from_rgb(0xf0, 0xb2, 0x32)),
_ => ("Inactive", t.text_muted),
};
let when = match sub["status"].as_u64().unwrap_or(1) {
1 if !end.is_empty() => format!("Renews on {end}"),
3 if !end.is_empty() => format!("Ends on {end}"),
_ => String::new(),
};
let since = sub["created_at"].as_str().map(long_date).unwrap_or_default();
Frame::none().fill(overlay(0.04)).stroke(Stroke::new(1.0_f32, t.border_subtle)).rounding(8.0).inner_margin(Margin::symmetric(16.0, 12.0)).show(ui, |ui| {
ui.set_width(ui.available_width());
ui.horizontal(|ui| {
ui.label(RichText::new(&title).font(crate::style::medium(16.0)).color(t.header_primary));
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
ui.label(RichText::new(state).font(crate::style::medium(14.0)).color(color));
});
});
if !when.is_empty() {
ui.label(RichText::new(when).size(14.0).color(t.text_normal));
}
if !since.is_empty() {
ui.label(RichText::new(format!("Subscribed since {since}")).size(13.0).color(t.text_muted));
}
});
ui.add_space(8.0);
}
}
self.billing_stub(ui, t, "Changing or cancelling a plan happens on Discord.", "Manage Subscriptions on discord.com", "manage your subscriptions");
}
fn gifts_tab(&mut self, ui: &mut Ui, t: &Theme) {
section(ui, t, 0, "Redeem Codes");
note(ui, t, "Received a code for Nitro or a game? That's exciting! Enter it below.");
let code_id = egui::Id::new("settings_gift_code");
let mut text: String = ui.data(|d| d.get_temp(code_id)).unwrap_or_default();
// A pasted gift link works too: the code is its last part.
let code: String = text.trim().trim_end_matches('/').rsplit('/').next().unwrap_or("").chars().filter(|c| c.is_ascii_alphanumeric()).collect();
let mut look_up = false;
ui.horizontal(|ui| {
Frame::none().fill(Color32::from_black_alpha(31)).stroke(Stroke::new(1.0_f32, overlay(0.2))).rounding(8.0).inner_margin(Margin::symmetric(10.0, 8.0)).show(ui, |ui| {
let r = ui.add(TextEdit::singleline(&mut text).frame(false).hint_text("WUMP-USWU-MPUS-WUMP").desired_width(ui.available_width() - 130.0));
look_up |= r.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter));
});
look_up |= primary_button(ui, t, "Check Code").clicked();
});
ui.data_mut(|d| d.insert_temp(code_id, text));
if look_up && !code.is_empty() && !self.demo {
self.api_results.remove("us:gift-redeem");
self.api("us:gift-code", reqwest::Method::GET, format!("/entitlements/gift-codes/{code}?with_application=false&with_subscription_plan=true"), None);
}
ui.add_space(8.0);
if self.api_busy("us:gift-code") || self.api_busy("us:gift-redeem") {
ui.spinner();
}
match self.api_results.get("us:gift-redeem") {
Some(Ok(_)) => {
ui.label(RichText::new("Redeemed! It's on your account now.").font(crate::style::medium(15.0)).color(Color32::from_rgb(0x23, 0xa5, 0x5a)));
}
Some(Err(e)) => {
ui.label(RichText::new(format!("Couldn't redeem that code: {e}")).color(t.danger));
}
None => {}
}
let found = match self.api_results.get("us:gift-code") {
Some(Ok(v)) => Some(Ok(v.clone())),
Some(Err(e)) => Some(Err(e.clone())),
None => None,
};
match found {
Some(Ok(gift)) if !matches!(self.api_results.get("us:gift-redeem"), Some(Ok(_))) => {
let what = gift["subscription_plan"]["name"].as_str().or(gift["store_listing"]["sku"]["name"].as_str()).unwrap_or("A gift").to_string();
let used = gift["redeemed"].as_bool() == Some(true) || (gift["max_uses"].as_u64().is_some_and(|m| m > 0 && gift["uses"].as_u64().unwrap_or(0) >= m));
let expired = gift["expires_at"].as_str().and_then(|e| chrono::DateTime::parse_from_rfc3339(e).ok()).is_some_and(|e| e < chrono::Utc::now());
let from = gift["user"]["global_name"].as_str().or(gift["user"]["username"].as_str()).map(|u| format!("From {u}")).unwrap_or_default();
let gift_code = gift["code"].as_str().unwrap_or("").to_string();
let mut redeem = false;
Frame::none().fill(overlay(0.04)).stroke(Stroke::new(1.0_f32, t.border_subtle)).rounding(8.0).inner_margin(Margin::symmetric(16.0, 12.0)).show(ui, |ui| {
ui.set_width(ui.available_width());
ui.horizontal(|ui| {
ui.vertical(|ui| {
ui.label(RichText::new(&what).font(crate::style::medium(16.0)).color(t.header_primary));
if !from.is_empty() {
ui.label(RichText::new(&from).size(13.0).color(t.text_muted));
}
});
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if used {
ui.label(RichText::new("Already redeemed").size(14.0).color(t.text_muted));
} else if expired {
ui.label(RichText::new("Expired").size(14.0).color(t.text_muted));
} else {
redeem = primary_button(ui, t, "Redeem").clicked();
}
});
});
});
if redeem && !gift_code.is_empty() {
self.api("us:gift-redeem", reqwest::Method::POST, format!("/entitlements/gift-codes/{gift_code}/redeem"), Some(json!({ "channel_id": null, "payment_source_id": null })));
}
}
Some(Err(e)) => {
let text = if e.contains("404") || e.contains("10038") { "That code isn't valid. Check it and try again.".to_string() } else { format!("Couldn't check that code: {e}") };
ui.label(RichText::new(text).color(t.danger));
}
_ => {}
}
if self.demo {
note(ui, t, "You're in demo mode: codes aren't checked.");
}
section(ui, t, 1, "The Gifting Badge");
Grid::new("gifting_badge").num_columns(2).spacing(vec2(28.0, 8.0)).show(ui, |ui| {
for (name, n) in [("Patron", "Gifted 1x"), ("Champion", "Gifted 2x"), ("Luminary", "Gifted 3x"), ("Icon", "Gifted 6x"), ("Hero", "Gifted 10x"), ("Legend", "Gifted 20x")] {
ui.label(RichText::new(name).font(crate::style::medium(15.0)).color(t.header_primary));
ui.label(RichText::new(n).size(14.0).color(t.text_muted));
ui.end_row();
}
});
ui.add_space(8.0);
note(ui, t, "Your badge progresses as you gift. Exceptions include when a gift is refunded or when fraud is detected.");
section(ui, t, 2, "Gifts I Purchased");
if let Some(gifts) = self.billing_list(ui, t, "us:gifts", "/users/@me/entitlements/gifts") {
if gifts.is_empty() {
note(ui, t, "You have no gifts waiting to be given.");
}
for gift in &gifts {
let name = gift["sku"]["name"].as_str().or(gift["subscription_plan"]["name"].as_str()).unwrap_or("A gift");
Frame::none().fill(overlay(0.04)).stroke(Stroke::new(1.0_f32, t.border_subtle)).rounding(8.0).inner_margin(Margin::symmetric(16.0, 12.0)).show(ui, |ui| {
ui.set_width(ui.available_width());
ui.label(RichText::new(name).font(crate::style::medium(16.0)).color(t.header_primary));
ui.label(RichText::new("Not given yet. Create its gift link on discord.com.").size(13.0).color(t.text_muted));
});
ui.add_space(8.0);
}
}
}
fn billing_tab(&mut self, ui: &mut Ui, t: &Theme) {
section(ui, t, 0, "Payment Methods");
self.billing_stub(ui, t, "Your cards and other payment methods, your gift card balance and where to add a new one.", "Manage Payment Methods on discord.com", "manage your payment methods");
section(ui, t, 1, "Transaction History");
if let Some(payments) = self.billing_list(ui, t, "us:payments", "/users/@me/billing/payments?limit=30") {
if payments.is_empty() {
note(ui, t, "You have no past payments.");
}
for pay in &payments {
let what = pay["description"].as_str().filter(|d| !d.is_empty()).or(pay["sku"]["name"].as_str()).unwrap_or("Payment");
let date = pay["created_at"].as_str().map(long_date).unwrap_or_default();
let amount = money(pay["amount"].as_i64().unwrap_or(0), pay["currency"].as_str().unwrap_or(""));
let refunded = pay["amount_refunded"].as_i64().unwrap_or(0) > 0;
let (state, color) = match pay["status"].as_u64().unwrap_or(1) {
0 => ("Pending", t.text_muted),
1 if refunded => ("Refunded", Color32::from_rgb(0xf0, 0xb2, 0x32)),
1 => ("", t.text_muted),
2 => ("Failed", t.danger),
3 => ("Reversed", Color32::from_rgb(0xf0, 0xb2, 0x32)),
4 => ("Refunded", Color32::from_rgb(0xf0, 0xb2, 0x32)),
_ => ("Cancelled", t.text_muted),
};
ui.horizontal(|ui| {
ui.set_height(44.0);
ui.vertical(|ui| {
ui.add_space(4.0);
ui.label(RichText::new(what).size(15.0).color(t.header_primary));
ui.label(RichText::new(&date).size(13.0).color(t.text_muted));
});
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
ui.label(RichText::new(&amount).font(crate::style::medium(15.0)).color(t.header_primary));
if !state.is_empty() {
ui.add_space(8.0);
ui.label(RichText::new(state).size(13.0).color(color));
}
});
});
let y = ui.cursor().top();
ui.painter().hline(ui.max_rect().x_range(), y, Stroke::new(1.0_f32, t.border_subtle));
}
}
}
/// Data & Privacy → "Request my data": pick what goes in the package,
/// then ask Discord for it (it emails you a link; one request per 30 days).
fn data_request(&mut self, ui: &mut Ui, t: &Theme) {
if !self.demo {
self.api_get_once("us:harvest", "/users/@me/harvest");
}
match self.api_take("us:harvest-post") {
Some(Ok(v)) => {
self.api_results.insert("us:harvest".into(), Ok(v));
self.toast("Data requested. Discord will email you when it's ready.", false);
}
Some(Err(e)) => self.toast(format!("Couldn't request your data: {e}"), true),
None => {}
}
let asked = match self.api_results.get("us:harvest") {
Some(Ok(v)) => v["created_at"].as_str().map(long_date),
_ => None,
};
let open_id = egui::Id::new("settings_harvest_open");
let open = ui.data(|d| d.get_temp::<bool>(open_id).unwrap_or(false));
let about = "If you need a copy of your personal data from your account's entire history, you can get it here.";
if let Some(date) = asked {
ui.horizontal_top(|ui| {
let w = ui.available_width() - 220.0;
row_text(ui, t, "Request my data", about, w, false);
ui.with_layout(Layout::right_to_left(Align::Min), |ui| {
ui.label(RichText::new(format!("Requested on {date}")).size(13.0).color(t.text_muted));
});
});
ui.add_space(16.0);
return;
}
if button_row(ui, t, "Request my data", about, if open { "Never mind" } else { "Request Data" }, ButtonKind::Secondary) {
ui.data_mut(|d| d.insert_temp(open_id, !open));
}
if !open {
return;
}
// (What Discord calls each part of the package, and what it sends.)
const PARTS: [(&str, &str); 7] = [("Account", "Account"), ("Your Activity", "Analytics"), ("Activities", "Activities"), ("Ads", "Ads"), ("Messages", "Messages"), ("Servers", "Servers"), ("Support Tickets", "Zendesk")];
let picks_id = egui::Id::new("settings_harvest_parts");
let mut picks: [bool; 7] = ui.data(|d| d.get_temp(picks_id)).unwrap_or([true; 7]);
let mut send = false;
Frame::none().fill(overlay(0.04)).stroke(Stroke::new(1.0_f32, t.border_subtle)).rounding(8.0).inner_margin(Margin::same(16.0)).show(ui, |ui| {
ui.set_width(ui.available_width());
ui.label(RichText::new("Submit Data Request").font(crate::style::medium(16.0)).color(t.header_primary));
ui.add(egui::Label::new(RichText::new("Select the data that you'd like to be included in your data package. Some selections, like Messages, may delay the delivery of your package and it may take up to 30 days to collect your data. Discord emails you at your account's address when the package is ready.").size(14.0).color(t.text_muted)).wrap());
ui.add_space(8.0);
for (i, (label, _)) in PARTS.iter().enumerate() {
ui.checkbox(&mut picks[i], RichText::new(*label).size(15.0).color(t.text_normal));
}
ui.add_space(10.0);
ui.add_enabled_ui(picks.iter().any(|p| *p) && !self.demo, |ui| {
send = primary_button(ui, t, "Request My Data").clicked();
});
});
ui.add_space(16.0);
ui.data_mut(|d| d.insert_temp(picks_id, picks));
if send {
let backends: Vec<&str> = PARTS.iter().zip(picks).filter(|(_, on)| *on).map(|((_, key), _)| *key).collect();
self.api("us:harvest-post", reqwest::Method::POST, "/users/@me/harvest", Some(json!({ "backends": backends })));
ui.data_mut(|d| d.insert_temp(open_id, false));
}
}
// ---- Experience -----------------------------------------------------------
fn appearance_tab(&mut self, ui: &mut Ui, t: &Theme) {
let ready = matches!(self.api_results.get("us:settings"), Some(Ok(_)));
section(ui, t, 0, "Theme");
let current = if self.rencord.theme.base.is_empty() { "dark".to_string() } else { self.rencord.theme.base.clone() };
if let Some(v) = toggle_row(ui, t, "Same as Device Theme", "Match Windows' light or dark mode: the Light theme in light mode, your dark theme otherwise.", self.prefs.theme_follow_device) {
self.prefs.theme_follow_device = v;
if v && current != "light" {
self.prefs.theme_dark = current.clone();
}
crate::features::save_prefs(self.config_dir.as_deref(), &self.prefs);
}
subheading(ui, t, "Default Themes");
let mut pick = None;
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 8.0;
// Discord's order: Light, Ash, Dark, Onyx.
for key in ["light", "ash", "dark", "onyx"] {
let label = &crate::style::PRESETS.iter().find(|(k, _)| *k == key).map_or("Light", |(_, l)| *l);
let preview = crate::style::Theme::preset(key);
let (rect, resp) = ui.allocate_exact_size(vec2(48.0, 48.0), Sense::click());
let sel = current == key;
ui.painter().rect_filled(rect, 8.0, preview.bg_primary);
ui.painter().rect_stroke(rect, 8.0, Stroke::new(if sel { 2.0_f32 } else { 1.0_f32 }, if sel { BRAND } else if resp.hovered() { t.interactive_hover } else { overlay(0.24) }));
if sel {
ui.painter().circle_filled(rect.right_top() + vec2(-2.0, 2.0), 9.0, BRAND);
ui.painter().text(rect.right_top() + vec2(-2.0, 2.0), Align2::CENTER_CENTER, icon::CHECK, icon_font(10.0), Color32::WHITE);
}
if resp.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(*label).clicked() {
pick = Some(key.to_string());
}
}
});
ui.add_space(16.0);
if let Some(k) = pick {
// Like Discord: a plain theme drops the Nitro colour theme.
self.prefs.theme_color = Some("none".into());
// Picking one yourself stops following Windows.
self.prefs.theme_follow_device = false;
if k != "light" {
self.prefs.theme_dark = k.clone();
}
crate::features::save_prefs(self.config_dir.as_deref(), &self.prefs);
self.set_base_theme(&k);
// Discord's names for the same themes.
let discord = match k.as_str() {
"light" => "light",
"ash" => "dark",
"onyx" => "midnight",
_ => "darker",
};
if ready && self.prefs.sync_theme {
self.set_discord_setting("theme", json!(discord));
}
}
// Discord's Nitro colour themes.
subheading(ui, t, "Colour Themes");
note(ui, t, "Tints all of RustCord with one of Discord's gradients. The first one follows the theme you picked in Discord.");
let choice = self.prefs.theme_color.clone();
let account: Option<crate::style::Gradient> = match self.client_theme.preset.and_then(crate::style::gradient_preset) {
Some(p) => Some(p.gradient()),
None => {
let colors: Vec<Color32> = self.client_theme.colors.iter().filter_map(|c| crate::style::parse_hex(c)).collect();
(!colors.is_empty()).then(|| crate::style::Gradient::even(&colors, self.client_theme.angle))
}
};
let plain = crate::style::Theme::preset(¤t).bg_primary;
let mut new_choice: Option<Option<String>> = None;
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing = vec2(10.0, 10.0);
if color_swatch(ui, t, account.as_ref(), plain, choice.is_none(), "Your Discord theme").clicked() {
new_choice = Some(None);
}
if color_swatch(ui, t, None, plain, choice.as_deref() == Some("none"), "Default colours (no gradient)").clicked() {
new_choice = Some(Some("none".into()));
}
for p in crate::style::GRADIENT_PRESETS {
let key = format!("preset:{}", p.id);
if color_swatch(ui, t, Some(&p.gradient()), plain, choice.as_deref() == Some(key.as_str()), p.name).clicked() {
new_choice = Some(Some(key));
}
}
});
if let Some(c) = new_choice {
self.prefs.theme_color = c;
crate::features::save_prefs(self.config_dir.as_deref(), &self.prefs);
self.apply_theme();
}
ui.add_space(16.0);
if let Some(v) = toggle_row(ui, t, "Sync theme across my devices", "A theme you pick here is saved to your Discord account, so your other Discord apps switch too.", self.prefs.sync_theme) {
self.prefs.sync_theme = v;
crate::features::save_prefs(self.config_dir.as_deref(), &self.prefs);
}
if let Some(v) = toggle_row(ui, t, "Show other users' profile themes", "Off: everyone's profile is drawn in your theme's colours instead of their own.", self.prefs.profile_themes) {
self.prefs.profile_themes = v;
self.save_prefs();
}
subheading(ui, t, "Zoom Level");
note(ui, t, "Make everything in RustCord bigger or smaller.");
let mut zoom = ui.ctx().zoom_factor() * 100.0;
let r = ui.add(Slider::new(&mut zoom, 50.0..=200.0).clamping(egui::SliderClamping::Edits).step_by(10.0).suffix("%"));
if r.drag_stopped() || (r.changed() && !r.dragged()) {
self.prefs.zoom = (zoom / 100.0).clamp(0.5, 2.0);
crate::features::apply_zoom(ui.ctx(), self.prefs.zoom);
self.save_prefs();
}
ui.add_space(12.0);
note(ui, t, "Custom themes and QuickCSS are under RustCord → Themes.");
if related(ui, t, "accessibility", "Accessibility", "Change saturation of colours, enable high-contrast mode and more") {
self.go_settings(SettingsTab::Accessibility);
}
section(ui, t, 1, "App Icon");
note(ui, t, "RustCord has one app icon.");
section(ui, t, 2, "Messages");
subheading(ui, t, "Show images, videos and lolcats...");
if ready {
self.discord_toggle(ui, t, "inline_embed_media", "When posted as links to chat", "", false, true);
self.discord_toggle(ui, t, "inline_attachment_media", "When uploaded directly to Discord", "", false, true);
self.discord_toggle(ui, t, "render_embeds", "Show embeds and link previews", "", false, true);
self.discord_toggle(ui, t, "render_reactions", "Show emoji reactions", "", false, true);
} else {
ui.spinner();
}
if self.proto_ready() {
subheading(ui, t, "Show spoiler content");
let mode = self.account_proto.string(&[6, 4]).unwrap_or_default();
let mode = if mode.is_empty() { "ON_CLICK".to_string() } else { mode };
for (key, title) in [("ON_CLICK", "On click"), ("IF_MODERATOR", "On servers I moderate"), ("ALWAYS", "Always")] {
if radio_row(ui, t, title, "", mode == key) && mode != key {
self.set_proto(&[6, 4], Leaf::StringValue(key.into()));
}
}
ui.add_space(12.0);
} else {
web(ui, t, "Show spoiler content", "On click, on servers I moderate, or always.");
}
soon(ui, t, "Open threads in split view", "");
if let Some(v) = toggle_row(ui, t, "Show user avatars", "Show a small avatar beside each name in the Compact chat display (Accessibility → Chat Message Display).", self.prefs.compact_avatars) {
self.prefs.compact_avatars = v;
self.save_prefs();
}
if self.proto_ready() {
let shown = self.store.favorites.guild_visible != Some(false);
if let Some(v) = toggle_row(ui, t, "Show Favourites server", "Your Favourites stay saved, even if you toggle this off.", shown) {
self.store.favorites.guild_visible = Some(v);
self.set_proto(&[15, 3], Leaf::BoolValue(v));
}
} else {
web(ui, t, "Show Favourites server", "Your Favourites stay saved, even if you toggle this off.");
}
if related(ui, t, "accessibility", "Accessibility", "Adjust the visual density of chat messages and UI") {
self.go_settings(SettingsTab::Accessibility);
ui.data_mut(|d| d.insert_temp(jump_id(), 1usize));
}
section(ui, t, 3, "Chat Box");
locked_row(ui, t, "Preview emojis, mentions and markdown syntax as you type", "", Locked::Always);
if ready {
self.discord_toggle(ui, t, "convert_emoticons", "Automatically convert emoticons in your messages to emojis", "For example, when you type :) Discord will convert it to 🙂", false, true);
}
if let Some(v) = toggle_row(ui, t, "Spellcheck", "Underline misspelled words as you type; right-click one for corrections. Uses your Windows dictionaries.", self.prefs.spellcheck) {
self.prefs.spellcheck = v;
self.save_prefs();
}
self.proto_toggle(ui, t, &[6, 28], "Show stickers in autocomplete results", "Used by Discord's official apps.", false, true, true);
self.proto_toggle(ui, t, &[6, 39], "Show games in autocomplete results", "Used by Discord's official apps.", false, true, true);
if let Some(v) = toggle_row(ui, t, "Show send message button", "", self.prefs.send_button) {
self.prefs.send_button = v;
self.save_prefs();
}
section(ui, t, 4, "Typing Effects");
self.typing_effects(ui, t);
section(ui, t, 5, "Search");
self.proto_toggle(ui, t, &[6, 36], "By default, search across all my DMs", "In Discord's official apps, search all your DMs instead of only the selected one.", false, false, true);
section(ui, t, 6, "Streamer Mode");
let mut changed = false;
if let Some(v) = toggle_row(ui, t, "Enable Streamer Mode", "Streamer Mode hides your personal info so others watching your stream can't see it.", self.prefs.streamer_mode) {
self.prefs.streamer_mode = v;
changed = true;
}
subheading(ui, t, "If Streamer Mode is enabled...");
let p = &mut self.prefs;
for (title, desc, value) in [
("Hide my personal information, such as email, connected accounts and notes", "Your email and phone number in Settings stay masked and your connected accounts aren't listed.", &mut p.streamer_hide_personal),
("Disable all sound effects", "", &mut p.streamer_no_sounds),
("Disable notifications", "", &mut p.streamer_no_notifications),
] {
if let Some(v) = toggle_row(ui, t, title, desc, *value) {
*value = v;
changed = true;
}
}
if changed {
self.save_prefs();
}
if let Some(v) = toggle_row(ui, t, "Hide invite links to Discord servers", "While Streamer Mode is on, the code of every invite link in chat is shown as dots.", self.prefs.streamer_hide_invites) {
self.prefs.streamer_hide_invites = v;
self.save_prefs();
}
}
/// Appearance → Typing Effects: how the message box's letters move as you
/// type and what colour they are, with a box that types a sentence to show it.
fn typing_effects(&mut self, ui: &mut Ui, t: &Theme) {
use super::typing_fx::{self, Fx, Style};
note(ui, t, "Animate and colour the text in the message box while you type.");
let style = Style::from_prefs(&self.prefs);
// The preview: the message box, typing a sentence over and over.
let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), 56.0), Sense::hover());
ui.painter().rect(rect, 8.0, t.input_bg, Stroke::new(1.0_f32, t.border_subtle));
if ui.is_rect_visible(rect) {
const SAMPLE: &str = "Typing in RustCord can look like this!";
let now = ui.input(|i| i.time);
let motion = super::animating();
let total = SAMPLE.chars().count();
// A letter every 85 ms, then the sentence rests for two seconds.
let cycle = total as f64 * 0.085 + 2.0;
let shown = if style.anim == 0 || !motion { total } else { (((now % cycle) / 0.085) as usize + 1).min(total) };
let text: String = SAMPLE.chars().take(shown).collect();
let state = typing_fx::state(ui.ctx(), egui::Id::new("settings_typing_preview"));
let mut state = state.lock().unwrap_or_else(|e| e.into_inner());
if shown == 1 {
state.clear();
}
state.update(&text, now);
let fx = Fx { style, state: &state, now, motion };
let galley = ui.painter().layout_no_wrap(text, FontId::proportional(16.0), t.text_normal);
let pos = pos2(rect.left() + 16.0, rect.center().y - galley.size().y / 2.0);
fx.paint(&ui.painter().with_clip_rect(rect.intersect(ui.clip_rect())), &galley, pos, &[], t.text_normal);
if motion && (style.anim != 0 || fx.cycling()) {
ui.ctx().request_repaint();
}
}
ui.add_space(20.0);
let mut changed = false;
if let Some(i) = choice_row(ui, t, "typing_animation", "Typing animation", "Bounce and Wave move the whole line while you type, Ripple spreads out from the caret, Shake rattles every letter, Pop and Drop bring each new letter in. The text rests when you stop.", &typing_fx::ANIMATIONS, style.anim as usize) {
self.prefs.typing_animation = i as u8;
changed = true;
}
if let Some(i) = choice_row(ui, t, "typing_color", "Text colour", "The colour of what you type: the theme's, one colour, a gradient of two, or colours that move.", &typing_fx::COLOR_MODES, style.color as usize) {
self.prefs.typing_color_mode = i as u8;
changed = true;
}
if style.color == 3 {
if let Some(i) = choice_row(ui, t, "typing_color_anim", "Colour animation", "Rainbow runs through every hue; Flowing gradient and Pulse use your two colours.", &typing_fx::COLOR_ANIMS, style.color_anim as usize) {
self.prefs.typing_color_anim = i as u8;
changed = true;
}
}
// How many colours the choice uses.
let colors = match (style.color, style.color_anim) {
(1, _) => 1,
(2, _) | (3, 1 | 2) => 2,
_ => 0,
};
if colors > 0 {
ui.horizontal(|ui| {
ui.set_height(36.0);
ui.label(RichText::new(if colors == 1 { "Colour" } else { "Colours" }).font(crate::style::medium(16.0)).color(t.header_primary));
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
ui.spacing_mut().interact_size = vec2(56.0, 32.0);
ui.spacing_mut().item_spacing.x = 8.0;
if colors == 2 {
changed |= egui::color_picker::color_edit_button_srgb(ui, &mut self.prefs.typing_color_b).changed();
}
changed |= egui::color_picker::color_edit_button_srgb(ui, &mut self.prefs.typing_color_a).changed();
});
});
ui.add_space(16.0);
}
if changed {
self.save_prefs();
}
if crate::ui::REDUCED_MOTION.load(std::sync::atomic::Ordering::Relaxed) && (style.anim != 0 || style.color == 3) {
note(ui, t, "Reduced Motion is on (Accessibility), so the text stays still and animated colours don't move.");
}
}
fn accessibility_tab(&mut self, ui: &mut Ui, t: &Theme) {
let ready = matches!(self.api_results.get("us:settings"), Some(Ok(_)));
section(ui, t, 0, "Text Readability");
let sizes = [12.0_f32, 14.0, 15.0, 16.0, 18.0, 20.0, 24.0];
let at = sizes.iter().position(|s| (*s - self.prefs.chat_font_size).abs() < 0.5).unwrap_or(3);
if let Some(i) = marks_slider(ui, t, "Text size in chat", "Adjust the size of the chat font.", &["12px", "14px", "15px", "16px", "18px", "20px", "24px"], at) {
self.prefs.chat_font_size = sizes[i];
self.save_prefs();
}
if let Some(v) = toggle_row(ui, t, "Always underline links", "Make links stand out more.", self.prefs.underline_links) {
self.prefs.underline_links = v;
self.save_prefs();
}
if let Some(v) = toggle_row(ui, t, "Display Name Styles", "Enable display name styles – including font, effect and colour – across Discord.", self.prefs.name_styles) {
self.prefs.name_styles = v;
self.save_prefs();
}
section(ui, t, 1, "Visual Density");
if let Some(i) = choice_row(ui, t, "ui_density", "UI Density", "Adjust the height of rows in the channel, DM and member lists.", &["Compact", "Default", "Spacious"], self.prefs.ui_density.min(2) as usize) {
self.prefs.ui_density = i as u8;
self.save_prefs();
}
subheading(ui, t, "Chat Message Display");
for (on, title, desc) in [(false, "Default", "Avatars, with the name above the message."), (true, "Compact", "The time, the name and the message on one line: more messages on screen.")] {
if radio_row(ui, t, title, desc, self.prefs.compact_chat == on) && self.prefs.compact_chat != on {
self.prefs.compact_chat = on;
self.save_prefs();
}
}
ui.add_space(12.0);
let gaps = [0.0_f32, 4.0, 8.0, 16.0, 24.0];
let at = gaps.iter().position(|s| (*s - self.prefs.group_spacing).abs() < 0.5).unwrap_or(3);
if let Some(i) = marks_slider(ui, t, "Space Between Message Groups", "Adjust the spacing between message groups.", &["0px", "4px", "8px", "16px", "24px"], at) {
self.prefs.group_spacing = gaps[i];
self.save_prefs();
}
section(ui, t, 2, "Colour & Contrast");
let at = (self.prefs.saturation.clamp(0.0, 1.0) * 10.0).round() as usize;
if let Some(i) = marks_slider(ui, t, "Saturation", "Reduce the saturation of colours within the app, for those with colour sensitivities. This does not affect the saturation of images, videos, role colours or other user content.", &["0%", "10%", "20%", "30%", "40%", "50%", "60%", "70%", "80%", "90%", "100%"], at) {
self.prefs.saturation = i as f32 / 10.0;
crate::features::save_prefs(self.config_dir.as_deref(), &self.prefs);
self.apply_theme();
}
if let Some(v) = toggle_row(ui, t, "Apply saturation setting to custom colours", "Apply the above setting to custom colour choices, like role colours.", self.prefs.saturation_custom) {
self.prefs.saturation_custom = v;
self.save_prefs();
}
if let Some(v) = toggle_row(ui, t, "Enable High Contrast Mode", "Enhance visibility with bold colours and sharp contrast: text and icons at full strength, clearer borders.", self.prefs.high_contrast) {
self.prefs.high_contrast = v;
self.save_prefs();
self.apply_theme();
}
if let Some(v) = toggle_row(ui, t, "Sync contrast settings", "Follow Windows' contrast themes (Settings → Accessibility → Contrast themes).", self.prefs.contrast_sync) {
self.prefs.contrast_sync = v;
self.save_prefs();
self.apply_theme();
}
subheading(ui, t, "Role Colours");
note(ui, t, "Choose how you would like role colours to be displayed.");
for (n, title) in [(0u8, "Show role colours in names"), (1, "Show role colours next to names"), (2, "Don't show role colours")] {
if radio_row(ui, t, title, "", self.prefs.role_colors == n) && self.prefs.role_colors != n {
self.prefs.role_colors = n;
self.save_prefs();
}
}
ui.add_space(12.0);
soon(ui, t, "Official Messages", "Choose how official developer messages look on verified servers that support it.");
if let Some(v) = toggle_row(ui, t, "Show on/off indicators", "On forms, menus and settings, on/off toggles will have icons.", self.prefs.switch_icons) {
self.prefs.switch_icons = v;
self.save_prefs();
}
if related(ui, t, "appearance", "Appearance", "Change your app theme") {
self.go_settings(SettingsTab::Appearance);
}
section(ui, t, 3, "Reduced Motion");
let about = "Reduce the amount and intensity of animations, hover effects and other moving effects. Stops GIFs, animated emoji, avatars and other animations.";
if self.prefs.reduced_motion_sync {
// Windows decides: shown, not changeable.
let on = !crate::tray::system_animations();
ui.horizontal_top(|ui| {
let w = ui.available_width() - 170.0;
row_text(ui, t, "Enable Reduced Motion", about, w, true);
ui.with_layout(Layout::right_to_left(Align::Min), |ui| {
ui.label(RichText::new(if on { "On (from Windows)" } else { "Off (from Windows)" }).size(13.0).color(t.text_muted));
});
});
ui.add_space(16.0);
} else if let Some(v) = toggle_row(ui, t, "Enable Reduced Motion", about, self.prefs.reduced_motion) {
self.prefs.reduced_motion = v;
self.save_prefs();
}
if let Some(v) = toggle_row(ui, t, "Sync with computer setting", "Follow Windows' \"Animation effects\" switch (Settings → Accessibility → Visual effects).", self.prefs.reduced_motion_sync) {
self.prefs.reduced_motion_sync = v;
self.save_prefs();
}
// RustCord's own: how popouts, menus and dialogs arrive and leave.
let reduced = crate::ui::REDUCED_MOTION.load(std::sync::atomic::Ordering::Relaxed);
let about = if reduced {
"Popouts, menus and dialogs slide and fade as they open and close. Off while Reduced Motion is on."
} else {
"Popouts, menus and dialogs slide and fade as they open and close, like windows do in Windows."
};
if let Some(v) = toggle_row(ui, t, "Open and close animations", about, self.prefs.open_animations) {
self.prefs.open_animations = v;
self.save_prefs();
}
let stays = [5u32, 10, 15, 30, 60];
let at = stays.iter().position(|s| *s == self.prefs.toast_seconds).unwrap_or(0);
if let Some(i) = marks_slider(ui, t, "Minimum notification duration", "Keep RustCord's pop-up messages (like \"Link copied.\") on screen for at least this long.", &["5s", "10s", "15s", "30s", "60s"], at) {
self.prefs.toast_seconds = stays[i];
self.save_prefs();
}
if ready {
self.discord_toggle(ui, t, "gif_auto_play", "Play GIFs when Discord is focused", "", false, true);
self.discord_toggle(ui, t, "animate_emoji", "Play animated emojis", "", false, true);
subheading(ui, t, "Play sticker animations");
let st = self.sticker_animation().unwrap_or(0);
for (n, title, desc) in [
(0u64, "Always animate", ""),
(1, "Animate on interaction", "On the desktop client, stickers will animate on hover or focus. On mobile clients, stickers will animate on long-press."),
(2, "Never animate", ""),
] {
if radio_row(ui, t, title, desc, st == n) && st != n {
if self.account_proto.is_empty() {
self.set_discord_setting("animate_stickers", json!(n));
} else {
self.set_proto(&[6, 15], Leaf::UInt32Value(n as u32));
self.apply_discord_settings();
}
}
}
} else {
ui.spinner();
}
section(ui, t, 4, "Audio & Screen Reader");
let rates = [-6, -3, 0, 3, 6];
let at = rates.iter().position(|r| *r == self.prefs.tts_rate).unwrap_or(2);
if let Some(i) = marks_slider(ui, t, "Text-to-speech rate", "Control the speed at which text is read aloud when using Speak Message (right-click a message).", &["Slowest", "Slow", "Normal", "Fast", "Fastest"], at) {
self.prefs.tts_rate = rates[i];
self.save_prefs();
}
if let Some(v) = toggle_row(ui, t, "Show image descriptions", "Pictures that were given a description get an ALT tag: hover it to read the description.", self.prefs.image_descriptions) {
self.prefs.image_descriptions = v;
self.save_prefs();
}
if let Some(v) = toggle_row(ui, t, "Use the legacy chat input", "A plain message box: emoji stay as text while you type and typing effects are off.", self.prefs.legacy_chat_input) {
self.prefs.legacy_chat_input = v;
self.save_prefs();
}
}
fn system_tab(&mut self, ui: &mut Ui, t: &Theme) {
// Discord's General: what the title bar's X does (not on macOS).
let general = usize::from(cfg!(any(windows, target_os = "linux")));
if general == 1 {
section(ui, t, 0, "General");
if self.tray_available() {
if let Some(v) = toggle_row(ui, t, "Minimize RustCord to System Tray", "Clicking X minimizes RustCord instead of closing it completely.", self.prefs.minimize_to_tray) {
self.prefs.minimize_to_tray = v;
self.save_prefs();
}
} else {
note(ui, t, "Clicking X closes RustCord: this desktop doesn't show notification-area icons.");
}
}
section(ui, t, general, "Custom Keybinds");
note(ui, t, "Keybinds are custom keyboard shortcuts that let you perform specific actions without needing to click through menus. The Push to Talk shortcut works in any app.");
if let Some(v) = toggle_row(ui, t, "Push to Talk", "Send your microphone only while the shortcut is held (Voice & Video → Input Mode).", self.voice_ui.prefs.push_to_talk) {
self.voice_ui.prefs.push_to_talk = v;
self.voice_ui.changed();
}
self.ptt_shortcut_row(ui, t);
section(ui, t, general + 1, "Default Keybinds");
use super::shortcuts::{groups, hint, key_text, COMBOS_TOGGLE, MAC};
note(ui, t, &format!("RustCord's built-in keyboard shortcuts. {} shows them anywhere.", hint(COMBOS_TOGGLE, MAC)));
for (name, list) in groups(MAC) {
subheading(ui, t, name);
for s in list {
ui.horizontal(|ui| {
ui.set_height(36.0);
ui.label(RichText::new(s.label).size(16.0).color(t.text_normal));
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
ui.spacing_mut().item_spacing.x = 4.0;
for (i, combo) in s.combos.iter().rev().enumerate() {
if i > 0 {
ui.add_space(8.0);
}
for &k in combo.iter().rev() {
keycap(ui, t, key_text(k, MAC));
}
}
});
});
}
}
}
fn language_tab(&mut self, ui: &mut Ui, t: &Theme) {
section(ui, t, 0, "Select a Language");
note(ui, t, "Choose the language Discord uses for your account, in its official apps and emails.");
if self.settings_ready(ui, t) {
let current = self.setting_value("locale").and_then(|v| v.as_str().map(str::to_string)).unwrap_or_else(|| "en-US".into());
let label = LOCALES.iter().find(|(k, _)| *k == current).map(|(_, l)| *l).unwrap_or(current.as_str()).to_string();
let mut pick = None;
ui.scope(|ui| {
ui.spacing_mut().button_padding = vec2(12.0, 10.0);
ComboBox::from_id_salt("settings_locale").width(ui.available_width()).selected_text(RichText::new(label).size(16.0)).show_ui(ui, |ui| {
for (k, l) in LOCALES {
if ui.selectable_label(*k == current, *l).clicked() {
pick = Some(k.to_string());
}
}
});
});
if let Some(k) = pick.filter(|k| *k != current) {
self.set_discord_setting("locale", json!(k));
}
}
ui.add_space(24.0);
subheading(ui, t, "Time format");
for (on, title) in [(false, "12-hour"), (true, "24-hour")] {
if radio_row(ui, t, title, "", self.prefs.hour24 == on) && self.prefs.hour24 != on {
self.prefs.hour24 = on;
self.save_prefs();
}
}
}
// ---- Games & Apps ---------------------------------------------------------
fn activity_tab(&mut self, ui: &mut Ui, t: &Theme) {
let ready = self.settings_ready(ui, t);
section(ui, t, 0, "What Activity I Share");
if ready {
self.discord_toggle(ui, t, "show_current_game", "Share my activity", "Share activity information from games and connected apps I use, including when and how I engage.", false, true);
}
if !self.rpc_activities.is_empty() {
let names: Vec<String> = self.rpc_activities.values().map(|(id, a)| a["details"].as_str().or(a["state"].as_str()).map_or_else(|| format!("application {id}"), String::from)).collect();
note(ui, t, &format!("Rich Presence now: {}", names.join(", ")));
}
self.sync_rpc_presence();
self.proto_toggle(ui, t, &[7, 25], "Share when I come online", "Allow friends to receive a push notification when you come online.", false, true, true);
self.proto_toggle(ui, t, &[7, 26], "Share when I start streaming", "Allow members that you interact with the most to get a notification when you start streaming in small servers.", false, true, true);
section(ui, t, 1, "Where I Share Activity");
if self.proto_ready() {
subheading(ui, t, "Automatically share my activity when joining a server");
note(ui, t, "Your activity is always shared with your friends.");
// The newer field (1 share, 2 small servers only, 3 none), else the older one (0, 1, 2).
let mode = self.account_proto.uint(&[8, 29]).filter(|v| *v != 0).or_else(|| self.account_proto.uint(&[8, 14]).map(|v| v + 1)).unwrap_or(2);
for (n, title) in [(1u64, "All servers"), (2, "Only servers with 200 or fewer members"), (3, "No servers")] {
if radio_row(ui, t, title, "", mode == n) && mode != n {
self.set_proto(&[8, 29], Leaf::Enum(n));
}
}
ui.add_space(12.0);
} else {
web(ui, t, "Automatically share my activity when joining a server", "Your activity is always shared with your friends. Share in all servers, in servers with 200 or fewer members, or in none.");
}
note(ui, t, "Looking for per-server controls? Open the server's menu and choose Privacy Settings.");
if related(ui, t, "privacy", "Data & Privacy", "Control who can see your profile info – like your bio and connected accounts.") {
self.go_settings(SettingsTab::DataPrivacy);
ui.data_mut(|d| d.insert_temp(jump_id(), 1usize));
}
section(ui, t, 2, "Activity Joining");
note(ui, t, "Some games allow users to join the game you're playing when viewing your activity.");
if ready {
self.discord_toggle(ui, t, "allow_activity_party_privacy_friends", "Allow friends to join my game", "Allows friends to join without sending a request.", false, true);
self.discord_toggle(ui, t, "allow_activity_party_privacy_voice_channel", "Allow voice channel participants to join my game", "Allow anyone in a shared voice channel to join my game without sending a request. This feature only works in non-Community-enabled servers.", false, true);
}
}
fn connections_tab(&mut self, ui: &mut Ui, t: &Theme) {
// Discord's Connections page: the add grid and your accounts (ui/connections.rs).
self.connections_section(ui, t);
if matches!(self.api_results.get("us:settings"), Some(Ok(_))) {
ui.add_space(8.0);
self.discord_toggle(ui, t, "detect_platform_accounts", "Automatically detect accounts from other platforms on this computer", "", false, true);
}
section(ui, t, 1, "Authorised Apps");
note(ui, t, "These include third-party services you've given permission to access your Discord account. You can review what each app can do and revoke access anytime.");
if !self.demo {
self.api_get_once("us:tokens", "/oauth2/tokens");
}
if let Some(Err(e)) = self.api_take("us:token-delete") {
self.toast(format!("Couldn't deauthorise that app: {e}"), true);
self.api("us:tokens", reqwest::Method::GET, "/oauth2/tokens", None);
}
let apps = match self.api_results.get("us:tokens") {
Some(Ok(Value::Array(a))) => a.clone(),
Some(Err(e)) => {
ui.label(RichText::new(format!("Couldn't load your authorised apps: {e}")).color(t.danger));
Vec::new()
}
_ if self.demo => Vec::new(),
_ => {
ui.spinner();
Vec::new()
}
};
let confirm_id = egui::Id::new("settings_deauth_confirm");
let confirming: Option<String> = ui.data(|d| d.get_temp(confirm_id));
let mut remove: Option<String> = None;
for app in &apps {
let id = app["id"].as_str().unwrap_or("").to_string();
let name = app["application"]["name"].as_str().unwrap_or("Unknown app");
let about = app["application"]["description"].as_str().unwrap_or("");
let scopes: Vec<&str> = app["scopes"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
Frame::none().fill(overlay(0.04)).stroke(Stroke::new(1.0_f32, t.border_subtle)).rounding(8.0).inner_margin(Margin::same(16.0)).show(ui, |ui| {
ui.set_width(ui.available_width());
ui.horizontal(|ui| {
ui.label(RichText::new(name).font(crate::style::medium(16.0)).color(t.header_primary));
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
let sure = confirming.as_deref() == Some(id.as_str());
let b = ui.add(Button::new(RichText::new(if sure { "Click again to confirm" } else { "Deauthorise" }).size(14.0).color(Color32::WHITE)).fill(t.danger).rounding(8.0).min_size(vec2(0.0, 32.0)));
if b.clicked() {
if sure {
remove = Some(id.clone());
} else {
ui.data_mut(|d| d.insert_temp(confirm_id, id.clone()));
}
}
});
});
if !about.is_empty() {
ui.add_space(4.0);
ui.add(egui::Label::new(RichText::new(about).size(14.0).color(t.text_normal)).wrap());
}
if !scopes.is_empty() {
ui.add_space(6.0);
ui.label(RichText::new(format!("{} Permission{} enabled", scopes.len(), if scopes.len() == 1 { "" } else { "s" })).size(12.0).color(t.text_muted));
for s in &scopes {
ui.label(RichText::new(format!("• {}", scope_text(s))).size(14.0).color(t.text_normal));
}
}
});
ui.add_space(8.0);
}
if let Some(id) = remove {
if let Some(Ok(Value::Array(a))) = self.api_results.get_mut("us:tokens") {
a.retain(|x| x["id"].as_str() != Some(id.as_str()));
}
ui.data_mut(|d| d.remove::<String>(confirm_id));
self.api("us:token-delete", reqwest::Method::DELETE, format!("/oauth2/tokens/{id}"), None);
}
if apps.is_empty() && matches!(self.api_results.get("us:tokens"), Some(Ok(_))) {
note(ui, t, "No apps are authorised.");
}
}
fn developer_tab(&mut self, ui: &mut Ui, t: &Theme) {
section(ui, t, 0, "Developer");
if self.settings_ready(ui, t) {
self.discord_toggle(ui, t, "developer_mode", "Developer Mode", "Developer Mode exposes context menu items helpful for people writing apps using the Discord API.", false, false);
}
soon(ui, t, "Application Test Mode", "Enter your Discord application ID to enable test mode for that application.");
}
// ---- RustCord ---------------------------------------------------------------
fn plugins_tab(&mut self, ui: &mut Ui, t: &Theme) {
heading(ui, t, "Rencord Plugins");
ui.label(
RichText::new("RustCord's built-in mod system. Plugins tagged \"Vencord port\" work like the Vencord plugin with the same name.")
.color(t.text_muted),
);
ui.add_space(12.0);
let mut toggles = Vec::new();
let mut changes = Vec::new();
for (i, e) in self.rencord.entries().iter().enumerate() {
Frame::none().fill(t.bg_secondary).rounding(8.0).inner_margin(14.0).show(ui, |ui| {
ui.set_width(ui.available_width());
ui.horizontal(|ui| {
ui.label(bold(e.meta.name).size(16.0).color(t.header_primary));
if e.meta.vencord_equivalent.is_some() {
ui.label(RichText::new(" Vencord port ").size(10.5).strong().color(Color32::WHITE).background_color(t.accent));
}
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
let mut on = e.enabled;
if toggle_switch(ui, &mut on, t).changed() {
toggles.push((i, on));
}
});
});
ui.label(RichText::new(e.meta.description).color(t.text_normal));
if let Some(c) = &e.crashed {
ui.colored_label(t.danger, c);
}
ui.label(RichText::new(format!("by {}", e.meta.authors.join(", "))).size(11.5).color(t.text_muted));
if !e.settings.defs().is_empty() {
CollapsingHeader::new(RichText::new("Settings").color(t.header_secondary)).id_salt(("plugin_settings", i)).show(ui, |ui| {
for def in e.settings.defs() {
if let Some(v) = setting_widget(ui, t, i, def, e.settings.get(def.key)) {
changes.push((i, def.key, v));
}
}
});
}
});
ui.add_space(8.0);
}
for (i, on) in toggles {
self.rencord.set_enabled(i, on);
}
for (i, key, value) in changes {
self.rencord.set_setting(i, key, value);
}
}
fn themes_tab(&mut self, ui: &mut Ui, t: &Theme) {
heading(ui, t, "Themes");
ui.label(
RichText::new(
"Load a Vencord / BetterDiscord theme from a URL or a local .css file. RustCord applies the theme's \
colour variables (--background-primary, --text-normal, --brand-experiment, …).",
)
.color(t.text_muted),
);
ui.add_space(10.0);
let (mut load, mut reset) = (false, false);
ui.horizontal(|ui| {
let w = (ui.available_width() - 140.0).max(120.0);
let r = ui.add(TextEdit::singleline(&mut self.theme_input).hint_text("https://…/theme.css or C:\\path\\to\\theme.css").desired_width(w));
load |= r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
load |= ui.add(Button::new(RichText::new("Load").color(Color32::WHITE)).fill(t.accent)).on_hover_cursor(egui::CursorIcon::PointingHand).clicked();
reset = ui.button("Reset").on_hover_cursor(egui::CursorIcon::PointingHand).clicked();
});
if load {
let src = self.theme_input.clone();
self.load_theme_source(src);
}
if reset {
self.clear_theme();
}
if !self.theme_status.is_empty() {
ui.label(RichText::new(&self.theme_status).size(12.0).color(t.text_muted));
}
if let Some(report) = &self.theme_report {
ui.add_space(10.0);
ui.label(
RichText::new(format!(
"Translated {} of {} color slots ({} CSS variables found).",
report.mapped.len(),
rencord::theme::SLOTS.len(),
report.variables_found
))
.color(t.header_secondary),
);
Grid::new("theme_mapping").striped(true).spacing(vec2(12.0, 4.0)).show(ui, |ui| {
for m in &report.mapped {
swatch(ui, m.color);
ui.label(m.label);
ui.label(RichText::new(&m.variable).monospace().color(t.text_muted));
ui.end_row();
}
});
if !report.warnings.is_empty() {
CollapsingHeader::new(format!("{} variables couldn't be translated", report.warnings.len())).id_salt("theme_warnings").show(ui, |ui| {
for w in &report.warnings {
ui.label(RichText::new(w).size(12.0).color(t.text_muted));
}
});
}
}
divider(ui, t);
subheading(ui, t, "QuickCSS");
ui.label(RichText::new("Variables set here override the theme, e.g. :root { --brand-experiment: #e8590c; }").color(t.text_muted));
ui.add(TextEdit::multiline(&mut self.quick_css_input).code_editor().desired_rows(8).desired_width(f32::INFINITY));
if ui.button("Apply QuickCSS").on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
self.save_quick_css();
}
}
}
impl RustCord {
/// Voice & Video → Camera: which camera, a test picture, and whether to
/// preview before turning it on.
fn camera_settings(&mut self, ui: &mut Ui, t: &Theme) {
let ctx = ui.ctx().clone();
let devices = self.camera_devices(&ctx);
let listing = self.camera_listing();
let chosen = self.voice_ui.prefs.camera_device.clone();
let current = chosen.as_ref().and_then(|id| devices.iter().position(|d| &d.id == id)).unwrap_or(0);
let mut names: Vec<String> = devices.iter().map(|d| d.name.clone()).collect();
if names.is_empty() {
names.push(if listing { "Looking for cameras…".to_string() } else { "No camera found".to_string() });
}
let options: Vec<&str> = names.iter().map(String::as_str).collect();
if let Some(i) = choice_row(ui, t, "camera_device", "Camera", "The camera RustCord turns on in a call (the camera button in the call's controls).", &options, current) {
if let Some(d) = devices.get(i) {
self.voice_ui.prefs.camera_device = Some(d.id.clone());
self.voice_ui.prefs.camera_device_name = Some(d.name.clone());
self.voice_ui.changed();
// The test follows the choice.
if self.camera.testing() {
self.stop_camera_test();
self.start_camera_test();
}
}
}
// The test picture (your camera in the call, while that is on).
let w = ui.available_width().min(480.0);
let (rect, _) = ui.allocate_exact_size(vec2(w, w * 9.0 / 16.0), Sense::hover());
ui.painter().rect_filled(rect, 8.0, Color32::BLACK);
let in_call = self.camera.on.is_some();
let picture = if in_call { self.camera_texture(&ctx) } else { self.camera_test_texture(&ctx) };
match picture {
Some(tex) => {
let size = tex.size_vec2();
let fit = (rect.width() / size.x).min(rect.height() / size.y);
egui::Image::new((tex.id(), size * fit)).rounding(8.0).paint_at(ui, Rect::from_center_size(rect.center(), size * fit));
}
None => {
let text = match &self.camera.test_error {
Some(e) => e.clone(),
None if self.camera.testing() => "Starting your camera…".to_string(),
None => "Test your camera to see how you look.".to_string(),
};
ui.painter().text(rect.center(), Align2::CENTER_CENTER, text, FontId::proportional(14.0), t.text_muted);
if self.camera.testing() {
ui.ctx().request_repaint_after(std::time::Duration::from_millis(100));
}
}
}
ui.add_space(12.0);
ui.horizontal(|ui| {
if in_call {
ui.label(RichText::new("Your camera is on in the call.").size(14.0).color(t.text_muted));
} else if self.camera.testing() {
if secondary_button(ui, t, "Stop Testing").clicked() {
self.stop_camera_test();
}
} else if primary_button(ui, t, "Test Video").clicked() {
self.start_camera_test();
}
ui.add_space(8.0);
if secondary_button(ui, t, "Refresh Cameras").clicked() {
self.refresh_camera_devices(&ctx);
}
});
ui.add_space(20.0);
if let Some(v) = toggle_row(ui, t, "Always preview video", "Pops up a preview of your camera every time you turn on video, before anyone else sees it.", self.voice_ui.prefs.always_preview_video) {
self.voice_ui.prefs.always_preview_video = v;
self.voice_ui.changed();
}
note(ui, t, "Your camera is sent end-to-end encrypted, like your voice.");
}
/// The Push-to-Talk shortcut: its key, and a button that records the
/// next key (or extra mouse button) you press, wherever the pointer is.
fn ptt_shortcut_row(&mut self, ui: &mut Ui, t: &Theme) {
let rec_id = egui::Id::new("settings_ptt_recording");
let recording = ui.data(|d| d.get_temp::<bool>(rec_id).unwrap_or(false));
let key = self.voice_ui.prefs.ptt_key;
ui.horizontal(|ui| {
ui.set_height(40.0);
ui.label(RichText::new("Shortcut").font(crate::style::medium(16.0)).color(t.header_primary));
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
let b = if recording { primary_button(ui, t, "Press a key…") } else { secondary_button(ui, t, if key == 0 { "Record Keybind" } else { "Edit Keybind" }) };
if b.clicked() {
ui.data_mut(|d| d.insert_temp(rec_id, !recording));
}
ui.add_space(8.0);
if key != 0 {
keycap(ui, t, &crate::hotkey::name(key).to_uppercase());
} else {
ui.label(RichText::new("No keybind set").size(14.0).color(t.text_muted));
}
});
});
if recording {
ui.ctx().request_repaint_after(std::time::Duration::from_millis(30));
if ui.input(|i| i.key_pressed(Key::Escape)) {
ui.data_mut(|d| d.insert_temp(rec_id, false));
} else if let Some(vk) = crate::hotkey::any_pressed().filter(|vk| *vk != 0x1b) {
self.voice_ui.prefs.ptt_key = vk;
self.voice_ui.changed();
ui.data_mut(|d| d.insert_temp(rec_id, false));
}
}
if self.voice_ui.prefs.push_to_talk && self.voice_ui.prefs.ptt_key == 0 {
note(ui, t, "Until a shortcut is set, RustCord keeps sending while you speak.");
}
ui.add_space(8.0);
}
/// Voice & Video, like Discord's but only what matters: microphone and
/// speaker (System Default follows Windows), their volumes, a mic test and
/// the input profile. Everything applies to a call in progress at once.
fn voice_tab(&mut self, ui: &mut Ui, t: &Theme) {
section(ui, t, 0, "Voice");
self.voice_ui.want_devices(ui.ctx());
let gap = 24.0;
let col = ((ui.available_width() - gap) / 2.0).max(180.0);
let mut picked: Option<(bool, Option<String>, Option<String>)> = None;
let mut save = false;
ui.horizontal_top(|ui| {
ui.spacing_mut().item_spacing.x = gap;
for input in [true, false] {
ui.vertical(|ui| {
ui.set_width(col);
field_label(ui, t, if input { "Microphone" } else { "Speaker" });
let label = self.voice_ui.device_label(input);
let choices = self.voice_ui.device_choices(input);
ui.scope(|ui| {
let w = &mut ui.visuals_mut().widgets;
for s in [&mut w.inactive, &mut w.hovered, &mut w.active, &mut w.open] {
s.rounding = egui::Rounding::same(8.0);
}
w.inactive.bg_stroke = Stroke::new(1.0_f32, t.border_subtle);
ui.spacing_mut().button_padding = vec2(12.0, 9.0);
ComboBox::from_id_salt(("voice_device", input)).width(col).truncate().selected_text(RichText::new(label).size(14.0).color(t.text_normal)).show_ui(ui, |ui| {
ui.set_min_width(col);
for c in choices {
if ui.selectable_label(c.selected, c.label).clicked() && !c.selected {
picked = Some((input, c.id, c.name));
}
}
if self.voice_ui.devices.is_none() {
ui.label(RichText::new("Looking for devices…").size(13.0).color(t.text_muted));
}
});
});
ui.add_space(18.0);
field_label(ui, t, if input { "Microphone Volume" } else { "Speaker Volume" });
let prefs = &mut self.voice_ui.prefs;
let (value, max) = if input { (&mut prefs.input_volume, 100.0) } else { (&mut prefs.output_volume, 200.0) };
let r = volume_slider(ui, value, max, col);
if r.changed() {
self.voice_ui.apply();
}
save |= r.drag_stopped() || (r.changed() && !r.dragged());
});
}
});
if let Some((input, id, name)) = picked {
self.voice_ui.choose_device(input, id, name);
}
if save {
self.voice_ui.changed();
}
// Mic test: your voice as others get it (processing and send gate
// applied), played back on the speaker above.
ui.add_space(22.0);
if self.voice_ui.mic_test.as_ref().is_some_and(|m| !m.is_running() && m.error().is_none()) {
self.voice_ui.mic_test = None;
}
let testing = self.voice_ui.mic_test.as_ref().is_some_and(|m| m.is_running());
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 14.0;
let b = ui.add(Button::new(RichText::new(if testing { "Stop Testing" } else { "Mic Test" }).size(14.0).color(Color32::WHITE)).fill(BRAND).rounding(8.0).min_size(vec2(112.0, 36.0)));
if b.clicked() {
self.voice_ui.mic_test = if testing { None } else { Some(voice::MicTest::start()) };
self.voice_ui.meter = -100.0;
}
let level = self.voice_ui.mic_test.as_ref().filter(|m| m.is_running()).map(|m| m.level_db());
// Rise at once, fall back gently (40 dB/s).
let dt = ui.input(|i| i.stable_dt).min(0.1);
let meter = &mut self.voice_ui.meter;
*meter = match level {
Some(l) if l >= *meter => l,
Some(l) => (*meter - 40.0 * dt).max(l),
None => -100.0,
};
mic_meter(ui, if testing { *meter } else { -100.0 }, self.voice_ui.prefs.input_sensitivity, ui.available_width());
if testing {
ui.ctx().request_repaint_after(std::time::Duration::from_millis(33));
}
});
ui.add_space(6.0);
match self.voice_ui.mic_test.as_ref().and_then(|m| m.error()) {
Some(e) => ui.label(RichText::new(e).size(13.0).color(t.danger)),
None => ui.label(RichText::new("Say something: RustCord plays your voice back the way others hear it. The bright part of the meter is what gets sent.").size(13.0).color(t.text_muted)),
};
ui.add_space(18.0);
field_label(ui, t, "Input Sensitivity");
let (track, _) = ui.allocate_exact_size(vec2(ui.available_width().min(420.0), 24.0), Sense::hover());
let mut v = self.voice_ui.prefs.input_sensitivity.clamp(-70.0, 0.0) + 70.0;
let (changed, done) =
super::voice_menu::paint_slider_fmt(ui, t, egui::Id::new("settings_in_sens"), track, &mut v, 70.0, |v| format!("{:.0} dB", v - 70.0));
if changed || done {
self.voice_ui.prefs.input_sensitivity = v - 70.0;
if done {
self.voice_ui.changed();
} else {
self.voice_ui.apply();
}
}
ui.add_space(6.0);
ui.label(
RichText::new(format!(
"Sound quieter than {:.0} dB is not sent and doesn't show you as speaking. Raise it if your microphone picks up your headphones or room noise.",
self.voice_ui.prefs.input_sensitivity
))
.size(13.0)
.color(t.text_muted),
);
ui.add_space(16.0);
subheading(ui, t, "Input Profile");
let iso = self.voice_ui.prefs.voice_isolation;
let custom = self.voice_ui.prefs.custom_profile;
for (on, title, desc) in [
(true, "Voice Isolation", "Just your voice: background noise like fans, keys and traffic is cut out"),
(false, "Studio", "Pure audio: open mic with no processing"),
] {
if radio_row(ui, t, title, desc, !custom && iso == on) && (custom || iso != on) {
self.voice_ui.prefs.custom_profile = false;
self.voice_ui.set_voice_isolation(on);
self.voice_ui.changed();
}
}
if radio_row(ui, t, "Custom", "Advanced mode: set the processing switches below yourself.", custom) && !custom {
self.voice_ui.prefs.custom_profile = true;
self.voice_ui.changed();
}
if custom {
if let Some(v) = toggle_row(ui, t, "Noise Suppression", "Reduces background noise from your microphone.", iso) {
self.voice_ui.set_voice_isolation(v);
}
if let Some(v) = toggle_row(ui, t, "Echo Cancellation", "", self.voice_ui.prefs.echo_cancellation) {
self.voice_ui.prefs.echo_cancellation = v;
self.voice_ui.changed();
}
if let Some(v) = toggle_row(ui, t, "Automatic Gain Control", "Raises a quiet microphone to a steady speaking level.", self.voice_ui.prefs.automatic_gain_control) {
self.voice_ui.prefs.automatic_gain_control = v;
self.voice_ui.changed();
}
}
subheading(ui, t, "Input Mode");
let ptt = self.voice_ui.prefs.push_to_talk;
for (on, title, desc) in [
(false, "Voice Activity", "RustCord sends while you speak, above the Input Sensitivity level."),
(true, "Push to Talk", "Your microphone is sent only while you hold the shortcut, in any app."),
] {
if radio_row(ui, t, title, desc, ptt == on) && ptt != on {
self.voice_ui.prefs.push_to_talk = on;
self.voice_ui.changed();
}
}
if ptt {
ui.add_space(8.0);
self.ptt_shortcut_row(ui, t);
}
ui.add_space(12.0);
section(ui, t, 1, "Camera");
self.camera_settings(ui, t);
section(ui, t, 2, "Streaming");
self.proto_toggle(ui, t, &[5, 10], "Show Stream Previews", "Allows others to see a preview of your stream before they join.", true, false, true);
section(ui, t, 3, "Sounds");
if let Some(on) = toggle_row(ui, t, "Voice chimes", "A short chime when you mute, unmute, deafen, undeafen, join or leave a call, and when someone joins or leaves yours", self.voice_ui.prefs.sounds) {
self.voice_ui.set_sounds(on);
if on {
self.voice_cue(crate::audio::Cue::Join);
}
}
if self.voice_ui.prefs.sounds {
let mut seen: Vec<&str> = Vec::new();
let mut flip: Option<(&'static str, bool)> = None;
for cue in crate::audio::Cue::ALL {
if seen.contains(&cue.name()) {
continue;
}
seen.push(cue.name());
let on = !self.prefs.muted_cues.iter().any(|c| c == cue.name());
ui.horizontal(|ui| {
ui.set_height(36.0);
ui.label(RichText::new(cue.label()).size(16.0).color(t.text_normal));
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
let mut v = on;
if switch(ui, t, &mut v).changed() {
flip = Some((cue.name(), v));
}
let play = ui.add(egui::Label::new(RichText::new("Preview").size(13.0).color(t.text_link)).selectable(false).sense(Sense::click())).on_hover_cursor(egui::CursorIcon::PointingHand);
if play.clicked() && self.prefs.sounds_allowed() && !matches!(cue, crate::audio::Cue::Calling | crate::audio::Cue::Ringing) {
self.audio.cue(cue, self.voice_ui.prefs.output_volume / 100.0);
}
});
});
}
if let Some((name, on)) = flip {
self.prefs.muted_cues.retain(|c| c != name);
if !on {
self.prefs.muted_cues.push(name.to_string());
}
self.save_prefs();
}
ui.add_space(8.0);
}
if related(ui, t, "notifications", "Notifications", "Enable/disable sounds for new messages and incoming calls.") {
self.go_settings(SettingsTab::Notifications);
ui.data_mut(|d| d.insert_temp(jump_id(), 1usize));
}
section(ui, t, 4, "Soundboard");
field_label(ui, t, "Soundboard Volume");
let w = ui.available_width().min(420.0);
let r = volume_slider(ui, &mut self.voice_ui.prefs.soundboard_volume, 100.0, w);
if r.drag_stopped() || (r.changed() && !r.dragged()) {
self.voice_ui.changed();
}
note(ui, t, "Control how loud sounds are for you personally.");
web(ui, t, "Entrance Sounds", "Choose a Soundboard sound to automatically play whenever you join a voice channel.");
section(ui, t, 5, "Advanced");
note(ui, t, "Voice and video calls are end-to-end encrypted (DAVE).");
if let Some(v) = toggle_row(
ui,
t,
"Video Hardware Acceleration",
"Uses your GPU to encode and decode video. Turning it off saves about 80 MB of memory while you watch a stream, but uses more CPU. Applies to the next stream or camera.",
self.voice_ui.prefs.video_hardware_acceleration,
) {
self.voice_ui.prefs.video_hardware_acceleration = v;
self.voice_ui.changed();
}
if let Some(v) = toggle_row(ui, t, "Debug logging", "Write more detail to RustCord's log file, for tracking down a problem.", self.prefs.debug_logging) {
self.prefs.debug_logging = v;
self.save_prefs();
}
if button_row(ui, t, "Log files", "This run's log, and the one before it.", "Open Folder", ButtonKind::Secondary) {
if let Some(dir) = crate::diagnostics::log_path().and_then(|p| p.parent()) {
#[cfg(windows)]
let _ = std::process::Command::new("explorer").arg(dir).spawn();
#[cfg(target_os = "linux")]
crate::linux::open_folder(dir);
#[cfg(target_os = "macos")]
let _ = std::process::Command::new("open").arg(dir).spawn();
}
}
let confirm_id = egui::Id::new("settings_voice_reset");
let sure = ui.data(|d| d.get_temp::<bool>(confirm_id).unwrap_or(false));
if button_row(ui, t, "Reset all Voice & Video settings", "Return to the default set of Voice & Video settings: devices, volumes, input sensitivity, input profile, input mode and sounds.", if sure { "Click again to confirm" } else { "Reset Voice Settings" }, ButtonKind::Critical) {
if sure {
let old = std::mem::take(&mut self.voice_ui.prefs);
let p = &mut self.voice_ui.prefs;
p.user_volumes = old.user_volumes;
p.stream_volumes = old.stream_volumes;
p.local_mutes = old.local_mutes;
p.sound_uses = old.sound_uses;
self.voice_ui.changed();
self.prefs.muted_cues.clear();
self.save_prefs();
self.toast("Voice & Video settings were reset.", false);
}
ui.data_mut(|d| d.insert_temp(confirm_id, !sure));
}
}
}
/// Small bold caption over a field (Discord: "Microphone", "Speaker Volume").
fn field_label(ui: &mut Ui, t: &Theme, text: &str) {
ui.label(RichText::new(text).font(strong(14.0)).color(t.header_primary));
ui.add_space(6.0);
}
/// Discord's volume slider: a thin track filled in blurple up to a white
/// knob, the percentage above the knob while you drag. Snaps to 100%.
fn volume_slider(ui: &mut Ui, value: &mut f32, max: f32, width: f32) -> egui::Response {
let (rect, mut resp) = ui.allocate_exact_size(vec2(width, 28.0), Sense::click_and_drag());
let track = Rect::from_min_max(pos2(rect.left() + 5.0, rect.center().y - 4.0), pos2(rect.right() - 5.0, rect.center().y + 4.0));
if let Some(p) = resp.interact_pointer_pos().filter(|_| resp.dragged() || resp.clicked()) {
let mut v = ((p.x - track.left()) / track.width()).clamp(0.0, 1.0) * max;
if (v - 100.0).abs() < max * 0.025 {
v = 100.0;
}
let v = v.round();
if (v - *value).abs() >= 0.5 {
*value = v;
resp.mark_changed();
}
}
let frac = (*value / max).clamp(0.0, 1.0);
let x = track.left() + frac * track.width();
let p = ui.painter();
p.rect_filled(track, 4.0, overlay(0.24));
p.rect_filled(Rect::from_min_max(track.min, pos2(x, track.bottom())), 4.0, BRAND);
let knob = Rect::from_center_size(pos2(x, rect.center().y), vec2(10.0, 24.0));
p.rect_filled(knob.translate(vec2(0.0, 1.0)), 3.0, Color32::from_black_alpha(60));
p.rect_filled(knob, 3.0, Color32::WHITE);
if resp.hovered() || resp.dragged() {
ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
}
if resp.dragged() {
let text = format!("{:.0}%", *value);
let g = p.layout_no_wrap(text, FontId::proportional(12.0), Color32::WHITE);
let bubble = Rect::from_center_size(pos2(x, rect.top() - 14.0), g.size() + vec2(12.0, 6.0));
let layer = ui.ctx().layer_painter(egui::LayerId::new(Order::Tooltip, egui::Id::new("voice_volume_bubble")));
layer.rect_filled(bubble, 4.0, Color32::from_rgb(0x11, 0x12, 0x14));
layer.galley(bubble.center() - g.size() / 2.0, g, Color32::WHITE);
}
if resp.dragged() {
resp
} else {
resp.on_hover_text(format!("{:.0}%", *value))
}
}
/// The mic test meter: thin ticks lit up to the level, dim below the level
/// at which RustCord starts sending, bright above it.
fn mic_meter(ui: &mut Ui, level_db: f32, threshold_db: f32, width: f32) {
let (rect, _) = ui.allocate_exact_size(vec2(width.max(60.0), 32.0), Sense::hover());
let norm = |db: f32| ((db + 70.0) / 60.0).clamp(0.0, 1.0);
let (level, gate) = (norm(level_db), norm(threshold_db));
let n = ((rect.width() + 3.0) / 6.0).floor().max(1.0) as usize;
let green = crate::voice_call::VOICE_GREEN;
for i in 0..n {
let f = (i as f32 + 0.5) / n as f32;
let color = if f > level {
overlay(0.2)
} else if f < gate {
green.gamma_multiply(0.45)
} else {
green
};
let tick = Rect::from_min_size(pos2(rect.left() + i as f32 * 6.0, rect.top() + 4.0), vec2(3.0, 24.0));
ui.painter().rect_filled(tick, 1.5, color);
}
}
impl RustCord {
fn about_tab(&mut self, ui: &mut Ui, t: &Theme) {
ui.horizontal(|ui| {
ui.add(egui::Image::new(super::badges::rustcord_icon()).fit_to_exact_size(vec2(64.0, 64.0)));
ui.add_space(12.0);
ui.vertical(|ui| {
ui.add_space(10.0);
ui.label(RichText::new("RustCord").font(strong(24.0)).color(t.header_primary));
ui.label(RichText::new(concat!("Version ", env!("CARGO_PKG_VERSION"))).size(14.0).color(t.text_muted));
});
});
ui.add_space(16.0);
ui.label("A native Discord client written in Rust with egui. No Electron, no web runtime.");
ui.add_space(8.0);
ui.label(
"Rencord is RustCord's mod system, inspired by Vencord. Turn its plugins on and off under Rencord Plugins.",
);
ui.add_space(12.0);
ui.label(
RichText::new("Unofficial and not endorsed by Discord. Third-party clients are against Discord's Terms of Service; use at your own risk.").color(t.text_muted),
);
divider(ui, t);
subheading(ui, t, "Updates");
let Some(updater) = &mut self.updater else {
note(ui, t, "This copy of RustCord wasn't installed with RustCordSetup, so it doesn't update itself. New versions are on GitHub.");
if secondary_button(ui, t, "Open Releases").clicked() {
ui.ctx().open_url(egui::OpenUrl::new_tab(crate::updater::RELEASES_PAGE));
}
return;
};
let desc = "New versions are downloaded in the background and installed for the next time RustCord starts. RustCord looks for them on GitHub a minute after it starts and every 6 hours.";
if let Some(on) = toggle_row(ui, t, "Update automatically", desc, updater.enabled()) {
updater.set_enabled(on);
}
let status = updater.status();
let ready = matches!(status, crate::updater::Status::Ready(_));
let (title, desc) = update_status(&status, updater.enabled());
if button_row(ui, t, &title, &desc, if ready { "Restart" } else { "Check for Updates" }, ButtonKind::Secondary) && !status.busy() {
if ready {
self.install_update(ui.ctx());
} else {
updater.check_now();
}
}
}
}
/// Settings → About's line about updates: (title, description).
fn update_status(status: &crate::updater::Status, automatic: bool) -> (String, String) {
use crate::updater::Status;
let mb = |bytes: u64| bytes as f64 / (1024.0 * 1024.0);
match status {
Status::Idle if automatic => (concat!("RustCord ", env!("CARGO_PKG_VERSION")).into(), "Not checked for a newer version yet.".into()),
Status::Idle => (concat!("RustCord ", env!("CARGO_PKG_VERSION")).into(), "Automatic updates are off.".into()),
Status::Checking => ("Checking for updates\u{2026}".into(), String::new()),
Status::UpToDate(at) => {
let clock = if super::hour24() { at.format("%H:%M") } else { at.format("%-I:%M %p") };
("RustCord is up to date".into(), format!("Checked at {clock}."))
}
Status::Downloading { version, done, total } => (format!("Downloading RustCord {version}\u{2026}"), format!("{:.1} of {:.1} MB", mb(*done), mb(*total))),
Status::Installing(version) => (format!("Installing RustCord {version}\u{2026}"), String::new()),
Status::Ready(version) => (format!("RustCord {version} is ready"), "It's installed and starts the next time RustCord does. Restart to use it now.".into()),
Status::Failed(e) => ("Couldn't update".into(), format!("{e}.")),
}
}
/// What an OAuth2 scope lets an app do, in Discord's words.
fn scope_text(scope: &str) -> String {
match scope {
"identify" => "Access your username, avatar and banner",
"email" => "Access your email address",
"guilds" => "Know what servers you're in",
"guilds.join" => "Join servers for you",
"guilds.members.read" => "Read your member info (nickname, avatar, roles etc.) for servers you belong to",
"connections" => "Access your third-party connections",
"applications.commands" => "Create commands",
"applications.commands.permissions.update" => "Manage access to its commands in a server",
"bot" => "Add a bot to a server",
"rpc" => "Interface with your Discord client",
"messages.read" => "Read all messages",
"gdm.join" => "Join group DMs for you",
"role_connections.write" => "Update your connection and metadata for the app",
"voice" => "Connect to voice for you",
"activities.read" => "See your activity",
"activities.write" => "Update your current activity",
"relationships.read" => "Access your friends list",
"dm_channels.read" => "See information about your DMs and group DMs",
other => return format!("Scope: {other}"),
}
.to_string()
}
/// "19 December 2026" from an ISO-8601 time (empty if it isn't one).
fn long_date(iso: &str) -> String {
chrono::DateTime::parse_from_rfc3339(iso).map(|d| d.with_timezone(&chrono::Local).format("%-d %B %Y").to_string()).unwrap_or_default()
}
/// An amount in a currency's smallest unit, as Discord's receipts show it.
fn money(minor: i64, currency: &str) -> String {
let code = currency.to_ascii_uppercase();
// (Discord's own currency: whole Orbs.)
if code == "DISCORD_ORB" {
return format!("{minor} Orbs");
}
// (Currencies without cents.)
if matches!(code.as_str(), "JPY" | "KRW" | "VND" | "CLP" | "HUF") {
return format!("{minor} {code}");
}
let value = format!("{}.{:02}", minor / 100, (minor % 100).abs());
match code.as_str() {
"USD" => format!("${value}"),
"EUR" => format!("€{value}"),
"GBP" => format!("£{value}"),
_ => format!("{value} {code}"),
}
}
/// Discord's subscription plans by id (its own, long-lived ids).
fn plan_name(plan: &str) -> &'static str {
match plan {
"511651880837840896" => "Nitro Monthly",
"511651885459963904" => "Nitro Yearly",
"511651871736201216" => "Nitro Classic Monthly",
"511651876987469824" => "Nitro Classic Yearly",
"978380692553465866" => "Nitro Basic Monthly",
"1024422698568122368" => "Nitro Basic Yearly",
"590665532894740483" => "Server Boost Monthly",
"590665538238152709" => "Server Boost Yearly",
_ => "Subscription",
}
}