A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.
Rust archive-managerdesktop-appdual-paneexplorer-alternativefile-browserfile-explorerfile-managerfluent-designgpu-acceleratedgpuimacosmicaproductivityquick-lookrustrust-guitabswindowswindows-11windows-explorer
//! Select box: a bordered field showing the current value with up/down chevrons; its options
//! open in an Acrylic popup right under it (the material of the context menus), at least as
//! wide as the field, the chosen one ticked on the right. More than [`SEARCH_FROM`] options get
//! a search box. Keys: ↑ ↓, PgUp/PgDn, Home/End, Enter, Esc. Clicking elsewhere closes it.
//!
//! Opened from a window that shows glass, it is the liquid look instead (`liquid`): a capsule button with a chevron-down, and a list
//! on real glass whose chosen option is ticked at the leading edge and whose highlight is one capsule that glides between the rows.
use std::cell::Cell;
use std::rc::Rc;
use std::time::{Duration, Instant};
use gpui_kit::assets::IconName as L;
use gpui_kit::component::input::{InputEvent, InputState};
use gpui_kit::component::{Icon, h_flex, v_flex};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use crate::glass_watch::{self, PopupGlass};
use crate::liquid::{self, Glide};
use crate::t;
use crate::theme::{self, Palette};
/// More options than this: a search box on top.
pub const SEARCH_FROM: usize = 10;
const SEARCH_H: f32 = 40.;
const LIST_MAX: f32 = 320.;
const EDGE: f32 = 8.;
const PAGE: usize = 8;
pub struct Choice {
pub label: SharedString,
pub selected: bool,
pub run: Rc<dyn Fn(&mut Window, &mut App)>,
}
impl Choice {
pub fn new(label: impl Into<SharedString>, selected: bool, run: impl Fn(&mut Window, &mut App) + 'static) -> Self {
Self { label: label.into(), selected, run: Rc::new(run) }
}
}
/// The open popup (one at a time), and which field closed one last: a click on the field that
/// owns the open popup first deactivates the popup (closing it); that same click must not
/// reopen it.
#[derive(Default)]
struct Host {
open: Option<AnyWindowHandle>,
closed: Option<(SharedString, Instant)>,
}
impl Global for Host {}
/// The field. `choices` is asked when it is clicked.
pub fn select_box(id: impl Into<SharedString>, p: &Palette, label: impl Into<SharedString>, choices: impl Fn(&App) -> Vec<Choice> + 'static) -> AnyElement {
select_box_h(id, p, label, 32., choices)
}
/// [`select_box`] at a given height (to line up with other controls in a row).
pub fn select_box_h(id: impl Into<SharedString>, p: &Palette, label: impl Into<SharedString>, height: f32, choices: impl Fn(&App) -> Vec<Choice> + 'static) -> AnyElement {
field(id, p, label, height, false, choices)
}
/// [`select_box_h`] as wide as the box it is put in, for a column of a row that has a width of its own. The field's usual smallest
/// width ([`MIN_W`]) is wider than a narrow column: there the field stood out of its column and over what was beside it (issue 12, a
/// user's picture of the rule editor: "Extension" lay over "is one of").
pub fn select_box_fill(id: impl Into<SharedString>, p: &Palette, label: impl Into<SharedString>, height: f32, choices: impl Fn(&App) -> Vec<Choice> + 'static) -> AnyElement {
field(id, p, label, height, true, choices)
}
/// The smallest and the largest width of a field that sizes itself.
pub const MIN_W: f32 = 180.0;
const MAX_W: f32 = 320.0;
fn field(id: impl Into<SharedString>, p: &Palette, label: impl Into<SharedString>, height: f32, fill: bool, choices: impl Fn(&App) -> Vec<Choice> + 'static) -> AnyElement {
let key: SharedString = id.into();
let bounds = Rc::new(Cell::new(Bounds::<Pixels>::default()));
let seen = bounds.clone();
let base = h_flex().id(ElementId::Name(key.clone())).relative().h(px(height)).gap_2().items_center().text_sm().cursor_pointer()
// Tab reaches the field, Enter / Space opens it
.tab_index(0);
let base = if fill { base.w_full().min_w_0() } else { base.min_w(px(MIN_W)).max_w(px(MAX_W)) };
// over glass: a capsule with a chevron-down, a wash of white or black and no border; otherwise the bordered field
let (field, chevron) = if p.liquid {
let dark = p.dark;
(
base.px(px(14.)).rounded(px(height / 2.)).bg(liquid::dropdown_fill(dark, false)).hover(move |s| s.bg(liquid::dropdown_fill(dark, true))),
L::ChevronDown,
)
} else {
(base.px_3().rounded(theme::RADIUS_SM).bg(p.hover).border_1().border_color(p.border).hover(|s| s.border_color(p.text_tertiary)), L::ChevronsUpDown)
};
field
.child(div().flex_1().min_w_0().overflow_hidden().text_ellipsis().whitespace_nowrap().child(label.into()))
.child(Icon::new(chevron).size(px(14.)).text_color(p.text_secondary))
.child(canvas(move |b, _, _| seen.set(b), |_, _, _, _| {}).absolute().top_0().left_0().size_full())
.on_click(move |_, window, cx| {
let key = key.clone();
let just_closed = cx
.try_global::<Host>()
.and_then(|h| h.closed.clone())
.is_some_and(|(k, at)| k == key && at.elapsed() < Duration::from_millis(250));
if !just_closed {
open(key, bounds.get(), choices(cx), window, cx);
}
})
.into_any_element()
}
/// Turkish-insensitive search key: case, dotted/dotless i and common accents don't matter.
fn fold(s: &str) -> String {
s.chars()
.flat_map(|c| c.to_lowercase())
.map(|c| match c {
'ı' | 'í' | 'ì' | 'î' | 'ï' => 'i',
'ç' | 'ć' | 'č' => 'c',
'ğ' => 'g',
'ö' | 'ó' | 'ò' | 'ô' | 'õ' | 'ø' => 'o',
'ş' | 'ś' | 'š' => 's',
'ü' | 'ú' | 'ù' | 'û' => 'u',
'á' | 'à' | 'â' | 'ä' | 'ã' | 'å' => 'a',
'é' | 'è' | 'ê' | 'ë' => 'e',
'ñ' | 'ń' => 'n',
'ž' | 'ź' | 'ż' => 'z',
other => other,
})
.filter(|c| *c != '\u{307}') // the dot left over from lowercasing "İ"
.collect()
}
/// Indices of `labels` matching `query`: prefix matches first, then the rest that contain it.
fn filter(labels: &[SharedString], query: &str) -> Vec<usize> {
let q = fold(query.trim());
if q.is_empty() {
return (0..labels.len()).collect();
}
let (mut starts, mut contains) = (Vec::new(), Vec::new());
for (i, l) in labels.iter().enumerate() {
let f = fold(l);
if f.starts_with(&q) {
starts.push(i);
} else if f.contains(&q) {
contains.push(i);
}
}
starts.extend(contains);
starts
}
fn open(key: SharedString, field: Bounds<Pixels>, choices: Vec<Choice>, window: &mut Window, cx: &mut App) {
if choices.is_empty() {
return;
}
close_open(cx);
let search = choices.len() > SEARCH_FROM;
let material = cx.global::<crate::settings::Settings>().menu_material;
let auto_liquid = crate::glass::liquid(crate::look::window::hwnd_of(window));
let (liquid, background) = material.resolve(auto_liquid, false, crate::settings::materials_available(), crate::settings::glass_available());
let m = liquid::metrics(liquid);
// wide enough for the longest label (estimated: the popup is sized before it is drawn); the leading tick column adds its width
let longest = choices.iter().map(|c| c.label.chars().count()).max().unwrap_or(0) as f32;
let column = liquid::has_tick_column(liquid, choices.iter().any(|c| c.selected));
let fw = f32::from(field.size.width);
let w = (longest * 7.4 + 64. + if column { liquid::TICK_COL } else { 0. }).clamp(fw.max(180.), fw.max(440.));
let list_h = (choices.len() as f32 * m.row_h).min(LIST_MAX);
let h = list_h + 2. * m.pad_y + if search { SEARCH_H } else { 0. };
let win = window.bounds();
let area = window.display(cx).map(|d| d.bounds()).unwrap_or(win);
let (ax, ay) = (f32::from(area.origin.x), f32::from(area.origin.y));
let (right, bottom) = (ax + f32::from(area.size.width), ay + f32::from(area.size.height));
let fx = f32::from(win.origin.x + field.origin.x);
let ftop = f32::from(win.origin.y + field.origin.y);
let fbottom = ftop + f32::from(field.size.height);
let x = fx.clamp(ax + EDGE, (right - EDGE - w).max(ax + EDGE));
let y = if fbottom + 4. + h <= bottom - EDGE { fbottom + 4. } else { (ftop - 4. - h).max(ay + EDGE) };
let dark = match crate::settings::theme_override() {
crate::settings::ThemePref::Light => false,
crate::settings::ThemePref::Dark | crate::settings::ThemePref::Black => true,
crate::settings::ThemePref::System => matches!(cx.window_appearance(), WindowAppearance::Dark | WindowAppearance::VibrantDark),
};
let main = window.window_handle();
let opts = WindowOptions {
window_bounds: Some(WindowBounds::Windowed(Bounds::new(point(px(x), px(y)), size(px(w), px(h))))),
display_id: crate::theme::popup_display(window, cx),
titlebar: None,
focus: true,
show: true,
kind: WindowKind::PopUp,
is_movable: false,
is_resizable: false,
is_minimizable: false,
// over glass the window is see-through and the glass engine draws behind it (the view paints its own fill until it does)
window_background: theme::window_material(background),
..Default::default()
};
let opaque = matches!(background, WindowBackgroundAppearance::Opaque);
let opened = cx.open_window(opts, move |w, cx| {
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
if let Ok(h) = w.window_handle() {
if let RawWindowHandle::Win32(h) = h.as_raw() {
rf_win::window::set_dark_mode(h.hwnd.get(), dark);
crate::glass::keep_out_of_capture(h.hwnd.get());
}
}
cx.new(|cx| SelectView::new(key, choices, search, main, liquid.then_some(dark), opaque, w, cx))
});
match opened {
Ok(h) => {
// the app window keeps its active look while the popup has the keyboard
gpui_windows::KEEP_ACTIVE_LOOK.store(true, std::sync::atomic::Ordering::Relaxed);
cx.default_global::<Host>().open = Some(h.into());
}
Err(e) => log::warn!("select popup: {e:#}"),
}
}
/// Closes the open popup (if any), after the current update.
fn close_open(cx: &mut App) {
let Some(w) = cx.default_global::<Host>().open.take() else { return };
gpui_windows::KEEP_ACTIVE_LOOK.store(false, std::sync::atomic::Ordering::Relaxed);
cx.defer(move |cx| {
let _ = w.update(cx, |_, window, _| window.remove_window());
});
}
struct SelectView {
key: SharedString,
choices: Rc<Vec<Choice>>,
labels: Vec<SharedString>,
/// Indices into `choices`, in display order.
shown: Vec<usize>,
/// Highlighted position in `shown`.
hl: usize,
search: Option<Entity<InputState>>,
focus: FocusHandle,
scroll: ScrollHandle,
main: AnyWindowHandle,
done: bool,
/// The liquid look: the list sits on real glass (`glass`), its rows are 34 high and one capsule (`glide`) is the highlight.
liquid: bool,
glass: Option<PopupGlass>,
opaque: bool,
glide: Glide,
_watch: Option<Task<()>>,
_subs: Vec<Subscription>,
}
impl SelectView {
/// `liquid`: `Some(dark)` for the liquid look over glass (and which tint), `None` otherwise.
#[allow(clippy::too_many_arguments)]
fn new(key: SharedString, choices: Vec<Choice>, search: bool, main: AnyWindowHandle, liquid: Option<bool>, opaque: bool, window: &mut Window, cx: &mut Context<Self>) -> Self {
let labels: Vec<SharedString> = choices.iter().map(|c| c.label.clone()).collect();
let hl = choices.iter().position(|c| c.selected).unwrap_or(0);
let focus = cx.focus_handle();
let mut subs = vec![cx.observe_window_activation(window, |this: &mut Self, window, cx| {
if !window.is_window_active() {
let wid = window.window_handle().window_id();
if crate::fluent_menu::is_open_for(wid, cx) {
let weak = cx.entity().downgrade();
crate::fluent_menu::on_dismiss_for(
wid,
move |cx| {
let _ = weak.update(cx, |this, cx| this.dismiss(cx));
},
cx,
);
return;
}
this.dismiss(cx);
}
})];
let search = search.then(|| {
let input = cx.new(|cx| InputState::new(window, cx).placeholder(t!("Ara")));
subs.push(cx.subscribe_in(&input, window, |this: &mut Self, input, ev: &InputEvent, _, cx| {
if let InputEvent::Change = ev {
let q = input.read(cx).value().to_string();
this.shown = filter(&this.labels, &q);
this.hl = 0;
this.scroll.scroll_to_item(this.item_ix(0));
// the list changed under the capsule: it appears at the first row, it does not glide there
let m = liquid::metrics(this.liquid);
this.glide.jump(liquid::highlight_top(0., &m));
cx.notify();
}
}));
input
});
match &search {
Some(input) => input.update(cx, |s, cx| s.focus(window, cx)),
None => window.focus(&focus, cx),
}
let scroll = ScrollHandle::new();
let is_liquid = liquid.is_some();
// (the highlight capsule is the list's first child in the liquid look: the rows come one place later)
scroll.scroll_to_item(hl + usize::from(is_liquid));
let m = liquid::metrics(is_liquid);
let glide = Glide::at(liquid::highlight_top(hl as f32 * m.row_h, &m));
// the glass of the popup: attached to its window, which is marked as a liquid one so its controls look the part
let glass = liquid.map(|dark| PopupGlass::start(crate::look::window::hwnd_of(window), dark));
let watch = glass.is_some().then(|| glass_watch::watch(cx, |this: &mut Self| this.glass.as_mut()));
Self {
key,
shown: (0..choices.len()).collect(),
choices: Rc::new(choices),
labels,
hl,
search,
focus,
scroll,
main,
done: false,
liquid: is_liquid,
glass,
opaque,
glide,
_watch: watch,
_subs: subs,
}
}
/// The scroll handle's index of the list's child for the row at `pos` (the highlight capsule is the first child in the liquid look).
fn item_ix(&self, pos: usize) -> usize {
pos + usize::from(self.liquid)
}
/// Closes without choosing (Esc, a click elsewhere).
fn dismiss(&mut self, cx: &mut Context<Self>) {
if self.done {
return;
}
self.done = true;
cx.default_global::<Host>().closed = Some((self.key.clone(), Instant::now()));
close_open(cx);
}
fn pick(&mut self, pos: usize, cx: &mut Context<Self>) {
let Some(&ix) = self.shown.get(pos) else { return };
let run = self.choices[ix].run.clone();
let main = self.main;
self.dismiss(cx);
cx.defer(move |cx| {
let _ = main.update(cx, |_, window, cx| {
window.activate_window();
run(window, cx);
window.refresh();
});
});
}
fn move_hl(&mut self, to: usize, cx: &mut Context<Self>) {
if self.shown.is_empty() {
return;
}
self.hl = to.min(self.shown.len() - 1);
let ix = self.item_ix(self.hl);
if self.liquid {
// A row that is not wholly in view scrolls the list under the capsule at once; a capsule that glided from the old row
// would start a row away from where its row now is. So it goes there without gliding (a row in view gets the glide).
let (view, row) = (self.scroll.bounds(), self.scroll.bounds_for_item(ix));
let in_view = row.is_some_and(|r| liquid::row_in_view(f32::from(view.top()), f32::from(view.bottom()), f32::from(r.top()), f32::from(r.bottom())));
if !in_view {
let m = liquid::metrics(true);
self.glide.jump(liquid::highlight_top(self.hl as f32 * m.row_h, &m));
}
}
self.scroll.scroll_to_item(ix);
cx.notify();
}
fn on_key(&mut self, ev: &KeyDownEvent, cx: &mut Context<Self>) {
let n = self.shown.len();
match ev.keystroke.key.as_str() {
"escape" => self.dismiss(cx),
"enter" => self.pick(self.hl, cx),
"down" => self.move_hl(if self.hl + 1 < n { self.hl + 1 } else { 0 }, cx),
"up" => self.move_hl(if self.hl > 0 { self.hl - 1 } else { n.saturating_sub(1) }, cx),
"pagedown" => self.move_hl(self.hl + PAGE, cx),
"pageup" => self.move_hl(self.hl.saturating_sub(PAGE), cx),
// with a search box, Home/End move in the text
"home" if self.search.is_none() => self.move_hl(0, cx),
"end" if self.search.is_none() => self.move_hl(n.saturating_sub(1), cx),
_ => return,
}
cx.stop_propagation();
}
}
impl Render for SelectView {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let p = Palette::for_window(window);
let liquid = self.liquid;
let m = liquid::metrics(liquid);
let mut list = v_flex().id("select-list").relative().flex_1().min_h_0().overflow_y_scroll().track_scroll(&self.scroll);
if self.shown.is_empty() {
list = list.child(div().h(px(m.row_h)).flex().items_center().justify_center().text_sm().text_color(p.text_secondary).child(t!("Eşleşen öğe yok")));
}
let column = liquid::has_tick_column(liquid, self.choices.iter().any(|c| c.selected));
if liquid && !self.shown.is_empty() {
// One capsule for the highlight (the first child: behind the rows, and before them for the scroll handle's indices). It
// glides to the row the pointer or the keyboard is on over about 120 ms; a frame is asked for only while it moves.
let (now, animate) = (Instant::now(), crate::settings::animations());
let top = liquid::highlight_top(self.hl.min(self.shown.len() - 1) as f32 * m.row_h, &m);
let y = self.glide.aim(top, now, animate);
if self.glide.running(now, animate) {
window.request_animation_frame();
}
list = list.child(liquid::highlight_capsule(y, &m, p.dark));
}
for (pos, &ix) in self.shown.iter().enumerate() {
let c = &self.choices[ix];
let row = h_flex()
.id(("opt", ix))
.flex_shrink_0()
.h(px(m.row_h))
.gap_2()
.items_center()
.text_sm()
.on_hover(cx.listener(move |this, on: &bool, _, cx| {
if *on && this.hl != pos {
this.hl = pos;
cx.notify();
}
}))
.on_click(cx.listener(move |this, _, _, cx| this.pick(pos, cx)));
let label = div().flex_1().min_w_0().overflow_hidden().text_ellipsis().whitespace_nowrap().child(c.label.clone());
list = list.child(if liquid {
// the tick at the leading edge, the others make room for it; no fill of its own: the capsule behind is the highlight
row.px(px(12.)).children(liquid::tick_cell(liquid::tick_slot(column, c.selected), p.text)).child(label)
} else {
row.px_3()
.rounded(px(4.))
.when(pos == self.hl, |d| d.bg(p.hover))
.active(|s| s.bg(p.pressed))
.child(label)
.child(div().w(px(16.)).flex_shrink_0().when(c.selected, |d| d.child(Icon::new(L::Check).size(px(16.)).text_color(p.accent))))
});
}
// the panel: over glass a wash (or the plain fill until the glass runs); the Acrylic list has no fill of its own
let fill = if self.opaque {
Some(p.card_bg)
} else {
self.glass.as_ref().map(|g| glass_watch::panel_fill(p.dark, g.fallback())).or_else(|| theme::popup_fill(&p))
};
v_flex()
.size_full()
.px(px(m.pad_x))
.py(px(m.pad_y))
.when_some(fill, |d, f| d.bg(f))
// (a window of its own, opened without the main window's root: the font chosen in Settings is set here, issue 913)
.font_family(gpui_kit::component::theme::Theme::global(cx).font_family.clone())
.text_color(p.text)
.track_focus(&self.focus)
.capture_key_down(cx.listener(|this, ev: &KeyDownEvent, _, cx| this.on_key(ev, cx)))
.children(self.search.as_ref().map(|input| {
div()
.flex_shrink_0()
.h(px(SEARCH_H - m.pad_y))
.mb(px(m.pad_y))
.child(crate::text_menu::input(input).prefix(Icon::new(L::Search).size(px(14.)).text_color(p.text_secondary)))
}))
.child(list)
}
}
#[cfg(test)]
mod tests {
use super::{filter, fold};
use gpui_kit::SharedString;
#[test]
fn search_ignores_case_and_turkish_letters() {
assert_eq!(fold("İngilizce"), "ingilizce");
assert_eq!(fold("Türkçe"), "turkce");
assert_eq!(fold("Français"), "francais");
let labels: Vec<SharedString> = ["English", "Türkçe", "Deutsch", "Português (Brasil)"].into_iter().map(Into::into).collect();
assert_eq!(filter(&labels, "tur"), vec![1]);
assert_eq!(filter(&labels, "SC"), vec![2]); // contains
assert_eq!(filter(&labels, "p"), vec![3]);
assert_eq!(filter(&labels, ""), vec![0, 1, 2, 3]);
assert_eq!(filter(&labels, "e"), vec![0, 1, 2, 3]); // "English" starts, the rest contain
}
}