Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.
Rust desktop-appdiscorddiscord-clienteguielectron-alternativelightweightlinuxmacosnative-apprustwindows
//! Home → Nitro Home, Shop and Quests, drawn natively from Discord's own
//! endpoints (see `discord::commerce`). Buying and claiming still happen on
//! discord.com (payments and captchas), everything else is in-app.
use super::paint_avatar;
use crate::app::RustCord;
use crate::backend::Command;
use crate::features::StorePage;
use crate::style::{icon, icon_font, overlay, Theme};
use discord::commerce::{Quest, ShopProduct, Subscription};
use eframe::egui::{
self, pos2, vec2, Align2, CentralPanel, Color32, FontId, Frame, Margin, Rect, Response, RichText, ScrollArea, Sense, Stroke,
TopBottomPanel, Ui,
};
const BRAND: Color32 = Color32::from_rgb(0x58, 0x65, 0xf2);
const BRAND_HOVER: Color32 = Color32::from_rgb(0x47, 0x52, 0xc4);
const BRAND_TEXT: Color32 = Color32::from_rgb(0x94, 0x9c, 0xf7);
const NITRO_PINK: Color32 = Color32::from_rgb(0xff, 0x73, 0xfa);
fn strong(size: f32) -> FontId {
FontId::new(size, egui::FontFamily::Name(crate::style::BOLD.into()))
}
fn parse_time(s: &str) -> Option<chrono::DateTime<chrono::Local>> {
chrono::DateTime::parse_from_rfc3339(s).ok().map(|d| d.with_timezone(&chrono::Local))
}
/// A rounded rect filled with a left → right gradient.
fn hgradient_rrect(painter: &egui::Painter, rect: Rect, r: f32, left: Color32, right: Color32) {
let mut outline = Vec::new();
egui::epaint::tessellator::path::rounded_rectangle(&mut outline, rect, egui::Rounding::same(r));
let color = |x: f32| left.lerp_to_gamma(right, ((x - rect.left()) / rect.width().max(1.0)).clamp(0.0, 1.0));
let mut mesh = egui::Mesh::default();
mesh.colored_vertex(rect.center(), color(rect.center().x));
for p in &outline {
mesh.colored_vertex(*p, color(p.x));
}
let n = outline.len() as u32;
for i in 0..n {
mesh.add_triangle(0, 1 + i, 1 + (i + 1) % n);
}
painter.add(egui::Shape::mesh(mesh));
}
/// A flat rounded button painted at `rect`.
fn button_at(ui: &mut Ui, rect: Rect, id: egui::Id, label: &str, fill: Color32, hover: Color32, fg: Color32) -> Response {
let resp = ui.interact(rect, id, Sense::click());
ui.painter().rect_filled(rect, 8.0, if resp.hovered() { hover } else { fill });
ui.painter().text(rect.center(), Align2::CENTER_CENTER, label, strong(14.0), fg);
resp.on_hover_cursor(egui::CursorIcon::PointingHand)
}
/// Discord's Orb: a little faceted gem.
fn paint_orb(ui: &Ui, center: egui::Pos2, r: f32) {
let p = ui.painter();
p.circle_filled(center, r, Color32::from_rgb(0x8f, 0x96, 0xff));
p.circle_filled(center - vec2(r * 0.15, r * 0.15), r * 0.72, Color32::from_rgb(0xb7, 0xbc, 0xff));
let s = r * 0.42;
let star = vec![center + vec2(0.0, -s), center + vec2(s * 0.3, -s * 0.3), center + vec2(s, 0.0), center + vec2(s * 0.3, s * 0.3), center + vec2(0.0, s), center + vec2(-s * 0.3, s * 0.3), center + vec2(-s, 0.0), center + vec2(-s * 0.3, -s * 0.3)];
p.add(egui::Shape::convex_polygon(star, Color32::WHITE, Stroke::NONE));
}
/// The 48px page header: icon, title, bottom border. `right` draws on the right.
fn page_header(ui: &mut Ui, t: &Theme, id: &str, glyph: &str, title: &str, add: impl FnOnce(&mut Ui)) {
TopBottomPanel::top(egui::Id::new(id))
.exact_height(48.0)
.frame(Frame::none().fill(t.bg_primary).inner_margin(Margin::symmetric(16.0, 0.0)))
.show_inside(ui, |ui| {
let full = ui.max_rect().expand2(vec2(16.0, 0.0));
ui.painter().hline(full.x_range(), full.bottom() - 0.5, Stroke::new(1.0_f32, t.border_subtle));
ui.horizontal_centered(|ui| {
ui.spacing_mut().item_spacing.x = 8.0;
ui.label(RichText::new(glyph).font(icon_font(20.0)).color(t.text_muted));
ui.label(RichText::new(title).font(strong(16.0)).color(t.header_primary));
add(ui);
});
});
}
/// "◎ 320" chip (right-aligned in a header).
fn orbs_chip(ui: &mut Ui, t: &Theme, orbs: Option<u64>) {
let Some(n) = orbs else { return };
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let g = ui.painter().layout_no_wrap(n.to_string(), strong(14.0), t.header_primary);
let (r, resp) = ui.allocate_exact_size(vec2(g.size().x + 42.0, 30.0), Sense::hover());
ui.painter().rect(r, 8.0, overlay(0.08), Stroke::new(1.0_f32, overlay(0.2)));
paint_orb(ui, pos2(r.left() + 17.0, r.center().y), 8.0);
ui.painter().galley(pos2(r.left() + 31.0, r.center().y - g.size().y / 2.0), g, t.header_primary);
resp.on_hover_text("Your Orbs");
});
}
fn loading_or_error<T>(ui: &mut Ui, t: &Theme, state: &Option<Result<T, String>>, what: &str) -> bool {
match state {
None => {
ui.add_space(80.0);
ui.vertical_centered(|ui| {
ui.spinner();
ui.add_space(8.0);
ui.label(RichText::new(format!("Loading {what}…")).size(14.0).color(t.text_muted));
});
true
}
Some(Err(e)) => {
ui.add_space(80.0);
ui.vertical_centered(|ui| {
ui.label(RichText::new(format!("Couldn't load {what}.")).font(strong(16.0)).color(t.header_primary));
ui.add_space(4.0);
ui.label(RichText::new(e).size(13.0).color(t.text_muted));
});
true
}
Some(Ok(_)) => false,
}
}
enum StoreAction {
Open(String),
Enroll(discord::Id, Option<String>),
Page(StorePage),
ClaimedTab(bool),
Retry(StorePage),
/// Play a video quest in RustCord.
Watch(discord::Id),
}
impl RustCord {
fn apply_store_action(&mut self, action: Option<StoreAction>) {
match action {
Some(StoreAction::Open(url)) => self.ctx.open_url(egui::OpenUrl::new_tab(url)),
Some(StoreAction::Enroll(quest, sealed)) => self.backend.send(Command::EnrollQuest { quest, sealed }),
Some(StoreAction::Watch(id)) => self.watch_quest(id),
Some(StoreAction::Page(p)) => self.open_store_page(p),
Some(StoreAction::ClaimedTab(on)) => self.quests_claimed_tab = on,
Some(StoreAction::Retry(p)) => {
match p {
StorePage::Shop => self.shop = None,
StorePage::Nitro => self.nitro = None,
StorePage::Quests => self.quests = None,
}
self.open_store_page(p);
}
None => {}
}
}
/// Start a video quest: accept it if needed, then play it here.
fn watch_quest(&mut self, id: discord::Id) {
let Some(Ok(list)) = &self.quests else { return };
let Some(q) = list.quests.iter().find(|q| q.id == id) else { return };
let Some((task, url)) = q.video() else { return };
let size = task.assets.as_ref().and_then(|a| a.video_low_res.as_ref().or(a.video.as_ref())).map(|v| (v.width, v.height)).unwrap_or((1280, 720));
let (target, done, enrolled, sealed) = (task.target as f64, q.progress_seconds(), q.enrolled(), q.traffic_metadata_sealed.clone());
let title = q.config.messages.quest_name.clone();
if !enrolled {
self.backend.send(Command::EnrollQuest { quest: id, sealed });
}
// Resume where you left off (Discord counts from there).
let start = if done + 2.0 < target { done } else { 0.0 };
self.quest_video = Some(crate::quest_video::QuestVideo::start(&self.ctx, id, title, url, target, start, size));
}
/// The video quest player: the clip, how much is watched, and the
/// progress reports to Discord.
pub fn quest_video_ui(&mut self, ctx: &egui::Context) {
// Dev aid: RUSTCORD_DEV_VIEW=quest-video plays the first video quest
// without reporting anything to Discord.
static DEV_STARTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
if self.quest_video.is_none() && crate::diagnostics::dev_var("RUSTCORD_DEV_VIEW").as_deref() == Ok("quest-video") {
if let Some(Ok(list)) = &self.quests {
let pick = list.quests.iter().find_map(|q| q.video().map(|(task, url)| (q.id, q.config.messages.quest_name.clone(), url, task.target as f64)));
if let Some((id, title, url, target)) = pick.filter(|_| !DEV_STARTED.swap(true, std::sync::atomic::Ordering::Relaxed)) {
let mut v = crate::quest_video::QuestVideo::start(ctx, id, title, url, target, 0.0, (1280, 720));
v.report = false;
self.quest_video = Some(v);
}
}
}
let Some(v) = self.quest_video.as_mut() else { return };
let t = self.theme.clone();
let (position, loading, finished, error) = {
let mut s = v.shared.lock().expect("quest video");
if let Some(frame) = s.frame.take() {
match &mut v.texture {
Some(tex) => tex.set(frame, egui::TextureOptions::LINEAR),
None => v.texture = Some(ctx.load_texture("quest-video", frame, egui::TextureOptions::LINEAR)),
}
}
(s.position, s.loading, s.finished, s.error.clone())
};
// Report the watched time every few seconds, and the end.
let (quest, target) = (v.quest, v.target);
let mut report = None;
if v.report && !v.completed && (position - v.reported >= 5.0 || (position >= target && v.reported < target)) {
let at = position.min(target);
v.reported = at;
report = Some(at);
if at >= target {
v.completed = true;
}
}
let completed = v.completed;
let plain = v.plain;
let title = v.title.clone();
let (vw, vh) = v.size;
let texture = v.texture.as_ref().map(|tx| (tx.id(), tx.size_vec2()));
let mut close = ctx.input(|i| i.key_pressed(egui::Key::Escape));
let screen = ctx.screen_rect();
egui::Area::new(egui::Id::new("quest_video_bg")).order(egui::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(200));
});
let w = (screen.width() - 120.0).min(960.0);
let h = w * vh.max(1) as f32 / vw.max(1) as f32;
let h = h.min(screen.height() - 200.0);
let w = w.min(h * vw.max(1) as f32 / vh.max(1) as f32);
let area = egui::Area::new(egui::Id::new("quest_video")).order(egui::Order::Foreground).anchor(Align2::CENTER_CENTER, vec2(0.0, 0.0)).show(ctx, |ui| {
ui.ctx().move_to_top(ui.layer_id());
Frame::none().fill(t.bg_secondary).rounding(12.0).stroke(Stroke::new(1.0_f32, t.border_subtle)).inner_margin(Margin::same(16.0)).show(ui, |ui| {
ui.set_width(w);
ui.horizontal(|ui| {
let heading = if plain { title.to_uppercase() } else { format!("{} QUEST", title.to_uppercase()) };
ui.label(RichText::new(heading).font(strong(13.0)).color(BRAND_TEXT));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.add(egui::Button::new(RichText::new(icon::CLOSE).font(icon_font(12.0)).color(t.header_primary)).fill(overlay(0.12)).rounding(8.0)).on_hover_text(if plain { "Close" } else { "Close (progress so far is kept)" }).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
close = true;
}
});
});
ui.add_space(10.0);
let (rect, _) = ui.allocate_exact_size(vec2(w, h), Sense::hover());
ui.painter().rect_filled(rect, 8.0, Color32::BLACK);
match (texture, &error) {
(_, Some(e)) => {
ui.painter().text(rect.center(), Align2::CENTER_CENTER, e, FontId::proportional(15.0), t.text_muted);
}
(Some((id, size)), None) => {
let scale = (rect.width() / size.x).min(rect.height() / size.y);
let img = Rect::from_center_size(rect.center(), size * scale);
ui.painter().image(id, img, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
}
(None, None) => {
ui.put(Rect::from_center_size(rect.center(), vec2(32.0, 32.0)), egui::Spinner::new().size(32.0));
if loading {
ui.painter().text(rect.center() + vec2(0.0, 36.0), Align2::CENTER_CENTER, "Loading the video…", FontId::proportional(14.0), t.text_muted);
}
}
}
ui.add_space(12.0);
// Watched / needed.
let frac = (position / target.max(1.0)).clamp(0.0, 1.0) as f32;
let (bar, _) = ui.allocate_exact_size(vec2(w, 6.0), Sense::hover());
ui.painter().rect_filled(bar, 3.0, overlay(0.2));
ui.painter().rect_filled(Rect::from_min_max(bar.min, pos2(bar.left() + bar.width() * frac, bar.bottom())), 3.0, BRAND);
ui.add_space(8.0);
let mmss = |s: f64| format!("{}:{:02}", s as u64 / 60, s as u64 % 60);
let line = if plain {
format!("{} / {} · Picture only, no sound yet", mmss(position.min(target)), mmss(target))
} else if completed {
"Quest complete! Claim your reward from the Quests page.".to_string()
} else if finished {
"The video ended before the quest's time; play it again to finish.".to_string()
} else {
format!("Watched {} of {} · Picture only, no sound yet", mmss(position.min(target)), mmss(target))
};
ui.label(RichText::new(line).size(14.0).color(if completed { Color32::from_rgb(0x23, 0xa5, 0x5a) } else { t.text_muted }));
});
});
// Clicking off the player closes it (the progress so far is kept).
close |= super::pressed_outside(ctx, area.response.rect);
if let Some(at) = report {
self.api("qv:progress", reqwest::Method::POST, format!("/quests/{quest}/video-progress"), Some(serde_json::json!({ "timestamp": at })));
if at >= target {
self.toast("Video quest complete! Claim the reward from Quests.", false);
self.backend.send(Command::FetchQuests);
}
}
if let Some(Err(e)) = self.api_take("qv:progress") {
self.toast(format!("Discord didn't count that watch time: {e}"), true);
}
if finished && !completed && !plain {
ctx.request_repaint_after(std::time::Duration::from_millis(500));
}
if close {
// Count what was watched before leaving.
if !completed && self.quest_video.as_ref().is_some_and(|v| v.report && position > v.reported + 1.0) {
self.api("qv:progress", reqwest::Method::POST, format!("/quests/{quest}/video-progress"), Some(serde_json::json!({ "timestamp": position.min(target) })));
}
self.quest_video = None;
if !plain {
self.backend.send(Command::FetchQuests);
}
}
}
pub(crate) fn has_nitro(&self) -> bool {
self.store.me.as_ref().and_then(|u| u.premium_type).is_some_and(|p| p > 0)
|| matches!(&self.nitro, Some(Ok(subs)) if subs.iter().any(|s| s.kind == 1 && s.status == 1))
}
// ---- Quests ---------------------------------------------------------------
pub fn quests_ui(&mut self, ui: &mut Ui) {
let t = self.theme.clone();
let mut action = None;
let claimed_tab = self.quests_claimed_tab;
page_header(ui, &t, "quests_header", icon::QUESTS, "Quests", |ui| {
ui.add_space(16.0);
for (label, on) in [("All Quests", false), ("Claimed Quests", true)] {
let selected = claimed_tab == on;
let g = ui.painter().layout_no_wrap(label.into(), FontId::proportional(16.0), Color32::PLACEHOLDER);
let (r, resp) = ui.allocate_exact_size(vec2(g.size().x + 8.0, 48.0), Sense::click());
let fg = if selected || resp.hovered() { t.header_primary } else { t.interactive_normal };
ui.painter().galley(pos2(r.left() + 4.0, r.center().y - g.size().y / 2.0), g, fg);
if selected {
ui.painter().rect_filled(Rect::from_min_max(pos2(r.left(), r.bottom() - 2.0), r.right_bottom()), 1.0, t.header_primary);
}
if resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
action = Some(StoreAction::ClaimedTab(on));
}
ui.add_space(12.0);
}
orbs_chip(ui, &t, self.orbs);
});
CentralPanel::default().frame(Frame::none().fill(t.bg_primary).inner_margin(Margin::symmetric(24.0, 0.0))).show_inside(ui, |ui| {
if loading_or_error(ui, &t, &self.quests, "Quests") {
if matches!(self.quests, Some(Err(_))) && ui.button("Try again").on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
action = Some(StoreAction::Retry(StorePage::Quests));
}
return;
}
let Some(Ok(list)) = &self.quests else { return };
let now = chrono::Local::now();
let mut quests: Vec<&Quest> = list
.quests
.iter()
.filter(|q| {
if claimed_tab {
q.claimed()
} else {
!q.claimed() && parse_time(&q.config.expires_at).map_or(true, |e| e > now) && parse_time(&q.config.starts_at).map_or(true, |s| s <= now)
}
})
.collect();
// Ones you've started first, like Discord's "Suggested".
quests.sort_by_key(|q| (!(q.enrolled() && !q.completed()), q.completed()));
ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
ui.add_space(20.0);
if !claimed_tab {
if let Some(a) = orbs_banner(ui) {
action = Some(a);
}
ui.add_space(28.0);
}
let title = if claimed_tab { format!("Claimed Quests – {}", quests.len()) } else { "Available Quests".to_string() };
ui.label(RichText::new(title).font(strong(20.0)).color(t.header_primary));
ui.add_space(16.0);
if quests.is_empty() {
ui.add_space(30.0);
ui.vertical_centered(|ui| {
let msg = if claimed_tab { "Quests you claim will show up here." } else { "No quests right now. Check back soon!" };
ui.label(RichText::new(msg).size(15.0).color(t.text_muted));
});
return;
}
let gap = 16.0;
let w = ui.available_width();
let cols = if w >= 2.0 * 340.0 + gap { 2 } else { 1 };
let tile_w = ((w - gap * (cols as f32 - 1.0)) / cols as f32).floor();
let nitro = self.has_nitro();
for row in quests.chunks(cols) {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = gap;
for q in row {
if let Some(a) = quest_tile(ui, &t, q, tile_w, nitro, now) {
action = Some(a);
}
}
});
ui.add_space(gap);
}
ui.add_space(16.0);
});
});
self.apply_store_action(action);
}
// ---- Shop -----------------------------------------------------------------
pub fn shop_ui(&mut self, ui: &mut Ui) {
let t = self.theme.clone();
let mut action = None;
page_header(ui, &t, "shop_header", icon::SHOP, "Shop", |ui| orbs_chip(ui, &t, self.orbs));
let me = self.store.me.clone().unwrap_or_default();
let nitro = self.has_nitro();
CentralPanel::default().frame(Frame::none().fill(t.bg_primary).inner_margin(Margin::symmetric(24.0, 0.0))).show_inside(ui, |ui| {
if loading_or_error(ui, &t, &self.shop, "the Shop") {
if matches!(self.shop, Some(Err(_))) && ui.button("Try again").on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
action = Some(StoreAction::Retry(StorePage::Shop));
}
return;
}
let Some(Ok(shop)) = &self.shop else { return };
ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
ui.add_space(20.0);
for (ci, cat) in shop.categories.iter().enumerate() {
// Hero banner with the collection's logo.
let w = ui.available_width();
let banner_h = (w * 0.27).clamp(150.0, 300.0);
let (rect, resp) = ui.allocate_exact_size(vec2(w, banner_h), Sense::click());
let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
if ui.is_rect_visible(rect) {
ui.painter().rect_filled(rect, 12.0, t.bg_secondary);
if let Some(url) = cat.hero_banner_url.as_deref().or(cat.catalog_banner_url.as_deref()) {
super::paint_cover(ui, rect, url, egui::Rounding::same(12.0));
}
if let Some(logo) = &cat.hero_logo_url {
let lr = Rect::from_center_size(pos2(rect.left() + rect.width() * 0.25, rect.center().y), vec2(rect.width() * 0.36, banner_h * 0.6));
egui::Image::new(logo.as_str()).maintain_aspect_ratio(true).fit_to_exact_size(lr.size()).paint_at(ui, lr);
}
}
if resp.on_hover_text("Open this collection on discord.com").on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
action = Some(StoreAction::Open(format!("https://discord.com/shop#itemSkuId={}", cat.sku_id)));
}
ui.add_space(16.0);
ui.label(RichText::new(&cat.name).font(strong(20.0)).color(t.header_primary));
if !cat.summary.trim().is_empty() {
ui.add_space(2.0);
ui.label(RichText::new(cat.summary.trim()).size(14.0).color(t.text_muted));
}
ui.add_space(12.0);
// Product cards.
let gap = 16.0;
let cols = ((w + gap) / (200.0 + gap)).floor().max(1.0) as usize;
let card_w = ((w - gap * (cols as f32 - 1.0)) / cols as f32).floor();
for row in cat.products.chunks(cols) {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = gap;
for p in row {
if let Some(a) = product_card(ui, &t, p, card_w, &me, nitro) {
action = Some(a);
}
}
});
ui.add_space(gap);
}
if ci + 1 < shop.categories.len() {
ui.add_space(20.0);
}
}
ui.add_space(8.0);
ui.vertical_centered(|ui| {
let all = egui::Button::new(RichText::new("Browse the whole Shop on discord.com").font(strong(14.0)).color(t.header_primary))
.fill(overlay(0.12))
.rounding(8.0)
.min_size(vec2(0.0, 38.0));
if ui.add(all).clicked() {
action = Some(StoreAction::Open("https://discord.com/shop".into()));
}
});
ui.add_space(24.0);
});
});
self.apply_store_action(action);
}
// ---- Nitro Home -------------------------------------------------------------
pub fn nitro_ui(&mut self, ui: &mut Ui) {
let t = self.theme.clone();
let mut action = None;
page_header(ui, &t, "nitro_header", icon::NITRO, "Nitro", |ui| {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let gift = egui::Button::new(RichText::new("Gift Nitro").font(strong(14.0)).color(t.header_primary))
.fill(overlay(0.12))
.rounding(8.0)
.min_size(vec2(0.0, 32.0));
if ui.add(gift).on_hover_text("Opens on discord.com").clicked() {
action = Some(StoreAction::Open("https://discord.com/nitro".into()));
}
});
});
let me = self.store.me.clone().unwrap_or_default();
CentralPanel::default().frame(Frame::none().fill(t.bg_primary).inner_margin(Margin::symmetric(32.0, 0.0))).show_inside(ui, |ui| {
ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
ui.add_space(28.0);
// "GOOD EVENING," + you.
let hour = chrono::Timelike::hour(&chrono::Local::now());
let greeting = match hour {
5..=11 => "GOOD MORNING,",
12..=17 => "GOOD AFTERNOON,",
_ => "GOOD EVENING,",
};
ui.label(RichText::new(greeting).font(strong(34.0)).color(t.header_primary));
ui.add_space(10.0);
ui.horizontal(|ui| {
let (r, _) = ui.allocate_exact_size(vec2(48.0, 48.0), Sense::hover());
paint_avatar(ui, r, Some(super::avatar_uri(&me, 96, true)), me.display_name());
if let Some(deco) = super::decoration_uri(&me, true) {
egui::Image::new(deco).paint_at(ui, r.expand(5.0));
}
ui.add_space(8.0);
ui.label(RichText::new(me.display_name()).font(strong(28.0)).color(t.header_primary));
});
ui.add_space(24.0);
// Your subscription.
let w = ui.available_width().min(760.0);
match &self.nitro {
None => {
ui.spinner();
}
Some(Err(e)) => {
ui.label(RichText::new(format!("Couldn't load your subscription: {e}")).size(14.0).color(t.text_muted));
if ui.button("Try again").on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
action = Some(StoreAction::Retry(StorePage::Nitro));
}
}
Some(Ok(subs)) => {
let sub = subs.iter().find(|s| s.kind == 1);
if let Some(a) = subscription_card(ui, sub, w) {
action = Some(a);
}
}
}
ui.add_space(32.0);
ui.label(RichText::new("YOUR NITRO PERKS").font(strong(22.0)).color(t.header_primary));
ui.add_space(14.0);
let perks: [(&str, &str, &str); 8] = [
("\u{E76E}", "Custom Emoji Anywhere", "Use custom and animated emoji in every server and DM."),
("\u{E790}", "Profile Themes & Banners", "Personalise your profile with colours, a banner and an animated avatar."),
("\u{E898}", "Bigger Uploads", "Share files up to 500MB."),
("\u{E714}", "HD Video & Streaming", "Stream at up to 4K and 60fps."),
("\u{E945}", "2 Server Boosts", "Boost your favourite servers, plus 30% off extra Boosts."),
("\u{E734}", "Super Reactions", "Unlimited Super Reactions with burst animations."),
("\u{E8BD}", "Longer Messages", "Send messages up to 4,000 characters."),
("\u{E7FC}", "Shop Discounts & Bonus Orbs", "Member prices in the Shop and extra Orbs from Quests."),
];
let gap = 16.0;
let cols = ((w + gap) / (240.0 + gap)).floor().max(1.0) as usize;
let card_w = ((w - gap * (cols as f32 - 1.0)) / cols as f32).floor();
for row in perks.chunks(cols) {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = gap;
for (glyph, title, text) in row {
let (r, _) = ui.allocate_exact_size(vec2(card_w, 132.0), Sense::hover());
ui.painter().rect(r, 12.0, t.bg_secondary, Stroke::new(1.0_f32, overlay(0.12)));
let c = pos2(r.left() + 34.0, r.top() + 34.0);
ui.painter().circle_filled(c, 18.0, NITRO_PINK.gamma_multiply(0.18));
ui.painter().text(c, Align2::CENTER_CENTER, *glyph, icon_font(17.0), NITRO_PINK);
ui.painter().text(pos2(r.left() + 16.0, r.top() + 72.0), Align2::LEFT_CENTER, *title, strong(15.0), t.header_primary);
let g = ui.painter().layout(text.to_string(), FontId::proportional(13.0), t.text_muted, r.width() - 32.0);
ui.painter().galley(pos2(r.left() + 16.0, r.top() + 86.0), g, t.text_muted);
}
});
ui.add_space(gap);
}
ui.add_space(12.0);
ui.horizontal(|ui| {
for (label, page) in [("Spend Orbs in the Shop", StorePage::Shop), ("Earn Orbs with Quests", StorePage::Quests)] {
let b = egui::Button::new(RichText::new(label).font(strong(14.0)).color(Color32::WHITE)).fill(BRAND).rounding(8.0).min_size(vec2(0.0, 38.0));
if ui.add(b).clicked() {
action = Some(StoreAction::Page(page));
}
ui.add_space(8.0);
}
});
ui.add_space(28.0);
});
});
self.apply_store_action(action);
}
}
/// Nitro plan names by plan ID.
fn plan_name(plan: u64) -> &'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",
_ => "Nitro",
}
}
fn subscription_card(ui: &mut Ui, sub: Option<&Subscription>, w: f32) -> Option<StoreAction> {
let mut action = None;
let (rect, _) = ui.allocate_exact_size(vec2(w, 120.0), Sense::hover());
// Nitro's purple → pink.
hgradient_rrect(ui.painter(), rect, 12.0, Color32::from_rgb(0x53, 0x3a, 0xb5), Color32::from_rgb(0xb4, 0x3a, 0xa8));
let x = rect.left() + 24.0;
match sub {
Some(s) => {
let plan = s.items.first().map_or("Nitro", |i| plan_name(i.plan_id.0));
ui.painter().text(pos2(x, rect.top() + 32.0), Align2::LEFT_CENTER, plan, strong(22.0), Color32::WHITE);
let end = s.current_period_end.as_deref().and_then(parse_time).map(|d| d.format("%-d %B %Y").to_string());
let line = match (s.canceled_at.is_some() || s.status == 3, end) {
(true, Some(d)) => format!("Ends on {d}"),
(false, Some(d)) => format!("Renews on {d}"),
_ => "Active".into(),
};
ui.painter().text(pos2(x, rect.top() + 62.0), Align2::LEFT_CENTER, line, FontId::proportional(15.0), crate::style::rgba(255, 255, 255, 230));
if let Some(since) = s.created_at.as_deref().and_then(parse_time) {
ui.painter().text(pos2(x, rect.top() + 86.0), Align2::LEFT_CENTER, format!("Subscriber since {}", since.format("%B %Y")), FontId::proportional(13.0), crate::style::rgba(255, 255, 255, 190));
}
let br = Rect::from_min_size(pos2(rect.right() - 24.0 - 190.0, rect.center().y - 20.0), vec2(190.0, 40.0));
if button_at(ui, br, egui::Id::new("nitro_manage"), "Manage Subscription", Color32::WHITE, Color32::from_gray(225), Color32::from_rgb(0x53, 0x3a, 0xb5)).on_hover_text("Opens on discord.com").clicked() {
action = Some(StoreAction::Open("https://discord.com/settings/subscriptions".into()));
}
}
None => {
ui.painter().text(pos2(x, rect.top() + 40.0), Align2::LEFT_CENTER, "Unleash more fun with Nitro", strong(22.0), Color32::WHITE);
ui.painter().text(pos2(x, rect.top() + 72.0), Align2::LEFT_CENTER, "Bigger uploads, custom emoji everywhere, HD streaming and more.", FontId::proportional(14.0), crate::style::rgba(255, 255, 255, 230));
let br = Rect::from_min_size(pos2(rect.right() - 24.0 - 140.0, rect.center().y - 20.0), vec2(140.0, 40.0));
if button_at(ui, br, egui::Id::new("nitro_get"), "Get Nitro", Color32::WHITE, Color32::from_gray(225), Color32::from_rgb(0x53, 0x3a, 0xb5)).on_hover_text("Opens on discord.com").clicked() {
action = Some(StoreAction::Open("https://discord.com/nitro".into()));
}
}
}
action
}
/// The "Introducing Discord Orbs" banner at the top of Quests.
fn orbs_banner(ui: &mut Ui) -> Option<StoreAction> {
let mut action = None;
let w = ui.available_width();
let (rect, _) = ui.allocate_exact_size(vec2(w, 190.0), Sense::hover());
hgradient_rrect(ui.painter(), rect, 12.0, Color32::from_rgb(0x0b, 0x0c, 0x1e), Color32::from_rgb(0x2a, 0x1f, 0x6e));
// A few orbs floating on the right.
for (dx, dy, r) in [(0.78, 0.45, 46.0), (0.92, 0.25, 22.0), (0.64, 0.25, 14.0)] {
paint_orb(ui, pos2(rect.left() + rect.width() * dx, rect.top() + rect.height() * dy), r);
}
let x = rect.left() + 28.0;
ui.painter().text(pos2(x, rect.top() + 48.0), Align2::LEFT_CENTER, "INTRODUCING", strong(30.0), Color32::WHITE);
ui.painter().text(pos2(x, rect.top() + 84.0), Align2::LEFT_CENTER, "DISCORD ORBS", strong(30.0), Color32::WHITE);
ui.painter().text(pos2(x, rect.top() + 116.0), Align2::LEFT_CENTER, "Reward Your Play. Earn through Quests. Spend in the Shop.", FontId::proportional(14.0), crate::style::rgba(255, 255, 255, 220));
let br = Rect::from_min_size(pos2(x, rect.top() + 136.0), vec2(150.0, 36.0));
if button_at(ui, br, egui::Id::new("orbs_shop"), "Explore Orbs Shop", Color32::WHITE, Color32::from_gray(225), Color32::from_rgb(0x1e, 0x1f, 0x22)).clicked() {
action = Some(StoreAction::Page(StorePage::Shop));
}
action
}
/// One quest tile: hero art, what to do, the reward and the buttons.
fn quest_tile(ui: &mut Ui, t: &Theme, q: &Quest, w: f32, nitro: bool, now: chrono::DateTime<chrono::Local>) -> Option<StoreAction> {
let mut action = None;
let h = 332.0;
let (rect, resp) = ui.allocate_exact_size(vec2(w, h), Sense::hover());
if !ui.is_rect_visible(rect) {
return None;
}
let p = ui.painter();
p.rect(rect, 12.0, t.bg_secondary, Stroke::new(1.0_f32, overlay(0.12)));
// Hero.
let hero = Rect::from_min_size(rect.min, vec2(w, 140.0));
let top_round = egui::Rounding { nw: 12.0, ne: 12.0, sw: 0.0, se: 0.0 };
if let Some(url) = q.hero_url() {
super::paint_cover(ui, hero, &url, top_round);
} else {
ui.painter().rect_filled(hero, top_round, t.bg_tertiary);
}
// Darken the bottom for the logo and text.
let mut mesh = egui::Mesh::default();
let fade = Rect::from_min_max(pos2(hero.left(), hero.top() + 50.0), hero.max);
for (pt, c) in [(fade.left_top(), Color32::TRANSPARENT), (fade.right_top(), Color32::TRANSPARENT), (fade.right_bottom(), Color32::from_black_alpha(200)), (fade.left_bottom(), Color32::from_black_alpha(200))] {
mesh.colored_vertex(pt, c);
}
mesh.add_triangle(0, 1, 2);
mesh.add_triangle(0, 2, 3);
ui.painter().add(egui::Shape::mesh(mesh));
if let Some(logo) = q.logo_url() {
let lr = Rect::from_min_size(pos2(hero.left() + 14.0, hero.bottom() - 70.0), vec2(w * 0.4, 44.0));
egui::Image::new(logo).maintain_aspect_ratio(true).fit_to_exact_size(lr.size()).paint_at(ui, lr);
}
let small = FontId::proportional(12.0);
let publisher = &q.config.messages.game_publisher;
if !publisher.is_empty() {
ui.painter().text(pos2(hero.left() + 14.0, hero.bottom() - 14.0), Align2::LEFT_CENTER, format!("Promoted by: {publisher}"), small.clone(), crate::style::rgba(255, 255, 255, 220));
}
if let Some(end) = parse_time(&q.config.expires_at) {
let left = end - now;
let text = if left.num_hours() < 48 && left.num_hours() >= 0 { format!("Ends in {}h", left.num_hours().max(1)) } else { format!("Ends {}", end.format("%d/%m")) };
ui.painter().text(pos2(hero.right() - 14.0, hero.bottom() - 14.0), Align2::RIGHT_CENTER, text, small.clone(), crate::style::rgba(255, 255, 255, 220));
}
// Body.
let x = rect.left() + 16.0;
let mut y = hero.bottom() + 18.0;
let name = format!("{} QUEST", q.config.messages.quest_name.trim().to_uppercase());
let clip = ui.painter().with_clip_rect(Rect::from_min_max(pos2(x, hero.bottom()), pos2(rect.right() - 16.0, rect.bottom())));
clip.text(pos2(x, y), Align2::LEFT_CENTER, name, strong(12.0), BRAND_TEXT);
y += 16.0;
// Reward thumbnail.
let thumb = Rect::from_min_size(pos2(x, y), vec2(56.0, 56.0));
ui.painter().rect_filled(thumb, 8.0, t.bg_tertiary);
let reward = q.reward();
match reward {
Some(r) if r.kind == 4 => paint_orb(ui, thumb.center(), 18.0),
Some(r) => {
let art = r.asset.as_deref().filter(|a| !a.ends_with(".mp4") && *a != "PLACEHOLDER").map(discord::commerce::quest_asset);
let video = r.asset.as_deref().filter(|a| a.ends_with(".mp4")).map(discord::commerce::quest_asset);
let tile = q.config.assets.game_tile_dark.as_deref().filter(|a| *a != "PLACEHOLDER").map(discord::commerce::quest_asset);
let frame = video.and_then(|v| crate::video::current_frame(ui.ctx(), &v, resp.hovered()));
if let Some(src) = frame.or(art).or(tile) {
egui::Image::new(src).rounding(8.0).paint_at(ui, thumb);
}
}
None => {}
}
let tx = thumb.right() + 12.0;
let text_w = rect.right() - 16.0 - tx;
// Orbs: Nitro members get the boosted amount (Discord's "x1.2").
let boosted = reward.filter(|r| r.kind == 4 && nitro).and_then(|r| r.premium_orb_quantity.filter(|p| Some(*p) != r.orb_quantity));
let reward_name = match reward {
Some(r) if r.kind == 4 => boosted.or(r.orb_quantity).map_or_else(|| r.messages.name.clone(), |n| format!("{n} Orbs")),
Some(r) => r.messages.name.clone(),
None => String::new(),
};
let title = ui.painter().layout(format!("Claim {reward_name}"), strong(16.0), t.header_primary, text_w);
let title_h = title.size().y.min(42.0);
let title_w = title.size().x;
ui.painter().with_clip_rect(Rect::from_min_size(pos2(tx, y), vec2(text_w, 42.0))).galley(pos2(tx, y), title, t.header_primary);
if let (Some(b), Some(base)) = (boosted, reward.and_then(|r| r.orb_quantity).filter(|b| *b > 0)) {
let chip = format!("x{:.1}", b as f64 / base as f64);
let g = ui.painter().layout_no_wrap(chip, strong(11.0), NITRO_PINK);
let cr = Rect::from_min_size(pos2(tx + title_w + 6.0, y + 2.0), g.size() + vec2(10.0, 4.0));
if cr.right() < rect.right() - 16.0 {
ui.painter().rect_filled(cr, 4.0, NITRO_PINK.gamma_multiply(0.18));
ui.painter().galley(cr.min + vec2(5.0, 2.0), g, NITRO_PINK);
}
}
let reward_text = match (reward, boosted) {
(Some(r), Some(n)) if r.kind == 4 => format!("{n} Orbs"),
(Some(r), _) => r.messages.name_with_article.clone(),
_ => String::new(),
};
let desc = ui.painter().layout(quest_text(q, &reward_text), FontId::proportional(13.0), t.text_muted, text_w);
ui.painter().with_clip_rect(Rect::from_min_size(pos2(tx, y + title_h + 4.0), vec2(text_w, 36.0))).galley(pos2(tx, y + title_h + 4.0), desc, t.text_muted);
// Progress (accepted quests).
let by = rect.bottom() - 16.0 - 36.0;
if q.enrolled() && !q.claimed() {
let frac = if q.completed() { 1.0 } else { q.progress() };
let track = Rect::from_min_max(pos2(x, by - 20.0), pos2(rect.right() - 16.0, by - 14.0));
ui.painter().rect_filled(track, 3.0, overlay(0.2));
ui.painter().rect_filled(Rect::from_min_max(track.min, pos2(track.left() + track.width() * frac, track.bottom())), 3.0, BRAND);
let label = if q.completed() { "Completed!".to_string() } else { format!("{}% complete", (frac * 100.0).round()) };
ui.painter().text(pos2(x, by - 30.0), Align2::LEFT_CENTER, label, strong(12.0), t.header_primary);
}
if q.mobile_only() && !q.enrolled() {
ui.painter().text(pos2(rect.right() - 16.0, by - 14.0), Align2::RIGHT_CENTER, "Complete on mobile", small, t.text_muted);
}
// Buttons.
let half = (w - 32.0 - 10.0) / 2.0;
let left = Rect::from_min_size(pos2(x, by), vec2(half, 36.0));
let right = Rect::from_min_size(pos2(x + half + 10.0, by), vec2(half, 36.0));
let quest_page = format!("https://discord.com/quests/{}", q.id);
let cta_label = q.config.cta_config.as_ref().and_then(|c| c.button_label.clone()).unwrap_or_else(|| if q.is_video() { "Learn More".into() } else { "Play Now".into() });
let cta_link = q.config.cta_config.as_ref().and_then(|c| c.link.clone()).or_else(|| q.config.application.link.clone()).unwrap_or_else(|| quest_page.clone());
if button_at(ui, left, egui::Id::new(("quest_cta", q.id.0)), &cta_label, overlay(0.16), overlay(0.24), t.header_primary).on_hover_text("Opens in your browser").clicked() {
action = Some(StoreAction::Open(cta_link));
}
// Video quests play right here (accepting them first if needed).
let watchable = q.video().is_some();
let (label, fill, hover) = if q.claimed() {
("Claimed", overlay(0.12), overlay(0.12))
} else if q.completed() {
("Claim Reward", BRAND, BRAND_HOVER)
} else if watchable {
("Watch Video", BRAND, BRAND_HOVER)
} else if q.enrolled() {
("Quest Accepted", overlay(0.12), overlay(0.16))
} else {
("Accept Quest", BRAND, BRAND_HOVER)
};
let b = button_at(ui, right, egui::Id::new(("quest_main", q.id.0)), label, fill, hover, Color32::WHITE);
let b = match label {
"Claim Reward" => b.on_hover_text("Claiming opens on discord.com"),
"Watch Video" if !q.enrolled() => b.on_hover_text("Accepts the quest and plays the video here"),
"Quest Accepted" => b.on_hover_text("Progress counts while you play with Discord's desktop app running"),
_ => b,
};
if b.clicked() {
action = match label {
"Accept Quest" => Some(StoreAction::Enroll(q.id, q.traffic_metadata_sealed.clone())),
"Watch Video" => Some(StoreAction::Watch(q.id)),
"Claim Reward" => Some(StoreAction::Open(quest_page)),
_ => None,
};
}
action
}
/// "Play Call of Duty for 15 minutes and win A 15m 2XP Token."
fn quest_text(q: &Quest, reward: &str) -> String {
let game = &q.config.messages.game_title;
let minutes = |t: &discord::commerce::QuestTask| t.target.div_ceil(60).max(1);
match q.task() {
Some(t) if t.kind.starts_with("WATCH_VIDEO") => format!("Watch the video to win {reward}!"),
Some(t) if t.kind.starts_with("PLAY") => format!("Play {game} for {} minutes and win {reward}.", minutes(t)),
Some(t) if t.kind.starts_with("STREAM") => format!("Stream {game} to a friend for {} minutes and win {reward}.", minutes(t)),
_ => format!("Complete the quest in {game} and win {reward}."),
}
}
/// One Shop product: a preview on your own avatar / name, then price.
fn product_card(ui: &mut Ui, t: &Theme, p: &ShopProduct, w: f32, me: &discord::model::User, nitro: bool) -> Option<StoreAction> {
let h = w + 92.0;
let (rect, resp) = ui.allocate_exact_size(vec2(w, h), Sense::click());
let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
if !ui.is_rect_visible(rect) {
return None;
}
let hovered = resp.hovered();
ui.painter().rect(rect, 12.0, if hovered { t.bg_secondary_alt } else { t.bg_secondary }, Stroke::new(1.0_f32, if hovered { overlay(0.24) } else { overlay(0.12) }));
let stage = Rect::from_min_size(rect.min + vec2(8.0, 8.0), vec2(w - 16.0, w - 16.0));
ui.painter().rect_filled(stage, 8.0, t.bg_tertiary);
let kind = if p.kind == 1000 { p.items.first().map_or(1000, |i| i.kind as u32) } else { p.kind };
match p.preview() {
Some((0, url)) => {
// Decoration on your avatar.
let av = Rect::from_center_size(stage.center(), vec2(stage.width() * 0.5, stage.width() * 0.5));
paint_avatar(ui, av, Some(me.avatar_or_default(128)), me.display_name());
egui::Image::new(url).paint_at(ui, av.expand(av.width() * 0.1));
}
Some((2, url)) => {
// Nameplate behind your name, like the member list.
let row = Rect::from_center_size(stage.center(), vec2(stage.width() - 16.0, 44.0));
egui::Image::new(url).rounding(6.0).paint_at(ui, row);
let av = Rect::from_center_size(pos2(row.left() + 24.0, row.center().y), vec2(28.0, 28.0));
paint_avatar(ui, av, Some(me.avatar_or_default(64)), me.display_name());
ui.painter().text(pos2(av.right() + 8.0, row.center().y), Align2::LEFT_CENTER, me.display_name(), strong(14.0), Color32::WHITE);
}
Some((_, url)) => {
egui::Image::new(url).rounding(8.0).maintain_aspect_ratio(true).fit_to_exact_size(stage.size()).paint_at(ui, stage);
}
None => {
ui.painter().text(stage.center(), Align2::CENTER_CENTER, icon::SHOP, icon_font(28.0), t.interactive_muted);
}
}
let x = rect.left() + 12.0;
let clip = ui.painter().with_clip_rect(Rect::from_min_max(pos2(x, stage.bottom()), pos2(rect.right() - 12.0, rect.bottom())));
clip.text(pos2(x, stage.bottom() + 18.0), Align2::LEFT_CENTER, &p.name, strong(15.0), t.header_primary);
let label = match (p.kind, kind) {
(1000, _) => "Bundle",
(_, 0) => "Avatar Decoration",
(_, 1) => "Profile Effect",
(_, 2) => "Nameplate",
(_, 3) => "Profile Frame",
_ => "Collectible",
};
clip.text(pos2(x, stage.bottom() + 38.0), Align2::LEFT_CENTER, label, FontId::proportional(12.0), t.text_muted);
// Price: with Nitro you pay the member price; show both.
let price_y = stage.bottom() + 62.0;
match (p.regular_price(), p.nitro_price()) {
(Some(reg), Some(member)) if nitro => {
let r = clip.text(pos2(x, price_y), Align2::LEFT_CENTER, member.display(), strong(14.0), t.header_primary);
let old = clip.text(pos2(r.right() + 8.0, price_y), Align2::LEFT_CENTER, reg.display(), FontId::proportional(12.0), t.text_muted);
clip.hline(old.x_range(), price_y, Stroke::new(1.0_f32, t.text_muted));
}
(Some(reg), member) => {
let r = clip.text(pos2(x, price_y), Align2::LEFT_CENTER, reg.display(), strong(14.0), t.header_primary);
if let Some(m) = member {
clip.text(pos2(r.right() + 8.0, price_y), Align2::LEFT_CENTER, format!("{} with Nitro", m.display()), FontId::proportional(12.0), NITRO_PINK);
}
}
_ => {}
}
let tip = p.summary.trim();
let resp = if tip.is_empty() { resp } else { resp.on_hover_text(tip) };
resp.on_hover_cursor(egui::CursorIcon::PointingHand)
.clicked()
.then(|| StoreAction::Open(format!("https://discord.com/shop#itemSkuId={}", p.sku_id)))
}