Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.
Rust desktop-appdiscorddiscord-clienteguielectron-alternativelightweightlinuxmacosnative-apprustwindows
//! The search box's filters and the list of suggestions under it, as Discord
//! web has them (measured 2026-12-04). Filters are typed among the words:
//! `from:name`, `in:channel`, `has:image`, `mentions:name`, `before:`,
//! `during:` and `after:` with a date, `pinned:true`, `authorType:bot`.
use crate::app::RustCord;
use discord::http::SearchQuery;
use discord::model::{Id, User, DISCORD_EPOCH};
use eframe::egui::{self, pos2, vec2, Align2, Color32, FontId, Key, Modifiers, Order, Rect, Sense, Stroke};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Filter {
From,
In,
Has,
Mentions,
Before,
During,
After,
Pinned,
AuthorType,
}
impl Filter {
const ALL: [Filter; 9] =
[Filter::From, Filter::In, Filter::Has, Filter::Mentions, Filter::Before, Filter::During, Filter::After, Filter::Pinned, Filter::AuthorType];
fn key(self) -> &'static str {
match self {
Filter::From => "from:",
Filter::In => "in:",
Filter::Has => "has:",
Filter::Mentions => "mentions:",
Filter::Before => "before:",
Filter::During => "during:",
Filter::After => "after:",
Filter::Pinned => "pinned:",
Filter::AuthorType => "authorType:",
}
}
/// The filter a word starts with (case aside), and the rest of it.
fn split(word: &str) -> Option<(Filter, &str)> {
Filter::ALL.into_iter().find_map(|f| {
let k = f.key();
let head = word.get(..k.len())?;
head.eq_ignore_ascii_case(k).then(|| (f, &word[k.len()..]))
})
}
}
/// `has:` as typed, in Discord's order, and as the API names it.
const HAS: [(&str, &str); 9] = [
("image", "image"),
("video", "video"),
("link", "link"),
("file", "file"),
("embed", "embed"),
("sound", "sound"),
("poll", "poll"),
("sticker", "sticker"),
("forward", "snapshot"),
];
const AUTHOR_TYPES: [&str; 3] = ["user", "bot", "webhook"];
/// The text as words, a filter's value joined to its key when typed after a
/// space ("from: vr"): `(Some(filter), value)` or `(None, word)`.
fn words(text: &str) -> Vec<(Option<Filter>, String)> {
let mut out = Vec::new();
let mut it = text.split_whitespace().peekable();
while let Some(w) = it.next() {
match Filter::split(w) {
Some((f, "")) => {
let value = it.next_if(|next| Filter::split(next).is_none()).unwrap_or("");
out.push((Some(f), value.to_string()));
}
Some((f, value)) => out.push((Some(f), value.to_string())),
None => out.push((None, w.to_string())),
}
}
out
}
fn same(a: &str, b: &str) -> bool {
a.to_lowercase() == b.to_lowercase()
}
fn parse_date(v: &str) -> Option<chrono::NaiveDate> {
["%Y-%m-%d", "%Y/%m/%d"].iter().find_map(|f| chrono::NaiveDate::parse_from_str(v, f).ok())
}
/// The first message ID of `day`, from your local midnight, as Discord web
/// works it out for `before:` / `during:` / `after:`.
fn day_start(day: chrono::NaiveDate) -> Option<Id> {
let t = day.and_hms_opt(0, 0, 0)?.and_local_timezone(chrono::Local).earliest()?;
let ms = u64::try_from(t.timestamp_millis()).ok()?.checked_sub(DISCORD_EPOCH)?;
Some(Id(ms << 22))
}
/// The part of the text being typed (a word, or a filter and its value so
/// far) and what's before it: `(before, filter, value)`.
fn current(text: &str) -> (&str, Option<Filter>, &str) {
let trimmed = text.trim_end();
let typing = trimmed.len() == text.len();
let last_start = trimmed.rfind(char::is_whitespace).map_or(0, |i| i + 1);
let last = &trimmed[last_start..];
if !typing {
// "from: " — the key alone, its value still to come.
return match Filter::split(last) {
Some((f, "")) => (&text[..last_start], Some(f), ""),
_ => (text, None, ""),
};
}
if let Some((f, value)) = Filter::split(last) {
return (&text[..last_start], Some(f), value);
}
// "from: vr": the value of the key before it.
let before_last = trimmed[..last_start].trim_end();
let prev_start = before_last.rfind(char::is_whitespace).map_or(0, |i| i + 1);
match Filter::split(&before_last[prev_start..]) {
Some((f, "")) if !before_last.is_empty() => (&text[..prev_start], Some(f), last),
_ => (&text[..last_start], None, last),
}
}
/// One row of the list.
enum Row {
/// A filter to start: icon, what it does, its key, what follows the key.
Filter { filter: Option<Filter>, icon: Option<&'static str>, title: &'static str, key: &'static str, hint: &'static str },
User(User, Option<String>),
Channel(String),
Value(String),
}
/// The list's state between frames.
#[derive(Default)]
pub struct SearchSuggest {
pub open: bool,
/// The row chosen with the arrow keys.
highlight: Option<usize>,
/// "More filters" was clicked.
more: bool,
/// Rows shown last frame (for the arrow keys).
len: usize,
/// Where the list was last frame: a press there keeps it open.
rect: Option<Rect>,
/// The member search last asked of the gateway for `from:` / `mentions:`.
asked: Option<(Id, String)>,
}
/// The list: 356 px wide, its right edge 4 px inside the box's and its top
/// 8 px under it; 44 px filter rows 4 px apart, 12 px / 8 px padding.
const LIST_W: f32 = 356.0;
const FILTER_ROW_H: f32 = 44.0;
const VALUE_ROW_H: f32 = 36.0;
const MAX_VALUES: usize = 10;
impl RustCord {
/// What the search box's text asks Discord for, or what in it can't be
/// asked ("Couldn't find …").
pub(super) fn search_query(&self, ch: Id, text: &str) -> Result<SearchQuery, String> {
let mut q = SearchQuery::default();
let mut content = Vec::new();
for (filter, v) in words(text) {
let Some(filter) = filter else {
content.push(v);
continue;
};
if v.is_empty() {
continue;
}
match filter {
Filter::From | Filter::Mentions => {
let id = self.search_user(ch, &v).ok_or_else(|| format!("Couldn't find anyone called \"{v}\"."))?;
if filter == Filter::From {
q.author_id.push(id);
} else {
q.mentions.push(id);
}
}
Filter::In => {
let name = v.trim_start_matches('#');
let id = self.channel_pool(ch).into_iter().find(|c| c.name.as_deref().is_some_and(|n| same(n, name))).map(|c| c.id);
q.channel_id.push(id.ok_or_else(|| format!("Couldn't find a channel called \"{name}\"."))?);
}
Filter::Has => {
let api = HAS.iter().find(|(typed, _)| same(typed, &v)).map(|(_, api)| api.to_string());
q.has.push(api.ok_or_else(|| format!("has: can be {}.", HAS.map(|(t, _)| t).join(", ")))?);
}
Filter::Before | Filter::During | Filter::After => {
let today = chrono::Local::now().date_naive().format("%Y-%m-%d");
let day = parse_date(&v).ok_or_else(|| format!("\"{v}\" isn't a date. Dates look like {today}."))?;
let (start, next) = (day_start(day), day.succ_opt().and_then(day_start));
// Several dates narrow it down, as on Discord.
let earlier = |a: Option<Id>, b: Option<Id>| a.into_iter().chain(b).min();
let later = |a: Option<Id>, b: Option<Id>| a.into_iter().chain(b).max();
match filter {
Filter::Before => q.max_id = earlier(q.max_id, start),
Filter::After => q.min_id = later(q.min_id, next),
_ => {
q.min_id = later(q.min_id, start);
q.max_id = earlier(q.max_id, next);
}
}
}
Filter::Pinned => {
let pinned = match v.to_lowercase().as_str() {
"true" => true,
"false" => false,
_ => return Err("pinned: is true or false.".into()),
};
// Discord keeps "true" if both are given.
q.pinned = Some(q.pinned.unwrap_or(false) || pinned);
}
Filter::AuthorType => {
let kind = AUTHOR_TYPES.iter().find(|t| same(t, &v)).ok_or_else(|| "authorType: is user, bot or webhook.".to_string())?;
q.author_type.push(kind.to_string());
}
}
}
q.content = content.join(" ");
Ok(q)
}
/// Someone named in `from:` / `mentions:`: by username, then by display
/// name or server nickname.
fn search_user(&self, ch: Id, name: &str) -> Option<Id> {
let name = name.trim_start_matches('@');
let pool = self.mention_pool(ch);
let by_username = pool.iter().find(|(u, _)| same(&u.username, name)).map(|(u, _)| u.id);
let by_name = || {
pool.iter()
.find(|(u, nick)| u.global_name.as_deref().is_some_and(|g| same(g, name)) || nick.as_deref().is_some_and(|n| same(n, name)))
.map(|(u, _)| u.id)
};
let anyone = || self.store.users.values().find(|u| same(&u.username, name)).map(|u| u.id);
by_username.or_else(by_name).or_else(anyone)
}
/// The list's rows for the search box's text.
fn search_rows(&self, ch: Id, text: &str) -> Vec<Row> {
let in_guild = self.store.channels.get(&ch).is_some_and(|c| c.guild_id.is_some());
let (_, filter, value) = current(text);
let q = value.to_lowercase();
let Some(filter) = filter else {
// Discord's "Filters", narrowed to the keys a word starts.
let row = |filter: Filter, icon: Option<&'static str>, title: &'static str, hint: &'static str| Row::Filter {
filter: Some(filter),
icon,
title,
key: filter.key(),
hint,
};
let mut rows = vec![row(Filter::From, Some("account"), "From a specific user", "user")];
if in_guild {
rows.push(row(Filter::In, Some("#"), "Sent in a specific channel", "channel"));
}
rows.push(row(Filter::Has, Some("search-has"), "Includes a specific type of data", "link, embed or file"));
rows.push(row(Filter::Mentions, Some("search-at"), "Mentions a specific user", "user"));
let more = [
row(Filter::Before, None, "When the message was sent", "specific date"),
row(Filter::During, None, "When the message was sent", "specific date"),
row(Filter::After, None, "When the message was sent", "specific date"),
row(Filter::Pinned, None, "If the message is pinned or not", "true or false"),
row(Filter::AuthorType, None, "Sent by any of the selected types of author", "user, bot or webhook"),
];
if !q.is_empty() {
// "be" → before:. Words that start no filter get no list.
rows.extend(more);
rows.retain(|r| matches!(r, Row::Filter { key, .. } if key.to_lowercase().starts_with(&q)));
} else if self.search_suggest.more {
rows.extend(more);
} else {
rows.push(Row::Filter { filter: None, icon: Some("search-more"), title: "More filters", key: "", hint: "dates, author type, and more" });
}
return rows;
};
match filter {
Filter::From | Filter::Mentions => {
let q = q.trim_start_matches('@');
let rank = |u: &User, nick: &Option<String>| -> Option<u8> {
let names = [Some(u.username.as_str()), u.global_name.as_deref(), nick.as_deref()];
let names = names.iter().flatten().map(|n| n.to_lowercase());
let names: Vec<String> = names.collect();
if names.iter().any(|n| n.starts_with(q)) {
Some(0)
} else if names.iter().any(|n| n.contains(q)) {
Some(1)
} else {
None
}
};
let mut users: Vec<(u8, User, Option<String>)> =
self.mention_pool(ch).into_iter().filter_map(|(u, nick)| Some((rank(&u, &nick)?, u, nick))).collect();
users.sort_by_key(|(r, _, _)| *r);
users.into_iter().take(MAX_VALUES).map(|(_, u, nick)| Row::User(u, nick)).collect()
}
Filter::In => {
let q = q.trim_start_matches('#');
let pool = self.channel_pool(ch);
let names = pool.iter().filter_map(|c| c.name.clone()).filter(|n| n.to_lowercase().contains(q));
names.take(MAX_VALUES).map(Row::Channel).collect()
}
Filter::Has => HAS.iter().filter(|(t, _)| t.starts_with(&q)).map(|(t, _)| Row::Value(t.to_string())).collect(),
Filter::Pinned => ["true", "false"].iter().filter(|v| v.starts_with(&q)).map(|v| Row::Value(v.to_string())).collect(),
Filter::AuthorType => AUTHOR_TYPES.iter().filter(|v| v.starts_with(&q)).map(|v| Row::Value(v.to_string())).collect(),
Filter::Before | Filter::During | Filter::After => {
// Today and yesterday, written the way a date is typed.
let today = chrono::Local::now().date_naive();
let days = [Some(today), today.pred_opt()];
let dates = days.into_iter().flatten().map(|d| d.format("%Y-%m-%d").to_string());
dates.filter(|d| d.starts_with(&q)).map(Row::Value).collect()
}
}
}
/// Arrow keys, Enter and Tab for the list, taken before the search box
/// sees them. The row picked with Enter or Tab, if any.
pub(super) fn search_keys(&mut self, ctx: &egui::Context, box_id: egui::Id) -> Option<usize> {
let s = &mut self.search_suggest;
if !s.open || s.len == 0 || !ctx.memory(|m| m.has_focus(box_id)) {
return None;
}
let (down, up, enter, tab) = ctx.input_mut(|i| {
(
i.consume_key(Modifiers::NONE, Key::ArrowDown),
i.consume_key(Modifiers::NONE, Key::ArrowUp),
s.highlight.is_some() && i.consume_key(Modifiers::NONE, Key::Enter),
i.consume_key(Modifiers::NONE, Key::Tab),
)
});
if down {
s.highlight = Some(s.highlight.map_or(0, |h| (h + 1) % s.len));
}
if up {
s.highlight = Some(s.highlight.map_or(s.len - 1, |h| (h + s.len - 1) % s.len));
}
if enter {
return s.highlight;
}
tab.then(|| s.highlight.unwrap_or(0))
}
/// The list under the search box (`bar`), while the box is in use.
/// `picked`: a row chosen with the keyboard this frame.
pub(super) fn search_suggest_ui(&mut self, ctx: &egui::Context, bar: Rect, ch: Id, box_id: egui::Id, picked: Option<usize>) {
let focused = ctx.memory(|m| m.has_focus(box_id));
let s = &mut self.search_suggest;
if focused {
s.open = true;
} else if s.open {
// A press on the list takes the focus from the box: stay open for it.
let pressed_off = ctx.input(|i| i.pointer.any_pressed() && i.pointer.press_origin().is_some_and(|p| !s.rect.is_some_and(|r| r.contains(p))));
let escape = ctx.input(|i| i.key_pressed(Key::Escape));
if pressed_off || escape || !ctx.input(|i| i.pointer.any_down() || i.pointer.any_released()) {
s.open = false;
}
}
if !s.open {
*s = SearchSuggest { asked: s.asked.take(), ..Default::default() };
return;
}
let text = self.search_input.clone();
// Members not met yet: ask Discord for those matching the name.
if let (_, Some(Filter::From | Filter::Mentions), value) = current(&text) {
let value = value.trim_start_matches('@').to_string();
if let Some(g) = self.store.channels.get(&ch).and_then(|c| c.guild_id).filter(|_| !value.is_empty()) {
if self.search_suggest.asked.as_ref() != Some(&(g, value.clone())) {
self.backend.send(crate::backend::Command::SearchMembers { guild: g, query: value.clone() });
self.search_suggest.asked = Some((g, value));
}
}
}
let rows = self.search_rows(ch, &text);
self.search_suggest.len = rows.len();
if self.search_suggest.highlight.is_some_and(|h| h >= rows.len()) {
self.search_suggest.highlight = None;
}
// Naming someone, a channel or a value: the first match is chosen,
// so Enter takes it (as on Discord). The filter list waits for the arrows.
if self.search_suggest.highlight.is_none() && current(&text).1.is_some() && !rows.is_empty() {
self.search_suggest.highlight = Some(0);
}
if rows.is_empty() {
self.search_suggest.rect = None;
return;
}
let t = self.theme.clone();
let highlight = self.search_suggest.highlight;
let mut clicked = None;
let mut hovered = None;
let pos = pos2(bar.right() - 4.0 - LIST_W, bar.bottom() + 8.0);
let area = egui::Area::new(egui::Id::new("search_suggest")).order(Order::Foreground).fixed_pos(pos).constrain(true).show(ctx, |ui| {
egui::Frame::none()
.fill(t.bg_floating)
.stroke(Stroke::new(1.0_f32, t.border_subtle))
.rounding(8.0)
.shadow(egui::epaint::Shadow { offset: vec2(0.0, 12.0), blur: 24.0, spread: 0.0, color: Color32::from_black_alpha(61) })
.inner_margin(egui::Margin::symmetric(8.0, 12.0))
.show(ui, |ui| {
ui.set_width(LIST_W - 18.0);
ui.spacing_mut().item_spacing.y = 4.0;
if rows.iter().any(|r| matches!(r, Row::Filter { .. })) {
// "Filters": 12 px semibold, 8 px in, 10 px above the rows.
let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 23.0), Sense::hover());
let font = FontId::new(12.0, egui::FontFamily::Name(crate::style::BOLD.into()));
ui.painter().text(pos2(r.left() + 8.0, r.top() + 15.0), Align2::LEFT_CENTER, "Filters", font, t.text_muted);
ui.add_space(2.0);
}
for (i, row) in rows.iter().enumerate() {
let h = if matches!(row, Row::Filter { .. }) { FILTER_ROW_H } else { VALUE_ROW_H };
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click());
let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
if resp.hovered() {
hovered = Some(i);
}
if resp.hovered() || highlight == Some(i) {
ui.painter().rect_filled(r, 8.0, t.bg_hover);
}
if resp.clicked() {
clicked = Some(i);
}
paint_row(ui, &t, r, row);
}
});
});
self.search_suggest.rect = Some(area.response.rect);
if hovered.is_some() && ctx.input(|i| i.pointer.delta() != egui::Vec2::ZERO) {
self.search_suggest.highlight = hovered;
}
let Some(row) = clicked.or(picked).and_then(|i| rows.get(i)) else { return };
let (before, filter, _) = current(&text);
let key = filter.map_or("", |f| f.key());
let new_text = match row {
Row::Filter { filter: None, .. } => {
self.search_suggest.more = true;
text.clone()
}
Row::Filter { key, .. } => format!("{before}{key}"),
Row::User(u, _) => format!("{before}{key}{} ", u.username),
Row::Channel(name) => format!("{before}{key}{name} "),
Row::Value(v) => format!("{before}{key}{v} "),
};
self.search_suggest.highlight = None;
self.search_input = new_text;
// Back to the box, typing at the end.
ctx.memory_mut(|m| m.request_focus(box_id));
if let Some(mut state) = egui::text_edit::TextEditState::load(ctx, box_id) {
let end = egui::text::CCursor::new(self.search_input.chars().count());
state.cursor.set_char_range(Some(egui::text::CCursorRange::one(end)));
state.store(ctx, box_id);
}
}
}
/// A row's contents: a filter (icon, title, `key` hint), a person (avatar,
/// name, username), a channel or a value.
fn paint_row(ui: &egui::Ui, t: &crate::style::Theme, r: Rect, row: &Row) {
let p = ui.painter_at(r);
let semibold = FontId::new(14.0, egui::FontFamily::Name(crate::style::BOLD.into()));
let medium = crate::style::medium(14.0);
match row {
Row::Filter { icon, title, key, hint, .. } => {
let icon_r = Rect::from_center_size(pos2(r.left() + 18.0, r.center().y), vec2(20.0, 20.0));
match *icon {
Some("#") => {
p.text(icon_r.center(), Align2::CENTER_CENTER, crate::style::icon::HASH, crate::style::icon_font(20.0), t.text_muted);
}
Some(name) => {
if let Some(src) = super::settings_icons::icon(name, t.text_muted) {
egui::Image::new(src).paint_at(ui, icon_r);
}
}
None => {}
}
p.text(pos2(r.left() + 36.0, r.top() + 13.0), Align2::LEFT_CENTER, *title, medium.clone(), t.text_normal);
let mut x = r.left() + 36.0;
if !key.is_empty() {
let g = p.layout_no_wrap(key.to_string(), semibold, t.text_muted);
let w = g.size().x;
p.galley(pos2(x, r.top() + 31.0 - g.size().y / 2.0), g, t.text_muted);
x += w + 4.0;
}
p.text(pos2(x, r.top() + 31.0), Align2::LEFT_CENTER, *hint, medium, t.channel_default);
}
Row::User(u, nick) => {
let av = Rect::from_center_size(pos2(r.left() + 20.0, r.center().y), vec2(24.0, 24.0));
let name = nick.clone().unwrap_or_else(|| u.display_name().to_string());
super::paint_avatar(ui, av, Some(super::avatar_uri(u, 32, false)), &name);
let g = p.layout_no_wrap(name, medium.clone(), t.text_normal);
let w = g.size().x;
p.galley(pos2(r.left() + 40.0, r.center().y - g.size().y / 2.0), g, t.text_normal);
p.text(pos2(r.left() + 40.0 + w + 6.0, r.center().y), Align2::LEFT_CENTER, &u.username, medium, t.text_muted);
}
Row::Channel(name) => {
let icon_r = Rect::from_center_size(pos2(r.left() + 18.0, r.center().y), vec2(20.0, 20.0));
p.text(icon_r.center(), Align2::CENTER_CENTER, crate::style::icon::HASH, crate::style::icon_font(18.0), t.text_muted);
p.text(pos2(r.left() + 36.0, r.center().y), Align2::LEFT_CENTER, name, medium, t.text_normal);
}
Row::Value(v) => {
p.text(pos2(r.left() + 12.0, r.center().y), Align2::LEFT_CENTER, v, medium, t.text_normal);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn filters_are_read_among_the_words() {
let w = words("hello from: vr has:IMAGE world in:#general pinned:");
assert_eq!(
w,
vec![
(None, "hello".into()),
(Some(Filter::From), "vr".into()),
(Some(Filter::Has), "IMAGE".into()),
(None, "world".into()),
(Some(Filter::In), "#general".into()),
(Some(Filter::Pinned), "".into()),
]
);
// A key straight after a key is a key, not the first one's value.
assert_eq!(words("from: has:link"), vec![(Some(Filter::From), "".into()), (Some(Filter::Has), "link".into())]);
assert_eq!(Filter::split("AUTHORTYPE:bot"), Some((Filter::AuthorType, "bot")));
}
#[test]
fn the_part_being_typed_is_found() {
assert_eq!(current(""), ("", None, ""));
assert_eq!(current("hello "), ("hello ", None, ""));
assert_eq!(current("hello fr"), ("hello ", None, "fr"));
assert_eq!(current("hello from:"), ("hello ", Some(Filter::From), ""));
assert_eq!(current("hello from: "), ("hello ", Some(Filter::From), ""));
assert_eq!(current("hello from:v"), ("hello ", Some(Filter::From), "v"));
assert_eq!(current("hello from: vr"), ("hello ", Some(Filter::From), "vr"));
assert_eq!(current("from:vr "), ("from:vr ", None, ""));
}
#[test]
fn a_day_starts_at_local_midnight() {
let day = chrono::NaiveDate::from_ymd_opt(2026, 11, 15).unwrap();
let id = day_start(day).unwrap();
let ms = (id.0 >> 22) + DISCORD_EPOCH;
let back = chrono::DateTime::from_timestamp_millis(ms as i64).unwrap().with_timezone(&chrono::Local);
assert_eq!(back.date_naive(), day);
assert_eq!(back.format("%H:%M:%S").to_string(), "00:00:00");
assert_eq!(id.0 & ((1 << 22) - 1), 0);
}
}