Skip to content

armgit / muxin

Public Imported from GitHub
0

All your machines, one app. For you and your AI agents: agent sessions, desktops, files, logs and GitHub across your Macs, Linux and Windows machines, with an MCP server.

Keyboard shortcuts you can change, a folder browser for new sessions, colorful icons

Adib Hannadadcaf9213b7
diff --git a/README.md b/README.md
index 9652d5a..cdec527 100644
--- a/README.md
+++ b/README.md
@@ -78,7 +78,7 @@ muxen status
The macOS themes also switch to the system fonts (SF Pro, and SF Mono when it's installed). The choice is saved in `ui.json` next to `fleet.toml`.
-Keyboard: ⌘B hide or show the sidebar · ⌘R check now · ⇧⌘R sync GitHub · ⌘N add machine · ⌘T new session · ⌘1 / ⌘2 overview / jobs · ⌘F or `/` search the fleet · ⌘J activity · ⌘[ / ⌘] back / forward · ⌘, settings. On Linux and Windows, use Ctrl instead of ⌘.
+Keyboard: ⌘1…⌘9 go to your machines · ⌃1…⌃4 overview, jobs, workspaces, GitHub (Alt on Linux and Windows) · ⌘J activity · ⌘R check machines · ⇧⌘R sync GitHub · ⌘N add machine · ⌘T new session · ⌘F or `/` search the fleet · ⌘B sidebar · ⌘[ / ⌘] back / forward · ⌘, settings. Hold ⌘ to see them in the app, and change them in Settings › Keyboard. On Linux and Windows, use Ctrl instead of ⌘.
## The inventory: `fleet.toml`
diff --git a/src/fleet/files.rs b/src/fleet/files.rs
index 933e78b..d10565a 100644
--- a/src/fleet/files.rs
+++ b/src/fleet/files.rs
@@ -76,7 +76,7 @@ impl Engine {
pub async fn list_files(self: &Arc<Self>, machine_id: &str, path: &str) -> Result<Listing, String> {
let (spec, _) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;
if self.demo_world().is_some() {
- return Err("The demo has no files to show.".into());
+ return Ok(demo_listing(&spec, path));
}
let l = self.files_link(&spec).await.ok_or_else(|| format!("Browsing {} needs Muxen's agent there (Linux or macOS).", spec.name))?;
let r = l.request(json!({ "op": "files", "path": if path.trim().is_empty() { "~" } else { path } }), Duration::from_secs(20)).await?;
@@ -410,3 +410,30 @@ impl WaitOutput for Child {
Ok((status, err))
}
}
+
+/// A made-up home folder for the demo: a few projects to browse.
+fn demo_listing(spec: &MachineSpec, path: &str) -> Listing {
+ let home = if spec.platform.as_deref().is_some_and(|p| p.starts_with("darwin")) { "/Users/ci" } else { "/home/ci" };
+ let path = path.trim();
+ let abs = match path.strip_prefix('~') {
+ Some(rest) => format!("{home}{rest}"),
+ None if path.is_empty() => home.to_string(),
+ None if !path.starts_with('/') => format!("{home}/{path}"),
+ None => path.to_string(),
+ };
+ let abs = if abs.len() > 1 { abs.trim_end_matches('/').to_string() } else { abs };
+ let (folders, files): (&[&str], &[&str]) = match abs.strip_prefix(home).map(|r| r.trim_start_matches('/')) {
+ Some("") => (&[".config", "code", "Documents", "Downloads", "notes"], &["todo.md"]),
+ Some("code") => (&["api", "checkout", "desktop", "infra", "ios-app", "muxen", "web"], &[]),
+ Some(p) if p.starts_with("code/") && !p["code/".len()..].contains('/') => (&[".github", "docs", "src", "tests"], &["README.md", "package.json"]),
+ _ => (&[], &[]),
+ };
+ let entry = |name: &&str, folder: bool| FileEntry { name: name.to_string(), kind: if folder { "dir" } else { "file" }.into(), folder, size: (!folder).then_some(2048), modified: None };
+ Listing {
+ machine_id: spec.id.clone(),
+ path: abs,
+ home: home.to_string(),
+ entries: folders.iter().map(|n| entry(n, true)).chain(files.iter().map(|n| entry(n, false))).collect(),
+ more: false,
+ }
+}
diff --git a/src/ui/activity.rs b/src/ui/activity.rs
index 5a526ab..43a73e2 100644
--- a/src/ui/activity.rs
+++ b/src/ui/activity.rs
@@ -282,7 +282,7 @@ impl Root {
})),
),
)
- .child(
+ .children(Some(super::shortcuts::label_for(cx, "activity")).filter(|k| !k.is_empty()).map(|keys| {
div()
.mt(px(18.))
.flex()
@@ -291,8 +291,8 @@ impl Root {
.text_size(px(12.))
.text_color(theme.text_placeholder)
.child("Open Activity from anywhere with")
- .child(kit::kbd(theme, "⌘J")),
- )
+ .child(kit::kbd(theme, keys))
+ }))
.into_any_element()
}
@@ -596,13 +596,11 @@ fn start_row(
/// The filter matched nothing (but there is other activity).
fn filtered_empty(theme: &Theme, filter: ActivityFilter) -> AnyElement {
- let (icon_name, color, title, body) = match filter {
- ActivityFilter::Failed => ("circle-check", theme.success, "Nothing failed", "Failed operations and agent commands that exit non-zero show up here."),
- ActivityFilter::Operations => {
- ("activity", theme.text_muted, "No operations yet", "Runner installs, restarts, log requests and workspace setup show up here.")
- }
- ActivityFilter::Agents => ("terminal", theme.text_muted, "No agent commands yet", "Commands agents run in workspaces show up here with their output."),
- ActivityFilter::All => ("activity", theme.text_muted, "Nothing here", "Activity shows up here as it happens."),
+ let (icon_name, title, body) = match filter {
+ ActivityFilter::Failed => ("circle-check", "Nothing failed", "Failed operations and agent commands that exit non-zero show up here."),
+ ActivityFilter::Operations => ("activity", "No operations yet", "Runner installs, restarts, log requests and workspace setup show up here."),
+ ActivityFilter::Agents => ("terminal", "No agent commands yet", "Commands agents run in workspaces show up here with their output."),
+ ActivityFilter::All => ("activity", "Nothing here", "Activity shows up here as it happens."),
};
div()
.flex_1()
@@ -613,7 +611,7 @@ fn filtered_empty(theme: &Theme, filter: ActivityFilter) -> AnyElement {
.gap(px(8.))
.px(px(28.))
.pb(px(80.))
- .child(div().size(px(44.)).mb(px(4.)).rounded_full().bg(theme.element).flex().items_center().justify_center().child(icon(icon_name, 20., color)))
+ .child(kit::color_tile(icon_name, 44.).mb(px(4.)))
.child(div().text_size(px(15.)).font_weight(FontWeight::SEMIBOLD).text_color(theme.text).child(title))
.child(div().w(px(340.)).text_center().text_size(px(12.5)).text_color(theme.text_muted).child(body))
.into_any_element()
diff --git a/src/ui/desktop.rs b/src/ui/desktop.rs
index 6ebb67e..76b011d 100644
--- a/src/ui/desktop.rs
+++ b/src/ui/desktop.rs
@@ -15,7 +15,7 @@ use gpui::{
};
use serde_json::{Value, json};
-use super::kit::{Button, ButtonStyle, icon, spinner};
+use super::kit::{self, Button, ButtonStyle, spinner};
use super::theme::ActiveTheme;
use crate::fleet::Engine;
use crate::fleet::desktop::{FRAME, INPUT, TILES, keysym};
@@ -25,13 +25,13 @@ const CONTEXT: &str = "Desktop";
/// Keys that would otherwise run Muxen's own shortcuts go to the machine.
pub fn bind_keys(cx: &mut App) {
- let mut keys = vec!["escape", "/", "tab", "shift-tab"];
+ let mut keys: Vec<String> = ["escape", "/", "tab", "shift-tab"].map(String::from).to_vec();
if cfg!(target_os = "macos") {
- keys.extend(["cmd-r", "cmd-t", "cmd-n", "cmd-f"]);
+ keys.extend(["cmd-r", "cmd-t", "cmd-n", "cmd-f"].map(String::from));
} else {
- keys.extend(["ctrl-r", "ctrl-shift-r", "ctrl-1", "ctrl-2", "ctrl-,", "ctrl-f", "ctrl-j", "ctrl-n"]);
+ keys.extend(super::shortcuts::ctrl_keys(cx));
}
- cx.bind_keys(keys.into_iter().map(|k| KeyBinding::new(k, NoAction, Some(CONTEXT))));
+ cx.bind_keys(keys.iter().map(|k| KeyBinding::new(k, NoAction, Some(CONTEXT))));
}
enum State {
@@ -550,7 +550,7 @@ impl Render for DesktopView {
.flex_col()
.items_center()
.gap(px(10.))
- .child(icon("power", 28., theme.text_placeholder))
+ .child(kit::color_tile("power", 44.))
.child(div().text_size(px(14.)).text_color(theme.text).child(why))
.child(div().text_size(px(12.5)).text_color(theme.text_muted).child("Comes back when it does.")),
),
@@ -560,7 +560,7 @@ impl Render for DesktopView {
.flex_col()
.items_center()
.gap(px(10.))
- .child(icon("monitor", 28., theme.text_placeholder))
+ .child(kit::color_tile("monitor", 44.))
.child(div().max_w(px(460.)).text_center().text_size(px(13.)).text_color(theme.text_muted).child(why.clone()))
.child(Button::new("desktop-retry", "Try again").icon("refresh-cw").on_click(cx.listener(|this, _, window, cx| {
this.retries = 0;
@@ -653,10 +653,10 @@ pub fn toolbar(view: &Entity<DesktopView>, extra: Vec<AnyElement>, cx: &App) ->
.flex()
.items_center()
.gap(px(10.))
- .child(icon("monitor", 14., theme.text_muted))
+ .child(kit::color_icon(&theme, "monitor", 14., theme.text_muted))
.child(div().flex_none().text_size(px(12.5)).text_color(theme.text_muted).child(status))
.when(!via.is_empty(), |d| {
- d.child(div().flex_none().flex().items_center().gap(px(5.)).text_size(px(12.)).text_color(theme.text_placeholder).child(icon("network", 12., theme.text_placeholder)).child(via))
+ d.child(div().flex_none().flex().items_center().gap(px(5.)).text_size(px(12.)).text_color(theme.text_placeholder).child(kit::color_icon(&theme, "network", 12., theme.text_placeholder)).child(via))
}),
)
.child(picker.flex_none())
diff --git a/src/ui/detail.rs b/src/ui/detail.rs
index d5929ab..24e3b4f 100644
--- a/src/ui/detail.rs
+++ b/src/ui/detail.rs
@@ -194,7 +194,7 @@ impl Root {
.flex_row()
.items_center()
.gap(px(12.))
- .child(icon("box", 16., theme.text_placeholder))
+ .child(kit::color_tile("box", 28.))
.child(div().flex_1().min_w(px(0.)).text_size(px(12.5)).text_color(theme.text_muted).child(
"No runners on this machine yet. Install one and it will register with GitHub and start picking up jobs.",
))
diff --git a/src/ui/dialogs.rs b/src/ui/dialogs.rs
index 92ad5c4..426e186 100644
--- a/src/ui/dialogs.rs
+++ b/src/ui/dialogs.rs
@@ -7,10 +7,12 @@ use gpui::{
Window, div, prelude::*, px,
};
+use super::github::Load;
use super::input::{InputEvent, TextInput};
use super::kit::{self, Button, ButtonStyle, checkbox, icon, label};
use super::theme::{ActiveTheme, mono_font, Theme};
use crate::fleet::Engine;
+use crate::fleet::files::Listing;
use crate::fleet::sessions::{AGENTS, StartSession};
use crate::fleet::workspaces::{CreateWorkspace, DEFAULT_IMAGE, WorkspaceIsolation};
use crate::fleet::model::Snapshot;
@@ -68,7 +70,7 @@ fn error_line(theme: &Theme, error: &Option<String>) -> Option<impl IntoElement>
.text_size(px(12.5))
.text_color(theme.text)
.child(icon("circle-alert", 14., theme.error))
- .child(div().flex_1().child(e.clone()))
+ .child(div().flex_1().min_w(px(0.)).child(e.clone()))
})
}
@@ -227,7 +229,7 @@ impl Render for AddMachineDialog {
.on_click(cx.listener(move |this, _, _, cx| {
this.pick(host.clone(), name.clone(), cx);
if !ssh {
- this.note = Some(format!("Turn on Remote Login on {name} (Settings › General › Sharing), then add it."));
+ this.note = Some(format!("Turn on Remote Login on {name}: Settings › General › Sharing."));
}
cx.notify();
}))
@@ -242,7 +244,7 @@ impl Render for AddMachineDialog {
div().flex().flex_col().gap(px(6.)).child(label(&theme, "On this network")).child(body)
})
.children(self.note.clone().map(|n| {
- div().flex().items_start().gap(px(8.)).text_size(px(12.)).text_color(theme.text_muted).child(icon("info", 13., theme.info)).child(div().flex_1().child(n))
+ div().flex().items_start().gap(px(8.)).text_size(px(12.)).text_color(theme.text_muted).child(icon("info", 13., theme.info)).child(div().flex_1().min_w(px(0.)).child(n))
}))
.children(error_line(&theme, &self.error))
.child(footer(vec![
@@ -269,7 +271,7 @@ fn suggestion(theme: &Theme, id: impl Into<gpui::ElementId>, text: impl Into<Sha
.text_size(px(12.))
.font_family(mono_font())
.text_color(theme.text_muted)
- .child(icon(icon_name, 12., theme.text_placeholder))
+ .child(kit::color_icon(theme, icon_name, 12., theme.text_placeholder))
.child(text.into())
}
@@ -404,7 +406,7 @@ impl Render for InstallDialog {
.bg(theme.warning.opacity(0.1))
.text_size(px(12.5))
.child(icon("triangle-alert", 14., theme.warning))
- .child(div().flex_1().child("Runners register with a GitHub organization or repository. Add one in Settings first."))
+ .child(div().flex_1().min_w(px(0.)).child("Runners register with a GitHub organization or repository. Add one in Settings first."))
.child(Button::new("inst-settings", "Settings").on_click(cx.listener(|_, _, _, cx| cx.emit(DialogEvent::OpenSettings))))
.into_any_element()
} else {
@@ -429,7 +431,7 @@ impl Render for InstallDialog {
.bg(if selected { theme.accent.opacity(0.12) } else { theme.element })
.text_size(px(12.5))
.font_family(mono_font())
- .child(icon(if sc.contains('/') { "git-branch" } else { "layers" }, 12., if selected { theme.accent } else { theme.text_placeholder }))
+ .child(kit::color_icon(&theme, if sc.contains('/') { "git-branch" } else { "layers" }, 12., theme.text_placeholder))
.child(sc.clone())
.on_click(cx.listener(move |this, _, _, cx| {
this.scope = Some(value.clone());
@@ -540,7 +542,7 @@ impl InstallDialog {
.border_color(if selected { theme.accent } else { theme.border_variant })
.bg(if selected { theme.accent.opacity(0.10) } else { theme.element })
.when(!available, |d| d.opacity(0.6))
- .child(div().pt(px(1.)).child(icon(icon_name, 13., if selected { theme.accent } else { theme.text_placeholder })))
+ .child(kit::color_tile(icon_name, 20.))
.child(
div()
.flex()
@@ -732,7 +734,7 @@ impl NewWorkspaceDialog {
.cursor_pointer()
.border_color(if selected { theme.accent } else { theme.border_variant })
.bg(if selected { theme.accent.opacity(0.10) } else { theme.element })
- .child(div().pt(px(1.)).child(icon(icon_name, 14., if selected { theme.accent } else { theme.text_placeholder })))
+ .child(kit::color_tile(icon_name, 22.))
.child(
div()
.flex()
@@ -831,7 +833,7 @@ impl Render for NewWorkspaceDialog {
.bg(if selected { theme.accent.opacity(0.12) } else { theme.element })
.text_size(px(12.5))
.child(if id.is_none() {
- icon("zap", 12., if selected { theme.accent } else { theme.text_placeholder }).into_any_element()
+ kit::color_icon(&theme, "zap", 12., theme.text_placeholder).into_any_element()
} else {
div().size(px(7.)).rounded_full().bg(if online { theme.success } else { theme.text_placeholder }).into_any_element()
})
@@ -884,6 +886,10 @@ pub struct NewSessionDialog {
/// Start in a new workspace (`prefill.workspace`) rather than a folder.
in_workspace: bool,
branch: Entity<TextInput>,
+ /// The folders where the Folder field points: (machine, folder) asked
+ /// for, and the last listing that came back (for which machine and folder).
+ folders_asked: Option<(String, String)>,
+ folders: Option<((String, String), Load<Listing>)>,
_subscriptions: Vec<Subscription>,
}
@@ -929,7 +935,14 @@ impl NewSessionDialog {
InputEvent::Cancel => cx.emit(DialogEvent::Dismissed),
InputEvent::Changed => cx.notify(),
};
- let subs = vec![cx.subscribe_in(&cwd, window, on_input), cx.subscribe_in(&prompt, window, on_input), cx.subscribe_in(&branch, window, on_input)];
+ // Typing a folder lists what's in it.
+ let on_folder = move |this: &mut Self, input: &Entity<TextInput>, e: &InputEvent, window: &mut Window, cx: &mut Context<Self>| {
+ if matches!(e, InputEvent::Changed) {
+ this.list_folders(cx);
+ }
+ on_input(this, input, e, window, cx)
+ };
+ let subs = vec![cx.subscribe_in(&cwd, window, on_folder), cx.subscribe_in(&prompt, window, on_input), cx.subscribe_in(&branch, window, on_input)];
let snapshot = engine.current();
let machine = machine.or_else(|| session_machines(&snapshot).into_iter().find(|m| m.status == "online").map(|m| m.id.clone()));
let mut dialog = NewSessionDialog {
@@ -942,12 +955,54 @@ impl NewSessionDialog {
prefill: Prefill::default(),
in_workspace: false,
branch,
+ folders_asked: None,
+ folders: None,
_subscriptions: subs,
};
dialog.agent = dialog.default_agent(&snapshot);
+ dialog.list_folders(cx);
dialog
}
+ /// Lists the folder the Folder field points at, on the chosen machine,
+ /// unless that's what's listed already.
+ fn list_folders(&mut self, cx: &mut Context<Self>) {
+ let Some(machine) = self.machine.clone() else { return };
+ if self.without_agent(&self.engine.current()) {
+ self.folders_asked = None;
+ return;
+ }
+ let (dir, _) = folder_query(self.cwd.read(cx).text());
+ let key = (machine.clone(), dir.clone());
+ if self.folders_asked.as_ref() == Some(&key) {
+ return;
+ }
+ self.folders_asked = Some(key.clone());
+ if self.folders.is_none() {
+ self.folders = Some((key.clone(), Load::Loading));
+ }
+ let engine = self.engine.clone();
+ let job = engine.runtime().spawn({
+ let engine = engine.clone();
+ async move { engine.list_files(&machine, &dir).await }
+ });
+ cx.spawn(async move |this, cx| {
+ let result = job.await.unwrap_or_else(|e| Err(e.to_string()));
+ let _ = this.update(cx, |this, cx| {
+ if this.folders_asked.as_ref() == Some(&key) {
+ this.folders = Some((key, result.map_or_else(Load::Failed, Load::Ready)));
+ cx.notify();
+ }
+ });
+ })
+ .detach();
+ }
+
+ /// Puts `path` in the Folder field (which lists it).
+ fn go_to_folder(&mut self, path: String, cx: &mut Context<Self>) {
+ self.cwd.update(cx, |i, cx| i.set_text(path, cx));
+ }
+
pub fn first_focus(&self, cx: &App) -> FocusHandle {
self.cwd.focus_handle(cx)
}
@@ -1012,7 +1067,7 @@ impl NewSessionDialog {
let session = StartSession {
machine_id: machine_id.clone(),
agent: self.agent.to_string(),
- cwd: text(&self.cwd, cx).unwrap_or_else(|| "~".into()),
+ cwd: text(&self.cwd, cx).map(|t| if t.len() > 1 { t.trim_end_matches('/').to_string() } else { t }).unwrap_or_else(|| "~".into()),
title,
prompt: if self.agent == "shell" { None } else { message },
cols: 0,
@@ -1046,7 +1101,125 @@ impl NewSessionDialog {
}
}
+/// What the Folder field points at: the folder to list ("~/code") and the
+/// start of a name in it ("ap" in "~/code/ap").
+fn folder_query(text: &str) -> (String, String) {
+ let t = text.trim();
+ if t.is_empty() || t == "~" {
+ return ("~".into(), String::new());
+ }
+ let (dir, name) = match t.rsplit_once('/') {
+ Some(("", name)) => ("/", name),
+ Some((dir, name)) => (dir, name),
+ // A bare name is in the home folder, where sessions start.
+ None => ("~", t),
+ };
+ (dir.to_string(), name.to_string())
+}
+
+/// `name` inside `dir`, ending in a slash so its folders list next.
+fn folder_path(dir: &str, name: &str) -> String {
+ if dir == "/" { format!("/{name}/") } else { format!("{}/{name}/", dir.trim_end_matches('/')) }
+}
+
impl NewSessionDialog {
+ /// The folders where the Folder field points: click one to go into it.
+ fn folder_browser(&self, theme: &Theme, cx: &mut Context<Self>) -> Option<AnyElement> {
+ let asked = self.folders_asked.clone()?;
+ let (shown, load) = self.folders.as_ref()?;
+ // Still showing the last folder while the next one loads: not clickable.
+ let stale = *shown != asked;
+ let (dir, typed) = folder_query(self.cwd.read(cx).text());
+ let quiet = |text: String| div().px(px(2.)).text_size(px(11.5)).text_color(theme.text_placeholder).child(text).into_any_element();
+ let listing = match load {
+ Load::Ready(l) => l,
+ Load::Loading => {
+ return Some(div().flex().items_center().gap(px(6.)).child(kit::spinner("ns-folders", 11., theme.text_placeholder)).child(quiet("Looking…".into())).into_any_element());
+ }
+ Load::Failed(e) => return Some(quiet(e.clone())),
+ };
+ let needle = typed.to_lowercase();
+ let mut found: Vec<&str> = listing
+ .entries
+ .iter()
+ .filter(|e| e.folder && (needle.starts_with('.') || !e.name.starts_with('.')))
+ .map(|e| e.name.as_str())
+ .filter(|n| n.to_lowercase().contains(&needle))
+ .collect();
+ // Names that start with what's typed first.
+ found.sort_by_key(|n| !n.to_lowercase().starts_with(&needle));
+ const SHOWN: usize = 24;
+ let more = found.len().saturating_sub(SHOWN);
+ let chips: Vec<AnyElement> = found
+ .iter()
+ .take(SHOWN)
+ .enumerate()
+ .map(|(i, name)| {
+ let next = folder_path(&dir, name);
+ div()
+ .id(("ns-dir", i))
+ .flex()
+ .items_center()
+ .gap(px(5.))
+ .h(px(24.))
+ .px(px(8.))
+ .rounded(px(5.))
+ .bg(theme.element)
+ .border_1()
+ .border_color(theme.border_variant)
+ .font_family(mono_font())
+ .text_size(px(12.))
+ .when(stale, |d| d.opacity(0.5))
+ .when(!stale, |d| d.cursor_pointer().hover(|st| st.bg(theme.element_hover)))
+ .child(kit::color_icon(theme, "folder", 12., theme.text_placeholder))
+ .child(name.to_string())
+ .on_click(cx.listener(move |this, _, _, cx| {
+ if !stale {
+ this.go_to_folder(next.clone(), cx)
+ }
+ }))
+ .into_any_element()
+ })
+ .collect();
+ // Where it is, and the way up.
+ let here = super::files::display(listing);
+ let parent = match listing.path.trim_end_matches('/').rsplit_once('/') {
+ _ if listing.path == "/" => None,
+ Some(("", _)) => Some("/".to_string()),
+ Some((up, _)) => Some(super::files::tilde(up, &listing.home) + "/"),
+ None => None,
+ };
+ let header = div()
+ .flex()
+ .items_center()
+ .gap(px(6.))
+ .h(px(22.))
+ .child(div().flex_1().min_w(px(0.)).truncate().text_size(px(11.5)).text_color(theme.text_placeholder).child(format!("Folders in {here}")))
+ .when(stale, |d| d.child(kit::spinner("ns-folders", 11., theme.text_placeholder)))
+ .children(parent.map(|up| {
+ Button::icon_only("ns-up", "arrow-up").tooltip("Up a folder").disabled(stale).on_click(cx.listener(move |this, _, _, cx| this.go_to_folder(up.clone(), cx)))
+ }));
+ let body = if chips.is_empty() {
+ quiet(if needle.is_empty() { "No folders here.".into() } else { format!("No folder matches \"{typed}\".") })
+ } else {
+ div().flex().flex_wrap().gap(px(6.)).children(chips).into_any_element()
+ };
+ Some(
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(6.))
+ .p(px(8.))
+ .rounded(px(7.))
+ .border_1()
+ .border_color(theme.border_variant)
+ .child(header)
+ .child(body)
+ .when(more > 0, |d| d.child(quiet(format!("{more} more: type to narrow them down."))))
+ .into_any_element(),
+ )
+ }
+
/// New workspace, or a folder that's already there.
fn where_choice(&self, theme: &Theme, plan: &WorkspacePlan, cx: &mut Context<Self>) -> AnyElement {
let fresh = if plan.branch.is_some() { "A fresh clone, on its own branch" } else { "A fresh clone of the pull request" };
@@ -1065,7 +1238,7 @@ impl NewSessionDialog {
.cursor_pointer()
.border_color(if selected { theme.accent } else { theme.border_variant })
.bg(if selected { theme.accent.opacity(0.10) } else { theme.element })
- .child(icon(glyph, 16., if selected { theme.text_accent } else { theme.text_muted }))
+ .child(kit::color_tile(glyph, 26.))
.child(
div()
.flex()
@@ -1167,6 +1340,7 @@ impl Render for NewSessionDialog {
.on_click(cx.listener(move |this, _, _, cx| {
this.machine = Some(id.clone());
this.agent_picked = false;
+ this.list_folders(cx);
// Find out what's installed there if we don't know yet.
let engine = this.engine.clone();
let id = id.clone();
@@ -1223,17 +1397,29 @@ impl Render for NewSessionDialog {
rows.push(div().flex().gap(px(8.)).children(cards).into_any_element());
}
- // Checkouts of the repository at hand, then workspace folders on this machine.
+ // Checkouts of the repository at hand, then where sessions run on this
+ // machine, then workspace folders there.
let on_machine = |id: &str| self.machine.as_deref() == Some(id);
- let folders: Vec<String> = snapshot
+ let mut folders: Vec<String> = Vec::new();
+ for path in snapshot
.checkouts
.iter()
.filter(|c| on_machine(&c.machine_id) && self.prefill.repo.is_some() && c.repo.as_deref().map(str::to_lowercase) == self.prefill.repo.as_deref().map(str::to_lowercase))
.map(|c| c.path.clone())
+ .chain(snapshot.sessions.iter().filter(|x| on_machine(&x.machine_id) && !matches!(x.cwd.as_str(), "" | "~")).map(|x| x.cwd.clone()))
.chain(snapshot.workspaces.iter().filter(|w| on_machine(&w.machine_id)).map(|w| w.path.clone()))
- .take(4)
- .collect();
+ {
+ if folders.len() < 5 && !folders.contains(&path) {
+ folders.push(path);
+ }
+ }
+ // Shown as ~/... once the machine's home folder is known.
+ let home = match &self.folders {
+ Some(((m, _), Load::Ready(l))) if self.machine.as_ref() == Some(m) => l.home.clone(),
+ _ => String::new(),
+ };
let folder_chips = div().flex().flex_wrap().gap(px(6.)).children(folders.into_iter().enumerate().map(|(i, path)| {
+ let path = super::files::tilde(&path, &home);
let value = path.clone();
div()
.id(("ns-folder", i))
@@ -1241,6 +1427,8 @@ impl Render for NewSessionDialog {
.px(px(8.))
.flex()
.items_center()
+ .gap(px(5.))
+ .child(kit::color_icon(&theme, "clock", 11., theme.text_placeholder))
.rounded(px(5.))
.border_1()
.border_color(theme.border_variant)
@@ -1290,7 +1478,7 @@ impl Render for NewSessionDialog {
.children(self.prefill.workspace.clone().map(|plan| field(&theme, "Where", self.where_choice(&theme, &plan, cx), None)))
.map(|d| match self.prefill.workspace.clone().filter(|_| self.in_workspace) {
Some(plan) => d.child(self.workspace_fields(&theme, &plan, machine.as_ref(), cx)),
- None => d.child(field(&theme, "Folder", div().flex().flex_col().gap(px(8.)).child(self.cwd.clone()).child(folder_chips), None)),
+ None => d.child(field(&theme, "Folder", div().flex().flex_col().gap(px(8.)).child(self.cwd.clone()).child(folder_chips).children(self.folder_browser(&theme, cx)), None)),
})
.when(self.agent != "shell", |d| {
let prepared = self.prefill.message.clone().map(|m| {
@@ -1335,3 +1523,24 @@ impl Render for NewSessionDialog {
]))
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_folder_field_points_at_a_folder_and_a_name() {
+ let q = |t: &str| folder_query(t);
+ assert_eq!(q(""), ("~".into(), "".into()));
+ assert_eq!(q("~"), ("~".into(), "".into()));
+ assert_eq!(q("~/"), ("~".into(), "".into()));
+ assert_eq!(q("~/code/"), ("~/code".into(), "".into()));
+ assert_eq!(q("~/code/ap"), ("~/code".into(), "ap".into()));
+ assert_eq!(q("co"), ("~".into(), "co".into()));
+ assert_eq!(q("/"), ("/".into(), "".into()));
+ assert_eq!(q("/us"), ("/".into(), "us".into()));
+ assert_eq!(folder_path("~", "code"), "~/code/");
+ assert_eq!(folder_path("/", "usr"), "/usr/");
+ assert_eq!(folder_path("~/code/", "api"), "~/code/api/");
+ }
+}
diff --git a/src/ui/files.rs b/src/ui/files.rs
index 3c89a6f..8d20f58 100644
--- a/src/ui/files.rs
+++ b/src/ui/files.rs
@@ -262,7 +262,7 @@ impl CopyDialog {
}).collect();
let body: AnyElement = match &pane.listing {
Load::Loading => div().p(px(14.)).flex().items_center().gap(px(8.)).text_size(px(12.5)).text_color(theme.text_muted).child(kit::spinner(SharedString::from(format!("cp-{tag}-spin")), 12., theme.text_muted)).child("Opening…").into_any_element(),
- Load::Failed(e) => div().p(px(14.)).flex().gap(px(8.)).text_size(px(12.5)).text_color(theme.text_muted).child(icon("circle-alert", 14., theme.warning)).child(div().flex_1().child(e.clone())).into_any_element(),
+ Load::Failed(e) => div().p(px(14.)).flex().gap(px(8.)).text_size(px(12.5)).text_color(theme.text_muted).child(icon("circle-alert", 14., theme.warning)).child(div().flex_1().min_w(px(0.)).child(e.clone())).into_any_element(),
Load::Ready(l) => {
let shown: Vec<&crate::fleet::files::FileEntry> = l.entries.iter().filter(|e| self.show_hidden || !e.name.starts_with('.')).collect();
if shown.is_empty() {
@@ -346,7 +346,7 @@ impl CopyDialog {
})),
)
})
- .child(icon(if e.folder { "folder" } else { "file" }, 14., if e.folder { theme.text_accent } else { theme.text_placeholder }))
+ .child(kit::color_icon(&theme, if e.folder { "folder" } else { "file" }, 14., theme.text_placeholder))
.child(div().flex_1().min_w(px(0.)).truncate().text_size(px(12.5)).text_color(if dim { theme.text_placeholder } else { theme.text }).child(e.name.clone()))
.child(div().flex_none().font_family(mono_font()).text_size(px(11.)).text_color(theme.text_placeholder).child(meta));
// A folder opens; a file (on the left) is picked.
@@ -361,10 +361,16 @@ impl CopyDialog {
}
/// A folder as people say it: ~/x for the home folder.
-fn display(l: &Listing) -> String {
- match l.path.strip_prefix(&l.home) {
- Some(rest) if !l.home.is_empty() && (rest.is_empty() || rest.starts_with('/')) => format!("~{rest}"),
- _ => l.path.clone(),
+/// The listing's folder, as ~/... when it's in the home folder.
+pub(super) fn display(l: &Listing) -> String {
+ tilde(&l.path, &l.home)
+}
+
+/// `path`, as ~/... when it's in `home`.
+pub(super) fn tilde(path: &str, home: &str) -> String {
+ match path.strip_prefix(home) {
+ Some(rest) if !home.is_empty() && (rest.is_empty() || rest.starts_with('/')) => format!("~{rest}"),
+ _ => path.to_string(),
}
}
diff --git a/src/ui/github.rs b/src/ui/github.rs
index 3c1b843..0417ce7 100644
--- a/src/ui/github.rs
+++ b/src/ui/github.rs
@@ -546,7 +546,7 @@ impl Root {
.text_color(if inbox_active { theme.text } else { theme.text_muted })
.when(inbox_active, |d| d.bg(theme.element_selected))
.when(!inbox_active, |d| d.hover(|st| st.bg(theme.ghost_hover)))
- .child(icon("inbox", 14., if inbox_active { theme.text_accent } else { theme.text_placeholder }))
+ .child(kit::color_tile("inbox", 18.))
.child("For you")
.child(div().flex_1())
.children(waiting.filter(|n| *n > 0).map(|n| kit::pill(n.to_string(), theme.accent)))
@@ -646,7 +646,7 @@ impl Root {
.cursor_pointer()
.when(selected, |d| d.bg(theme.element_selected))
.when(!selected, |d| d.hover(|st| st.bg(theme.ghost_hover)))
- .child(icon(if private { "lock" } else { "book-open" }, 13., theme.text_placeholder))
+ .child(kit::color_icon(theme, if private { "lock" } else { "book-open" }, 13., theme.text_placeholder))
.child(
div()
.flex()
@@ -655,7 +655,7 @@ impl Root {
.when(owner_line, |d| d.child(div().w(px(text_w)).truncate().text_size(px(11.)).text_color(theme.text_placeholder).child(owner.to_string()))),
)
.child(div().flex_1())
- .when(local, |d| d.child(icon("laptop", 12., theme.text_accent)))
+ .when(local, |d| d.child(kit::color_icon(theme, "laptop", 12., theme.text_accent)))
.child(
div()
.id(SharedString::from(format!("gh-star-{full}")))
@@ -760,7 +760,7 @@ impl Root {
),
)
.when(it.comments > 0, |d| {
- d.child(div().flex().items_center().gap(px(4.)).text_size(px(11.5)).text_color(theme.text_placeholder).child(icon("message-square", 12., theme.text_placeholder)).child(it.comments.to_string()))
+ d.child(div().flex().items_center().gap(px(4.)).text_size(px(11.5)).text_color(theme.text_placeholder).child(kit::color_icon(theme, "message-square", 12., theme.text_placeholder)).child(it.comments.to_string()))
})
.on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::GithubItem(repo.clone(), number), window, cx)))
.on_mouse_down(
@@ -937,7 +937,7 @@ impl Root {
.gap(px(8.))
.text_size(px(11.5))
.text_color(theme.text_placeholder)
- .child(icon("git-branch", 11., theme.text_placeholder))
+ .child(kit::color_icon(theme, "git-branch", 11., theme.text_placeholder))
.child(div().font_family(mono_font()).child(c.branch.clone()))
.child(format!("· {sync}"))
.child(if c.dirty == 0 { "· clean".to_string() } else { format!("· {} changed", c.dirty) }),
@@ -1127,7 +1127,7 @@ fn runs_list(theme: &Theme, runs: &[Run]) -> AnyElement {
format::ago(Some(r.created_at))
))),
)
- .child(icon("external-link", 12., theme.text_placeholder))
+ .child(kit::color_icon(theme, "external-link", 12., theme.text_placeholder))
.on_click(move |_, _, cx| cx.open_url(&url))
.into_any_element()
})
diff --git a/src/ui/kit.rs b/src/ui/kit.rs
index 25d1cc1..224c29f 100644
--- a/src/ui/kit.rs
+++ b/src/ui/kit.rs
@@ -41,6 +41,58 @@ pub mod tiles {
pub const OTHER: (u32, u32) = (0xa7aebb, 0x5f6673);
}
+/// An icon's colors, by what it stands for, so a thing looks the same in
+/// menus, buttons and rows. `None` for small controls (chevrons, close) that
+/// stay quiet.
+pub fn icon_colors(name: &str) -> Option<(u32, u32)> {
+ Some(match name {
+ "terminal" | "square-terminal" => (0x8f95ff, 0x5057e0),
+ "monitor" | "laptop" | "server" | "maximize" | "minimize" | "panel-left" | "panel-right" | "panel-bottom" | "layout-grid" => {
+ (0x6cc8ff, 0x2f7ae4)
+ }
+ "folder" | "folder-open" | "hard-drive" | "box" => (0xffd36b, 0xf09a0b),
+ "file" | "settings" | "gauge" | "cpu" | "memory-stick" | "search" => (0xa3b4d9, 0x5a6d99),
+ "copy" => (0xf0a6fc, 0xb83ad0),
+ "refresh-cw" | "rotate-ccw" | "play" | "check" | "circle-check" => (0x6ee7a0, 0x1c9e55),
+ "plus" => (0xb69cff, 0x7a4ce8),
+ "trash-2" | "circle-x" | "square" => (0xff8080, 0xdc3b33),
+ "power" | "unplug" => (0xff8fb1, 0xd63c6e),
+ "external-link" | "info" | "inbox" | "message-square" | "arrow-up" | "arrow-down" => (0x6cb6ff, 0x2f6fe4),
+ "git-branch" | "git-merge" | "git-pull-request" | "git-pull-request-draft" | "workflow" | "list" | "scroll-text" => {
+ (0xffa95c, 0xea6a2a)
+ }
+ "layers" => tiles::WORKSPACES,
+ "activity" | "clock" => tiles::ACTIVITY,
+ "zap" | "star" | "star-filled" | "circle-alert" | "triangle-alert" => (0xffcc4d, 0xf08c00),
+ "network" | "plug" | "radio" => (0x5ee7f0, 0x0d9cbd),
+ "lock" | "book-open" => tiles::OVERVIEW,
+ "bot" => (0xf472d0, 0xb33fd0),
+ "agent-github" => (0x4a4a50, 0x18181b),
+ _ => return None,
+ })
+}
+
+/// `icon` on its colored tile (see `icon_colors`).
+pub fn color_tile(name: &str, size: f32) -> Div {
+ let (from, to) = icon_colors(name).unwrap_or(tiles::OTHER);
+ tile(name, from, to, size)
+}
+
+/// An icon's own color, readable on this theme: the lighter stop on dark
+/// themes, the deeper one on light themes. Logos keep the text color.
+pub fn tint(theme: &Theme, name: &str) -> Option<Hsla> {
+ if name.starts_with("agent-") {
+ return None;
+ }
+ let (from, to) = icon_colors(name)?;
+ Some(gpui::rgb(if theme.canvas.l < 0.5 { from } else { to }).into())
+}
+
+/// `icon` in its own color, or in `fallback` when it has none.
+pub fn color_icon(theme: &Theme, name: &str, size: f32, fallback: Hsla) -> Svg {
+ icon(name, size, tint(theme, name).unwrap_or(fallback))
+}
+
/// Logo and tile colors for an agent CLI (see fleet::sessions::AGENTS): the
/// product's own mark, white on its brand color.
pub fn agent_look(agent: &str) -> (&'static str, (u32, u32)) {
@@ -50,7 +102,7 @@ pub fn agent_look(agent: &str) -> (&'static str, (u32, u32)) {
"opencode" => ("agent-opencode", (0x34363c, 0x16171a)),
"gemini" => ("agent-gemini", (0x4796e3, 0x9a6fd0)),
"amp" => ("agent-amp", (0xf2704f, 0xc9352b)),
- "shell" => ("terminal", (0xa7aebb, 0x5f6673)),
+ "shell" => ("terminal", (0x8f95ff, 0x5057e0)),
_ => ("bot", (0xa7aebb, 0x5f6673)),
}
}
@@ -179,7 +231,7 @@ pub fn empty_state(theme: &Theme, icon_name: &str, text: impl Into<SharedString>
.text_size(px(12.5))
.text_color(theme.text_placeholder)
// Icon box matches the first line's height so long text wraps under itself.
- .child(div().flex_none().h(px(20.)).flex().items_center().child(icon(icon_name, 14., theme.text_placeholder)))
+ .child(div().flex_none().h(px(20.)).flex().items_center().child(color_icon(theme, icon_name, 14., theme.text_placeholder)))
.child(div().flex_1().min_w(px(0.)).child(text.into()))
}
@@ -312,7 +364,12 @@ impl RenderOnce for Button {
if self.loading {
el = el.child(spinner(ElementId::Name(format!("{}-spin", self.id).into()), 13., fg));
} else if let Some(i) = self.icon {
- el = el.child(icon(i, if icon_only { 15. } else { 13. }, fg));
+ // Icons carry their own color, except on filled and danger buttons.
+ let color = match self.style {
+ ButtonStyle::Outlined | ButtonStyle::Ghost => tint(&theme, i).unwrap_or(fg),
+ ButtonStyle::Primary | ButtonStyle::Danger => fg,
+ };
+ el = el.child(icon(i, if icon_only { 15. } else { 13. }, color));
}
if let Some(label) = self.label {
el = el.child(label);
diff --git a/src/ui/menu.rs b/src/ui/menu.rs
index 2d218c8..7de87d7 100644
--- a/src/ui/menu.rs
+++ b/src/ui/menu.rs
@@ -58,6 +58,8 @@ enum Item {
enum Glyph {
Icon(&'static str),
Agent(&'static str),
+ /// The one picked (a plain check).
+ Selected,
None,
}
@@ -159,14 +161,14 @@ impl Root {
}
for x in &a.accounts {
let label = if x.ok { format!("@{}", x.login) } else { format!("@{} (sign in again)", x.login) };
- let glyph = if using(&x.login, None) { Glyph::Icon("check") } else { Glyph::None };
+ let glyph = if using(&x.login, None) { Glyph::Selected } else { Glyph::None };
items.push(Item::Action { label, glyph, action: Action::UseAccount(x.login.clone(), None), danger: false });
}
if !a.machines.is_empty() {
items.push(Item::Note("Signed in on your machines".into()));
}
for m in &a.machines {
- let glyph = if using(&m.login, Some(&m.machine_id)) { Glyph::Icon("check") } else { Glyph::None };
+ let glyph = if using(&m.login, Some(&m.machine_id)) { Glyph::Selected } else { Glyph::None };
let label = format!("@{} · {}", m.login, m.machine);
items.push(Item::Action { label, glyph, action: Action::UseAccount(m.login.clone(), Some(m.machine_id.clone())), danger: false });
}
@@ -276,11 +278,12 @@ impl Root {
Item::Action { label, glyph, action, danger } => {
let color = if danger { theme.error } else { theme.text };
let glyph = match glyph {
- Glyph::Icon(name) => icon(name, 14., if danger { theme.error } else { theme.text_muted }).into_any_element(),
+ Glyph::Icon(name) => kit::color_tile(name, 18.).into_any_element(),
Glyph::Agent(agent) => {
let (name, (from, to)) = kit::agent_look(agent);
- kit::tile(name, from, to, 16.).into_any_element()
+ kit::tile(name, from, to, 18.).into_any_element()
}
+ Glyph::Selected => icon("check", 14., theme.accent).into_any_element(),
Glyph::None => div().into_any_element(),
};
div()
@@ -296,7 +299,7 @@ impl Root {
.hover(|st| st.bg(theme.element_hover))
.text_size(px(13.))
.text_color(color)
- .child(div().w(px(16.)).flex().justify_center().child(glyph))
+ .child(div().w(px(18.)).flex().justify_center().child(glyph))
.child(label)
.on_click(cx.listener(move |this, _, window, cx| this.run_menu_action(action.clone(), window, cx)))
.into_any_element()
diff --git a/src/ui/mod.rs b/src/ui/mod.rs
index a42925f..1e13d51 100644
--- a/src/ui/mod.rs
+++ b/src/ui/mod.rs
@@ -15,6 +15,7 @@ mod overview;
mod desktop;
mod sessions;
mod settings;
+mod shortcuts;
mod terminal;
mod theme;
mod themes;
diff --git a/src/ui/overview.rs b/src/ui/overview.rs
index 6e168f7..52e55d7 100644
--- a/src/ui/overview.rs
+++ b/src/ui/overview.rs
@@ -111,7 +111,7 @@ impl Root {
.gap(px(6.))
.text_size(px(12.))
.text_color(theme.text_muted)
- .child(icon("gauge", 13., theme.text_accent))
+ .child(kit::color_icon(theme, "gauge", 13., theme.text_accent))
.child("Fleet pulse"),
)
.child(
@@ -344,7 +344,7 @@ impl Root {
.items_center()
.gap(px(5.))
.text_color(theme.text_placeholder)
- .child(icon("clock", 12., theme.text_placeholder))
+ .child(kit::color_icon(theme, "clock", 12., theme.text_placeholder))
.child(p.and_then(|p| p.uptime_sec).map(|u| format!("up {}", format::uptime(u))).unwrap_or_else(|| "—".into())),
)
.child(div().text_color(diag_color).child(diag)),
diff --git a/src/ui/root.rs b/src/ui/root.rs
index 661621a..49e9cb9 100644
--- a/src/ui/root.rs
+++ b/src/ui/root.rs
@@ -32,6 +32,17 @@ actions!(
SyncGitHub,
ShowOverview,
ShowJobs,
+ ShowWorkspaces,
+ ShowGithub,
+ GoToMachine1,
+ GoToMachine2,
+ GoToMachine3,
+ GoToMachine4,
+ GoToMachine5,
+ GoToMachine6,
+ GoToMachine7,
+ GoToMachine8,
+ GoToMachine9,
OpenSettings,
FocusFilter,
GoBack,
@@ -56,20 +67,12 @@ const SIDEBAR_MAX: f32 = 420.;
const PULSE_SAMPLES: usize = 64;
const PULSE_EVERY: Duration = Duration::from_secs(5);
+/// The app's shortcuts, as the user has them (see shortcuts.rs), and the
+/// few that don't change.
pub fn bind_keys(cx: &mut App) {
+ let custom = super::shortcuts::bindings(cx);
+ cx.bind_keys(custom);
cx.bind_keys([
- KeyBinding::new("secondary-r", CheckNow, None),
- KeyBinding::new("secondary-shift-r", SyncGitHub, None),
- KeyBinding::new("secondary-1", ShowOverview, None),
- KeyBinding::new("secondary-2", ShowJobs, None),
- KeyBinding::new("secondary-,", OpenSettings, None),
- KeyBinding::new("secondary-f", FocusFilter, None),
- KeyBinding::new("secondary-[", GoBack, None),
- KeyBinding::new("secondary-]", GoForward, None),
- KeyBinding::new("secondary-j", ToggleActivity, None),
- KeyBinding::new("secondary-b", ToggleSidebar, None),
- KeyBinding::new("secondary-n", AddMachine, None),
- KeyBinding::new("secondary-t", NewSession, None),
KeyBinding::new("secondary-q", Quit, None),
KeyBinding::new("escape", Dismiss, Some(WORKSPACE)),
KeyBinding::new("/", FocusFilter, Some(WORKSPACE)),
@@ -91,7 +94,7 @@ pub fn menus() -> Vec<Menu> {
Menu {
name: "Fleet".into(),
items: vec![
- MenuItem::action("Check Now", CheckNow),
+ MenuItem::action("Check Machines", CheckNow),
MenuItem::action("Sync GitHub", SyncGitHub),
MenuItem::separator(),
MenuItem::action("Add Machine…", AddMachine),
@@ -103,6 +106,8 @@ pub fn menus() -> Vec<Menu> {
items: vec![
MenuItem::action("Overview", ShowOverview),
MenuItem::action("Jobs", ShowJobs),
+ MenuItem::action("Workspaces", ShowWorkspaces),
+ MenuItem::action("GitHub", ShowGithub),
MenuItem::action("Activity", ToggleActivity),
MenuItem::separator(),
MenuItem::action("Back", GoBack),
@@ -199,6 +204,10 @@ pub struct Root {
sidebar_resizing: bool,
/// The sidebar is tucked away (the toolbar's button, ⌘B).
pub(super) sidebar_hidden: bool,
+ /// ⌘ is held down: shortcuts show next to what they do. `keys_soon` shows
+ /// them after a moment, so a quick ⌘C doesn't flash them.
+ pub(super) show_keys: bool,
+ keys_soon: Option<Task<()>>,
/// Terminals attached to agent sessions, kept while the app runs so
/// switching pages doesn't drop them.
pub(super) terminals: HashMap<String, Entity<TerminalView>>,
@@ -339,6 +348,8 @@ impl Root {
sidebar_width: cx.global::<super::theme::Appearance>().sidebar_width.clamp(SIDEBAR_MIN, SIDEBAR_MAX),
sidebar_resizing: false,
sidebar_hidden: cx.global::<super::theme::Appearance>().sidebar_hidden,
+ show_keys: false,
+ keys_soon: None,
terminals: HashMap::new(),
resuming: HashMap::new(),
sessions_requested: HashSet::new(),
@@ -355,7 +366,7 @@ impl Root {
last_notice: None,
refocus: false,
context_menu: None,
- window_active: true,
+ window_active: false,
ws_ui: WorkspaceUi::default(),
clipboard_seen: (super::pasteboard_state().map(|s| s.0).unwrap_or(0), String::new()),
_tasks: vec![updates, ticker, clipboard_out, clipboard_in],
@@ -447,6 +458,12 @@ impl Root {
let engine = self.engine.clone();
self.settings = Some(cx.new(|cx| SettingsPage::new(engine, window, cx)));
}
+ // Leaving Settings while it waits for a shortcut's keys: stop waiting.
+ if self.route != Route::Settings {
+ if let Some(page) = &self.settings {
+ page.update(cx, |p, cx| p.stop_recording(cx));
+ }
+ }
// A desktop streams only while it's shown: its page, or beside a session.
let showing = match &self.route {
Route::Desktop(id) => Some(id.clone()),
@@ -503,7 +520,11 @@ impl Root {
}
"size" | "display" => {}
"session" => self.navigate(Route::Session(arg.into()), window, cx),
- "new-session" => self.show_new_session(Some(arg.to_string()).filter(|a| !a.is_empty()), window, cx),
+ // "new-session:<machine>", or "new-session:<machine>@<folder>".
+ "new-session" => match arg.split_once('@') {
+ Some((m, folder)) => self.show_new_session_prefilled(Some(m.to_string()), Some(folder.to_string()), Default::default(), window, cx),
+ None => self.show_new_session(Some(arg.to_string()).filter(|a| !a.is_empty()), window, cx),
+ },
// An issue or pull request handed to an agent: "fix:owner/name#12", or in a new workspace "fix-ws:...".
"fix" | "fix-ws" => {
if let Some((repo, n)) = arg.split_once('#') {
@@ -529,7 +550,27 @@ impl Root {
};
self.show(Route::Activity, cx);
}
- "settings" => self.navigate(Route::Settings, window, cx),
+ "settings" => {
+ self.navigate(Route::Settings, window, cx);
+ // "settings:keyboard": scrolled down to the shortcuts.
+ if arg == "keyboard" {
+ cx.spawn(async move |this, cx| {
+ cx.background_executor().timer(Duration::from_millis(400)).await;
+ let _ = this.update(cx, |this, cx| {
+ if let Some(p) = &this.settings {
+ p.read(cx).scroll.scroll_to_bottom();
+ }
+ cx.notify();
+ });
+ })
+ .detach();
+ }
+ }
+ // Shortcuts shown, as while ⌘ is held (for screenshots).
+ "keys" => {
+ self.show_keys = true;
+ cx.notify();
+ }
"machine" => self.navigate(Route::Machine(arg.into()), window, cx),
"runner" => self.navigate(Route::Runner(arg.into()), window, cx),
"install" => {
@@ -537,6 +578,7 @@ impl Root {
self.show_install_dialog(arg, window, cx);
}
"add-machine" => self.show_add_machine(window, cx),
+ "menu" => self.open_menu(super::menu::MenuTarget::Machine(arg.into()), gpui::point(px(260.), px(160.)), cx),
"copy" => self.show_copy_files(Some(arg.to_string()).filter(|a| !a.is_empty()), None, window, cx),
"logs" => {
self.navigate(Route::Runner(arg.into()), window, cx);
@@ -958,6 +1000,40 @@ impl Root {
self.navigate(Route::Jobs, window, cx);
}
+ /// The machines in the sidebar's order (⌘1 is the first).
+ pub(super) fn machine_order(s: &Snapshot) -> Vec<&Machine> {
+ s.machines.iter().filter(|m| m.kind == "runner").chain(s.machines.iter().filter(|m| m.kind != "runner")).collect()
+ }
+
+ /// ⌘1…⌘9: the n-th machine in the sidebar (1-based).
+ fn go_to_machine(&mut self, n: usize, window: &mut Window, cx: &mut Context<Self>) {
+ if let Some(id) = Self::machine_order(&self.snapshot).get(n - 1).map(|m| m.id.clone()) {
+ self.navigate(Route::Machine(id), window, cx);
+ }
+ }
+
+ /// ⌘ or ⌃ went down or up: shortcuts show while one is held.
+ fn modifiers_changed(&mut self, e: &gpui::ModifiersChangedEvent, _: &mut Window, cx: &mut Context<Self>) {
+ // ⌘ (the machines and most shortcuts) or ⌃ (the pages).
+ let held = e.modifiers.platform || e.modifiers.control;
+ if !held {
+ self.keys_soon = None;
+ if self.show_keys {
+ self.show_keys = false;
+ cx.notify();
+ }
+ } else if !self.show_keys && self.keys_soon.is_none() {
+ self.keys_soon = Some(cx.spawn(async move |this, cx| {
+ cx.background_executor().timer(Duration::from_millis(350)).await;
+ let _ = this.update(cx, |this, cx| {
+ this.keys_soon = None;
+ this.show_keys = true;
+ cx.notify();
+ });
+ }));
+ }
+ }
+
fn open_settings(&mut self, _: &OpenSettings, window: &mut Window, cx: &mut Context<Self>) {
self.navigate(Route::Settings, window, cx);
}
@@ -1043,13 +1119,14 @@ impl Root {
let mut rows: Vec<AnyElement> = Vec::new();
// Machines with runners first, then the rest; all under one heading.
- let runner_machines: Vec<&Machine> =
- s.machines.iter().filter(|m| m.kind == "runner").chain(s.machines.iter().filter(|m| m.kind != "runner")).collect();
+ let runner_machines: Vec<&Machine> = Self::machine_order(&s);
let unassigned: Vec<&Runner> = s.runners.iter().filter(|r| r.machine_id.is_none() && matches_runner(r)).collect();
rows.push(self.section_header("Machines", runner_machines.len(), true, cx).into_any_element());
let pinned_desktops = cx.global::<super::theme::Appearance>().desktops.clone();
- for m in &runner_machines {
+ for (n, m) in runner_machines.iter().enumerate() {
+ // While ⌘ is held: the shortcut that goes to it.
+ let hint = if self.show_keys { super::shortcuts::machine_keys(cx, n + 1).map(|k| super::shortcuts::label(&k)) } else { None };
let runners: Vec<&Runner> = m.runner_ids.iter().filter_map(|id| s.runners.iter().find(|r| &r.id == id)).collect();
let machine_match = q.is_empty() || m.name.to_lowercase().contains(&q);
let visible: Vec<&Runner> = runners.iter().copied().filter(|r| machine_match || matches_runner(r)).collect();
@@ -1065,7 +1142,7 @@ impl Root {
// Collapsed: the machine carries its sessions' unread dot.
let alert = (!open).then(|| sessions.iter().find_map(|x| x.attention.clone().map(|k| (k, x.exit_code)))).flatten();
let has_desktop = pinned_desktops.contains(&m.id);
- rows.push(self.machine_row(&theme, m, open, !sessions.is_empty() || has_desktop, alert, selected_machine.as_deref() == Some(&m.id), cx).into_any_element());
+ rows.push(self.machine_row(&theme, m, open, !sessions.is_empty() || has_desktop, alert, selected_machine.as_deref() == Some(&m.id), hint, cx).into_any_element());
if open {
// Agent sessions first: they're what you come back to.
for x in sessions {
@@ -1124,10 +1201,10 @@ impl Root {
.gap(px(2.))
.px(px(10.))
.pt(px(6.))
- .child(self.nav_item("nav-overview", "gauge", kit::tiles::OVERVIEW, "Overview", None, Route::Overview, cx))
- .child(self.nav_item("nav-jobs", "workflow", kit::tiles::JOBS, "Jobs", Some(s.counts.queued + s.counts.running), Route::Jobs, cx))
- .child(self.nav_item("nav-workspaces", "terminal", kit::tiles::WORKSPACES, "Workspaces", Some(s.workspaces.len()), Route::Workspaces, cx))
- .child(self.nav_item("nav-github", "agent-github", super::github::TILE, "GitHub", self.gh.waiting(), Route::Github, cx))
+ .child(self.nav_item("nav-overview", "gauge", kit::tiles::OVERVIEW, "Overview", None, Route::Overview, "overview", cx))
+ .child(self.nav_item("nav-jobs", "workflow", kit::tiles::JOBS, "Jobs", Some(s.counts.queued + s.counts.running), Route::Jobs, "jobs", cx))
+ .child(self.nav_item("nav-workspaces", "terminal", kit::tiles::WORKSPACES, "Workspaces", Some(s.workspaces.len()), Route::Workspaces, "workspaces", cx))
+ .child(self.nav_item("nav-github", "agent-github", super::github::TILE, "GitHub", self.gh.waiting(), Route::Github, "github", cx))
.child(self.activity_nav(&theme, running_ops, cx)),
)
.child(
@@ -1177,8 +1254,22 @@ impl Root {
}
#[allow(clippy::too_many_arguments)]
- fn nav_item(&self, id: &'static str, icon_name: &'static str, colors: (u32, u32), text: &'static str, count: Option<usize>, route: Route, cx: &mut Context<Self>) -> impl IntoElement {
+ #[allow(clippy::too_many_arguments)]
+ fn nav_item(
+ &self,
+ id: &'static str,
+ icon_name: &'static str,
+ colors: (u32, u32),
+ text: &'static str,
+ count: Option<usize>,
+ route: Route,
+ shortcut: &'static str,
+ cx: &mut Context<Self>,
+ ) -> impl IntoElement {
let theme = cx.theme();
+ // While ⌘ is held the count gives way to the shortcut.
+ let keys = self.show_keys.then(|| super::shortcuts::label_for(cx, shortcut)).filter(|k| !k.is_empty());
+ let count = count.filter(|_| keys.is_none());
// A workspace page keeps "Workspaces" highlighted.
let active = self.route == route
|| (route == Route::Workspaces && matches!(self.route, Route::Workspace(_)))
@@ -1212,6 +1303,7 @@ impl Root {
.text_color(theme.text_muted)
.child(n.to_string())
}))
+ .children(keys.map(|k| kit::kbd(&theme, k)))
.on_click(cx.listener(move |this, _, window, cx| this.navigate(route.clone(), window, cx)))
}
@@ -1234,7 +1326,10 @@ impl Root {
.child("Activity")
.child(div().flex_1())
.when(running > 0, |d| d.child(spinner("nav-activity-spin", 13., theme.accent)))
- .when(running == 0, |d| d.child(kit::kbd(theme, "⌘J")))
+ .when(running == 0 && self.show_keys, |d| {
+ let keys = super::shortcuts::label_for(cx, "activity");
+ d.when(!keys.is_empty(), |d| d.child(kit::kbd(theme, keys)))
+ })
.on_click(cx.listener(|this, _, _, cx| this.show(Route::Activity, cx)))
}
@@ -1257,7 +1352,7 @@ impl Root {
.when(with_add, |d| {
d.child(
Button::icon_only("sidebar-add-machine", "plus")
- .tooltip("Add machine ⌘N")
+ .tooltip(tip("Add machine", &super::shortcuts::label_for(cx, "add-machine")))
.on_click(cx.listener(|this, _, window, cx| this.show_add_machine(window, cx))),
)
})
@@ -1272,11 +1367,13 @@ impl Root {
has_sessions: bool,
alert: Option<(String, Option<i32>)>,
selected: bool,
+ hint: Option<String>,
cx: &mut Context<Self>,
) -> impl IntoElement {
let id = m.id.clone();
let toggle_id = m.id.clone();
- let has_runners = !m.runner_ids.is_empty();
+ // The shortcut takes the place of the runner count and the toggle.
+ let (has_runners, has_sessions) = if hint.is_some() { (false, false) } else { (!m.runner_ids.is_empty(), has_sessions) };
let (tile_from, tile_to) = format::machine_tile(m);
let (subtitle, tone) = format::machine_subtitle(m);
// Runner count: "5/7" while some are working, else the total.
@@ -1292,7 +1389,7 @@ impl Root {
// whose width is known before layout. Row chrome: margins, padding, tile, gaps,
// and the count pill (padding, dot, gap, ~6.7px per mono character).
let pill_w = 12. + 6. + 4. + count.len() as f32 * 6.7;
- let trailing = if has_runners { 10. + pill_w.max(22.) } else if has_sessions { 32. } else { 0. } + if alert.is_some() { 18. } else { 0. };
+ let trailing = if hint.is_some() { 40. } else if has_runners { 10. + pill_w.max(22.) } else if has_sessions { 32. } else { 0. } + if alert.is_some() { 18. } else { 0. };
let text_w = (self.sidebar_width - 20. - 16. - 30. - 10. - trailing).max(40.);
div()
.id(SharedString::from(format!("side-m-{}", m.id)))
@@ -1360,6 +1457,7 @@ impl Root {
),
)
.children(alert.map(|(kind, code)| super::sessions::attention_dot(theme, &kind, code)))
+ .children(hint.map(|k| kit::kbd(theme, k)))
.when(has_runners || has_sessions, |d| {
d.child(
div()
@@ -1629,7 +1727,7 @@ impl Root {
.text_color(if active { theme.text } else { theme.text_muted })
.when(active, |d| d.bg(theme.element_selected))
.when(!active, |d| d.hover(|st| st.bg(theme.ghost_hover).text_color(theme.text)))
- .child(icon(icon_name, 13., if active { theme.text_accent } else { theme.text_placeholder }))
+ .child(kit::color_icon(theme, icon_name, 13., theme.text_placeholder))
.child(label)
.on_click(cx.listener(move |this, _, window, cx| this.navigate(route.clone(), window, cx)))
};
@@ -1710,7 +1808,7 @@ impl Root {
.on_mouse_down(gpui::MouseButton::Left, |e: &gpui::MouseDownEvent, window, _| super::title_bar_press(e, window))
.child(
Button::icon_only("toggle-sidebar", "panel-left")
- .tooltip(if self.sidebar_hidden { "Show sidebar ⌘B" } else { "Hide sidebar ⌘B" })
+ .tooltip(tip(if self.sidebar_hidden { "Show sidebar" } else { "Hide sidebar" }, &super::shortcuts::label_for(cx, "sidebar")))
.on_click(cx.listener(|this, _, _, cx| this.toggle_sidebar(cx))),
)
.child(
@@ -1719,13 +1817,13 @@ impl Root {
.gap(px(2.))
.child(
Button::icon_only("back", "arrow-left")
- .tooltip("Back ⌘[")
+ .tooltip(tip("Back", &super::shortcuts::label_for(cx, "back")))
.disabled(self.back.is_empty())
.on_click(cx.listener(|this, _, window, cx| this.go_back(&GoBack, window, cx))),
)
.child(
Button::icon_only("forward", "arrow-right")
- .tooltip("Forward ⌘]")
+ .tooltip(tip("Forward", &super::shortcuts::label_for(cx, "forward")))
.disabled(self.forward.is_empty())
.on_click(cx.listener(|this, _, window, cx| this.go_forward(&GoForward, window, cx))),
),
@@ -1743,19 +1841,30 @@ impl Root {
.child(div().truncate().font_weight(FontWeight::SEMIBOLD).text_color(theme.text).child(title)),
)
.child(div().flex_1())
- .child(div().text_size(px(12.)).text_color(theme.text_placeholder).child(format!("Updated {}", format::ago(s.updated_at))))
- .child(
- Button::icon_only("sync", "refresh-cw")
- .loading(s.github.syncing && s.github.configured)
- .tooltip("Sync GitHub ⇧⌘R")
- .on_click(cx.listener(|this, _, _, _| this.engine.trigger_sync())),
- )
+ // Each says what it refreshes; when it last did is in its tooltip.
+ .when(s.github.configured, |d| {
+ d.child(
+ Button::new("sync", if s.github.syncing { "Syncing" } else { "Sync GitHub" })
+ .icon("agent-github")
+ .loading(s.github.syncing)
+ .map(|b| match super::shortcuts::label_for(cx, "sync") {
+ k if self.show_keys && !k.is_empty() => b.key_hint(k),
+ _ => b,
+ })
+ .tooltip(tip(&format!("Synced {}", format::ago(s.github.last_sync_at)), &super::shortcuts::label_for(cx, "sync")))
+ .on_click(cx.listener(|this, _, _, _| this.engine.trigger_sync())),
+ )
+ })
.child(
- Button::new("check-now", if s.check.running { "Checking" } else { "Check now" })
+ Button::new("check-now", if s.check.running { "Checking" } else { "Check machines" })
.style(ButtonStyle::Primary)
- .icon("refresh-cw")
+ .icon("server")
.loading(s.check.running)
- .key_hint("⌘R")
+ .map(|b| match super::shortcuts::label_for(cx, "check") {
+ k if self.show_keys && !k.is_empty() => b.key_hint(k),
+ _ => b,
+ })
+ .tooltip(tip(&format!("Checked {}", format::ago(s.check.finished_at)), &super::shortcuts::label_for(cx, "check")))
.on_click(cx.listener(|this, _, _, _| this.engine.trigger_check(None))),
)
}
@@ -1950,7 +2059,12 @@ impl Render for Root {
self.finish_split_resize(cx);
}
self.content_width = f32::from(window.viewport_size().width) - if self.sidebar_hidden { 0. } else { self.sidebar_width } - 56.;
- self.window_active = window.is_window_active();
+ // Switching away with ⌘ held (⌘Tab): its release never arrives here.
+ let was_active = std::mem::replace(&mut self.window_active, window.is_window_active());
+ if was_active && !self.window_active {
+ self.show_keys = false;
+ self.keys_soon = None;
+ }
if std::mem::take(&mut self.refocus) {
window.focus(&self.focus);
}
@@ -1979,6 +2093,18 @@ impl Render for Root {
.on_action(cx.listener(Self::sync_github))
.on_action(cx.listener(Self::show_overview))
.on_action(cx.listener(Self::show_jobs))
+ .on_action(cx.listener(|this, _: &ShowWorkspaces, window, cx| this.navigate(Route::Workspaces, window, cx)))
+ .on_action(cx.listener(|this, _: &ShowGithub, window, cx| this.navigate(Route::Github, window, cx)))
+ .on_action(cx.listener(|this, _: &GoToMachine1, window, cx| this.go_to_machine(1, window, cx)))
+ .on_action(cx.listener(|this, _: &GoToMachine2, window, cx| this.go_to_machine(2, window, cx)))
+ .on_action(cx.listener(|this, _: &GoToMachine3, window, cx| this.go_to_machine(3, window, cx)))
+ .on_action(cx.listener(|this, _: &GoToMachine4, window, cx| this.go_to_machine(4, window, cx)))
+ .on_action(cx.listener(|this, _: &GoToMachine5, window, cx| this.go_to_machine(5, window, cx)))
+ .on_action(cx.listener(|this, _: &GoToMachine6, window, cx| this.go_to_machine(6, window, cx)))
+ .on_action(cx.listener(|this, _: &GoToMachine7, window, cx| this.go_to_machine(7, window, cx)))
+ .on_action(cx.listener(|this, _: &GoToMachine8, window, cx| this.go_to_machine(8, window, cx)))
+ .on_action(cx.listener(|this, _: &GoToMachine9, window, cx| this.go_to_machine(9, window, cx)))
+ .on_modifiers_changed(cx.listener(Self::modifiers_changed))
.on_action(cx.listener(Self::open_settings))
.on_action(cx.listener(Self::focus_filter))
.on_action(cx.listener(Self::go_back))
@@ -2101,3 +2227,8 @@ fn route_title(s: &Snapshot, route: &Route) -> (Option<&'static str>, String) {
fn ellipsize(s: &str, max: usize) -> String {
if s.chars().count() <= max { s.to_string() } else { format!("{}…", s.chars().take(max - 1).collect::<String>()) }
}
+
+/// A tooltip with its shortcut, when it has one: "Back ⌘[".
+fn tip(text: &str, keys: &str) -> String {
+ if keys.is_empty() { text.to_string() } else { format!("{text} {keys}") }
+}
diff --git a/src/ui/sessions.rs b/src/ui/sessions.rs
index 457d333..753352b 100644
--- a/src/ui/sessions.rs
+++ b/src/ui/sessions.rs
@@ -447,7 +447,7 @@ impl Root {
.p(px(20.))
.max_w(px(420.))
.bg(theme.elevated)
- .child(icon(if format::is_just_offline(&m) { "power" } else { "unplug" }, 22., theme.text_muted))
+ .child(kit::color_tile(if format::is_just_offline(&m) { "power" } else { "unplug" }, 36.))
.child(div().text_size(px(14.)).font_weight(FontWeight::SEMIBOLD).child(title))
.child(div().text_size(px(12.5)).text_color(theme.text_muted).text_center().child("Shut down: this session ended. Asleep: it's still there."))
.child(
@@ -487,7 +487,7 @@ impl Root {
.gap(px(10.))
.p(px(20.))
.bg(theme.elevated)
- .child(icon("unplug", 22., theme.text_muted))
+ .child(kit::color_tile("unplug", 36.))
.child(div().text_size(px(14.)).font_weight(FontWeight::SEMIBOLD).child("Disconnected"))
.child(
div()
@@ -655,7 +655,7 @@ impl Root {
.flex_row()
.items_center()
.gap(px(12.))
- .child(icon("square-terminal", 16., theme.text_placeholder))
+ .child(kit::color_tile("square-terminal", 28.))
.child(div().flex_1().min_w(px(0.)).text_size(px(12.5)).text_color(theme.text_muted).child(text))
.child(
Button::new("m-session-empty", "New session")
@@ -811,7 +811,7 @@ impl Root {
.gap(px(12.))
.px(px(14.))
.py(px(10.))
- .child(icon(glyph, 15., theme.text_muted))
+ .child(kit::color_tile(glyph, 22.))
.child(div().w(px(130.)).flex_none().text_size(px(12.5)).text_color(theme.text_muted).child(name))
.child(
div()
@@ -901,7 +901,7 @@ impl Root {
}
let mid = m.id.clone();
let changing = self.conn_changing.contains(&m.id);
- let (glyph, color, value, detail, direct) = match self.machine_conn.get(&m.id) {
+ let (glyph, value, detail, direct) = match self.machine_conn.get(&m.id) {
Some(Load::Ready(c)) => {
let speed = c.latency_ms.map(|ms| format!(" · {ms} ms")).unwrap_or_default();
// Through Tailscale: straight to the machine, or through its relay.
@@ -915,23 +915,21 @@ impl Root {
match c.via.as_str() {
"direct" => (
"zap",
- if c.note.is_some() { theme.warning } else { theme.success },
format!("Direct{net}{speed}"),
c.note.clone().unwrap_or_else(|| format!("QUIC to {}{at}, no ssh in between.", c.address.clone().unwrap_or_default())),
true,
),
"ssh" => (
"network",
- if c.direct { theme.warning } else { theme.text_muted },
format!("Over ssh{net}{speed}"),
c.note.clone().unwrap_or_else(|| "One ssh connection, kept open.".into()),
c.direct,
),
- _ => ("unplug", theme.text_placeholder, "Not connected".into(), c.note.clone().unwrap_or_else(|| "The agent there didn't answer.".into()), c.direct),
+ _ => ("unplug", "Not connected".into(), c.note.clone().unwrap_or_else(|| "The agent there didn't answer.".into()), c.direct),
}
}
- Some(Load::Failed(e)) => ("unplug", theme.error, "Not connected".into(), e.clone(), false),
- _ => ("network", theme.text_placeholder, "Checking…".into(), String::new(), false),
+ Some(Load::Failed(e)) => ("unplug", "Not connected".into(), e.clone(), false),
+ _ => ("network", "Checking…".into(), String::new(), false),
};
// Not on the tailnet (while this computer is): offer to set it up there.
let offer_tailscale = m.platform.starts_with("linux")
@@ -978,7 +976,7 @@ impl Root {
.gap(px(12.))
.px(px(14.))
.py(px(12.))
- .child(icon(glyph, 16., color))
+ .child(kit::color_tile(glyph, 28.))
.child(
div()
.flex()
@@ -1275,7 +1273,7 @@ fn ended(theme: &Theme, id: &str, cx: &mut Context<Root>) -> AnyElement {
.justify_center()
.gap(px(10.))
.pb(px(80.))
- .child(div().size(px(44.)).rounded_full().bg(theme.element).flex().items_center().justify_center().child(icon("square-terminal", 20., theme.text_muted)))
+ .child(kit::color_tile("square-terminal", 44.))
.child(div().text_size(px(15.)).font_weight(FontWeight::SEMIBOLD).text_color(theme.text).child("This session has ended"))
.child(div().text_size(px(12.5)).text_color(theme.text_muted).child(id.to_string()))
.child(
diff --git a/src/ui/settings.rs b/src/ui/settings.rs
index 27a37ea..84f3bc8 100644
--- a/src/ui/settings.rs
+++ b/src/ui/settings.rs
@@ -27,6 +27,12 @@ pub struct SettingsPage {
/// The login in use: its permissions and organizations (to offer them).
access: Option<crate::api::AccountsOut>,
pub scroll: gpui::ScrollHandle,
+ /// A shortcut waiting for its new keys, and what catches them before
+ /// they run anything.
+ recording: Option<&'static str>,
+ catch_keys: Option<Subscription>,
+ /// What the last change did ("Removed from Jobs"), or why it didn't happen.
+ shortcut_note: Option<String>,
_tasks: Vec<Task<()>>,
_subscriptions: Vec<Subscription>,
}
@@ -85,6 +91,9 @@ impl SettingsPage {
saved_at: None,
access: None,
scroll: gpui::ScrollHandle::new(),
+ recording: None,
+ catch_keys: None,
+ shortcut_note: None,
_tasks: vec![updates],
_subscriptions: subs,
};
@@ -277,7 +286,7 @@ impl SettingsPage {
.flex()
.items_center()
.gap(px(10.))
- .child(icon(icon_name, 14., theme.text_muted))
+ .child(kit::color_tile(icon_name, 20.))
.child(div().font_family(mono_font()).text_size(px(13.)).child(name.clone()))
.child(div().flex_1().truncate().text_size(px(12.)).text_color(color).child(text))
.child(
@@ -340,7 +349,7 @@ impl SettingsPage {
.hover(|st| st.bg(theme.element_hover))
.font_family(mono_font())
.text_size(px(12.))
- .child(icon("plus", 12., theme.text_muted))
+ .child(kit::color_icon(theme, "plus", 12., theme.text_muted))
.child(name.to_string())
.on_click(cx.listener(move |this, _, _, cx| this.add_scope(Some(scope.clone()), cx)))
.into_any_element()
@@ -594,7 +603,7 @@ impl SettingsPage {
.text_color(if selected { theme.text } else { theme.text_muted })
.when(selected, |d| d.bg(theme.surface).border_1().border_color(theme.border).shadow_sm())
.when(!selected, |d| d.hover(|st| st.text_color(theme.text)))
- .child(icon(icon_name, 13., if selected { theme.text_accent } else { theme.text_placeholder }))
+ .child(kit::color_icon(theme, icon_name, 13., if selected { theme.text_accent } else { theme.text_placeholder }))
.child(label)
.on_click(cx.listener(move |_, _, window, cx| theme_mod::update_appearance(window, cx, |a, _| a.mode = mode)))
};
@@ -782,19 +791,6 @@ impl Render for SettingsPage {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let terminal_font = super::terminal::font_family(window);
- let shortcuts = [
- ("⌘R", "Check now"),
- ("⇧⌘R", "Sync GitHub"),
- ("⌘N", "Add machine"),
- ("⌘1 / ⌘2", "Overview / Jobs"),
- ("⌘F or /", "Filter the fleet"),
- ("⌘J", "Toggle activity"),
- ("⌘B", "Hide or show the sidebar"),
- ("⌘[ / ⌘]", "Back / forward"),
- ("⌘,", "Settings"),
- ("⌘T", "New session"),
- ("⌘+ / ⌘− / ⌘0", "Terminal text size (in a terminal)"),
- ];
div()
.id("settings-page")
.size_full()
@@ -817,27 +813,223 @@ impl Render for SettingsPage {
.child(self.terminal_section(&theme, terminal_font, cx))
.child(self.checks_section(&theme, cx))
.child(self.inventory_section(&theme))
- .child(
- div()
- .flex()
- .flex_col()
- .gap(px(10.))
- .child(section_title(&theme, "Keyboard", None))
- .child(card(&theme).px(px(14.)).py(px(6.)).children(shortcuts.iter().map(|(k, what)| {
- div()
- .flex()
- .items_center()
- .justify_between()
- .py(px(5.))
- .text_size(px(12.5))
- .child(div().text_color(theme.text_muted).child(*what))
- .child(kit::kbd(&theme, *k))
- }))),
- ),
+ .child(self.keyboard_section(&theme, cx)),
)
}
}
+impl SettingsPage {
+ /// The shortcuts, each one changeable: click its keys, then press new ones.
+ fn keyboard_section(&self, theme: &Theme, cx: &mut Context<Self>) -> impl IntoElement {
+ use super::shortcuts::{self, ALL};
+ let any_changed = !cx.global::<theme_mod::Appearance>().shortcuts.is_empty();
+ let row = |label: SharedString| div().flex().items_center().gap(px(8.)).min_h(px(34.)).text_size(px(12.5)).child(div().flex_1().text_color(theme.text_muted).child(label));
+
+ // ⌘1…⌘9: one modifier for all nine.
+ let chosen = shortcuts::machine_modifier(cx);
+ let options: Vec<AnyElement> = shortcuts::machine_modifiers()
+ .iter()
+ .map(|(value, shown)| {
+ let on = chosen == *value;
+ div()
+ .id(SharedString::from(format!("sc-m-{shown}")))
+ .h(px(24.))
+ .min_w(px(36.))
+ .px(px(8.))
+ .flex()
+ .items_center()
+ .justify_center()
+ .rounded(px(5.))
+ .border_1()
+ .border_color(if on { theme.accent } else { theme.border_variant })
+ .bg(if on { theme.accent.opacity(0.12) } else { theme.element })
+ .cursor_pointer()
+ .font_family(mono_font())
+ .text_size(px(12.))
+ .text_color(if on { theme.text } else { theme.text_muted })
+ .child(*shown)
+ .on_click(cx.listener(move |this, _, _, cx| this.set_machine_keys(value, cx)))
+ .into_any_element()
+ })
+ .collect();
+ let machines_label = match shortcuts::machine_keys(cx, 1) {
+ Some(k) => format!("Go to machine 1–9 ({} …)", shortcuts::label(&k)),
+ None => "Go to machine 1–9".to_string(),
+ };
+ let machines = row(machines_label.into()).child(div().flex().gap(px(4.)).children(options));
+
+ let rows: Vec<AnyElement> = ALL
+ .iter()
+ .enumerate()
+ .map(|(i, sc)| {
+ let recording = self.recording == Some(sc.id);
+ let keys = shortcuts::label_for(cx, sc.id);
+ let id = sc.id;
+ let chip = div()
+ .id(("sc-keys", i))
+ .h(px(24.))
+ .min_w(px(72.))
+ .px(px(8.))
+ .flex()
+ .items_center()
+ .justify_center()
+ .rounded(px(5.))
+ .border_1()
+ .cursor_pointer()
+ .font_family(mono_font())
+ .text_size(px(12.))
+ .map(|d| match (recording, keys.is_empty()) {
+ (true, _) => d.border_color(theme.accent).bg(theme.accent.opacity(0.12)).text_color(theme.text_accent).child("Press keys…"),
+ (false, true) => d.border_color(theme.border_variant).bg(theme.element).text_color(theme.text_placeholder).child("None"),
+ (false, false) => d.border_color(theme.border_variant).bg(theme.element).text_color(theme.text).child(keys.clone()),
+ })
+ .on_click(cx.listener(move |this, _, _, cx| this.record(id, cx)));
+ let reset = if shortcuts::changed(cx, sc.id) {
+ Button::icon_only(("sc-reset", i), "rotate-ccw").tooltip("Back to the default").on_click(cx.listener(move |this, _, _, cx| this.reset_shortcut(id, cx))).into_any_element()
+ } else {
+ div().w(px(26.)).into_any_element()
+ };
+ row(sc.label.into()).child(chip).child(reset).into_any_element()
+ })
+ .collect();
+ let fixed = row("Terminal text size".into()).child(kit::kbd(theme, "⌘+ ⌘− ⌘0")).child(div().w(px(26.)));
+
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(10.))
+ .child(
+ div()
+ .flex()
+ .items_center()
+ .child(section_title(theme, "Keyboard", None))
+ .child(div().flex_1())
+ .when(any_changed, |d| {
+ d.child(Button::new("sc-reset-all", "Reset all").style(ButtonStyle::Ghost).on_click(cx.listener(|this, _, _, cx| this.reset_all_shortcuts(cx))))
+ }),
+ )
+ .child(div().text_size(px(12.5)).text_color(theme.text_placeholder).child(if cfg!(target_os = "macos") { "Hold ⌘ or ⌃ to see them anywhere." } else { "Hold Ctrl to see them anywhere." }))
+ .children(self.shortcut_note.clone().map(|n| note(theme, "info", theme.info, n)))
+ .child(
+ card(theme)
+ .px(px(14.))
+ .py(px(4.))
+ .child(machines)
+ .child(div().h(px(1.)).my(px(4.)).bg(theme.border_variant))
+ .children(rows)
+ .child(fixed),
+ )
+ }
+
+ /// Waits for the keys of shortcut `id` (or stops waiting, on a second click).
+ fn record(&mut self, id: &'static str, cx: &mut Context<Self>) {
+ if self.recording == Some(id) {
+ self.stop_recording(cx);
+ return;
+ }
+ self.recording = Some(id);
+ self.shortcut_note = None;
+ if self.catch_keys.is_none() {
+ // Before shortcuts run: a key pressed here is recorded, not done.
+ let page = cx.entity().downgrade();
+ self.catch_keys = Some(cx.intercept_keystrokes(move |e, _, cx| {
+ let Some(page) = page.upgrade() else { return };
+ if page.read(cx).recording.is_none() {
+ return;
+ }
+ cx.stop_propagation();
+ let k = e.keystroke.clone();
+ page.update(cx, |p, cx| p.pressed(&k, cx));
+ }));
+ }
+ cx.notify();
+ }
+
+ pub(super) fn stop_recording(&mut self, cx: &mut Context<Self>) {
+ if self.recording.take().is_some() {
+ cx.notify();
+ }
+ }
+
+ /// A key pressed while recording: Esc cancels, ⌫ clears, anything with
+ /// ⌘, ⌃ or ⌥ becomes the shortcut (taken from whatever had it).
+ fn pressed(&mut self, k: &gpui::Keystroke, cx: &mut Context<Self>) {
+ use super::shortcuts::{self, MACHINES};
+ let Some(id) = self.recording else { return };
+ let m = &k.modifiers;
+ let plain = !(m.platform || m.control || m.alt || m.shift);
+ match k.key.as_str() {
+ "escape" if plain => self.recording = None,
+ "backspace" | "delete" if plain => {
+ shortcuts::set(cx, id, "");
+ shortcuts::apply(cx);
+ self.recording = None;
+ }
+ _ => match shortcuts::from_press(k) {
+ None => self.shortcut_note = Some(if cfg!(target_os = "macos") { "Add ⌘, ⌃ or ⌥." } else { "Add Ctrl or Alt." }.into()),
+ Some(keys) => match shortcuts::used_by(cx, &keys, id) {
+ Some((MACHINES, what)) => self.shortcut_note = Some(format!("{} goes to {what}.", shortcuts::label(&keys))),
+ taken => {
+ if let Some((other, what)) = taken {
+ shortcuts::set(cx, other, "");
+ self.shortcut_note = Some(format!("Taken from {what}."));
+ }
+ shortcuts::set(cx, id, &keys);
+ shortcuts::apply(cx);
+ self.recording = None;
+ }
+ },
+ },
+ }
+ cx.notify();
+ }
+
+ fn reset_shortcut(&mut self, id: &'static str, cx: &mut Context<Self>) {
+ use super::shortcuts::{self, ALL, MACHINES};
+ let default = ALL.iter().find(|s| s.id == id).map(|s| s.default).unwrap_or_default();
+ self.shortcut_note = None;
+ match shortcuts::used_by(cx, default, id) {
+ Some((MACHINES, what)) => {
+ self.shortcut_note = Some(format!("{} goes to {what}.", shortcuts::label(default)));
+ cx.notify();
+ return;
+ }
+ Some((other, what)) => {
+ shortcuts::set(cx, other, "");
+ self.shortcut_note = Some(format!("Taken from {what}."));
+ }
+ None => {}
+ }
+ shortcuts::set(cx, id, default);
+ shortcuts::apply(cx);
+ cx.notify();
+ }
+
+ fn reset_all_shortcuts(&mut self, cx: &mut Context<Self>) {
+ theme_mod::remember(cx, |a| a.shortcuts.clear());
+ super::shortcuts::apply(cx);
+ self.recording = None;
+ self.shortcut_note = None;
+ cx.notify();
+ }
+
+ /// The modifier for ⌘1…⌘9; shortcuts on those keys give way.
+ fn set_machine_keys(&mut self, modifier: &'static str, cx: &mut Context<Self>) {
+ use super::shortcuts::{self, MACHINES};
+ shortcuts::set(cx, MACHINES, modifier);
+ let mut freed = Vec::new();
+ for n in 1..=9 {
+ if let Some((other, what)) = shortcuts::machine_keys(cx, n).and_then(|k| shortcuts::used_by(cx, &k, MACHINES)) {
+ shortcuts::set(cx, other, "");
+ freed.push(what);
+ }
+ }
+ shortcuts::apply(cx);
+ self.shortcut_note = (!freed.is_empty()).then(|| format!("Removed from {}.", freed.join(", ")));
+ cx.notify();
+ }
+}
+
fn note(_theme: &Theme, icon_name: &'static str, color: gpui::Hsla, text: impl Into<SharedString>) -> impl IntoElement {
div().flex().items_center().gap(px(8.)).text_size(px(12.5)).child(icon(icon_name, 14., color)).child(text.into())
}
diff --git a/src/ui/shortcuts.rs b/src/ui/shortcuts.rs
new file mode 100644
index 0000000..52449ea
--- /dev/null
+++ b/src/ui/shortcuts.rs
@@ -0,0 +1,261 @@
+//! The app's keyboard shortcuts: what each one does, its keys by default, and
+//! the user's own keys from Settings (saved in ui.json). ⌘1…⌘9 go to the
+//! machines in the sidebar; holding ⌘ shows every shortcut where it applies.
+
+use gpui::{App, KeyBinding, Keystroke};
+
+use super::root::{
+ AddMachine, CheckNow, FocusFilter, GoBack, GoForward, GoToMachine1, GoToMachine2, GoToMachine3, GoToMachine4, GoToMachine5, GoToMachine6,
+ GoToMachine7, GoToMachine8, GoToMachine9, NewSession, OpenSettings, ShowGithub, ShowJobs, ShowOverview, ShowWorkspaces, SyncGitHub,
+ ToggleActivity, ToggleSidebar,
+};
+use super::theme::Appearance;
+
+/// One shortcut the user can change.
+pub struct Shortcut {
+ pub id: &'static str,
+ pub label: &'static str,
+ /// GPUI key syntax ("secondary-r": ⌘R on a Mac, Ctrl+R elsewhere).
+ pub default: &'static str,
+ bind: fn(&str) -> KeyBinding,
+}
+
+macro_rules! shortcut {
+ ($id:literal, $label:literal, $default:expr, $action:expr) => {
+ Shortcut { id: $id, label: $label, default: $default, bind: |keys| KeyBinding::new(keys, $action, None) }
+ };
+}
+
+/// The pages: ⌃1…⌃4 on a Mac (⌘1…⌘9 are the machines); Alt elsewhere, where
+/// Ctrl is what ⌘ is on a Mac.
+const fn page(mac: &'static str, other: &'static str) -> &'static str {
+ if cfg!(target_os = "macos") { mac } else { other }
+}
+
+/// In the order Settings lists them.
+pub const ALL: &[Shortcut] = &[
+ shortcut!("overview", "Overview", page("ctrl-1", "alt-1"), ShowOverview),
+ shortcut!("jobs", "Jobs", page("ctrl-2", "alt-2"), ShowJobs),
+ shortcut!("workspaces", "Workspaces", page("ctrl-3", "alt-3"), ShowWorkspaces),
+ shortcut!("github", "GitHub", page("ctrl-4", "alt-4"), ShowGithub),
+ shortcut!("activity", "Activity", "secondary-j", ToggleActivity),
+ shortcut!("settings", "Settings", "secondary-,", OpenSettings),
+ shortcut!("check", "Check machines", "secondary-r", CheckNow),
+ shortcut!("sync", "Sync GitHub", "secondary-shift-r", SyncGitHub),
+ shortcut!("add-machine", "Add machine", "secondary-n", AddMachine),
+ shortcut!("new-session", "New session", "secondary-t", NewSession),
+ shortcut!("filter", "Search the fleet", "secondary-f", FocusFilter),
+ shortcut!("sidebar", "Hide or show the sidebar", "secondary-b", ToggleSidebar),
+ shortcut!("back", "Back", "secondary-[", GoBack),
+ shortcut!("forward", "Forward", "secondary-]", GoForward),
+];
+
+/// The machines' shortcuts: this modifier with 1…9 (in Appearance under this id).
+pub const MACHINES: &str = "machines";
+const MACHINES_DEFAULT: &str = "secondary";
+
+/// Choices for the machines' modifier: (keys, how Settings shows them).
+pub fn machine_modifiers() -> &'static [(&'static str, &'static str)] {
+ if cfg!(target_os = "macos") {
+ &[("cmd", "⌘"), ("ctrl", "⌃"), ("alt-cmd", "⌥⌘"), ("", "Off")]
+ } else {
+ &[("ctrl", "Ctrl"), ("alt", "Alt"), ("", "Off")]
+ }
+}
+
+/// The keys for a shortcut now ("" when it has none).
+pub fn keys(cx: &App, id: &str) -> String {
+ let a = cx.global::<Appearance>();
+ match a.shortcuts.get(id) {
+ Some(k) => k.clone(),
+ None if id == MACHINES => MACHINES_DEFAULT.into(),
+ None => ALL.iter().find(|s| s.id == id).map(|s| s.default.to_string()).unwrap_or_default(),
+ }
+}
+
+/// The modifier for ⌘1…⌘9, normalized ("secondary" is ⌘ or Ctrl).
+pub fn machine_modifier(cx: &App) -> String {
+ modifier(&keys(cx, MACHINES))
+}
+
+fn modifier(m: &str) -> String {
+ match m {
+ "secondary" if cfg!(target_os = "macos") => "cmd".into(),
+ "secondary" => "ctrl".into(),
+ other => other.into(),
+ }
+}
+
+/// The keys that go to the n-th machine (1-based), if any.
+pub fn machine_keys(cx: &App, n: usize) -> Option<String> {
+ let m = machine_modifier(cx);
+ (!m.is_empty() && (1..=9).contains(&n)).then(|| format!("{m}-{n}"))
+}
+
+/// What already uses `keys`, other than `except`: a shortcut's id and label,
+/// or (MACHINES, "Machine 3") for a machine's.
+pub fn used_by(cx: &App, keys_: &str, except: &str) -> Option<(&'static str, String)> {
+ let k = normalize(keys_)?;
+ if except != MACHINES {
+ if let Some(n) = (1..=9).find(|n| machine_keys(cx, *n).and_then(|m| normalize(&m)).as_deref() == Some(k.as_str())) {
+ return Some((MACHINES, format!("Machine {n}")));
+ }
+ }
+ ALL.iter().filter(|s| s.id != except).find(|s| normalize(&keys(cx, s.id)).as_deref() == Some(k.as_str())).map(|s| (s.id, s.label.to_string()))
+}
+
+/// Sets a shortcut's keys ("" for none), keeping only what differs from the default.
+pub fn set(cx: &mut App, id: &str, keys_: &str) {
+ let same = if id == MACHINES {
+ modifier(keys_) == modifier(MACHINES_DEFAULT)
+ } else {
+ normalize(keys_) == ALL.iter().find(|s| s.id == id).and_then(|s| normalize(s.default))
+ };
+ super::theme::remember(cx, |a| {
+ if same {
+ a.shortcuts.remove(id);
+ } else {
+ a.shortcuts.insert(id.to_string(), keys_.to_string());
+ }
+ });
+}
+
+/// Whether the user changed this one.
+pub fn changed(cx: &App, id: &str) -> bool {
+ cx.global::<Appearance>().shortcuts.contains_key(id)
+}
+
+/// A comparable form of a key combination ("secondary-r" and "cmd-r" are the same on a Mac).
+fn normalize(keys: &str) -> Option<String> {
+ let parts: Option<Vec<String>> = keys.split_whitespace().map(|p| Keystroke::parse(p).ok().map(|k| k.unparse())).collect();
+ parts.filter(|p| !p.is_empty()).map(|p| p.join(" "))
+}
+
+/// Every shortcut, bound as the user has them. Keys that don't parse are skipped.
+pub fn bindings(cx: &App) -> Vec<KeyBinding> {
+ let mut out: Vec<KeyBinding> = ALL.iter().filter_map(|s| normalize(&keys(cx, s.id)).map(|k| (s.bind)(&k))).collect();
+ let machines: [fn(&str) -> KeyBinding; 9] = [
+ |k| KeyBinding::new(k, GoToMachine1, None),
+ |k| KeyBinding::new(k, GoToMachine2, None),
+ |k| KeyBinding::new(k, GoToMachine3, None),
+ |k| KeyBinding::new(k, GoToMachine4, None),
+ |k| KeyBinding::new(k, GoToMachine5, None),
+ |k| KeyBinding::new(k, GoToMachine6, None),
+ |k| KeyBinding::new(k, GoToMachine7, None),
+ |k| KeyBinding::new(k, GoToMachine8, None),
+ |k| KeyBinding::new(k, GoToMachine9, None),
+ ];
+ for (i, bind) in machines.iter().enumerate() {
+ if let Some(k) = machine_keys(cx, i + 1).and_then(|k| normalize(&k)) {
+ out.push(bind(&k));
+ }
+ }
+ out
+}
+
+/// Every shortcut that uses Ctrl (Linux and Windows hand these to terminals
+/// and remote desktops, where Ctrl keys mean something).
+pub fn ctrl_keys(cx: &App) -> Vec<String> {
+ let mut keys: Vec<String> = ALL.iter().filter_map(|s| normalize(&keys(cx, s.id))).collect();
+ keys.extend((1..=9).filter_map(|n| machine_keys(cx, n).and_then(|k| normalize(&k))));
+ keys.retain(|k| k.split('-').any(|p| p == "ctrl"));
+ keys
+}
+
+/// Binds every key in the app again, after the user changed a shortcut, and
+/// refreshes the menu bar (which shows them).
+pub fn apply(cx: &mut App) {
+ cx.clear_key_bindings();
+ super::input::bind_keys(cx);
+ super::terminal::bind_keys(cx);
+ super::desktop::bind_keys(cx);
+ super::root::bind_keys(cx);
+ cx.set_menus(super::root::menus());
+}
+
+/// How a key combination reads: "⌥⌘1" on a Mac, "Ctrl+Alt+1" elsewhere.
+pub fn label(keys: &str) -> String {
+ keys.split_whitespace().filter_map(|p| Keystroke::parse(p).ok()).map(|k| one(&k)).collect::<Vec<_>>().join(" ")
+}
+
+fn one(k: &Keystroke) -> String {
+ let m = &k.modifiers;
+ let key = match k.key.as_str() {
+ "escape" => "Esc".to_string(),
+ "enter" => "↵".into(),
+ "tab" => "⇥".into(),
+ "backspace" => "⌫".into(),
+ "delete" => "⌦".into(),
+ "space" => "Space".into(),
+ "up" => "↑".into(),
+ "down" => "↓".into(),
+ "left" => "←".into(),
+ "right" => "→".into(),
+ other if other.chars().count() == 1 => other.to_uppercase(),
+ other => {
+ let mut c = other.chars();
+ c.next().map(|f| f.to_uppercase().collect::<String>() + c.as_str()).unwrap_or_default()
+ }
+ };
+ if cfg!(target_os = "macos") {
+ let mut s = String::new();
+ for (on, sym) in [(m.control, "⌃"), (m.alt, "⌥"), (m.shift, "⇧"), (m.platform, "⌘"), (m.function, "fn ")] {
+ if on {
+ s.push_str(sym);
+ }
+ }
+ s + &key
+ } else {
+ let mut parts: Vec<&str> = Vec::new();
+ for (on, name) in [(m.control, "Ctrl"), (m.alt, "Alt"), (m.shift, "Shift"), (m.platform, "Super"), (m.function, "Fn")] {
+ if on {
+ parts.push(name);
+ }
+ }
+ parts.push(&key);
+ parts.join("+")
+ }
+}
+
+/// The label for a shortcut now ("" when it has none).
+pub fn label_for(cx: &App, id: &str) -> String {
+ label(&keys(cx, id))
+}
+
+/// A key the user pressed in Settings, as the keys to bind: None when it
+/// can't be a shortcut (no ⌘, ⌃ or ⌥, so it would type instead).
+pub fn from_press(k: &Keystroke) -> Option<String> {
+ let m = &k.modifiers;
+ let function_key = k.key.len() > 1 && k.key.starts_with('f') && k.key[1..].parse::<u8>().is_ok();
+ if !(m.platform || m.control || m.alt || function_key) || k.key.is_empty() {
+ return None;
+ }
+ Some(k.unparse())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn shortcuts_read_like_the_platform_writes_them() {
+ if cfg!(target_os = "macos") {
+ assert_eq!(label("secondary-shift-r"), "⇧⌘R");
+ assert_eq!(label("alt-secondary-1"), "⌥⌘1");
+ assert_eq!(label("cmd-,"), "⌘,");
+ assert_eq!(label("ctrl-escape"), "⌃Esc");
+ } else {
+ assert_eq!(label("secondary-shift-r"), "Ctrl+Shift+R");
+ }
+ assert_eq!(normalize("secondary-r"), normalize(if cfg!(target_os = "macos") { "cmd-r" } else { "ctrl-r" }));
+ assert_eq!(normalize(""), None);
+ }
+
+ #[test]
+ fn a_shortcut_needs_a_modifier() {
+ assert_eq!(from_press(&Keystroke::parse("a").unwrap()), None);
+ assert_eq!(from_press(&Keystroke::parse("shift-a").unwrap()), None);
+ assert!(from_press(&Keystroke::parse("cmd-k").unwrap()).is_some());
+ assert!(from_press(&Keystroke::parse("f5").unwrap()).is_some());
+ }
+}
diff --git a/src/ui/terminal/mod.rs b/src/ui/terminal/mod.rs
index e5450ba..102209d 100644
--- a/src/ui/terminal/mod.rs
+++ b/src/ui/terminal/mod.rs
@@ -62,11 +62,12 @@ const CONTEXT: &str = "Terminal";
/// terminals. On Linux and Windows the app's shortcuts use Ctrl, so those go
/// to the program too (the app's menu and ⌘ on macOS still work).
pub fn bind_keys(cx: &mut App) {
- let mut keys = vec!["escape", "/"];
+ let mut keys: Vec<String> = vec!["escape".into(), "/".into()];
if !cfg!(target_os = "macos") {
- keys.extend(["ctrl-r", "ctrl-shift-r", "ctrl-1", "ctrl-2", "ctrl-,", "ctrl-f", "ctrl-[", "ctrl-]", "ctrl-j", "ctrl-n", "ctrl-q"]);
+ keys.extend(super::shortcuts::ctrl_keys(cx));
+ keys.push("ctrl-q".into());
}
- cx.bind_keys(keys.into_iter().map(|k| KeyBinding::new(k, NoAction, Some(CONTEXT))));
+ cx.bind_keys(keys.iter().map(|k| KeyBinding::new(k, NoAction, Some(CONTEXT))));
cx.bind_keys([
KeyBinding::new("secondary-=", IncreaseFontSize, Some(CONTEXT)),
KeyBinding::new("secondary-+", IncreaseFontSize, Some(CONTEXT)),
diff --git a/src/ui/theme.rs b/src/ui/theme.rs
index 7c8f289..11400d1 100644
--- a/src/ui/theme.rs
+++ b/src/ui/theme.rs
@@ -139,6 +139,8 @@ pub struct Appearance {
pub split_ratio: f32,
/// Machines whose desktop is an item in the sidebar.
pub desktops: Vec<String>,
+ /// Shortcuts the user changed: id → keys ("" for none). See shortcuts.rs.
+ pub shortcuts: std::collections::BTreeMap<String, String>,
/// Where to save; None in demo mode.
#[serde(skip)]
pub path: Option<PathBuf>,
@@ -159,6 +161,7 @@ impl Default for Appearance {
github_folded_owners: Vec::new(),
split_ratio: 0.5,
desktops: Vec::new(),
+ shortcuts: Default::default(),
path: None,
}
}
diff --git a/src/ui/workspaces.rs b/src/ui/workspaces.rs
index 1ddffd7..bde2632 100644
--- a/src/ui/workspaces.rs
+++ b/src/ui/workspaces.rs
@@ -87,17 +87,7 @@ impl Root {
.flex()
.items_center()
.gap(px(10.))
- .child(
- div()
- .size(px(32.))
- .flex_none()
- .rounded(px(8.))
- .bg(theme.accent.opacity(0.14))
- .flex()
- .items_center()
- .justify_center()
- .child(icon("terminal", 15., theme.text_accent)),
- )
+ .child(kit::tile("terminal", kit::tiles::WORKSPACES.0, kit::tiles::WORKSPACES.1, 32.))
.child(
div()
.flex()
@@ -433,7 +423,7 @@ impl Root {
.cursor_pointer()
.hover(|st| st.bg(theme.ghost_hover))
.when(i > 0, |d| d.border_t_1().border_color(theme.border_variant))
- .child(icon("terminal", 13., theme.text_accent))
+ .child(kit::tile("terminal", kit::tiles::WORKSPACES.0, kit::tiles::WORKSPACES.1, 18.))
.child(div().text_size(px(13.)).child(w.name.clone()))
.child(div().font_family(mono_font()).text_size(px(11.)).text_color(theme.text_placeholder).child(w.id.clone()))
.child(div().flex_1())