Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.
Rust desktop-appdiscorddiscord-clienteguielectron-alternativelightweightlinuxmacosnative-apprustwindows
//! The chat area: header, message list, composer and message context menu.
use super::{format_timestamp, format_unix, human_size, paint_avatar, short_time};
use super::chat_placeholder::Placeholder;
use crate::app::{ContextMenu, EditState, RustCord};
use crate::emoji::twemoji_url;
use crate::features::PickerTarget;
use crate::markdown::{self, Block, Inline, LineKind};
use crate::store::Store;
use crate::style::{bold, icon, icon_font};
use discord::model::{channel_kind, Attachment, Channel, DeletedStyle, Id, Message, Reaction, ReactionEmoji, User};
use std::collections::HashMap;
use eframe::egui::{
self, pos2, vec2, Align, Align2, Button, CentralPanel, Color32, CursorIcon, FontId, Frame, Key, Label, Layout,
Margin, Modifiers, Order, Pos2, Rect, Response, RichText, Rounding, ScrollArea, Sense, Shape, Stroke, TextEdit,
TopBottomPanel, Ui,
};
pub enum UiAction {
/// The DM start header's Add Friend / Accept (true), Remove Friend / Unblock (false).
Relationship { user: Id, add: bool },
Block(Id),
/// "Wave to …" in a new DM: Wumpus's wave sticker, sent as Discord's greeting.
Wave(Id),
OpenContext { channel: Id, msg: Id, pos: Pos2 },
Reveal(Id, usize),
LoadOlder(Id),
Retry(Id),
SaveEdit,
CancelEdit,
SelectChannel(Id),
React { channel: Id, msg: Id, emoji: ReactionEmoji },
Reply { channel: Id, msg: Id },
StartEdit { channel: Id, msg: Id },
Forward { channel: Id, msg: Id },
OpenPicker { channel: Id, msg: Id, pos: Pos2 },
OpenProfile { user: Box<User>, guild: Option<Id>, pos: Pos2 },
/// A server message's author was right-clicked: the member menu.
MemberMenu { guild: Id, user: Box<User>, pos: Pos2 },
/// Open an image / GIF in the in-app viewer.
View(crate::features::MediaView),
/// A server tag was clicked: show that server's card.
OpenTag { guild: Id, pos: Pos2 },
/// A sticker in a message was clicked: its popout (pack or server).
OpenSticker { sticker: discord::model::StickerItem, channel: Id, message: Id, anchor: Rect },
AudioToggle(String),
AudioSeek(String, f32),
AudioMute,
/// Play / pause the inline video at this URL (starting it if needed).
VideoToggle(String),
VideoSeek(String, f32),
VideoMute,
VideoFullscreen,
/// Open the provider's player (YouTube, Spotify…) over an embed.
PlayEmbed { key: crate::embed_view::Key, channel: Id, src: String, bg: Color32 },
/// The ✕ beside an embed: remove all embeds from the message.
SuppressEmbeds { channel: Id, msg: Id },
/// A reaction's tooltip was clicked: open the Reactions dialog on it.
OpenReactions { channel: Id, msg: Id, emoji: ReactionEmoji },
/// A reaction is hovered: find out who reacted.
FetchReactors { channel: Id, msg: Id, emoji: ReactionEmoji, count: u32 },
/// A `</command:id>` mention was clicked: put it in the message box.
UseCommand(String),
OpenUrl(String),
/// A bot button / select menu was used.
Interact { channel: Id, msg: Id, component_type: u8, custom_id: String, values: Option<Vec<String>> },
/// Open / close a bot's select menu.
ToggleSelect { msg: Id, custom_id: String },
/// "Dismiss message" on a reply only you can see.
Dismiss { channel: Id, msg: Id },
/// Vote in a poll (an empty list takes your votes back).
PollVote { channel: Id, msg: Id, answers: Vec<u32> },
/// An AutoMod alert's buttons: lift the mention-raid restrictions
/// (true) or open the server's settings (false).
AutoMod { guild: Id, clear_raid: bool },
/// Scroll the chat to a message (a closed poll's "View Poll").
JumpTo { channel: Id, msg: Id },
/// "pinned messages" in a pin notice: open that channel's pins popout.
OpenPins(Id),
/// The new-messages bar: jump up to the first message you missed.
JumpToNew(Id),
/// The new-messages bar's "Mark As Read".
MarkRead(Id),
/// Scrolled up to the NEW line: the bar has done its job.
HideNewBar(Id),
/// Open a thread (fetched first if RustCord doesn't know it yet).
OpenThread(Id),
/// Rencord's MessageSelect: check a message off (or un-check it).
PickMessage { channel: Id, msg: Id },
}
/// The message the chat should scroll to next frame (egui temp data per channel).
fn jump_id(ch: Id) -> egui::Id {
egui::Id::new(("jump_to", ch.0))
}
fn message_scroll_area(ch: Id, follow_bottom: bool) -> ScrollArea {
ScrollArea::vertical()
.id_salt(("messages", ch.0))
.stick_to_bottom(follow_bottom)
.animated(follow_bottom)
.auto_shrink([false, false])
}
/// Body text size (Discord uses 16px).
/// The chat text size (Discord's 16 px unless changed in Accessibility).
fn text_px() -> f32 {
super::chat_text()
}
/// Discord's code background: its blurple at 12 %.
fn code_fill() -> Color32 {
crate::style::rgba(130, 142, 236, 32)
}
/// Discord's system messages (joins, pins, boosts, thread and poll notices):
/// an icon in the avatar gutter, one muted line with the time after it.
fn is_system(m: &Message) -> bool {
!matches!(m.kind, 0 | 19 | 20 | 23 | 24) && (matches!(m.kind, 18 | 46 | FRIEND_REQUEST_ACCEPTED) || system_text(m, m.display_name()).is_some())
}
/// Discord's FRIEND_REQUEST_ACCEPTED message (type 67), the first thing in a
/// DM once a request is accepted: written by whoever accepted it, with the
/// note the request came with as its text.
const FRIEND_REQUEST_ACCEPTED: u8 = 67;
/// Wumpus waving (a Lottie sticker): what Discord's "Wave to …" sends.
pub(super) const WAVE_STICKER: Id = Id(749_054_660_769_218_631);
/// Channel flag: the DM holds only system messages (Discord's
/// HAS_ONLY_SYSTEM_MESSAGES), e.g. just the accepted friend request.
pub(super) const HAS_ONLY_SYSTEM_MESSAGES: u32 = 1 << 23;
/// The icon Discord shows in the gutter of a system message.
fn system_icon(ui: &Ui, t: &crate::style::Theme, kind: u8, rect: Rect) {
let c = rect.center();
let p = ui.painter();
let green = Color32::from_rgb(0x23, 0xa5, 0x5a);
match kind {
// Joined / added: Discord's green arrow.
1 | 7 => {
let s = Stroke::new(2.0_f32, green);
p.line_segment([c - vec2(7.0, 0.0), c + vec2(7.0, 0.0)], s);
p.line_segment([c + vec2(2.0, -5.0), c + vec2(7.0, 0.0)], s);
p.line_segment([c + vec2(2.0, 5.0), c + vec2(7.0, 0.0)], s);
}
// A call: Discord's phone, green (red for one you missed).
3 | MISSED_CALL => {
let color = if kind == MISSED_CALL { t.danger } else { green };
p.text(c, Align2::CENTER_CENTER, icon::PHONE_CALL, icon_font(18.0), color);
}
// Removed / left: the red one, pointing back.
2 => {
let s = Stroke::new(2.0_f32, t.danger);
p.line_segment([c - vec2(7.0, 0.0), c + vec2(7.0, 0.0)], s);
p.line_segment([c + vec2(-2.0, -5.0), c - vec2(7.0, 0.0)], s);
p.line_segment([c + vec2(-2.0, 5.0), c - vec2(7.0, 0.0)], s);
}
4 | 5 => {
p.text(c, Align2::CENTER_CENTER, icon::EDIT, icon_font(16.0), t.text_muted);
}
6 => {
p.text(c, Align2::CENTER_CENTER, icon::PIN, icon_font(16.0), t.text_muted);
}
8..=11 => {
p.text(c, Align2::CENTER_CENTER, icon::NITRO, icon_font(16.0), Color32::from_rgb(0xff, 0x73, 0xfa));
}
18 => {
p.text(c, Align2::CENTER_CENTER, icon::THREAD, icon_font(18.0), t.text_muted);
}
// A friend request accepted: Discord's UserCheckIcon (18 px) in
// --status-positive.
FRIEND_REQUEST_ACCEPTED => {
egui::Image::new(egui::ImageSource::Bytes { uri: "bytes://user-check.svg".into(), bytes: egui::load::Bytes::Static(super::profile::USER_CHECK_SVG.as_bytes()) })
.tint(green)
.paint_at(ui, Rect::from_center_size(c, vec2(18.0, 18.0)));
}
// Poll results: Discord's three bars.
46 => {
for (i, w) in [12.0_f32, 8.0, 10.0].iter().enumerate() {
let y = c.y - 5.0 + i as f32 * 5.0;
p.rect_filled(Rect::from_min_size(pos2(c.x - 7.0, y - 1.0), vec2(*w, 2.0)), 1.0, t.text_muted);
}
}
_ => {
p.circle_filled(c, 2.0, t.text_muted);
}
}
}
/// "6d ago" as Discord's thread cards put it.
fn short_ago(ms: u64) -> String {
let now = chrono::Utc::now().timestamp_millis().max(0) as u64;
let mins = now.saturating_sub(ms) / 60_000;
match mins {
0 => "just now".into(),
1..=59 => format!("{mins}m ago"),
60..=1439 => format!("{}h ago", mins / 60),
1440..=43_199 => format!("{}d ago", mins / 1440),
_ => "30d+ ago".into(),
}
}
/// Regular (non-system) messages that can be grouped under one header.
fn is_regular(m: &Message) -> bool {
matches!(m.kind, 0 | 19)
}
/// Width of an emoji picture in the message box.
const COMPOSER_EMOJI: f32 = 22.0;
/// `<:name:id>` / `<a:name:id>` at the start of `chars`: (length, image URL).
fn custom_emoji_token(chars: &[char]) -> Option<(usize, String)> {
let end = chars.iter().take(100).position(|c| *c == '>')?;
let inner: String = chars.get(1..end)?.iter().collect();
let (animated, rest) = match inner.strip_prefix("a:") {
Some(r) => (true, r),
None => (false, inner.strip_prefix(':')?),
};
let (name, id) = rest.split_once(':')?;
if name.is_empty() || !name.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '~') {
return None;
}
let id: u64 = id.parse().ok()?;
Some((end + 1, super::emoji_img(Id(id), animated, 48)))
}
/// Emoji in message-box text: (first char, char count, image URL).
fn composer_emoji_spans(text: &str) -> Vec<(usize, usize, String)> {
// (The legacy chat input shows what you typed, as text.)
if super::LEGACY_INPUT.load(std::sync::atomic::Ordering::Relaxed) {
return Vec::new();
}
let chars: Vec<char> = text.chars().collect();
let mut out = Vec::new();
let mut i = 0;
while i < chars.len() {
if chars[i] == '<' {
if let Some((n, url)) = custom_emoji_token(&chars[i..]) {
out.push((i, n, url));
i += n;
continue;
}
}
if let Some(n) = crate::emoji::emoji_len(&chars, i) {
let seq: String = chars[i..i + n].iter().collect();
out.push((i, n, twemoji_url(&seq)));
i += n;
continue;
}
i += 1;
}
out
}
/// Message-box layout: normal text, and for each emoji an invisible run one
/// picture wide (the picture is painted on top by [`paint_composer_emoji`]).
fn composer_layout(ui: &Ui, text: &str, font: FontId, color: Color32, wrap: f32) -> egui::text::LayoutJob {
let mut job = egui::text::LayoutJob::default();
job.wrap.max_width = wrap;
let normal = egui::TextFormat::simple(font.clone(), color);
let row_h = ui.fonts(|f| f.row_height(&font));
let hidden = egui::TextFormat {
font_id: FontId::proportional(1.0),
color: Color32::TRANSPARENT,
line_height: Some(row_h),
..Default::default()
};
let chars: Vec<char> = text.chars().collect();
let spans = composer_emoji_spans(text);
let (mut i, mut k) = (0, 0);
while i < chars.len() {
match spans.get(k) {
Some(&(s, n, _)) if s == i => {
// The gap goes before the (invisible) characters.
let span: String = chars[s..s + n].iter().collect();
job.append(&span, COMPOSER_EMOJI, hidden.clone());
i = s + n;
k += 1;
}
next => {
let end = next.map(|s| s.0).unwrap_or(chars.len());
let run: String = chars[i..end].iter().collect();
job.append(&run, 0.0, normal.clone());
i = end;
}
}
}
if job.sections.is_empty() {
job.append("", 0.0, normal);
}
job
}
/// `text` with the code of every server invite link replaced by dots.
fn mask_invites(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut rest = text;
loop {
let hit = ["discord.gg/", "discord.com/invite/", "discordapp.com/invite/"].iter().filter_map(|p| rest.find(p).map(|i| i + p.len())).min();
let Some(i) = hit else { break };
out.push_str(&rest[..i]);
let code = rest[i..].find(|c: char| !(c.is_ascii_alphanumeric() || c == '-')).unwrap_or(rest.len() - i);
if code > 0 {
out.push_str("\u{2022}\u{2022}\u{2022}");
}
rest = &rest[i + code..];
}
out.push_str(rest);
out
}
/// Byte offset of the `ci`-th character of `s` (its length past the end).
fn char_to_byte(s: &str, ci: usize) -> usize {
s.char_indices().nth(ci).map_or(s.len(), |(i, _)| i)
}
/// The spell checker's red wavy underlines (Chrome's look: a 1 px wave, 4 px
/// long and 2 px tall, just under the baseline) below each misspelled word.
fn paint_misspellings(ui: &Ui, out: &egui::text_edit::TextEditOutput, text: &str, ranges: &[std::ops::Range<usize>]) {
if ranges.is_empty() {
return;
}
let painter = ui.painter().with_clip_rect(out.text_clip_rect.intersect(ui.clip_rect()));
let red = Color32::from_rgb(240, 71, 71);
for r in ranges {
let (a, b) = (text[..r.start].chars().count(), text[..r.end].chars().count());
let start = out.galley.pos_from_ccursor(egui::text::CCursor::new(a));
// (Stay on the word's row when it ends exactly at a wrap.)
let end = out.galley.pos_from_cursor(&out.galley.from_ccursor(egui::text::CCursor { index: b, prefer_next_row: false }));
if (start.top() - end.top()).abs() > 1.0 || end.left() <= start.left() {
continue;
}
let y = out.galley_pos.y + start.bottom() - 2.0;
let (x0, x1) = (out.galley_pos.x + start.left(), out.galley_pos.x + end.left());
let mut points = Vec::new();
let mut x = x0;
let mut up = false;
while x <= x1 {
points.push(pos2(x, y + if up { -1.0 } else { 1.0 }));
up = !up;
x += 2.0;
}
if points.len() > 1 {
painter.add(egui::Shape::line(points, Stroke::new(1.0_f32, red)));
}
}
}
/// Paint the emoji pictures over the gaps [`composer_layout`] left.
/// `shift`: how far the character at an index is moved right now (typing effects).
fn paint_composer_emoji(ui: &Ui, out: &egui::text_edit::TextEditOutput, text: &str, shift: &dyn Fn(usize) -> egui::Vec2) {
let spans = composer_emoji_spans(text);
if spans.is_empty() {
return;
}
// Char index → (glyph x, row rect), in galley coordinates.
let mut glyphs: Vec<(f32, Rect)> = Vec::new();
for row in &out.galley.rows {
for g in &row.glyphs {
glyphs.push((g.pos.x, row.rect));
}
if row.ends_with_newline {
glyphs.push((row.rect.right(), row.rect));
}
}
let painter = ui.painter().with_clip_rect(out.text_clip_rect.intersect(ui.clip_rect()));
for (start, _, url) in spans {
let Some(&(x, row)) = glyphs.get(start) else { continue };
let size = COMPOSER_EMOJI - 2.0;
let r = Rect::from_min_size(out.galley_pos + vec2(x - COMPOSER_EMOJI + 1.0, row.center().y - size / 2.0) + shift(start), vec2(size, size));
if !painter.clip_rect().intersects(r) {
continue;
}
if let Ok(egui::load::TexturePoll::Ready { texture }) = egui::Image::new(url).load_for_size(ui.ctx(), r.size()) {
painter.image(texture.id, r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
}
}
}
/// The message is just a link to a GIF / image that Discord shows as media:
/// Discord hides the link text then.
pub(super) fn link_only_media(m: &Message) -> bool {
let c = m.content.trim();
let single_url = (c.starts_with("https://") || c.starts_with("http://")) && !c.contains(char::is_whitespace);
single_url && m.embeds.iter().any(|e| matches!(e.kind.as_deref(), Some("gifv" | "image")))
}
/// A lone link Discord would show as media, judged by the link itself: the
/// GIF services' pages and direct picture / clip files. (For a quoted
/// message whose embed isn't known here, e.g. one that was still unfurling.)
fn media_link(content: &str) -> bool {
let c = content.trim();
if !(c.starts_with("https://") || c.starts_with("http://")) || c.contains(char::is_whitespace) {
return false;
}
let rest = c.split_once("://").map_or("", |(_, r)| r);
let (host, path) = rest.split_once('/').unwrap_or((rest, ""));
let host = host.trim_start_matches("www.").to_ascii_lowercase();
let path = path.split(['?', '#']).next().unwrap_or("").to_ascii_lowercase();
let gif_page = match host.as_str() {
"tenor.com" => path.starts_with("view/") || path.contains("/view/"),
"giphy.com" => path.starts_with("gifs/") || path.starts_with("clips/"),
"klipy.com" => path.starts_with("gifs/") || path.starts_with("gif/") || path.starts_with("clips/"),
"media.tenor.com" | "c.tenor.com" | "media.giphy.com" | "i.giphy.com" | "static.klipy.com" | "i.imgur.com" => true,
h => h.starts_with("media") && h.ends_with(".giphy.com"),
};
gif_page || [".gif", ".gifv", ".png", ".jpg", ".jpeg", ".webp", ".avif"].iter().any(|e| path.ends_with(e))
}
/// What a reply's quoted line says in place of text, like Discord: nothing
/// to quote but a sticker or an attachment / media link.
fn reply_placeholder(r: &Message) -> Option<&'static str> {
if !r.content.trim().is_empty() && !link_only_media(r) && !media_link(&r.content) {
return None;
}
Some(if r.attachments.is_empty() && r.embeds.is_empty() && !r.sticker_items.is_empty() { "Click to see sticker" } else { "Click to see attachment" })
}
/// `who` is the author as the channel names them (server or friend nickname).
fn system_text(m: &Message, who: &str) -> Option<String> {
Some(match m.kind {
0 | 19 | 20 | 23 => return None,
1 => format!("{who} added someone to the group."),
2 => format!("{who} removed someone from the group."),
3 => format!("{who} started a call."),
4 => format!("{who} changed the channel name."),
5 => format!("{who} changed the channel icon."),
6 => format!("{who} pinned a message to this channel."),
7 => format!("{who} joined the server. Say hi! 👋"),
8..=11 => format!("{who} boosted the server! 🚀"),
18 | 46 | FRIEND_REQUEST_ACCEPTED => return None,
_ => {
if m.content.is_empty() {
format!("{who} did something RustCord can't display yet.")
} else {
return None;
}
}
})
}
/// How long a call lasted, the way Discord says it ("a few seconds", "5 minutes").
fn lasted(secs: i64) -> String {
let minutes = (secs as f64 / 60.0).round() as i64;
let hours = (secs as f64 / 3600.0).round() as i64;
match secs {
..=44 => "a few seconds".into(),
45..=89 => "a minute".into(),
90..=2_699 => format!("{minutes} minutes"),
2_700..=5_399 => "an hour".into(),
5_400..=79_199 => format!("{hours} hours"),
79_200..=129_599 => "a day".into(),
_ => format!("{} days", (secs as f64 / 86_400.0).round() as i64),
}
}
/// A DM call's line, and whether it is one you missed: "X started a call." while it
/// runs, then "X started a call that lasted …" or "You missed a call from X that lasted …".
fn call_text(m: &Message, who: &str, me: Option<Id>) -> (String, bool) {
let seconds = m.call.as_ref().and_then(|c| c.ended_timestamp.as_deref()).and_then(|end| {
let start = chrono::DateTime::parse_from_rfc3339(&m.timestamp).ok()?;
let end = chrono::DateTime::parse_from_rfc3339(end).ok()?;
Some((end - start).num_seconds().max(0))
});
let missed = Some(m.author.id) != me && m.call.as_ref().is_some_and(|c| me.is_some_and(|me| !c.participants.contains(&me)));
match seconds {
None => (format!("{who} started a call."), false),
Some(s) if missed => (format!("You missed a call from {who} that lasted {}.", lasted(s)), true),
Some(s) => (format!("{who} started a call that lasted {}.", lasted(s)), false),
}
}
/// `system_icon`'s kind for a missed call (no Discord message type uses it).
const MISSED_CALL: u8 = 253;
/// Discord's NEW line colour (--background-feedback-notification).
const NEW_RED: Color32 = Color32::from_rgb(210, 45, 57);
/// --brand-500, the new-messages bar.
const BRAND_500: Color32 = Color32::from_rgb(88, 101, 242);
/// Discord's ChatCheckIcon (Mark As Read), in white.
const CHAT_CHECK_SVG: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"><path fill="#fff" d="M12.66 21.98c.4-.03.56-.51.28-.8l-.06-.06a3 3 0 1 1 4.24-4.24l.53.52c.2.2.5.2.7 0l2.53-2.52a3 3 0 0 1 .64-.5c.14-.07.24-.2.27-.34a10 10 0 1 0-18.24 3.32c.13.19.11.44-.04.61l-2.06 2.37A1 1 0 0 0 2.2 22H12c.22 0 .44 0 .66-.02Z"/><path fill="#fff" d="M23.7 17.7a1 1 0 0 0-1.4-1.4L18 20.58l-2.3-2.3a1 1 0 0 0-1.4 1.42l3 3a1 1 0 0 0 1.4 0l5-5Z"/></svg>"##;
/// The red NEW line (no date on it) at `y`, across the message list.
fn new_line(ui: &Ui, y: f32) {
let r = ui.max_rect();
let right = r.right() - 14.0;
ui.painter().rect_filled(Rect::from_x_y_ranges((r.left() + 16.0)..=right, y..=y + 1.0), 0.0, NEW_RED);
new_pill(ui.painter(), right, y);
}
/// Discord's red "NEW" tag at the right end of the line at `y`: a 13 px
/// pill with an arrow-shaped cap on its left.
fn new_pill(painter: &egui::Painter, right: f32, y: f32) {
let galley = painter.layout_no_wrap("NEW".into(), FontId::new(10.0, egui::FontFamily::Name(crate::style::BOLD.into())), Color32::WHITE);
let w = 1.0 + galley.size().x + 4.0;
let pill = Rect::from_min_max(pos2(right - w, y - 7.0), pos2(right, y + 6.0));
painter.rect_filled(pill, Rounding { nw: 0.0, sw: 0.0, ne: 4.0, se: 4.0 }, NEW_RED);
// The cap: Discord's 8×13 arrow (path + its 1 px stroke).
let (x0, y0) = (pill.left() - 8.0, pill.top());
let cap = [(8.5, 0.0), (6.9, 0.3), (5.4, 1.2), (0.2, 6.5), (5.4, 11.8), (6.9, 12.7), (8.5, 13.0)];
painter.add(Shape::convex_polygon(cap.iter().map(|&(x, yy)| pos2(x0 + x, y0 + yy)).collect(), NEW_RED, Stroke::NONE));
painter.galley(pos2(pill.left() + 1.0, pill.center().y - galley.size().y / 2.0), galley, Color32::WHITE);
}
/// Where the "who reacted" lookup for a reaction is kept (a changed count
/// asks again).
fn reactors_tag(msg: Id, emoji: &ReactionEmoji, count: u32) -> String {
format!("rx:{msg}:{}:{}:{count}", emoji.id.map_or(0, |i| i.0), emoji.name.as_deref().unwrap_or(""))
}
fn local_day(ts: &str) -> Option<chrono::NaiveDate> {
chrono::DateTime::parse_from_rfc3339(ts)
.ok()
.map(|d| d.with_timezone(&chrono::Local).date_naive())
}
pub(super) fn fit(w: f32, h: f32, max_w: f32, max_h: f32) -> (f32, f32) {
let scale = (max_w / w).min(max_h / h).min(1.0);
((w * scale).max(1.0), (h * scale).max(1.0))
}
/// Discord's mention: medium weight, 3 px corners, 2 px of padding each
/// side. Blurple at 24 % (solid, white text when hovered); a role mention
/// takes the role's colour at 10 % (30 % hovered).
fn mention_chip(ui: &mut Ui, t: &crate::style::Theme, text: String, size: f32, role: Option<Color32>) -> Response {
mention_chip_with(ui, t, None, text, size, role, true)
}
/// [`mention_chip`] with an icon before the text (channel mentions), and
/// `interactive` off for mentions that do nothing when clicked (roles,
/// @everyone): those don't light up or show a hand.
fn mention_chip_with(ui: &mut Ui, t: &crate::style::Theme, glyph: Option<&str>, text: String, size: f32, role: Option<Color32>, interactive: bool) -> Response {
let fg = role.unwrap_or(if t.gradient.is_some() { Color32::from_rgb(187, 200, 255) } else { Color32::from_rgb(169, 187, 255) });
let galley = ui.painter().layout_no_wrap(text, crate::style::medium(size), fg);
// Discord's channel icon: 1 em wide, a little gap before the name.
let icon_w = if glyph.is_some() { size + 2.0 } else { 0.0 };
// (In 14 px text the chip stays inside the 18 px line.)
let h = if size < text_px() { galley.size().y.min((size * 9.0 / 7.0).round()) } else { galley.size().y };
let (rect, resp) = ui.allocate_exact_size(vec2(icon_w + galley.size().x + 4.0, h), if interactive { Sense::click() } else { Sense::hover() });
let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
let hovered = interactive && resp.hovered();
let a = |c: Color32, alpha: f32| crate::style::rgba(c.r(), c.g(), c.b(), (alpha * 255.0).round() as u8);
let (bg, fg) = match role {
Some(c) => (a(c, if hovered { 0.3 } else { 0.1 }), c),
None if hovered => (t.accent, Color32::WHITE),
None => (a(t.accent, 0.24), fg),
};
ui.painter().rect_filled(rect, 3.0, bg);
if let Some(g) = glyph {
ui.painter().text(pos2(rect.left() + 2.0 + size / 2.0, rect.center().y), Align2::CENTER_CENTER, g, icon_font(size * 0.9), fg);
}
ui.painter().galley_with_override_text_color(pos2(rect.left() + 2.0 + icon_w, rect.center().y - galley.size().y / 2.0), galley, fg);
if interactive {
resp.on_hover_cursor(CursorIcon::PointingHand)
} else {
resp
}
}
/// An emoji in a line of text. Discord's 22 px emoji sit inside the 22 px
/// line without making it taller, so the widget is only as tall as the text
/// and the picture overhangs it; jumbo emoji (emoji-only messages) take
/// their full size.
fn inline_emoji(ui: &mut Ui, url: String, text_size: f32, emoji_size: f32) -> Response {
if emoji_size > text_size * 1.5 {
return ui.add(egui::Image::new(url).fit_to_exact_size(vec2(emoji_size, emoji_size)));
}
let row_h = ui.fonts(|f| f.row_height(&FontId::proportional(text_size)));
let (rect, resp) = ui.allocate_exact_size(vec2(emoji_size, row_h.min(emoji_size)), Sense::hover());
egui::Image::new(url).paint_at(ui, Rect::from_center_size(rect.center(), vec2(emoji_size, emoji_size)));
resp
}
/// Discord's spoiler colours: (hidden, hidden + hovered, revealed).
pub(super) fn spoiler_colors(t: &crate::style::Theme) -> (Color32, Color32, Color32) {
let (mut hidden, mut hover) = (Color32::from_rgb(103, 102, 112), Color32::from_rgb(132, 133, 141));
if t.gradient.is_some() {
// A client theme mixes its dark base in (color-mix … 66 %).
hidden = hidden.lerp_to_gamma(t.overlays.color, 0.4);
hover = hover.lerp_to_gamma(t.overlays.color, 0.4);
}
(hidden, hover, crate::style::rgba(151, 151, 159, 31))
}
/// Discord's box in place of the composer on a message request: "Accept the
/// request to send a message…" with Decline / Accept DM. Some(accepted).
pub(super) fn request_bar(ui: &mut Ui, t: &crate::style::Theme) -> Option<bool> {
let mut answer = None;
Frame::none()
.fill(Color32::from_black_alpha(31))
.stroke(Stroke::new(1.0_f32, crate::style::overlay(0.2)))
.rounding(8.0)
.inner_margin(Margin::same(12.0))
.show(ui, |ui| {
ui.horizontal(|ui| {
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
ui.spacing_mut().item_spacing.x = 8.0;
let accept = Button::new(RichText::new("Accept DM").size(15.0).color(Color32::WHITE))
.fill(Color32::from_rgb(0x58, 0x65, 0xf2))
.stroke(Stroke::new(1.0_f32, crate::style::rgba(255, 255, 255, 20)))
.rounding(8.0)
.min_size(vec2(0.0, 32.0));
if ui.add(accept).clicked() {
answer = Some(true);
}
let decline = Button::new(RichText::new("Decline").size(15.0).color(t.header_primary))
.fill(crate::style::overlay(0.12))
.stroke(Stroke::new(1.0_f32, crate::style::overlay(0.04)))
.rounding(8.0)
.min_size(vec2(0.0, 32.0));
if ui.add(decline).clicked() {
answer = Some(false);
}
ui.with_layout(Layout::left_to_right(Align::Center), |ui| {
ui.add(Label::new(RichText::new("Accept the request to send a message, view attachments and use links.").size(15.0).color(t.text_muted)).wrap());
});
});
});
});
answer
}
/// A context-menu row with just a label (the message box's Cut / Copy /
/// Paste); greyed out and inert when `enabled` is false.
fn text_menu_row(ui: &mut Ui, t: &crate::style::Theme, label: &str, enabled: bool) -> Response {
super::ctx_row(ui, t, None, label, None, false, enabled)
}
/// A Discord-style context menu row: icon, label, optional submenu chevron.
fn menu_row(ui: &mut Ui, t: &crate::style::Theme, glyph: &str, label: &str, danger: bool, chevron: bool) -> Response {
super::ctx_row(ui, t, Some(glyph), label, chevron.then_some(icon::CHEVRON), danger, true)
}
/// A 32×32 icon button in the channel header toolbar.
fn header_icon(ui: &mut Ui, t: &crate::style::Theme, glyph: &str, active: bool, tip: &str) -> Response {
// Discord: 32 px buttons, 20 px icons in --text-muted (white when on / hovered).
let (r, b) = ui.allocate_exact_size(vec2(32.0, 32.0), Sense::click());
let b = b.on_hover_cursor(egui::CursorIcon::PointingHand);
let c = if active || b.hovered() { t.header_primary } else { t.text_muted };
super::paint_icon(ui.painter(), Rect::from_center_size(r.center(), vec2(20.0, 20.0)), glyph, c);
b.on_hover_text(tip)
}
fn menu_separator(ui: &mut Ui, t: &crate::style::Theme) {
super::ctx_separator(ui, t);
}
/// A pending upload: preview, name, size and a trash button that overhangs
/// the top-right corner (Serein's design).
fn upload_tile(ui: &mut Ui, t: &crate::style::Theme, u: &crate::features::PendingUpload) -> bool {
let (rect, _) = ui.allocate_exact_size(vec2(176.0, 168.0), Sense::hover());
ui.painter().rect(rect, 8.0, t.bg_secondary, Stroke::new(1.0_f32, t.bg_tertiary));
let preview = Rect::from_min_size(rect.min + vec2(8.0, 8.0), vec2(160.0, 108.0));
if let (true, discord::model::UploadData::Memory(bytes)) = (u.is_image, &u.data) {
let mut child = ui.new_child(
egui::UiBuilder::new()
.max_rect(preview)
.layout(Layout::centered_and_justified(egui::Direction::TopDown)),
);
child.add(
egui::Image::from_bytes(u.uri.clone(), egui::load::Bytes::Shared(bytes.clone()))
.max_size(preview.size())
.rounding(4.0),
);
} else {
ui.painter().rect_filled(preview, 4.0, t.bg_secondary_alt);
ui.painter().text(preview.center(), Align2::CENTER_CENTER, icon::FILE, icon_font(48.0), t.text_muted);
}
let painter = ui.painter_at(rect.shrink(8.0));
painter.text(
pos2(rect.left() + 8.0, preview.bottom() + 8.0),
Align2::LEFT_TOP,
&u.name,
egui::FontId::new(13.0, egui::FontFamily::Name(crate::style::BOLD.into())),
t.header_primary,
);
painter.text(
pos2(rect.left() + 8.0, preview.bottom() + 26.0),
Align2::LEFT_TOP,
human_size(u.size),
FontId::proportional(12.0),
t.text_muted,
);
let trash = Rect::from_min_size(pos2(rect.right() - 26.0, rect.top() - 10.0), vec2(36.0, 36.0));
let resp = ui.interact(trash, egui::Id::new(("upload_trash", &u.uri)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
let hovered = resp.hovered();
ui.painter().rect(trash, 6.0, if hovered { t.danger } else { t.bg_primary }, Stroke::new(1.0_f32, t.bg_tertiary));
ui.painter().text(trash.center(), Align2::CENTER_CENTER, icon::DELETE, icon_font(16.0), if hovered { Color32::WHITE } else { t.danger });
resp.on_hover_text("Remove attachment").clicked()
}
impl RustCord {
pub fn chat_ui(&mut self, ui: &mut Ui) {
// A thread RustCord had to fetch before opening it.
match self.api_take("open-thread") {
Some(Ok(v)) => {
self.store.upsert_channel(&v);
if let Some(id) = Id::from_value(&v["id"]) {
self.current_guild = self.store.channels.get(&id).and_then(|c| c.guild_id);
self.select_channel(Some(id));
}
}
Some(Err(e)) => self.toast(format!("Couldn't open the thread: {e}"), true),
None => {}
}
let t = self.theme.clone();
if self.current_guild.is_none() && (self.friends_open || self.current_channel.is_none()) {
if self.requests_open {
self.message_requests_ui(ui);
} else if let Some(page) = self.store_page {
match page {
crate::features::StorePage::Nitro => self.nitro_ui(ui),
crate::features::StorePage::Shop => self.shop_ui(ui),
crate::features::StorePage::Quests => self.quests_ui(ui),
}
} else {
self.friends_ui(ui);
}
return;
}
let Some(ch) = self.current_channel else {
ui.centered_and_justified(|ui| {
ui.label(RichText::new("Pick a channel to start chatting.").size(16.0).color(t.text_muted));
});
return;
};
let Some(channel) = self.store.channels.get(&ch).cloned() else { return };
let name = self.store.label(&channel);
self.message_select_input(ch);
let (mut open_pins, mut toggle_members, mut do_search, mut toggle_profile) = (false, false, false, false);
// The search box (for its list of filters) and a row picked with the keyboard.
// (Ctrl+F focuses it by this id: see shortcuts.rs.)
let search_id = egui::Id::new("chat_search_input");
let mut search_bar: Option<(Rect, Option<usize>)> = None;
let mut open_notify: Option<Rect> = None;
let (mut start_call, mut start_video, mut toggle_group_members, mut open_invite) = (false, false, false, false);
let mut open_threads: Option<Pos2> = None;
let mut go_parent: Option<Id> = None;
let is_forum = channel_kind::is_forum(channel.kind);
let is_dm = channel.kind == channel_kind::DM;
let is_group = channel.kind == channel_kind::GROUP_DM;
// Calls and adding people: DMs and group DMs with people (not Discord's system DM).
let with_people = channel.guild_id.is_none() && !channel.recipients.first().is_some_and(|u| u.system);
// Discord: "Search <server>", and in a DM the other person's username.
let place = match channel.guild_id.and_then(|g| self.store.guilds.get(&g)) {
Some(g) => g.guild.name.clone(),
None => channel.recipients.first().filter(|_| is_dm).map_or_else(|| name.clone(), |u| u.username.clone()),
};
TopBottomPanel::top("chat_header")
.exact_height(super::HEADER)
// Discord: 15 px in on the left, 8 px on the right.
.frame(Frame::none().fill(t.page(t.bg_primary)).inner_margin(Margin { left: 15.0, right: 8.0, top: 0.0, bottom: 0.0 }))
.show_inside(ui, |ui| {
ui.horizontal_centered(|ui| {
let left_w = (ui.available_width() - 420.0).max(120.0);
ui.scope(|ui| {
ui.set_max_width(left_w);
if channel.guild_id.is_some() {
let (r, _) = ui.allocate_exact_size(vec2(21.0, 24.0), Sense::hover());
let r = Rect::from_min_size(pos2(r.left(), r.top()), vec2(20.0, 24.0));
let g = super::channel_icon(channel.kind);
let g = if self.store.is_private(&channel) { super::locked_icon(g) } else { g };
super::paint_icon(ui.painter(), Rect::from_center_size(r.center(), vec2(20.0, 20.0)), g, t.channel_default);
} else {
// Discord: a 20 px avatar 16 px in, its status dot cut into
// the bottom-right corner.
ui.add_space(1.0);
let (r, _) = ui.allocate_exact_size(vec2(20.0, 24.0), Sense::hover());
let r = Rect::from_center_size(r.center(), vec2(20.0, 20.0));
let other = channel.recipients.first().filter(|_| is_dm);
paint_avatar(ui, r, other.map(|u| u.avatar_or_default(48)), &name);
if let Some(u) = other {
super::paint_status_dot(ui, r.right_bottom() - vec2(3.0, 3.0), 3.0, self.store.dot_status(u.id), t.bg_primary);
}
}
// A thread: its channel first ("resources ›"), which takes you back.
if let Some(parent) = channel.parent_id.filter(|_| channel_kind::is_thread(channel.kind)).and_then(|p| self.store.channels.get(&p)) {
let label = Label::new(RichText::new(Store::channel_label(parent)).font(crate::style::medium(16.0)).color(t.text_muted)).selectable(false).sense(Sense::click());
if ui.add(label).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
go_parent = Some(parent.id);
}
ui.add_space(4.0);
ui.label(RichText::new(icon::CHEVRON).font(icon_font(9.0)).color(t.text_muted));
ui.add_space(4.0);
}
// Name with its emoji drawn as pictures (e.g. "🧽 | queue").
let y = ui.max_rect().center().y;
let x = ui.cursor().min.x;
let painter = ui.painter().clone();
let r = super::paint_text_emoji(ui, &painter, pos2(x, y), &name, crate::style::medium(16.0), t.header_primary);
ui.allocate_exact_size(vec2(r.width(), 24.0), Sense::hover());
// A DM: the other person's activity in a pill 16 px after the
// name (Discord: 14 px icon, 4 px, 14 px medium text; 2 x 4 px
// padding, 8 px corners, shaded while hovered).
let activity = channel.recipients.first().filter(|_| is_dm).and_then(|u| self.store.presences.get(&u.id)).and_then(super::SubLine::of);
if let Some(super::SubLine::Status { activity: Some((glyph, text)), .. }) = activity {
ui.add_space(16.0);
let font = crate::style::medium(14.0);
let tw = ui.painter().layout_no_wrap(text.clone(), font.clone(), t.text_normal).size().x;
let w = (4.0 + 14.0 + 4.0 + tw + 4.0).min(ui.available_width().max(0.0));
let (pr, pb) = ui.allocate_exact_size(vec2(w, 22.0), Sense::hover());
if pb.hovered() {
ui.painter().rect_filled(pr, 8.0, t.bg_hover);
}
let clip = ui.painter().with_clip_rect(pr.intersect(ui.clip_rect()));
if !glyph.is_empty() {
clip.text(pos2(pr.left() + 11.0, pr.center().y), Align2::CENTER_CENTER, glyph, icon_font(14.0), t.text_normal);
}
clip.text(pos2(pr.left() + 22.0, pr.center().y), Align2::LEFT_CENTER, &text, font, t.text_normal);
}
if let Some(topic) = channel.topic.as_deref().filter(|s| !s.is_empty()) {
ui.add_space(6.0);
ui.label(RichText::new("|").color(t.channel_default));
ui.add(Label::new(RichText::new(topic).size(13.0).color(t.text_muted)).truncate());
}
});
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
ui.spacing_mut().item_spacing.x = 8.0;
// Search box: Discord's 244 × 32, a hairline border on the
// surface, 14 px medium placeholder, magnifier on the right.
let (sr, _) = ui.allocate_exact_size(vec2(244.0, 32.0), Sense::hover());
ui.painter().rect_stroke(sr, 8.0, Stroke::new(1.0_f32, crate::style::rgba(145, 145, 150, 51)));
let icon_r = Rect::from_min_size(pos2(sr.right() - 25.0, sr.top() + 4.0), vec2(24.0, 24.0));
ui.painter().text(icon_r.center(), Align2::CENTER_CENTER, icon::SEARCH, icon_font(14.0), t.interactive_normal);
let text_r = Rect::from_min_max(pos2(sr.left() + 7.0, sr.top() + 1.0), pos2(icon_r.left() - 2.0, sr.bottom() - 1.0));
// "Search A Long Server Na…": cut to fit, like Discord.
let hint_color = Color32::from_rgb(166, 166, 174);
let mut hint = format!("Search {place}");
let fits = |s: &str| ui.painter().layout_no_wrap(s.to_string(), crate::style::medium(14.0), hint_color).size().x <= text_r.width() - 2.0;
if !fits(&hint) {
while hint.chars().count() > 8 && !fits(&format!("{hint}…")) {
hint.pop();
}
hint = format!("{}…", hint.trim_end());
}
let key_pick = self.search_keys(ui.ctx(), search_id);
let search = ui.put(
text_r,
TextEdit::singleline(&mut self.search_input)
.id(search_id)
.frame(false)
.font(crate::style::medium(14.0))
.hint_text(RichText::new(hint).font(crate::style::medium(14.0)).color(hint_color))
.desired_width(text_r.width())
.vertical_align(Align::Center)
.margin(vec2(0.0, 0.0)),
);
ui.add_space(4.0);
do_search = search.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter)) && !self.search_input.trim().is_empty();
search_bar = Some((sr, key_pick));
if channel.guild_id.is_some() {
let r = header_icon(ui, &t, icon::PEOPLE, self.show_members, if self.show_members { "Hide Member List" } else { "Show Member List" });
toggle_members = r.clicked();
} else if is_group {
let on = self.show_group_members;
toggle_group_members = header_icon(ui, &t, icon::PEOPLE, on, if on { "Hide Member List" } else { "Show Member List" }).clicked();
} else if is_dm {
// Discord offers the profile panel only in a window at
// least 1132 px wide (greyed out, "(Unavailable)", below).
if super::dm_profile_fits(ui.ctx()) {
let on = self.show_dm_profile;
let r = header_icon(ui, &t, icon::USER_CIRCLE, on, if on { "Hide User Profile" } else { "Show User Profile" });
toggle_profile = r.clicked();
} else {
let (r, b) = ui.allocate_exact_size(vec2(32.0, 32.0), Sense::hover());
super::paint_icon(ui.painter(), Rect::from_center_size(r.center(), vec2(20.0, 20.0)), icon::USER_CIRCLE, t.text_muted.gamma_multiply(0.5));
b.on_hover_text("Show User Profile (Unavailable)");
}
}
// Discord: "Invite to Group DM", or in a DM "Add Friends to DM"
// (a new group with them); not with bots.
if with_people && (is_group || channel.recipients.first().is_some_and(|u| !u.bot)) {
let tip = if is_group { "Invite to Group DM" } else { "Add Friends to DM" };
open_invite = header_icon(ui, &t, icon::GROUP_PLUS, self.group_invite_open(ch), tip).clicked();
}
// (A forum has posts, not messages: nothing to pin.)
if !is_forum {
let r = header_icon(ui, &t, icon::PIN, self.pins.is_some(), "Pinned Messages");
// Where the pins popout hangs (also when a pin notice opens it).
ui.ctx().data_mut(|d| d.insert_temp(super::members::pins_button_id(), r.rect));
open_pins = r.clicked();
}
// DMs and group DMs: Discord's "Start Video Call" and "Start
// Voice Call" (joins the call; Discord rings the others). The
// camera is Windows-only in RustCord so far.
if with_people {
let in_call = self.voice.as_ref().is_some_and(|v| v.channel == ch);
if cfg!(windows) {
let filming = in_call && self.camera.on.is_some();
start_video = header_icon(ui, &t, crate::camera::CAMERA, filming, "Start Video Call").clicked();
}
start_call = header_icon(ui, &t, icon::PHONE_CALL, in_call, if in_call { "Show Call" } else { "Start Voice Call" }).clicked();
}
// Discord's bell: mute the channel, or change its notifications.
if channel.guild_id.is_some() {
let kind = super::voice_menu::VoiceMenuKind::Notify(ch);
let muted = self.store.muted_channels.contains(&ch);
let r = header_icon(ui, &t, if muted { icon::BELL_SLASH } else { icon::BELL }, self.voice_menu_open(kind), "Notification Settings");
if r.clicked() {
open_notify = Some(r.rect);
}
// (Right to left: Threads sits before the bell.)
if !channel_kind::is_thread(channel.kind) && !is_forum {
let r = header_icon(ui, &t, icon::THREADS, self.threads_popout.is_some(), "Threads");
if r.clicked() {
open_threads = Some(r.rect.right_bottom() + vec2(0.0, 8.0));
}
}
}
});
});
});
if let Some(rect) = open_notify {
self.toggle_voice_menu(super::voice_menu::VoiceMenuKind::Notify(ch), rect);
}
if toggle_members {
self.show_members = !self.show_members;
}
if toggle_group_members {
self.show_group_members = !self.show_group_members;
}
if open_invite {
if self.group_invite_open(ch) {
self.group_invite = None;
} else {
self.open_group_invite(ch);
}
}
if start_video {
self.start_dm_video_call(ch);
}
if let Some(parent) = go_parent {
self.select_channel(Some(parent));
return;
}
if start_call {
self.start_dm_call(ch);
}
if let Some(at) = open_threads {
self.threads_popout = match self.threads_popout.take() {
Some(_) => None,
None => Some((ch, at, self.ctx.cumulative_pass_nr())),
};
}
if toggle_profile {
self.show_dm_profile = !self.show_dm_profile;
}
if open_pins {
if self.pins.as_ref().is_some_and(|p| p.0 == ch) {
self.pins = None;
} else {
self.open_pins(ch);
}
}
if let Some((bar, key_pick)) = search_bar {
self.search_suggest_ui(ui.ctx(), bar, ch, search_id, key_pick);
}
if do_search {
let query = self.search_input.trim().to_string();
match self.search_query(ch, &query) {
Ok(filters) => {
self.search = Some((query.clone(), None));
self.backend.send(crate::backend::Command::Search { guild: channel.guild_id, channel: ch, query, filters });
}
// A name or date it couldn't make out: said in the results panel.
Err(e) => self.search = Some((query, Some(Err(e)))),
}
}
// Member list / DM profile: under the header, right of the chat and composer.
self.chat_side_panel(ui);
// A call in this DM: Discord's call area above the messages.
if channel.guild_id.is_none() && self.dm_call_visible(ch) {
let watching = self.voice.as_ref().is_some_and(|v| v.channel == ch) && self.watching.iter().any(|w| w.channel == ch);
let height = if watching {
let max_h = (ui.available_height() - 150.0).max(320.0);
(ui.available_height() * 0.68).clamp(320.0, max_h)
} else if self.dm_call_has_video(ch) {
(ui.available_height() * 0.50).clamp(260.0, 380.0)
} else {
(ui.available_height() * 0.42).clamp(200.0, 300.0)
};
TopBottomPanel::top("dm_call_area")
.show_separator_line(false)
.exact_height(height)
.frame(Frame::none().fill(Color32::BLACK))
.show_inside(ui, |ui| self.dm_call_panel(ui, ch));
}
// Forum and media channels: their posts.
if channel_kind::is_forum(channel.kind) {
self.forum_ui(ui, &channel);
return;
}
if !channel_kind::is_text(channel.kind) {
CentralPanel::default().frame(Frame::none().fill(t.page(t.bg_primary))).show_inside(ui, |ui| {
ui.centered_and_justified(|ui| {
let what = if channel_kind::is_voice(channel.kind) { "Voice channels aren't" } else { "This kind of channel isn't" };
ui.label(RichText::new(format!("{what} supported in RustCord yet.")).size(16.0).color(t.text_muted));
});
});
return;
}
self.ensure_loaded(ch);
let system_dm = channel.kind == channel_kind::DM && channel.recipients.first().is_some_and(|u| u.system);
if channel.is_message_request {
// A message request: accept or decline before you can reply.
let mut answer = None;
TopBottomPanel::bottom("request_bar")
.show_separator_line(false)
.frame(Frame::none().fill(t.page(t.bg_primary)).inner_margin(Margin { left: 16.0, right: 16.0, top: 4.0, bottom: 16.0 }))
.show_inside(ui, |ui| answer = request_bar(ui, &t));
if let Some(accept) = answer {
self.answer_request(ch, accept);
return;
}
} else if system_dm {
// Discord's official-notifications DM can't be replied to.
TopBottomPanel::bottom("system_notice")
.show_separator_line(false)
.frame(Frame::none().fill(t.page(t.bg_primary)).inner_margin(Margin { left: 16.0, right: 16.0, top: 4.0, bottom: 12.0 }))
.show_inside(ui, |ui| {
Frame::none()
.fill(t.input_bg)
.stroke(Stroke::new(1.0_f32, t.border_subtle))
.rounding(8.0)
.inner_margin(Margin::symmetric(14.0, 10.0))
.show(ui, |ui| {
ui.horizontal(|ui| {
ui.label(RichText::new(icon::SHIELD).font(icon_font(24.0)).color(t.interactive_normal));
ui.vertical(|ui| {
ui.label(bold("This chat is reserved for official Discord notifications.").size(14.0).color(t.header_primary));
ui.label(RichText::new("Discord will never ask you for your password or account token.").size(12.0).color(t.text_muted));
});
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if ui.add(Button::new(bold("Learn More").size(13.0).color(t.header_primary)).fill(t.surface_high)).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
ui.ctx().open_url(egui::OpenUrl::new_tab("https://support.discord.com/hc/en-us/articles/360036118732"));
}
});
});
});
});
} else if !self.store.can_send(&channel) {
// Discord's locked box instead of the composer.
TopBottomPanel::bottom("no_permission")
.show_separator_line(false)
.frame(Frame::none().fill(t.page(t.bg_primary)).inner_margin(Margin { left: 16.0, right: 16.0, top: 2.0, bottom: 24.0 }))
.show_inside(ui, |ui| {
let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), 52.0), Sense::hover());
ui.painter().rect(rect, 8.0, t.input_bg, Stroke::new(1.0_f32, t.border_subtle));
ui.painter().text(
pos2(rect.left() + 16.0, rect.center().y),
Align2::LEFT_CENTER,
"You do not have permission to send messages in this channel.",
egui::FontId::proportional(15.0),
t.text_muted,
);
});
} else {
TopBottomPanel::bottom("composer")
.show_separator_line(false)
// Discord: the box 8 px from the sides and the bottom.
.frame(Frame::none().fill(t.page(t.bg_primary)).inner_margin(Margin { left: 8.0, right: 8.0, top: 2.0, bottom: 8.0 }))
.show_inside(ui, |ui| {
super::gray_text(ui, true);
self.composer(ui, ch, &channel, &name);
super::gray_text(ui, false);
});
}
CentralPanel::default().frame(Frame::none().fill(t.page(t.bg_primary))).show_inside(ui, |ui| {
let mut actions = Vec::new();
let mut editing = self.editing.take();
super::gray_text(ui, true);
self.message_list(ui, &channel, &name, &mut editing, &mut actions);
super::gray_text(ui, false);
self.editing = editing;
for a in actions {
self.apply_action(a);
}
});
}
/// A voice channel's text chat beside the call (Discord's chat bubble):
/// header with ×, the messages, and the message box. Returns true when
/// it should close.
pub(super) fn voice_chat_panel(&mut self, ui: &mut Ui, ch: Id) -> bool {
let t = self.theme.clone();
let Some(channel) = self.store.channels.get(&ch).cloned() else { return true };
let name = self.store.label(&channel);
let mut close = false;
ui.painter().rect_filled(ui.max_rect(), 0.0, t.bg_primary);
TopBottomPanel::top("vc_chat_header")
.exact_height(44.0)
.frame(Frame::none().fill(t.page(t.bg_primary)).inner_margin(Margin::symmetric(14.0, 0.0)))
.show_inside(ui, |ui| {
ui.horizontal_centered(|ui| {
ui.label(RichText::new(icon::MESSAGE).font(icon_font(16.0)).color(t.interactive_normal));
ui.add(Label::new(bold(&name).size(15.0).color(t.header_primary)).truncate());
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
let (r, resp) = ui.allocate_exact_size(vec2(28.0, 28.0), Sense::click());
let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
if resp.hovered() {
ui.painter().rect_filled(r, 6.0, t.bg_hover);
}
ui.painter().text(r.center(), Align2::CENTER_CENTER, icon::CLOSE, icon_font(12.0), t.interactive_normal);
close = resp.on_hover_text("Close Chat").clicked();
});
});
});
self.ensure_loaded(ch);
if self.store.can_send(&channel) {
TopBottomPanel::bottom("vc_chat_composer")
.show_separator_line(false)
.frame(Frame::none().fill(t.page(t.bg_primary)).inner_margin(Margin { left: 10.0, right: 10.0, top: 2.0, bottom: 8.0 }))
.show_inside(ui, |ui| {
super::gray_text(ui, true);
self.composer(ui, ch, &channel, &name);
super::gray_text(ui, false);
});
}
CentralPanel::default().frame(Frame::none().fill(t.page(t.bg_primary))).show_inside(ui, |ui| {
let mut actions = Vec::new();
let mut editing = self.editing.take();
super::gray_text(ui, true);
self.message_list(ui, &channel, &name, &mut editing, &mut actions);
super::gray_text(ui, false);
self.editing = editing;
for a in actions {
self.apply_action(a);
}
});
close
}
/// Rencord's MessageSelect, before the chat is drawn: whether Ctrl/Cmd + Shift
/// is picking messages, and Ctrl/Cmd + C / Esc on the picked ones.
fn message_select_input(&mut self, ch: Id) {
let Some(plugin) = self.rencord.enabled(rencord::plugins::message_select::ID) else {
self.picking = false;
self.picked_msgs.1.clear();
return;
};
if self.picked_msgs.0 != ch {
self.picked_msgs = (ch, Default::default());
}
self.picking = self.ctx.input(|i| i.modifiers.command && i.modifiers.shift && !i.modifiers.alt);
if self.picked_msgs.1.is_empty() {
return;
}
// Taken out of the input, so a text selection or the message box
// doesn't copy over RustCord's.
let (copy, clear) = self.ctx.input_mut(|i| {
let before = i.events.len();
i.events.retain(|e| !matches!(e, egui::Event::Copy));
(i.events.len() != before, i.key_pressed(Key::Escape))
});
if copy {
let picked: Vec<(String, String)> = self
.store
.messages
.get(&ch)
.map(|cm| {
cm.list
.iter()
.filter(|m| self.picked_msgs.1.contains(&m.id))
.map(|m| {
let mut text = if m.content.is_empty() { system_text(m, &self.author_name(m)).unwrap_or_default() } else { m.content.clone() };
for a in &m.attachments {
if !text.is_empty() {
text.push('\n');
}
text.push_str(&a.url);
}
(self.author_name(m), text)
})
.collect()
})
.unwrap_or_default();
let n = picked.len();
self.ctx.copy_text(rencord::plugins::message_select::format(&plugin.settings, picked.iter().map(|(a, t)| (a.as_str(), t.as_str()))));
self.toast(format!("Copied {n} message{}", if n == 1 { "" } else { "s" }), false);
}
if copy || clear {
self.picked_msgs.1.clear();
}
}
pub(super) fn apply_action(&mut self, action: UiAction) {
match action {
UiAction::OpenContext { channel, msg, pos } => {
super::claim_menu_media(&self.ctx);
self.context_menu = Some(ContextMenu { channel, msg, pos, opened_frame: self.ctx.cumulative_pass_nr() })
}
UiAction::Reveal(id, k) => {
self.revealed.insert((id, k));
}
UiAction::LoadOlder(ch) => self.load_older(ch),
UiAction::PickMessage { channel, msg } => {
if self.picked_msgs.0 != channel {
self.picked_msgs = (channel, Default::default());
}
if !self.picked_msgs.1.remove(&msg) {
self.picked_msgs.1.insert(msg);
}
}
UiAction::Relationship { user, add } => self.relationship(user, add, "DM Channel"),
UiAction::Block(user) => self.api("block-user", reqwest::Method::PUT, format!("/users/@me/relationships/{user}"), Some(serde_json::json!({ "type": 2 }))),
UiAction::Retry(ch) => self.retry_load(ch),
UiAction::SaveEdit => self.save_edit(),
UiAction::CancelEdit => self.editing = None,
UiAction::JumpTo { channel, msg } => self.jump_to_message(channel, msg, 0),
UiAction::OpenPins(ch) => self.open_pins(ch),
UiAction::Wave(ch) => {
let tag = format!("greet:{ch}");
if self.dev_wave.is_some() {
self.toast("Wave (test): nothing sent.", false);
} else if !self.api_pending.contains(&tag) {
self.api(&tag, reqwest::Method::POST, format!("/channels/{ch}/greet"), Some(serde_json::json!({ "sticker_ids": [WAVE_STICKER.to_string()] })));
}
}
UiAction::JumpToNew(ch) => {
let Some(n) = self.new_since.filter(|n| n.channel == ch) else { return };
self.new_since = Some(crate::app::NewSince { bar: false, ..n });
let me = self.store.me_id();
// The first message you missed; if that's older than what's
// loaded, the last one you read (older pages load until it is).
let first = self.store.messages.get(&ch).and_then(|cm| {
let more = cm.has_more && cm.list.first().is_some_and(|m| m.id > n.last_read);
(!more).then(|| cm.list.iter().find(|m| m.id > n.last_read && Some(m.author.id) != me).map(|m| m.id)).flatten()
});
self.jump_to_message(ch, first.unwrap_or(n.last_read), 0);
}
UiAction::MarkRead(ch) => self.mark_channel_read(ch),
UiAction::HideNewBar(ch) => {
if let Some(n) = self.new_since.as_mut().filter(|n| n.channel == ch) {
n.bar = false;
}
}
UiAction::OpenThread(id) => {
if let Some(c) = self.store.channels.get(&id) {
self.current_guild = c.guild_id;
self.select_channel(Some(id));
} else {
self.api("open-thread", reqwest::Method::GET, format!("/channels/{id}"), None);
}
}
UiAction::SelectChannel(ch) => {
if let Some(c) = self.store.channels.get(&ch) {
self.current_guild = c.guild_id;
self.select_channel(Some(ch));
}
}
UiAction::React { channel, msg, emoji } => {
if let Some(name) = emoji.name.as_deref().filter(|_| emoji.id.is_none()) {
self.use_emoji(name);
}
self.toggle_reaction(channel, msg, emoji)
}
UiAction::Reply { channel, msg } => self.start_reply(channel, msg),
UiAction::StartEdit { channel, msg } => self.start_edit(channel, msg),
UiAction::Forward { channel, msg } => self.start_forward(channel, msg),
UiAction::AudioToggle(url) => self.audio_toggle(&url),
UiAction::AudioSeek(url, f) => self.audio.seek(&url, f),
UiAction::AudioMute => self.audio.toggle_mute(),
UiAction::VideoToggle(url) => match self.video_player.as_mut().filter(|p| p.url == url) {
Some(p) => p.toggle(),
None => {
// One thing plays at a time, like Discord.
if let Some(v) = &mut self.embed_view {
v.stop();
}
self.video_channel = self.current_channel;
self.video_player = Some(crate::video_player::VideoPlayer::start(&self.ctx, url, false));
}
},
UiAction::VideoSeek(url, f) => {
if let Some(p) = self.video_player.as_mut().filter(|p| p.url == url) {
p.seek(f);
}
}
UiAction::VideoMute => {
if let Some(p) = &mut self.video_player {
p.toggle_mute();
}
}
UiAction::VideoFullscreen => {
if let Some(p) = &mut self.video_player {
p.fullscreen = !p.fullscreen;
}
}
UiAction::PlayEmbed { key, channel, src, bg } => {
// (The webview is kept: the new player loads in it.)
if let Some(v) = &mut self.embed_view {
v.stop();
}
self.video_player = None;
self.embed_request = Some(crate::app::EmbedRequest { key, channel, src, bg, at: std::time::Instant::now() });
}
UiAction::SuppressEmbeds { channel, msg } => {
// Discord asks first (unless Shift is held): here, a second click.
let armed = self.suppress_armed.is_some_and(|(id, at)| id == msg && at.elapsed().as_secs() < 5);
if armed || self.ctx.input(|i| i.modifiers.shift) {
self.suppress_armed = None;
let flags = self.store.messages.get(&channel).and_then(|l| l.list.iter().find(|m| m.id == msg)).map_or(0, |m| m.flags);
self.api("suppress_embeds", reqwest::Method::PATCH, format!("/channels/{channel}/messages/{msg}"), Some(serde_json::json!({ "flags": flags | 4 })));
} else {
self.suppress_armed = Some((msg, std::time::Instant::now()));
self.toast("Click ✕ again to remove all embeds from this message for everyone.", false);
}
}
UiAction::OpenReactions { channel, msg, emoji } => self.open_reactions(channel, msg, Some(&emoji)),
UiAction::FetchReactors { channel, msg, emoji, count } => {
let tag = reactors_tag(msg, &emoji, count);
let name = emoji.name.clone().unwrap_or_default();
let spec = match emoji.id {
Some(id) => format!("{name}:{id}"),
None => name,
};
let spec: String = url::form_urlencoded::byte_serialize(spec.as_bytes()).collect();
self.api_get_once(&tag, format!("/channels/{channel}/messages/{msg}/reactions/{spec}?limit=3&type=0"));
}
UiAction::UseCommand(name) => {
if let Some(ch) = self.current_channel {
self.drafts.insert(ch, format!("/{name}"));
self.compose.focus_composer = true;
}
}
UiAction::OpenUrl(url) => self.ctx.open_url(egui::OpenUrl::new_tab(url)),
UiAction::PollVote { channel, msg, answers } => self.vote_poll(channel, msg, answers),
UiAction::AutoMod { guild, clear_raid: true } => {
self.api("automod_clear_raid", reqwest::Method::POST, format!("/guilds/{guild}/auto-moderation/clear-mention-raid"), None);
self.toast("Removing the restrictions…", false);
}
UiAction::AutoMod { guild, clear_raid: false } => self.open_server_settings(guild),
UiAction::Interact { channel, msg, component_type, custom_id, values } => self.start_interaction(channel, msg, component_type, custom_id, values),
UiAction::ToggleSelect { msg, custom_id } => {
let key = Some((msg, custom_id));
self.open_select = if self.open_select == key { None } else { key };
}
UiAction::Dismiss { channel, msg } => {
self.store.remove_message(channel, msg);
}
UiAction::OpenPicker { channel, msg, pos } => self.open_emoji_picker(PickerTarget::React { channel, msg }, pos),
UiAction::MemberMenu { guild, user, pos } => self.open_member_menu(guild, *user, pos),
UiAction::OpenProfile { user, guild, pos } => {
// Clicking the same person again closes it, like Discord.
if self.profile.as_ref().is_some_and(|p| p.user.id == user.id) {
self.profile = None;
} else {
self.open_profile(*user, guild, pos);
}
}
UiAction::View(v) => self.viewer = Some(v),
UiAction::OpenTag { guild, pos } => self.open_tag_popout(guild, pos),
UiAction::OpenSticker { sticker, channel, message, anchor } => self.open_sticker_popout(sticker, channel, message, anchor),
}
}
// ---- message list ---------------------------------------------------
/// The start of a DM, as Discord shows it: avatar, name, username, "This is the
/// beginning…", then mutual servers and Add Friend / Block.
fn dm_welcome(&self, ui: &mut Ui, channel: &Channel, name: &str, actions: &mut Vec<UiAction>) {
let t = &self.theme;
let user = channel.recipients.first();
ui.add_space(16.0);
ui.horizontal(|ui| {
ui.add_space(16.0);
ui.vertical(|ui| {
ui.spacing_mut().item_spacing.y = 0.0;
let (rect, _) = ui.allocate_exact_size(vec2(80.0, 80.0), Sense::hover());
paint_avatar(ui, rect, user.map(|u| u.avatar_or_default(160)), name);
ui.add_space(8.0);
ui.label(bold(name).size(32.0).color(t.header_primary));
if let Some(u) = user {
ui.add_space(4.0);
ui.label(RichText::new(&u.username).font(crate::style::medium(24.0)).color(t.header_primary));
}
ui.add_space(14.0);
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing.x = 0.0;
ui.label(RichText::new("This is the beginning of your direct message history with ").size(text_px()).color(t.header_primary));
ui.label(bold(name).size(text_px()).color(t.header_primary));
ui.label(RichText::new(".").size(text_px()).color(t.header_primary));
});
let Some(u) = user.filter(|u| !u.system) else { return };
ui.add_space(10.0);
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 8.0;
ui.spacing_mut().button_padding = vec2(12.0, 4.0);
// Mutual servers: up to three icons and the count, or "No servers in
// common", then Discord's divider dot (4 px, --border-strong, 4 px
// either side of it).
self.profiles_wanted.borrow_mut().push((u.id, None));
let profile = self.profiles.get(&(u.id, None)).and_then(|r| r.as_ref().ok());
let mutual = profile.map(|p| p.mutual_guilds.clone()).unwrap_or_default();
let divider = |ui: &mut Ui| {
let (d, _) = ui.allocate_exact_size(vec2(12.0, 32.0), Sense::hover());
ui.painter().circle_filled(d.center(), 2.0, crate::style::rgba(151, 151, 159, 112));
};
if mutual.is_empty() && profile.is_some() {
let g = ui.painter().layout_no_wrap("No servers in common".into(), FontId::proportional(14.0), t.text_normal);
let (r, _) = ui.allocate_exact_size(vec2(g.size().x, 32.0), Sense::hover());
ui.painter().galley(pos2(r.left(), r.center().y - g.size().y / 2.0), g, t.text_normal);
divider(ui);
}
if !mutual.is_empty() {
let icons: Vec<(Option<String>, String)> =
mutual.iter().filter_map(|m| self.store.guilds.get(&m.id)).take(3).map(|g| (g.guild.icon_url(64), g.guild.name.clone())).collect();
let label = format!("{} Mutual Server{}", mutual.len(), if mutual.len() == 1 { "" } else { "s" });
let galley = ui.painter().layout_no_wrap(label, FontId::proportional(14.0), t.header_secondary);
let icons_w = if icons.is_empty() { 0.0 } else { 24.0 + (icons.len() - 1) as f32 * 18.0 + 6.0 };
let (r, resp) = ui.allocate_exact_size(vec2(icons_w + galley.size().x, 32.0), Sense::click());
for (i, (url, guild)) in icons.iter().enumerate() {
let a = Rect::from_min_size(pos2(r.left() + i as f32 * 18.0, r.center().y - 12.0), vec2(24.0, 24.0));
paint_avatar(ui, a, url.clone(), guild);
}
let pos = pos2(r.left() + icons_w, r.center().y - galley.size().y / 2.0);
let text = Rect::from_min_size(pos, galley.size());
ui.painter().galley(pos, galley, t.header_secondary);
if resp.hovered() {
ui.painter().hline(text.x_range(), text.bottom() - 1.0, Stroke::new(1.0_f32, t.header_secondary));
}
if resp.on_hover_cursor(CursorIcon::PointingHand).clicked() {
actions.push(UiAction::OpenProfile { user: Box::new(u.clone()), guild: None, pos: r.right_top() });
}
divider(ui);
}
// Friendship: 1 friend, 2 blocked, 3 incoming request, 4 outgoing.
let relation = self.store.relationships.get(&u.id).map(|r| r.kind);
let small = |label: &str, fill: Color32| Button::new(RichText::new(label).font(crate::style::medium(14.0)).color(Color32::WHITE)).fill(fill).rounding(8.0).min_size(vec2(0.0, 32.0));
let brand = Color32::from_rgb(88, 101, 242);
let grey = crate::style::rgba(151, 151, 159, 31);
match relation {
Some(1) => {
if ui.add(small("Remove Friend", grey)).clicked() {
actions.push(UiAction::Relationship { user: u.id, add: false });
}
}
Some(2) => {}
Some(3) => {
if ui.add(small("Accept", brand)).clicked() {
actions.push(UiAction::Relationship { user: u.id, add: true });
}
}
Some(4) => {
ui.add_enabled(false, small("Friend Request Sent", brand));
}
_ => {
if ui.add(small("Add Friend", brand)).clicked() {
actions.push(UiAction::Relationship { user: u.id, add: true });
}
}
}
if relation == Some(2) {
if ui.add(small("Unblock", grey)).clicked() {
actions.push(UiAction::Relationship { user: u.id, add: false });
}
} else {
// Blocking asks twice (Discord asks in a dialog).
let sure_id = egui::Id::new(("dm_block_sure", u.id.0));
let now = ui.input(|i| i.time);
let sure = ui.data(|d| d.get_temp::<f64>(sure_id)).is_some_and(|at| now - at < 4.0);
if ui.add(small(if sure { "Click again to block" } else { "Block" }, if sure { t.danger } else { grey })).clicked() {
if sure {
ui.data_mut(|d| d.remove::<f64>(sure_id));
actions.push(UiAction::Block(u.id));
} else {
ui.data_mut(|d| d.insert_temp(sure_id, now));
}
}
}
});
});
});
ui.add_space(12.0);
}
/// Whether a DM gets Discord's "Wave to …" under its messages, and in which
/// form (`true`: the small pill, once they've written something). Discord's
/// rule: a one-to-one DM (no bots, not Discord's system account, not a
/// message request, not someone you blocked) whose history is short (all of
/// it loaded and under 25 messages, or flagged as only system messages)
/// and where you haven't written anything yet besides accepting the request.
fn wave_state(&self, channel: &Channel, cm: &crate::store::ChannelMessages) -> Option<bool> {
if let Some((_, compact)) = self.dev_wave.filter(|w| w.0 == channel.id) {
return Some(compact);
}
if channel.kind != channel_kind::DM || channel.is_message_request || !cm.loaded {
return None;
}
let other = channel.recipients.first()?;
if other.system || channel.recipients.iter().any(|u| u.bot) || self.store.relationships.get(&other.id).is_some_and(|r| r.kind == 2) {
return None;
}
let short = channel.flags & HAS_ONLY_SYSTEM_MESSAGES != 0 || (!cm.has_more && cm.list.len() < 25);
let me = self.store.me_id()?;
if !short || cm.list.iter().any(|m| m.author.id == me && m.kind != FRIEND_REQUEST_ACCEPTED) {
return None;
}
Some(cm.list.iter().any(|m| m.author.id != me && !m.meta.pending && !m.meta.failed && !is_system(m)))
}
/// Discord's "👋 Wave" on a DM's row in the list (in place of its ✕): a
/// DM under 21 days old with a friend you don't ignore, holding nothing
/// yet (or only the accepted friend request), and nothing written by you.
pub(super) fn dm_row_wave(&self, c: &Channel) -> bool {
if self.dev_wave.is_some_and(|w| w.0 == c.id) {
return true;
}
if c.kind != channel_kind::DM {
return false;
}
let Some(other) = c.recipients.first() else { return false };
if other.system || c.recipients.iter().any(|u| u.bot) || !self.store.relationships.get(&other.id).is_some_and(|r| r.kind == 1 && !r.user_ignored) {
return false;
}
let now = chrono::Utc::now().timestamp_millis().max(0) as u64;
if now.saturating_sub(c.id.timestamp_ms()) > 21 * 24 * 3_600_000 {
return false;
}
let msgs = self.store.messages.get(&c.id).map(|cm| cm.list.as_slice()).unwrap_or(&[]);
let quiet = c.flags & HAS_ONLY_SYSTEM_MESSAGES != 0 || c.last_message_id.is_none() || (msgs.len() == 1 && msgs[0].kind == FRIEND_REQUEST_ACCEPTED);
let me = self.store.me_id();
quiet && !msgs.iter().any(|m| Some(m.author.id) == me && m.kind != FRIEND_REQUEST_ACCEPTED)
}
/// Discord's "Wave to …" (measured 2026-11-23). Before they've written:
/// a 232 px column 20 px in, the 160 px wave sticker, 24 px, then a 40 px
/// brand button across it. After: a pill 16 px in (12 px padding, a 24 px
/// sticker, the 16 px medium label 8 px either side) on --background-base-lowest,
/// --background-mod-normal when hovered. Both 20 px under the last message.
fn wave_prompt(&self, ui: &mut Ui, channel: &Channel, compact: bool, actions: &mut Vec<UiAction>) {
let t = &self.theme;
let ch = channel.id;
let tag = format!("greet:{ch}");
let busy = self.api_pending.contains(&tag);
let error = self.api_results.get(&tag).and_then(|r| r.as_ref().err());
let name = if channel.recipients.is_empty() { "your mate".to_string() } else { self.store.label(channel) };
let label = format!("Wave to {name}");
let font = crate::style::medium(16.0);
// Discord's "Play sticker animations": 0 always, 1 on hover, 2 never.
let sticker_anim = super::sticker_animation();
ui.add_space(20.0);
let left = ui.max_rect().left();
let clicked;
if compact {
let g = ui.painter().layout_no_wrap(label, font, t.header_primary);
let w = 12.0 + 24.0 + 8.0 + g.size().x + 8.0 + 12.0;
let (row, _) = ui.allocate_exact_size(vec2(ui.available_width(), 48.0), Sense::hover());
let pill = Rect::from_min_size(pos2(left + 16.0, row.top()), vec2(w, 48.0));
let resp = ui.interact(pill, egui::Id::new(("wave_pill", ch.0)), Sense::click());
let resp = if busy { resp } else { resp.on_hover_cursor(CursorIcon::PointingHand) };
ui.painter().rect_filled(pill, 24.0, if resp.hovered() && !busy { t.bg_selected } else { t.bg_tertiary });
let s = Rect::from_min_size(pos2(pill.left() + 12.0, pill.top() + 12.0), vec2(24.0, 24.0));
super::expression::paint_sticker(ui, s, WAVE_STICKER, 3, sticker_anim == 0 || (sticker_anim == 1 && resp.hovered()), None);
ui.painter().galley(pos2(s.right() + 8.0, pill.center().y - g.size().y / 2.0), g, t.header_primary);
clicked = resp.clicked();
} else {
let (col, _) = ui.allocate_exact_size(vec2(ui.available_width(), 160.0 + 24.0 + 40.0), Sense::hover());
let x0 = left + 20.0;
let s = Rect::from_min_size(pos2(x0 + (232.0 - 160.0) / 2.0, col.top()), vec2(160.0, 160.0));
let b = Rect::from_min_size(pos2(x0, s.bottom() + 24.0), vec2(232.0, 40.0));
let resp = ui.interact(b, egui::Id::new(("wave_button", ch.0)), Sense::click());
let resp = if busy { resp } else { resp.on_hover_cursor(CursorIcon::PointingHand) };
let sticker_hover = ui.rect_contains_pointer(s);
super::expression::paint_sticker(ui, s, WAVE_STICKER, 3, sticker_anim == 0 || (sticker_anim == 1 && sticker_hover), None);
let brand = Color32::from_rgb(0x58, 0x65, 0xf2);
let fill = if busy { brand.gamma_multiply(0.5) } else if resp.hovered() { Color32::from_rgb(0x47, 0x52, 0xc4) } else { brand };
ui.painter().rect(b, 8.0, fill, Stroke::new(1.0_f32, crate::style::rgba(255, 255, 255, 20)));
ui.painter().text(b.center(), Align2::CENTER_CENTER, label, font, Color32::WHITE);
clicked = resp.clicked();
}
if let Some(e) = error {
ui.add_space(8.0);
ui.horizontal(|ui| {
ui.add_space(if compact { 16.0 } else { 20.0 });
ui.label(RichText::new(e).size(14.0).color(t.danger));
});
}
// (The pill has no margin under it; the big one has 20 px.)
if !compact {
ui.add_space(20.0);
}
if clicked && !busy {
actions.push(UiAction::Wave(ch));
}
}
fn welcome_header(&self, ui: &mut Ui, channel: &Channel, name: &str) {
let t = &self.theme;
ui.add_space(24.0);
ui.horizontal(|ui| {
ui.add_space(16.0);
ui.vertical(|ui| {
ui.spacing_mut().item_spacing.y = 6.0;
let (title, subtitle) = match channel.kind {
channel_kind::DM => {
let user = channel.recipients.first();
let (rect, _) = ui.allocate_exact_size(vec2(80.0, 80.0), Sense::hover());
paint_avatar(ui, rect, user.map(|u| u.avatar_or_default(160)), name);
let username = user.map(|u| u.username.clone()).unwrap_or_default();
(
name.to_string(),
format!("{username}\nThis is the beginning of your direct message history with {name}."),
)
}
channel_kind::GROUP_DM => {
let (rect, _) = ui.allocate_exact_size(vec2(80.0, 80.0), Sense::hover());
paint_avatar(ui, rect, None, name);
(name.to_string(), format!("Welcome to the beginning of the {name} group."))
}
_ => {
let (rect, _) = ui.allocate_exact_size(vec2(68.0, 68.0), Sense::hover());
ui.painter().circle_filled(rect.center(), 34.0, t.input_bg);
super::paint_icon(ui.painter(), Rect::from_center_size(rect.center(), vec2(42.0, 42.0)), icon::HASH, t.header_primary);
(format!("Welcome to #{name}!"), format!("This is the start of the #{name} channel."))
}
};
ui.label(bold(title).size(32.0).color(t.header_primary));
ui.label(RichText::new(subtitle).size(text_px()).color(t.header_secondary));
});
});
ui.add_space(16.0);
let y = ui.cursor().top();
let x = ui.max_rect().x_range();
ui.painter().hline((x.min + 16.0)..=(x.max - 16.0), y, Stroke::new(1.0_f32, t.bg_hover));
ui.add_space(4.0);
}
pub(super) fn message_list(
&self,
ui: &mut Ui,
channel: &Channel,
name: &str,
editing: &mut Option<EditState>,
actions: &mut Vec<UiAction>,
) {
let ch = channel.id;
let t = &self.theme;
let Some(cm) = self.store.messages.get(&ch) else { return };
// Last frame's toolbar position; the hovered row re-registers it below.
let prev_toolbar = self.hover_toolbar.take();
// Heights of message rows from earlier frames, so rows far outside
// the view are skipped (just their space reserved) instead of being
// laid out and re-parsed every frame.
let heights_id = egui::Id::new(("message_heights", ch.0));
let me = self.store.me_id();
let list_rect = ui.max_rect();
// Messages you missed: the first gets the red NEW line (as does a
// "Mark Unread" spot), and the blue bar counts them.
let new_since = self.new_since.filter(|n| n.channel == ch);
let first_new = new_since.and_then(|n| cm.list.iter().find(|m| m.id > n.last_read && Some(m.author.id) != me).map(|m| m.id));
let anchor_id = egui::Id::new(("message_anchor", ch.0));
// A jump (reply, new-messages bar) or putting the chat back where you
// were: egui's stick-to-bottom would undo the scroll, so it's off for
// those frames.
let jump_pending = ui.data(|d| d.get_temp::<(Id, f64, bool)>(jump_id(ch))).is_some_and(|j| !j.2);
let restoring = self.scroll_restore.get().filter(|r| r.0 == ch);
if jump_pending && restoring.is_some() {
self.scroll_restore.set(None);
}
let restoring = restoring.filter(|_| !jump_pending);
// Put back only once the live messages (not the cached copy shown
// while connecting) include that message; until then the chat stays
// at the bottom.
let restore_ready = restoring.is_some_and(|r| !cm.from_cache && cm.list.binary_search_by_key(&r.1, |m| m.id).is_ok());
// Discord's chat scrollbar: a 16 px gutter holding an 8 px rounded track
// (faint, only over a client theme) and a thumb that shows while the
// pointer is over the chat. The style is put back for the messages.
let list_style = ui.style().clone();
{
let hovered = ui.rect_contains_pointer(ui.max_rect());
let thumb = t.scrollbar_thumb();
let style = ui.style_mut();
style.spacing.scroll = egui::style::ScrollStyle { bar_width: 8.0, handle_min_length: 40.0, bar_inner_margin: 4.0, bar_outer_margin: 4.0, ..egui::style::ScrollStyle::solid() };
style.visuals.extreme_bg_color = if t.gradient.is_some() { crate::style::overlay(0.08) } else { Color32::TRANSPARENT };
for w in [&mut style.visuals.widgets.inactive, &mut style.visuals.widgets.hovered, &mut style.visuals.widgets.active] {
w.rounding = Rounding::same(4.0);
w.bg_fill = thumb;
}
if !hovered {
style.visuals.widgets.inactive.bg_fill = Color32::TRANSPARENT;
}
}
// Discord's stand-ins for the history above (see chat_placeholder),
// made once per channel for this window and text size.
let font = text_px();
let spacing = f32::from_bits(super::GROUP_SPACING.load(std::sync::atomic::Ordering::Relaxed));
let window_h = ui.ctx().screen_rect().height();
let placeholder_id = egui::Id::new(("history_placeholder", ch.0));
let placeholder = match ui.data(|d| d.get_temp::<std::sync::Arc<Placeholder>>(placeholder_id)) {
Some(p) if p.fits(font, spacing) => p,
_ => {
let p = std::sync::Arc::new(Placeholder::generate(ch.0, window_h, font, spacing));
ui.data_mut(|d| d.insert_temp(placeholder_id, p.clone()));
p
}
};
let shine = (!super::REDUCED_MOTION.load(std::sync::atomic::Ordering::Relaxed)).then(|| ui.input(|i| i.time));
// How far older messages added above moved what you were reading:
// put straight back into the scroll position (see below).
let mut keep_place = 0.0f32;
let scroll = message_scroll_area(ch, !restore_ready && !jump_pending)
.show_viewport(ui, |ui, viewport| {
ui.set_style(list_style.clone());
ui.set_width(ui.available_width());
let width = ui.available_width().round();
let origin = ui.max_rect().top();
let (cached_w, mut heights) = ui
.data(|d| d.get_temp::<(f32, std::sync::Arc<HashMap<Id, f32>>)>(heights_id))
.map(|(w, h)| (w, (*h).clone()))
.unwrap_or_default();
if cached_w != width {
heights.clear();
}
let near = viewport.expand2(vec2(0.0, 600.0));
ui.add_space(8.0);
// Discord anchors a short conversation to the bottom, above the message
// box: leave the room it didn't fill last frame above it.
let fill_id = egui::Id::new(("message_fill", ch.0));
// (Not measured yet: a full view of room, so the first frame already has
// the messages at the bottom instead of jumping down a frame later.)
let content_h = ui.data(|d| d.get_temp::<f32>(fill_id)).unwrap_or(0.0);
let fill = (viewport.height() - content_h).floor().max(0.0);
if fill > 0.0 && !cm.has_more {
ui.add_space(fill);
}
let content_top = ui.cursor().top();
if cm.has_more && cm.loaded {
// Like Discord: stand-in messages above the oldest one
// (then 16 px), and older ones load as you near them; they
// fill in below the stand-ins, and what you were reading
// stays where it is.
let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), placeholder.height), Sense::hover());
if placeholder.paint(ui, r.min, r.width(), t.text_normal, shine) && shine.is_some() && super::animating() {
ui.ctx().request_repaint_after(std::time::Duration::from_millis(33));
}
ui.add_space(16.0);
if !cm.loading && cm.error.is_none() && viewport.top() < placeholder.height + 600.0 {
actions.push(UiAction::LoadOlder(ch));
}
} else if cm.loaded && channel.kind == channel_kind::DM {
self.dm_welcome(ui, channel, name, actions);
} else if cm.loaded {
self.welcome_header(ui, channel, name);
}
if let Some(err) = &cm.error {
ui.vertical_centered(|ui| {
ui.colored_label(t.danger, format!("Couldn't load messages: {err}"));
if ui.button("Retry").on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
actions.push(UiAction::Retry(ch));
}
});
} else if !cm.loaded && cm.loading {
// Discord's loading look: its stand-in messages, ending at the bottom.
let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), (viewport.height() - 24.0).max(0.0)), Sense::hover());
let painter_clip = ui.clip_rect().intersect(r);
let mut clipped = ui.new_child(egui::UiBuilder::new().max_rect(r));
clipped.set_clip_rect(painter_clip);
if placeholder.paint(&clipped, pos2(r.left(), r.bottom() - placeholder.height), r.width(), t.text_normal, shine) && shine.is_some() && super::animating() {
ui.ctx().request_repaint_after(std::time::Duration::from_millis(33));
}
}
let marker = self.unread_marker.get(&ch).copied().or(first_new);
// What you're reading stays put when rows above it change
// (older pages, images loading): (message, its top) last frame.
let anchor: Option<(Id, f32)> = ui.data(|d| d.get_temp(anchor_id));
let mut shift = 0.0f32;
let mut new_anchor: Option<(Id, f32)> = None;
// Where the first missed message starts (its NEW line), from the list's top.
let mut line_at: Option<f32> = None;
// Where the view's top goes when putting the chat back.
let mut restore_to: Option<f32> = None;
// A jump: scroll there once, and tint the row for a moment.
// (message, when it was scrolled to, scrolled yet)
let jump: Option<(Id, f64, bool)> = ui.data(|d| d.get_temp(jump_id(ch)));
let now = ui.input(|i| i.time);
let mut jumped = false;
let mut prev: Option<&Message> = None;
// Rows start on whole points from the top of the list and take whole
// points, so a row lays out the same at every scroll position and the
// list's height never depends on where it is scrolled to. Pinned to the
// bottom, egui derives the scroll position from that height every frame;
// a height that moved with it made the rows (names, times) jitter.
pad_to_whole(ui, origin);
for m in &cm.list {
let day = local_day(&m.timestamp);
let new_day = prev.map(|p| local_day(&p.timestamp)) != Some(day);
let unread_here = marker == Some(m.id);
let grouped = !new_day
&& !unread_here
&& prev.is_some_and(|p| {
p.author.id == m.author.id
&& m.id.timestamp_ms().saturating_sub(p.id.timestamp_ms()) < 7 * 60_000
&& m.kind == 0
&& !m.is_forward()
&& is_regular(p)
});
let y = ui.cursor().top() - origin;
if let Some((_, was)) = anchor.filter(|(id, _)| *id == m.id) {
shift = y - was;
}
if new_anchor.is_none() || y <= viewport.top() {
new_anchor = Some((m.id, y));
}
if first_new == Some(m.id) {
line_at = Some(y + 8.0);
}
if let Some((_, _, off, _)) = restoring.filter(|r| restore_ready && r.1 == m.id) {
restore_to = Some(y + off);
}
let editing_this = editing.as_ref().is_some_and(|e| e.msg == m.id);
let jump_here = jump.is_some_and(|(id, at, done)| id == m.id && (!done || now - at < 2.0));
if jump_here && jump.is_some_and(|(_, _, done)| !done) {
let h = heights.get(&m.id).copied().unwrap_or(60.0);
ui.scroll_to_rect(Rect::from_min_size(pos2(ui.max_rect().left(), origin + y), vec2(1.0, h)), Some(Align::Center));
jumped = true;
}
if let Some(&h) = heights.get(&m.id).filter(|_| !editing_this && !jump_here) {
if y + h < near.top() || y > near.bottom() {
// Exactly the height it took when laid out (no item spacing on
// top, which `allocate_space` would add).
ui.add_space(h);
prev = Some(m);
continue;
}
}
let start = ui.cursor().top();
let dated = new_day && day.is_some();
if dated {
self.divider(ui, &day.map(|d| d.format("%-d %B %Y").to_string()).unwrap_or_default(), unread_here);
}
self.message_row(ui, m, grouped, me, prev_toolbar, editing, actions);
if unread_here && !dated {
// Discord's NEW line sits in the gap above the group.
new_line(ui, start + 8.0);
}
pad_to_whole(ui, origin);
if jump_here {
// Discord's brief highlight on the message you jumped to.
let since = jump.filter(|j| j.2).map_or(0.0, |(_, at, _)| now - at);
let fade = (1.0 - since / 2.0).clamp(0.0, 1.0) as f32;
let r = Rect::from_min_max(pos2(ui.max_rect().left(), start), pos2(ui.max_rect().right(), ui.cursor().top()));
ui.painter().rect_filled(r, 0.0, t.accent.gamma_multiply(0.18 * fade));
ui.ctx().request_repaint();
}
heights.insert(m.id, ui.cursor().top() - start);
prev = Some(m);
}
if let Some(compact) = self.wave_state(channel, cm) {
self.wave_prompt(ui, channel, compact, actions);
}
// Discord keeps ~30 px between the last message and the box.
ui.add_space(23.0);
ui.data_mut(|d| d.insert_temp(heights_id, (width, std::sync::Arc::new(heights))));
let at_bottom = viewport.bottom() >= ui.cursor().top() - origin - 2.0;
if let Some((_, msg, off, pages)) = restoring {
if let Some(target) = restore_to {
log::info!("nav: {ch} back at {msg} (view top {:.0} -> {target:.0})", viewport.top());
ui.scroll_with_delta_animation(vec2(0.0, -(target - viewport.top())), egui::style::ScrollAnimation::none());
self.scroll_restore.set(None);
ui.ctx().request_repaint();
} else if !restore_ready && cm.loaded && !cm.loading && !cm.from_cache {
// Not loaded yet: older pages until it is (20 at most);
// gone (deleted) or too far back: the bottom, as usual.
if cm.has_more && pages < 20 && cm.list.first().is_some_and(|f| msg < f.id) {
actions.push(UiAction::LoadOlder(ch));
self.scroll_restore.set(Some((ch, msg, off, pages + 1)));
} else {
log::info!("nav: {ch}: message {msg} not found ({} loaded, more {}, {pages} pages)", cm.list.len(), cm.has_more);
self.scroll_restore.set(None);
}
}
} else if !jump_pending && jump.is_none() && cm.loaded && !cm.from_cache {
// Remember where you are in this chat for coming back to it
// this session; at the bottom there's nothing to keep.
let now = new_anchor.filter(|_| !at_bottom).map(|(id, y)| (id, viewport.top() - y));
let mut marks = self.scroll_marks.borrow_mut();
let was = marks.get(&ch).copied();
let moved = match (was, now) {
(Some((m1, o1)), Some((m2, o2))) => m1 != m2 || (o1 - o2).abs() > 1.0,
(None, None) => false,
_ => true,
};
if moved {
match now {
Some((m, o)) => {
marks.insert(ch, (m, o));
}
None => {
marks.remove(&ch);
}
}
}
}
if shift.abs() > 0.5 && !at_bottom && jump.is_none() && restoring.is_none() {
keep_place = shift;
}
if let Some(a) = new_anchor {
ui.data_mut(|d| d.insert_temp(anchor_id, a));
}
// Scrolled up to (or past) the NEW line: the bar has done its job.
if line_at.is_some_and(|y| y >= viewport.top() + 34.0) && !at_bottom && new_since.is_some_and(|n| n.bar) {
actions.push(UiAction::HideNewBar(ch));
}
if jump.is_some_and(|(_, at, done)| done && now - at >= 2.0) {
ui.data_mut(|d| d.remove::<(Id, f64, bool)>(jump_id(ch)));
} else if jumped {
// Scroll once: later frames only fade the highlight.
if let Some((id, _, _)) = jump {
ui.data_mut(|d| d.insert_temp(jump_id(ch), (id, now, true)));
}
}
let content_h = ui.cursor().top() - content_top + 8.0;
let before = ui.data(|d| d.get_temp::<f32>(fill_id));
ui.data_mut(|d| d.insert_temp(fill_id, content_h));
// The chat's height changed (first open, the live messages replacing the
// saved copy, a new message) while it shows its bottom: egui only moves
// the scroll position after this frame, so the frame would be drawn at
// the old position and the chat would visibly jump. Lay it out again
// instead of showing that frame.
let at_bottom = before.is_none_or(|h| viewport.bottom() >= h + fill - 12.0);
if at_bottom && before.is_none_or(|h| (h - content_h).abs() > 0.5) {
ui.ctx().request_discard("chat height changed");
}
});
// Rows above what you're reading changed height (older messages
// added, a picture loaded): move the scroll position by as much, now,
// and lay the frame out again so it's never drawn shifted. (Asking
// egui to scroll instead only took effect a frame later, and a wheel
// scroll in progress cancelled it: the chat leapt up by a page.)
if keep_place != 0.0 {
let mut state = scroll.state;
state.offset.y = (state.offset.y + keep_place).max(0.0);
state.store(ui.ctx(), scroll.id);
ui.ctx().request_discard("kept the chat in place");
}
if let Some(n) = new_since.filter(|n| n.bar) {
let count = cm.list.iter().filter(|m| m.id > n.last_read && Some(m.author.id) != me).count();
// More missed than is loaded: "50+ new messages".
let more = cm.has_more && cm.list.first().is_some_and(|m| m.id > n.last_read);
let since = first_new.filter(|_| !more).unwrap_or(n.last_read);
if count > 0 {
self.new_messages_bar(ui, list_rect, ch, since.timestamp_ms(), count, more, actions);
}
}
}
/// Discord's day divider: a hairline 24 px under the last message with the
/// date on it. Over the first message you missed it's red, with NEW.
fn divider(&self, ui: &mut Ui, label: &str, unread: bool) {
let t = &self.theme;
ui.add_space(16.0);
let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), 16.0), Sense::hover());
let (left, right, y) = (rect.left() + 16.0, rect.right() - 14.0, rect.top() + 8.0);
let (text, line) = if unread { (NEW_RED, NEW_RED) } else { (t.text_muted, t.bg_hover) };
let galley = ui.painter().layout_no_wrap(label.to_string(), egui::FontId::new(12.0, egui::FontFamily::Name(crate::style::BOLD.into())), text);
let (w, c) = (galley.size().x, (left + right) / 2.0);
// 1 px rows (crisp), with the label's 4 px of padding around it.
ui.painter().rect_filled(Rect::from_x_y_ranges(left..=(c - w / 2.0 - 4.0), y..=y + 1.0), 0.0, line);
ui.painter().rect_filled(Rect::from_x_y_ranges((c + w / 2.0 + 4.0)..=right, y..=y + 1.0), 0.0, line);
ui.painter().galley(pos2(c - w / 2.0, y + 0.5 - galley.size().y / 2.0), galley, text);
if unread {
new_pill(ui.painter(), right, y);
}
ui.add_space(4.0);
}
/// Discord's blue bar over the top of the chat: "N new messages since
/// TIME" (click to jump up to them) and "Mark As Read".
#[allow(clippy::too_many_arguments)]
fn new_messages_bar(&self, ui: &mut Ui, area: Rect, ch: Id, since_ms: u64, count: usize, more: bool, actions: &mut Vec<UiAction>) {
let Some(since) = chrono::DateTime::from_timestamp_millis(since_ms as i64).map(|d| d.with_timezone(&chrono::Local)) else {
return;
};
let time = since.format(super::time_fmt()).to_string();
let mut text = match (more, count) {
(true, _) => format!("{count}+ new messages since {time}"),
(false, 1) => format!("1 new message since {time}"),
_ => format!("{count} new messages since {time}"),
};
if since.date_naive() != chrono::Local::now().date_naive() {
text += &format!(" on {}", since.format("%-d %B %Y"));
}
// 8 px in from the left, 16 from the right (the scrollbar), 32 tall
// plus a 1 px border, flush with the top.
let rect = Rect::from_min_max(pos2(area.left() + 8.0, area.top()), pos2(area.right() - 16.0, area.top() + 34.0));
egui::Area::new(egui::Id::new(("new_messages_bar", ch.0)))
.order(Order::Middle)
.fixed_pos(rect.min)
.show(ui.ctx(), |ui| {
let (r, _) = ui.allocate_exact_size(rect.size(), Sense::hover());
let rounding = Rounding { nw: 0.0, ne: 0.0, sw: 8.0, se: 8.0 };
let label = ui.painter().layout_no_wrap(
"Mark As Read".into(),
FontId::new(13.33, egui::FontFamily::Name(crate::style::BOLD.into())),
Color32::WHITE,
);
// "Mark As Read" + Discord's chat-check icon on the right
// (padding 4/8, 8 px gap, 16 px icon), 16 px from the edge.
let alt_w = 8.0 + label.size().x + 8.0 + 16.0 + 8.0;
let alt = Rect::from_center_size(pos2(r.right() - 17.0 - alt_w / 2.0, r.center().y), vec2(alt_w, 26.0));
let alt_resp = ui.interact(alt, ui.id().with("mark_read"), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
let main = Rect::from_min_max(pos2(r.left() + 17.0, r.top() + 1.0), pos2(alt.left(), r.bottom() - 1.0));
let main_resp = ui.interact(main, ui.id().with("jump"), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
let pressed = main_resp.is_pointer_button_down_on() || alt_resp.is_pointer_button_down_on();
let dy = if pressed { 1.0 } else { 0.0 };
let p = ui.painter();
if !pressed {
// --elevation-low: a soft edge under the bar.
p.rect_filled(r.translate(vec2(0.0, 2.0)), rounding, Color32::from_black_alpha(10));
p.rect_filled(r.translate(vec2(0.0, 1.0)), rounding, Color32::from_black_alpha(51));
}
p.rect_filled(r, rounding, BRAND_500);
p.rect_stroke(r.shrink(0.5), rounding, Stroke::new(1.0_f32, crate::style::rgba(151, 151, 159, 31)));
if alt_resp.hovered() {
p.rect_filled(alt.translate(vec2(0.0, dy)), 8.0, crate::style::rgba(151, 151, 159, 41));
}
let label_h = label.size().y;
p.galley(pos2(alt.left() + 8.0, alt.center().y - label_h / 2.0 + dy), label, Color32::WHITE);
let icon = Rect::from_min_size(pos2(alt.right() - 24.0, alt.center().y - 9.0 + dy), vec2(16.0, 16.0));
egui::Image::new(egui::ImageSource::Bytes {
uri: "bytes://chat-check.svg".into(),
bytes: egui::load::Bytes::Static(CHAT_CHECK_SVG.as_bytes()),
})
.paint_at(ui, icon);
// The count, cut short with … when the chat is narrow.
let mut job = egui::text::LayoutJob::single_section(
text,
egui::TextFormat { font_id: crate::style::medium(13.33), color: Color32::WHITE, ..Default::default() },
);
job.wrap = egui::text::TextWrapping { max_width: (main.width() - 12.0).max(0.0), max_rows: 1, break_anywhere: true, overflow_character: Some('…') };
let galley = ui.fonts(|f| f.layout_job(job));
ui.painter().galley(pos2(main.left() + 4.0, r.center().y - galley.size().y / 2.0 + dy), galley, Color32::WHITE);
if main_resp.clicked() {
actions.push(UiAction::JumpToNew(ch));
}
if alt_resp.clicked() {
actions.push(UiAction::MarkRead(ch));
}
});
}
/// Discord-style floating action bar on the hovered message.
fn hover_toolbar_ui(&self, ui: &mut Ui, m: &Message, rect: Rect, me: Option<Id>, actions: &mut Vec<UiAction>) {
enum Tool<'a> {
React(&'a str),
AddReaction,
Reply,
Forward,
Edit,
More,
}
let t = &self.theme;
let live = !m.meta.deleted && !m.meta.pending && !m.meta.failed;
let mut tools = Vec::new();
let quick = self.quick_reactions(3);
if live {
if self.can_add_reactions(m.channel_id) {
tools.extend(quick.iter().map(|e| Tool::React(e.as_str())));
tools.push(Tool::AddReaction);
}
tools.push(Tool::Reply);
tools.push(Tool::Forward);
if Some(m.author.id) == me {
tools.push(Tool::Edit);
}
}
tools.push(Tool::More);
const CELL: f32 = 32.0;
let width = CELL * tools.len() as f32 + 4.0;
let top = (rect.top() - 16.0).max(ui.clip_rect().top() + 2.0);
let bar = Rect::from_min_size(pos2(rect.right() - 16.0 - width, top), vec2(width, CELL + 4.0));
self.hover_toolbar.set(Some((m.id, bar)));
let shadow = egui::epaint::Shadow { offset: vec2(0.0, 2.0), blur: 8.0, spread: 0.0, color: Color32::from_black_alpha(80) };
ui.painter().add(shadow.as_shape(bar, 6.0));
ui.painter().rect(bar, 6.0, t.bg_primary, Stroke::new(1.0_f32, t.bg_tertiary));
for (i, tool) in tools.iter().enumerate() {
let cell = Rect::from_min_size(pos2(bar.left() + 2.0 + i as f32 * CELL, bar.top() + 2.0), vec2(CELL, CELL));
let r = ui.interact(cell, egui::Id::new(("message_toolbar", m.id.0, i)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
if r.hovered() {
ui.painter().rect_filled(cell.shrink(2.0), 4.0, t.bg_hover);
}
let glyph = |g: &str| {
let c = if r.hovered() { t.interactive_hover } else { t.interactive_normal };
ui.painter().text(cell.center(), Align2::CENTER_CENTER, g, icon_font(18.0), c);
};
let (tip, action) = match tool {
Tool::React(e) => {
let size = if r.hovered() { 22.0 } else { 20.0 };
egui::Image::new(twemoji_url(e)).paint_at(ui, Rect::from_center_size(cell.center(), vec2(size, size)));
let emoji = ReactionEmoji::unicode(e);
("React", UiAction::React { channel: m.channel_id, msg: m.id, emoji })
}
Tool::AddReaction => {
glyph(icon::EMOJI);
("Add Reaction", UiAction::OpenPicker { channel: m.channel_id, msg: m.id, pos: cell.left_bottom() + vec2(-360.0, 4.0) })
}
Tool::Reply => {
glyph(icon::REPLY);
("Reply", UiAction::Reply { channel: m.channel_id, msg: m.id })
}
Tool::Forward => {
glyph(icon::FORWARD);
("Forward", UiAction::Forward { channel: m.channel_id, msg: m.id })
}
Tool::Edit => {
glyph(icon::EDIT);
("Edit", UiAction::StartEdit { channel: m.channel_id, msg: m.id })
}
Tool::More => {
glyph(icon::MORE);
("More", UiAction::OpenContext { channel: m.channel_id, msg: m.id, pos: cell.left_bottom() + vec2(-200.0, 4.0) })
}
};
if r.on_hover_text(tip).clicked() {
actions.push(action);
}
}
}
/// Discord's audio attachment card: file row + play/seek/time/mute bar.
fn audio_card(&self, ui: &mut Ui, a: &Attachment, actions: &mut Vec<UiAction>) {
let t = &self.theme;
let st = self.audio.state(&a.url);
// Discord's audio card: 432 px wide, 16 px padding, a 24 × 40 icon
// beside the name and size, then a 32 px control bar (black 40 %).
Frame::none()
.fill(if t.gradient.is_some() { t.bg_hover } else { t.bg_secondary })
.rounding(8.0)
.stroke(Stroke::new(1.0_f32, t.border_subtle))
.inner_margin(16.0)
.show(ui, |ui| {
ui.set_width((ui.available_width() - 2.0).min(398.0));
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 8.0;
let (r, _) = ui.allocate_exact_size(vec2(24.0, 40.0), Sense::hover());
ui.painter().text(r.center(), Align2::CENTER_CENTER, icon::AUDIO, icon_font(26.0), t.interactive_normal);
ui.vertical(|ui| {
ui.spacing_mut().item_spacing.y = 0.0;
ui.add(egui::Hyperlink::from_label_and_url(RichText::new(&a.filename).size(16.0).color(t.text_link), &a.url)).on_hover_cursor(CursorIcon::PointingHand);
ui.label(RichText::new(human_size(a.size)).size(12.0).color(t.text_muted));
});
});
ui.add_space(4.0);
let (bar, _) = ui.allocate_exact_size(vec2(ui.available_width(), 32.0), Sense::hover());
ui.painter().rect_filled(bar, 8.0, Color32::from_black_alpha(102));
// Play / pause.
let play = Rect::from_center_size(pos2(bar.left() + 20.0, bar.center().y), vec2(28.0, 28.0));
let pr = ui.interact(play, egui::Id::new(("audio_play", &a.url)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
if st.loading {
egui::Spinner::new().size(16.0).paint_at(ui, Rect::from_center_size(play.center(), vec2(16.0, 16.0)));
} else {
let g = if st.playing { icon::PAUSE } else { icon::PLAY };
let c = if pr.hovered() { t.header_primary } else { t.interactive_normal };
ui.painter().text(play.center(), Align2::CENTER_CENTER, g, icon_font(16.0), c);
}
if pr.on_hover_text(if st.playing { "Pause" } else { "Play" }).clicked() {
actions.push(UiAction::AudioToggle(a.url.clone()));
}
// Time.
let total = st.duration.map(crate::audio::fmt_time).unwrap_or_else(|| "-:--".into());
let time = format!("{}/{}", crate::audio::fmt_time(st.position), total);
let galley = ui.painter().layout_no_wrap(time, egui::FontId::monospace(12.0), t.header_primary);
let tw = galley.size().x;
ui.painter().galley(pos2(play.right() + 8.0, bar.center().y - galley.size().y / 2.0), galley, t.header_primary);
// Mute.
let vol = Rect::from_center_size(pos2(bar.right() - 20.0, bar.center().y), vec2(28.0, 28.0));
let vr = ui.interact(vol, egui::Id::new(("audio_vol", &a.url)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
let g = if self.audio.muted { icon::MUTE } else { icon::SPEAK };
ui.painter().text(vol.center(), Align2::CENTER_CENTER, g, icon_font(16.0), if vr.hovered() { t.header_primary } else { t.interactive_normal });
if vr.on_hover_text(if self.audio.muted { "Unmute" } else { "Mute" }).clicked() {
actions.push(UiAction::AudioMute);
}
// Seek bar.
let rail = Rect::from_min_max(
pos2(play.right() + 18.0 + tw, bar.center().y - 3.0),
pos2(vol.left() - 10.0, bar.center().y + 3.0),
);
if rail.width() > 20.0 {
let sr = ui.interact(rail.expand2(vec2(0.0, 8.0)), egui::Id::new(("audio_seek", &a.url)), Sense::click_and_drag());
let frac = match st.duration {
Some(d) if d.as_secs_f32() > 0.0 => (st.position.as_secs_f32() / d.as_secs_f32()).clamp(0.0, 1.0),
_ => 0.0,
};
ui.painter().rect_filled(rail, 3.0, crate::style::rgba(255, 255, 255, 77));
let filled = Rect::from_min_max(rail.min, pos2(rail.left() + rail.width() * frac, rail.max.y));
ui.painter().rect_filled(filled, 3.0, t.accent);
if sr.hovered() || sr.dragged() {
ui.painter().circle_filled(pos2(filled.right(), rail.center().y), 6.0, Color32::WHITE);
}
if sr.clicked() || sr.drag_stopped() {
if let Some(p) = sr.interact_pointer_pos() {
actions.push(UiAction::AudioSeek(a.url.clone(), (p.x - rail.left()) / rail.width()));
}
}
}
});
}
/// Image attachments (up to 550×350, like Discord), audio players and file cards.
pub(super) fn attachments_ui(&self, ui: &mut Ui, attachments: &[Attachment], actions: &mut Vec<UiAction>) {
let t = &self.theme;
// Narrower than Discord's 550 px where the column is (a pin's card).
let max_w = ui.available_width().clamp(160.0, 550.0);
for a in attachments {
let video = crate::video_player::is_video(&a.filename, a.content_type.as_deref()) && a.width.is_some();
let proxy = if a.proxy_url.is_empty() { &a.url } else { &a.proxy_url };
if (video || a.is_image()) && a.filename.starts_with("SPOILER_") && !self.spoiler_shown((a.id, 0)) {
// Discord blurs it under a "SPOILER" tag until clicked.
let (w, h) = fit(a.width.unwrap_or(550) as f32, a.height.unwrap_or(350) as f32, max_w, 350.0);
let (rect, resp) = ui.allocate_exact_size(vec2(w, h), Sense::click());
ui.painter().rect_filled(rect, 8.0, spoiler_colors(t).0);
if proxy.contains("discordapp.") {
egui::Image::new(super::embeds::blurred(proxy)).rounding(8.0).paint_at(ui, rect);
}
let g = ui.painter().layout_no_wrap("SPOILER".into(), FontId::new(15.0, egui::FontFamily::Name(crate::style::BOLD.into())), Color32::WHITE);
let pill = Rect::from_center_size(rect.center(), g.size() + vec2(24.0, 16.0));
ui.painter().rect_filled(pill, 20.0, Color32::from_black_alpha(if resp.hovered() { 230 } else { 153 }));
ui.painter().galley(pill.center() - g.size() / 2.0, g, Color32::WHITE);
if resp.on_hover_cursor(CursorIcon::PointingHand).clicked() {
actions.push(UiAction::Reveal(a.id, 0));
}
} else if video {
// Discord's player; the poster is a still from its media proxy.
let (w, h) = fit(a.width.unwrap_or(550) as f32, a.height.unwrap_or(350) as f32, max_w, 350.0);
let poster = format!("{proxy}{}format=webp&width={}&height={}", if proxy.contains('?') { '&' } else { '?' }, w as u32, h as u32);
self.video_box(ui, &a.url, Some(&poster), vec2(w.max(150.0), h.max(80.0)), 8.0, actions);
} else if crate::audio::is_audio(&a.filename, a.content_type.as_deref()) {
self.audio_card(ui, a, actions);
} else if a.is_image() {
let (w, h) = fit(a.width.unwrap_or(550) as f32, a.height.unwrap_or(350) as f32, max_w, 350.0);
let base = if a.proxy_url.is_empty() { &a.url } else { &a.proxy_url };
let is_gif = a.content_type.as_deref() == Some("image/gif") || a.filename.to_ascii_lowercase().ends_with(".gif");
let url = if base.starts_with("bytes://") {
base.clone()
} else if is_gif {
// The original file, so it plays.
super::anim(&a.url)
} else {
// Ask Discord's media proxy for a right-sized copy.
let sep = if base.contains('?') { '&' } else { '?' };
format!("{base}{sep}width={}&height={}", w as u32, h as u32)
};
let r = super::media_image(ui, url, vec2(w, h), 8.0, a.placeholder.as_deref());
super::note_media(ui, &r, if base.starts_with("bytes://") { base } else { &a.url }, &a.url);
// Discord's "ALT" tag: the picture's description on hover.
if let Some(alt) = a.description.as_deref().filter(|d| !d.is_empty() && super::IMAGE_ALT.load(std::sync::atomic::Ordering::Relaxed)) {
let chip = Rect::from_min_size(pos2(r.rect.left() + 6.0, r.rect.bottom() - 26.0), vec2(34.0, 20.0));
ui.painter().rect_filled(chip, 4.0, Color32::from_black_alpha(175));
ui.painter().text(chip.center(), Align2::CENTER_CENTER, "ALT", FontId::new(12.0, egui::FontFamily::Name(crate::style::BOLD.into())), Color32::WHITE);
ui.interact(chip, egui::Id::new(("alt", a.id)), Sense::hover()).on_hover_text(alt);
}
if r.clicked() {
// Open in the viewer, at a size that fits a big window.
let natural = (a.width.unwrap_or(1200) as f32, a.height.unwrap_or(800) as f32);
let (vw, vh) = fit(natural.0, natural.1, 1600.0, 1000.0);
let image = if is_gif || base.starts_with("bytes://") {
if is_gif { a.url.clone() } else { base.clone() }
} else {
let sep = if base.contains('?') { '&' } else { '?' };
format!("{base}{sep}width={}&height={}", vw as u32, vh as u32)
};
actions.push(UiAction::View(crate::features::MediaView { image, video: None, link: a.url.clone(), size: Some(natural) }));
}
r.on_hover_cursor(CursorIcon::PointingHand);
} else {
// Discord's file card: 432 px wide, 16 px padding, a 30 × 40
// icon, the name (16 px link) over its size (12 px muted).
Frame::none()
.fill(if t.gradient.is_some() { t.bg_hover } else { t.surface_high })
.rounding(8.0)
.stroke(Stroke::new(1.0_f32, t.border_subtle))
.inner_margin(16.0)
.show(ui, |ui| {
ui.set_width((ui.available_width() - 2.0).min(398.0));
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 8.0;
let (r, _) = ui.allocate_exact_size(vec2(30.0, 40.0), Sense::hover());
ui.painter().text(r.center(), Align2::CENTER_CENTER, icon::FILE, icon_font(32.0), t.interactive_normal);
ui.vertical(|ui| {
ui.spacing_mut().item_spacing.y = 0.0;
ui.add(egui::Hyperlink::from_label_and_url(RichText::new(&a.filename).size(16.0).color(t.text_link), &a.url)).on_hover_cursor(CursorIcon::PointingHand);
ui.label(RichText::new(human_size(a.size)).size(12.0).color(t.text_muted));
});
});
});
}
}
}
/// Discord's reaction: 1 px border, 8 px corners, 2 × 6 px padding, a
/// 20 px emoji and the count (14 px semibold) 6 px after it.
fn reaction_chip(&self, ui: &mut Ui, r: &Reaction) -> Response {
let font = FontId::new(14.0, egui::FontFamily::Name(crate::style::BOLD.into()));
let galley = ui.painter().layout_no_wrap(r.count.to_string(), font, Color32::PLACEHOLDER);
let size = vec2(1.0 + 6.0 + 20.0 + 6.0 + galley.size().x + 6.0 + 1.0, 30.0);
let (rect, resp) = ui.allocate_exact_size(size, Sense::click());
let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
let grey = |a: u8| crate::style::rgba(151, 151, 159, a);
let (fill, border, text_color) = if r.me {
(crate::style::rgba(88, 101, 242, 61), Color32::from_rgb(88, 101, 242), Color32::from_rgb(185, 200, 255))
} else if resp.hovered() {
(grey(41), grey(10), Color32::from_rgb(251, 251, 251))
} else {
(grey(31), Color32::TRANSPARENT, Color32::from_rgb(171, 172, 178))
};
ui.painter().rect(rect, 8.0, fill, Stroke::new(1.0_f32, border));
let icon = Rect::from_center_size(pos2(rect.left() + 17.0, rect.center().y), vec2(20.0, 20.0));
match (r.emoji.id, r.emoji.name.as_deref()) {
(Some(id), _) => egui::Image::new(super::emoji_img(id, r.emoji.animated, 48)).paint_at(ui, icon),
(None, Some(name)) => egui::Image::new(twemoji_url(name)).paint_at(ui, icon),
_ => {}
}
let text_pos = pos2(icon.right() + 6.0, rect.center().y - galley.size().y / 2.0);
ui.painter().galley_with_override_text_color(text_pos, galley, text_color);
resp.on_hover_cursor(CursorIcon::PointingHand)
}
/// Discord's reaction tooltip: the emoji, big, and who reacted with it
/// ("Ana, Ben and 3 others reacted with :tada:").
fn reactors_tooltip(&self, chip: Response, m: &Message, r: &Reaction, actions: &mut Vec<UiAction>) {
let t = &self.theme;
let name = r.emoji.name.clone().unwrap_or_default();
let label = match r.emoji.id {
Some(_) => format!(":{name}:"),
None => crate::emoji::shortcode_of(&name).map(|n| format!(":{n}:")).unwrap_or_else(|| name.clone()),
};
// It stays while the pointer is on the reaction or on the card itself
// (and the gap between), so the card can be clicked.
let tip_id = egui::Id::new(("reactors_tip", m.id.0, &label));
let was: Option<Rect> = chip.ctx.data(|d| d.get_temp(tip_id));
let pointer = chip.ctx.input(|i| i.pointer.hover_pos());
let on_tip = was.zip(pointer).is_some_and(|(r, p)| r.expand2(vec2(0.0, 10.0)).contains(p));
if !(chip.hovered() || on_tip) || self.context_menu.is_some() || self.reactions_dialog.is_some() {
chip.ctx.data_mut(|d| d.remove::<Rect>(tip_id));
return;
}
// (Who reacted is only worked out for the reaction under the pointer.)
let guild = self.guild_of(m);
let names: Option<Vec<String>> = match self.api_result(&reactors_tag(m.id, &r.emoji, r.count)) {
Some(Ok(v)) => v.as_array().map(|users| {
users
.iter()
.filter_map(|u| {
let id = u["id"].as_str().and_then(|s| s.parse::<u64>().ok()).map(Id);
let nick = id.zip(guild).and_then(|(id, g)| self.store.members.get(&(g, id))).and_then(|i| i.nick.clone());
nick.or_else(|| u["global_name"].as_str().map(str::to_string)).or_else(|| u["username"].as_str().map(str::to_string))
})
.collect()
}),
_ => None,
};
let text = match names.as_deref() {
Some([]) | None => label.clone(),
Some(n) => {
let others = (r.count as usize).saturating_sub(n.len());
let who = match (n, others) {
([a], 0) => a.clone(),
([a, b], 0) => format!("{a} and {b}"),
([a, b, c], 0) => format!("{a}, {b} and {c}"),
(n, 1) => format!("{} and 1 other", n.join(", ")),
(n, k) => format!("{} and {k} others", n.join(", ")),
};
format!("{who} reacted with {label}")
}
};
let image = match (r.emoji.id, r.emoji.name.as_deref()) {
(Some(id), _) => Some(super::emoji_img(id, r.emoji.animated, 96)),
(None, Some(n)) => Some(twemoji_url(n)),
_ => None,
};
// Discord's card: surface-high, 4 px corners, 16 px padding, at most
// 288 px wide, a 32 px emoji and the text 12 px after it; centred
// above the reaction.
let ctx = chip.ctx.clone();
let area = egui::Area::new(tip_id)
.order(egui::Order::Tooltip)
.pivot(Align2::CENTER_BOTTOM)
.fixed_pos(chip.rect.center_top() - vec2(0.0, 8.0))
.constrain(true)
.show(&ctx, |ui| {
Frame::none()
.fill(if t.gradient.is_some() { t.bg_floating } else { t.surface_high })
.stroke(Stroke::new(1.0_f32, t.border_subtle))
.rounding(4.0)
.inner_margin(Margin::same(16.0))
.shadow(egui::epaint::Shadow { offset: vec2(0.0, 8.0), blur: 16.0, spread: 0.0, color: Color32::from_black_alpha(60) })
.show(ui, |ui| {
ui.set_max_width(256.0);
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 12.0;
if let Some(url) = &image {
ui.add(egui::Image::new(url.as_str()).fit_to_exact_size(vec2(32.0, 32.0)));
}
ui.add(Label::new(RichText::new(&text).font(crate::style::medium(14.0)).color(t.text_normal)).wrap());
});
});
// Clicking the card lists everyone (Discord's Reactions dialog).
ui.interact(ui.min_rect(), tip_id.with("click"), Sense::click()).on_hover_cursor(CursorIcon::PointingHand).clicked()
});
let rect = area.response.rect;
ctx.data_mut(|d| d.insert_temp(tip_id, rect));
if area.inner {
actions.push(UiAction::OpenReactions { channel: m.channel_id, msg: m.id, emoji: r.emoji.clone() });
}
}
/// The message's server (history messages don't say; their channel does).
fn guild_of(&self, m: &Message) -> Option<Id> {
m.guild_id.or_else(|| self.store.channels.get(&m.channel_id).and_then(|c| c.guild_id))
}
/// The author's roles here: from the message, else what RustCord knows of them.
fn author_roles(&self, m: &Message) -> Vec<Id> {
if let Some(mem) = &m.member {
return mem.roles.clone();
}
self.guild_of(m).and_then(|g| self.store.members.get(&(g, m.author.id))).map(|i| i.roles.clone()).unwrap_or_default()
}
/// `base` in the author's display-name font: the one they set for this
/// server when they did, else their own.
pub(super) fn author_font(&self, m: &Message, base: FontId) -> FontId {
let own = m.member.as_ref().and_then(|mem| mem.display_name_styles.as_ref()).or_else(|| self.store.member_style(self.guild_of(m), m.author.id));
match own {
Some(style) => {
let mut author = m.author.clone();
author.display_name_styles = Some(style.clone());
super::name_font(&author, base)
}
None => super::name_font(&m.author, base),
}
}
/// A system message's line ("X started a call.") and the author's name in it.
fn system_line(&self, m: &Message) -> Option<(String, String)> {
if matches!(m.kind, 0 | 19 | 20 | 23) {
return None;
}
let who = self.author_name(m);
let line = system_text(m, &who)?;
Some((if m.kind == 3 { call_text(m, &who, self.store.me_id()).0 } else { line }, who))
}
/// Server nickname in a server, friend nickname in a DM, else display name.
pub(super) fn author_name(&self, m: &Message) -> String {
m.member
.as_ref()
.and_then(|mem| mem.nick.clone())
.filter(|n| !n.is_empty())
.or_else(|| self.store.nick_in(self.guild_of(m), Some(m.channel_id), m.author.id))
.unwrap_or_else(|| m.author.display_name().to_string())
}
/// `<@id>`, `<#id>`, `<@&id>` and `<:emoji:id>` as Discord shows them in
/// one-line previews: @name, #channel, @role, :emoji:.
pub(super) fn plain_mentions(&self, m: &Message, text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut rest = text;
while let Some(start) = rest.find('<') {
out.push_str(&rest[..start]);
let tail = &rest[start..];
let Some(end) = tail.find('>') else {
out.push_str(tail);
return out;
};
let inner = &tail[1..end];
let id = |s: &str| s.parse::<u64>().ok().map(Id);
let replaced = if let Some(r) = inner.strip_prefix("@&") {
id(r).map(|r| format!("@{}", self.store.role_name(m.guild_id, r).unwrap_or_else(|| "deleted-role".into())))
} else if let Some(u) = inner.strip_prefix("@!").or_else(|| inner.strip_prefix('@')) {
id(u).map(|u| format!("@{}", self.user_name(m, u)))
} else if let Some(c) = inner.strip_prefix('#') {
id(c).map(|c| format!("#{}", self.store.channel_name(c)))
} else if inner.starts_with(':') || inner.starts_with("a:") {
inner.trim_start_matches("a").split(':').nth(1).map(|n| format!(":{n}:"))
} else {
None
};
match replaced {
Some(r) => out.push_str(&r),
None => out.push_str(&tail[..=end]),
}
rest = &tail[end + 1..];
}
out.push_str(rest);
out
}
/// Is this spoiler open: clicked, or "Show spoiler content" says so
/// (always, or on servers you moderate).
pub(super) fn spoiler_shown(&self, key: (Id, usize)) -> bool {
self.revealed.contains(&key)
|| match super::SPOILERS.load(std::sync::atomic::Ordering::Relaxed) {
2 => true,
1 => self.current_guild.is_some_and(|g| self.store.has_perm(g, 1 << 13)),
_ => false,
}
}
/// The author's role colour as a dot beside the name (Accessibility →
/// Role Colours → "Show role colours next to names").
fn role_dot(&self, ui: &mut Ui, m: &Message) {
if super::ROLE_COLORS.load(std::sync::atomic::Ordering::Relaxed) != 1 {
return;
}
if let Some(c) = self.store.role_color(self.guild_of(m), &self.author_roles(m)) {
let (r, _) = ui.allocate_exact_size(vec2(10.0, 10.0), Sense::hover());
ui.painter().circle_filled(r.center(), 5.0, Color32::from_rgb((c >> 16) as u8, (c >> 8) as u8, c as u8));
}
}
pub(super) fn name_color(&self, m: &Message) -> Color32 {
if super::ROLE_COLORS.load(std::sync::atomic::Ordering::Relaxed) != 0 {
return self.theme.header_primary;
}
let rgb = |c: u32| Color32::from_rgb((c >> 16) as u8, (c >> 8) as u8, c as u8);
// Discord's chat: the role colour, else plain white (a Nitro name
// style only lends its font here; its colours are for profiles).
self.store.role_color(self.guild_of(m), &self.author_roles(m)).map(rgb).unwrap_or(self.theme.header_primary)
}
/// Chat Message Display → Compact: the time, the name and the text on one
/// line, with no avatar column (a small avatar with "Show user avatars").
fn compact_row(&self, ui: &mut Ui, m: &Message, color: Color32, forced: bool, editing: &mut Option<EditState>, actions: &mut Vec<UiAction>) {
let t = &self.theme;
ui.horizontal_top(|ui| {
ui.spacing_mut().item_spacing.x = 6.0;
ui.add_space(8.0);
let line = (text_px() * 1.375).round();
let (time, _) = ui.allocate_exact_size(vec2(54.0, line), Sense::hover());
ui.painter().text(time.right_center(), Align2::RIGHT_CENTER, super::short_time(&m.timestamp), FontId::proportional(11.0), t.text_muted);
let open_profile = |resp: &Response, actions: &mut Vec<UiAction>| {
if m.kind == 24 {
return;
}
if resp.hovered() {
self.profiles_wanted.borrow_mut().push((m.author.id, m.guild_id));
}
if resp.clicked() {
let at = resp.interact_pointer_pos().unwrap_or(resp.rect.right_top());
actions.push(UiAction::OpenProfile { user: Box::new(m.author.clone()), guild: self.guild_of(m), pos: at + vec2(12.0, -40.0) });
}
self.author_menu(m, self.guild_of(m), resp, actions);
};
if is_system(m) {
let (rect, _) = ui.allocate_exact_size(vec2(20.0, line), Sense::hover());
let kind = if m.kind == 3 && call_text(m, "", self.store.me_id()).1 { MISSED_CALL } else { m.kind };
system_icon(ui, t, kind, rect);
} else {
if super::COMPACT_AVATARS.load(std::sync::atomic::Ordering::Relaxed) {
let (rect, resp) = ui.allocate_exact_size(vec2(16.0, line), Sense::click());
paint_avatar(ui, Rect::from_center_size(rect.center(), vec2(16.0, 16.0)), Some(m.author.avatar_or_default(32)), m.display_name());
open_profile(&resp.on_hover_cursor(CursorIcon::PointingHand), actions);
}
let name_font = self.author_font(m, crate::style::medium(text_px()));
let name = ui
.add(Label::new(RichText::new(self.author_name(m)).font(name_font).color(self.name_color(m))).selectable(false).sense(Sense::click()))
.on_hover_cursor(CursorIcon::PointingHand);
open_profile(&name, actions);
self.role_dot(ui, m);
super::bot_badge(ui, t, &m.author);
}
ui.vertical(|ui| {
ui.set_max_width((ui.available_width() - 24.0).max(100.0));
ui.spacing_mut().item_spacing.y = 3.0;
self.message_body(ui, m, color, forced, editing, actions);
});
});
}
#[allow(clippy::too_many_arguments)]
fn message_row(
&self,
ui: &mut Ui,
m: &Message,
grouped: bool,
me: Option<Id>,
prev_toolbar: Option<(Id, Rect)>,
editing: &mut Option<EditState>,
actions: &mut Vec<UiAction>,
) {
let t = &self.theme;
let top = ui.cursor().top();
let bg = ui.painter().add(Shape::Noop);
// Discord: each message padded 2 px top and bottom, 17 px more above
// a group (the trailing gap below is the list's 3 px item spacing).
// (The 16 px is Accessibility → Space Between Message Groups.)
let compact = super::COMPACT.load(std::sync::atomic::Ordering::Relaxed);
let pad = if compact { 1.0 } else { 2.0 };
ui.add_space(if grouped { pad } else { pad + f32::from_bits(super::GROUP_SPACING.load(std::sync::atomic::Ordering::Relaxed)) });
// (Compact: every message has its time and name, grouped or not.)
let grouped = grouped && !compact;
let full_w = ui.available_width();
let left = ui.max_rect().left();
let deleted_text = m.meta.deleted && m.meta.deleted_style == DeletedStyle::Text;
let (color, forced) = if deleted_text {
(t.danger, true)
} else if m.meta.pending || m.meta.failed {
(t.text_muted, true)
} else {
(t.text_normal, false)
};
// Reply preview, joined to the avatar by Discord's curved "spine".
if m.kind == 19 {
let row = ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 4.0;
ui.add_space(if compact { 64.0 } else { 72.0 });
// (A reply only you can see names its message without carrying it.)
let referenced = m.referenced_message.as_deref().or_else(|| m.message_reference.as_ref().and_then(|x| x.message_id).and_then(|id| self.store.message(m.channel_id, id)));
match referenced {
Some(r) => {
let (rect, _) = ui.allocate_exact_size(vec2(16.0, 16.0), Sense::hover());
paint_avatar(ui, rect, Some(r.author.avatar_or_default(32)), r.display_name());
// "@name" only when the reply pinged its author, like Discord.
let pinged = m.mentions.iter().any(|u| u.id == r.author.id);
let rname = self.author_name(r);
let label = if pinged { format!("@{rname}") } else { rname };
let name = ui
.add(Label::new(RichText::new(label).font(self.author_font(r, crate::style::medium(14.0))).color(self.name_color(r).gamma_multiply(0.64))).selectable(false).sense(Sense::click()))
.on_hover_cursor(CursorIcon::PointingHand);
if name.clicked() {
let at = name.interact_pointer_pos().unwrap_or(name.rect.right_top());
actions.push(UiAction::OpenProfile { user: Box::new(r.author.clone()), guild: self.guild_of(m), pos: at + vec2(12.0, -40.0) });
}
if let Some((tag, badge)) = r.author.server_tag() {
if let (Some(pos), Some(guild)) = (self.tag_chip(ui, &tag, badge), r.author.server_tag_guild()) {
actions.push(UiAction::OpenTag { guild, pos });
}
}
// A GIF / picture link (hidden in the message itself), an
// attachment or a sticker: Discord's italic placeholder and
// its picture icon, never the bare link.
let placeholder = reply_placeholder(r);
let snippet: String = match placeholder {
Some(p) => p.to_string(),
None => self.plain_mentions(r, r.content.lines().next().unwrap_or("")).chars().take(140).collect(),
};
// Like Discord: clicking the quoted line jumps to the original
// (and flashes it); the text brightens on hover.
let hovered = ui.rect_contains_pointer(ui.available_rect_before_wrap().with_max_y(ui.cursor().top() + 20.0));
let quote_color = if hovered { t.header_primary } else { t.text_normal };
let mut quote = RichText::new(snippet).size(14.0).color(quote_color);
if placeholder.is_some() {
quote = quote.family(crate::style::markup_family(false, true));
}
// (Not selectable: a selectable label takes the press as the
// start of a text selection, and the slightest movement as a
// drag, which swallowed the click that jumps.)
let mut jump = ui.add(Label::new(quote).truncate().selectable(false).sense(Sense::click())).on_hover_cursor(CursorIcon::PointingHand);
if placeholder.is_some() {
let pic = ui
.add(Label::new(RichText::new("\u{E8B9}").font(icon_font(14.0)).color(quote_color)).selectable(false).sense(Sense::click()))
.on_hover_cursor(CursorIcon::PointingHand);
jump = jump.union(pic);
}
if jump.clicked() {
let target = m.message_reference.as_ref().and_then(|x| x.message_id).unwrap_or(r.id);
actions.push(UiAction::JumpTo { channel: m.channel_id, msg: target });
}
}
None => {
ui.label(RichText::new("Original message was deleted").family(crate::style::markup_family(false, true)).size(14.0).color(t.text_muted));
}
}
});
let r = row.response.rect;
let (x0, x1, y_mid, y_end, rad) = (left + 36.0, left + 68.0, r.center().y, r.bottom() + 4.0, 6.0);
let mut pts = vec![pos2(x0, y_end), pos2(x0, y_mid + rad)];
for k in 1..=6 {
let a = std::f32::consts::FRAC_PI_2 * k as f32 / 6.0;
pts.push(pos2(x0 + rad - rad * a.cos(), y_mid + rad - rad * a.sin()));
}
pts.push(pos2(x1, y_mid));
if !compact {
ui.painter().add(Shape::line(pts, Stroke::new(2.0_f32, t.interactive_muted)));
}
}
if compact {
self.compact_row(ui, m, color, forced, editing, actions);
} else {
ui.horizontal_top(|ui| {
ui.add_space(16.0);
let open_profile = |resp: &Response, actions: &mut Vec<UiAction>| {
// AutoMod alerts come from Discord's system "user": no profile.
if m.kind == 24 {
return;
}
// Hovering a name / avatar fetches the profile ahead of the click.
if resp.hovered() {
self.profiles_wanted.borrow_mut().push((m.author.id, m.guild_id));
}
if resp.clicked() {
let at = resp.interact_pointer_pos().unwrap_or(resp.rect.right_top());
actions.push(UiAction::OpenProfile { user: Box::new(m.author.clone()), guild: self.guild_of(m), pos: at + vec2(12.0, -40.0) });
}
self.author_menu(m, self.guild_of(m), resp, actions);
};
let system = is_system(m);
if grouped {
ui.allocate_exact_size(vec2(40.0, 1.0), Sense::hover());
} else if system {
// The gutter icon, level with the 22 px line.
let (rect, _) = ui.allocate_exact_size(vec2(40.0, 22.0), Sense::hover());
let kind = if m.kind == 3 && call_text(m, "", self.store.me_id()).1 { MISSED_CALL } else { m.kind };
system_icon(ui, t, kind, rect);
} else {
let (rect, resp) = ui.allocate_exact_size(vec2(40.0, 40.0), Sense::click());
// Like Discord: an animated avatar and decoration play while the
// message is hovered (last frame's hover: the row's size isn't
// known until it's laid out).
let frame = ui.ctx().cumulative_pass_nr();
let playing = ui.data(|d| d.get_temp::<(Id, u64)>(egui::Id::new("chat_hover_msg"))).is_some_and(|(id, f)| id == m.id && f + 2 >= frame);
paint_avatar(ui, rect, Some(super::avatar_uri(&m.author, 80, playing)), m.display_name());
if let Some(deco) = super::decoration_uri(&m.author, playing) {
egui::Image::new(deco).paint_at(ui, rect.expand(rect.width() * 0.1));
}
open_profile(&resp.on_hover_cursor(CursorIcon::PointingHand), actions);
}
// Discord's text starts 72 px in: 16 + 40 + 16 (the row's 8 px item
// spacing is half of that last gap).
ui.add_space(16.0 - ui.spacing().item_spacing.x);
ui.vertical(|ui| {
ui.set_max_width((full_w - 72.0 - 24.0).max(100.0));
ui.spacing_mut().item_spacing.y = 3.0;
if !grouped && !system {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 6.0;
// Their Nitro display-name font (Discord's chat shows the font
// with the role colour; the effects are for profiles).
let name_font = self.author_font(m, crate::style::medium(text_px()));
let name = ui
.add(Label::new(RichText::new(self.author_name(m)).font(name_font).color(self.name_color(m))).sense(Sense::click()))
.on_hover_cursor(CursorIcon::PointingHand);
open_profile(&name, actions);
self.role_dot(ui, m);
if let Some((tag, badge)) = m.author.server_tag() {
if let (Some(pos), Some(guild)) = (self.tag_chip(ui, &tag, badge), m.author.server_tag_guild()) {
actions.push(UiAction::OpenTag { guild, pos });
}
}
if let Some(url) = self.store.role_icon(self.guild_of(m), &self.author_roles(m)) {
ui.add(egui::Image::new(url).fit_to_exact_size(vec2(20.0, 20.0)));
}
super::bot_badge(ui, t, &m.author);
ui.add_space(2.0);
ui.label(RichText::new(format_timestamp(&m.timestamp)).font(crate::style::medium(12.0)).color(t.text_muted));
});
// Discord's header line is 22 px: the text follows 2 px sooner.
ui.add_space(-2.0);
}
self.message_body(ui, m, color, forced, editing, actions);
});
});
}
// Hover background, deleted overlay, hover time and toolbar.
let rect = Rect::from_min_max(pos2(left, top), pos2(ui.max_rect().right(), ui.cursor().top()));
// The toolbar sticks out above its message, so while the pointer is on
// last frame's toolbar, its message keeps the hover.
let pointer = ui.input(|i| i.pointer.hover_pos());
let on_toolbar = match (prev_toolbar, pointer) {
(Some((_, bar)), Some(p)) => bar.contains(p),
_ => false,
};
let hovered = self.context_menu.is_none()
&& if on_toolbar {
prev_toolbar.is_some_and(|(id, _)| id == m.id)
} else {
ui.rect_contains_pointer(rect)
};
let mentions_me = me.is_some_and(|me| m.mentions.iter().any(|u| u.id == me)) || m.mention_everyone;
// Rencord's MessageSelect: a circle beside the message while Ctrl +
// Shift is held (and on the checked ones after), the row one big button.
let picked = self.picked_msgs.0 == m.channel_id && self.picked_msgs.1.contains(&m.id);
if self.picking {
// Added last, so it's above the row's own links, names and pictures.
let pick = ui.interact(rect, egui::Id::new(("pick_msg", m.id)), Sense::click_and_drag()).on_hover_cursor(CursorIcon::PointingHand);
if pick.clicked() {
actions.push(UiAction::PickMessage { channel: m.channel_id, msg: m.id });
}
}
if self.picking || picked {
// On the first line; on a message taller than the view, it stays
// in sight while the message does.
let first = top + if grouped { 13.0 } else { 29.0 };
let y = first.max(ui.clip_rect().top() + 16.0).min((rect.bottom() - 13.0).max(first));
let c = pos2(rect.right() - 28.0, y);
if picked {
ui.painter().circle_filled(c, 10.0, t.accent);
let tick = vec![c + vec2(-4.5, 0.5), c + vec2(-1.5, 3.5), c + vec2(4.5, -3.0)];
ui.painter().add(Shape::line(tick, Stroke::new(2.0_f32, Color32::WHITE)));
} else {
let ring = if hovered { t.header_primary } else { t.interactive_muted };
ui.painter().circle_stroke(c, 9.0, Stroke::new(2.0_f32, ring));
}
}
let mut fill = Color32::TRANSPARENT;
if picked {
fill = t.accent.gamma_multiply(0.12);
} else if m.meta.deleted && m.meta.deleted_style == DeletedStyle::Overlay {
fill = t.danger.gamma_multiply(0.15);
} else if mentions_me {
fill = t.bg_mentioned;
} else if hovered {
fill = t.bg_message_hover;
}
ui.painter().set(bg, Shape::rect_filled(rect, 0.0, fill));
if mentions_me {
ui.painter().rect_filled(Rect::from_min_size(rect.min, vec2(2.0, rect.height())), 0.0, Color32::from_rgb(0xf0, 0xb2, 0x32));
}
if hovered {
let frame = ui.ctx().cumulative_pass_nr();
ui.data_mut(|d| d.insert_temp(egui::Id::new("chat_hover_msg"), (m.id, frame)));
if grouped {
ui.painter().text(
pos2(rect.left() + 36.0, top + 12.0),
Align2::CENTER_CENTER,
short_time(&m.timestamp),
FontId::proportional(10.5),
t.text_muted,
);
}
// Painted + interacted by hand: `ui.put` would move the layout
// cursor back up and make the following messages overlap.
// (Not while picking messages: it would sit on the circle.)
if !self.picking && !picked {
self.hover_toolbar_ui(ui, m, rect, me, actions);
}
// (Not when the author's name / avatar took it for the member menu.)
if ui.input(|i| i.pointer.secondary_clicked()) && !actions.iter().any(|a| matches!(a, UiAction::MemberMenu { .. })) {
let pos = ui.input(|i| i.pointer.interact_pos()).unwrap_or(rect.center());
actions.push(UiAction::OpenContext { channel: m.channel_id, msg: m.id, pos });
}
}
}
/// AutoMod's messages (type 24), drawn like Discord's: a raid alert card
/// ("Unusual Mention Activity Detected", what it did, Remove
/// Restrictions / Configure Settings), or "AutoMod has blocked a message"
/// with the blocked text and the rule. False if it isn't one RustCord knows.
fn automod_ui(&self, ui: &mut Ui, m: &Message, actions: &mut Vec<UiAction>) -> bool {
let t = &self.theme;
let Some(e) = m.embeds.first() else { return false };
let field = |name: &str| e.fields.iter().find(|f| f.name == name).map(|f| f.value.as_str()).filter(|v| !v.is_empty());
let guild = self.guild_of(m);
let card = |ui: &mut Ui, add: &mut dyn FnMut(&mut Ui)| {
Frame::none().fill(t.bg_secondary).stroke(Stroke::new(1.0_f32, t.border_subtle)).rounding(8.0).inner_margin(Margin::same(12.0)).show(ui, |ui| {
ui.set_max_width(ui.available_width().min(520.0));
ui.spacing_mut().item_spacing.y = 4.0;
add(ui);
});
};
match e.kind.as_deref() {
Some("auto_moderation_notification") => {
let kind = field("notification_type").unwrap_or("");
let (title, body) = match kind {
"mention_raid" => ("Unusual Mention Activity Detected", "We're restricting some messages due to a potential mention raid."),
"raid" | "join_raid" => ("Unusual Join Activity Detected", "We've noticed a lot of new members joining at once. This may be a raid."),
"dm_raid" => ("Unusual DM Activity Detected", "We've noticed members of this server sending a lot of DMs. This may be spam."),
"activity_alerts_enabled" => ("Activity Alerts Enabled", "AutoMod will post here when it notices unusual activity in the server."),
"interaction_blocked" => ("Interaction Blocked", "AutoMod blocked an app's response in this server."),
_ => ("AutoMod Alert", ""),
};
let when = field("raid_datetime")
.and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok())
.or_else(|| chrono::DateTime::parse_from_rfc3339(&m.timestamp).ok())
.map(|d| super::relative_time(d.timestamp() - chrono::Utc::now().timestamp()));
card(ui, &mut |ui| {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 6.0;
let (r, _) = ui.allocate_exact_size(vec2(16.0, 16.0), Sense::hover());
// Discord's ⊘ "restricted" mark.
ui.painter().circle_stroke(r.center(), 6.5, Stroke::new(2.0_f32, t.danger));
ui.painter().line_segment([r.center() + vec2(-4.5, 4.5), r.center() + vec2(4.5, -4.5)], Stroke::new(2.0_f32, t.danger));
ui.label(bold(title).size(15.0).color(t.header_primary));
});
if let Some(w) = &when {
ui.label(RichText::new(w).size(12.0).color(t.text_muted));
}
if !body.is_empty() {
ui.label(RichText::new(body).size(14.0).color(t.text_normal));
} else if !kind.is_empty() {
ui.label(RichText::new(kind.replace('_', " ")).size(14.0).color(t.text_normal));
}
let manage = guild.is_some_and(|g| self.store.has_perm(g, discord::model::permissions::MANAGE_GUILD));
if let (Some(g), true) = (guild, manage) {
ui.add_space(6.0);
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 8.0;
let button = |ui: &mut Ui, label: &str| {
ui.add(Button::new(bold(label).size(13.0).color(t.header_primary)).fill(crate::style::overlay(0.12)).rounding(6.0).min_size(vec2(0.0, 28.0)))
};
if kind == "mention_raid" && button(ui, "Remove Restrictions").clicked() {
actions.push(UiAction::AutoMod { guild: g, clear_raid: true });
}
if button(ui, "Configure Settings").clicked() {
actions.push(UiAction::AutoMod { guild: g, clear_raid: false });
}
});
}
});
true
}
Some("auto_moderation_message") => {
let channel = field("channel_id").and_then(|c| c.parse::<u64>().ok()).and_then(|c| self.store.channels.get(&Id(c)));
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 4.0;
ui.label(RichText::new(icon::SHIELD).font(icon_font(14.0)).color(t.text_muted));
let where_ = channel.map(|c| format!(" in #{}", Store::channel_label(c))).unwrap_or_default();
ui.label(RichText::new(format!("AutoMod has blocked a message{where_}")).size(14.0).color(t.text_muted));
});
card(ui, &mut |ui| {
if let Some(d) = e.description.as_deref().filter(|d| !d.is_empty()) {
self.render_markdown(ui, m, d, t.text_normal, false, actions);
}
let mut facts = Vec::new();
if let Some(r) = field("rule_name") {
facts.push(format!("Rule: {r}"));
}
if let Some(k) = field("keyword") {
facts.push(format!("Keyword: {k}"));
}
if let Some(s) = field("timeout_duration").and_then(|s| s.parse::<u64>().ok()) {
facts.push(format!("Timed out for {}", if s >= 3600 { format!("{}h", s / 3600) } else { format!("{}m", (s / 60).max(1)) }));
}
if !facts.is_empty() {
ui.add_space(4.0);
ui.label(RichText::new(facts.join(" • ")).size(12.5).color(t.text_muted));
}
});
true
}
_ => false,
}
}
fn message_body(
&self,
ui: &mut Ui,
m: &Message,
color: Color32,
forced: bool,
editing: &mut Option<EditState>,
actions: &mut Vec<UiAction>,
) {
let t = &self.theme;
if let Some(es) = editing.as_mut().filter(|e| e.msg == m.id) {
let id = egui::Id::new(("edit", m.id.0));
let has_focus = ui.memory(|mem| mem.has_focus(id));
let save = has_focus && ui.input_mut(|i| !i.modifiers.shift && i.consume_key(Modifiers::NONE, Key::Enter));
let mut cancel = ui.input(|i| i.key_pressed(Key::Escape));
Frame::none()
.fill(t.input_bg)
.rounding(8.0)
.inner_margin(Margin::symmetric(12.0, 8.0))
.show(ui, |ui| {
let r = ui.add(
TextEdit::multiline(&mut es.text)
.id(id)
.frame(false)
.desired_rows(1)
.desired_width(f32::INFINITY)
.font(FontId::proportional(15.0)),
);
if es.focus {
r.request_focus();
es.focus = false;
}
});
let mut save_click = false;
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 3.0;
ui.label(RichText::new("escape to").size(11.5).color(t.text_muted));
cancel |= ui.link(RichText::new("cancel").size(11.5)).on_hover_cursor(egui::CursorIcon::PointingHand).clicked();
ui.label(RichText::new("• enter to").size(11.5).color(t.text_muted));
save_click = ui.link(RichText::new("save").size(11.5)).on_hover_cursor(egui::CursorIcon::PointingHand).clicked();
});
if save || save_click {
actions.push(UiAction::SaveEdit);
} else if cancel {
actions.push(UiAction::CancelEdit);
}
} else {
if m.meta.edits_inline {
for past in &m.meta.edit_history {
self.render_markdown(ui, m, &past.content, t.text_muted, true, actions);
ui.label(RichText::new("(edited)").size(10.5).color(t.text_muted));
}
}
if m.kind == 24 && self.automod_ui(ui, m, actions) {
return;
}
if matches!(m.kind, 18 | 46 | FRIEND_REQUEST_ACCEPTED) {
self.rich_system_message(ui, m, actions);
} else if m.kind == 6 {
self.pin_notice(ui, m, actions);
} else if let Some((sys, who)) = self.system_line(m) {
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing.x = 0.0;
match sys.strip_prefix(&who) {
Some(rest) => {
// The name opens their profile, as in a normal message
// ("X joined the server", "X boosted…", "X started a call").
let name = ui
.add(
Label::new(RichText::new(self.author_name(m)).font(self.author_font(m, crate::style::medium(text_px()))).color(self.name_color(m)))
.selectable(false)
.sense(Sense::click()),
)
.on_hover_cursor(CursorIcon::PointingHand);
if name.hovered() {
let y = name.rect.bottom() - 2.0;
ui.painter().hline(name.rect.x_range(), y, Stroke::new(1.0_f32, self.name_color(m)));
}
if name.clicked() && m.kind != 24 {
let at = name.interact_pointer_pos().unwrap_or(name.rect.left_bottom());
actions.push(UiAction::OpenProfile { user: Box::new(m.author.clone()), guild: self.guild_of(m), pos: at + vec2(12.0, -40.0) });
}
ui.label(RichText::new(rest).size(text_px()).color(t.text_muted));
}
None => {
ui.label(RichText::new(&sys).size(text_px()).color(t.text_muted));
}
}
ui.add_space(4.0);
ui.label(RichText::new(format_timestamp(&m.timestamp)).font(crate::style::medium(12.0)).color(t.text_muted));
});
} else if !m.content.is_empty() && !link_only_media(m) {
self.render_markdown(ui, m, &m.content, color, forced, actions);
}
// Forwarded message: "Forwarded" header, then the snapshot in a quote box.
if m.is_forward() {
for snap in &m.message_snapshots {
let s = &snap.message;
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 4.0;
ui.label(RichText::new(icon::FORWARD).font(icon_font(14.0)).color(t.text_muted));
ui.label(RichText::new("Forwarded").family(crate::style::markup_family(false, true)).size(14.0).color(t.text_muted));
});
let inner = ui.horizontal(|ui| {
ui.add_space(12.0);
ui.vertical(|ui| {
ui.set_max_width(ui.available_width().min(560.0));
if !s.content.is_empty() {
self.render_markdown(ui, m, &s.content, t.text_normal, false, actions);
}
self.attachments_ui(ui, &s.attachments, actions);
let origin = m
.message_reference
.as_ref()
.and_then(|r| r.channel_id)
.and_then(|c| self.store.channels.get(&c))
.map(|c| format!("#{} • ", Store::channel_label(c)))
.unwrap_or_default();
ui.label(RichText::new(format!("{origin}{}", format_timestamp(&s.timestamp))).size(12.0).color(t.text_muted));
});
});
let r = inner.response.rect;
ui.painter().rect_filled(Rect::from_min_size(r.min, vec2(4.0, r.height())), 2.0, t.interactive_muted);
}
}
if m.meta.uploading > 0 {
ui.horizontal(|ui| {
ui.spinner();
let n = m.meta.uploading;
ui.label(RichText::new(format!("Uploading {n} file{}…", if n == 1 { "" } else { "s" })).color(t.text_muted));
});
}
// (Without text, "(edited)" goes under the embeds and buttons.)
let edited = (m.edited_timestamp.is_some() && !m.content.is_empty()) || !m.meta.edit_history.is_empty();
if edited || m.meta.deleted || m.meta.failed {
ui.horizontal(|ui| {
if edited {
let r = ui.label(RichText::new("(edited)").size(10.5).color(t.text_muted));
if !m.meta.edits_inline && !m.meta.edit_history.is_empty() {
r.on_hover_ui(|ui| {
ui.label(RichText::new("Previous versions (MessageLogger)").strong());
for past in &m.meta.edit_history {
ui.label(&past.content);
}
});
}
}
if m.meta.deleted {
ui.label(RichText::new("(deleted)").size(10.5).color(t.danger));
}
if m.meta.failed {
ui.label(RichText::new("Failed to send. Right-click to delete.").size(11.5).color(t.danger));
}
});
}
}
self.attachments_ui(ui, &m.attachments, actions);
// Stickers.
// Discord's "Play sticker animations": 0 always, 1 on hover, 2 never.
let sticker_anim = super::sticker_animation();
for s in &m.sticker_items {
let (rect, resp) = ui.allocate_exact_size(vec2(160.0, 160.0), egui::Sense::click());
let open = self.sticker_popout.as_ref().is_some_and(|p| p.sticker.id == s.id && p.message == m.id);
if open {
// Where it is this frame: the popout follows it while scrolling.
let frame = ui.ctx().cumulative_pass_nr();
ui.ctx().data_mut(|d| d.insert_temp(egui::Id::new("sticker_popout_anchor"), (rect, frame)));
}
if ui.is_rect_visible(rect) {
// (`paint_sticker` also stops when RustCord isn't focused.)
// "On hover" stickers also play while their popout is open
// (Discord's isInteracting).
let play = match sticker_anim {
0 => true,
1 => resp.hovered() || open,
_ => false,
};
super::expression::paint_sticker(ui, rect, s.id, s.format_type, play, None);
}
let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
// Discord's tooltip: the small sticker icon and the name, above it;
// hidden while the popout is open.
let resp = if open {
resp
} else {
resp.on_hover_ui_at_pointer(|ui| {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 4.0;
ui.label(RichText::new(icon::STICKER_SMALL).font(icon_font(14.0)).color(t.header_primary));
ui.label(RichText::new(&s.name).size(14.0).color(t.header_primary));
});
})
};
if resp.clicked() {
actions.push(UiAction::OpenSticker { sticker: s.clone(), channel: m.channel_id, message: m.id, anchor: rect });
}
}
// Poll.
if let Some(poll) = &m.poll {
ui.add_space(4.0);
self.poll_ui(ui, m, poll, actions);
}
// Embeds (a poll result's data embed is drawn as its card instead).
self.embeds_ui(ui, m, actions);
// Buttons, select menus and Components V2 layout.
self.components_ui(ui, m, &m.components, actions);
// Reactions.
if !m.reactions.is_empty() && self.discord_setting("render_reactions", true) {
ui.add_space(2.0);
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing = vec2(4.0, 4.0);
for r in &m.reactions {
let chip = self.reaction_chip(ui, r);
if chip.clicked() {
actions.push(UiAction::React { channel: m.channel_id, msg: m.id, emoji: r.emoji.clone() });
}
if chip.hovered() {
actions.push(UiAction::FetchReactors { channel: m.channel_id, msg: m.id, emoji: r.emoji.clone(), count: r.count });
}
self.reactors_tooltip(chip, m, r, actions);
}
// Discord's "Add Reaction" smiley after the last one, while
// the pointer is over the row.
let row_id = egui::Id::new(("reactions_row", m.id.0));
let was: Option<Rect> = ui.ctx().data(|d| d.get_temp(row_id));
if was.is_some_and(|r| ui.rect_contains_pointer(r.expand(2.0))) && self.context_menu.is_none() && self.can_add_reactions(m.channel_id) {
let (r, b) = ui.allocate_exact_size(vec2(26.0, 30.0), Sense::click());
ui.painter().text(r.center(), Align2::CENTER_CENTER, icon::EMOJI, icon_font(16.0), if b.hovered() { t.interactive_hover } else { t.interactive_normal });
if b.on_hover_cursor(CursorIcon::PointingHand).on_hover_text("Add Reaction").clicked() {
actions.push(UiAction::OpenPicker { channel: m.channel_id, msg: m.id, pos: r.right_top() });
}
}
let row = ui.min_rect();
ui.ctx().data_mut(|d| d.insert_temp(row_id, Rect::from_min_max(row.min, pos2(row.right() + 30.0, row.bottom()))));
});
}
}
// ---- markdown -------------------------------------------------------
fn render_markdown(&self, ui: &mut Ui, m: &Message, text: &str, color: Color32, forced: bool, actions: &mut Vec<UiAction>) {
self.render_markdown_with(ui, m, text, text_px(), color, forced, actions);
}
/// Markdown at a different base size (profile bios use 14px).
pub(crate) fn render_markdown_sized(&self, ui: &mut Ui, m: &Message, text: &str, base: f32, color: Color32, actions: &mut Vec<UiAction>) {
self.render_markdown_with(ui, m, text, base, color, false, actions);
}
#[allow(clippy::too_many_arguments)]
pub(super) fn render_markdown_with(&self, ui: &mut Ui, m: &Message, text: &str, base: f32, color: Color32, forced: bool, actions: &mut Vec<UiAction>) {
// Discord's 14 px text (embeds, bios) sits on exact 18 px lines with
// 18 px emoji: the rows get that height themselves, with no gaps
// between them.
if base < text_px() {
let lh = (base * 9.0 / 7.0).round();
ui.scope(|ui| {
ui.spacing_mut().item_spacing.y = 0.0;
self.render_blocks(ui, m, text, base, Some(lh), None, color, forced, actions);
});
} else {
self.render_blocks(ui, m, text, base, None, None, color, forced, actions);
}
}
/// A profile bio as Discord sets it: 14 px text on 18 px lines, with its
/// emoji at 1.375 em (19.25 px; a line holding one grows to fit it).
pub(crate) fn render_bio(&self, ui: &mut Ui, m: &Message, text: &str, color: Color32, actions: &mut Vec<UiAction>) {
ui.scope(|ui| {
ui.spacing_mut().item_spacing.y = 0.0;
self.render_blocks(ui, m, text, 14.0, Some(18.0), Some(19.25), color, false, actions);
});
}
/// [`Self::render_markdown_with`]'s blocks; `lh` is the fixed line height
/// of small text.
#[allow(clippy::too_many_arguments)]
fn render_blocks(&self, ui: &mut Ui, m: &Message, text: &str, base: f32, lh: Option<f32>, emoji: Option<f32>, color: Color32, forced: bool, actions: &mut Vec<UiAction>) {
let t = &self.theme;
// Streamer Mode → Hide invite links.
let masked = super::HIDE_INVITES.load(std::sync::atomic::Ordering::Relaxed).then(|| mask_invites(text));
let text = masked.as_deref().unwrap_or(text);
let blocks = markdown::parse(text);
// Emoji-only messages are shown "jumbo", like Discord.
let emoji_size = match emoji {
Some(px) => px,
None if markdown::is_emoji_only(&blocks) => 48.0,
None => lh.unwrap_or((base * 1.375).round()),
};
let is_quote = |b: Option<&Block>| matches!(b, Some(Block::Line { kind: LineKind::Quote, .. }));
let quote_edges: Vec<(bool, bool)> = (0..blocks.len())
.map(|i| (!is_quote(i.checked_sub(1).and_then(|j| blocks.get(j))), !is_quote(blocks.get(i + 1))))
.collect();
for (block_index, block) in blocks.into_iter().enumerate() {
let first_block = block_index == 0;
let (quote_first, quote_last) = quote_edges[block_index];
match block {
Block::Code { code, lang } => {
// Discord: 6 px above the box (one is the row gap), 18 px
// lines, nothing below.
ui.add_space(5.0);
Frame::none()
.fill(code_fill())
.stroke(Stroke::new(1.0_f32, crate::style::overlay(0.2)))
.rounding(4.0)
.inner_margin(7.0)
.show(ui, |ui| {
// Discord's box: 90 % of the text column, at most half
// the window (50vw), border and padding included.
ui.set_width(((ui.available_width() + 16.0) * 0.9).min(ui.ctx().screen_rect().width() * 0.5) - 16.0);
// Discord's highlight.js colours for the block's language.
let s = &t.syntax;
let font = FontId::monospace(14.0);
let mut job = egui::text::LayoutJob::default();
job.wrap.max_width = ui.available_width();
let push = |job: &mut egui::text::LayoutJob, text: &str, color: Color32| {
if !text.is_empty() {
job.append(text, 0.0, egui::TextFormat { font_id: font.clone(), color, line_height: Some(18.0), ..Default::default() });
}
};
let mut at = 0;
for (start, end, tok) in crate::highlight::highlight(&lang, &code) {
use crate::highlight::Tok;
push(&mut job, &code[at..start], s.code);
let color = match tok {
Tok::Keyword | Tok::Section => s.keyword,
Tok::Type | Tok::BuiltIn => s.r#type,
Tok::Title => s.title,
Tok::Attr => s.attribute,
Tok::Meta => s.decorator,
Tok::Number => s.number,
Tok::Str => s.string,
Tok::Comment => s.comment,
Tok::Addition => s.addition,
Tok::Deletion => s.deletion,
Tok::Literal | Tok::Plain => s.code,
};
push(&mut job, &code[start..end], color);
at = end;
}
push(&mut job, &code[at..], s.code);
ui.add(Label::new(job).wrap());
});
}
Block::Line { kind, inlines } => {
if inlines.is_empty() {
// A blank line is a full (empty) line in Discord.
ui.add_space(lh.unwrap_or((base * 1.15).round()));
continue;
}
let heading = matches!(kind, LineKind::Heading(_));
// Discord: h1 8 px above, h2 / h3 16 px (8 when first), all
// 8 px below; here less the taller rows' own leading.
if let LineKind::Heading(level) = kind {
ui.add_space(match (first_block, level) {
(true, _) => 8.0,
(false, 1) => 8.0,
(false, 2) => 6.0,
(false, _) => 9.0,
});
}
// (Only body lines are tight; headings keep their own height.)
let lh = lh.filter(|_| matches!(kind, LineKind::Normal | LineKind::Quote | LineKind::Bullet(_) | LineKind::Numbered(..)));
let (size, color) = match kind {
LineKind::Heading(1) => (24.0, if forced { color } else { t.header_primary }),
LineKind::Heading(2) => (20.0, if forced { color } else { t.header_primary }),
LineKind::Heading(_) => (text_px(), if forced { color } else { t.header_primary }),
LineKind::Subtext => (14.0, if forced { color } else { t.text_muted }),
_ => (base, color),
};
match kind {
LineKind::Quote => {
// Discord's quote: one 4 px bar (rgb 108,108,118, round ends)
// down the whole quote, text 12 px after it, 22 px lines.
if !quote_first {
ui.add_space(-ui.spacing().item_spacing.y);
}
let row = ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 0.0;
let (r, _) = ui.allocate_exact_size(vec2(4.0, lh.unwrap_or((size * 1.375).round())), Sense::hover());
ui.add_space(12.0);
self.inline_row(ui, m, &inlines, size, emoji_size, lh, color, forced, heading, actions);
r
});
let bar = Rect::from_min_max(row.inner.min, pos2(row.inner.right(), row.response.rect.bottom()));
let rounding = Rounding { nw: if quote_first { 2.0 } else { 0.0 }, ne: if quote_first { 2.0 } else { 0.0 }, sw: if quote_last { 2.0 } else { 0.0 }, se: if quote_last { 2.0 } else { 0.0 } };
ui.painter().rect_filled(bar, rounding, Color32::from_rgb(108, 108, 118));
}
// Discord's lists: 16px in per level, the marker hanging left
// of the text, 4px between items.
LineKind::Bullet(depth) | LineKind::Numbered(_, depth) => {
ui.horizontal_top(|ui| {
ui.spacing_mut().item_spacing.x = 0.0;
let indent = 16.0 * (depth as f32 + 1.0);
let (slot, _) = ui.allocate_exact_size(vec2(indent, lh.unwrap_or(size + 6.0)), Sense::hover());
// The browser's list markers, as Discord shows them:
// a disc, then a ring, then a square, 13 px left of the text.
let mc = pos2(slot.right() - 13.0, slot.center().y);
match kind {
LineKind::Numbered(n, _) => {
let g = ui.painter().layout_no_wrap(format!("{n}."), FontId::proportional(size), color);
ui.painter().galley(pos2(slot.right() - g.size().x - 6.0, slot.top() + 1.0), g, color);
}
_ if depth == 0 => {
ui.painter().circle_filled(mc, 2.6, color);
}
_ if depth == 1 => {
ui.painter().circle_stroke(mc, 2.3, Stroke::new(1.0_f32, color));
}
_ => {
ui.painter().rect_filled(Rect::from_center_size(mc, vec2(4.6, 4.6)), 0.0, color);
}
}
self.inline_row(ui, m, &inlines, size, emoji_size, lh, color, forced, heading, actions);
});
// Discord: 22 px lines, 26 px apart.
ui.add_space(if lh.is_some() { 4.0 } else { 1.0 });
}
_ => self.inline_row(ui, m, &inlines, size, emoji_size, lh, color, forced, heading, actions),
}
if heading {
ui.add_space(6.0);
}
}
}
}
}
/// How wide `text` would be on unbroken lines (its widest line), as
/// [`Self::render_markdown_with`] draws it: what CSS calls max-content.
/// Embeds size their field columns with it.
pub(super) fn markdown_width(&self, ui: &Ui, m: &Message, text: &str, base: f32, strong: bool) -> f32 {
let emoji = if base < text_px() { (base * 9.0 / 7.0).round() } else { (base * 1.375).round() };
let measure = |s: &str, font: FontId| ui.fonts(|f| f.layout_no_wrap(s.replace(['\u{FE0E}', '\u{FE0F}'], ""), font, Color32::WHITE).size().x);
let chip = |s: String| measure(&s, crate::style::medium(base)) + 4.0;
let mut widest: f32 = 0.0;
for block in markdown::parse(text) {
let Block::Line { kind, inlines } = block else { return f32::INFINITY };
let mut w = match kind {
LineKind::Quote => 16.0,
LineKind::Bullet(d) | LineKind::Numbered(_, d) => 16.0 * (d as f32 + 1.0),
_ => 0.0,
};
let size = match kind {
LineKind::Heading(1) => 24.0,
LineKind::Heading(2) => 20.0,
LineKind::Heading(_) => text_px(),
_ => base,
};
for inline in &inlines {
w += match inline {
Inline::Text(s, st) if st.code => measure(s, FontId::monospace((size * 0.85).round())) + 6.0,
Inline::Text(s, st) => {
let bold = st.bold || strong || matches!(kind, LineKind::Heading(_));
let family = if bold && !st.italic && self.markup_semibold.get() { egui::FontFamily::Name(crate::style::BOLD.into()) } else { crate::style::markup_family(bold, st.italic) };
measure(s, FontId::new(size, family))
}
Inline::Link { text, style, .. } => measure(text, FontId::new(size, crate::style::markup_family(style.bold, style.italic))),
Inline::User(id) => chip(format!("@{}", self.user_name(m, *id))),
Inline::Channel(id) => chip(self.store.channel_name(*id)) + size + 2.0,
Inline::Role(id) => chip(format!("@{}", self.store.role_name(m.guild_id, *id).unwrap_or_else(|| "deleted-role".into()))),
Inline::Everyone(word) => chip(word.to_string()),
Inline::Command(name) => chip(format!("/{name}")),
Inline::Nav(label) => chip(label.to_string()),
Inline::Emoji { .. } | Inline::Unicode { .. } => emoji,
Inline::Timestamp { unix, style } => measure(&format_unix(*unix, *style), FontId::proportional(size)) + 4.0,
};
}
widest = widest.max(w);
}
widest
}
/// A mentioned user as this channel names them.
fn user_name(&self, m: &Message, id: Id) -> String {
m.mentions
.iter()
.find(|u| u.id == id)
.or_else(|| self.store.users.get(&id))
.map(|u| self.store.name_in(self.guild_of(m), Some(m.channel_id), u))
.unwrap_or_else(|| "unknown-user".into())
}
#[allow(clippy::too_many_arguments)]
fn inline_row(
&self,
ui: &mut Ui,
m: &Message,
inlines: &[Inline],
size: f32,
emoji_size: f32,
lh: Option<f32>,
color: Color32,
forced: bool,
heading: bool,
actions: &mut Vec<UiAction>,
) {
let t = &self.theme;
let row = ui.horizontal_wrapped(|ui| {
// Lines 22 px apart at Discord's 16 px (its 1.375 line height).
ui.spacing_mut().item_spacing = vec2(0.0, if lh.is_some() { 0.0 } else if size >= text_px() { 3.0 } else { 2.0 });
for inline in inlines {
match inline {
Inline::Text(text, st) => {
let strong = st.bold || heading;
let c = if strong && !forced { t.header_primary } else { color };
// Discord: bold and headings in gg sans 700, italics in the italic face.
let family = if strong && !st.italic && self.markup_semibold.get() {
egui::FontFamily::Name(crate::style::BOLD.into())
} else {
crate::style::markup_family(strong, st.italic)
};
// (A text-style selector left on its own has no glyph.)
let shown: std::borrow::Cow<str> = if text.contains(['\u{FE0E}', '\u{FE0F}']) { text.replace(['\u{FE0E}', '\u{FE0F}'], "").into() } else { text.as_str().into() };
let mut rt = RichText::new(shown).family(family).size(size).color(c).line_height(lh);
if st.underline {
rt = rt.underline();
}
if st.strike {
rt = rt.strikethrough();
}
if st.code && st.spoiler.is_none() {
// Discord's inline code: a rounded chip, 85% size,
// broken at spaces onto the next line like Discord's
// (each piece one measured widget, so rows wrap).
let mono = FontId::monospace((size * 0.85).round());
let width_of = |ui: &Ui, s: &str| ui.fonts(|f| f.layout_no_wrap(s.to_string(), mono.clone(), c).size().x) + 6.0;
let mut rest = text.as_str();
let mut first = true;
while !rest.is_empty() {
if !first {
rest = rest.trim_start();
if rest.is_empty() {
break;
}
}
let (room, full) = (ui.available_size_before_wrap().x, ui.max_rect().width());
let fit_in = |limit: f32| -> Option<usize> {
if width_of(ui, rest) <= limit {
return Some(rest.len());
}
// The last space the row still reaches: widths only grow
// with the cut, so it is searched for, not tried one by one
// (a long span of short words is measured ~10 times, not ~1000).
let spaces: Vec<usize> = rest.char_indices().filter(|&(i, ch)| ch == ' ' && i > 0).map(|(i, _)| i).collect();
let fitting = spaces.partition_point(|&i| width_of(ui, &rest[..i]) <= limit);
fitting.checked_sub(1).map(|k| spaces[k])
};
let cut = fit_in(room).or_else(|| fit_in(full)).unwrap_or_else(|| rest.find(' ').filter(|&i| i > 0).unwrap_or(rest.len()));
let galley = ui.fonts(|f| f.layout_no_wrap(rest[..cut].trim_end().to_string(), mono.clone(), c));
// (Discord's chip makes a small-text line 1 px taller.)
let chip_h = lh.map_or(galley.size().y + 2.0, |h| h + 1.0);
let (r, _) = ui.allocate_exact_size(vec2(galley.size().x + 6.0, chip_h), Sense::hover());
let r = Rect::from_center_size(r.center(), vec2(r.width(), galley.size().y + 2.0));
ui.painter().rect(r, 4.0, code_fill(), Stroke::new(1.0_f32, crate::style::overlay(0.2)));
ui.painter().galley(pos2(r.left() + 3.0, r.center().y - galley.size().y / 2.0), galley, c);
rest = &rest[cut..];
first = false;
}
continue;
}
if let Some(k) = st.spoiler {
// Discord's spoiler: a 4 px rounded box per line
// (solid while hidden, a faint tint once revealed).
let hidden = !self.spoiler_shown((m.id, k));
let (bg_hidden, bg_hover, bg_shown) = spoiler_colors(t);
let (pos, galley, r) = Label::new(rt).sense(if hidden { Sense::click() } else { Sense::hover() }).layout_in_ui(ui);
let bg = if !hidden {
bg_shown
} else if r.hovered() {
bg_hover
} else {
bg_hidden
};
for row in &galley.rows {
let line = row.rect.translate(pos.to_vec2());
if line.width() > 0.5 {
ui.painter().rect_filled(line.expand2(vec2(0.0, 1.0)), 4.0, bg);
}
}
if hidden {
if r.on_hover_cursor(CursorIcon::PointingHand).clicked() {
actions.push(UiAction::Reveal(m.id, k));
}
} else {
ui.painter().galley(pos, galley, c);
}
continue;
}
ui.label(rt);
}
Inline::Link { text, url, style } if style.spoiler.is_some_and(|k| !self.spoiler_shown((m.id, k))) => {
// A link inside a hidden spoiler is hidden with it.
let _ = url;
let rt = RichText::new(text).size(size).color(Color32::TRANSPARENT);
let (pos, galley, r) = Label::new(rt).sense(Sense::click()).layout_in_ui(ui);
let (bg, bg_hover, _) = spoiler_colors(t);
for row in &galley.rows {
let line = row.rect.translate(pos.to_vec2());
if line.width() > 0.5 {
ui.painter().rect_filled(line.expand2(vec2(0.0, 1.0)), 4.0, if r.hovered() { bg_hover } else { bg });
}
}
if let (true, Some(k)) = (r.on_hover_cursor(CursorIcon::PointingHand).clicked(), style.spoiler) {
actions.push(UiAction::Reveal(m.id, k));
}
}
Inline::Link { text, url, style } => {
let mut rt = RichText::new(text).family(crate::style::markup_family(style.bold, style.italic)).size(size).color(t.text_link).line_height(lh);
if style.underline || super::UNDERLINE_LINKS.load(std::sync::atomic::Ordering::Relaxed) {
rt = rt.underline();
}
ui.hyperlink_to(rt, url).on_hover_text(url);
}
Inline::User(id) => {
let chip = mention_chip(ui, t, format!("@{}", self.user_name(m, *id)), size, None);
let user = m.mentions.iter().find(|u| u.id == *id).or_else(|| self.store.users.get(id));
// Discord opens the profile beside the mention itself.
if let (true, Some(user)) = (chip.clicked(), user) {
actions.push(UiAction::OpenProfile { user: Box::new(user.clone()), guild: self.guild_of(m), pos: chip.rect.right_top() + vec2(8.0, 0.0) });
}
}
Inline::Channel(id) => {
// Discord: the channel's icon (# or a speaker) and its
// name; one you can't see is "# unknown" and inert.
let known = self.store.channels.get(id);
let voice = known.is_some_and(|c| matches!(c.kind, 2 | 13));
let glyph = if voice { icon::VOICE } else { icon::HASH };
let chip = mention_chip_with(ui, t, Some(glyph), self.store.channel_name(*id), size, None, known.is_some());
if chip.clicked() {
actions.push(UiAction::SelectChannel(*id));
}
}
Inline::Role(id) => {
let name = self.store.role_name(m.guild_id, *id).unwrap_or_else(|| "deleted-role".into());
// Coloured roles tint their mention.
let rc = self.store.role_color(self.guild_of(m), &[*id]).filter(|c| *c != 0).map(|c| Color32::from_rgb((c >> 16) as u8, (c >> 8) as u8, c as u8));
mention_chip_with(ui, t, None, format!("@{name}"), size, rc, false);
}
Inline::Everyone(word) => {
mention_chip_with(ui, t, None, word.to_string(), size, None, false);
}
Inline::Command(name) => {
if mention_chip(ui, t, format!("/{name}"), size, None).clicked() {
actions.push(UiAction::UseCommand(name.clone()));
}
}
Inline::Nav(label) => {
mention_chip(ui, t, label.to_string(), size, None);
}
Inline::Emoji { name, id, animated } => {
let url = super::emoji_img(*id, *animated, 96);
inline_emoji(ui, url, size, emoji_size).on_hover_text(format!(":{name}:"));
}
Inline::Unicode { seq, style } => {
let hidden = style.spoiler.is_some_and(|k| !self.spoiler_shown((m.id, k)));
if hidden {
let (rect, r) = ui.allocate_exact_size(vec2(emoji_size, emoji_size), Sense::click());
ui.painter().rect_filled(rect, 4.0, if r.hovered() { spoiler_colors(t).1 } else { spoiler_colors(t).0 });
if let (true, Some(k)) = (r.on_hover_cursor(CursorIcon::PointingHand).clicked(), style.spoiler) {
actions.push(UiAction::Reveal(m.id, k));
}
} else {
inline_emoji(ui, twemoji_url(seq), size, emoji_size);
}
}
Inline::Timestamp { unix, style } => {
// Discord: --background-mod-subtle, 3 px corners, 2 px padding.
let galley = ui.painter().layout_no_wrap(format_unix(*unix, *style), FontId::proportional(size), color);
let (rect, r) = ui.allocate_exact_size(vec2(galley.size().x + 4.0, galley.size().y), Sense::hover());
ui.painter().rect_filled(rect, 3.0, crate::style::rgba(151, 151, 159, 31));
ui.painter().galley(pos2(rect.left() + 2.0, rect.top()), galley, color);
if let Some(d) = chrono::DateTime::from_timestamp(*unix, 0) {
r.on_hover_text(d.with_timezone(&chrono::Local).format("%A, %-d %B %Y %H:%M").to_string());
}
}
}
}
});
// More than one row: the text wrapped (an embed then takes its full width).
if row.response.rect.height() > lh.unwrap_or(size * 1.375) * 1.5 {
self.markup_wrapped.set(true);
}
}
// ---- composer -------------------------------------------------------
pub(super) fn composer(&mut self, ui: &mut Ui, ch: Id, channel: &Channel, name: &str) {
let t = self.theme.clone();
// Where the composer's stack starts (the reply / command / schedule
// bars sit on top of the box): "… is typing…" goes above all of it.
let stack_top = ui.cursor().top();
// Discord's reply bar (measured in its web app, 2026-11-17): 32 px on
// top of the box, "Replying to" in 14 px with the name in semibold and
// its role colour, 16 px in; on the right "@ ON" / "@ OFF" (not for
// your own messages) and a round ✕ in a 40 px button.
let mut cancel_reply = false;
let reply_info = self.reply.as_ref().filter(|r| r.channel == ch).map(|r| {
let m = self.store.message(ch, r.msg);
let mine = m.is_some_and(|m| Some(m.author.id) == self.store.me_id());
(r.author.clone(), m.map_or(t.header_primary, |m| self.name_color(m)), r.mention, mine)
});
if let Some((author, name_color, mention, mine)) = reply_info {
let (bar, _) = ui.allocate_exact_size(vec2(ui.available_width(), 32.0), Sense::hover());
let p = ui.painter().clone();
p.rect_filled(bar, Rounding { nw: 8.0, ne: 8.0, sw: 0.0, se: 0.0 }, t.bg_secondary);
let mid = bar.center().y;
let close = Rect::from_min_size(pos2(bar.right() - 44.0, bar.top()), vec2(40.0, 32.0));
let close_resp = ui.interact(close, ui.id().with(("reply_close", ch.0)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
let cc = if close_resp.hovered() { t.interactive_hover } else { t.header_secondary };
p.circle_filled(close.center(), 8.0, cc);
let x = Stroke::new(1.6_f32, t.bg_secondary);
p.line_segment([close.center() + vec2(-3.0, -3.0), close.center() + vec2(3.0, 3.0)], x);
p.line_segment([close.center() + vec2(-3.0, 3.0), close.center() + vec2(3.0, -3.0)], x);
if close_resp.on_hover_text("Cancel reply").on_hover_cursor(CursorIcon::PointingHand).clicked() {
cancel_reply = true;
}
let mut text_right = close.left();
if !mine {
let (label, color) = if mention { ("@ ON", t.text_link) } else { ("@ OFF", t.text_muted) };
let font = FontId::new(14.0, egui::FontFamily::Name(crate::style::BOLD.into()));
let w = ui.fonts(|f| f.layout_no_wrap(label.to_string(), font.clone(), color).size().x) + 24.0;
let mr = Rect::from_min_size(pos2(close.left() - w, bar.top()), vec2(w, 32.0));
let resp = ui.interact(mr, ui.id().with(("reply_mention", ch.0)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
p.text(mr.center(), Align2::CENTER_CENTER, label, font, color);
// (The line between the two buttons.)
p.vline(mr.right(), (bar.top() + 8.0)..=(bar.bottom() - 8.0), Stroke::new(1.0_f32, t.border_subtle));
let tip = if mention { "Click to disable pinging the original author." } else { "Click to enable pinging the original author." };
if resp.on_hover_text(tip).on_hover_cursor(CursorIcon::PointingHand).clicked() {
if let Some(r) = self.reply.as_mut() {
r.mention = !r.mention;
}
}
text_right = mr.left();
}
let tp = p.with_clip_rect(Rect::from_min_max(bar.min, pos2(text_right - 8.0, bar.bottom())));
let lead = tp.text(pos2(bar.left() + 16.0, mid), Align2::LEFT_CENTER, "Replying to ", FontId::proportional(14.0), t.text_normal);
super::paint_text_emoji(ui, &tp, pos2(lead.right(), mid), &author, FontId::new(14.0, egui::FontFamily::Name(crate::style::BOLD.into())), name_color);
}
self.command_bar(ui, ch);
self.schedule_bar(ui, ch);
let id = egui::Id::new(("composer", ch.0));
if std::mem::take(&mut self.compose.focus_composer) {
ui.memory_mut(|m| m.request_focus(id));
}
let focused = ui.memory(|m| m.has_focus(id));
// While the command list is up, arrows move in it and Enter/Tab pick.
let listing = {
let d = self.drafts.get(&ch).map(String::as_str).unwrap_or("");
d.starts_with('/') && self.slash_listing(d) && self.compose.command.is_none() && self.compose.apps_dismissed.as_ref().map_or(true, |(c, x)| *c != ch || x != d)
};
if focused && listing {
ui.input_mut(|i| {
if i.consume_key(Modifiers::NONE, Key::ArrowDown) {
self.compose.apps_nav += 1;
self.compose.apps_scroll = true;
}
if i.consume_key(Modifiers::NONE, Key::ArrowUp) {
self.compose.apps_nav -= 1;
self.compose.apps_scroll = true;
}
if i.consume_key(Modifiers::NONE, Key::Tab) || i.consume_key(Modifiers::NONE, Key::Enter) {
self.compose.apps_pick = true;
}
});
}
// Likewise the "@" member list (it takes Escape too).
if focused && !listing {
self.mention_keys(ui, ch);
}
// Shift + Enter is a new line (egui's `consume_key` ignores an extra
// Shift, so it has to be ruled out here).
let send = focused && ui.input_mut(|i| !i.modifiers.shift && i.consume_key(Modifiers::NONE, Key::Enter));
// Appearance → Chat Box → "Show send message button".
let mut send_clicked = false;
// (With the right-click menu open, Escape just closes the menu.)
if focused && self.compose.text_menu.is_none() && ui.input(|i| i.key_pressed(Key::Escape)) {
if self.reply.is_some() {
cancel_reply = true;
} else if self.new_since.is_some_and(|n| n.channel == ch) || self.unread_marker.contains_key(&ch) {
// Discord: Escape marks the channel read (bar and NEW line go).
self.mark_channel_read(ch);
}
}
if cancel_reply {
self.reply = None;
}
let mut draft = self.drafts.remove(&ch).unwrap_or_default();
// Ctrl+V with files or a picture on the clipboard: they become uploads,
// like Discord (and any text that came with them isn't pasted too).
let pasting = focused && (self.compose.paste_key || ui.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Paste(_)))));
if pasting {
self.compose.paste_key = false;
if let Some(clip) = crate::clipboard::read_attachments() {
ui.input_mut(|i| i.events.retain(|e| !matches!(e, egui::Event::Paste(_))));
self.add_clip(ch, clip);
}
}
// An emoji is one thing to the keyboard, like Discord: Backspace / Delete
// beside one removes all of it (it's `<:name:id>`, or several code
// points, underneath), not one hidden character of it.
let caret_before = TextEdit::load_state(ui.ctx(), id).and_then(|s| s.cursor.char_range());
if let Some(at) = caret_before.filter(|r| focused && r.primary.index == r.secondary.index).map(|r| r.primary.index) {
let spans = composer_emoji_spans(&draft);
for (key, back) in [(Key::Backspace, true), (Key::Delete, false)] {
let hit = spans.iter().find(|(s, n, _)| *n > 1 && if back { *s < at && at <= s + n } else { *s <= at && at < s + n });
let Some(&(s, n, _)) = hit else { continue };
if ui.input_mut(|i| i.consume_key(Modifiers::NONE, key)) {
draft.replace_range(char_to_byte(&draft, s)..char_to_byte(&draft, s + n), "");
if let Some(mut st) = TextEdit::load_state(ui.ctx(), id) {
st.cursor.set_char_range(Some(egui::text::CCursorRange::one(egui::text::CCursor::new(s))));
st.store(ui.ctx(), id);
}
break;
}
}
}
// egui moves the caret on a right-click; keep a selection for Cut / Copy.
let kept_selection = ui
.input(|i| i.pointer.button_pressed(egui::PointerButton::Secondary))
.then(|| TextEdit::load_state(ui.ctx(), id).and_then(|s| s.cursor.char_range()))
.flatten()
.filter(|r| r.primary.index != r.secondary.index);
let edit_last = focused && draft.is_empty() && ui.input(|i| i.key_pressed(Key::ArrowUp));
let placeholder = if channel.guild_id.is_some() { format!("Message #{name}") } else { format!("Message @{name}") };
let has_uploads = self.uploads.get(&ch).is_some_and(|u| !u.is_empty());
let (mut plus, mut emoji_at, mut remove, mut gif_at) = (None, None, None, None);
let (mut gift, mut sticker_at) = (false, None);
// The GIF / sticker / emoji buttons (clicks there toggle the picker).
let mut expr_buttons = Rect::NOTHING;
let mut typed_colon: Option<usize> = None;
let replying = self.reply.as_ref().is_some_and(|r| r.channel == ch);
let mut misspelled: Vec<std::ops::Range<usize>> = Vec::new();
let mut clicked_word: Option<std::ops::Range<usize>> = None;
let mut apps = false;
// Discord: 56 px inside a 1 px border, 8 px corners; over a client theme
// the gradient with its 50 % black overlay (like the user panel).
let themed = t.gradient.is_some();
let bg_slot = ui.painter().add(egui::Shape::Noop);
let resp = Frame::none()
.fill(if themed { Color32::TRANSPARENT } else { t.input_bg })
.stroke(Stroke::new(1.0_f32, t.border_subtle))
.rounding(if replying { Rounding { nw: 0.0, ne: 0.0, sw: 8.0, se: 8.0 } } else { Rounding::same(8.0) })
.inner_margin(Margin { left: 1.0, right: 1.0, top: 1.0, bottom: 1.0 })
.show(ui, |ui| {
// Pending uploads tray.
if let Some(list) = self.uploads.get(&ch).filter(|l| !l.is_empty()) {
ScrollArea::horizontal().id_salt(("uploads", ch.0)).show(ui, |ui| {
ui.vertical(|ui| {
ui.add_space(20.0);
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 16.0;
ui.add_space(12.0);
for (i, u) in list.iter().enumerate() {
if upload_tile(ui, &t, u) {
remove = Some(i);
}
}
});
ui.add_space(10.0);
});
});
let y = ui.cursor().top();
ui.painter().hline(ui.max_rect().x_range(), y, Stroke::new(1.0_f32, t.bg_hover));
}
// Discord condenses the right-hand buttons when the box is 450 px
// wide or less: GIF and sticker go (the emoji picker has their tabs).
let condensed = ui.available_width() + 2.0 <= 450.0;
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 0.0;
// "+" upload button: a plain 20 px plus in a 32 px button, 12 px in.
ui.add_space(11.0);
let (row, b) = ui.allocate_exact_size(vec2(32.0, 56.0), Sense::click());
let r = Rect::from_center_size(row.center(), vec2(32.0, 32.0));
let open = self.compose.plus_menu.is_some_and(|(c, _, _)| c == ch);
let c = if b.hovered() || open { t.interactive_hover } else { t.interactive_normal };
ui.painter().text(r.center(), Align2::CENTER_CENTER, icon::ADD, icon_font(16.0), c);
if b.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
plus = Some(r);
}
ui.add_space(16.0);
// Gift, GIF, sticker, emoji and Apps sit on the right: 32 px
// buttons 8 px apart, 12 px from the edge.
let buttons = if condensed { 3.0 } else { 5.0 } + if self.prefs.send_button { 1.0 } else { 0.0 };
let w = (ui.available_width() - (buttons * 40.0 + 12.0)).max(60.0);
// Emoji show as pictures while you type, like Discord: the
// layouter leaves a gap for each and the images go on top.
// (With typing effects the letters are laid out invisible and
// painted below, moved and coloured.)
let mut fx_style = super::typing_fx::Style::from_prefs(&self.prefs);
if self.prefs.legacy_chat_input {
(fx_style.anim, fx_style.color) = (0, 0);
}
let text_color = if fx_style.active() { Color32::TRANSPARENT } else { t.text_normal };
let mut layouter = |ui: &Ui, text: &str, wrap: f32| {
let job = composer_layout(ui, text, FontId::proportional(text_px()), text_color, wrap);
ui.fonts(|f| f.layout_job(job))
};
let mut out = TextEdit::multiline(&mut draft)
.id(id)
.frame(false)
.desired_rows(1)
.desired_width(w)
.font(FontId::proportional(text_px()))
.text_color(t.text_normal)
.margin(vec2(4.0, 17.0))
.layouter(&mut layouter)
.show(ui);
if let Some(range) = kept_selection.filter(|_| out.response.hovered()) {
out.state.cursor.set_char_range(Some(range));
out.state.clone().store(ui.ctx(), id);
}
// The caret never rests inside an emoji: an arrow key steps
// over it, a click lands on its nearer side.
if let Some(r) = out.state.cursor.char_range() {
let p = r.primary.index;
if let Some(&(s, n, _)) = composer_emoji_spans(&draft).iter().find(|(s, n, _)| *s < p && p < s + n) {
let to = match caret_before.map(|c| c.primary.index) {
Some(o) if o >= s + n => s,
Some(o) if o <= s => s + n,
_ if p - s < s + n - p => s,
_ => s + n,
};
let primary = egui::text::CCursor::new(to);
let secondary = if r.secondary.index == p { primary } else { r.secondary };
out.state.cursor.set_char_range(Some(egui::text::CCursorRange { primary, secondary }));
out.state.clone().store(ui.ctx(), id);
ui.ctx().request_repaint();
}
}
let fx_state = fx_style.active().then(|| super::typing_fx::state(ui.ctx(), id));
let fx_guard = fx_state.as_ref().map(|s| {
let mut st = s.lock().unwrap_or_else(|e| e.into_inner());
st.update(&draft, ui.input(|i| i.time));
st
});
let fx = fx_guard.as_deref().map(|state| super::typing_fx::Fx { style: fx_style, state, now: ui.input(|i| i.time), motion: super::animating() });
if let Some(fx) = &fx {
let skip: Vec<(usize, usize)> = composer_emoji_spans(&draft).iter().map(|(s, n, _)| (*s, *n)).collect();
// (The whole box, margins included: letters hop above their line.)
let painter = ui.painter().with_clip_rect(out.response.rect.intersect(ui.clip_rect()));
fx.paint(&painter, &out.galley, out.galley_pos, &skip, t.text_normal);
if fx.moving() {
ui.ctx().request_repaint();
} else if fx.cycling() && !draft.is_empty() && out.response.has_focus() {
ui.ctx().request_repaint_after(std::time::Duration::from_millis(33));
}
}
paint_composer_emoji(ui, &out, &draft, &|i| fx.as_ref().map_or(egui::Vec2::ZERO, |f| f.transform(i).0));
drop(fx);
drop(fx_guard);
// The placeholder, with any emoji in the channel's name drawn as
// pictures (a plain hint showed them as boxes).
if draft.is_empty() {
let hint = if t.light { t.text_muted } else { crate::style::rgba(240, 240, 245, 102) };
let clip = ui.painter().with_clip_rect(out.response.rect.intersect(ui.clip_rect()));
// Too long for the box: cut with "…" like Discord's placeholder.
let room = out.response.rect.right() - out.galley_pos.x - 4.0;
let width = |s: &str| ui.fonts(|f| f.layout_no_wrap(s.to_string(), FontId::proportional(text_px()), hint).size().x);
let mut shown = placeholder.clone();
if width(&shown) > room {
let chars: Vec<char> = placeholder.chars().collect();
let (mut lo, mut hi) = (0usize, chars.len());
while lo < hi {
let mid = (lo + hi + 1) / 2;
let s: String = chars[..mid].iter().collect::<String>() + "…";
if width(&s) <= room { lo = mid } else { hi = mid - 1 }
}
shown = chars[..lo].iter().collect::<String>().trim_end().to_string() + "…";
}
super::paint_text_emoji(ui, &clip, pos2(out.galley_pos.x, out.response.rect.center().y), &shown, FontId::proportional(text_px()), hint);
}
// Spell checking: a red wavy line under each misspelled word
// (not the one still being typed).
let caret = out.cursor_range.filter(|_| out.response.has_focus()).map(|c| char_to_byte(&draft, c.primary.ccursor.index));
misspelled = crate::spellcheck::misspelled(&draft, caret);
paint_misspellings(ui, &out, &draft, &misspelled);
if out.response.secondary_clicked() {
// Which word the right-click landed on (for the menu's corrections).
clicked_word = out.response.interact_pointer_pos().and_then(|p| {
let at = char_to_byte(&draft, out.galley.cursor_from_pos(p - out.galley_pos).ccursor.index);
// (Checked without the "word being typed" exception: the
// right-click itself has just put the caret in this word,
// which used to hide it from the menu's corrections.)
crate::spellcheck::misspelled(&draft, None).into_iter().find(|r| at >= r.start && at <= r.end)
});
}
if out.response.changed() {
typed_colon = out.cursor_range.map(|c| c.primary.ccursor.index);
}
let edit = out.response;
// One of the right-hand buttons: 32 px wide, the full row tall.
let button = |ui: &mut Ui, first: bool| {
if !first {
ui.add_space(8.0);
}
ui.allocate_exact_size(vec2(32.0, 56.0), Sense::click())
};
// Gift button: a gift box (opens Nitro gifting).
let (r, b) = button(ui, true);
let c = if b.hovered() { t.interactive_hover } else { t.interactive_normal };
super::compose_tools::paint_gift(ui.painter(), r.center(), c);
gift = b.on_hover_text("Send a gift").clicked();
if !condensed {
// GIF button: Discord's outlined "GIF" glyph.
let (r, b) = button(ui, false);
expr_buttons = expr_buttons.union(r);
let open = self.expression_open(ch, crate::features::ExpressionTab::Gifs);
let c = if b.hovered() || open { t.interactive_hover } else { t.interactive_normal };
super::paint_icon(ui.painter(), Rect::from_center_size(r.center(), vec2(20.0, 20.0)), icon::GIF, c);
if b.on_hover_text("Open GIF picker").clicked() {
gif_at = Some(r.right_top());
}
// Sticker button.
let (r, b) = button(ui, false);
expr_buttons = expr_buttons.union(r);
let open = self.expression_open(ch, crate::features::ExpressionTab::Stickers);
let c = if b.hovered() || open { t.interactive_hover } else { t.interactive_normal };
super::compose_tools::paint_sticker(ui.painter(), r.center(), c);
if b.on_hover_text("Open sticker picker").clicked() {
sticker_at = Some(r.right_top());
}
}
// Emoji button.
let (r, b) = button(ui, false);
expr_buttons = expr_buttons.union(r);
let open = self.expression_open(ch, crate::features::ExpressionTab::Emoji);
let c = if b.hovered() || open { t.interactive_hover } else { t.interactive_normal };
ui.painter().text(r.center(), Align2::CENTER_CENTER, icon::EMOJI, icon_font(20.0), c);
if b.on_hover_text("Select emoji").clicked() {
emoji_at = Some(r.right_top());
}
// Apps button (Discord's app launcher: the command list).
let (r, b) = button(ui, false);
let c = if b.hovered() { t.interactive_hover } else { t.interactive_normal };
super::compose_tools::paint_apps(ui.painter(), r.center(), c);
apps = b.on_hover_text("Apps").clicked();
if self.prefs.send_button {
let (r, b) = button(ui, false);
let ready = !draft.trim().is_empty();
let sq = Rect::from_center_size(r.center(), vec2(32.0, 32.0));
let brand = Color32::from_rgb(0x58, 0x65, 0xf2);
ui.painter().rect_filled(sq, 8.0, if !ready { brand.gamma_multiply(0.4) } else if b.hovered() { Color32::from_rgb(0x47, 0x52, 0xc4) } else { brand });
let c = r.center();
let plane = [c + vec2(-7.0, -7.0), c + vec2(8.0, 0.0), c + vec2(-7.0, 7.0), c + vec2(-4.0, 0.0)];
let ink = if ready { Color32::WHITE } else { crate::style::rgba(255, 255, 255, 120) };
ui.painter().add(Shape::convex_polygon(vec![plane[0], plane[1], plane[3]], ink, Stroke::NONE));
ui.painter().add(Shape::convex_polygon(vec![plane[3], plane[1], plane[2]], ink, Stroke::NONE));
send_clicked = b.on_hover_cursor(CursorIcon::PointingHand).on_hover_text("Send Message").clicked() && ready;
}
ui.add_space(12.0);
edit
})
.inner
});
let composer_frame = resp.response.rect;
let resp = resp.inner;
// Right-click: Discord's Cut / Copy / Paste menu.
if resp.secondary_clicked() {
let at = resp.interact_pointer_pos().unwrap_or(resp.rect.center());
self.compose.text_menu = Some((ch, at, ui.ctx().cumulative_pass_nr()));
self.compose.text_menu_word = clicked_word.map(|r| {
let word = draft[r.clone()].to_string();
crate::spellcheck::request_suggestions(&word);
(r, word)
});
ui.memory_mut(|m| m.request_focus(id));
}
self.composer_menu(ui.ctx(), ch, id, &mut draft);
if let Some(shapes) = super::theme_surface_shapes(ui.ctx(), composer_frame, 8.0, super::surface::PANEL, &t) {
ui.painter().set(bg_slot, egui::Shape::Vec(shapes));
}
if apps {
draft = "/".into();
self.compose.apps_dismissed = None;
ui.memory_mut(|m| m.request_focus(id));
}
self.compose.composer_rect = Some((ch, composer_frame));
self.track_mention(ui.ctx(), ch, id, &draft);
if resp.changed() && !draft.trim().is_empty() {
self.maybe_send_typing(ch);
}
// Typing the closing ':' of :name: turns it into the emoji right away.
if let Some(cursor) = typed_colon {
let count = draft.chars().count();
if cursor > 0 && draft.chars().nth(cursor - 1) == Some(':') {
let expanded = self.expand_shortcodes(&draft, ch);
if expanded != draft {
let new_cursor = (cursor + expanded.chars().count()).saturating_sub(count);
draft = expanded;
if let Some(mut state) = TextEdit::load_state(ui.ctx(), id) {
let cc = egui::text::CCursor::new(new_cursor);
state.cursor.set_char_range(Some(egui::text::CCursorRange::one(cc)));
state.store(ui.ctx(), id);
}
}
}
}
let send = send || send_clicked;
if send && self.compose.command.as_ref().is_some_and(|d| d.channel == ch) {
self.submit_command(ch);
} else if send {
let text = draft.trim().to_string();
if self.compose.schedule.is_some_and(|(c, _)| c == ch) {
if !text.is_empty() {
draft.clear();
self.send_scheduled(ch, text);
}
} else if !text.is_empty() || has_uploads {
draft.clear();
self.send_message(ch, text);
}
}
self.drafts.insert(ch, draft);
if let Some(i) = remove {
self.remove_upload(ch, i);
}
if let Some(r) = plus {
self.toggle_plus_menu(ch, r);
}
if gift {
self.open_store_page(crate::features::StorePage::Nitro);
}
// GIF / sticker / emoji: one expression picker over the composer's
// right edge, on that tab (again on the open tab closes it).
self.compose.expression_buttons = Some(expr_buttons);
let expr_anchor = composer_frame.right_top();
for (wanted, tab) in [
(gif_at, crate::features::ExpressionTab::Gifs),
(sticker_at, crate::features::ExpressionTab::Stickers),
(emoji_at, crate::features::ExpressionTab::Emoji),
] {
if wanted.is_some() {
self.toggle_expression(ch, tab, expr_anchor);
}
}
if edit_last {
let me = self.store.me_id();
let last = self.store.messages.get(&ch).and_then(|cm| {
cm.list
.iter()
.rev()
.find(|m| Some(m.author.id) == me && !m.meta.deleted && !m.meta.pending)
.map(|m| m.id)
});
if let Some(msg) = last {
self.start_edit(ch, msg);
}
}
// Clicking anywhere off the message box lets go of it: it stops taking what
// you type until you click it again or open another channel.
let pressed_off = ui.input(|i| i.pointer.any_pressed() && i.pointer.interact_pos().is_some_and(|p| !composer_frame.contains(p)));
if pressed_off {
self.compose.blurred = Some(ch);
ui.memory_mut(|m| {
if m.has_focus(id) {
m.surrender_focus(id);
}
});
} else if ui.memory(|m| m.has_focus(id)) || self.compose.blurred.is_some_and(|c| c != ch) {
self.compose.blurred = None;
}
// Otherwise keep the composer focused, like Discord, unless something else wants focus.
let nothing_focused = ui.memory(|m| m.focused().is_none()) && self.compose.blurred != Some(ch);
let overlay = self.settings_open
|| self.shortcuts_open
|| self.server_settings_is_open()
|| self.full_profile.is_some()
|| self.quest_video.is_some()
|| self.compose.poll.is_some()
|| self.compose.schedule_dialog.is_some()
|| self.compose.expression.is_some()
|| self.emoji_picker.is_some()
|| self.compose.new_thread.is_some();
if nothing_focused && !overlay && self.editing.is_none() && self.context_menu.is_none() {
ui.memory_mut(|m| m.request_focus(id));
}
// Discord: "… is typing…" in the 24 px just above the box (over the
// chat's bottom edge), names in semibold, after three bouncing dots.
// With a "Replying to" bar (or a command / schedule bar) on the box,
// the line moves up above that bar instead of drawing through it.
let names = self.store.typing_names(ch);
if !names.is_empty() {
let bold = FontId::new(12.0, egui::FontFamily::Name(crate::style::BOLD.into()));
let plain = crate::style::medium(12.0);
let mut job = egui::text::LayoutJob::default();
let mut push = |s: &str, strong: bool| {
let (font, color) = if strong { (bold.clone(), t.text_normal) } else { (plain.clone(), t.text_muted) };
job.append(s, 0.0, egui::TextFormat { font_id: font, color, ..Default::default() });
};
match names.len() {
1 => {
push(&names[0], true);
push(" is typing…", false);
}
2 => {
push(&names[0], true);
push(" and ", false);
push(&names[1], true);
push(" are typing…", false);
}
_ => push("Several people are typing…", false),
}
let band_bottom = stack_top.min(composer_frame.top());
let band = Rect::from_min_max(pos2(composer_frame.left(), band_bottom - 24.0), pos2(composer_frame.right(), band_bottom));
let p = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Middle, egui::Id::new(("typing", ch.0)))).with_clip_rect(band);
// The dots bounce only while the window animates (focused, and
// without Reduced Motion): in the background they stand still and
// the window stays idle.
let animate = super::animating();
let now = if animate { ui.input(|i| i.time) as f32 } else { 0.0 };
for k in 0..3 {
let phase = ((now * 2.4 - k as f32 * 0.35).rem_euclid(1.4) / 1.4 * std::f32::consts::TAU).sin().max(0.0);
let c = pos2(band.left() + 16.0 + 4.0 + k as f32 * 6.0, band.center().y - phase * 2.0);
p.circle_filled(c, 2.0, t.text_normal.gamma_multiply(0.5 + 0.5 * phase));
}
let galley = p.layout_job(job);
p.galley(pos2(band.left() + 16.0 + 24.0, band.center().y - galley.size().y / 2.0), galley, t.text_normal);
if animate {
ui.ctx().request_repaint_after(std::time::Duration::from_millis(50));
}
}
}
// ---- context menu -------------------------------------------------------
/// The message box's right-click menu: Cut and Copy (with a selection)
/// and Paste (text at the caret; files or a picture become uploads).
fn composer_menu(&mut self, ctx: &egui::Context, ch: Id, id: egui::Id, draft: &mut String) {
let Some((menu_ch, pos, opened)) = self.compose.text_menu else { return };
if menu_ch != ch {
return;
}
let t = self.theme.clone();
let state = TextEdit::load_state(ctx, id);
let end = draft.chars().count();
let (a, b) = state
.as_ref()
.and_then(|s| s.cursor.char_range())
.map_or((end, end), |r| (r.primary.index.min(r.secondary.index).min(end), r.primary.index.max(r.secondary.index).min(end)));
let selected = a != b;
let mut choice = None;
// (The word must still be where it was when the menu opened.)
let word = self.compose.text_menu_word.clone().filter(|(r, w)| draft.get(r.clone()) == Some(w.as_str()));
let mut replacement: Option<String> = None;
let area = egui::Area::new(egui::Id::new("composer_text_menu"))
.order(Order::Foreground)
.fixed_pos(pos)
.constrain(true)
.show(ctx, |ui| {
Frame::none()
.fill(t.bg_floating)
.rounding(8.0)
.stroke(Stroke::new(1.0_f32, t.bg_hover))
.shadow(egui::epaint::Shadow { offset: vec2(0.0, 6.0), blur: 18.0, spread: 0.0, color: Color32::from_black_alpha(120) })
.inner_margin(8.0)
.show(ui, |ui| {
ui.set_width(188.0);
ui.spacing_mut().item_spacing.y = 1.0;
// On a misspelled word: its corrections, then Add to Dictionary.
if let Some((_, word)) = &word {
match crate::spellcheck::suggestions(word) {
Some(list) if !list.is_empty() => {
for (k, fix) in list.iter().enumerate() {
if text_menu_row(ui, &t, fix, true).clicked() {
choice = Some(10 + k);
replacement = Some(fix.clone());
}
}
}
Some(_) => {
text_menu_row(ui, &t, "No suggestions", false);
}
None => {
text_menu_row(ui, &t, "Checking…", false);
}
}
menu_separator(ui, &t);
if text_menu_row(ui, &t, "Add to Dictionary", true).clicked() {
choice = Some(3);
}
menu_separator(ui, &t);
}
for (n, label, enabled) in [(0, "Cut", selected), (1, "Copy", selected), (2, "Paste", true)] {
if text_menu_row(ui, &t, label, enabled).clicked() {
choice = Some(n);
}
}
menu_separator(ui, &t);
let on = self.prefs.spellcheck;
let row = text_menu_row(ui, &t, "Spellcheck", true);
// Discord's menu checkbox: filled blurple with a tick when on.
let boxr = Rect::from_center_size(pos2(row.rect.right() - 18.0, row.rect.center().y), vec2(18.0, 18.0));
if on {
ui.painter().rect_filled(boxr, 4.0, t.accent);
ui.painter().text(boxr.center(), Align2::CENTER_CENTER, icon::CHECK, icon_font(12.0), Color32::WHITE);
} else {
ui.painter().rect_stroke(boxr.shrink(0.5), 4.0, Stroke::new(1.0_f32, t.interactive_normal));
}
if row.clicked() {
choice = Some(4);
}
});
});
let byte = |s: &str, ci: usize| s.char_indices().nth(ci).map_or(s.len(), |(i, _)| i);
let (ba, bb) = (byte(draft, a), byte(draft, b));
let mut caret = None;
match choice {
Some(0) => {
ctx.copy_text(draft[ba..bb].to_string());
draft.replace_range(ba..bb, "");
caret = Some(a);
}
Some(1) => ctx.copy_text(draft[ba..bb].to_string()),
Some(3) => {
if let Some((_, w)) = &word {
crate::spellcheck::add_to_dictionary(w);
}
}
Some(4) => {
self.prefs.spellcheck = !self.prefs.spellcheck;
self.save_prefs();
}
Some(n) if n >= 10 => {
if let (Some((r, _)), Some(fix)) = (&word, replacement) {
let before = draft[..r.start].chars().count();
draft.replace_range(r.clone(), &fix);
caret = Some(before + fix.chars().count());
}
}
Some(_) => match crate::clipboard::read() {
Some(crate::clipboard::Clip::Text(text)) => {
draft.replace_range(ba..bb, &text);
caret = Some(a + text.chars().count());
}
Some(clip) => self.add_clip(ch, clip),
None => {}
},
None => {}
}
if let Some(c) = caret {
let mut st = state.unwrap_or_default();
st.cursor.set_char_range(Some(egui::text::CCursorRange::one(egui::text::CCursor::new(c))));
st.store(ctx, id);
}
let dismissed = ctx.input(|i| i.key_pressed(Key::Escape)) || (area.response.clicked_elsewhere() && ctx.cumulative_pass_nr() > opened + 1);
if choice.is_some() || dismissed {
self.compose.text_menu = None;
self.compose.text_menu_word = None;
ctx.memory_mut(|m| m.request_focus(id));
ctx.request_repaint();
}
}
pub fn context_menu_ui(&mut self, ctx: &egui::Context) {
// Copy Image / Save Image finishing in the background.
for (text, error) in crate::media_copy::poll(ctx) {
self.toast(text, error);
}
let Some(cm) = self.context_menu else { return };
let media = super::menu_media(ctx);
let Some(m) = self.store.message(cm.channel, cm.msg).cloned() else {
self.context_menu = None;
return;
};
let t = self.theme.clone();
let mine = Some(m.author.id) == self.store.me_id();
let live = !m.meta.deleted && !m.meta.pending && !m.meta.failed;
let can_pin = self.can_pin(cm.channel);
let can_react = self.can_add_reactions(cm.channel);
// Moderators (Manage Messages in the channel) delete anyone's messages.
const MANAGE_MESSAGES: u64 = 1 << 13;
let moderates = self.store.channels.get(&cm.channel).and_then(|c| Some((c.guild_id?, self.store.channel_perms(c)))).is_some_and(|(g, p)| match p {
Some(p) => p & MANAGE_MESSAGES != 0,
None => self.store.has_perm(g, MANAGE_MESSAGES),
});
let plugin_actions = self.rencord.message_actions(&m);
let quick: Vec<String> = self.quick_reactions(4);
enum Choice {
React(String),
AddReaction(Pos2),
Edit,
Reply,
Forward,
CopyText,
Reactions,
Pin,
MarkUnread,
CopyLink,
Speak,
Delete,
CopyId,
Plugin(usize, &'static str),
CopyImage,
SaveImage,
CopyMediaLink,
OpenMediaLink,
}
let mut choice = None;
let area = egui::Area::new(egui::Id::new("message_context_menu"))
.order(Order::Foreground)
.fixed_pos(cm.pos)
.constrain(true)
.show(ctx, |ui| {
Frame::none()
.fill(t.bg_floating)
.rounding(8.0)
.stroke(Stroke::new(1.0_f32, t.bg_hover))
.shadow(egui::epaint::Shadow { offset: vec2(0.0, 6.0), blur: 18.0, spread: 0.0, color: Color32::from_black_alpha(120) })
.inner_margin(8.0)
.show(ui, |ui| {
ui.set_width(204.0);
ui.spacing_mut().item_spacing.y = 1.0;
if live {
// Frequently used reactions and "Add Reaction", where you
// may add new ones (Discord leaves both out elsewhere).
if can_react {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 6.0;
for e in &quick {
let (r, b) = ui.allocate_exact_size(vec2(46.5, 44.0), Sense::click());
let b = b.on_hover_cursor(egui::CursorIcon::PointingHand);
ui.painter().rect_filled(r, 8.0, if b.hovered() { t.bg_hover } else { t.bg_secondary });
let s = if b.hovered() { 26.0 } else { 24.0 };
egui::Image::new(twemoji_url(e)).paint_at(ui, Rect::from_center_size(r.center(), vec2(s, s)));
if b.clicked() {
choice = Some(Choice::React(e.clone()));
}
}
});
ui.add_space(6.0);
let r = menu_row(ui, &t, icon::EMOJI, "Add Reaction", false, true);
if r.clicked() {
choice = Some(Choice::AddReaction(r.rect.right_top()));
}
menu_separator(ui, &t);
}
if mine && menu_row(ui, &t, icon::EDIT, "Edit Message", false, false).clicked() {
choice = Some(Choice::Edit);
}
if menu_row(ui, &t, icon::REPLY, "Reply", false, false).clicked() {
choice = Some(Choice::Reply);
}
if menu_row(ui, &t, icon::FORWARD, "Forward", false, false).clicked() {
choice = Some(Choice::Forward);
}
menu_separator(ui, &t);
}
if menu_row(ui, &t, icon::COPY, "Copy Text", false, false).clicked() {
choice = Some(Choice::CopyText);
}
if !m.reactions.is_empty() && menu_row(ui, &t, icon::EMOJI, "View Reactions", false, false).clicked() {
choice = Some(Choice::Reactions);
}
if live {
let (glyph, label) = if m.pinned { (icon::UNPIN, "Unpin Message") } else { (icon::PIN, "Pin Message") };
if can_pin && menu_row(ui, &t, glyph, label, false, false).clicked() {
choice = Some(Choice::Pin);
}
if menu_row(ui, &t, icon::UNREAD, "Mark Unread", false, false).clicked() {
choice = Some(Choice::MarkUnread);
}
if menu_row(ui, &t, icon::LINK, "Copy Message Link", false, false).clicked() {
choice = Some(Choice::CopyLink);
}
if menu_row(ui, &t, icon::SPEAK, "Speak Message", false, false).clicked() {
choice = Some(Choice::Speak);
}
}
if (mine || m.meta.failed || (moderates && live)) && !m.meta.deleted {
menu_separator(ui, &t);
if menu_row(ui, &t, icon::DELETE, "Delete Message", true, false).clicked() {
choice = Some(Choice::Delete);
}
}
if !plugin_actions.is_empty() {
menu_separator(ui, &t);
ui.label(bold(" RENCORD").size(10.5).color(t.text_muted));
for (plugin, action) in &plugin_actions {
if menu_row(ui, &t, icon::PLUGIN, &action.label, action.danger, false).clicked() {
choice = Some(Choice::Plugin(*plugin, action.id));
}
}
}
// On a picture, like Discord: the image itself, then its link.
if media.is_some() {
menu_separator(ui, &t);
if menu_row(ui, &t, icon::COPY, "Copy Image", false, false).clicked() {
choice = Some(Choice::CopyImage);
}
if menu_row(ui, &t, icon::DOWNLOAD, "Save Image", false, false).clicked() {
choice = Some(Choice::SaveImage);
}
menu_separator(ui, &t);
if menu_row(ui, &t, icon::LINK, "Copy Link", false, false).clicked() {
choice = Some(Choice::CopyMediaLink);
}
if menu_row(ui, &t, icon::OPEN_EXTERNAL, "Open Link", false, false).clicked() {
choice = Some(Choice::OpenMediaLink);
}
}
menu_separator(ui, &t);
if menu_row(ui, &t, icon::ID, "Copy Message ID", false, false).clicked() {
choice = Some(Choice::CopyId);
}
});
});
let clicked_away = area.response.clicked_elsewhere() && ctx.cumulative_pass_nr() > cm.opened_frame + 1;
let (c, id) = (cm.channel, cm.msg);
if let Some(choice) = choice {
self.context_menu = None;
match choice {
Choice::React(e) => {
self.use_emoji(&e);
self.add_reaction(c, id, ReactionEmoji::unicode(&e));
}
Choice::AddReaction(at) => self.open_emoji_picker(PickerTarget::React { channel: c, msg: id }, at + vec2(8.0, 0.0)),
Choice::Edit => self.start_edit(c, id),
Choice::Reply => self.start_reply(c, id),
Choice::Forward => self.start_forward(c, id),
Choice::CopyText => ctx.copy_text(m.content.clone()),
Choice::Reactions => self.open_reactions(c, id, None),
Choice::Pin => self.ask_pin(m.clone(), !m.pinned),
Choice::MarkUnread => self.mark_unread(c, id),
Choice::CopyLink => self.copy_link(c, id),
Choice::Speak => self.speak(c, id),
Choice::Delete => self.delete_message(c, id),
Choice::CopyId => ctx.copy_text(m.id.to_string()),
Choice::Plugin(p, a) => self.run_plugin_action(c, id, p, a),
Choice::CopyImage => {
if let Some((image, _)) = &media {
crate::media_copy::request(image, crate::media_copy::Kind::Copy);
}
}
Choice::SaveImage => {
if let Some((image, _)) = &media {
crate::media_copy::request(image, crate::media_copy::Kind::Save);
}
}
Choice::CopyMediaLink => {
if let Some((_, link)) = &media {
ctx.copy_text(link.clone());
}
}
Choice::OpenMediaLink => {
if let Some((_, link)) = &media {
ctx.open_url(egui::OpenUrl::new_tab(link));
}
}
}
} else if clicked_away || ctx.input(|i| i.key_pressed(Key::Escape)) {
self.context_menu = None;
}
}
}
/// Move the cursor down to the next whole point below `origin` (the list's top).
fn pad_to_whole(ui: &mut Ui, origin: f32) {
let used = ui.cursor().top() - origin;
let gap = used.ceil() - used;
if gap > 0.0 {
ui.add_space(gap);
}
}
impl RustCord {
/// Discord's richer system messages: "X started a thread: **name**" with the
/// thread's card, and a closed poll's result ("X's poll **question** has
/// closed.", the winning answer and "View Poll").
fn rich_system_message(&self, ui: &mut Ui, m: &Message, actions: &mut Vec<UiAction>) {
let t = &self.theme;
let bold = |s: f32| egui::FontId::new(s, egui::FontFamily::Name(crate::style::BOLD.into()));
match m.kind {
// "You accepted KEUPL’s friend request. They said: note" (or "KEUPL
// accepted your friend request. You said: note"), as Discord words
// it: the name is the other person in the DM and opens their
// profile; name and note are medium text-strong, the rest muted.
FRIEND_REQUEST_ACCEPTED => {
let mine = Some(m.author.id) == self.store.me_id();
let dm = self.store.channels.get(&m.channel_id).filter(|c| c.kind == channel_kind::DM);
let other = dm.and_then(|c| c.recipients.first()).cloned().or_else(|| (!mine).then(|| m.author.clone()));
let name = match (dm, &other) {
(Some(c), _) => self.store.label(c),
(None, Some(u)) => u.display_name().to_string(),
(None, None) => "Someone".to_string(),
};
let note = m.content.trim();
let muted = |ui: &mut Ui, s: &str| {
ui.label(RichText::new(s).size(text_px()).color(t.text_muted));
};
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing.x = 0.0;
if mine {
muted(ui, "You accepted ");
}
let r = ui
.add(Label::new(RichText::new(&name).font(crate::style::medium(text_px())).color(t.header_primary)).selectable(false).sense(Sense::click()))
.on_hover_cursor(CursorIcon::PointingHand);
if r.hovered() {
ui.painter().hline(r.rect.x_range(), r.rect.bottom() - 2.0, Stroke::new(1.0_f32, t.header_primary));
if let Some(u) = &other {
self.profiles_wanted.borrow_mut().push((u.id, None));
}
}
if r.clicked() {
if let Some(u) = &other {
let at = r.interact_pointer_pos().unwrap_or(r.rect.left_bottom());
actions.push(UiAction::OpenProfile { user: Box::new(u.clone()), guild: None, pos: at + vec2(12.0, -40.0) });
}
}
match (mine, note.is_empty()) {
(true, true) => muted(ui, "\u{2019}s friend request."),
(true, false) => muted(ui, "\u{2019}s friend request. They said: "),
(false, true) => muted(ui, " accepted your friend request."),
(false, false) => muted(ui, " accepted your friend request. You said: "),
}
if !note.is_empty() {
ui.label(RichText::new(note).font(crate::style::medium(text_px())).color(t.header_primary));
}
ui.add_space(4.0);
ui.label(RichText::new(format_timestamp(&m.timestamp)).font(crate::style::medium(12.0)).color(t.text_muted));
});
}
18 => {
let thread = m.message_reference.as_ref().and_then(|r| r.channel_id);
let name = if m.content.is_empty() { "a thread".to_string() } else { m.content.clone() };
// "VR started a thread: Name. See all threads." + the time.
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing.x = 0.0;
ui.label(RichText::new(self.author_name(m)).font(self.author_font(m, crate::style::medium(text_px()))).color(self.name_color(m)));
ui.label(RichText::new(" started a thread: ").size(text_px()).color(t.text_muted));
let r = ui.add(Label::new(RichText::new(&name).font(crate::style::medium(text_px())).color(t.header_primary)).selectable(false).sense(Sense::click()));
if r.hovered() {
ui.painter().hline(r.rect.x_range(), r.rect.bottom() - 2.0, Stroke::new(1.0_f32, t.header_primary));
}
if let Some(id) = thread {
if r.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
actions.push(UiAction::OpenThread(id));
}
}
ui.label(RichText::new(". See all ").size(text_px()).color(t.text_muted));
ui.label(RichText::new("threads").font(crate::style::medium(text_px())).color(t.header_primary));
ui.label(RichText::new(".").size(text_px()).color(t.text_muted));
ui.add_space(4.0);
ui.label(RichText::new(format_timestamp(&m.timestamp)).font(crate::style::medium(12.0)).color(t.text_muted));
});
// The thread's card (Discord: mod-subtle fill, 4 px corners,
// 8 px padding; name + "N Messages ›", then its latest news).
let known = thread.and_then(|id| self.store.channels.get(&id));
let cta = match known.and_then(|c| c.message_count) {
Some(1) => "1 Message \u{203a}".to_string(),
Some(n) if n > 0 => format!("{n} Messages \u{203a}"),
_ => "See Thread \u{203a}".to_string(),
};
let last = known.and_then(|c| c.last_message_id).or(thread).map(|id| id.timestamp_ms());
let semibold = egui::FontId::new(14.0, egui::FontFamily::Name(crate::style::BOLD.into()));
let g_name = ui.painter().layout_no_wrap(name.clone(), semibold.clone(), t.header_primary);
let g_cta = ui.painter().layout_no_wrap(cta, semibold, t.text_link);
let g_body = ui.painter().layout_no_wrap("There are no recent messages in this thread.".into(), egui::FontId::proportional(14.0), t.text_normal);
let g_ago = ui.painter().layout_no_wrap(last.map(short_ago).unwrap_or_default(), egui::FontId::proportional(14.0), t.text_muted);
let inner_w = (g_name.size().x + 8.0 + g_cta.size().x).max(g_body.size().x + 8.0 + g_ago.size().x);
ui.add_space(-1.0);
let (card, resp) = ui.allocate_exact_size(vec2((inner_w + 18.0).min(ui.available_width()), 56.0), Sense::click());
ui.painter().rect_filled(card, 4.0, crate::style::rgba(151, 151, 159, if resp.hovered() { 41 } else { 31 }));
let p = ui.painter_at(card);
let (x, y1, y2) = (card.left() + 9.0, card.top() + 9.0, card.top() + 29.0);
let name_w = g_name.size().x;
p.galley(pos2(x, y1 + (18.0 - g_name.size().y) / 2.0), g_name, t.header_primary);
p.galley(pos2(x + name_w + 8.0, y1 + (18.0 - g_cta.size().y) / 2.0), g_cta, t.text_link);
let body_w = g_body.size().x;
p.galley(pos2(x, y2 + (18.0 - g_body.size().y) / 2.0), g_body, t.text_normal);
p.galley(pos2(x + body_w + 8.0, y2 + (18.0 - g_ago.size().y) / 2.0), g_ago, t.text_muted);
if let Some(id) = thread {
if resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
actions.push(UiAction::OpenThread(id));
}
}
}
46 => {
let e = m.embeds.iter().find(|e| e.kind.as_deref() == Some("poll_result"));
let field = |k: &str| e.and_then(|e| e.fields.iter().find(|f| f.name == k)).map(|f| f.value.clone());
let question = field("poll_question_text").unwrap_or_else(|| "A poll".into());
let total: u32 = field("total_votes").and_then(|v| v.parse().ok()).unwrap_or(0);
let votes: u32 = field("victor_answer_votes").and_then(|v| v.parse().ok()).unwrap_or(0);
let winner = field("victor_answer_text");
let emoji = field("victor_answer_emoji_name");
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing.x = 0.0;
ui.label(RichText::new(self.author_name(m)).font(self.author_font(m, crate::style::medium(text_px()))).color(self.name_color(m)));
ui.label(RichText::new("\u{2019}s poll ").size(text_px()).color(t.text_muted));
ui.label(RichText::new(&question).font(crate::style::medium(text_px())).color(t.header_primary));
ui.label(RichText::new(" has closed.").size(text_px()).color(t.text_muted));
ui.add_space(4.0);
ui.label(RichText::new(format_timestamp(&m.timestamp)).font(crate::style::medium(12.0)).color(t.text_muted));
});
ui.add_space(1.0);
let (card, _) = ui.allocate_exact_size(vec2(ui.available_width().min(380.0), 56.0), Sense::hover());
ui.painter().rect_filled(card, 8.0, t.bg_secondary);
ui.painter().rect_stroke(card, 8.0, Stroke::new(1.0_f32, t.border_subtle));
let p = ui.painter_at(card.shrink2(vec2(12.0, 0.0)));
let won = winner.is_some() && votes > 0;
let (line1, line2) = match &winner {
Some(w) if votes > 0 => {
let pct = if total > 0 { (votes as f32 / total as f32 * 100.0).round() as u32 } else { 0 };
let text = match &emoji {
Some(e) => format!("{e} {w}"),
None => w.clone(),
};
(text, format!("Winning answer \u{2022} {pct}%"))
}
_ => ("There was no winner".to_string(), format!("{total} vote{}", if total == 1 { "" } else { "s" })),
};
let r = super::paint_text_emoji(ui, &p, pos2(card.left() + 14.0, card.top() + 19.0), &line1, bold(14.0), t.header_primary);
if won {
let c = pos2(r.right() + 10.0, card.top() + 19.0);
p.circle_filled(c, 7.0, Color32::from_rgb(0x23, 0xa5, 0x5a));
p.text(c, Align2::CENTER_CENTER, icon::CHECK, icon_font(8.0), Color32::WHITE);
}
p.text(pos2(card.left() + 14.0, card.top() + 38.0), Align2::LEFT_CENTER, line2, egui::FontId::proportional(12.5), t.text_muted);
if let Some(poll_msg) = m.message_reference.as_ref().and_then(|r| r.message_id) {
let b = Rect::from_min_size(pos2(card.right() - 98.0, card.center().y - 16.0), vec2(86.0, 32.0));
let br = ui.interact(b, egui::Id::new(("view_poll", m.id.0)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
ui.painter().rect_filled(b, 8.0, if br.hovered() { crate::style::overlay(0.24) } else { crate::style::overlay(0.14) });
ui.painter().text(b.center(), Align2::CENTER_CENTER, "View Poll", bold(14.0), t.header_primary);
if br.clicked() {
actions.push(UiAction::JumpTo { channel: m.channel_id, msg: poll_msg });
}
}
}
_ => {}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_jump_from_the_bottom_keeps_the_target_in_view() {
let ctx = egui::Context::default();
let mut offset = 0.0;
for frame in 0..6 {
let input = egui::RawInput {
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(500.0, 300.0))),
time: Some(frame as f64 / 60.0),
..Default::default()
};
let jump = frame == 3;
let _ = ctx.run(input, |ctx| {
CentralPanel::default().show(ctx, |ui| {
let list = message_scroll_area(Id(1), !jump).show(ui, |ui| {
ui.add_space(300.0);
if jump {
let row = Rect::from_min_size(ui.cursor().min, vec2(1.0, 30.0));
ui.scroll_to_rect(row, Some(Align::Center));
}
ui.add_space(2100.0);
});
offset = list.state.offset.y;
});
});
if frame == 2 {
assert!(offset > 2000.0);
}
}
assert!((60.0..300.0).contains(&offset), "offset after jumping: {offset}");
}
}