use std::rc::Rc;
use std::cell::Cell;
use std::time::{Duration, Instant};
use gpui::popup::{PopupAnchor, PopupConstraintAdjustment, PopupGravity, PopupOptions};
use gpui::{
AnyWindowHandle, App, AppContext as _, Bounds, Context, Entity, MouseButton, Pixels, Render,
SharedString, Size, Subscription, Window, WindowBounds, WindowHandle, WindowKind,
WindowOptions, div, point, prelude::*, px, size,
};
use crate::controls::WidgetContext;
use crate::easing::{ease_out_cubic, progress};
use crate::lighting;
use crate::overlay::{
self, Activate, Command, PALETTE_WIDTH, command_results, palette_fill, palette_panel,
palette_panel_height,
};
use crate::state::{COMBO_REVEAL, ComboId, ControlHost, ControlState};
use crate::text_input::{InputStyle, TextInput};
use crate::{Palette, keyboard};
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CommandBarOutcome {
Chosen(SharedString),
Dismissed(Dismissal),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Dismissal {
Escape,
Deactivated,
Closed,
Scrim,
WindowClosed,
}
impl Dismissal {
fn closed_from_inside(self) -> bool {
matches!(
self,
Dismissal::Escape | Dismissal::Closed | Dismissal::Scrim
)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct CommandBarOptions {
pub dim: bool,
}
type Done<V> = Box<dyn FnOnce(&mut V, CommandBarOutcome, &mut Window, &mut Context<V>)>;
pub(crate) struct Session {
id: ComboId,
window: WindowHandle<CommandBarWindow>,
_resized: Subscription,
}
fn anchor_rect(viewport: gpui::Size<gpui::Pixels>) -> Bounds<gpui::Pixels> {
Bounds::new(
point(px(0.0), viewport.height * 0.16),
size(viewport.width, px(0.0)),
)
}
fn bar_width(viewport: gpui::Size<gpui::Pixels>) -> f32 {
PALETTE_WIDTH
.min(f32::from(viewport.width) * 0.9)
.max(160.0)
}
#[allow(clippy::too_many_arguments)]
pub fn open_command_bar<V: ControlHost>(
this: &mut V,
id: ComboId,
commands: Vec<Command>,
palette: Palette,
options: CommandBarOptions,
window: &mut Window,
cx: &mut Context<V>,
on_done: impl FnOnce(&mut V, CommandBarOutcome, &mut Window, &mut Context<V>) + 'static,
) -> gpui::Result<()> {
if let Some(open) = command_bar(this.control_state(), id) {
let reopened = open.update(cx, |bar, bar_window, cx| {
if bar.ended {
return false;
}
bar_window.activate();
let focus = bar.query.read(cx).focus_handle.clone();
bar_window.focus(&focus, cx);
true
});
if matches!(reopened, Ok(true)) {
return Ok(());
}
forget(this.control_state_mut(), open);
}
let parent = window.window_handle();
let host = cx.entity().downgrade();
let return_focus = window.focused(cx);
let viewport = window.viewport_size();
let width = bar_width(viewport);
let time_scale = this.control_state().time_scale();
let reveal_duration = this.control_state().scaled(COMBO_REVEAL);
let display_id = window.display(cx).map(|display| display.id());
let bar_slot: Rc<Cell<Option<WindowHandle<CommandBarWindow>>>> = Rc::default();
let scrim = if options.dim && can_dim(cx) {
let slot = bar_slot.clone();
Some(cx.open_window(
popup_window(
parent,
Bounds::new(point(px(0.0), px(0.0)), size(px(0.0), px(0.0))),
PopupAnchor::TopLeft,
PopupGravity::BottomRight,
PopupConstraintAdjustment::empty(),
viewport,
false,
display_id,
),
|_, cx| cx.new(|_| Scrim::new(palette, slot, reveal_duration)),
)?)
} else {
None
};
let finish: Finish = {
let slot = bar_slot.clone();
let on_done: std::cell::RefCell<Option<Done<V>>> =
std::cell::RefCell::new(Some(Box::new(on_done)));
Rc::new(move |outcome: CommandBarOutcome, cx: &mut App| {
let Some(on_done) = on_done.borrow_mut().take() else {
return;
};
let host = host.clone();
let return_focus = return_focus.clone();
let slot = slot.clone();
cx.defer(move |cx| {
if let Some(scrim) = scrim {
let _ = scrim.update(cx, |_, window, _| window.remove_window());
}
let Some(closed) = slot.get() else {
return;
};
let _ = parent.update(cx, |_, window, cx| {
let Some(host) = host.upgrade() else {
return;
};
let inside = match &outcome {
CommandBarOutcome::Chosen(_) => true,
CommandBarOutcome::Dismissed(why) => why.closed_from_inside(),
};
host.update(cx, |host, cx| {
forget(host.control_state_mut(), closed);
if inside && host.control_state().command_bars.is_empty() {
if !window.is_window_active() {
window.activate();
}
if let Some(focus) = &return_focus {
window.focus(focus, cx);
}
}
on_done(host, outcome, window, cx);
cx.notify();
});
});
});
})
};
let bar_options = popup_window(
parent,
anchor_rect(viewport),
PopupAnchor::Top,
PopupGravity::Bottom,
PopupConstraintAdjustment::SLIDE_X
| PopupConstraintAdjustment::SLIDE_Y
| PopupConstraintAdjustment::RESIZE_Y,
size(px(width), px(120.0)),
true,
display_id,
);
let bar = match cx.open_window(bar_options, |bar_window, cx| {
cx.new(|cx| {
CommandBarWindow::new(
id,
commands,
palette,
finish.clone(),
time_scale,
bar_window,
cx,
)
})
}) {
Ok(bar) => bar,
Err(error) => {
if let Some(scrim) = scrim {
let _ = scrim.update(cx, |_, window, _| window.remove_window());
}
return Err(error);
}
};
bar_slot.set(Some(bar));
let resized = cx.observe_window_bounds(window, move |_, window, cx| {
let viewport = window.viewport_size();
if let Some(scrim) = scrim {
let _ = scrim.update(cx, |_, scrim_window, _| scrim_window.resize(viewport));
}
let _ = bar.update(cx, |bar, bar_window, cx| {
bar_window.set_popup_anchor(anchor_rect(viewport));
bar.width = bar_width(viewport);
cx.notify();
});
});
this.control_state_mut().command_bars.push(Session {
id,
window: bar,
_resized: resized,
});
Ok(())
}
fn can_dim(cx: &App) -> bool {
cx.windows_are_composited() && cx.compositor_name() != "Wayland"
}
#[allow(clippy::too_many_arguments)]
fn popup_window(
parent: AnyWindowHandle,
anchor_rect: Bounds<Pixels>,
anchor: PopupAnchor,
gravity: PopupGravity,
constraint_adjustment: PopupConstraintAdjustment,
window_size: Size<Pixels>,
focus: bool,
display_id: Option<gpui::DisplayId>,
) -> WindowOptions {
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(Bounds::new(
point(px(0.0), px(0.0)),
window_size,
))),
titlebar: None,
focus,
show: true,
kind: WindowKind::AnchoredPopup(PopupOptions {
parent,
anchor_rect,
anchor,
gravity,
constraint_adjustment,
offset: point(px(0.0), px(0.0)),
grab: focus,
}),
is_movable: false,
is_resizable: false,
is_minimizable: false,
display_id,
#[cfg(target_os = "macos")]
macos_window_background: gpui::MacosWindowBackground::Transparent,
#[cfg(target_os = "windows")]
windows_window_background: gpui::WindowsWindowBackground::Transparent,
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
linux_window_background: gpui::LinuxWindowBackground::Transparent,
..Default::default()
}
}
struct Scrim {
palette: Palette,
opened_at: Instant,
reveal_duration: Duration,
bar: Rc<Cell<Option<WindowHandle<CommandBarWindow>>>>,
}
impl Scrim {
fn new(
palette: Palette,
bar: Rc<Cell<Option<WindowHandle<CommandBarWindow>>>>,
reveal_duration: Duration,
) -> Self {
Self {
palette,
opened_at: Instant::now(),
reveal_duration,
bar,
}
}
}
impl Render for Scrim {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let reveal = ease_out_cubic(progress(self.opened_at, self.reveal_duration));
if reveal < 1.0 {
window.request_animation_frame();
}
let scrim = self.palette.scrim();
div()
.id("vampir-command-bar-scrim")
.size_full()
.bg(crate::color::with_alpha(scrim, scrim.alpha * reveal))
.on_mouse_down(
MouseButton::Left,
cx.listener(|scrim, _, _, cx| {
if let Some(bar) = scrim.bar.get() {
let _ = bar.update(cx, |bar, bar_window, cx| {
bar.end(
CommandBarOutcome::Dismissed(Dismissal::Scrim),
bar_window,
cx,
);
});
}
}),
)
}
}
pub fn close_command_bar<V: ControlHost>(this: &V, id: ComboId, cx: &mut Context<V>) {
if let Some(bar) = command_bar(this.control_state(), id) {
let _ = bar.update(cx, |bar, bar_window, cx| {
bar.end(
CommandBarOutcome::Dismissed(Dismissal::Closed),
bar_window,
cx,
);
});
}
}
pub fn set_command_bar_commands<V: ControlHost>(
this: &V,
id: ComboId,
commands: Vec<Command>,
cx: &mut Context<V>,
) {
if let Some(bar) = command_bar(this.control_state(), id) {
let _ = bar.update(cx, |bar, _, cx| {
bar.commands = commands;
bar.matches.invalidate();
cx.notify();
});
}
}
pub fn is_command_bar_open(state: &ControlState, id: ComboId) -> bool {
command_bar(state, id).is_some()
}
fn command_bar(state: &ControlState, id: ComboId) -> Option<WindowHandle<CommandBarWindow>> {
state
.command_bars
.iter()
.find(|session| session.id == id)
.map(|session| session.window)
}
fn forget(state: &mut ControlState, closed: WindowHandle<CommandBarWindow>) {
state
.command_bars
.retain(|session| session.window.window_id() != closed.window_id());
}
type Finish = Rc<dyn Fn(CommandBarOutcome, &mut App)>;
#[derive(Default)]
struct CommandMatches {
query: Option<SharedString>,
rows: Rc<[overlay::SearchResult]>,
}
impl CommandMatches {
fn results(
&mut self,
query: &SharedString,
commands: &[Command],
) -> Rc<[overlay::SearchResult]> {
if self.query.as_ref() != Some(query) {
self.rows = command_results(query, commands).into();
self.query = Some(query.clone());
}
self.rows.clone()
}
fn invalidate(&mut self) {
self.query = None;
}
}
pub struct CommandBarWindow {
id: ComboId,
controls: ControlState,
query: Entity<TextInput>,
commands: Vec<Command>,
matches: CommandMatches,
palette: Palette,
width: f32,
finish: Finish,
was_active: bool,
ended: bool,
_activation: Subscription,
}
impl ControlHost for CommandBarWindow {
fn control_state(&self) -> &ControlState {
&self.controls
}
fn control_state_mut(&mut self) -> &mut ControlState {
&mut self.controls
}
}
impl CommandBarWindow {
fn new(
id: ComboId,
commands: Vec<Command>,
palette: Palette,
finish: Finish,
time_scale: Option<f32>,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let query = cx.new(|cx| {
TextInput::new(
cx,
"Type a command",
false,
InputStyle::from_palette(palette, 13.0),
)
});
let mut controls = ControlState::default();
if let Some(scale) = time_scale {
controls.set_time_scale(scale);
}
controls.open_palette(id, &query, window, cx);
let activation = cx.observe_window_activation(window, |bar, window, cx| {
if window.is_window_active() {
bar.was_active = true;
} else if bar.was_active {
bar.end(
CommandBarOutcome::Dismissed(Dismissal::Deactivated),
window,
cx,
);
}
});
cx.on_release(|bar, cx| {
if !bar.ended {
bar.ended = true;
(bar.finish)(CommandBarOutcome::Dismissed(Dismissal::WindowClosed), cx);
}
})
.detach();
Self {
id,
controls,
query,
commands,
matches: CommandMatches::default(),
palette,
width: f32::from(window.viewport_size().width),
finish,
was_active: window.is_window_active(),
ended: false,
_activation: activation,
}
}
fn end(&mut self, outcome: CommandBarOutcome, window: &mut Window, cx: &mut Context<Self>) {
if self.ended {
return;
}
self.ended = true;
window.remove_window();
(self.finish)(outcome, cx);
}
}
impl Render for CommandBarWindow {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let id = self.id;
let palette = self.palette;
let text = self.query.read(cx).shared_text();
let matches = self.matches.results(&text, &self.commands);
let on_activate: Activate<Self> = Rc::new(move |bar, picked, window, cx| {
bar.end(CommandBarOutcome::Chosen(picked), window, cx);
});
let list = overlay::result_list(
id,
&text,
"",
&matches,
overlay::PALETTE_RESULT_MAX_HEIGHT,
WidgetContext {
palette,
view: self,
cx,
},
on_activate.clone(),
);
let wanted = size(px(self.width), px(palette_panel_height(&list)));
if (window.viewport_size().height - wanted.height).abs() > px(0.5)
|| (window.viewport_size().width - wanted.width).abs() > px(0.5)
{
window.resize(wanted);
}
let panel = palette_panel(
id,
&self.query,
list,
"No matching commands",
WidgetContext {
palette,
view: self,
cx,
},
window,
on_activate,
Rc::new(
|bar: &mut Self, window: &mut Window, cx: &mut Context<Self>| {
bar.end(CommandBarOutcome::Dismissed(Dismissal::Escape), window, cx);
},
),
);
let reveal = overlay::palette_opened_at(&self.controls, id).map_or(1.0, |opened_at| {
ease_out_cubic(progress(opened_at, self.controls.scaled(COMBO_REVEAL)))
});
let fill = palette_fill(palette);
let mut root = div().id("vampir-command-bar");
if !cx.windows_are_composited() {
root = root.bg(fill);
}
let element = keyboard::handle_keys(root, self, cx)
.size_full()
.text_color(palette.text_primary)
.font(crate::ui_font_face())
.child(
panel
.size_full()
.relative()
.top(px(-6.0 * (1.0 - reveal)))
.opacity(reveal)
.rounded(px(10.0))
.border_1()
.border_color(lighting::rim(fill, palette.is_dark)),
);
if self.controls.animating() || reveal < 1.0 {
window.request_animation_frame();
}
element
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_stale_completion_preserves_the_replacement_and_its_resize_subscription() {
let old = WindowHandle::new(gpui::WindowId::from(1));
let replacement = WindowHandle::new(gpui::WindowId::from(2));
let cancelled = Rc::new(Cell::new(false));
let mut state = ControlState::default();
state.command_bars.push(Session {
id: "commands",
window: replacement,
_resized: Subscription::new({
let cancelled = cancelled.clone();
move || cancelled.set(true)
}),
});
forget(&mut state, old);
assert_eq!(
command_bar(&state, "commands").unwrap().window_id(),
replacement.window_id()
);
assert!(!cancelled.get());
forget(&mut state, replacement);
assert!(!is_command_bar_open(&state, "commands"));
assert!(cancelled.get());
}
#[test]
fn unchanged_queries_reuse_rows_and_command_changes_invalidate_them() {
let mut matches = CommandMatches::default();
let commands = [
Command::new("open", "Open file"),
Command::new("save", "Save file"),
];
let first = matches.results(&"file".into(), &commands);
let repeated = matches.results(&"file".into(), &commands);
assert!(Rc::ptr_eq(&first, &repeated));
let changed = matches.results(&"save".into(), &commands);
assert!(!Rc::ptr_eq(&first, &changed));
assert_eq!(changed[0].id.as_ref(), "save");
matches.invalidate();
let replaced = matches.results(&"save".into(), &[Command::new("new", "Save all")]);
assert_eq!(replaced[0].id.as_ref(), "new");
assert!(!Rc::ptr_eq(&changed, &replaced));
}
#[test]
#[ignore = "timing benchmark; run explicitly without concurrent tests"]
fn command_bar_cache_benchmark() {
use crate::menu::ownership_bench::measure;
use std::hint::black_box;
let commands: Vec<_> = (0..1000)
.map(|index| Command::new(format!("command-{index}"), format!("Open settings {index}")))
.collect();
for query in ["", "ops"] {
let query = SharedString::from(query);
let mut cache = CommandMatches::default();
cache.results(&query, &commands);
measure(&format!("unchanged_query_{query:?}_before"), || {
black_box(command_results(black_box(&query), black_box(&commands)));
});
measure(&format!("unchanged_query_{query:?}_after"), || {
black_box(cache.results(black_box(&query), black_box(&commands)));
});
}
}
#[test]
fn the_bar_sits_where_the_in_window_palette_does() {
let rect = anchor_rect(size(px(1000.0), px(600.0)));
assert_eq!(rect.origin, point(px(0.0), px(96.0)));
assert_eq!(rect.size.width, px(1000.0));
}
#[test]
fn a_narrow_host_gets_a_narrower_bar_but_never_a_sliver() {
assert_eq!(bar_width(size(px(1200.0), px(800.0))), PALETTE_WIDTH);
assert_eq!(bar_width(size(px(400.0), px(800.0))), 360.0);
assert_eq!(bar_width(size(px(100.0), px(800.0))), 160.0);
}
#[test]
fn only_a_bar_closed_from_inside_takes_the_host_window_back() {
assert!(Dismissal::Escape.closed_from_inside());
assert!(Dismissal::Closed.closed_from_inside());
assert!(!Dismissal::Deactivated.closed_from_inside());
assert!(!Dismissal::WindowClosed.closed_from_inside());
}
}