Add searchable command palette with nested menus and shared dispatch
This commit is contained in:
@@ -105,6 +105,7 @@ run `psyterm --shutdown` on the remote host, for example through SSH.
|
||||
|
||||
| Input | Action |
|
||||
| --- | --- |
|
||||
| Ctrl/Cmd+Shift+P | Open the command palette |
|
||||
| Click a tab | Switch the server's active tab |
|
||||
| `+` or Ctrl+Shift+T | Create a tab |
|
||||
| Ctrl+Shift+D | Add a pane beside the focused pane |
|
||||
@@ -120,6 +121,12 @@ run `psyterm --shutdown` on the remote host, for example through SSH.
|
||||
| Shift+PageUp / PageDown | Scroll one page |
|
||||
| Shift+Home / End | Jump to oldest history / live screen |
|
||||
|
||||
The command palette searches command names and keywords as you type. Arrow keys
|
||||
or Tab select a result; Enter runs it or opens a submenu. Escape returns to the
|
||||
parent menu, then closes the palette. “Switch to tab…” and “Focus pane…” offer
|
||||
live workspace lists. Commands without shortcuts, such as restoring automatic
|
||||
pane names, are available here too. Palette input never reaches the shell.
|
||||
|
||||
Typing returns to the live screen. Ctrl+C, Ctrl+D, Alt combinations, arrows,
|
||||
navigation keys, and function keys reach the terminal application.
|
||||
Alternate-screen applications receive shifted navigation; the wheel sends
|
||||
@@ -174,7 +181,8 @@ scrollback by default.
|
||||
| `server.rs`, `session.rs` | Authoritative workspace, PTYs, child processes, parser, terminal grids, selection, scrolling, and resize |
|
||||
| `protocol.rs`, `client.rs` | Versioned bounded messages, local socket / SSH transport, snapshot delivery |
|
||||
| `launcher.rs` | Server startup, private paths, lifecycle locks, and the server-owned GUI zygote |
|
||||
| `terminal.rs` | Snapshot-only GUI workspace and panes, input, focus, and animation scheduling |
|
||||
| `terminal.rs` | Snapshot-only GUI workspace and panes, command dispatch, focus, and animation scheduling |
|
||||
| `commands.rs`, `palette.rs` | Extensible command metadata, optional shortcuts, searchable nested menus |
|
||||
| `pane_name.rs`, `label.rs` | Pane name editor, Unicode composition, and middle-truncated labels |
|
||||
| `render.rs`, `cursor.rs` | Cached text and batched drawing; cursor motion and blink |
|
||||
| `chrome.rs`, `colors.rs`, `fonts.rs` | Window chrome, terminal colors, font selection |
|
||||
@@ -188,6 +196,10 @@ still happen in each child. This is a safe prefork foundation, not a guarantee
|
||||
of the fastest possible launch time. Headless terminal/bridge use does not
|
||||
start the zygote.
|
||||
|
||||
Add an action and registry entry in `commands.rs`, then handle it in the workspace
|
||||
dispatcher to add a command. Shortcut hints are optional. The same recursive menu
|
||||
model supports commands that lead to further choices.
|
||||
|
||||
Snapshot queues retain the newest frame for a slow client rather than an
|
||||
unbounded backlog. GUI rows keep their shaped text until the snapshot changes.
|
||||
ASCII runs, Unicode glyphs, backgrounds, and decorations are batched; cursor
|
||||
|
||||
+299
@@ -0,0 +1,299 @@
|
||||
//! Command metadata shared by the palette and workspace dispatch.
|
||||
//!
|
||||
//! Add an action and a registry entry here to expose a command. A shortcut is
|
||||
//! optional; menus use the same item model and may be nested to any depth.
|
||||
use crate::protocol::{ScrollKind, Snapshot};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum CommandAction {
|
||||
NewTab,
|
||||
SplitPane,
|
||||
ClosePane,
|
||||
RenamePane,
|
||||
ResetPaneName,
|
||||
Copy,
|
||||
Paste,
|
||||
PreviousTab,
|
||||
NextTab,
|
||||
PreviousPane,
|
||||
NextPane,
|
||||
FocusLeft,
|
||||
FocusRight,
|
||||
FocusTab(u64),
|
||||
FocusPane(u64),
|
||||
Scroll(ScrollKind),
|
||||
Detach,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum PaletteItemKind {
|
||||
Action(CommandAction),
|
||||
Menu(Vec<PaletteItem>),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PaletteItem {
|
||||
/// Stable across snapshots, so open submenus survive background updates.
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
pub keywords: String,
|
||||
pub shortcut: Option<&'static str>,
|
||||
pub enabled: bool,
|
||||
pub kind: PaletteItemKind,
|
||||
}
|
||||
|
||||
impl PaletteItem {
|
||||
pub fn action(
|
||||
id: impl Into<String>,
|
||||
title: impl Into<String>,
|
||||
keywords: impl Into<String>,
|
||||
shortcut: Option<&'static str>,
|
||||
action: CommandAction,
|
||||
) -> Self {
|
||||
Self {
|
||||
id: id.into(),
|
||||
title: title.into(),
|
||||
keywords: keywords.into(),
|
||||
shortcut,
|
||||
enabled: true,
|
||||
kind: PaletteItemKind::Action(action),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn menu(
|
||||
id: impl Into<String>,
|
||||
title: impl Into<String>,
|
||||
keywords: impl Into<String>,
|
||||
items: Vec<Self>,
|
||||
) -> Self {
|
||||
Self {
|
||||
id: id.into(),
|
||||
title: title.into(),
|
||||
keywords: keywords.into(),
|
||||
shortcut: None,
|
||||
enabled: !items.is_empty(),
|
||||
kind: PaletteItemKind::Menu(items),
|
||||
}
|
||||
}
|
||||
|
||||
fn available(mut self, enabled: bool) -> Self {
|
||||
self.enabled = enabled;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// The complete command list. UI state affects availability, never discovery.
|
||||
pub fn root_items(snapshot: Option<&Snapshot>) -> Vec<PaletteItem> {
|
||||
use CommandAction::*;
|
||||
let pane = snapshot.is_some_and(|s| !s.panes.is_empty());
|
||||
let tabs = snapshot.is_some_and(|s| !s.tabs.is_empty());
|
||||
let mut items = vec![
|
||||
PaletteItem::action(
|
||||
"new-tab",
|
||||
"New tab",
|
||||
"create shell terminal",
|
||||
Some("Ctrl+Shift+T"),
|
||||
NewTab,
|
||||
),
|
||||
PaletteItem::action(
|
||||
"split-pane",
|
||||
"Split pane right",
|
||||
"new create horizontal shell",
|
||||
Some("Ctrl+Shift+D"),
|
||||
SplitPane,
|
||||
)
|
||||
.available(pane),
|
||||
PaletteItem::action(
|
||||
"close-pane",
|
||||
"Close pane",
|
||||
"exit shell terminate",
|
||||
Some("Ctrl+Shift+W"),
|
||||
ClosePane,
|
||||
)
|
||||
.available(pane),
|
||||
PaletteItem::action(
|
||||
"rename-pane",
|
||||
"Rename pane",
|
||||
"name title label",
|
||||
Some("Ctrl+Shift+R"),
|
||||
RenamePane,
|
||||
)
|
||||
.available(pane),
|
||||
PaletteItem::action(
|
||||
"reset-pane-name",
|
||||
"Use automatic pane name",
|
||||
"reset rename title cwd directory",
|
||||
None,
|
||||
ResetPaneName,
|
||||
)
|
||||
.available(pane),
|
||||
PaletteItem::action(
|
||||
"previous-tab",
|
||||
"Previous tab",
|
||||
"switch navigate left",
|
||||
None,
|
||||
PreviousTab,
|
||||
)
|
||||
.available(tabs),
|
||||
PaletteItem::action(
|
||||
"next-tab",
|
||||
"Next tab",
|
||||
"switch navigate right",
|
||||
None,
|
||||
NextTab,
|
||||
)
|
||||
.available(tabs),
|
||||
PaletteItem::action(
|
||||
"previous-pane",
|
||||
"Previous pane",
|
||||
"switch focus cycle",
|
||||
Some("Ctrl+Shift+Left"),
|
||||
PreviousPane,
|
||||
)
|
||||
.available(pane),
|
||||
PaletteItem::action(
|
||||
"next-pane",
|
||||
"Next pane",
|
||||
"switch focus cycle",
|
||||
Some("Ctrl+Shift+Right"),
|
||||
NextPane,
|
||||
)
|
||||
.available(pane),
|
||||
PaletteItem::action(
|
||||
"focus-left",
|
||||
"Focus pane or tab left",
|
||||
"navigate previous horizontal",
|
||||
None,
|
||||
FocusLeft,
|
||||
)
|
||||
.available(pane),
|
||||
PaletteItem::action(
|
||||
"focus-right",
|
||||
"Focus pane or tab right",
|
||||
"navigate next horizontal",
|
||||
None,
|
||||
FocusRight,
|
||||
)
|
||||
.available(pane),
|
||||
PaletteItem::action(
|
||||
"copy",
|
||||
"Copy selection",
|
||||
"clipboard text",
|
||||
Some("Ctrl+Shift+C"),
|
||||
Copy,
|
||||
)
|
||||
.available(pane),
|
||||
PaletteItem::action(
|
||||
"paste",
|
||||
"Paste",
|
||||
"clipboard text",
|
||||
Some("Ctrl+Shift+V"),
|
||||
Paste,
|
||||
)
|
||||
.available(pane),
|
||||
PaletteItem::action(
|
||||
"history-page-up",
|
||||
"Scroll history up one page",
|
||||
"scrollback previous page",
|
||||
Some("Shift+PageUp"),
|
||||
Scroll(ScrollKind::PageUp),
|
||||
)
|
||||
.available(pane),
|
||||
PaletteItem::action(
|
||||
"history-page-down",
|
||||
"Scroll history down one page",
|
||||
"scrollback next page",
|
||||
Some("Shift+PageDown"),
|
||||
Scroll(ScrollKind::PageDown),
|
||||
)
|
||||
.available(pane),
|
||||
PaletteItem::action(
|
||||
"history-top",
|
||||
"Go to oldest history",
|
||||
"scrollback top beginning",
|
||||
Some("Shift+Home"),
|
||||
Scroll(ScrollKind::Top),
|
||||
)
|
||||
.available(pane),
|
||||
PaletteItem::action(
|
||||
"history-bottom",
|
||||
"Return to live terminal",
|
||||
"scrollback bottom latest end",
|
||||
Some("Shift+End"),
|
||||
Scroll(ScrollKind::Bottom),
|
||||
)
|
||||
.available(pane),
|
||||
PaletteItem::action(
|
||||
"detach",
|
||||
"Detach window",
|
||||
"close window keep sessions running",
|
||||
None,
|
||||
Detach,
|
||||
),
|
||||
];
|
||||
let tab_items = snapshot
|
||||
.into_iter()
|
||||
.flat_map(|snapshot| snapshot.tabs.iter())
|
||||
.enumerate()
|
||||
.map(|(index, tab)| {
|
||||
PaletteItem::action(
|
||||
format!("tab-{}", tab.id),
|
||||
format!("{} {}", index + 1, tab.title),
|
||||
"switch focus tab",
|
||||
None,
|
||||
FocusTab(tab.id),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let pane_items = snapshot
|
||||
.into_iter()
|
||||
.flat_map(|snapshot| snapshot.panes.iter())
|
||||
.enumerate()
|
||||
.map(|(index, pane)| {
|
||||
PaletteItem::action(
|
||||
format!("pane-{}", pane.id),
|
||||
format!("{} {}", index + 1, pane.title),
|
||||
"switch focus pane",
|
||||
None,
|
||||
FocusPane(pane.id),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
items.insert(
|
||||
5,
|
||||
PaletteItem::menu(
|
||||
"switch-tab",
|
||||
"Switch to tab…",
|
||||
"navigate focus tabs",
|
||||
tab_items,
|
||||
),
|
||||
);
|
||||
items.insert(
|
||||
6,
|
||||
PaletteItem::menu(
|
||||
"focus-pane",
|
||||
"Focus pane…",
|
||||
"navigate switch panes",
|
||||
pane_items,
|
||||
),
|
||||
);
|
||||
items
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn empty_workspace_keeps_commands_discoverable_without_unsafe_actions() {
|
||||
let items = root_items(None);
|
||||
let find = |id: &str| items.iter().find(|item| item.id == id).unwrap();
|
||||
assert!(find("new-tab").enabled);
|
||||
assert!(find("detach").enabled);
|
||||
assert!(!find("close-pane").enabled);
|
||||
assert!(!find("switch-tab").enabled);
|
||||
assert!(find("reset-pane-name").shortcut.is_none());
|
||||
let unique: std::collections::HashSet<_> = items.iter().map(|item| &item.id).collect();
|
||||
assert_eq!(unique.len(), items.len());
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
mod chrome;
|
||||
mod client;
|
||||
mod colors;
|
||||
mod commands;
|
||||
mod cursor;
|
||||
mod fonts;
|
||||
mod input;
|
||||
mod label;
|
||||
mod launcher;
|
||||
mod palette;
|
||||
mod pane_name;
|
||||
mod protocol;
|
||||
mod render;
|
||||
|
||||
+943
@@ -0,0 +1,943 @@
|
||||
//! Searchable command launcher with nested menus and isolated text input.
|
||||
use std::ops::Range;
|
||||
|
||||
use gpui::{
|
||||
App, Bounds, ClipboardItem, ContentMask, Context, CursorStyle, Div, ElementId,
|
||||
ElementInputHandler, EntityInputHandler, FocusHandle, Focusable, KeyDownEvent, MouseButton,
|
||||
MouseDownEvent, MouseMoveEvent, Pixels, Point, Render, ScrollHandle, ShapedLine, TextRun,
|
||||
UTF16Selection, UnderlineStyle, Window, canvas, div, fill, font, point, prelude::*, px,
|
||||
relative, rgb, rgba, size,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
chrome,
|
||||
commands::{CommandAction, PaletteItem, PaletteItemKind},
|
||||
pane_name::NameEditor,
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Match {
|
||||
item: PaletteItem,
|
||||
path: Vec<String>,
|
||||
context: String,
|
||||
score: i64,
|
||||
}
|
||||
|
||||
struct PaletteModel {
|
||||
items: Vec<PaletteItem>,
|
||||
path: Vec<String>,
|
||||
query: String,
|
||||
matches: Vec<Match>,
|
||||
selected: usize,
|
||||
}
|
||||
|
||||
impl PaletteModel {
|
||||
fn new(items: Vec<PaletteItem>) -> Self {
|
||||
let mut model = Self {
|
||||
items,
|
||||
path: Vec::new(),
|
||||
query: String::new(),
|
||||
matches: Vec::new(),
|
||||
selected: 0,
|
||||
};
|
||||
model.refresh(false);
|
||||
model
|
||||
}
|
||||
|
||||
fn set_items(&mut self, items: Vec<PaletteItem>) {
|
||||
self.items = items;
|
||||
while !self.path.is_empty() && items_at_path(&self.items, &self.path).is_none() {
|
||||
self.path.pop();
|
||||
}
|
||||
self.refresh(true);
|
||||
}
|
||||
|
||||
fn set_query(&mut self, query: String) {
|
||||
if self.query != query {
|
||||
self.query = query;
|
||||
self.selected = 0;
|
||||
self.refresh(false);
|
||||
}
|
||||
}
|
||||
|
||||
fn refresh(&mut self, keep_selection: bool) {
|
||||
let selected_path = keep_selection
|
||||
.then(|| {
|
||||
self.matches
|
||||
.get(self.selected)
|
||||
.map(|item| item.path.clone())
|
||||
})
|
||||
.flatten();
|
||||
let items = items_at_path(&self.items, &self.path).unwrap_or(&self.items);
|
||||
let mut matches = Vec::new();
|
||||
gather_matches(items, &self.path, &[], &self.query, &mut matches);
|
||||
if !self.query.trim().is_empty() {
|
||||
matches.sort_by_key(|item| std::cmp::Reverse(item.score));
|
||||
}
|
||||
self.matches = matches;
|
||||
self.selected = selected_path
|
||||
.and_then(|path| self.matches.iter().position(|item| item.path == path))
|
||||
.unwrap_or(self.selected)
|
||||
.min(self.matches.len().saturating_sub(1));
|
||||
}
|
||||
|
||||
fn move_selection(&mut self, delta: isize) {
|
||||
if !self.matches.is_empty() {
|
||||
self.selected =
|
||||
(self.selected as isize + delta).rem_euclid(self.matches.len() as isize) as usize;
|
||||
}
|
||||
}
|
||||
|
||||
fn activate(&mut self) -> Option<CommandAction> {
|
||||
let result = self.matches.get(self.selected)?;
|
||||
if !result.item.enabled {
|
||||
return None;
|
||||
}
|
||||
match &result.item.kind {
|
||||
PaletteItemKind::Action(action) => Some(action.clone()),
|
||||
PaletteItemKind::Menu(_) => {
|
||||
self.path = result.path.clone();
|
||||
self.query.clear();
|
||||
self.selected = 0;
|
||||
self.refresh(false);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn go_to_depth(&mut self, depth: usize) {
|
||||
self.path.truncate(depth);
|
||||
self.query.clear();
|
||||
self.selected = 0;
|
||||
self.refresh(false);
|
||||
}
|
||||
|
||||
fn back(&mut self) -> bool {
|
||||
if self.path.is_empty() {
|
||||
false
|
||||
} else {
|
||||
self.go_to_depth(self.path.len() - 1);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
fn breadcrumbs(&self) -> Vec<String> {
|
||||
let mut labels = Vec::new();
|
||||
let mut items = self.items.as_slice();
|
||||
for id in &self.path {
|
||||
let Some(item) = items.iter().find(|item| &item.id == id) else {
|
||||
break;
|
||||
};
|
||||
labels.push(item.title.trim_end_matches('…').to_owned());
|
||||
if let PaletteItemKind::Menu(children) = &item.kind {
|
||||
items = children;
|
||||
}
|
||||
}
|
||||
labels
|
||||
}
|
||||
}
|
||||
|
||||
fn items_at_path<'a>(items: &'a [PaletteItem], path: &[String]) -> Option<&'a [PaletteItem]> {
|
||||
let mut items = items;
|
||||
for id in path {
|
||||
let item = items.iter().find(|item| &item.id == id)?;
|
||||
let PaletteItemKind::Menu(children) = &item.kind else {
|
||||
return None;
|
||||
};
|
||||
items = children;
|
||||
}
|
||||
Some(items)
|
||||
}
|
||||
|
||||
fn gather_matches(
|
||||
items: &[PaletteItem],
|
||||
parent_path: &[String],
|
||||
ancestors: &[String],
|
||||
query: &str,
|
||||
output: &mut Vec<Match>,
|
||||
) {
|
||||
let searching = !query.trim().is_empty();
|
||||
for item in items {
|
||||
let mut path = parent_path.to_vec();
|
||||
path.push(item.id.clone());
|
||||
let context = ancestors.join(" › ");
|
||||
let keywords = format!("{} {}", item.keywords, context);
|
||||
if let Some(score) = match_score(query, &item.title, &keywords) {
|
||||
output.push(Match {
|
||||
item: item.clone(),
|
||||
path: path.clone(),
|
||||
context,
|
||||
score,
|
||||
});
|
||||
}
|
||||
if searching && let PaletteItemKind::Menu(children) = &item.kind {
|
||||
let mut ancestors = ancestors.to_vec();
|
||||
ancestors.push(item.title.trim_end_matches('…').to_owned());
|
||||
gather_matches(children, &path, &ancestors, query, output);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn match_score(query: &str, title: &str, keywords: &str) -> Option<i64> {
|
||||
let title = title.to_lowercase();
|
||||
let keywords = keywords.to_lowercase();
|
||||
let mut score = 0;
|
||||
for word in query.to_lowercase().split_whitespace() {
|
||||
score += if let Some(score) = word_score(word, &title) {
|
||||
score + 1_000
|
||||
} else {
|
||||
word_score(word, &keywords)?
|
||||
};
|
||||
}
|
||||
Some(score)
|
||||
}
|
||||
|
||||
fn word_score(word: &str, text: &str) -> Option<i64> {
|
||||
if word == text {
|
||||
return Some(10_000);
|
||||
}
|
||||
if let Some(index) = text.find(word) {
|
||||
let boundary = index == 0
|
||||
|| text[..index]
|
||||
.chars()
|
||||
.next_back()
|
||||
.is_some_and(|c| !c.is_alphanumeric());
|
||||
return Some(500 + if boundary { 100 } else { 0 } - index as i64);
|
||||
}
|
||||
let mut characters = text.chars().enumerate();
|
||||
let mut previous = None;
|
||||
let mut score = 0;
|
||||
for wanted in word.chars() {
|
||||
let (index, _) = characters.find(|&(_, character)| character == wanted)?;
|
||||
if previous.is_some_and(|previous| previous + 1 == index) {
|
||||
score += 12;
|
||||
} else {
|
||||
score -= index as i64 - previous.map_or(0, |previous| previous as i64);
|
||||
}
|
||||
previous = Some(index);
|
||||
}
|
||||
Some(score)
|
||||
}
|
||||
|
||||
const INPUT_HEIGHT: f32 = 40.;
|
||||
const INPUT_PADDING: f32 = 12.;
|
||||
const INPUT_TEXT_SIZE: f32 = 15.;
|
||||
type Finish = Box<dyn Fn(Option<CommandAction>, &mut Window, &mut App)>;
|
||||
|
||||
/// An overlay whose entire key and pointer surface is separate from PTY input.
|
||||
pub struct CommandPalette {
|
||||
model: PaletteModel,
|
||||
editor: NameEditor,
|
||||
focus: FocusHandle,
|
||||
on_finish: Finish,
|
||||
query_bounds: Bounds<Pixels>,
|
||||
query_line: Option<ShapedLine>,
|
||||
query_scroll: Pixels,
|
||||
selecting: bool,
|
||||
results_scroll: ScrollHandle,
|
||||
}
|
||||
|
||||
impl CommandPalette {
|
||||
pub fn new(
|
||||
items: Vec<PaletteItem>,
|
||||
on_finish: impl Fn(Option<CommandAction>, &mut Window, &mut App) + 'static,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Self {
|
||||
let focus = cx.focus_handle();
|
||||
window.focus(&focus);
|
||||
Self {
|
||||
model: PaletteModel::new(items),
|
||||
editor: NameEditor::new(""),
|
||||
focus,
|
||||
on_finish: Box::new(on_finish),
|
||||
query_bounds: Bounds::default(),
|
||||
query_line: None,
|
||||
query_scroll: px(0.),
|
||||
selecting: false,
|
||||
results_scroll: ScrollHandle::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn focus(&self, window: &mut Window) {
|
||||
window.focus(&self.focus);
|
||||
}
|
||||
|
||||
pub fn set_items(&mut self, items: Vec<PaletteItem>, cx: &mut Context<Self>) {
|
||||
self.model.set_items(items);
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn query_changed(&mut self, cx: &mut Context<Self>) {
|
||||
if self.model.query != self.editor.text {
|
||||
self.model.set_query(self.editor.text.clone());
|
||||
self.results_scroll.set_offset(point(px(0.), px(0.)));
|
||||
}
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn activate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
if let Some(action) = self.model.activate() {
|
||||
(self.on_finish)(Some(action), window, cx);
|
||||
} else {
|
||||
if self.editor.text != self.model.query {
|
||||
self.editor = NameEditor::new(&self.model.query);
|
||||
}
|
||||
self.results_scroll.scroll_to_item(self.model.selected);
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
|
||||
fn go_to_depth(&mut self, depth: usize, cx: &mut Context<Self>) {
|
||||
self.model.go_to_depth(depth);
|
||||
self.editor = NameEditor::new("");
|
||||
self.results_scroll.set_offset(point(px(0.), px(0.)));
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn back(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
if self.model.back() {
|
||||
self.editor = NameEditor::new("");
|
||||
self.results_scroll.set_offset(point(px(0.), px(0.)));
|
||||
cx.notify();
|
||||
} else {
|
||||
(self.on_finish)(None, window, cx);
|
||||
}
|
||||
}
|
||||
|
||||
fn key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
|
||||
cx.stop_propagation();
|
||||
let key = &event.keystroke;
|
||||
let primary = key.modifiers.control || key.modifiers.platform;
|
||||
match key.key.as_str() {
|
||||
"escape" => {
|
||||
self.back(window, cx);
|
||||
return;
|
||||
}
|
||||
"enter" => {
|
||||
if self.editor.marked_utf16().is_some() {
|
||||
self.editor.unmark();
|
||||
cx.notify();
|
||||
} else {
|
||||
self.activate(window, cx);
|
||||
}
|
||||
return;
|
||||
}
|
||||
"up" | "down" | "tab" => {
|
||||
let delta = if key.key == "up" || key.key == "tab" && key.modifiers.shift {
|
||||
-1
|
||||
} else {
|
||||
1
|
||||
};
|
||||
self.model.move_selection(delta);
|
||||
self.results_scroll.scroll_to_item(self.model.selected);
|
||||
cx.notify();
|
||||
return;
|
||||
}
|
||||
"pageup" | "pagedown" => {
|
||||
self.model
|
||||
.move_selection(if key.key == "pageup" { -8 } else { 8 });
|
||||
self.results_scroll.scroll_to_item(self.model.selected);
|
||||
cx.notify();
|
||||
return;
|
||||
}
|
||||
"left" if key.modifiers.alt => {
|
||||
self.back(window, cx);
|
||||
return;
|
||||
}
|
||||
"left" => self.editor.left(key.modifiers.shift),
|
||||
"right" => self.editor.right(key.modifiers.shift),
|
||||
"home" => self.editor.home(key.modifiers.shift),
|
||||
"end" => self.editor.end(key.modifiers.shift),
|
||||
"backspace" => self.editor.backspace(),
|
||||
"delete" => self.editor.delete(),
|
||||
_ if primary && !key.modifiers.alt => match key.key.to_lowercase().as_str() {
|
||||
"a" => self.editor.select_all(),
|
||||
"c" | "x" => {
|
||||
let selection = self.editor.selection();
|
||||
if !selection.is_empty() {
|
||||
cx.write_to_clipboard(ClipboardItem::new_string(
|
||||
self.editor.text[selection].to_owned(),
|
||||
));
|
||||
if key.key.eq_ignore_ascii_case("x") {
|
||||
self.editor.replace(None, "");
|
||||
}
|
||||
}
|
||||
}
|
||||
"v" => {
|
||||
if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) {
|
||||
self.editor.replace(None, &text);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
_ if !primary && !key.modifiers.alt => {
|
||||
if let Some(text) = &key.key_char {
|
||||
self.editor.replace(None, text);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
self.query_changed(cx);
|
||||
}
|
||||
|
||||
fn query_index(&self, position: Point<Pixels>) -> usize {
|
||||
if self.editor.text.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
self.query_line.as_ref().map_or(0, |line| {
|
||||
line.closest_index_for_x(
|
||||
position.x - self.query_bounds.left() - px(INPUT_PADDING) + self.query_scroll,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn query_mouse_down(
|
||||
&mut self,
|
||||
event: &MouseDownEvent,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
cx.stop_propagation();
|
||||
self.focus(window);
|
||||
if event.click_count > 1 {
|
||||
self.editor.select_all();
|
||||
} else {
|
||||
self.editor
|
||||
.set_cursor(self.query_index(event.position), event.modifiers.shift);
|
||||
}
|
||||
self.selecting = true;
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn prepare_query(&mut self, bounds: Bounds<Pixels>, window: &mut Window) {
|
||||
self.query_bounds = bounds;
|
||||
let empty = self.editor.text.is_empty();
|
||||
let text = if empty {
|
||||
"Search commands…"
|
||||
} else {
|
||||
&self.editor.text
|
||||
};
|
||||
let default = TextRun {
|
||||
len: text.len(),
|
||||
font: font(".SystemUIFont"),
|
||||
color: rgb(if empty { chrome::MUTED } else { chrome::TEXT }).into(),
|
||||
background_color: None,
|
||||
underline: None,
|
||||
strikethrough: None,
|
||||
};
|
||||
let runs = if let Some(marked) = self.editor.marked_utf16() {
|
||||
let start = self.editor.byte_offset_for_utf16(marked.start);
|
||||
let end = self.editor.byte_offset_for_utf16(marked.end);
|
||||
[
|
||||
(0..start, false),
|
||||
(start..end, true),
|
||||
(end..text.len(), false),
|
||||
]
|
||||
.into_iter()
|
||||
.filter(|(range, _)| !range.is_empty())
|
||||
.map(|(range, marked)| TextRun {
|
||||
len: range.len(),
|
||||
underline: marked.then_some(UnderlineStyle {
|
||||
thickness: px(1.),
|
||||
color: None,
|
||||
wavy: false,
|
||||
}),
|
||||
..default.clone()
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
vec![default]
|
||||
};
|
||||
let line = window.text_system().shape_line(
|
||||
text.to_owned().into(),
|
||||
px(INPUT_TEXT_SIZE),
|
||||
&runs,
|
||||
None,
|
||||
);
|
||||
let caret = if empty {
|
||||
px(0.)
|
||||
} else {
|
||||
line.x_for_index(self.editor.cursor())
|
||||
};
|
||||
let width = (bounds.size.width - px(INPUT_PADDING * 2. + 1.)).max(px(1.));
|
||||
if caret - self.query_scroll > width {
|
||||
self.query_scroll = caret - width;
|
||||
} else if caret < self.query_scroll {
|
||||
self.query_scroll = caret;
|
||||
}
|
||||
if empty {
|
||||
self.query_scroll = px(0.);
|
||||
}
|
||||
self.query_line = Some(line);
|
||||
}
|
||||
|
||||
fn query_field(&self, cx: &mut Context<Self>) -> Div {
|
||||
let prepare = cx.entity();
|
||||
let paint = cx.entity();
|
||||
div()
|
||||
.w_full()
|
||||
.h(px(INPUT_HEIGHT))
|
||||
.flex_shrink_0()
|
||||
.bg(rgb(chrome::CONTROL_BACKGROUND))
|
||||
.border_b_1()
|
||||
.border_color(rgb(chrome::BORDER))
|
||||
.cursor(CursorStyle::IBeam)
|
||||
.on_mouse_down(MouseButton::Left, cx.listener(Self::query_mouse_down))
|
||||
.on_mouse_move(cx.listener(|palette, event: &MouseMoveEvent, _, cx| {
|
||||
if palette.selecting && event.dragging() {
|
||||
palette
|
||||
.editor
|
||||
.set_cursor(palette.query_index(event.position), true);
|
||||
cx.stop_propagation();
|
||||
cx.notify();
|
||||
}
|
||||
}))
|
||||
.on_mouse_up(
|
||||
MouseButton::Left,
|
||||
cx.listener(|palette, _, _, cx| {
|
||||
palette.selecting = false;
|
||||
cx.stop_propagation();
|
||||
}),
|
||||
)
|
||||
.on_mouse_up_out(
|
||||
MouseButton::Left,
|
||||
cx.listener(|palette, _, _, _| palette.selecting = false),
|
||||
)
|
||||
.child(
|
||||
canvas(
|
||||
move |bounds, window, cx| {
|
||||
prepare.update(cx, |palette, _| palette.prepare_query(bounds, window))
|
||||
},
|
||||
move |bounds, (), window, cx| {
|
||||
let palette = paint.read(cx);
|
||||
let focus = palette.focus.clone();
|
||||
let line = palette.query_line.clone();
|
||||
let selection = palette.editor.selection();
|
||||
let caret = palette.editor.cursor();
|
||||
let empty = palette.editor.text.is_empty();
|
||||
let origin =
|
||||
bounds.origin + point(px(INPUT_PADDING) - palette.query_scroll, px(0.));
|
||||
window.handle_input(
|
||||
&focus,
|
||||
ElementInputHandler::new(bounds, paint.clone()),
|
||||
cx,
|
||||
);
|
||||
if let Some(line) = line {
|
||||
window.with_content_mask(Some(ContentMask { bounds }), |window| {
|
||||
if !selection.is_empty() {
|
||||
let start = line.x_for_index(selection.start);
|
||||
let end = line.x_for_index(selection.end);
|
||||
window.paint_quad(fill(
|
||||
Bounds::new(
|
||||
origin + point(start, px(6.)),
|
||||
size(end - start, bounds.size.height - px(12.)),
|
||||
),
|
||||
rgb(chrome::BORDER),
|
||||
));
|
||||
}
|
||||
let _ = line.paint(origin, bounds.size.height, window, cx);
|
||||
if focus.is_focused(window) {
|
||||
let x = if empty {
|
||||
px(0.)
|
||||
} else {
|
||||
line.x_for_index(caret)
|
||||
};
|
||||
window.paint_quad(fill(
|
||||
Bounds::new(
|
||||
origin + point(x, px(10.)),
|
||||
size(px(1.), bounds.size.height - px(20.)),
|
||||
),
|
||||
rgb(chrome::PANE_FOCUS),
|
||||
));
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
)
|
||||
.size_full(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Focusable for CommandPalette {
|
||||
fn focus_handle(&self, _: &App) -> FocusHandle {
|
||||
self.focus.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for CommandPalette {
|
||||
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let mut breadcrumbs = div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap(px(6.))
|
||||
.h(px(32.))
|
||||
.px(px(12.))
|
||||
.flex_shrink_0()
|
||||
.text_size(px(11.))
|
||||
.text_color(rgb(chrome::MUTED))
|
||||
.child(
|
||||
div()
|
||||
.id("palette-root")
|
||||
.cursor_pointer()
|
||||
.text_color(rgb(chrome::PANE_FOCUS))
|
||||
.on_click(cx.listener(|palette, _, _, cx| palette.go_to_depth(0, cx)))
|
||||
.child("Commands"),
|
||||
);
|
||||
for (index, title) in self.model.breadcrumbs().into_iter().enumerate() {
|
||||
breadcrumbs = breadcrumbs.child("›").child(
|
||||
div()
|
||||
.id(ElementId::Name(format!("palette-crumb-{index}").into()))
|
||||
.min_w_0()
|
||||
.text_ellipsis()
|
||||
.cursor_pointer()
|
||||
.on_click(
|
||||
cx.listener(move |palette, _, _, cx| palette.go_to_depth(index + 1, cx)),
|
||||
)
|
||||
.child(title),
|
||||
);
|
||||
}
|
||||
let mut results = div()
|
||||
.id("palette-results")
|
||||
.w_full()
|
||||
.min_h_0()
|
||||
.max_h(px(336.))
|
||||
.overflow_y_scroll()
|
||||
.track_scroll(&self.results_scroll);
|
||||
if self.model.matches.is_empty() {
|
||||
results = results.child(
|
||||
div()
|
||||
.p(px(16.))
|
||||
.text_color(rgb(chrome::MUTED))
|
||||
.child("No matching commands"),
|
||||
);
|
||||
}
|
||||
for (index, matched) in self.model.matches.iter().enumerate() {
|
||||
let selected = index == self.model.selected;
|
||||
let enabled = matched.item.enabled;
|
||||
let menu = matches!(matched.item.kind, PaletteItemKind::Menu(_));
|
||||
let mut title = div()
|
||||
.flex_1()
|
||||
.min_w_0()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.justify_center()
|
||||
.child(
|
||||
div()
|
||||
.min_w_0()
|
||||
.text_ellipsis()
|
||||
.child(matched.item.title.clone()),
|
||||
);
|
||||
if !matched.context.is_empty() {
|
||||
title = title.child(
|
||||
div()
|
||||
.text_size(px(10.))
|
||||
.text_color(rgb(chrome::MUTED))
|
||||
.text_ellipsis()
|
||||
.child(matched.context.clone()),
|
||||
);
|
||||
}
|
||||
let mut row = div()
|
||||
.id(ElementId::Name(
|
||||
format!("palette-item-{}", matched.path.join("/")).into(),
|
||||
))
|
||||
.h(px(42.))
|
||||
.w_full()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap(px(12.))
|
||||
.px(px(12.))
|
||||
.border_l_2()
|
||||
.border_color(rgb(if selected {
|
||||
chrome::PANE_FOCUS
|
||||
} else {
|
||||
chrome::PANEL_BACKGROUND
|
||||
}))
|
||||
.bg(rgb(if selected {
|
||||
chrome::HOVER_BACKGROUND
|
||||
} else {
|
||||
chrome::PANEL_BACKGROUND
|
||||
}))
|
||||
.text_color(rgb(if enabled { chrome::TEXT } else { chrome::MUTED }))
|
||||
.cursor_pointer()
|
||||
.on_hover(cx.listener(move |palette, hovered, _, cx| {
|
||||
if *hovered && palette.model.selected != index {
|
||||
palette.model.selected = index;
|
||||
cx.notify();
|
||||
}
|
||||
}))
|
||||
.on_click(cx.listener(move |palette, _, window, cx| {
|
||||
cx.stop_propagation();
|
||||
palette.model.selected = index;
|
||||
palette.activate(window, cx);
|
||||
}))
|
||||
.child(title);
|
||||
if let Some(shortcut) = matched.item.shortcut {
|
||||
row = row.child(
|
||||
div()
|
||||
.flex_shrink_0()
|
||||
.text_size(px(10.))
|
||||
.text_color(rgb(chrome::MUTED))
|
||||
.child(shortcut),
|
||||
);
|
||||
}
|
||||
if menu {
|
||||
row = row.child(
|
||||
div()
|
||||
.flex_shrink_0()
|
||||
.text_color(rgb(chrome::PANE_FOCUS))
|
||||
.child("›"),
|
||||
);
|
||||
}
|
||||
results = results.child(row);
|
||||
}
|
||||
let hint = if self
|
||||
.model
|
||||
.matches
|
||||
.get(self.model.selected)
|
||||
.is_some_and(|item| !item.item.enabled)
|
||||
{
|
||||
"Unavailable in this workspace"
|
||||
} else if self
|
||||
.model
|
||||
.matches
|
||||
.get(self.model.selected)
|
||||
.is_some_and(|item| matches!(item.item.kind, PaletteItemKind::Menu(_)))
|
||||
{
|
||||
"↑↓ Select Enter Open Esc Back"
|
||||
} else {
|
||||
"↑↓ Select Enter Run Esc Back"
|
||||
};
|
||||
let query = self.query_field(cx);
|
||||
let panel = div()
|
||||
.w(px(620.))
|
||||
.max_w(relative(0.9))
|
||||
.max_h(relative(0.85))
|
||||
.flex()
|
||||
.flex_col()
|
||||
.min_h_0()
|
||||
.overflow_hidden()
|
||||
.border_1()
|
||||
.border_color(rgb(chrome::PANE_FOCUS))
|
||||
.bg(rgb(chrome::PANEL_BACKGROUND))
|
||||
.shadow_lg()
|
||||
.font_family(".SystemUIFont")
|
||||
.text_size(px(13.))
|
||||
.text_color(rgb(chrome::TEXT))
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.child(breadcrumbs)
|
||||
.child(query)
|
||||
.child(results)
|
||||
.child(
|
||||
div()
|
||||
.h(px(30.))
|
||||
.flex_shrink_0()
|
||||
.flex()
|
||||
.items_center()
|
||||
.px(px(12.))
|
||||
.border_t_1()
|
||||
.border_color(rgb(chrome::BORDER))
|
||||
.text_size(px(10.))
|
||||
.text_color(rgb(chrome::MUTED))
|
||||
.child(hint),
|
||||
);
|
||||
div()
|
||||
.absolute()
|
||||
.inset_0()
|
||||
.flex()
|
||||
.justify_center()
|
||||
.items_start()
|
||||
.pt(px(64.))
|
||||
.bg(rgba(0x00000066))
|
||||
.track_focus(&self.focus)
|
||||
.on_key_down(cx.listener(Self::key_down))
|
||||
.on_mouse_down(
|
||||
MouseButton::Left,
|
||||
cx.listener(|palette, _, window, cx| {
|
||||
cx.stop_propagation();
|
||||
(palette.on_finish)(None, window, cx);
|
||||
}),
|
||||
)
|
||||
.on_scroll_wheel(|_, _, cx| cx.stop_propagation())
|
||||
.child(panel)
|
||||
}
|
||||
}
|
||||
|
||||
impl EntityInputHandler for CommandPalette {
|
||||
fn text_for_range(
|
||||
&mut self,
|
||||
range: Range<usize>,
|
||||
actual: &mut Option<Range<usize>>,
|
||||
_: &mut Window,
|
||||
_: &mut Context<Self>,
|
||||
) -> Option<String> {
|
||||
let (text, range) = self.editor.text_for_range(range);
|
||||
*actual = Some(range);
|
||||
Some(text)
|
||||
}
|
||||
fn selected_text_range(
|
||||
&mut self,
|
||||
_: bool,
|
||||
_: &mut Window,
|
||||
_: &mut Context<Self>,
|
||||
) -> Option<UTF16Selection> {
|
||||
Some(UTF16Selection {
|
||||
range: self.editor.selection_utf16(),
|
||||
reversed: self.editor.reversed(),
|
||||
})
|
||||
}
|
||||
fn marked_text_range(&self, _: &mut Window, _: &mut Context<Self>) -> Option<Range<usize>> {
|
||||
self.editor.marked_utf16()
|
||||
}
|
||||
fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
|
||||
self.editor.unmark();
|
||||
cx.notify();
|
||||
}
|
||||
fn replace_text_in_range(
|
||||
&mut self,
|
||||
range: Option<Range<usize>>,
|
||||
text: &str,
|
||||
_: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
self.editor.replace(range, text);
|
||||
self.query_changed(cx);
|
||||
}
|
||||
fn replace_and_mark_text_in_range(
|
||||
&mut self,
|
||||
range: Option<Range<usize>>,
|
||||
text: &str,
|
||||
selected: Option<Range<usize>>,
|
||||
_: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
self.editor.replace_and_mark(range, text, selected);
|
||||
self.query_changed(cx);
|
||||
}
|
||||
fn bounds_for_range(
|
||||
&mut self,
|
||||
range: Range<usize>,
|
||||
_: Bounds<Pixels>,
|
||||
_: &mut Window,
|
||||
_: &mut Context<Self>,
|
||||
) -> Option<Bounds<Pixels>> {
|
||||
let line = self.query_line.as_ref()?;
|
||||
let start = line.x_for_index(self.editor.byte_offset_for_utf16(range.start));
|
||||
let end = line.x_for_index(self.editor.byte_offset_for_utf16(range.end));
|
||||
Some(Bounds::new(
|
||||
self.query_bounds.origin + point(px(INPUT_PADDING) - self.query_scroll + start, px(0.)),
|
||||
size((end - start).max(px(1.)), self.query_bounds.size.height),
|
||||
))
|
||||
}
|
||||
fn character_index_for_point(
|
||||
&mut self,
|
||||
position: Point<Pixels>,
|
||||
_: &mut Window,
|
||||
_: &mut Context<Self>,
|
||||
) -> Option<usize> {
|
||||
Some(
|
||||
self.editor
|
||||
.utf16_offset_for_byte(self.query_index(position)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn fixture() -> Vec<PaletteItem> {
|
||||
vec![
|
||||
PaletteItem::action(
|
||||
"new",
|
||||
"New tab",
|
||||
"create terminal",
|
||||
None,
|
||||
CommandAction::NewTab,
|
||||
),
|
||||
PaletteItem::action(
|
||||
"rename",
|
||||
"Rename pane",
|
||||
"title name",
|
||||
None,
|
||||
CommandAction::RenamePane,
|
||||
),
|
||||
PaletteItem::menu(
|
||||
"tabs",
|
||||
"Switch to tab…",
|
||||
"tabs",
|
||||
vec![
|
||||
PaletteItem::action("tab-2", "Codex", "work", None, CommandAction::FocusTab(2)),
|
||||
PaletteItem::action(
|
||||
"tab-5",
|
||||
"日本語",
|
||||
"notes",
|
||||
None,
|
||||
CommandAction::FocusTab(5),
|
||||
),
|
||||
],
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matching_accepts_keywords_and_subsequences_but_ranks_direct_titles_first() {
|
||||
assert!(match_score("rnp", "Rename pane", "").is_some());
|
||||
assert!(match_score("create", "New tab", "create terminal").is_some());
|
||||
assert!(match_score("pane rename", "Rename pane", "").is_some());
|
||||
assert!(match_score("missing", "New tab", "create terminal").is_none());
|
||||
assert!(
|
||||
match_score("tab", "Tab", "").unwrap() > match_score("tab", "New tab", "").unwrap()
|
||||
);
|
||||
assert!(match_score("日本", "日本語", "").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_reaches_nested_commands_and_escape_restores_parent() {
|
||||
let mut model = PaletteModel::new(fixture());
|
||||
model.set_query("codex".into());
|
||||
assert_eq!(model.matches.len(), 1);
|
||||
assert_eq!(model.matches[0].context, "Switch to tab");
|
||||
assert!(matches!(model.activate(), Some(CommandAction::FocusTab(2))));
|
||||
model.set_query(String::new());
|
||||
model.selected = 2;
|
||||
assert!(model.activate().is_none());
|
||||
assert_eq!(model.path, vec!["tabs"]);
|
||||
assert_eq!(model.matches.len(), 2);
|
||||
assert!(model.back());
|
||||
assert!(!model.back());
|
||||
assert_eq!(model.matches.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshots_keep_query_selection_and_submenu_by_stable_ids() {
|
||||
let mut model = PaletteModel::new(fixture());
|
||||
model.selected = 2;
|
||||
model.activate();
|
||||
model.move_selection(1);
|
||||
model.set_items(fixture());
|
||||
assert_eq!(model.matches[model.selected].item.id, "tab-5");
|
||||
model.set_query("日本".into());
|
||||
model.set_items(fixture());
|
||||
assert_eq!(model.query, "日本");
|
||||
assert_eq!(model.path, vec!["tabs"]);
|
||||
assert_eq!(model.matches[model.selected].item.id, "tab-5");
|
||||
model.set_items(Vec::new());
|
||||
assert!(model.path.is_empty());
|
||||
assert!(model.matches.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_commands_never_execute_and_empty_navigation_is_safe() {
|
||||
let mut items = fixture();
|
||||
items[0].enabled = false;
|
||||
let mut model = PaletteModel::new(items);
|
||||
assert!(model.activate().is_none());
|
||||
model.move_selection(-1);
|
||||
assert_eq!(model.selected, 2);
|
||||
model.set_query("unmatched".into());
|
||||
model.move_selection(1);
|
||||
assert!(model.activate().is_none());
|
||||
}
|
||||
}
|
||||
+216
-66
@@ -3,9 +3,11 @@ use crate::{
|
||||
chrome,
|
||||
client::{Client, Updates},
|
||||
colors,
|
||||
commands::{self, CommandAction},
|
||||
cursor::CursorAnimator,
|
||||
input,
|
||||
label::middle_label,
|
||||
palette::CommandPalette,
|
||||
pane_name::RenameField,
|
||||
protocol::{
|
||||
ClientMessage, PaneSnapshot, ScrollKind, SelectionCommand, SelectionKind, SelectionSide,
|
||||
@@ -33,12 +35,205 @@ pub struct Workspace {
|
||||
snapshot: Option<Arc<Snapshot>>,
|
||||
panes: HashMap<u64, Entity<TerminalPane>>,
|
||||
error: Option<String>,
|
||||
focus: FocusHandle,
|
||||
palette: Option<Entity<CommandPalette>>,
|
||||
outgoing: Vec<Entity<TerminalPane>>,
|
||||
transition: Option<Slide>,
|
||||
transition_frame_pending: bool,
|
||||
_updates: Task<()>,
|
||||
}
|
||||
impl Workspace {
|
||||
fn focused_pane(&self) -> Option<Entity<TerminalPane>> {
|
||||
let snapshot = self.snapshot.as_ref()?;
|
||||
let tab = snapshot
|
||||
.tabs
|
||||
.iter()
|
||||
.find(|tab| tab.id == snapshot.active_tab)?;
|
||||
self.panes.get(&tab.active_pane).cloned()
|
||||
}
|
||||
|
||||
fn restore_focus(&self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
if let Some(pane) = self.focused_pane() {
|
||||
window.focus(&pane.read(cx).focus);
|
||||
} else {
|
||||
window.focus(&self.focus);
|
||||
}
|
||||
}
|
||||
|
||||
fn close_palette(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
self.palette = None;
|
||||
self.restore_focus(window, cx);
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn open_palette(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
if self.palette.is_some() {
|
||||
self.close_palette(window, cx);
|
||||
return;
|
||||
}
|
||||
for pane in self.panes.values() {
|
||||
pane.update(cx, |pane, cx| {
|
||||
pane.rename = None;
|
||||
pane.selecting = false;
|
||||
pane.preedit.clear();
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
let items = commands::root_items(self.snapshot.as_deref());
|
||||
let owner = cx.weak_entity();
|
||||
self.palette = Some(cx.new(|cx| {
|
||||
CommandPalette::new(
|
||||
items,
|
||||
move |action, window, cx| {
|
||||
let _ = owner.update(cx, |view, cx| {
|
||||
view.close_palette(window, cx);
|
||||
if let Some(action) = action {
|
||||
view.execute(action, window, cx);
|
||||
}
|
||||
});
|
||||
},
|
||||
window,
|
||||
cx,
|
||||
)
|
||||
}));
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let key = &event.keystroke;
|
||||
let command = (key.modifiers.control || key.modifiers.platform)
|
||||
&& key.modifiers.shift
|
||||
&& !key.modifiers.alt;
|
||||
if command && key.key.eq_ignore_ascii_case("p") {
|
||||
self.open_palette(window, cx);
|
||||
cx.stop_propagation();
|
||||
return;
|
||||
}
|
||||
if self.palette.is_some()
|
||||
|| self
|
||||
.focused_pane()
|
||||
.is_some_and(|pane| pane.read(cx).rename.is_some())
|
||||
{
|
||||
return;
|
||||
}
|
||||
let action = if command {
|
||||
match key.key.to_lowercase().as_str() {
|
||||
"t" => Some(CommandAction::NewTab),
|
||||
"d" => Some(CommandAction::SplitPane),
|
||||
"w" => Some(CommandAction::ClosePane),
|
||||
"r" => Some(CommandAction::RenamePane),
|
||||
"c" => Some(CommandAction::Copy),
|
||||
"v" => Some(CommandAction::Paste),
|
||||
"left" => Some(CommandAction::PreviousPane),
|
||||
"right" => Some(CommandAction::NextPane),
|
||||
_ => None,
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(action) = action {
|
||||
self.execute(action, window, cx);
|
||||
cx.stop_propagation();
|
||||
}
|
||||
}
|
||||
|
||||
fn execute(&mut self, action: CommandAction, window: &mut Window, cx: &mut Context<Self>) {
|
||||
use CommandAction::*;
|
||||
let pane = self.focused_pane();
|
||||
let pane_id = pane.as_ref().map(|pane| pane.read(cx).data().id);
|
||||
let message = match action {
|
||||
NewTab => Some(ClientMessage::NewTab { cwd: None }),
|
||||
SplitPane => pane_id.map(|pane| ClientMessage::Split { pane, cwd: None }),
|
||||
ClosePane => pane_id.map(|pane| ClientMessage::ClosePane { pane }),
|
||||
ResetPaneName => pane_id.map(|pane| ClientMessage::RenamePane { pane, name: None }),
|
||||
Copy => pane_id.map(|pane| ClientMessage::Copy { pane }),
|
||||
Scroll(kind) => pane_id.map(|pane| ClientMessage::Scroll { pane, kind }),
|
||||
FocusTab(tab) => Some(ClientMessage::FocusTab { tab }),
|
||||
FocusPane(pane) => Some(ClientMessage::FocusPane { pane }),
|
||||
PreviousTab | NextTab => self.adjacent_tab(matches!(action, NextTab)),
|
||||
PreviousPane | NextPane => self.snapshot.as_ref().and_then(|snapshot| {
|
||||
let index = snapshot
|
||||
.panes
|
||||
.iter()
|
||||
.position(|pane| Some(pane.id) == pane_id)?;
|
||||
let count = snapshot.panes.len();
|
||||
let next = if matches!(action, NextPane) {
|
||||
(index + 1) % count
|
||||
} else {
|
||||
(index + count - 1) % count
|
||||
};
|
||||
Some(ClientMessage::FocusPane {
|
||||
pane: snapshot.panes[next].id,
|
||||
})
|
||||
}),
|
||||
FocusLeft | FocusRight => {
|
||||
let forward = matches!(action, FocusRight);
|
||||
self.snapshot.as_ref().and_then(|snapshot| {
|
||||
let index = snapshot
|
||||
.panes
|
||||
.iter()
|
||||
.position(|pane| Some(pane.id) == pane_id)?;
|
||||
let next = if forward {
|
||||
index.checked_add(1)
|
||||
} else {
|
||||
index.checked_sub(1)
|
||||
};
|
||||
next.and_then(|next| snapshot.panes.get(next))
|
||||
.map(|pane| ClientMessage::FocusPane { pane: pane.id })
|
||||
.or_else(|| self.adjacent_tab(forward))
|
||||
})
|
||||
}
|
||||
RenamePane => {
|
||||
if let Some(pane) = pane {
|
||||
pane.update(cx, |pane, cx| pane.begin_rename(window, cx));
|
||||
}
|
||||
None
|
||||
}
|
||||
Paste => {
|
||||
if let Some(pane) = pane
|
||||
&& let Some(text) = cx.read_from_clipboard().and_then(|item| item.text())
|
||||
{
|
||||
pane.update(cx, |pane, cx| {
|
||||
pane.send(
|
||||
input::paste_text(
|
||||
&text,
|
||||
pane.mode().contains(TermMode::BRACKETED_PASTE),
|
||||
),
|
||||
cx,
|
||||
);
|
||||
});
|
||||
}
|
||||
None
|
||||
}
|
||||
Detach => {
|
||||
window.remove_window();
|
||||
None
|
||||
}
|
||||
};
|
||||
if let Some(message) = message
|
||||
&& let Err(error) = self.client.send(message)
|
||||
{
|
||||
self.error = Some(error.to_string());
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
|
||||
fn adjacent_tab(&self, forward: bool) -> Option<ClientMessage> {
|
||||
let snapshot = self.snapshot.as_ref()?;
|
||||
let index = snapshot
|
||||
.tabs
|
||||
.iter()
|
||||
.position(|tab| tab.id == snapshot.active_tab)?;
|
||||
let count = snapshot.tabs.len();
|
||||
let next = if forward {
|
||||
(index + 1) % count
|
||||
} else {
|
||||
(index + count - 1) % count
|
||||
};
|
||||
Some(ClientMessage::FocusTab {
|
||||
tab: snapshot.tabs[next].id,
|
||||
})
|
||||
}
|
||||
pub fn new(
|
||||
client: Client,
|
||||
updates: Updates,
|
||||
@@ -46,6 +241,8 @@ impl Workspace {
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Self {
|
||||
let focus = cx.focus_handle();
|
||||
window.focus(&focus);
|
||||
let task = cx.spawn_in(window, async move |view, cx| {
|
||||
while let Some(update) = updates.recv().await {
|
||||
if cx
|
||||
@@ -140,6 +337,15 @@ impl Workspace {
|
||||
.unwrap_or("Terminal");
|
||||
window.set_window_title(&format!("psyTerm — {title}"));
|
||||
view.snapshot = Some(snapshot);
|
||||
if let Some(palette) = &view.palette {
|
||||
let items = commands::root_items(view.snapshot.as_deref());
|
||||
palette.update(cx, |palette, cx| {
|
||||
palette.set_items(items, cx);
|
||||
palette.focus(window);
|
||||
});
|
||||
} else if view.panes.is_empty() {
|
||||
window.focus(&view.focus);
|
||||
}
|
||||
}
|
||||
cx.notify();
|
||||
})
|
||||
@@ -157,6 +363,8 @@ impl Workspace {
|
||||
snapshot: None,
|
||||
panes: HashMap::new(),
|
||||
error: None,
|
||||
focus,
|
||||
palette: None,
|
||||
outgoing: Vec::new(),
|
||||
transition: None,
|
||||
transition_frame_pending: false,
|
||||
@@ -254,6 +462,9 @@ impl Render for Workspace {
|
||||
}
|
||||
body = body.child(incoming);
|
||||
let mut root = div()
|
||||
.relative()
|
||||
.track_focus(&self.focus)
|
||||
.capture_key_down(cx.listener(Self::key_down))
|
||||
.size_full()
|
||||
.flex()
|
||||
.flex_col()
|
||||
@@ -271,6 +482,9 @@ impl Render for Workspace {
|
||||
.child(error.clone()),
|
||||
);
|
||||
}
|
||||
if let Some(palette) = &self.palette {
|
||||
root = root.child(palette.clone());
|
||||
}
|
||||
root
|
||||
}
|
||||
}
|
||||
@@ -500,77 +714,13 @@ impl TerminalPane {
|
||||
header
|
||||
}
|
||||
|
||||
fn key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
|
||||
fn key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {
|
||||
if self.read_only || self.rename.is_some() {
|
||||
return;
|
||||
}
|
||||
let key = &event.keystroke;
|
||||
let pane = self.data().id;
|
||||
self.activity(cx);
|
||||
if key.modifiers.control
|
||||
&& key.modifiers.shift
|
||||
&& !key.modifiers.alt
|
||||
&& !key.modifiers.platform
|
||||
{
|
||||
let handled = match key.key.to_lowercase().as_str() {
|
||||
"r" => {
|
||||
self.begin_rename(window, cx);
|
||||
true
|
||||
}
|
||||
"c" => {
|
||||
self.command(ClientMessage::Copy { pane });
|
||||
true
|
||||
}
|
||||
"v" => {
|
||||
if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) {
|
||||
self.send(
|
||||
input::paste_text(
|
||||
&text,
|
||||
self.mode().contains(TermMode::BRACKETED_PASTE),
|
||||
),
|
||||
cx,
|
||||
);
|
||||
}
|
||||
true
|
||||
}
|
||||
"t" => {
|
||||
self.command(ClientMessage::NewTab { cwd: None });
|
||||
true
|
||||
}
|
||||
"d" => {
|
||||
self.command(ClientMessage::Split { pane, cwd: None });
|
||||
true
|
||||
}
|
||||
"w" => {
|
||||
self.command(ClientMessage::ClosePane { pane });
|
||||
true
|
||||
}
|
||||
"left" | "right" => {
|
||||
if let Some(tab) = self
|
||||
.snapshot
|
||||
.tabs
|
||||
.iter()
|
||||
.find(|t| t.id == self.snapshot.active_tab)
|
||||
&& let Some(index) = tab.panes.iter().position(|p| *p == pane)
|
||||
{
|
||||
let next = if key.key == "right" {
|
||||
(index + 1) % tab.panes.len()
|
||||
} else {
|
||||
(index + tab.panes.len() - 1) % tab.panes.len()
|
||||
};
|
||||
self.command(ClientMessage::FocusPane {
|
||||
pane: tab.panes[next],
|
||||
});
|
||||
}
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
if handled {
|
||||
cx.stop_propagation();
|
||||
return;
|
||||
}
|
||||
}
|
||||
if key.modifiers.shift
|
||||
&& !key.modifiers.control
|
||||
&& !key.modifiers.alt
|
||||
@@ -823,7 +973,7 @@ impl Render for TerminalPane {
|
||||
let mut delay=None;
|
||||
window.with_content_mask(Some(ContentMask{bounds}),|window| {
|
||||
let origin=bounds.origin+point(px(PADDING),px(PADDING));
|
||||
let focused=window.is_window_active() && pane.active && pane.rename.is_none();
|
||||
let focused=window.is_window_active() && pane.active && pane.focus.is_focused(window) && pane.rename.is_none();
|
||||
pane.renderer.paint_with_cursor(origin,window,cx,|window| {
|
||||
if !pane.transitioning {
|
||||
delay=pane.cursor.paint(Instant::now(),focused,window);
|
||||
|
||||
Reference in New Issue
Block a user