diff --git a/assets/icons/settings/about.svg b/assets/icons/settings/about.svg new file mode 100644 index 00000000..7b343ec5 --- /dev/null +++ b/assets/icons/settings/about.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/settings/appearance.svg b/assets/icons/settings/appearance.svg new file mode 100644 index 00000000..39a24ba5 --- /dev/null +++ b/assets/icons/settings/appearance.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/settings/back.svg b/assets/icons/settings/back.svg new file mode 100644 index 00000000..01698fba --- /dev/null +++ b/assets/icons/settings/back.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/settings/check.svg b/assets/icons/settings/check.svg new file mode 100644 index 00000000..214548b4 --- /dev/null +++ b/assets/icons/settings/check.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/settings/chevron-down.svg b/assets/icons/settings/chevron-down.svg new file mode 100644 index 00000000..e152c3cd --- /dev/null +++ b/assets/icons/settings/chevron-down.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/settings/chevron-right.svg b/assets/icons/settings/chevron-right.svg new file mode 100644 index 00000000..39c3ae72 --- /dev/null +++ b/assets/icons/settings/chevron-right.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/settings/close.svg b/assets/icons/settings/close.svg new file mode 100644 index 00000000..3a78e6b6 --- /dev/null +++ b/assets/icons/settings/close.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/settings/general.svg b/assets/icons/settings/general.svg new file mode 100644 index 00000000..2a74da9d --- /dev/null +++ b/assets/icons/settings/general.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/settings/integrations.svg b/assets/icons/settings/integrations.svg new file mode 100644 index 00000000..a2754b3d --- /dev/null +++ b/assets/icons/settings/integrations.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/settings/keyboard.svg b/assets/icons/settings/keyboard.svg new file mode 100644 index 00000000..dfa8d0bb --- /dev/null +++ b/assets/icons/settings/keyboard.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/settings/machine-local.svg b/assets/icons/settings/machine-local.svg new file mode 100644 index 00000000..e2a17a39 --- /dev/null +++ b/assets/icons/settings/machine-local.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/settings/machine-remote.svg b/assets/icons/settings/machine-remote.svg new file mode 100644 index 00000000..f4bd1e47 --- /dev/null +++ b/assets/icons/settings/machine-remote.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/settings/more.svg b/assets/icons/settings/more.svg new file mode 100644 index 00000000..956cf3e8 --- /dev/null +++ b/assets/icons/settings/more.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/settings/plus.svg b/assets/icons/settings/plus.svg new file mode 100644 index 00000000..90df7cc6 --- /dev/null +++ b/assets/icons/settings/plus.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/settings/search.svg b/assets/icons/settings/search.svg new file mode 100644 index 00000000..0ec9da6e --- /dev/null +++ b/assets/icons/settings/search.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/settings/ssh.svg b/assets/icons/settings/ssh.svg new file mode 100644 index 00000000..c1602af6 --- /dev/null +++ b/assets/icons/settings/ssh.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/settings/terminal.svg b/assets/icons/settings/terminal.svg new file mode 100644 index 00000000..6711f8cd --- /dev/null +++ b/assets/icons/settings/terminal.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/settings/window.svg b/assets/icons/settings/window.svg new file mode 100644 index 00000000..a259702b --- /dev/null +++ b/assets/icons/settings/window.svg @@ -0,0 +1 @@ + diff --git a/crates/tty7-core/src/core/agent_hooks.rs b/crates/tty7-core/src/core/agent_hooks.rs index 38c846c8..8af07878 100644 --- a/crates/tty7-core/src/core/agent_hooks.rs +++ b/crates/tty7-core/src/core/agent_hooks.rs @@ -266,7 +266,7 @@ fn ancestor_pids(procs: &[crate::daemon::winproc::Proc]) -> Vec { out } -#[derive(Clone, Copy, PartialEq, Eq, Debug)] +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub enum HookAgent { Claude, Codex, diff --git a/docs/customization/settings.mdx b/docs/customization/settings.mdx index 05f96cf9..d894d4db 100644 --- a/docs/customization/settings.mdx +++ b/docs/customization/settings.mdx @@ -15,9 +15,8 @@ section something is in. - Interface language, startup and layout restore, tray icon, default terminal, - command completion notifications, update preferences and proxy, and the - tty7 server. + Interface language, default terminal, startup window, size and layout + restore, tray icon, and command completion notifications. Theme and colors, interface and terminal fonts, cursor, background image, @@ -34,30 +33,36 @@ section something is in. Tab position and placement, sidebar grouping, and diff previews. - Hosts, connection defaults, security, authentication, proxies, and forwarding. + Recent and saved hosts, each opened and edited in place, and host key + security. AI agent hooks per machine and the tty7 command on PATH. - App information, version, manual update checks, and available updates. + Version and update checks, update preferences and proxy, the settings + file, and the tty7 server. ## Search and edit Search matches setting names, descriptions, English aliases, and configuration -keys such as `mouse_zoom_modifier`. Ordinary results are editable directly; -use the path above a result to open its category. SSH, theme editors, and -keyboard shortcuts have dedicated views. +keys such as `mouse_zoom_modifier`. Results are grouped by section and are +editable directly; click a section name to open it. Press ⌘F (Ctrl+F) to jump +to the search box. Use **Modified only** to find settings that differ from their defaults. A -modified setting offers **Reset setting**; installation and maintenance actions +modified setting offers **Reset** beside its name; installation and maintenance actions do not have a generic reset. Ordinary controls save automatically. Text fields commit valid values on Enter or when focus leaves the field. Custom theme edits are previewed until you save; -cancel restores the original theme. SSH profiles also use explicit saving. +cancel restores the original theme. SSH hosts also use explicit saving. + +Recording a keyboard shortcut that another action already uses asks before +taking it over: **Replace** moves the shortcut, **Cancel** leaves both as they +were. Leaving an edited form offers save, discard, or continue editing. ## The settings file diff --git a/src/core/session.rs b/src/core/session.rs index 4cf3af92..77841362 100644 --- a/src/core/session.rs +++ b/src/core/session.rs @@ -1,6 +1,6 @@ pub use tty7_core::core::session::{ - RemoteRef, RemoteTarget, RouteSnapshot, Session, SessionAxis, SessionPane, SessionTab, - WindowView, WindowViews, WorkspaceId, + RemoteRef, RemoteTarget, Session, SessionAxis, SessionPane, SessionTab, WindowView, + WindowViews, WorkspaceId, }; pub use tty7_core::host::HostId; diff --git a/src/ui/app.rs b/src/ui/app.rs index bd2b2d8b..19ec8bbb 100644 --- a/src/ui/app.rs +++ b/src/ui/app.rs @@ -4,11 +4,7 @@ use gpui::{ }; use gpui_component::color_picker::{ColorPickerEvent, ColorPickerState}; use gpui_component::input::{InputEvent, InputState}; -use gpui_component::select::{SearchableVec, SelectEvent, SelectState}; -use gpui_component::slider::{SliderEvent, SliderState}; -use gpui_component::{ - ActiveTheme as _, IndexPath, InteractiveElementExt as _, TitleBar, WindowExt as _, -}; +use gpui_component::{ActiveTheme as _, InteractiveElementExt as _, TitleBar, WindowExt as _}; use std::cell::{Cell, RefCell}; use std::rc::Rc; use std::sync::Arc; @@ -239,6 +235,7 @@ pub(crate) const TILE_SIZE_XS: f32 = 18.; pub(crate) const TILE_GLYPH_XS: f32 = 11.; /// Line-only controls share the toolbar icon size. +#[allow(dead_code)] pub(crate) const TILE_GLYPH_LINE: f32 = 16.; pub(crate) const TILE_PAD: f32 = (TILE_SIZE - TILE_GLYPH) / 2.; @@ -1031,28 +1028,9 @@ impl TabAgentSession { } } -/// Maps a backdrop onto the settings dropdown. The dropdown lists the -/// presets the current Windows build supports, plus the stored value even -/// when unsupported here (see `theme::backdrop_options`), so the label -/// always matches what the window actually resolves to. +/// The name the settings backdrop menu gives a material. #[cfg(target_os = "windows")] -fn window_backdrop_index(backdrop: WindowBackdrop) -> usize { - crate::ui::theme::backdrop_options(backdrop) - .iter() - .position(|candidate| *candidate == backdrop) - .unwrap_or(0) -} - -#[cfg(target_os = "windows")] -fn window_backdrop_from_index(idx: usize, current: WindowBackdrop) -> WindowBackdrop { - crate::ui::theme::backdrop_options(current) - .get(idx) - .copied() - .unwrap_or(WindowBackdrop::Auto) -} - -#[cfg(target_os = "windows")] -fn window_backdrop_label_key(backdrop: WindowBackdrop) -> L10nKey { +pub(crate) fn window_backdrop_label_key(backdrop: WindowBackdrop) -> L10nKey { match backdrop { WindowBackdrop::Auto => L10nKey::SettingsBackdropAuto, WindowBackdrop::Blur => L10nKey::SettingsBackdropBlur, @@ -1063,14 +1041,6 @@ fn window_backdrop_label_key(backdrop: WindowBackdrop) -> L10nKey { } } -#[cfg(target_os = "windows")] -fn window_backdrop_labels(backdrop: WindowBackdrop) -> Vec { - crate::ui::theme::backdrop_options(backdrop) - .iter() - .map(|backdrop| t(window_backdrop_label_key(*backdrop)).to_string()) - .collect() -} - /// What a full-window overlay (settings, the opened file, the diff view) /// paints between its own fill and its content. /// @@ -1386,7 +1356,6 @@ impl Tty7App { apply_theme(Some(window), cx); let _ = this.update(cx, |this, cx| { this.rebuild_theme_editor(window, cx); - this.sync_window_opacity_slider(window, cx); cx.notify(); }); }); @@ -2406,18 +2375,65 @@ impl Tty7App { cfg.theme_preset = effective; } self.after_theme_change(window, cx); - let slot = if on { - if crate::ui::theme::system_dark(cx) { - crate::ui::settings::ThemeSlot::Dark - } else { - crate::ui::settings::ThemeSlot::Light - } - } else { - crate::ui::settings::ThemeSlot::Manual - }; - if let Some(s) = self.active_settings_mut() { - s.theme_panel_slot = slot; + } + + /// The Appearance page's three modes. System follows the OS between the + /// light and the dark slot; Light and Dark pin the matching slot's theme. + pub(crate) fn set_theme_mode( + &mut self, + mode: crate::ui::settings::ThemeMode, + window: &mut Window, + cx: &mut Context, + ) { + use crate::ui::settings::ThemeMode; + if self.theme_draft_dirty() { + self.with_settings_edits_resolved(window, cx, move |this, window, cx| { + this.set_theme_mode(mode, window, cx) + }); + return; } + match mode { + ThemeMode::System => { + if !cx.global::().theme_follow_system { + self.set_theme_follow_system(true, window, cx); + } + } + ThemeMode::Light | ThemeMode::Dark => { + let cfg = cx.global_mut::(); + cfg.theme_follow_system = false; + cfg.theme_preset = if mode == ThemeMode::Dark { + cfg.theme_preset_dark.clone() + } else { + cfg.theme_preset_light.clone() + }; + self.theme_preview_restore = None; + self.after_theme_change(window, cx); + } + } + } + + /// A pick from a theme slot's menu. Pinned to one mode, the pick is also + /// what that mode's slot remembers, so System picks it back up. + pub(crate) fn pick_slot_theme( + &mut self, + dark_slot: bool, + id: &str, + window: &mut Window, + cx: &mut Context, + ) { + if cx.global::().theme_follow_system { + self.set_slot_preset(dark_slot, id, window, cx); + return; + } + if !self.theme_draft_dirty() { + let cfg = cx.global_mut::(); + if dark_slot { + cfg.theme_preset_dark = id.to_string(); + } else { + cfg.theme_preset_light = id.to_string(); + } + } + self.set_preset(id, window, cx); } pub(crate) fn set_theme_legible_palette( @@ -2444,59 +2460,9 @@ impl Tty7App { self.persist_settings_config(cx); } self.rebuild_theme_editor(window, cx); - self.sync_window_opacity_slider(window, cx); cx.notify(); } - /// Opens or closes the theme picker, and moves the caret with it. - /// - /// The panel leads with a search box, and it opened unfocused — so the - /// first thing typed at a panel whose whole job is picking one of nine - /// themes went nowhere. Closing hands the caret back to the settings - /// search rather than leaving it on a box that is no longer drawn. - pub(crate) fn toggle_theme_panel( - &mut self, - slot: crate::ui::settings::ThemeSlot, - window: &mut Window, - cx: &mut Context, - ) { - let opened = match self.active_settings_mut() { - Some(s) if s.theme_panel_open && s.theme_panel_slot == slot => { - s.theme_panel_open = false; - false - } - Some(s) => { - s.theme_panel_open = true; - s.theme_panel_slot = slot; - true - } - None => return, - }; - self.focus_theme_panel(opened, window, cx); - cx.notify(); - } - - pub(crate) fn close_theme_panel(&mut self, window: &mut Window, cx: &mut Context) { - if self.active_settings_mut().is_none() { - return; - } - if let Some(s) = self.active_settings_mut() { - s.theme_panel_open = false; - } - self.focus_theme_panel(false, window, cx); - cx.notify(); - } - - fn focus_theme_panel(&mut self, opened: bool, window: &mut Window, cx: &mut Context) { - let handle = self.settings.as_ref().map(|s| match opened { - true => s.theme_search.read(cx).focus_handle(cx), - false => s.search.read(cx).focus_handle(cx), - }); - if let Some(handle) = handle { - window.focus(&handle, cx); - } - } - pub(crate) fn open_themes_folder(&self, window: &mut Window, cx: &mut Context) { let Some(dir) = crate::ui::presets::themes_dir() else { log::warn!("no config directory, so no themes folder to open"); @@ -2521,28 +2487,6 @@ impl Tty7App { cx.open_with_system(&dir); } - pub(crate) fn fork_active_theme(&mut self, window: &mut Window, cx: &mut Context) { - let id = crate::ui::theme::effective_preset_id(cx); - let theme = crate::ui::presets::by_id(cx, &id); - match crate::ui::presets::fork_to_file(&theme) { - Ok(new_id) => { - crate::ui::presets::load_registry(cx); - self.set_preset(&new_id, window, cx); - } - // A button that does nothing is the worst kind of failure: there - // is no way to tell it from "I clicked the wrong thing". - Err(e) => { - log::warn!("failed to duplicate theme: {e}"); - crate::ui::host_ops::HostOps::notify_err( - window, - cx, - t(L10nKey::ThemeDuplicateFailed), - &e, - ); - } - } - } - pub(crate) fn theme_draft_dirty(&self) -> bool { self.active_settings() .is_some_and(|s| s.theme_draft.is_some()) @@ -2667,18 +2611,6 @@ impl Tty7App { }) } - pub(crate) fn set_window_opacity( - &mut self, - v: f32, - window: &mut Window, - cx: &mut Context, - ) { - cx.global_mut::().window_opacity = Some(v.clamp(0.2, 1.0)); - apply_theme(Some(window), cx); - self.persist_settings_config(cx); - cx.notify(); - } - pub(crate) fn set_window_blur( &mut self, on: bool, @@ -2701,14 +2633,6 @@ impl Tty7App { cx.global_mut::().window_backdrop = backdrop; apply_theme(Some(window), cx); self.persist_settings_config(cx); - // A material changes the default opacity (SYSTEM_MATERIAL_OPACITY - // vs 1.0), so the slider must track the new effective value. - self.sync_window_opacity_slider(window, cx); - // Rebuild the rows as well as the selected index. The previous value - // may have been an unsupported preset retained only for cross-machine - // config sync, and must disappear after the user selects a supported - // preset on this machine. - self.sync_window_backdrop_select(window, cx); cx.notify(); } @@ -2719,48 +2643,9 @@ impl Tty7App { } apply_theme(Some(window), cx); self.persist_settings_config(cx); - self.sync_window_opacity_slider(window, cx); - #[cfg(target_os = "windows")] - self.sync_window_backdrop_select(window, cx); cx.notify(); } - pub(crate) fn sync_window_opacity_slider( - &mut self, - window: &mut Window, - cx: &mut Context, - ) { - let eff = Self::effective_window_opacity(cx); - if let Some(slider) = self - .active_settings() - .map(|s| s.window_opacity_slider.clone()) - { - slider.update(cx, |s, cx| s.set_value(eff, window, cx)); - } - } - - #[cfg(target_os = "windows")] - pub(crate) fn sync_window_backdrop_select( - &mut self, - window: &mut Window, - cx: &mut Context, - ) { - if let Some(select) = self - .active_settings() - .map(|s| s.window_backdrop_select.clone()) - { - let current = cx.global::().window_backdrop; - let rows = window_backdrop_labels(current); - let selected = window_backdrop_index(current); - select.update(cx, |state, cx| { - state.set_items(SearchableVec::new(rows), window, cx); - // Replacing the delegate clears its selection snapshot, so - // restore the stored value after installing the new rows. - state.set_selected_index(Some(IndexPath::default().row(selected)), window, cx); - }); - } - } - pub(crate) fn pick_theme_image(&mut self, cx: &mut Context) { let rx = cx.prompt_for_paths(gpui::PathPromptOptions { files: true, @@ -2866,32 +2751,11 @@ impl Tty7App { }) .collect(); - let image_opacity_slider = theme.image.as_ref().map(|img| { - let slider = cx.new(|_| { - SliderState::new() - .min(0.0) - .max(1.0) - .step(0.01) - .default_value(img.opacity) - }); - subs.push(cx.subscribe_in( - &slider, - window, - |this, _s, ev: &SliderEvent, window, cx| { - if let SliderEvent::Change(v) = ev { - this.set_theme_image_opacity(v.start(), window, cx); - } - }, - )); - slider - }); - if let Some(s) = self.settings.as_mut() { s.theme_editor = Some(ThemeEditor { for_id: theme.id.clone(), seed, ansi, - image_opacity_slider, _subs: subs, }); } @@ -5968,24 +5832,6 @@ impl Tty7App { ) { let mut subs = Vec::new(); match title { - L10nKey::SettingsFontFamily - | L10nKey::SettingsBoldFont - | L10nKey::SettingsItalicFont - | L10nKey::SettingsUiFontFamily => { - let (font, bold, italic, ui) = self.build_font_selects(&mut subs, window, cx); - if let Some(s) = self.active_settings_mut() { - s.font_select = font; - s.font_bold_select = bold; - s.font_italic_select = italic; - s.ui_font_select = ui; - } - } - L10nKey::SettingsLanguage => { - let value = self.build_language_select(&mut subs, window, cx); - if let Some(s) = self.active_settings_mut() { - s.language_select = value; - } - } L10nKey::SettingsProgram | L10nKey::SettingsArguments => { let (program, args, _) = self.build_shell_inputs(&mut subs, window, cx); if let Some(s) = self.active_settings_mut() { @@ -6013,18 +5859,6 @@ impl Tty7App { s.http_proxy_input = value; } } - L10nKey::SettingsScrollSpeed => { - let value = self.build_scroll_slider(&mut subs, window, cx); - if let Some(s) = self.active_settings_mut() { - s.scroll_slider = value; - } - } - L10nKey::SettingsOpacity | L10nKey::SettingsBlur | L10nKey::SettingsBackdrop => { - let value = self.build_window_opacity_slider(&mut subs, window, cx); - if let Some(s) = self.active_settings_mut() { - s.window_opacity_slider = value; - } - } _ => {} } if let Some(s) = self.active_settings_mut() { @@ -6099,27 +5933,60 @@ impl Tty7App { }); } + /// Every family the settings font menus offer, with the configured ones + /// kept even when the system no longer has them — a menu that cannot show + /// the current value cannot say what it is. + fn settings_font_names(cx: &App) -> Vec { + let cfg = cx.global::(); + let mut names = cx.text_system().all_font_names(); + for configured in [ + Some(&cfg.font_family), + cfg.ui_font_family.as_ref(), + cfg.font_family_bold.as_ref(), + cfg.font_family_italic.as_ref(), + ] + .into_iter() + .flatten() + { + if !names.contains(configured) { + names.push(configured.clone()); + } + } + names.sort_unstable(); + names.dedup(); + names + } + /// Build the settings page's state against `window` — the window it will /// be drawn in, which owns its inputs' focus. fn build_settings_state(&mut self, window: &mut Window, cx: &mut Context) { let focus_handle = cx.focus_handle(); let mut subs = Vec::new(); - let (font_select, font_bold_select, font_italic_select, ui_font_select) = - self.build_font_selects(&mut subs, window, cx); - let language_select = self.build_language_select(&mut subs, window, cx); - #[cfg(target_os = "windows")] - let window_backdrop_select = self.build_window_backdrop_select(&mut subs, window, cx); + let font_names = std::rc::Rc::new(Self::settings_font_names(cx)); let (shell_program_input, shell_args_input, wd_path_input) = self.build_shell_inputs(&mut subs, window, cx); let link_file_command_input = self.build_link_file_command_input(&mut subs, window, cx); let http_proxy_input = self.build_http_proxy_input(&mut subs, window, cx); - let scroll_slider = self.build_scroll_slider(&mut subs, window, cx); - let window_opacity_slider = self.build_window_opacity_slider(&mut subs, window, cx); - let theme_search = cx.new(|cx| { - InputState::new(window, cx).placeholder(t(crate::ui::i18n::L10nKey::SearchThemes)) - }); + // One query box for whichever popover is open — a theme list or a + // font list — since only one is ever open at a time. + let menu_query = cx.new(|cx| InputState::new(window, cx)); subs.push( - cx.subscribe_in(&theme_search, window, |_this, _i, ev, _w, cx| { + cx.subscribe_in(&menu_query, window, |this, input, ev, _w, cx| { + if matches!(ev, InputEvent::Change) { + // A new query starts from the top; the clear that opens a + // popover keeps the row it opened on. + let typed = !input.read(cx).value().is_empty(); + if let Some(s) = this.active_settings_mut().filter(|_| typed) { + s.menu_hi = 0; + } + cx.notify(); + } + }), + ); + let agent_query = + cx.new(|cx| InputState::new(window, cx).placeholder(t(L10nKey::SettingsSearchAgents))); + subs.push( + cx.subscribe_in(&agent_query, window, |_this, _i, ev, _w, cx| { if matches!(ev, InputEvent::Change) { cx.notify(); } @@ -6141,7 +6008,7 @@ impl Tty7App { ); let shortcut_search = cx - .new(|cx| InputState::new(window, cx).placeholder(t(L10nKey::SettingsNavKeybindings))); + .new(|cx| InputState::new(window, cx).placeholder(t(L10nKey::SettingsSearchShortcuts))); subs.push( cx.subscribe_in(&shortcut_search, window, |_, _, ev, _, cx| { if matches!(ev, InputEvent::Change) { @@ -6161,17 +6028,6 @@ impl Tty7App { }), ); - let ssh_quick_connect = cx.new(|cx| { - InputState::new(window, cx).placeholder(t(L10nKey::AppPlaceholderSshQuickConnect)) - }); - subs.push( - cx.subscribe_in(&ssh_quick_connect, window, |_this, _i, ev, _w, cx| { - if matches!(ev, InputEvent::Change) { - cx.notify(); - } - }), - ); - let content_scroll = gpui::ScrollHandle::new(); content_scroll.set_offset(self.last_settings_location.1); let search_anchor = gpui::ScrollAnchor::for_handle(content_scroll.clone()); @@ -6188,44 +6044,42 @@ impl Tty7App { search_rows: std::cell::RefCell::new(None), focused_setting: None, content_scroll, - ssh_master_scroll: gpui::ScrollHandle::new(), - ssh_detail_scroll: gpui::ScrollHandle::new(), - theme_list_scroll: gpui::ScrollHandle::new(), search_anchor, reveal_first_hit: Cell::new(false), - font_select, - font_bold_select, - font_italic_select, - ui_font_select, - language_select, - #[cfg(target_os = "windows")] - window_backdrop_select, + font_names, shell_program_input, shell_args_input, wd_path_input, link_file_command_input, http_proxy_input, - scroll_slider, - window_opacity_slider, theme_editor: None, theme_draft: None, theme_draft_error: None, save_error: None, saved_config: cx.global::().clone(), - theme_panel_open: false, - theme_panel_slot: crate::ui::settings::ThemeSlot::Manual, - theme_search, + menu: None, + menu_query, + menu_hi: 0, + menu_scroll: gpui::ScrollHandle::new(), + focused: std::cell::RefCell::new(None), + kb_conflict: None, recording: None, rebinding_note: None, ssh_form: None, - ssh_detail: crate::ui::settings::SshDetail::None, + ssh_open: None, + ssh_show_all: false, + ssh_confirm_remove: false, + ssh_copied: None, ssh_filter, ssh_collapsed_groups: std::collections::HashSet::new(), - ssh_quick_connect, agent_hooks_host: crate::ui::host_ops::HostId::LOCAL, agent_hooks_states: crate::ui::settings::AgentHooksView::Loading, agent_hooks_seq: 0, agent_hooks_note: None, + agent_query, + agent_show_all: false, + agent_touched: std::collections::HashSet::new(), + agent_busy: std::collections::HashSet::new(), _subs: subs, }); let search_focus = self @@ -6241,214 +6095,12 @@ impl Tty7App { cx.notify(); } - fn build_font_selects( - &mut self, - subs: &mut Vec, - window: &mut Window, - cx: &mut Context, - ) -> ( - Entity>>, - Entity>>, - Entity>>, - Entity>>, - ) { - let cfg = cx.global::(); - let family = cfg.font_family.clone(); - let font_bold = cfg.font_family_bold.clone(); - let font_italic = cfg.font_family_italic.clone(); - let ui_font_family = cfg.ui_font_family.clone(); - let mut font_names = cx.text_system().all_font_names(); - if !font_names.contains(&family) { - font_names.push(family.clone()); - font_names.sort_unstable(); - } - if let Some(ui_font) = &ui_font_family - && !font_names.contains(ui_font) - { - font_names.push(ui_font.clone()); - font_names.sort_unstable(); - } - let selected_font_index = font_names - .iter() - .position(|n| *n == family) - .map(|row| IndexPath::default().row(row)); - let font_select = cx.new(|cx| { - SelectState::new( - SearchableVec::new(font_names.clone()), - selected_font_index, - window, - cx, - ) - .searchable(true) - }); - let build_alt_font_select = |value: &Option, - default_label: &str, - names: &[String], - window: &mut Window, - cx: &mut Context| { - let mut rows = Vec::with_capacity(names.len() + 1); - rows.push(default_label.to_string()); - rows.extend(names.iter().cloned()); - let selected = value - .as_ref() - .and_then(|v| rows.iter().position(|n| n == v)) - .unwrap_or(0); - cx.new(|cx| { - SelectState::new( - SearchableVec::new(rows), - Some(IndexPath::default().row(selected)), - window, - cx, - ) - .searchable(true) - }) - }; - let alt_default = crate::ui::settings::font_default_label(); - let font_bold_select = - build_alt_font_select(&font_bold, alt_default, &font_names, window, cx); - let font_italic_select = - build_alt_font_select(&font_italic, alt_default, &font_names, window, cx); - let ui_font_select = build_alt_font_select( - &ui_font_family, - crate::ui::settings::ui_font_default_label(), - &font_names, - window, - cx, - ); - subs.push(cx.subscribe_in( - &font_select, - window, - |this, _select, ev: &SelectEvent>, _window, cx| { - if let SelectEvent::Confirm(Some(family)) = ev { - this.commit_font_family(family.clone(), cx); - } - }, - )); - subs.push(cx.subscribe_in( - &font_bold_select, - window, - |this, _s, ev: &SelectEvent>, _w, cx| { - if let SelectEvent::Confirm(Some(name)) = ev { - this.commit_font_family_emphasis(true, name.clone(), cx); - } - }, - )); - subs.push(cx.subscribe_in( - &font_italic_select, - window, - |this, _s, ev: &SelectEvent>, _w, cx| { - if let SelectEvent::Confirm(Some(name)) = ev { - this.commit_font_family_emphasis(false, name.clone(), cx); - } - }, - )); - subs.push(cx.subscribe_in( - &ui_font_select, - window, - |this, _s, ev: &SelectEvent>, window, cx| { - if let SelectEvent::Confirm(Some(name)) = ev { - this.commit_ui_font_family(name.clone(), window, cx); - } - }, - )); - ( - font_select, - font_bold_select, - font_italic_select, - ui_font_select, - ) - } - - fn build_language_select( - &mut self, - subs: &mut Vec, - window: &mut Window, - cx: &mut Context, - ) -> Entity>> { - let labels = || { - crate::ui::i18n::SUPPORTED_LANGUAGES - .iter() - .map(|lang| t(lang.label_key).to_string()) - .collect::>() - }; - let cfg = cx.global::(); - let current = Self::normalize_gui_language(&cfg.gui_language); - let rows = labels(); - let selected = crate::ui::i18n::SUPPORTED_LANGUAGES - .iter() - .position(|lang| lang.code == current) - .unwrap_or(0); - let language_select = cx.new(|cx| { - SelectState::new( - SearchableVec::new(rows), - Some(IndexPath::default().row(selected)), - window, - cx, - ) - }); - subs.push(cx.subscribe_in( - &language_select, - window, - move |this, _select, ev: &SelectEvent>, window, cx| { - if let SelectEvent::Confirm(Some(label)) = ev { - let rows = labels(); - if let Some(idx) = rows.iter().position(|r| r == label) { - if let Some(lang) = crate::ui::i18n::SUPPORTED_LANGUAGES.get(idx) { - this.set_gui_language(lang.code, window, cx); - } - } - } - }, - )); - language_select - } - - fn normalize_gui_language(code: &str) -> &'static str { + pub(crate) fn normalize_gui_language(code: &str) -> &'static str { crate::ui::i18n::find_language(code) .map(|lang| lang.code) .unwrap_or_else(crate::ui::i18n::default_language_code) } - /// The backdrop dropdown only lists the presets this Windows build - /// supports, in the order of `theme::supported_backdrops`; the select - /// resolves the picked label back through that same list. - #[cfg(target_os = "windows")] - fn build_window_backdrop_select( - &mut self, - subs: &mut Vec, - window: &mut Window, - cx: &mut Context, - ) -> Entity>> { - let rows = window_backdrop_labels(cx.global::().window_backdrop); - let selected = window_backdrop_index(cx.global::().window_backdrop); - let select = cx.new(|cx| { - SelectState::new( - SearchableVec::new(rows), - Some(IndexPath::default().row(selected)), - window, - cx, - ) - }); - subs.push(cx.subscribe_in( - &select, - window, - move |this, _select, ev: &SelectEvent>, window, cx| { - if let SelectEvent::Confirm(Some(label)) = ev { - let current = cx.global::().window_backdrop; - let rows = window_backdrop_labels(current); - if let Some(idx) = rows.iter().position(|row| row == label) { - this.set_window_backdrop( - window_backdrop_from_index(idx, current), - window, - cx, - ); - } - } - }, - )); - select - } - pub(crate) fn set_gui_language( &mut self, code: &'static str, @@ -6484,45 +6136,17 @@ impl Tty7App { state.set_placeholder(t(L10nKey::SearchFiles), window, cx) }); if let Some(s) = self.active_settings() { - let rows = crate::ui::i18n::SUPPORTED_LANGUAGES - .iter() - .map(|lang| t(lang.label_key).to_string()) - .collect::>(); - s.language_select.update(cx, |state, cx| { - state.set_items(SearchableVec::new(rows), window, cx); - let code = Self::normalize_gui_language(&cx.global::().gui_language); - let selected = crate::ui::i18n::SUPPORTED_LANGUAGES - .iter() - .position(|lang| lang.code == code) - .unwrap_or(0); - state.set_selected_index(Some(IndexPath::default().row(selected)), window, cx); - }); - #[cfg(target_os = "windows")] - s.window_backdrop_select.update(cx, |state, cx| { - let current = cx.global::().window_backdrop; - let rows = window_backdrop_labels(current); - state.set_items(SearchableVec::new(rows), window, cx); - // `set_items` does not preserve the selection; restore the - // index of the stored value so a locale refresh (which - // re-translates the labels) cannot leave the dropdown - // showing no — or the wrong — selection. - state.set_selected_index( - Some(IndexPath::default().row(window_backdrop_index(current))), - window, - cx, - ); - }); s.search.update(cx, |state, cx| { state.set_placeholder(t(L10nKey::SearchSettings), window, cx) }); - s.theme_search.update(cx, |state, cx| { - state.set_placeholder(t(L10nKey::SearchThemes), window, cx) - }); s.ssh_filter.update(cx, |state, cx| { state.set_placeholder(t(L10nKey::FilterHosts), window, cx) }); - s.ssh_quick_connect.update(cx, |state, cx| { - state.set_placeholder(t(L10nKey::AppPlaceholderSshQuickConnect), window, cx) + s.shortcut_search.update(cx, |state, cx| { + state.set_placeholder(t(L10nKey::SettingsSearchShortcuts), window, cx) + }); + s.agent_query.update(cx, |state, cx| { + state.set_placeholder(t(L10nKey::SettingsSearchAgents), window, cx) }); s.shell_args_input.update(cx, |state, cx| { state.set_placeholder(t(L10nKey::AppPlaceholderNone), window, cx) @@ -6701,63 +6325,6 @@ impl Tty7App { cx.notify(); } - fn build_window_opacity_slider( - &mut self, - subs: &mut Vec, - window: &mut Window, - cx: &mut Context, - ) -> Entity { - let eff = Self::effective_window_opacity(cx); - let slider = cx.new(|_| { - SliderState::new() - .min(0.2) - .max(1.0) - .step(0.01) - .default_value(eff) - }); - subs.push(cx.subscribe_in( - &slider, - window, - |this, _s, ev: &SliderEvent, window, cx| match ev { - SliderEvent::Change(v) => { - cx.global_mut::().window_opacity = Some(v.start().clamp(0.2, 1.0)); - apply_theme(Some(window), cx); - cx.notify(); - } - SliderEvent::Release(_) => this.persist_settings_config(cx), - }, - )); - slider - } - - fn build_scroll_slider( - &mut self, - subs: &mut Vec, - window: &mut Window, - cx: &mut Context, - ) -> Entity { - let scroll_mult = cx.global::().mouse_scroll_multiplier; - let scroll_slider = cx.new(|_| { - SliderState::new() - .min(0.5) - .max(5.0) - .step(0.25) - .default_value(scroll_mult) - }); - subs.push(cx.subscribe_in( - &scroll_slider, - window, - |this, _s, ev: &SliderEvent, _w, cx| match ev { - SliderEvent::Change(v) => { - cx.global_mut::().mouse_scroll_multiplier = v.start().clamp(0.1, 10.0); - cx.notify(); - } - SliderEvent::Release(_) => this.persist_settings_config(cx), - }, - )); - scroll_slider - } - pub(crate) fn close_settings(&mut self, window: &mut Window, cx: &mut Context) { if let Some(s) = self.settings.take() { self.last_settings_location = ( @@ -6926,7 +6493,7 @@ impl Tty7App { self.open_ssh_profile_form(profile, window, cx); } - fn commit_font_family(&mut self, family: String, cx: &mut Context) { + pub(crate) fn commit_font_family(&mut self, family: String, cx: &mut Context) { self.font_family = family.clone(); for tab in &self.tabs { for leaf in tab.pane.terminals() { @@ -6940,7 +6507,12 @@ impl Tty7App { cx.notify(); } - fn commit_font_family_emphasis(&mut self, bold: bool, name: String, cx: &mut Context) { + pub(crate) fn commit_font_family_emphasis( + &mut self, + bold: bool, + name: String, + cx: &mut Context, + ) { let family = (name != crate::ui::settings::font_default_label()).then_some(name); for tab in &self.tabs { for leaf in tab.pane.terminals() { @@ -6969,7 +6541,12 @@ impl Tty7App { cx.notify(); } - fn commit_ui_font_family(&mut self, name: String, window: &mut Window, cx: &mut Context) { + pub(crate) fn commit_ui_font_family( + &mut self, + name: String, + window: &mut Window, + cx: &mut Context, + ) { let family = (name != crate::ui::settings::ui_font_default_label()).then_some(name); let cfg = cx.global_mut::(); if cfg.ui_font_family == family { @@ -6984,14 +6561,6 @@ impl Tty7App { fn reload_from_config(&mut self, window: &mut Window, cx: &mut Context) { apply_theme(Some(window), cx); - self.sync_window_opacity_slider(window, cx); - // Another window — or a hand edit / config sync picked up by the - // `Config` watcher — can change the backdrop while this window's - // settings panel is open. The window itself already switched - // material above, so the dropdown has to follow or it contradicts - // what it describes. - #[cfg(target_os = "windows")] - self.sync_window_backdrop_select(window, cx); let config = cx.global::().clone(); if config.cursor_style != self.terminal_cursor_style || config.scrollback_limit != self.terminal_scrollback_limit @@ -7614,6 +7183,11 @@ impl Tty7App { return; }; + if let Some(s) = self.settings.as_mut() { + s.agent_busy.insert(agent); + s.agent_touched.insert(agent); + } + cx.notify(); crate::ui::host_ops::HostOps::run( host, cx, @@ -7632,6 +7206,7 @@ impl Tty7App { }, move |this, result, cx| { if let Some(s) = this.settings.as_mut() { + s.agent_busy.remove(&agent); s.agent_hooks_note = Some(( agent, match result { @@ -7691,6 +7266,7 @@ impl Tty7App { self.record_gen = self.record_gen.wrapping_add(1); if let Some(s) = self.active_settings_mut() { s.rebinding_note = None; + s.kb_conflict = None; s.recording = Some(Recording { action, chords: Vec::new(), @@ -7776,7 +7352,54 @@ impl Tty7App { return; }; self.stop_recording(cx); - self.assign_keybinding(action, chords.join(" "), cx); + let spec = chords.join(" "); + // A chord another action answers to is not taken silently: the row + // asks whether to take it over, and only Replace moves it. + if let Some(other) = Self::keybinding_owner(&action, &spec, cx) { + if let Some(s) = self.active_settings_mut() { + s.kb_conflict = Some(crate::ui::settings::KeyConflict { + action, + spec, + other, + }); + } + cx.notify(); + return; + } + self.assign_keybinding(action, spec, cx); + } + + /// The other action that already answers to `spec`, if any. + fn keybinding_owner(action: &str, spec: &str, cx: &App) -> Option { + use crate::ui::keymap::same_chord; + crate::ui::keymap::effective_chords(cx) + .into_iter() + .find(|(a, chords)| a != action && chords.iter().any(|k| same_chord(k, spec))) + .map(|(a, _)| a) + .or_else(|| { + crate::ui::keymap::extra_bindings(cx) + .into_iter() + .find(|(a, k)| a != action && same_chord(k, spec)) + .map(|(a, _)| a) + }) + } + + /// Takes the conflicting chord over, as the row's Replace button says. + pub(crate) fn resolve_keybinding_conflict(&mut self, replace: bool, cx: &mut Context) { + let Some(conflict) = self + .active_settings_mut() + .and_then(|s| s.kb_conflict.take()) + else { + return; + }; + if replace { + self.assign_keybinding(conflict.action, conflict.spec, cx); + if let Some(s) = self.active_settings_mut() { + // The row already said what Replace would do. + s.rebinding_note = None; + } + } + cx.notify(); } fn stop_recording(&mut self, cx: &mut Context) { @@ -7892,36 +7515,7 @@ impl Tty7App { cx.notify(); } - pub(crate) fn restore_default_keybindings( - &mut self, - window: &mut Window, - cx: &mut Context, - ) { - // Nothing here is recoverable: the overrides are dropped from config - // and the only record of them was the config. - if cx.global::().keybindings.is_empty() { - return; - } - let answer = window.prompt( - PromptLevel::Warning, - t(crate::ui::i18n::L10nKey::SettingsRestoreAllDefaults), - Some(t(crate::ui::i18n::L10nKey::SettingsRestoreAllDefaultsBody)), - &crate::ui::confirm_answers( - t(crate::ui::i18n::L10nKey::SettingsRestoreAllDefaults), - t(crate::ui::i18n::L10nKey::Cancel), - ), - cx, - ); - cx.spawn_in(window, async move |this, cx| { - let Ok(0) = answer.await else { return }; - let _ = this.update(cx, |this, cx| { - this.restore_default_keybindings_confirmed(cx) - }); - }) - .detach(); - } - - fn restore_default_keybindings_confirmed(&mut self, cx: &mut Context) { + pub(crate) fn restore_default_keybindings_confirmed(&mut self, cx: &mut Context) { self.update_config(cx, |cfg| cfg.keybindings.clear()); crate::ui::keymap::rebind(cx); if let Some(s) = self.active_settings_mut() { @@ -11148,16 +10742,46 @@ mod keybinding_gpui_tests { } } + /// Waits for the row to ask about a chord another action has, checks who + /// it names, and answers Replace. + fn replace_conflict(app: &Entity, vcx: &mut VisualTestContext, owner: &str) { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + loop { + vcx.background_executor.run_until_parked(); + let other = app.update_in(vcx, |app, _, _| { + app.active_settings() + .and_then(|s| s.kb_conflict.as_ref().map(|c| c.other.clone())) + }); + if let Some(other) = other { + assert_eq!( + other, owner, + "the conflict names the action that has the chord" + ); + break; + } + assert!( + std::time::Instant::now() < deadline, + "recording a taken chord never asked about it" + ); + std::thread::sleep(std::time::Duration::from_millis(20)); + } + app.update_in(vcx, |app, _, cx| app.resolve_keybinding_conflict(true, cx)); + } + #[gpui::test] fn recording_a_shortcut_writes_the_override_and_ends_capture(cx: &mut TestAppContext) { let (app, mut vcx) = harness(cx); begin_capture(&app, &mut vcx, "NewTab"); - vcx.simulate_keystrokes("secondary-shift-n"); + vcx.simulate_keystrokes("secondary-shift-f9"); // A list, because recording a shortcut on the Settings page *sets* it: // the row showed one chord and now shows another. A bare string in // config adds a chord beside the default (#868), which is not what // the person at the row just did. - wait_for_binding(&mut vcx, "NewTab", serde_json::json!(["secondary-shift-n"])); + wait_for_binding( + &mut vcx, + "NewTab", + serde_json::json!(["secondary-shift-f9"]), + ); let recording = app.update_in(&mut vcx, |app, _, _| { app.active_settings().map(|s| s.recording.is_some()) @@ -11194,6 +10818,7 @@ mod keybinding_gpui_tests { }); begin_capture(&app, &mut vcx, "NewTab"); vcx.simulate_keystrokes("secondary-alt-n"); + replace_conflict(&app, &mut vcx, "NextTab"); wait_for_binding(&mut vcx, "NewTab", serde_json::json!(["secondary-alt-n"])); // Emptying the other action was right when an action had one chord. // With two, it would take Ctrl+Tab away as well, for a keystroke that @@ -11206,17 +10831,10 @@ mod keybinding_gpui_tests { let (app, mut vcx) = harness(cx); begin_capture(&app, &mut vcx, "NewTab"); vcx.simulate_keystrokes("alt-enter"); + // The row names the action that would lose the chord before it does. + replace_conflict(&app, &mut vcx, "InsertNewline"); wait_for_binding(&mut vcx, "NewTab", serde_json::json!(["alt-enter"])); wait_for_binding(&mut vcx, "InsertNewline", serde_json::json!([])); - - let note = app.update_in(&mut vcx, |app, _, _| { - app.active_settings().and_then(|s| s.rebinding_note.clone()) - }); - assert!( - note.as_deref() - .is_some_and(|n| n.contains("Insert Newline")), - "the takeover note must name the action that lost the chord (got {note:?})" - ); } /// #901, the half that happens in the UI: Alt+1…9 belongs to vim, and the diff --git a/src/ui/assets.rs b/src/ui/assets.rs index 2bf9e9ab..2b15848b 100644 --- a/src/ui/assets.rs +++ b/src/ui/assets.rs @@ -47,6 +47,36 @@ fn agent_icon(path: &str) -> Option<&'static [u8]> { "icons/machine-local.svg" => include_bytes!("../../assets/icons/machine-local.svg"), "icons/machine-remote.svg" => include_bytes!("../../assets/icons/machine-remote.svg"), "icons/refresh.svg" => include_bytes!("../../assets/icons/refresh.svg"), + "icons/settings/about.svg" => include_bytes!("../../assets/icons/settings/about.svg"), + "icons/settings/appearance.svg" => { + include_bytes!("../../assets/icons/settings/appearance.svg") + } + "icons/settings/back.svg" => include_bytes!("../../assets/icons/settings/back.svg"), + "icons/settings/check.svg" => include_bytes!("../../assets/icons/settings/check.svg"), + "icons/settings/chevron-down.svg" => { + include_bytes!("../../assets/icons/settings/chevron-down.svg") + } + "icons/settings/chevron-right.svg" => { + include_bytes!("../../assets/icons/settings/chevron-right.svg") + } + "icons/settings/close.svg" => include_bytes!("../../assets/icons/settings/close.svg"), + "icons/settings/general.svg" => include_bytes!("../../assets/icons/settings/general.svg"), + "icons/settings/integrations.svg" => { + include_bytes!("../../assets/icons/settings/integrations.svg") + } + "icons/settings/keyboard.svg" => include_bytes!("../../assets/icons/settings/keyboard.svg"), + "icons/settings/machine-local.svg" => { + include_bytes!("../../assets/icons/settings/machine-local.svg") + } + "icons/settings/machine-remote.svg" => { + include_bytes!("../../assets/icons/settings/machine-remote.svg") + } + "icons/settings/more.svg" => include_bytes!("../../assets/icons/settings/more.svg"), + "icons/settings/plus.svg" => include_bytes!("../../assets/icons/settings/plus.svg"), + "icons/settings/search.svg" => include_bytes!("../../assets/icons/settings/search.svg"), + "icons/settings/ssh.svg" => include_bytes!("../../assets/icons/settings/ssh.svg"), + "icons/settings/terminal.svg" => include_bytes!("../../assets/icons/settings/terminal.svg"), + "icons/settings/window.svg" => include_bytes!("../../assets/icons/settings/window.svg"), "icons/agents/claude.svg" => include_bytes!("../../assets/icons/agents/claude.svg"), "icons/agents/codex.svg" => include_bytes!("../../assets/icons/agents/codex.svg"), "icons/agents/traecli.svg" => include_bytes!("../../assets/icons/agents/traecli.svg"), diff --git a/src/ui/forwards.rs b/src/ui/forwards.rs index c1c9fde4..a8385466 100644 --- a/src/ui/forwards.rs +++ b/src/ui/forwards.rs @@ -463,8 +463,7 @@ impl Tty7App { ) }) .when(advanced, |form| { - form.child(self.segmented_on( - sf, + form.child(self.segmented( "ssh-managed-forward-kind", &[ t(L10nKey::ForwardLocal), diff --git a/src/ui/i18n/en.rs b/src/ui/i18n/en.rs index e2107e59..7966e063 100644 --- a/src/ui/i18n/en.rs +++ b/src/ui/i18n/en.rs @@ -2,6 +2,74 @@ use super::L10nKey; pub fn translate_en(key: L10nKey) -> &'static str { match key { + L10nKey::SettingsNoMatchesShort => "No matches", + L10nKey::SettingsModifiedTitle => "Modified", + L10nKey::SettingsMatchCount => "{count} matches", + L10nKey::SettingsNothingModified => "Nothing changed from defaults", + L10nKey::SettingsKeyThen => "then", + L10nKey::SettingsStartupRestore => "Startup & restore", + L10nKey::SettingsSettingsFile => "Settings file", + L10nKey::SettingsReveal => "Reveal", + L10nKey::SettingsThemeModeSystem => "System", + L10nKey::SettingsThemeModeSystemDesc => { + "Match the system, switching between a light and a dark theme." + } + L10nKey::SettingsThemeModeLightDesc => "Always use a light theme.", + L10nKey::SettingsThemeModeDarkDesc => "Always use a dark theme.", + L10nKey::SettingsThemeSlotLightDesc => "Used while the system is in light mode.", + L10nKey::SettingsThemeSlotDarkDesc => "Used while the system is in dark mode.", + L10nKey::SettingsThemeSlotDesc => "Theme for the terminal and interface.", + L10nKey::SettingsLightThemeLabel => "Light theme", + L10nKey::SettingsDarkThemeLabel => "Dark theme", + L10nKey::SettingsNoThemesMatch => "No themes match", + L10nKey::SettingsRestoreChanged => "Restore {count} changed", + L10nKey::SettingsShortcutsHint => { + "Click a shortcut and press new keys. Press a second chord right after to make a sequence. Esc cancels, ⌫ clears." + } + L10nKey::SettingsShortcutsHintTmux => { + "tmux preset: pane and tab actions use a prefix key. Click a shortcut to change it; Esc cancels, ⌫ clears." + } + L10nKey::SettingsShortcutConflict => { + "{keys} is already used by “{action}”. Replacing takes it from there." + } + L10nKey::SettingsReplace => "Replace", + L10nKey::SettingsNoActionsMatch => "No actions match “{query}”", + L10nKey::SettingsSearchShortcuts => "Search actions or keys", + L10nKey::SettingsHostsDesc => "Recently used hosts. Search to find any saved host.", + L10nKey::SettingsAddHost => "Add host", + L10nKey::SettingsNoHostsMatch => "No hosts match “{query}”", + L10nKey::SettingsHostsFromFiles => "{count} hosts from {files} sources", + L10nKey::SettingsMoreHosts => "{count} more hosts", + L10nKey::SettingsShowRecentOnly => "Show recent only", + L10nKey::SettingsShowAll => "Show all", + L10nKey::SettingsUnsaved => "Unsaved", + L10nKey::SettingsNever => "Never", + L10nKey::SettingsDefinedIn => "Defined in", + L10nKey::SettingsConnectInNewTab => "Connect in new tab", + L10nKey::SettingsCopied => "Copied", + L10nKey::SettingsCopySshCommand => "Copy ssh command", + L10nKey::SettingsStoredInTty7 => "Stored in tty7 settings", + L10nKey::SettingsClickAgainToRemove => "Click again to remove", + L10nKey::SettingsRemoveHost => "Remove host", + L10nKey::SettingsEditHost => "Edit", + L10nKey::SettingsLive => "Connected", + L10nKey::SettingsPressKeysShort => "Press keys…", + L10nKey::SettingsSearchAgents => "Search agents", + L10nKey::SettingsConnectedMachines => "Connected", + L10nKey::SettingsInstalledCount => "{count} installed", + L10nKey::SettingsMachine => "Machine", + L10nKey::SettingsMachineLocalDesc => { + "Hooks are installed per machine. Remote machines appear here while connected." + } + L10nKey::SettingsMachineRemoteDesc => "Installing over the active connection to {name}.", + L10nKey::SettingsAgentsInstalledSummary => "{count} of {total} installed", + L10nKey::SettingsNoAgentsInstalled => "No agent hooks installed on this machine yet.", + L10nKey::SettingsNoAgentsMatch => "No agents match “{query}”", + L10nKey::SettingsMoreAgents => "{count} more agents available", + L10nKey::SettingsShowInstalledOnly => "Show installed only", + L10nKey::SettingsWorking => "Working…", + L10nKey::SettingsUpdateAvailable => "Update available", + L10nKey::SettingsRevealHookFile => "Reveal hook file", L10nKey::SettingsSaveError => "Changes could not be saved: {error}", L10nKey::SettingsRetrySave => "Retry saving", @@ -102,41 +170,26 @@ pub fn translate_en(key: L10nKey) -> &'static str { L10nKey::Download => "Download", L10nKey::Link => "Link", L10nKey::SettingsThemeIntroTitle => "Theme", - L10nKey::SettingsThemeIntroDesc => { - "Pick a color theme. Each one sets its own light or dark look." - } + L10nKey::SettingsThemeIntroDesc => "Each theme sets its own light or dark look.", L10nKey::SettingsTypography => "Typography", L10nKey::SettingsFontSize => "Terminal font size", L10nKey::SettingsFontSizeDesc => "Terminal text size in pixels.", L10nKey::SettingsUiFontSize => "Interface font size", - L10nKey::SettingsUiFontSizeDesc => { - "Text size everywhere outside the terminal — tabs, panels and settings. \ - Raise it on a display that is not Retina." - } + L10nKey::SettingsUiFontSizeDesc => "Text size for tabs, panels and settings.", L10nKey::SettingsUiFontFamily => "Interface font", - L10nKey::SettingsUiFontFamilyDesc => { - "Face used for tabs, sidebars, dialogs and settings; Default uses the system UI font." - } + L10nKey::SettingsUiFontFamilyDesc => "For tabs, sidebars, dialogs and settings.", L10nKey::SettingsLineHeight => "Line height", L10nKey::SettingsLineHeightDesc => "Row spacing as a multiple of the font size.", L10nKey::SettingsFontFamily => "Terminal font", L10nKey::SettingsFontFamilyDesc => "Pick from fonts installed on your system.", L10nKey::SettingsBoldFont => "Bold font", - L10nKey::SettingsBoldFontDesc => { - "Face for bold text; Default synthesizes it from the primary." - } + L10nKey::SettingsBoldFontDesc => "Bold face; Default derives it from the main font.", L10nKey::SettingsItalicFont => "Italic font", - L10nKey::SettingsItalicFontDesc => { - "Face for italic text; Default synthesizes it from the primary." - } + L10nKey::SettingsItalicFontDesc => "Italic face; Default derives it from the main font.", L10nKey::SettingsFontLigatures => "Font ligatures", - L10nKey::SettingsFontLigaturesDesc => { - "Enable common programming ligature features for terminal text." - } + L10nKey::SettingsFontLigaturesDesc => "Programming ligatures in terminal text.", L10nKey::SettingsFontThicken => "Thicken strokes", - L10nKey::SettingsFontThickenDesc => { - "macOS font smoothing: draws text a little bolder, light text most. Takes effect after restarting tty7." - } + L10nKey::SettingsFontThickenDesc => "Draw text slightly bolder. Applies after a restart.", L10nKey::SettingsCursor => "Cursor", L10nKey::SettingsCursorShape => "Cursor shape", L10nKey::SettingsCursorShapeDesc => "How the terminal cursor is drawn.", @@ -150,9 +203,7 @@ pub fn translate_en(key: L10nKey) -> &'static str { L10nKey::SettingsSearchLanguageKeywords => "language, locale, english, chinese", L10nKey::SettingsTransparency => "Transparency", L10nKey::SettingsOpacity => "Opacity", - L10nKey::SettingsOpacityDesc => { - "How opaque the window background is, for every theme. Below 100% the desktop shows through." - } + L10nKey::SettingsOpacityDesc => "Below 100%, the desktop shows through.", L10nKey::SettingsBlur => "Blur", L10nKey::SettingsBlurDesc => { if cfg!(target_os = "macos") { @@ -161,13 +212,9 @@ pub fn translate_en(key: L10nKey) -> &'static str { "Blur whatever is behind a translucent window. Needs a compositor that offers it — KDE Plasma does; GNOME and plain X11 leave the window merely transparent." } } - L10nKey::SettingsBlurAutoDesc => { - "Blur whatever is behind a translucent window. Only applies while Background material is Auto." - } + L10nKey::SettingsBlurAutoDesc => "Blur behind a translucent window. Auto material only.", L10nKey::SettingsBackdrop => "Background material", - L10nKey::SettingsBackdropDesc => { - "Native Windows backdrop behind a translucent window. Mica needs Windows 11 22H2, Acrylic needs 1809; older builds fall back automatically." - } + L10nKey::SettingsBackdropDesc => "Native backdrop behind a translucent window.", L10nKey::SettingsSearchBackdropKeywords => { "material backdrop mica acrylic blur frosted window background" } @@ -180,7 +227,7 @@ pub fn translate_en(key: L10nKey) -> &'static str { L10nKey::FollowTheme => "Follow theme", L10nKey::SettingsDimInactivePanes => "Dim inactive panes", L10nKey::SettingsDimInactivePanesDesc => { - "Fade unfocused panes in a split so the active one stands out." + "Fade unfocused panes so the active one stands out." } L10nKey::SettingsOpenThemesFolder => "Open themes folder", L10nKey::SettingsChangeThemeImage => "Change…", @@ -192,7 +239,7 @@ pub fn translate_en(key: L10nKey) -> &'static str { } L10nKey::SettingsEditTheme => "Edit theme", L10nKey::SettingsEditThemeIntro => { - "You're editing a copy. Changes save to its file in the themes folder and apply live." + "Editing a copy. Changes apply live and save to its file." } L10nKey::SettingsBackgroundImage => "Background image", L10nKey::SettingsBackgroundImageDesc => { @@ -207,7 +254,7 @@ pub fn translate_en(key: L10nKey) -> &'static str { L10nKey::ExplorerMenuOpenIn => "Open in tty7", L10nKey::ExplorerMenuOpenHere => "Open tty7 here", L10nKey::SettingsCustomThemesIntro => { - "Duplicate a theme to edit its colors, or drop a tty7 YAML theme or iTerm2 .itermcolors file in the themes folder." + "Duplicate a theme to edit it, or drop a YAML or .itermcolors file into the themes folder." } L10nKey::SettingsDuplicateToEdit => "Duplicate to edit", L10nKey::SettingsHosts => "Hosts", @@ -226,9 +273,7 @@ pub fn translate_en(key: L10nKey) -> &'static str { L10nKey::SettingsMoreInSshConfig => "{count} more in ~/.ssh/config", L10nKey::SettingsAliasesLinked => "{count} aliases linked.", L10nKey::SettingsImportAliases => "Import aliases", - L10nKey::SettingsImportAliasesDesc => { - "Re-reads the file and adds anything new. Edits you make here are stored by tty7 — the file itself is never written." - } + L10nKey::SettingsImportAliasesDesc => "Re-read the file and add anything new.", L10nKey::SettingsImportNow => "Import now", L10nKey::SettingsImportUnreadable => "Could not read {path} — nothing was imported.", L10nKey::SettingsImportNoHosts => { @@ -242,7 +287,7 @@ pub fn translate_en(key: L10nKey) -> &'static str { } L10nKey::SettingsImportMoreOptions => "+{count} more", L10nKey::SettingsDefaultsIntro => { - "Every host starts from these. Any host can override one under its own Advanced." + "Every host starts here; override any under its Advanced." } L10nKey::SettingsCopyAddress => "Copy Address", L10nKey::SettingsDuplicate => "Duplicate", @@ -265,16 +310,14 @@ pub fn translate_en(key: L10nKey) -> &'static str { "Could not forget the saved password for {endpoint}: {error}" } L10nKey::SettingsSecurity => "Security", - L10nKey::SettingsSecurityIntro => { - "A host can override either of these under its own Advanced." - } + L10nKey::SettingsSecurityIntro => "Any host can override these under its Advanced.", L10nKey::SettingsVerifyHostKeys => "Verify host keys", L10nKey::SettingsVerifyHostKeysDesc => { - "Check each server's key against known_hosts before connecting. Off skips the check, so a spoofed server would go unnoticed." + "Check server keys against known_hosts. Off, a spoofed server goes unnoticed." } L10nKey::WarnBeforeClosing => "Warn before closing", L10nKey::SettingsWarnBeforeClosingDesc => { - "Ask for confirmation before closing a tab or pane with a live SSH session." + "Confirm before closing a tab with a live SSH session." } L10nKey::SettingsNewHost => "New host", L10nKey::SettingsDiscardChangesTitle => "Discard unsaved changes?", @@ -288,7 +331,7 @@ pub fn translate_en(key: L10nKey) -> &'static str { L10nKey::SettingsPortInvalid => "Port must be 1-65535 — blank means 22.", L10nKey::SettingsUser => "User", L10nKey::SettingsAuth => "Auth", - L10nKey::SettingsAuthDesc => "Authentication method. Auto tries every applicable method.", + L10nKey::SettingsAuthDesc => "Auto tries every applicable method.", L10nKey::SettingsAuthModeAuto => "Auto", L10nKey::SettingsAuthModePassword => "Password", L10nKey::SettingsAuthModeKey => "Key", @@ -313,9 +356,7 @@ pub fn translate_en(key: L10nKey) -> &'static str { "Could not save the passphrase for {key}: {error}" } L10nKey::SettingsJumpHost => "Jump host", - L10nKey::SettingsJumpHostDesc => { - "Name of another profile to tunnel through (blank = direct)." - } + L10nKey::SettingsJumpHostDesc => "Profile to tunnel through; blank connects directly.", L10nKey::SettingsJumpHostUnknown => "No host profile named {jump_name} — won't be saved.", L10nKey::SettingsJumpHostSelf => "A host can't be its own jump host — won't be saved.", L10nKey::SettingsNoneSummary => "(none)", @@ -342,7 +383,7 @@ pub fn translate_en(key: L10nKey) -> &'static str { L10nKey::SettingsGroupSecurity => "Security", L10nKey::SettingsRemoteClipboardWrite => "Remote clipboard images", L10nKey::SettingsRemoteClipboardWriteDesc => { - "Allow programs on this host to replace the local clipboard with images over OSC 5522." + "Let this host put images on your clipboard (OSC 5522)." } L10nKey::SettingsIdentityFiles => "Identity files", L10nKey::SettingsIdentityFilesDesc => "Private-key paths, one per line (%h/%r expand).", @@ -408,7 +449,7 @@ pub fn translate_en(key: L10nKey) -> &'static str { } L10nKey::SettingsShellIntegration => "Shell integration", L10nKey::SettingsShellIntegrationDesc => { - "Let the remote shell report prompts, exit codes, and the working directory." + "Remote shell reports prompts, exit codes and directory." } L10nKey::SettingsLoginScripts => "Login scripts", L10nKey::SettingsLoginScriptsDesc => "Commands sent after the shell opens, one per line.", @@ -421,24 +462,16 @@ pub fn translate_en(key: L10nKey) -> &'static str { L10nKey::SettingsOn => "On", L10nKey::SettingsOff => "Off", L10nKey::SettingsShell => "Shell", - L10nKey::SettingsShellIntro => { - "The program each new terminal launches. Leave Shell program empty to use the platform default ({default})." - } + L10nKey::SettingsShellIntro => "The program new terminals launch. Empty uses {default}.", L10nKey::SettingsProgram => "Shell program", - L10nKey::SettingsProgramDesc => { - "Executable name on PATH or an absolute path (e.g. zsh, fish, pwsh)." - } + L10nKey::SettingsProgramDesc => "A name on PATH or an absolute path, e.g. zsh, fish.", L10nKey::SettingsArguments => "Shell arguments", - L10nKey::SettingsArgumentsDesc => { - "Launch flags, split like a command line — quote anything containing spaces (e.g. -l, or -c \"echo hi\")." - } + L10nKey::SettingsArgumentsDesc => "Split like a command line, e.g. -l or -c \"echo hi\".", L10nKey::SettingsArgumentsInvalid => { "The quotes do not balance — this value was not saved." } L10nKey::SettingsStartIn => "Starting directory", - L10nKey::SettingsStartInDesc => { - "What a fresh shell starts in: tty7's launch directory, your home folder, or a fixed path." - } + L10nKey::SettingsStartInDesc => "Launch directory, home folder, or a fixed path.", L10nKey::SettingsCustomPath => "Custom path", L10nKey::SettingsCustomPathDesc => "The directory new shells start in.", L10nKey::SettingsWdInherit => "Inherit", @@ -448,7 +481,7 @@ pub fn translate_en(key: L10nKey) -> &'static str { "That directory does not exist — the value was not saved." } L10nKey::SettingsShellFooter => { - "Applies to shells with nothing to inherit, like a window's first tab. New tabs and splits still inherit the active pane's directory; open shells keep running." + "Only for shells with nothing to inherit, like a window's first tab. New tabs and splits take the active pane's directory." } L10nKey::SettingsScrolling => "Scrolling", L10nKey::SettingsScrollback => "Scrollback buffer", @@ -457,45 +490,37 @@ pub fn translate_en(key: L10nKey) -> &'static str { L10nKey::SettingsScrollSpeedDesc => "Multiplier applied to mouse-wheel scrolling.", L10nKey::SettingsSmoothScroll => "Smooth scrolling", L10nKey::SettingsSmoothScrollDesc => { - "Ease each wheel notch into place instead of jumping the whole way at once. \ - Trackpads scroll continuously already and are unaffected." + "Ease each wheel notch into place. Trackpads are unaffected." } L10nKey::SettingsMouse => "Mouse", L10nKey::SettingsFocusFollowsMouse => "Focus follows mouse", L10nKey::SettingsFocusFollowsMouseDesc => "Hovering a pane focuses it without a click.", L10nKey::SettingsHideMouseWhileTyping => "Hide mouse while typing", L10nKey::SettingsHideMouseWhileTypingDesc => { - "Hide the pointer as you type; it returns on the next move." + "Hide the pointer while typing; moving brings it back." } L10nKey::SettingsMouseZoom => "Zoom with the wheel", - L10nKey::SettingsMouseZoomDesc => { - "Modifier that makes the mouse wheel resize the terminal font instead of scrolling." - } + L10nKey::SettingsMouseZoomDesc => "Hold it and scroll to resize the terminal font.", L10nKey::SettingsMouseZoomOff => "Off", L10nKey::SettingsReportMouseToApps => "Report mouse to apps", L10nKey::SettingsReportMouseToAppsDesc => { - "Let full-screen apps (vim, tmux) handle clicks and scrolling; hold Shift to keep a gesture local. \ - Off keeps clicks from reaching them and turns the wheel into arrow keys." + "Let vim, tmux and other apps handle clicks; Shift keeps it local." } L10nKey::SettingsBell => "Bell", L10nKey::SettingsTerminalBell => "Terminal bell", - L10nKey::SettingsTerminalBellDesc => { - "How a bell (^G) is signalled: silenced, a brief flash, the system sound, or both." - } + L10nKey::SettingsTerminalBellDesc => "How a bell (^G) is signalled.", L10nKey::SettingsLinks => "Links", L10nKey::DetectUrls => "Detect URLs", - L10nKey::SettingsDetectUrlsDesc => { - "Underline links on hover and open them on {modifier}-click." - } + L10nKey::SettingsDetectUrlsDesc => "Underline links on hover; {modifier}-click opens them.", L10nKey::ForwardSshLoopbackLinks => "Forward remote ports", L10nKey::SettingsForwardSshLoopbackLinksDesc => { - "Over SSH, forward the ports a pane starts serving and open its localhost links here." + "Open a remote pane's localhost links here." } L10nKey::SettingsOpenFilesInternal => "Built-in editor", L10nKey::SettingsOpenFilesSystem => "Default app", L10nKey::SettingsOpenFilesCommand => "Command", L10nKey::SettingsOpenFilesModeDesc => { - "What a {modifier}-clicked file link opens. Only the built-in editor can jump to a line or open a file on a remote host." + "What {modifier}-clicking a file link opens. Only the built-in editor jumps to a line or opens remote files." } L10nKey::LinkFileNotUnder => "{path} — nothing by that name under {dir}", L10nKey::LinkFileNoDirectory => { @@ -507,7 +532,7 @@ pub fn translate_en(key: L10nKey) -> &'static str { } L10nKey::OpenFilesWith => "Open files with", L10nKey::SettingsOpenFilesWithDesc => { - "Command run when {modifier}-clicking a file link. Use {path}, {line}, {column} — a flag whose value is missing is dropped. Empty uses the default app." + "Use {path}, {line}, {column}. Empty uses the default app." } L10nKey::SettingsBellModeOff => "Off", L10nKey::SettingsBellModeVisual => "Visual", @@ -515,27 +540,27 @@ pub fn translate_en(key: L10nKey) -> &'static str { L10nKey::SettingsBellModeBoth => "Both", L10nKey::SettingsPrompt => "Prompt & command history", L10nKey::SettingsPromptIntro => { - "tty7's own editor and menus at the shell prompt. Turn one off to hand that much back to the shell." + "tty7's own editor and menus at the prompt. Turn one off to use the shell's." } L10nKey::SettingsPromptEditor => "tty7 prompt editor", L10nKey::SettingsPromptEditorDesc => { - "tty7 edits the line you type at the shell prompt: selection, undo, and the menus below. Off hands the prompt back to the shell's own editor — ZLE, readline, fish." + "Selection, undo and menus on the line you type. Off hands it back to ZLE, readline or fish." } L10nKey::SettingsNeedsPromptEditor => { "Needs the prompt editor: with it off, this key already belongs to the shell." } L10nKey::SettingsTabCompletion => "Tab completion", L10nKey::SettingsTabCompletionDesc => { - "Tab at the prompt opens tty7's completion menu. When off, Tab goes to the shell's own completion instead." + "Tab opens tty7's completion menu. Off, Tab goes to the shell." } L10nKey::SettingsHistorySearch => "Command history search", L10nKey::SettingsHistorySearchDesc => { - "⌃R at the prompt opens tty7's fuzzy history menu. Off sends ⌃R to the shell — its own reverse-i-search, or whatever you bound there (fzf, percol)." + "⌃R opens tty7's fuzzy history search. Off, ⌃R goes to the shell." } L10nKey::SettingsSelectionClipboard => "Selection & clipboard", L10nKey::SettingsSmartSelection => "Smart selection", L10nKey::SettingsSmartSelectionDesc => { - "Double-click selects the whole URL, file path, email, or bracket pair under the cursor." + "Double-click selects a whole URL, path or bracket pair." } L10nKey::SettingsCopyOnSelect => "Copy on select", L10nKey::SettingsCopyOnSelectDesc => { @@ -551,12 +576,10 @@ pub fn translate_en(key: L10nKey) -> &'static str { } L10nKey::SettingsKeyboard => "Keyboard", L10nKey::SettingsOptionAsMeta => "Option (⌥) acts as Meta", - L10nKey::SettingsOptionAsMetaDesc => { - "⌥+key sends the escape chord shells expect (⌥B = back one word) instead of typing a special character (∫)." - } - L10nKey::SettingsAgentsIntro => "AI agents", + L10nKey::SettingsOptionAsMetaDesc => "⌥+key sends Meta, e.g. ⌥B moves back a word.", + L10nKey::SettingsAgentsIntro => "Agent hooks", L10nKey::SettingsAgentsIntroDesc => { - "Hooks give panes running these agents live status (working / waiting / done) in the tab bar. Only inside tty7." + "Hooks show each agent's status — working, waiting, done — in the tab bar." } L10nKey::SettingsReadingAgentConfig => "Reading this machine's agent config…", L10nKey::SettingsStatusNotInstalled => "Not installed", @@ -569,14 +592,10 @@ pub fn translate_en(key: L10nKey) -> &'static str { L10nKey::SettingsOfflineMachines => { "{count} more saved machines are not connected — open a workspace on one to install its hooks there." } - L10nKey::SettingsSyncWithSystem => "Sync with system", - L10nKey::SettingsSyncWithSystemDesc => { - "Follow the OS appearance with separate light and dark themes." - } + L10nKey::SettingsSyncWithSystem => "Appearance", + L10nKey::SettingsSyncWithSystemDesc => "Separate light and dark themes that follow the OS.", L10nKey::SettingsLegiblePalette => "Legible bright colors", - L10nKey::SettingsLegiblePaletteDesc => { - "Automatically brighten or darken bright ANSI colors that would be unreadable on the theme background." - } + L10nKey::SettingsLegiblePaletteDesc => "Fix bright ANSI colors that are hard to read.", L10nKey::SettingsChangeTheme => "Change theme", L10nKey::SettingsThemes => "Themes", L10nKey::SettingsThemesCloseTooltip => "Close Themes (Esc)", @@ -595,37 +614,31 @@ pub fn translate_en(key: L10nKey) -> &'static str { L10nKey::SettingsStartupWindowDesc => "Window state when tty7 launches.", L10nKey::SettingsRememberWindowSize => "Remember window size & position", L10nKey::SettingsRememberWindowSizeDesc => { - "Reopen at the size and position the window had when tty7 last quit. Off opens centered at the default size." + "Reopen where the window was when tty7 last quit." } L10nKey::SettingsRestoreLastLayout => "Restore last layout", L10nKey::SettingsRestoreLastLayoutDesc => { - "Reopen the last window's tabs, splits, and directories on launch. Off starts with a single fresh terminal." + "Reopen last session's tabs, splits and directories." } L10nKey::SettingsShowTrayIcon => "Show tray icon", - L10nKey::SettingsShowTrayIconDesc => { - "A status item in the tray / menu bar: it signals when an agent needs input, and its menu jumps to agent panes." - } + L10nKey::SettingsShowTrayIconDesc => "Alerts when an agent needs input; jumps to its pane.", L10nKey::SettingsTabs => "Tabs", L10nKey::SettingsNewTabPosition => "New tab position", L10nKey::SettingsNewTabPositionDesc => "Where a freshly opened tab is inserted.", L10nKey::SettingsTabBarPosition => "Tab bar position", - L10nKey::SettingsTabBarPositionDesc => { - "Show tabs as a horizontal strip on top or a vertical sidebar on the left." - } + L10nKey::SettingsTabBarPositionDesc => "A strip on top or a sidebar on the left.", L10nKey::SettingsSidebarGrouping => "Sidebar grouping", L10nKey::SettingsSidebarGroupingDesc => { - "Group sidebar tabs by git repository. Tabs outside a repo collect under Scratch, or under their working directory with \"By repo or folder\". Left sidebar only." + "Group tabs by git repository; others go under Scratch." } L10nKey::SettingsDiffPreviewFromCounts => "Open diff preview from sidebar counts", - L10nKey::SettingsDiffPreviewFromCountsDesc => { - "Click a row's +N −N to open the working-tree diff in an overlay. Off leaves the counts visible, just not clickable." - } + L10nKey::SettingsDiffPreviewFromCountsDesc => "Click a row's +N −N to open its diff.", L10nKey::DocumentDock => "Dock beside terminal", L10nKey::DocumentFill => "Fill window", L10nKey::SettingsNotifications => "Notifications", L10nKey::SettingsNotifyOnCommandFinish => "Notify on command finish", L10nKey::SettingsNotifyOnCommandFinishDesc => { - "Desktop alert after a long foreground command completes." + "Alert when a long foreground command finishes." } L10nKey::SettingsNotifyThreshold => "Minimum command duration", L10nKey::SettingsNotifyThresholdDesc => { @@ -646,18 +659,14 @@ pub fn translate_en(key: L10nKey) -> &'static str { L10nKey::SettingsByRepoOrFolder => "By repo or folder", L10nKey::SettingsFlat => "Flat", L10nKey::SettingsPreset => "Preset", - L10nKey::SettingsPresetDesc => { - "tmux remaps pane/tab actions onto prefix sequences (e.g. Ctrl-B then C)." - } + L10nKey::SettingsPresetDesc => "tmux maps pane and tab actions to prefix keys (Ctrl-B C).", L10nKey::SettingsPrefix => "Prefix", L10nKey::SettingsPressKeys => "Press keys… · ⌫ for no shortcut", L10nKey::SettingsPauseToSaveEsc => "pause to save · Esc", L10nKey::SettingsKeybindingsIntroDesc => { - "Click a shortcut, then press the new keys — it saves after a brief pause. Chain keys for a sequence like Ctrl-B then X. Esc cancels; Backspace removes the last key, or, pressed first, leaves the action with no shortcut — Reset brings the default back." - } - L10nKey::SettingsPrefixNote => { - "With a prefix active, a bare prefix key reaches the shell after a ~1s pause, and prefix + an unbound key is sent through to the terminal." + "Click a shortcut and press new keys; chain keys for sequences like Ctrl-B X. Esc cancels, Backspace clears." } + L10nKey::SettingsPrefixNote => "A lone prefix key reaches the shell after ~1s.", L10nKey::SettingsRestoreAllDefaults => "Restore all defaults", L10nKey::SettingsRestoreAllDefaultsBody => { "Every key you have rebound goes back to its default. There is no undo." @@ -670,11 +679,11 @@ pub fn translate_en(key: L10nKey) -> &'static str { L10nKey::KeybindForkSessionDown => "Fork Session Down", L10nKey::KeybindForkSessionUp => "Fork Session Up", L10nKey::SettingsAboutDesc1 => { - "A terminal workbench: persistent sessions, remote work, agents." + "A terminal workbench for long-running work. Sessions outlive the window, remote hosts feel local, and coding agents report their status right in the sidebar." } L10nKey::SettingsDefaultTerminal => "Default terminal", L10nKey::SettingsDefaultTerminalDesc => { - "Make tty7 the macOS default terminal for Unix executables, SSH links, and man-page links. tty7 can also open folders and scripts, but does not replace Finder's folder handler. Apps that choose their own terminal may ignore this setting." + "Open Unix executables, SSH links and man pages in tty7." } L10nKey::SettingsDefaultTerminalSet => "Set as Default Terminal", L10nKey::SettingsDefaultTerminalSetSuccess => { @@ -707,17 +716,17 @@ pub fn translate_en(key: L10nKey) -> &'static str { L10nKey::SettingsUpdateDiscard => "Discard", L10nKey::SettingsAutoDownload => "Download updates in the background", L10nKey::SettingsAutoDownloadDesc => { - "Download and verify a new release as soon as it is found, so installing is just a restart. Nothing installs without asking. Packages are around 30 MB." + "Download updates in the background so installing is just a restart. Nothing installs without asking." } L10nKey::SettingsUpdateChannel => "Update channel", L10nKey::SettingsUpdateChannelDesc => { - "Stable follows published releases. Nightly rebuilds from the latest code every night — newer, but not release-tested." + "Nightly builds the latest code every night, untested." } L10nKey::SettingsUpdateChannelStable => "Stable", L10nKey::SettingsUpdateChannelNightly => "Nightly", L10nKey::SettingsDaemonStale => "tty7 server is still running {build}.", L10nKey::SettingsDaemonStaleDesc => { - "tty7 was updated in place: the app is new, your panes are still served by the old build. Restarting tty7 server picks up the new one and ends everything running in your panes. No hurry — do it when they're idle." + "tty7 was updated, but your panes still run on the old server. Restarting it loads the new build and ends everything running in them." } L10nKey::UpdateDialogTitle => "Update available", L10nKey::UpdateDialogDetail => { @@ -764,22 +773,18 @@ pub fn translate_en(key: L10nKey) -> &'static str { } L10nKey::SettingsVersionAvailable => "Version {version} is available.", L10nKey::SettingsCheckUpdatesDesc => { - "Installations that cannot update in place open the release page instead." + "Opens the release page if tty7 can't update in place." } L10nKey::SettingsCheckUpdatesOnLaunch => "Check for updates on launch", L10nKey::SettingsCommandLine => "Command line", - L10nKey::SettingsCommandLineDesc => { - "Make the bundled tty7 command available to scripts and AI agents. Takes effect on the next launch; turning this off does not remove an existing installation." - } + L10nKey::SettingsCommandLineDesc => "Put the tty7 command on PATH. Applies on next launch.", L10nKey::SettingsInstallCliOnPath => "Install the tty7 command on PATH", L10nKey::SettingsServer => "tty7 server", - L10nKey::SettingsServerDesc => { - "Manages terminal sessions on this computer and keeps them running in the background." - } + L10nKey::SettingsServerDesc => "Keeps terminal sessions running in the background.", L10nKey::SettingsRestartServer => "Restart tty7 server…", L10nKey::SettingsAppHttpProxy => "Proxy for updates", L10nKey::SettingsAppHttpProxyDesc => { - "Used only for tty7's update checks and downloads, not for programs in your panes. Empty follows the system proxy." + "For tty7's update checks. Empty uses the system proxy." } L10nKey::SettingsAppHttpProxyInvalid => { "Not a valid proxy address — this value was not saved." @@ -1756,7 +1761,7 @@ pub fn translate_en(key: L10nKey) -> &'static str { L10nKey::Replace => "Replace", L10nKey::SftpErrorInvalidOctalMode => "invalid octal mode", L10nKey::SettingsDaemonStaleDescInPlace => { - "tty7 was updated in place: the app is new, your panes still run on the old build. tty7 server can swap itself for the new one without stopping, so your shells carry straight over. Panes on tty7's built-in SSH client are the exception — those close and need reopening." + "tty7 was updated. The server can swap itself in place and keep your shells; only built-in SSH panes close." } L10nKey::AppRestartServerBodyInPlace => { "tty7 server swaps itself for this build in place: your shells keep running, and the window reconnects a moment later. Panes on tty7's built-in SSH client are the exception — those close and need reopening." @@ -1766,7 +1771,7 @@ pub fn translate_en(key: L10nKey) -> &'static str { } L10nKey::SettingsPerPaneHistory => "Separate command history per pane", L10nKey::SettingsPerPaneHistoryDescription => { - "Up walks through what you ran in this pane, not every pane interleaved. A new pane starts from your existing history and writes back what it adds when it closes. Applies to bash and zsh panes tty7 can set up; a shell started with your own arguments is left alone." + "↑ walks this pane's own history. bash and zsh only." } L10nKey::IntegrationNoticeBlocked => { "\u{201c}{wrapper}\u{201d} is intercepting shell reports in this pane, so inline completion and the Ctrl+R menu are unavailable. The shell's own history search still works." @@ -1911,6 +1916,18 @@ pub fn translate_en(key: L10nKey) -> &'static str { pub fn translate_variant_en(key: L10nKey, branch: &'static str) -> Option<&'static str> { let res = match (key, branch) { + (L10nKey::SettingsMatchCount, "zero") => "No matches", + (L10nKey::SettingsMatchCount, "one") => "1 match", + (L10nKey::SettingsMatchCount, "other") => "{count} matches", + (L10nKey::SettingsRestoreChanged, "zero") => "Restore changes", + (L10nKey::SettingsRestoreChanged, "one") => "Restore 1 changed", + (L10nKey::SettingsRestoreChanged, "other") => "Restore {count} changed", + (L10nKey::SettingsMoreHosts, "zero") => "No more hosts", + (L10nKey::SettingsMoreHosts, "one") => "1 more host", + (L10nKey::SettingsMoreHosts, "other") => "{count} more hosts", + (L10nKey::SettingsMoreAgents, "zero") => "No more agents", + (L10nKey::SettingsMoreAgents, "one") => "1 more agent available", + (L10nKey::SettingsMoreAgents, "other") => "{count} more agents available", (L10nKey::SettingsAliasesLinked, "zero") => "No aliases linked yet.", (L10nKey::SettingsAliasesLinked, "one") => "1 alias linked.", (L10nKey::SettingsAliasesLinked, "other") => "{count} aliases linked.", diff --git a/src/ui/i18n/ja.rs b/src/ui/i18n/ja.rs index 31949721..bc4930a8 100644 --- a/src/ui/i18n/ja.rs +++ b/src/ui/i18n/ja.rs @@ -2,6 +2,76 @@ use super::L10nKey; pub fn translate_ja(key: L10nKey) -> Option<&'static str> { Some(match key { + L10nKey::SettingsNoMatchesShort => "一致なし", + L10nKey::SettingsModifiedTitle => "変更済み", + L10nKey::SettingsMatchCount => "{count} 件", + L10nKey::SettingsNothingModified => "すべて既定値のままです", + L10nKey::SettingsKeyThen => "次に", + L10nKey::SettingsStartupRestore => "起動と復元", + L10nKey::SettingsSettingsFile => "設定ファイル", + L10nKey::SettingsReveal => "表示", + L10nKey::SettingsThemeModeSystem => "システム", + L10nKey::SettingsThemeModeSystemDesc => { + "システムに合わせて、ライトとダークのテーマを切り替えます。" + } + L10nKey::SettingsThemeModeLightDesc => "常にライトテーマを使います。", + L10nKey::SettingsThemeModeDarkDesc => "常にダークテーマを使います。", + L10nKey::SettingsThemeSlotLightDesc => "システムがライトモードのときに使います。", + L10nKey::SettingsThemeSlotDarkDesc => "システムがダークモードのときに使います。", + L10nKey::SettingsThemeSlotDesc => "ターミナルとインターフェースのテーマ。", + L10nKey::SettingsLightThemeLabel => "ライトテーマ", + L10nKey::SettingsDarkThemeLabel => "ダークテーマ", + L10nKey::SettingsNoThemesMatch => "一致するテーマがありません", + L10nKey::SettingsRestoreChanged => "変更した {count} 件を戻す", + L10nKey::SettingsShortcutsHint => { + "ショートカットをクリックして新しいキーを押します。続けて別の組み合わせを押すとシーケンスになります。Esc で取消、⌫ で解除。" + } + L10nKey::SettingsShortcutsHintTmux => { + "tmux プリセット:ペインとタブの操作はプレフィックスキーを使います。クリックで変更、Esc で取消、⌫ で解除。" + } + L10nKey::SettingsShortcutConflict => { + "{keys} は「{action}」で使われています。置き換えるとそちらから外れます。" + } + L10nKey::SettingsReplace => "置き換え", + L10nKey::SettingsNoActionsMatch => "「{query}」に一致する操作はありません", + L10nKey::SettingsSearchShortcuts => "操作またはキーを検索", + L10nKey::SettingsHostsDesc => { + "最近使ったホスト。検索すると保存済みのすべてのホストを探せます。" + } + L10nKey::SettingsAddHost => "ホストを追加", + L10nKey::SettingsNoHostsMatch => "「{query}」に一致するホストはありません", + L10nKey::SettingsHostsFromFiles => "{files} か所から {count} 台のホスト", + L10nKey::SettingsMoreHosts => "ほかに {count} 台のホスト", + L10nKey::SettingsShowRecentOnly => "最近のみ表示", + L10nKey::SettingsShowAll => "すべて表示", + L10nKey::SettingsUnsaved => "未保存", + L10nKey::SettingsNever => "未使用", + L10nKey::SettingsDefinedIn => "定義元", + L10nKey::SettingsConnectInNewTab => "新しいタブで接続", + L10nKey::SettingsCopied => "コピーしました", + L10nKey::SettingsCopySshCommand => "ssh コマンドをコピー", + L10nKey::SettingsStoredInTty7 => "tty7 の設定に保存", + L10nKey::SettingsClickAgainToRemove => "もう一度クリックで削除", + L10nKey::SettingsRemoveHost => "ホストを削除", + L10nKey::SettingsEditHost => "編集", + L10nKey::SettingsLive => "接続中", + L10nKey::SettingsPressKeysShort => "キーを押してください…", + L10nKey::SettingsSearchAgents => "エージェントを検索", + L10nKey::SettingsConnectedMachines => "接続中", + L10nKey::SettingsInstalledCount => "{count} 件インストール済み", + L10nKey::SettingsMachine => "マシン", + L10nKey::SettingsMachineLocalDesc => { + "フックはマシンごとにインストールされます。リモートマシンは接続中にここに表示されます。" + } + L10nKey::SettingsMachineRemoteDesc => "{name} への接続を通じてインストールします。", + L10nKey::SettingsAgentsInstalledSummary => "{total} 件中 {count} 件インストール済み", + L10nKey::SettingsNoAgentsInstalled => "このマシンにはまだエージェントフックがありません。", + L10nKey::SettingsNoAgentsMatch => "「{query}」に一致するエージェントはありません", + L10nKey::SettingsMoreAgents => "ほかに {count} 件のエージェント", + L10nKey::SettingsShowInstalledOnly => "インストール済みのみ表示", + L10nKey::SettingsWorking => "処理中…", + L10nKey::SettingsUpdateAvailable => "アップデートあり", + L10nKey::SettingsRevealHookFile => "フックファイルを表示", L10nKey::SettingsNavGeneral => "一般", L10nKey::SettingsEditShortcuts => "ショートカットを編集…", L10nKey::SettingsModifiedOnly => "変更済みのみ", @@ -105,40 +175,26 @@ pub fn translate_ja(key: L10nKey) -> Option<&'static str> { L10nKey::Download => "ダウンロード", L10nKey::Link => "リンク", L10nKey::SettingsThemeIntroTitle => "テーマ", - L10nKey::SettingsThemeIntroDesc => { - "配色テーマを選びます。明るいテーマと暗いテーマがあります" - } + L10nKey::SettingsThemeIntroDesc => "テーマごとにライトかダークが決まります", L10nKey::SettingsTypography => "タイポグラフィ", L10nKey::SettingsFontSize => "ターミナルの文字サイズ", L10nKey::SettingsFontSizeDesc => "ターミナルテキストのサイズ(ピクセル)", L10nKey::SettingsUiFontSize => "画面の文字サイズ", - L10nKey::SettingsUiFontSizeDesc => { - "ターミナル以外すべての文字サイズ(タブ・パネル・設定)。Retina でないディスプレイでは大きめに" - } + L10nKey::SettingsUiFontSizeDesc => "タブ・パネル・設定などの文字サイズ", L10nKey::SettingsUiFontFamily => "画面のフォント", - L10nKey::SettingsUiFontFamilyDesc => { - "タブ、サイドバー、ダイアログ、設定で使用するフォント。デフォルトではシステム UI フォントを使用します。" - } + L10nKey::SettingsUiFontFamilyDesc => "タブ、サイドバー、ダイアログ、設定で使うフォント", L10nKey::SettingsLineHeight => "行の高さ", L10nKey::SettingsLineHeightDesc => "フォントサイズに対する行間の倍率", L10nKey::SettingsFontFamily => "ターミナルのフォント", L10nKey::SettingsFontFamilyDesc => "システムにインストールされているフォントから選択", L10nKey::SettingsBoldFont => "太字フォント", - L10nKey::SettingsBoldFontDesc => { - "太字テキストに使用する書体。デフォルトではメインフォントから合成されます" - } + L10nKey::SettingsBoldFontDesc => "太字の書体。デフォルトはメインから合成", L10nKey::SettingsItalicFont => "斜体フォント", - L10nKey::SettingsItalicFontDesc => { - "斜体テキストに使用する書体。デフォルトではメインフォントから合成されます" - } + L10nKey::SettingsItalicFontDesc => "斜体の書体。デフォルトはメインから合成", L10nKey::SettingsFontLigatures => "フォントリガチャー", - L10nKey::SettingsFontLigaturesDesc => { - "ターミナルテキストで一般的なプログラミング用リガチャー(合字)を有効にする" - } + L10nKey::SettingsFontLigaturesDesc => "ターミナルでプログラミング用リガチャーを使用", L10nKey::SettingsFontThicken => "ストロークを太くする", - L10nKey::SettingsFontThickenDesc => { - "macOS のフォントスムージング:文字をやや太く描画し、明るい文字ほど太くなる。tty7 の再起動後に反映" - } + L10nKey::SettingsFontThickenDesc => "文字をやや太く描画します。再起動後に反映", L10nKey::SettingsCursor => "カーソル", L10nKey::SettingsCursorShape => "カーソルの形状", L10nKey::SettingsCursorShapeDesc => "ターミナルカーソルの描画方法", @@ -156,9 +212,7 @@ pub fn translate_ja(key: L10nKey) -> Option<&'static str> { } L10nKey::SettingsTransparency => "透明度", L10nKey::SettingsOpacity => "不透明度", - L10nKey::SettingsOpacityDesc => { - "すべてのテーマにおけるウィンドウ背景の不透明度。100% 未満ではデスクトップが透けて見えます" - } + L10nKey::SettingsOpacityDesc => "100% 未満ではデスクトップが透けて見えます", L10nKey::SettingsBlur => "背景のぼかし", L10nKey::SettingsBlurDesc => { if cfg!(target_os = "macos") { @@ -167,13 +221,9 @@ pub fn translate_ja(key: L10nKey) -> Option<&'static str> { "半透明ウィンドウの背後にあるものをぼかす。対応するコンポジターが必要です(KDE Plasma は対応、GNOME と素の X11 ではウィンドウが透けるだけです)" } } - L10nKey::SettingsBlurAutoDesc => { - "半透明ウィンドウの背後にあるものをぼかす。背景マテリアルが「自動」のときのみ有効です" - } + L10nKey::SettingsBlurAutoDesc => "半透明ウィンドウの背後をぼかす。「自動」のみ", L10nKey::SettingsBackdrop => "背景マテリアル", - L10nKey::SettingsBackdropDesc => { - "半透明ウィンドウの背後にあるネイティブ Windows 背景マテリアル。Mica には Windows 11 22H2、Acrylic には 1809 が必要です。古いビルドでは自動的にフォールバックします" - } + L10nKey::SettingsBackdropDesc => "半透明ウィンドウ背後のネイティブ背景", L10nKey::SettingsSearchBackdropKeywords => { "背景 マテリアル ぼかし すりガラス material backdrop mica acrylic blur frosted window background" } @@ -185,9 +235,7 @@ pub fn translate_ja(key: L10nKey) -> Option<&'static str> { L10nKey::SettingsBackdropOff => "オフ", L10nKey::FollowTheme => "テーマに従う", L10nKey::SettingsDimInactivePanes => "非アクティブなペインを暗くする", - L10nKey::SettingsDimInactivePanesDesc => { - "分割内のフォーカスされていないペインを暗くし、アクティブなペインを目立たせる" - } + L10nKey::SettingsDimInactivePanesDesc => "フォーカス外のペインを暗くします", L10nKey::SettingsOpenThemesFolder => "テーマフォルダを開く", L10nKey::SettingsChangeThemeImage => "変更…", L10nKey::SettingsChooseThemeImage => "選択…", @@ -195,9 +243,7 @@ pub fn translate_ja(key: L10nKey) -> Option<&'static str> { L10nKey::SettingsImageOpacity => "画像の不透明度", L10nKey::SettingsImageOpacityDesc => "背景色の上に画像をどれだけ強く表示するか", L10nKey::SettingsEditTheme => "テーマを編集", - L10nKey::SettingsEditThemeIntro => { - "コピーを編集します。変更はテーマフォルダ内のファイルに保存され、すぐ反映されます" - } + L10nKey::SettingsEditThemeIntro => "コピーを編集中。変更はすぐ反映・保存されます", L10nKey::SettingsBackgroundImage => "背景画像", L10nKey::SettingsBackgroundImageDesc => "背景色の上、テキストの下に表示されます", L10nKey::SettingsAnsiColors => "ANSI カラー", @@ -209,7 +255,7 @@ pub fn translate_ja(key: L10nKey) -> Option<&'static str> { L10nKey::ExplorerMenuOpenIn => "tty7 で開く", L10nKey::ExplorerMenuOpenHere => "ここで tty7 を開く", L10nKey::SettingsCustomThemesIntro => { - "テーマを複製して色を編集するか、tty7 の YAML テーマや iTerm2 の .itermcolors をテーマフォルダに置いてください" + "テーマを複製して編集するか、YAML や .itermcolors をテーマフォルダに置いてください" } L10nKey::SettingsDuplicateToEdit => "複製して編集", L10nKey::SettingsHosts => "ホスト", @@ -228,9 +274,7 @@ pub fn translate_ja(key: L10nKey) -> Option<&'static str> { L10nKey::SettingsMoreInSshConfig => "~/.ssh/config にさらに {count} 件", L10nKey::SettingsAliasesLinked => "{count} 件のエイリアスがリンクされています", L10nKey::SettingsImportAliases => "エイリアスをインポート", - L10nKey::SettingsImportAliasesDesc => { - "ファイルを再読み込みして新しい項目を追加します。ここでの編集は tty7 が保存します — ファイル自体には書き込まれません" - } + L10nKey::SettingsImportAliasesDesc => "ファイルを再読み込みし、新しい項目を追加", L10nKey::SettingsImportNow => "今すぐインポート", L10nKey::SettingsImportUnreadable => { "{path} を読み取れませんでした — 何もインポートされていません" @@ -245,9 +289,7 @@ pub fn translate_ja(key: L10nKey) -> Option<&'static str> { "tty7 に設定のないオプションが {count} 件あり、ファイルに残されています: {options}" } L10nKey::SettingsImportMoreOptions => "他 {count} 件", - L10nKey::SettingsDefaultsIntro => { - "すべてのホストはこの設定から始まります。各ホストは詳細設定で個別に上書きできます" - } + L10nKey::SettingsDefaultsIntro => "全ホストの既定値。各ホストの詳細設定で上書き可", L10nKey::SettingsCopyAddress => "アドレスをコピー", L10nKey::SettingsDuplicate => "複製", L10nKey::SettingsForgetPassword => "パスワードを消去", @@ -272,12 +314,10 @@ pub fn translate_ja(key: L10nKey) -> Option<&'static str> { L10nKey::SettingsSecurityIntro => "ホストは詳細設定でこれらを上書きできます", L10nKey::SettingsVerifyHostKeys => "ホストキーを検証", L10nKey::SettingsVerifyHostKeysDesc => { - "接続前に各サーバーのキーを known_hosts と照合します。オフでは確認しないため、なりすましサーバーに気づきません" + "サーバーのキーを known_hosts と照合します。オフではなりすましに気づけません" } L10nKey::WarnBeforeClosing => "閉じる前に警告", - L10nKey::SettingsWarnBeforeClosingDesc => { - "アクティブな SSH セッションのあるタブやペインを閉じる前に確認を求めます" - } + L10nKey::SettingsWarnBeforeClosingDesc => "SSH 接続中のタブを閉じる前に確認", L10nKey::SettingsNewHost => "新規ホスト", L10nKey::SettingsDiscardChangesTitle => "保存していない変更を破棄しますか?", L10nKey::SettingsDiscardChangesBody => "編集中の接続に、まだ保存していない変更があります。", @@ -298,9 +338,7 @@ pub fn translate_ja(key: L10nKey) -> Option<&'static str> { L10nKey::SettingsNameHint => "任意のラベル", L10nKey::SettingsHostHint => "ホスト名または IP", L10nKey::SettingsUserHint => "接続時に解決", - L10nKey::SettingsPasswordDesc => { - "システムのキーチェーンに保存され、設定ファイルには書き込まれません。" - } + L10nKey::SettingsPasswordDesc => "キーチェーンに保存され、設定ファイルには書きません", L10nKey::SettingsPasswordHint => "接続時に入力する", L10nKey::SettingsKeyPassphrase => "鍵のパスフレーズ", L10nKey::SettingsKeyPassphraseDesc => { @@ -313,9 +351,7 @@ pub fn translate_ja(key: L10nKey) -> Option<&'static str> { L10nKey::SettingsCouldntSavePassword => "{endpoint} のパスワードを保存できません: {error}", L10nKey::SettingsCouldntSavePassphrase => "{key} のパスフレーズを保存できません: {error}", L10nKey::SettingsJumpHost => "ジャンプホスト", - L10nKey::SettingsJumpHostDesc => { - "トンネリングに使用する別のプロファイル名 (空欄 = 直接接続)" - } + L10nKey::SettingsJumpHostDesc => "経由するプロファイル。空欄なら直接接続", L10nKey::SettingsJumpHostUnknown => { "{jump_name} という名前のホストプロファイルはありません — 保存されません" } @@ -346,7 +382,7 @@ pub fn translate_ja(key: L10nKey) -> Option<&'static str> { L10nKey::SettingsGroupSecurity => "セキュリティ", L10nKey::SettingsRemoteClipboardWrite => "リモートのクリップボード画像", L10nKey::SettingsRemoteClipboardWriteDesc => { - "このホスト上のプログラムが OSC 5522 でローカルクリップボードを画像に置き換えることを許可します" + "このホストが画像をクリップボードに書き込む(OSC 5522)" } L10nKey::SettingsIdentityFiles => "秘密鍵ファイル", L10nKey::SettingsIdentityFilesDesc => "秘密鍵のパス(1 行に 1 つ。%h/%r は展開されます)", @@ -411,9 +447,7 @@ pub fn translate_ja(key: L10nKey) -> Option<&'static str> { } } L10nKey::SettingsShellIntegration => "シェル統合", - L10nKey::SettingsShellIntegrationDesc => { - "リモートシェルにプロンプト・終了コード・作業ディレクトリを報告させる" - } + L10nKey::SettingsShellIntegrationDesc => "プロンプト・終了コード・ディレクトリを報告", L10nKey::SettingsLoginScripts => "ログインスクリプト", L10nKey::SettingsLoginScriptsDesc => "シェル起動後に送信するコマンド(1 行に 1 つ)", L10nKey::SettingsSkipBanner => "バナーをスキップ", @@ -427,24 +461,16 @@ pub fn translate_ja(key: L10nKey) -> Option<&'static str> { L10nKey::SettingsOn => "オン", L10nKey::SettingsOff => "オフ", L10nKey::SettingsShell => "シェル", - L10nKey::SettingsShellIntro => { - "新しいターミナルで起動するプログラム。「シェルプログラム」を空欄にすると、プラットフォーム既定の {default} を使います。" - } + L10nKey::SettingsShellIntro => "新しいターミナルで起動するプログラム。空欄なら {default}", L10nKey::SettingsProgram => "シェルプログラム", - L10nKey::SettingsProgramDesc => { - "PATH 上の実行可能ファイル名または絶対パス。例: zsh、fish、pwsh" - } + L10nKey::SettingsProgramDesc => "PATH 上の名前か絶対パス。例: zsh、fish", L10nKey::SettingsArguments => "シェル引数", - L10nKey::SettingsArgumentsDesc => { - "コマンドラインと同じ規則で分割される起動フラグ。空白を含むものはクォートしてください(例: -l、-c \"echo hi\")" - } + L10nKey::SettingsArgumentsDesc => "コマンドラインと同じ規則で分割。例: -l、-c \"echo hi\"", L10nKey::SettingsArgumentsInvalid => { "引用符が対応していないため、この値は保存されませんでした" } L10nKey::SettingsStartIn => "開始ディレクトリ", - L10nKey::SettingsStartInDesc => { - "新しいシェルの開始場所: tty7 の起動ディレクトリ、ホームフォルダ、または固定パス" - } + L10nKey::SettingsStartInDesc => "tty7 の起動ディレクトリ、ホームフォルダ、または固定パス", L10nKey::SettingsCustomPath => "カスタムパス", L10nKey::SettingsCustomPathDesc => "新しいシェルが起動するディレクトリ", L10nKey::SettingsWdInherit => "継承", @@ -454,7 +480,7 @@ pub fn translate_ja(key: L10nKey) -> Option<&'static str> { "このディレクトリは存在しないため、この値は保存されませんでした" } L10nKey::SettingsShellFooter => { - "継承元のないシェル(ウィンドウの最初のタブなど)に適用されます。新しいタブと分割はアクティブなペインのディレクトリを引き継ぎ、開いているシェルは動き続けます" + "継承元のないシェル(ウィンドウの最初のタブなど)にのみ適用。新しいタブと分割はアクティブなペインのディレクトリを使います" } L10nKey::SettingsScrolling => "スクロール", L10nKey::SettingsScrollback => "スクロールバックバッファー", @@ -465,8 +491,7 @@ pub fn translate_ja(key: L10nKey) -> Option<&'static str> { L10nKey::SettingsScrollSpeedDesc => "マウスホイールのスクロールに適用する倍率", L10nKey::SettingsSmoothScroll => "スムーズスクロール", L10nKey::SettingsSmoothScrollDesc => { - "ホイール1ノッチ分を一気に飛ばさず、数フレームかけて動かす。\ - トラックパッドは元から連続的なので影響しない" + "ホイールを滑らかにスクロール(トラックパッドは対象外)" } L10nKey::SettingsMouse => "マウス", L10nKey::SettingsFocusFollowsMouse => "フォーカスがマウスに追従する", @@ -478,34 +503,23 @@ pub fn translate_ja(key: L10nKey) -> Option<&'static str> { "入力中はポインタを隠し、次のマウス移動で再表示する" } L10nKey::SettingsMouseZoom => "ホイールで拡大縮小", - L10nKey::SettingsMouseZoomDesc => { - "この修飾キーを押しながらホイールを回すと、スクロールではなくフォントサイズが変わる" - } + L10nKey::SettingsMouseZoomDesc => "押しながらホイールを回すとフォントサイズが変わります", L10nKey::SettingsMouseZoomOff => "オフ", L10nKey::SettingsReportMouseToApps => "マウスイベントをアプリに報告", - L10nKey::SettingsReportMouseToAppsDesc => { - "フルスクリーンアプリ(vim、tmux)にクリックとスクロールを処理させる。Shift を押している間はローカルで処理されます。\ - オフにするとクリックは届かず、ホイールは矢印キーとして送られます" - } + L10nKey::SettingsReportMouseToAppsDesc => "vim や tmux にクリックを渡す。Shift で端末側に", L10nKey::SettingsBell => "ベル通知", L10nKey::SettingsTerminalBell => "ターミナルベル", - L10nKey::SettingsTerminalBellDesc => { - "ベル(^G)の通知方法: サイレント、短い点滅、システムサウンド、またはその両方" - } + L10nKey::SettingsTerminalBellDesc => "ベル(^G)の通知方法", L10nKey::SettingsLinks => "リンク", L10nKey::DetectUrls => "URL を自動検出", - L10nKey::SettingsDetectUrlsDesc => { - "ホバーでリンクに下線を表示し、{modifier}+クリックで開く" - } + L10nKey::SettingsDetectUrlsDesc => "ホバーで下線、{modifier}+クリックで開く", L10nKey::ForwardSshLoopbackLinks => "リモートポートを転送", - L10nKey::SettingsForwardSshLoopbackLinksDesc => { - "SSH 接続中、ペインが待ち受けを始めたポートを自動転送し、localhost リンクをこの端末で開く" - } + L10nKey::SettingsForwardSshLoopbackLinksDesc => "リモートの localhost リンクをここで開く", L10nKey::SettingsOpenFilesInternal => "内蔵エディタ", L10nKey::SettingsOpenFilesSystem => "デフォルトアプリ", L10nKey::SettingsOpenFilesCommand => "コマンド", L10nKey::SettingsOpenFilesModeDesc => { - "ファイルリンクを {modifier}+クリックしたときに開くもの。行番号へのジャンプとリモートファイルを開けるのは内蔵エディタだけです" + "{modifier}+クリックで開くもの。行ジャンプとリモートファイルは内蔵エディタのみ" } L10nKey::LinkFileNotUnder => "{path} — {dir} にそのファイルはありません", L10nKey::LinkFileNoDirectory => { @@ -516,37 +530,33 @@ pub fn translate_ja(key: L10nKey) -> Option<&'static str> { "{path} — 別のマシン上にあり、ファイルパネルで開いているどのフォルダにも含まれていません" } L10nKey::OpenFilesWith => "ファイルを開くアプリケーション", - L10nKey::SettingsOpenFilesWithDesc => { - "ファイルリンクを {modifier}+クリックしたときに実行するコマンド。{path}、{line}、{column} を使えます — 値のないフラグは除外されます。空欄ならデフォルトアプリ" - } + L10nKey::SettingsOpenFilesWithDesc => "{path}、{line}、{column} を使用。空欄ならデフォルト", L10nKey::SettingsBellModeOff => "オフ", L10nKey::SettingsBellModeVisual => "視覚的(画面点滅)", L10nKey::SettingsBellModeAudible => "音声(効果音)", L10nKey::SettingsBellModeBoth => "点滅 + 音声", L10nKey::SettingsPrompt => "プロンプトとコマンド履歴", L10nKey::SettingsPromptIntro => { - "シェルプロンプトでの tty7 独自のエディターとメニュー。オフにするとその分がシェルに渡されます" + "プロンプトでの tty7 独自のエディターとメニュー。オフでシェルに戻します" } L10nKey::SettingsPromptEditor => "tty7 のプロンプトエディター", L10nKey::SettingsPromptEditorDesc => { - "シェルプロンプトで入力する行を tty7 が編集します — 選択、取り消し、下のメニュー。オフにするとシェル自身の行エディター(ZLE、readline、fish)に戻ります" + "入力行で選択・取り消し・メニューを使えます。オフでは ZLE、readline、fish に戻します" } L10nKey::SettingsNeedsPromptEditor => { "プロンプトエディターが必要です。オフの間、このキーはすでにシェルのものです" } L10nKey::SettingsTabCompletion => "タブ補完", L10nKey::SettingsTabCompletionDesc => { - "プロンプトで Tab を押すと tty7 の補完メニューが開きます。オフの場合、Tab はシェル自身の補完に渡されます" + "Tab で tty7 の補完メニューを開きます。オフならシェルへ" } L10nKey::SettingsHistorySearch => "コマンド履歴検索", L10nKey::SettingsHistorySearchDesc => { - "プロンプトで ⌃R を押すと tty7 のファジー履歴メニューが開きます。オフなら ⌃R はシェルへ — 逆方向検索や、そこでバインドしたもの(fzf、percol)" + "⌃R で tty7 のファジー履歴検索を開きます。オフならシェルへ" } L10nKey::SettingsSelectionClipboard => "選択とクリップボード", L10nKey::SettingsSmartSelection => "スマート選択", - L10nKey::SettingsSmartSelectionDesc => { - "ダブルクリックでカーソル下の URL、ファイルパス、メールアドレス、または括弧ペア全体を選択" - } + L10nKey::SettingsSmartSelectionDesc => "ダブルクリックで URL やパス全体を選択", L10nKey::SettingsCopyOnSelect => "選択時に自動コピー", L10nKey::SettingsCopyOnSelectDesc => { if cfg!(target_os = "macos") { @@ -559,12 +569,10 @@ pub fn translate_ja(key: L10nKey) -> Option<&'static str> { L10nKey::SettingsTrimTrailingSpacesDesc => "コピーした各行の末尾の空白を除去する", L10nKey::SettingsKeyboard => "キーボード", L10nKey::SettingsOptionAsMeta => "Option(⌥)を Meta として使用", - L10nKey::SettingsOptionAsMetaDesc => { - "⌥+キーでシェルが期待するエスケープシーケンス(⌥B = 単語 1 つ戻る)を送信し、特殊文字(∫)を入力しない" - } - L10nKey::SettingsAgentsIntro => "AI エージェント", + L10nKey::SettingsOptionAsMetaDesc => "⌥+キーを Meta として送る(⌥B で 1 語戻る)", + L10nKey::SettingsAgentsIntro => "エージェントフック", L10nKey::SettingsAgentsIntroDesc => { - "フックにより、これらのエージェントを実行するペインの状態(作業中 / 待機中 / 完了)がタブバーに表示されます。tty7 内でのみ有効" + "フックでエージェントの状態(作業中 / 待機中 / 完了)をタブバーに表示します" } L10nKey::SettingsReadingAgentConfig => "このマシンのエージェント設定を読み込んでいます…", L10nKey::SettingsStatusNotInstalled => "未インストール", @@ -577,14 +585,12 @@ pub fn translate_ja(key: L10nKey) -> Option<&'static str> { L10nKey::SettingsOfflineMachines => { "未接続の保存済みマシンがさらに {count} 台あります。いずれかでワークスペースを開くと、そこにフックをインストールできます" } - L10nKey::SettingsSyncWithSystem => "システムテーマと同期", + L10nKey::SettingsSyncWithSystem => "外観", L10nKey::SettingsSyncWithSystemDesc => { "OS の外観に従い、ライトとダークのテーマを別々に使用する" } L10nKey::SettingsLegiblePalette => "明色の可読性", - L10nKey::SettingsLegiblePaletteDesc => { - "テーマ背景でコントラスト不足の明色を自動調整して、可読性を確保します。" - } + L10nKey::SettingsLegiblePaletteDesc => "背景上で読みにくい明色を自動調整します", L10nKey::SettingsChangeTheme => "テーマを変更", L10nKey::SettingsThemes => "テーマ一覧", L10nKey::SettingsThemesCloseTooltip => "テーマ一覧を閉じる (Esc)", @@ -602,17 +608,13 @@ pub fn translate_ja(key: L10nKey) -> Option<&'static str> { L10nKey::SettingsStartupWindow => "起動時のウィンドウ状態", L10nKey::SettingsStartupWindowDesc => "tty7 起動時のウィンドウ状態", L10nKey::SettingsRememberWindowSize => "ウィンドウサイズと位置を記憶", - L10nKey::SettingsRememberWindowSizeDesc => { - "tty7 が最後に終了したときのサイズと位置で開き直します。オフならデフォルトサイズで中央に開きます" - } + L10nKey::SettingsRememberWindowSizeDesc => "前回終了時のサイズと位置でウィンドウを開きます", L10nKey::SettingsRestoreLastLayout => "前回のレイアウトを復元", L10nKey::SettingsRestoreLastLayoutDesc => { - "起動時に前回のウィンドウのタブ、分割、ディレクトリを復元します。オフなら新しいターミナルが 1 つだけ起動します" + "起動時に前回のタブ、分割、ディレクトリを復元します" } L10nKey::SettingsShowTrayIcon => "システムトレイアイコンを表示", - L10nKey::SettingsShowTrayIconDesc => { - "システムトレイ / メニューバーの状態表示:エージェントが入力を必要とするときに通知し、メニューからそのペインへ移動できます" - } + L10nKey::SettingsShowTrayIconDesc => "エージェントの入力待ちを通知", L10nKey::SettingsTabs => "タブ", L10nKey::SettingsNewTabPosition => "新規タブの表示位置", L10nKey::SettingsNewTabPositionDesc => "新しく開いたタブが挿入される場所", @@ -621,20 +623,14 @@ pub fn translate_ja(key: L10nKey) -> Option<&'static str> { "タブを上部の横一列または左側の縦サイドバーとして表示" } L10nKey::SettingsSidebarGrouping => "サイドバーのグループ化", - L10nKey::SettingsSidebarGroupingDesc => { - "サイドバータブを git リポジトリごとにまとめます。リポジトリ外のタブはスクラッチに、「リポジトリ/フォルダ別」なら作業ディレクトリごとに。左サイドバーのみ" - } + L10nKey::SettingsSidebarGroupingDesc => "git リポジトリごとにまとめ、他はスクラッチへ", L10nKey::SettingsDiffPreviewFromCounts => "サイドバーのカウントから Diff プレビューを開く", - L10nKey::SettingsDiffPreviewFromCountsDesc => { - "行の +N −N をクリックすると、オーバーレイでワーキングツリーの Diff を開きます。オフならカウントは表示されたまま、クリックだけできません" - } + L10nKey::SettingsDiffPreviewFromCountsDesc => "行の +N −N をクリックして Diff を開きます", L10nKey::DocumentDock => "ターミナルの隣にドック", L10nKey::DocumentFill => "ウィンドウ全体", L10nKey::SettingsNotifications => "通知", L10nKey::SettingsNotifyOnCommandFinish => "コマンド終了時に通知", - L10nKey::SettingsNotifyOnCommandFinishDesc => { - "長時間のフォアグラウンドコマンドが完了したらデスクトップ通知を表示" - } + L10nKey::SettingsNotifyOnCommandFinishDesc => "長いコマンドの完了をデスクトップに通知", L10nKey::SettingsNotifyThreshold => "コマンド実行時間の下限", L10nKey::SettingsNotifyThresholdDesc => { "この時間以上実行されたコマンドの完了を通知します。" @@ -654,18 +650,14 @@ pub fn translate_ja(key: L10nKey) -> Option<&'static str> { L10nKey::SettingsByRepoOrFolder => "リポジトリ/フォルダ別", L10nKey::SettingsFlat => "フラット表示", L10nKey::SettingsPreset => "プリセット", - L10nKey::SettingsPresetDesc => { - "tmux では、ペイン/タブの操作をプレフィックスキーの後に行います(例: Ctrl-B の後に C)" - } + L10nKey::SettingsPresetDesc => "tmux はペイン・タブ操作をプレフィックスキーに(Ctrl-B C)", L10nKey::SettingsPrefix => "プレフィックスキー", L10nKey::SettingsPressKeys => "キーを入力… · ⌫ でショートカットなし", L10nKey::SettingsPauseToSaveEsc => "一時停止して保存 · Esc", L10nKey::SettingsKeybindingsIntroDesc => { - "ショートカットをクリックして新しいキーを押すと、少し間を置いて保存されます。Ctrl-B の後に X のようなシーケンスはキーを続けて入力。Esc でキャンセル、Backspace は最後のキーを削除し、最初に押すとショートカットなしになり、「リセット」でデフォルトに戻せます" - } - L10nKey::SettingsPrefixNote => { - "プレフィックスが有効な場合、プレフィックスキーを単独で押すと約 1 秒後にシェルに渡され、プレフィックス + 未割り当てのキーはターミナルへそのまま送信されます" + "ショートカットをクリックして新しいキーを押します。続けて押すと Ctrl-B X のようなシーケンスに。Esc で取消、Backspace で削除" } + L10nKey::SettingsPrefixNote => "プレフィックスキー単独は約 1 秒後にシェルへ", L10nKey::SettingsRestoreAllDefaults => "すべてのデフォルトを復元", L10nKey::SettingsRestoreAllDefaultsBody => { "変更したキーはすべてデフォルトに戻ります。元に戻すことはできません。" @@ -678,11 +670,11 @@ pub fn translate_ja(key: L10nKey) -> Option<&'static str> { L10nKey::KeybindForkSessionDown => "下にセッションをフォーク", L10nKey::KeybindForkSessionUp => "上にセッションをフォーク", L10nKey::SettingsAboutDesc1 => { - "ターミナルワークベンチ: 常駐セッション、リモート作業、エージェント" + "長く続く作業のためのターミナルワークベンチ。セッションはウィンドウを閉じても続き、リモートもローカルと同じように扱え、コーディングエージェントの状態はサイドバーに表示されます。" } L10nKey::SettingsDefaultTerminal => "デフォルトのターミナル", L10nKey::SettingsDefaultTerminalDesc => { - "tty7 を Unix 実行ファイル、SSH リンク、man ページリンク用の macOS のデフォルトターミナルにします。tty7 はフォルダとスクリプトも開けますが、Finder のフォルダハンドラは置き換えません。独自のターミナルを指定するアプリはこの設定を無視することがあります。" + "Unix 実行ファイル、SSH リンク、man ページを tty7 で開きます" } L10nKey::SettingsDefaultTerminalSet => "デフォルトのターミナルに設定", L10nKey::SettingsDefaultTerminalSetSuccess => { @@ -717,17 +709,15 @@ pub fn translate_ja(key: L10nKey) -> Option<&'static str> { L10nKey::SettingsUpdateDiscard => "破棄", L10nKey::SettingsAutoDownload => "アップデートをバックグラウンドでダウンロード", L10nKey::SettingsAutoDownloadDesc => { - "新しいリリースを見つけ次第ダウンロードと検証を済ませ、インストールは再起動するだけにします。確認なしにインストールすることはありません。パッケージは約 30 MB" + "更新をバックグラウンドで取得し、再起動だけで適用。確認なしにはインストールしません" } L10nKey::SettingsUpdateChannel => "更新チャンネル", - L10nKey::SettingsUpdateChannelDesc => { - "Stable は正式リリースを、Nightly は最新のコードから毎晩ビルドされる版を追いかけます。新しい代わりに、リリース前のテストは経ていません" - } + L10nKey::SettingsUpdateChannelDesc => "Nightly は毎晩最新コードからビルド(未テスト)", L10nKey::SettingsUpdateChannelStable => "安定版", L10nKey::SettingsUpdateChannelNightly => "ナイトリー", L10nKey::SettingsDaemonStale => "tty7 server は {build} のままです。", L10nKey::SettingsDaemonStaleDesc => { - "tty7 はその場で更新されました。アプリは新しく、ペインはまだ以前のビルドの tty7 server が処理しています。再起動すると新しいビルドに切り替わり、ペインで動いているプロセスはすべて終了します。急ぐ必要はなく、ペインが空いているときにどうぞ" + "tty7 は更新されましたが、ペインは古い server で動いています。再起動すると新しいビルドになり、ペインのプロセスはすべて終了します" } L10nKey::UpdateDialogTitle => "アップデートがあります", L10nKey::UpdateDialogDetail => { @@ -773,24 +763,16 @@ pub fn translate_ja(key: L10nKey) -> Option<&'static str> { "このリリースには checksums.txt がないため、tty7 は自動インストールを行いません" } L10nKey::SettingsVersionAvailable => "バージョン {version} が利用可能です", - L10nKey::SettingsCheckUpdatesDesc => { - "その場で更新できないインストール形式では、代わりにリリースページを開きます" - } + L10nKey::SettingsCheckUpdatesDesc => "自動更新できない場合はリリースページを開く", L10nKey::SettingsCheckUpdatesOnLaunch => "起動時にアップデートを確認", L10nKey::SettingsCommandLine => "コマンドライン", - L10nKey::SettingsCommandLineDesc => { - "付属の tty7 コマンドをスクリプトや AI エージェントから利用できます。次回起動時に反映されます。無効にしてもインストール済みのコマンドは削除されません。" - } + L10nKey::SettingsCommandLineDesc => "tty7 コマンドを PATH に追加。次回起動時に反映", L10nKey::SettingsInstallCliOnPath => "`tty7` コマンドを PATH にインストール", L10nKey::SettingsServer => "tty7 server", - L10nKey::SettingsServerDesc => { - "このコンピューターのターミナルセッションを管理し、バックグラウンドで実行し続けます。" - } + L10nKey::SettingsServerDesc => "ターミナルセッションをバックグラウンドで実行し続けます", L10nKey::SettingsRestartServer => "tty7 server を再起動…", L10nKey::SettingsAppHttpProxy => "アップデート用プロキシ", - L10nKey::SettingsAppHttpProxyDesc => { - "tty7 自身の更新チェックとダウンロードにのみ使用し、ペインで実行中のプログラムには影響しません。空欄ならシステムのプロキシに従います" - } + L10nKey::SettingsAppHttpProxyDesc => "tty7 の更新チェック用。空欄ならシステム設定", L10nKey::SettingsAppHttpProxyInvalid => { "プロキシアドレスとして正しくないため、この値は保存されませんでした" } @@ -1832,7 +1814,7 @@ pub fn translate_ja(key: L10nKey) -> Option<&'static str> { L10nKey::Replace => "置き換える", L10nKey::SftpErrorInvalidOctalMode => "無効な 8 進数モードです", L10nKey::SettingsDaemonStaleDescInPlace => { - "tty7 はその場で更新されました。アプリは新しく、ペインはまだ前のビルドで動いています。tty7 server は停止せずに新しいビルドへ置き換えられるので、シェルはそのまま引き継がれます。tty7 内蔵の SSH クライアントを使うペインだけは例外で、その接続は閉じられ、開き直しが必要です" + "tty7 が更新されました。server はその場で入れ替わり、シェルは続きます。内蔵 SSH のペインだけ閉じます" } L10nKey::AppRestartServerBodyInPlace => { "tty7 server は停止せずに自分自身をこのビルドへ置き換えます。シェルは動いたままで、ウィンドウはすぐに再接続します。tty7 内蔵の SSH クライアントを使うペインだけは例外で、その接続は閉じられ、開き直しが必要です" @@ -1841,9 +1823,7 @@ pub fn translate_ja(key: L10nKey) -> Option<&'static str> { "復元された画面 — 以下は新しいシェルで、これより上のものは動いていません" } L10nKey::SettingsPerPaneHistory => "ペインごとにコマンド履歴を分離", - L10nKey::SettingsPerPaneHistoryDescription => { - "上キーでたどるのは、全ペインが混ざったものではなくこのペインで実行したコマンドです。新しいペインは既存の履歴から始まり、追加分は閉じるときに書き戻されます。対象は tty7 が設定できる bash と zsh のペインで、独自の引数で起動したシェルはそのままです" - } + L10nKey::SettingsPerPaneHistoryDescription => "↑ はこのペインの履歴だけ(bash、zsh)", L10nKey::IntegrationNoticeBlocked => { "“{wrapper}”がこのペインのシェルレポートを横取りしているため、インライン補完と Ctrl+R メニューは使えません。シェル独自の履歴検索は引き続き使えます。" } @@ -1987,6 +1967,18 @@ pub fn translate_ja(key: L10nKey) -> Option<&'static str> { pub fn translate_variant_ja(key: L10nKey, branch: &'static str) -> Option<&'static str> { let res = match (key, branch) { + (L10nKey::SettingsMatchCount, "zero") => "0 件", + (L10nKey::SettingsMatchCount, "one") => "1 件", + (L10nKey::SettingsMatchCount, "other") => "{count} 件", + (L10nKey::SettingsRestoreChanged, "zero") => "変更を戻す", + (L10nKey::SettingsRestoreChanged, "one") => "変更した 1 件を戻す", + (L10nKey::SettingsRestoreChanged, "other") => "変更した {count} 件を戻す", + (L10nKey::SettingsMoreHosts, "zero") => "ほかのホストはありません", + (L10nKey::SettingsMoreHosts, "one") => "ほかに 1 台のホスト", + (L10nKey::SettingsMoreHosts, "other") => "ほかに {count} 台のホスト", + (L10nKey::SettingsMoreAgents, "zero") => "ほかのエージェントはありません", + (L10nKey::SettingsMoreAgents, "one") => "ほかに 1 件のエージェント", + (L10nKey::SettingsMoreAgents, "other") => "ほかに {count} 件のエージェント", (L10nKey::SettingsDeleteProfileCascade, "one") => { "{endpoint} を参照しているリモートワークスペースのエントリが 1 件あり、\ プロファイルと一緒にこのコンピュータから削除されます。リモートマシン上のセッションは\ diff --git a/src/ui/i18n/mod.rs b/src/ui/i18n/mod.rs index 56774889..4a1b6cc2 100644 --- a/src/ui/i18n/mod.rs +++ b/src/ui/i18n/mod.rs @@ -68,6 +68,64 @@ macro_rules! l10n_keys { } l10n_keys! { + SettingsNoMatchesShort, + SettingsModifiedTitle, + SettingsMatchCount, + SettingsNothingModified, + SettingsKeyThen, + SettingsStartupRestore, + SettingsSettingsFile, + SettingsReveal, + SettingsThemeModeSystem, + SettingsThemeModeSystemDesc, + SettingsThemeModeLightDesc, + SettingsThemeModeDarkDesc, + SettingsThemeSlotLightDesc, + SettingsThemeSlotDarkDesc, + SettingsThemeSlotDesc, + SettingsLightThemeLabel, + SettingsDarkThemeLabel, + SettingsNoThemesMatch, + SettingsRestoreChanged, + SettingsShortcutsHint, + SettingsShortcutsHintTmux, + SettingsShortcutConflict, + SettingsReplace, + SettingsNoActionsMatch, + SettingsSearchShortcuts, + SettingsHostsDesc, + SettingsAddHost, + SettingsNoHostsMatch, + SettingsHostsFromFiles, + SettingsMoreHosts, + SettingsShowRecentOnly, + SettingsShowAll, + SettingsUnsaved, + SettingsNever, + SettingsDefinedIn, + SettingsConnectInNewTab, + SettingsCopied, + SettingsCopySshCommand, + SettingsStoredInTty7, + SettingsClickAgainToRemove, + SettingsRemoveHost, + SettingsEditHost, + SettingsLive, + SettingsPressKeysShort, + SettingsSearchAgents, + SettingsConnectedMachines, + SettingsInstalledCount, + SettingsMachine, + SettingsMachineLocalDesc, + SettingsMachineRemoteDesc, + SettingsAgentsInstalledSummary, + SettingsNoAgentsInstalled, + SettingsNoAgentsMatch, + SettingsMoreAgents, + SettingsShowInstalledOnly, + SettingsWorking, + SettingsUpdateAvailable, + SettingsRevealHookFile, SettingsSaveError, SettingsRetrySave, @@ -1723,6 +1781,10 @@ mod tests { let plural_keys = [ L10nKey::SettingsDeleteProfileCascade, L10nKey::SettingsAliasesLinked, + L10nKey::SettingsMoreAgents, + L10nKey::SettingsMoreHosts, + L10nKey::SettingsRestoreChanged, + L10nKey::SettingsMatchCount, L10nKey::SettingsImportSummary, L10nKey::SettingsImportIgnored, L10nKey::SettingsRulesOpenedWithConnection, diff --git a/src/ui/i18n/zh.rs b/src/ui/i18n/zh.rs index e1cd767c..ea3d9fdf 100644 --- a/src/ui/i18n/zh.rs +++ b/src/ui/i18n/zh.rs @@ -2,6 +2,68 @@ use super::L10nKey; pub fn translate_zh(key: L10nKey) -> Option<&'static str> { Some(match key { + L10nKey::SettingsNoMatchesShort => "没有匹配项", + L10nKey::SettingsModifiedTitle => "已修改", + L10nKey::SettingsMatchCount => "{count} 个结果", + L10nKey::SettingsNothingModified => "所有设置均为默认值", + L10nKey::SettingsKeyThen => "再按", + L10nKey::SettingsStartupRestore => "启动与恢复", + L10nKey::SettingsSettingsFile => "设置文件", + L10nKey::SettingsReveal => "显示", + L10nKey::SettingsThemeModeSystem => "跟随系统", + L10nKey::SettingsThemeModeSystemDesc => "跟随系统外观,在浅色与深色主题之间切换。", + L10nKey::SettingsThemeModeLightDesc => "始终使用浅色主题。", + L10nKey::SettingsThemeModeDarkDesc => "始终使用深色主题。", + L10nKey::SettingsThemeSlotLightDesc => "系统处于浅色模式时使用。", + L10nKey::SettingsThemeSlotDarkDesc => "系统处于深色模式时使用。", + L10nKey::SettingsThemeSlotDesc => "终端和界面使用的主题。", + L10nKey::SettingsLightThemeLabel => "浅色主题", + L10nKey::SettingsDarkThemeLabel => "深色主题", + L10nKey::SettingsNoThemesMatch => "没有匹配的主题", + L10nKey::SettingsRestoreChanged => "恢复 {count} 项修改", + L10nKey::SettingsShortcutsHint => { + "点击快捷键后按下新组合键;紧接着再按一组即可组成序列。Esc 取消,⌫ 清除。" + } + L10nKey::SettingsShortcutsHintTmux => { + "tmux 预设:窗格与标签页操作使用前缀键。点击快捷键即可修改;Esc 取消,⌫ 清除。" + } + L10nKey::SettingsShortcutConflict => "{keys} 已被「{action}」使用,替换后将从那里移除。", + L10nKey::SettingsReplace => "替换", + L10nKey::SettingsNoActionsMatch => "没有与「{query}」匹配的操作", + L10nKey::SettingsSearchShortcuts => "搜索操作或按键", + L10nKey::SettingsHostsDesc => "最近使用的主机。搜索可找到任意已保存的主机。", + L10nKey::SettingsAddHost => "添加主机", + L10nKey::SettingsNoHostsMatch => "没有与「{query}」匹配的主机", + L10nKey::SettingsHostsFromFiles => "{count} 台主机,来自 {files} 个来源", + L10nKey::SettingsMoreHosts => "还有 {count} 台主机", + L10nKey::SettingsShowRecentOnly => "只显示最近", + L10nKey::SettingsShowAll => "显示全部", + L10nKey::SettingsUnsaved => "未保存", + L10nKey::SettingsNever => "从未", + L10nKey::SettingsDefinedIn => "定义于", + L10nKey::SettingsConnectInNewTab => "在新标签页中连接", + L10nKey::SettingsCopied => "已复制", + L10nKey::SettingsCopySshCommand => "复制 ssh 命令", + L10nKey::SettingsStoredInTty7 => "保存在 tty7 设置中", + L10nKey::SettingsClickAgainToRemove => "再次点击以删除", + L10nKey::SettingsRemoveHost => "删除主机", + L10nKey::SettingsEditHost => "编辑", + L10nKey::SettingsLive => "已连接", + L10nKey::SettingsPressKeysShort => "按下按键…", + L10nKey::SettingsSearchAgents => "搜索 Agent", + L10nKey::SettingsConnectedMachines => "已连接", + L10nKey::SettingsInstalledCount => "已安装 {count} 个", + L10nKey::SettingsMachine => "机器", + L10nKey::SettingsMachineLocalDesc => "钩子按机器安装。远程机器在连接期间会出现在这里。", + L10nKey::SettingsMachineRemoteDesc => "通过当前与 {name} 的连接安装。", + L10nKey::SettingsAgentsInstalledSummary => "已安装 {count} / {total}", + L10nKey::SettingsNoAgentsInstalled => "这台机器上还没有安装 Agent 钩子。", + L10nKey::SettingsNoAgentsMatch => "没有与「{query}」匹配的 Agent", + L10nKey::SettingsMoreAgents => "还有 {count} 个可用 Agent", + L10nKey::SettingsShowInstalledOnly => "只显示已安装", + L10nKey::SettingsWorking => "处理中…", + L10nKey::SettingsUpdateAvailable => "有可用更新", + L10nKey::SettingsRevealHookFile => "显示钩子文件", L10nKey::SettingsNavGeneral => "常规", L10nKey::SettingsEditShortcuts => "编辑快捷键…", L10nKey::SettingsModifiedOnly => "仅显示已修改", @@ -97,32 +159,26 @@ pub fn translate_zh(key: L10nKey) -> Option<&'static str> { L10nKey::Download => "下载", L10nKey::Link => "关联", L10nKey::SettingsThemeIntroTitle => "主题", - L10nKey::SettingsThemeIntroDesc => "选择配色主题。每个主题都有各自的浅色或深色外观。", + L10nKey::SettingsThemeIntroDesc => "每个主题自带浅色或深色外观。", L10nKey::SettingsTypography => "字体排版", L10nKey::SettingsFontSize => "终端字号", L10nKey::SettingsFontSizeDesc => "终端文字大小(像素)。", L10nKey::SettingsUiFontSize => "界面字号", - L10nKey::SettingsUiFontSizeDesc => { - "终端以外所有地方的文字大小——标签页、面板、设置。非 Retina 显示器上可以调大。" - } + L10nKey::SettingsUiFontSizeDesc => "标签页、面板、设置等非终端文字的大小。", L10nKey::SettingsUiFontFamily => "界面字体", - L10nKey::SettingsUiFontFamilyDesc => { - "用于标签页、侧栏、弹窗和设置的字体;默认使用系统 UI 字体。" - } + L10nKey::SettingsUiFontFamilyDesc => "用于标签页、侧栏、弹窗和设置。", L10nKey::SettingsLineHeight => "行高", L10nKey::SettingsLineHeightDesc => "行间距为字号的倍数。", L10nKey::SettingsFontFamily => "终端字体", L10nKey::SettingsFontFamilyDesc => "从系统已安装的字体中选择。", L10nKey::SettingsBoldFont => "粗体字体", - L10nKey::SettingsBoldFontDesc => "粗体文字使用的字体;默认由主字体合成。", + L10nKey::SettingsBoldFontDesc => "粗体字形;默认由主字体合成。", L10nKey::SettingsItalicFont => "斜体字体", - L10nKey::SettingsItalicFontDesc => "斜体文字使用的字体;默认由主字体合成。", + L10nKey::SettingsItalicFontDesc => "斜体字形;默认由主字体合成。", L10nKey::SettingsFontLigatures => "字体连字", - L10nKey::SettingsFontLigaturesDesc => "为终端文字启用常见的编程连字特性。", + L10nKey::SettingsFontLigaturesDesc => "终端文字启用编程连字。", L10nKey::SettingsFontThicken => "笔画加粗", - L10nKey::SettingsFontThickenDesc => { - "macOS 字体平滑:文字画得稍粗,浅色文字最明显。重启 tty7 后生效。" - } + L10nKey::SettingsFontThickenDesc => "文字画得稍粗一些,重启后生效。", L10nKey::SettingsCursor => "光标", L10nKey::SettingsCursorShape => "光标形状", L10nKey::SettingsCursorShapeDesc => "终端光标的绘制方式。", @@ -138,9 +194,7 @@ pub fn translate_zh(key: L10nKey) -> Option<&'static str> { } L10nKey::SettingsTransparency => "透明度", L10nKey::SettingsOpacity => "不透明度", - L10nKey::SettingsOpacityDesc => { - "窗口背景的不透明度,适用于所有主题。低于 100% 时可以看到桌面。" - } + L10nKey::SettingsOpacityDesc => "低于 100% 时可透出桌面。", L10nKey::SettingsBlur => "模糊", L10nKey::SettingsBlurDesc => { if cfg!(target_os = "macos") { @@ -149,13 +203,9 @@ pub fn translate_zh(key: L10nKey) -> Option<&'static str> { "模糊半透明窗口背后的内容。需要合成器支持——KDE Plasma 可以;GNOME 和裸 X11 下窗口只会变透明。" } } - L10nKey::SettingsBlurAutoDesc => { - "模糊半透明窗口背后的内容。仅在「背景材质」为「自动」时生效。" - } + L10nKey::SettingsBlurAutoDesc => "模糊窗口背后的内容,仅限「自动」材质。", L10nKey::SettingsBackdrop => "背景材质", - L10nKey::SettingsBackdropDesc => { - "半透明窗口背后的原生 Windows 背景材质。云母需要 Windows 11 22H2,亚克力需要 1809;更旧的系统会自动回退。" - } + L10nKey::SettingsBackdropDesc => "半透明窗口背后的原生背景材质。", L10nKey::SettingsSearchBackdropKeywords => { "材质 背景 云母 亚克力 模糊 毛玻璃 窗口 material backdrop mica acrylic blur frosted window background" } @@ -175,9 +225,7 @@ pub fn translate_zh(key: L10nKey) -> Option<&'static str> { L10nKey::SettingsImageOpacity => "图片不透明度", L10nKey::SettingsImageOpacityDesc => "图片叠加在背景色上的显示强度。", L10nKey::SettingsEditTheme => "编辑主题", - L10nKey::SettingsEditThemeIntro => { - "你正在编辑一份副本。更改会保存到主题文件夹中的对应文件并实时生效。" - } + L10nKey::SettingsEditThemeIntro => "正在编辑副本,更改实时生效并保存到主题文件夹。", L10nKey::SettingsBackgroundImage => "背景图片", L10nKey::SettingsBackgroundImageDesc => "叠加在背景色之上、文字之下。", L10nKey::SettingsAnsiColors => "ANSI 颜色", @@ -189,7 +237,7 @@ pub fn translate_zh(key: L10nKey) -> Option<&'static str> { L10nKey::ExplorerMenuOpenIn => "在 tty7 中打开", L10nKey::ExplorerMenuOpenHere => "在此处打开 tty7", L10nKey::SettingsCustomThemesIntro => { - "复制一个主题即可在此编辑颜色,或把 tty7 YAML 主题、iTerm2 .itermcolors 文件放进主题文件夹。" + "复制主题后即可编辑,或把 YAML、.itermcolors 文件放进主题文件夹。" } L10nKey::SettingsDuplicateToEdit => "复制以编辑", L10nKey::SettingsHosts => "主机", @@ -206,9 +254,7 @@ pub fn translate_zh(key: L10nKey) -> Option<&'static str> { L10nKey::SettingsMoreInSshConfig => "~/.ssh/config 中还有 {count} 个", L10nKey::SettingsAliasesLinked => "已关联 {count} 个别名。", L10nKey::SettingsImportAliases => "导入别名", - L10nKey::SettingsImportAliasesDesc => { - "重新读取文件并添加新内容。你在这里做的编辑由 tty7 保存——不会写入该文件本身。" - } + L10nKey::SettingsImportAliasesDesc => "重新读取文件并添加新条目,不会改动文件本身。", L10nKey::SettingsImportNow => "立即导入", L10nKey::SettingsImportUnreadable => "无法读取 {path}——没有导入任何内容。", L10nKey::SettingsImportNoHosts => "{path} 中没有可导入的主机——只有通配符或 Match 规则。", @@ -219,9 +265,7 @@ pub fn translate_zh(key: L10nKey) -> Option<&'static str> { "有 {count} 个选项在 tty7 中没有对应设置,仍留在文件里:{options}" } L10nKey::SettingsImportMoreOptions => "还有 {count} 个", - L10nKey::SettingsDefaultsIntro => { - "所有主机都从这些设置开始。每个主机都可以在自己的高级选项中覆盖某项。" - } + L10nKey::SettingsDefaultsIntro => "所有主机都以此为默认值,可在各自的高级选项中覆盖。", L10nKey::SettingsCopyAddress => "复制地址", L10nKey::SettingsDuplicate => "复制", L10nKey::SettingsForgetPassword => "清除已保存的密码", @@ -244,12 +288,10 @@ pub fn translate_zh(key: L10nKey) -> Option<&'static str> { L10nKey::SettingsSecurityIntro => "主机可以在自己的高级选项中覆盖这些设置。", L10nKey::SettingsVerifyHostKeys => "校验主机密钥", L10nKey::SettingsVerifyHostKeysDesc => { - "连接前对照 known_hosts 检查服务器密钥。关闭后不做检查,被仿冒的服务器也不会被察觉。" + "连接前对照 known_hosts 校验服务器密钥。关闭后无法察觉仿冒的服务器。" } L10nKey::WarnBeforeClosing => "关闭前警告", - L10nKey::SettingsWarnBeforeClosingDesc => { - "在关闭带有活动 SSH 会话的标签页或窗格前请求确认。" - } + L10nKey::SettingsWarnBeforeClosingDesc => "关闭有活动 SSH 会话的标签页前确认。", L10nKey::SettingsNewHost => "新主机", L10nKey::SettingsDiscardChangesTitle => "放弃未保存的更改?", L10nKey::SettingsDiscardChangesBody => "当前连接有未保存的更改。", @@ -301,9 +343,7 @@ pub fn translate_zh(key: L10nKey) -> Option<&'static str> { L10nKey::SettingsGroupSession => "会话", L10nKey::SettingsGroupSecurity => "安全", L10nKey::SettingsRemoteClipboardWrite => "远端剪贴板图片", - L10nKey::SettingsRemoteClipboardWriteDesc => { - "允许此主机上的程序通过 OSC 5522 用图片覆盖本机剪贴板。" - } + L10nKey::SettingsRemoteClipboardWriteDesc => "允许此主机通过 OSC 5522 写入图片到剪贴板。", L10nKey::SettingsIdentityFiles => "身份文件", L10nKey::SettingsIdentityFilesDesc => "私钥路径,每行一个(支持 %h/%r 展开)。", L10nKey::SettingsAgentForwarding => "ssh-agent 转发", @@ -375,18 +415,14 @@ pub fn translate_zh(key: L10nKey) -> Option<&'static str> { L10nKey::SettingsOn => "开", L10nKey::SettingsOff => "关", L10nKey::SettingsShell => "Shell", - L10nKey::SettingsShellIntro => { - "每个新终端启动的程序。将“Shell 程序”留空可使用平台默认值({default})。" - } + L10nKey::SettingsShellIntro => "新终端启动的程序,留空则使用 {default}。", L10nKey::SettingsProgram => "Shell 程序", - L10nKey::SettingsProgramDesc => "PATH 中的可执行文件名或绝对路径,例如 zsh、fish、pwsh。", + L10nKey::SettingsProgramDesc => "PATH 中的命令名或绝对路径,如 zsh、fish。", L10nKey::SettingsArguments => "Shell 参数", - L10nKey::SettingsArgumentsDesc => { - "启动参数,按命令行规则切分——含空格的参数请用引号包住(例如 -l,或 -c \"echo hi\")。" - } + L10nKey::SettingsArgumentsDesc => "按命令行规则切分,例如 -l 或 -c \"echo hi\"。", L10nKey::SettingsArgumentsInvalid => "引号不配对,该值未保存。", L10nKey::SettingsStartIn => "启动目录", - L10nKey::SettingsStartInDesc => "新 shell 的启动目录:tty7 的启动目录、主目录或固定路径。", + L10nKey::SettingsStartInDesc => "tty7 的启动目录、主目录或固定路径。", L10nKey::SettingsCustomPath => "自定义路径", L10nKey::SettingsCustomPathDesc => "新 shell 启动的目录。", L10nKey::SettingsWdInherit => "继承", @@ -394,7 +430,7 @@ pub fn translate_zh(key: L10nKey) -> Option<&'static str> { L10nKey::SettingsWdCustom => "自定义", L10nKey::SettingsWdPathInvalid => "这个目录不存在,该值未保存。", L10nKey::SettingsShellFooter => { - "仅适用于没有目录可继承的 shell,例如窗口的第一个标签页。新标签页和分屏仍继承活动窗格的目录,已打开的 shell 继续运行。" + "仅用于没有目录可继承的 shell,例如窗口的第一个标签页;新标签页和分屏沿用当前窗格的目录。" } L10nKey::SettingsScrolling => "滚动", L10nKey::SettingsScrollback => "终端输出历史行数", @@ -402,39 +438,32 @@ pub fn translate_zh(key: L10nKey) -> Option<&'static str> { L10nKey::SettingsScrollSpeed => "滚动速度", L10nKey::SettingsScrollSpeedDesc => "应用于鼠标滚轮滚动的倍率。", L10nKey::SettingsSmoothScroll => "平滑滚动", - L10nKey::SettingsSmoothScrollDesc => { - "滚轮每一格分几帧滚到位,而不是一次跳完。触控板本来就是连续滚动,不受影响。" - } + L10nKey::SettingsSmoothScrollDesc => "滚轮每格分几帧滚动,触控板不受影响。", L10nKey::SettingsMouse => "鼠标", L10nKey::SettingsFocusFollowsMouse => "焦点跟随鼠标", L10nKey::SettingsFocusFollowsMouseDesc => "悬停窗格即聚焦,无需点击。", L10nKey::SettingsHideMouseWhileTyping => "输入时隐藏鼠标", L10nKey::SettingsHideMouseWhileTypingDesc => "输入时隐藏指针;下次移动鼠标时恢复。", L10nKey::SettingsMouseZoom => "滚轮缩放", - L10nKey::SettingsMouseZoomDesc => "按住该修饰键滚轮时缩放终端字号,而不是滚动。", + L10nKey::SettingsMouseZoomDesc => "按住它滚动滚轮可缩放终端字号。", L10nKey::SettingsMouseZoomOff => "关闭", L10nKey::SettingsReportMouseToApps => "向应用报告鼠标", L10nKey::SettingsReportMouseToAppsDesc => { - "让全屏应用(如 vim、tmux)处理点击和滚动;按住 Shift 可让操作保持本地。\ - 关闭后点击不再传给它们,滚轮也会变成方向键。" + "让 vim、tmux 等应用处理点击,按住 Shift 则留在本地。" } L10nKey::SettingsBell => "铃声", L10nKey::SettingsTerminalBell => "终端铃声", - L10nKey::SettingsTerminalBellDesc => { - "铃声(^G)的通知方式:静音、短暂闪烁、系统声音,或两者同时。" - } + L10nKey::SettingsTerminalBellDesc => "铃声(^G)的提示方式。", L10nKey::SettingsLinks => "链接", L10nKey::DetectUrls => "检测 URL", - L10nKey::SettingsDetectUrlsDesc => "悬停时给链接加下划线,通过 {modifier}+点击 打开。", + L10nKey::SettingsDetectUrlsDesc => "悬停显示下划线,{modifier}+点击 打开。", L10nKey::ForwardSshLoopbackLinks => "转发远程端口", - L10nKey::SettingsForwardSshLoopbackLinksDesc => { - "SSH 会话里,自动转发窗格开始监听的端口,并在本机打开它的 localhost 链接。" - } + L10nKey::SettingsForwardSshLoopbackLinksDesc => "在本机打开远程窗格的 localhost 链接。", L10nKey::SettingsOpenFilesInternal => "内置编辑器", L10nKey::SettingsOpenFilesSystem => "默认应用", L10nKey::SettingsOpenFilesCommand => "自定义命令", L10nKey::SettingsOpenFilesModeDesc => { - "{modifier}+点击 文件链接时用什么打开。只有内置编辑器能跳到指定行、能打开远程主机上的文件。" + "{modifier}+点击 文件链接时用什么打开。只有内置编辑器能跳到指定行、打开远程文件。" } L10nKey::LinkFileNotUnder => "{path} —— {dir} 下没有这个文件", L10nKey::LinkFileNoDirectory => { @@ -443,37 +472,27 @@ pub fn translate_zh(key: L10nKey) -> Option<&'static str> { L10nKey::LinkFileMissing => "{path} —— 这个路径下什么也没有", L10nKey::LinkDirOutsideTree => "{path} —— 它在另一台机器上,也不在文件面板打开的任何目录里", L10nKey::OpenFilesWith => "打开文件方式", - L10nKey::SettingsOpenFilesWithDesc => { - "{modifier}+点击 文件链接时运行的命令。可用 {path}、{line}、{column}——取值缺失的标志会被丢弃。留空则用默认应用。" - } + L10nKey::SettingsOpenFilesWithDesc => "可用 {path}、{line}、{column},留空用默认应用。", L10nKey::SettingsBellModeOff => "关", L10nKey::SettingsBellModeVisual => "闪烁", L10nKey::SettingsBellModeAudible => "声音", L10nKey::SettingsBellModeBoth => "闪烁 + 声音", L10nKey::SettingsPrompt => "提示符与命令历史", - L10nKey::SettingsPromptIntro => { - "shell 提示符处的 tty7 自带编辑器与菜单。关闭某项即可把这部分交还给 shell。" - } + L10nKey::SettingsPromptIntro => "提示符上 tty7 自带的编辑器和菜单,关闭即交还给 shell。", L10nKey::SettingsPromptEditor => "tty7 提示符编辑器", L10nKey::SettingsPromptEditorDesc => { - "由 tty7 编辑你在 shell 提示符上敲的这一行:选择、撤销,以及下面这些菜单。关闭后交还给 shell 自己的行编辑器——ZLE、readline、fish。" + "在输入行上提供选择、撤销和菜单。关闭后交还给 ZLE、readline 或 fish。" } L10nKey::SettingsNeedsPromptEditor => { "需要提示符编辑器:它关闭时,这个按键本就归 shell 所有。" } L10nKey::SettingsTabCompletion => "Tab 补全", - L10nKey::SettingsTabCompletionDesc => { - "在提示符按 Tab 打开 tty7 的补全菜单。关闭后 Tab 交由 shell 自身的补全处理。" - } + L10nKey::SettingsTabCompletionDesc => "Tab 打开 tty7 的补全菜单,关闭后交给 shell。", L10nKey::SettingsHistorySearch => "命令历史搜索", - L10nKey::SettingsHistorySearchDesc => { - "在提示符按 ⌃R 打开 tty7 的模糊历史菜单。关闭后 ⌃R 交给 shell——它自带的反向搜索,或你绑定的其它功能(fzf、percol)。" - } + L10nKey::SettingsHistorySearchDesc => "⌃R 打开 tty7 的模糊历史搜索,关闭后交给 shell。", L10nKey::SettingsSelectionClipboard => "选择与剪贴板", L10nKey::SettingsSmartSelection => "智能选择", - L10nKey::SettingsSmartSelectionDesc => { - "双击选择光标下的完整 URL、文件路径、邮箱或成对的括号。" - } + L10nKey::SettingsSmartSelectionDesc => "双击选中完整的 URL、路径、邮箱或括号对。", L10nKey::SettingsCopyOnSelect => "选中即复制", L10nKey::SettingsCopyOnSelectDesc => { if cfg!(target_os = "macos") { @@ -486,12 +505,10 @@ pub fn translate_zh(key: L10nKey) -> Option<&'static str> { L10nKey::SettingsTrimTrailingSpacesDesc => "去除每行复制文本末尾的空白。", L10nKey::SettingsKeyboard => "键盘", L10nKey::SettingsOptionAsMeta => "Option (⌥) 作为 Meta", - L10nKey::SettingsOptionAsMetaDesc => { - "⌥+按键 发送 shell 期望的转义组合键(⌥B = 后退一个词),而不是输入特殊字符(∫)。" - } - L10nKey::SettingsAgentsIntro => "AI agent", + L10nKey::SettingsOptionAsMetaDesc => "⌥+按键 作为 Meta,如 ⌥B 后退一词。", + L10nKey::SettingsAgentsIntro => "Agent 钩子", L10nKey::SettingsAgentsIntroDesc => { - "安装 hook,让运行 AI agent 的窗格在标签栏显示实时状态(进行中 / 等待中 / 已完成)。仅在 tty7 内生效。" + "安装 hook 后,agent 的状态(进行中 / 等待中 / 已完成)会显示在标签栏。" } L10nKey::SettingsReadingAgentConfig => "正在读取这台机器的 AI agent 配置…", L10nKey::SettingsStatusNotInstalled => "未安装", @@ -504,10 +521,10 @@ pub fn translate_zh(key: L10nKey) -> Option<&'static str> { L10nKey::SettingsOfflineMachines => { "还有 {count} 台已保存的机器未连接——在其中一台上打开工作区,即可在那台机器上安装 hook。" } - L10nKey::SettingsSyncWithSystem => "跟随系统", + L10nKey::SettingsSyncWithSystem => "外观", L10nKey::SettingsSyncWithSystemDesc => "跟随操作系统外观,并分别使用浅色与深色主题。", L10nKey::SettingsLegiblePalette => "低对比度颜色纠偏", - L10nKey::SettingsLegiblePaletteDesc => "自动把主题背景上对比度不足的颜色调整到可读级别。", + L10nKey::SettingsLegiblePaletteDesc => "自动调整在背景上看不清的亮色。", L10nKey::SettingsChangeTheme => "更换主题", L10nKey::SettingsThemes => "主题", L10nKey::SettingsThemesCloseTooltip => "关闭主题面板 (Esc)", @@ -525,30 +542,20 @@ pub fn translate_zh(key: L10nKey) -> Option<&'static str> { L10nKey::SettingsStartupWindow => "启动窗口", L10nKey::SettingsStartupWindowDesc => "tty7 启动时的窗口状态。", L10nKey::SettingsRememberWindowSize => "记住窗口大小与位置", - L10nKey::SettingsRememberWindowSizeDesc => { - "以 tty7 上次退出时窗口的大小和位置重新打开。关闭时以默认大小居中打开。" - } + L10nKey::SettingsRememberWindowSizeDesc => "按上次退出时的大小和位置打开窗口。", L10nKey::SettingsRestoreLastLayout => "恢复上次布局", - L10nKey::SettingsRestoreLastLayoutDesc => { - "启动时恢复上次窗口的标签页、分屏和目录。关闭时从单个新终端开始。" - } + L10nKey::SettingsRestoreLastLayoutDesc => "启动时恢复上次的标签页、分屏和目录。", L10nKey::SettingsShowTrayIcon => "显示托盘图标", - L10nKey::SettingsShowTrayIconDesc => { - "在系统托盘/菜单栏保留状态项:agent 需要输入时发出提示,菜单可跳到该 agent 的窗格。" - } + L10nKey::SettingsShowTrayIconDesc => "agent 等待输入时提醒,可跳到对应窗格。", L10nKey::SettingsTabs => "标签页", L10nKey::SettingsNewTabPosition => "新标签页位置", L10nKey::SettingsNewTabPositionDesc => "新打开的标签页插入的位置。", L10nKey::SettingsTabBarPosition => "标签栏位置", L10nKey::SettingsTabBarPositionDesc => "将标签页显示为顶部横向条或左侧垂直侧栏。", L10nKey::SettingsSidebarGrouping => "侧栏分组", - L10nKey::SettingsSidebarGroupingDesc => { - "按 git 仓库给侧栏标签页分组。仓库外的标签页归到“草稿”,选“按仓库或文件夹”时则按工作目录分。仅左侧栏。" - } + L10nKey::SettingsSidebarGroupingDesc => "按 git 仓库分组侧栏标签页,其余归入“草稿”。", L10nKey::SettingsDiffPreviewFromCounts => "从侧栏计数打开 diff 预览", - L10nKey::SettingsDiffPreviewFromCountsDesc => { - "点击行上的 +N −N 在浮层中打开 worktree diff。关闭后计数仍显示,只是不可点击。" - } + L10nKey::SettingsDiffPreviewFromCountsDesc => "点击行上的 +N −N 打开 diff。", L10nKey::DocumentDock => "停靠在终端旁", L10nKey::DocumentFill => "铺满窗口", L10nKey::SettingsNotifications => "通知", @@ -571,18 +578,14 @@ pub fn translate_zh(key: L10nKey) -> Option<&'static str> { L10nKey::SettingsByRepoOrFolder => "按仓库或文件夹", L10nKey::SettingsFlat => "平铺", L10nKey::SettingsPreset => "预设", - L10nKey::SettingsPresetDesc => { - "tmux 预设把窗格/标签页操作映射为前缀序列(例如 Ctrl-B 后按 C)。" - } + L10nKey::SettingsPresetDesc => "tmux 预设把操作映射为前缀键(如 Ctrl-B C)。", L10nKey::SettingsPrefix => "前缀", L10nKey::SettingsPressKeys => "按下按键… · ⌫ 表示不设快捷键", L10nKey::SettingsPauseToSaveEsc => "暂停以保存 · Esc", L10nKey::SettingsKeybindingsIntroDesc => { - "点击某个快捷键,再按下新按键,短暂停顿后保存。连续按键可组成序列,例如 Ctrl-B 后按 X。Esc 取消;Backspace 移除最后一个按键,最先按下则不设快捷键,点「重置」可恢复默认。" - } - L10nKey::SettingsPrefixNote => { - "启用前缀后,单独按前缀键约 1 秒后会传给 shell,前缀 + 未绑定的按键会直接发送到终端。" + "点击快捷键后按新按键,连按可组成序列(如 Ctrl-B X)。Esc 取消,Backspace 清除。" } + L10nKey::SettingsPrefixNote => "单独按前缀键,约 1 秒后传给 shell。", L10nKey::SettingsRestoreAllDefaults => "恢复全部默认值", L10nKey::SettingsRestoreAllDefaultsBody => "你改过的每一个按键都会退回默认值,且无法撤销。", L10nKey::KeybindGoToTab => "跳到第 {n} 个标签页", @@ -592,10 +595,12 @@ pub fn translate_zh(key: L10nKey) -> Option<&'static str> { L10nKey::KeybindForkSessionLeft => "向左 Fork 会话", L10nKey::KeybindForkSessionDown => "向下 Fork 会话", L10nKey::KeybindForkSessionUp => "向上 Fork 会话", - L10nKey::SettingsAboutDesc1 => "终端工作台:持久会话、远程开发、AI agent。", + L10nKey::SettingsAboutDesc1 => { + "为长时间工作打造的终端工作台。会话不随窗口关闭而结束,远程主机用起来和本地一样,编程 agent 的状态直接显示在侧栏里。" + } L10nKey::SettingsDefaultTerminal => "默认终端", L10nKey::SettingsDefaultTerminalDesc => { - "将 tty7 设为 Unix 可执行文件、SSH 链接和 man 页面链接的 macOS 默认终端。tty7 仍可打开文件夹和脚本,但不会替换 Finder 的文件夹处理程序。自行指定终端的应用可能不会遵循此设置。" + "用 tty7 打开 Unix 可执行文件、SSH 链接和 man 页面。" } L10nKey::SettingsDefaultTerminalSet => "设为默认终端", L10nKey::SettingsDefaultTerminalSetSuccess => { @@ -623,18 +628,14 @@ pub fn translate_zh(key: L10nKey) -> Option<&'static str> { L10nKey::SettingsUpdateInstallNow => "安装并重启", L10nKey::SettingsUpdateDiscard => "丢弃", L10nKey::SettingsAutoDownload => "后台下载更新", - L10nKey::SettingsAutoDownloadDesc => { - "发现新版本就先下载并校验好,安装时只需重启一下。不会未经确认就安装。安装包约 30 MB。" - } + L10nKey::SettingsAutoDownloadDesc => "后台下载新版本,安装时只需重启;不会未经确认就安装。", L10nKey::SettingsUpdateChannel => "更新通道", - L10nKey::SettingsUpdateChannelDesc => { - "稳定版(Stable)跟随正式发布的版本;每夜构建(Nightly)跟随每晚从最新代码构建的版本,更新更快,但未经发布测试。" - } + L10nKey::SettingsUpdateChannelDesc => "Nightly 每晚从最新代码构建,未经发布测试。", L10nKey::SettingsUpdateChannelStable => "稳定版", L10nKey::SettingsUpdateChannelNightly => "每夜构建", L10nKey::SettingsDaemonStale => "tty7 server 仍运行在 {build}。", L10nKey::SettingsDaemonStaleDesc => { - "tty7 是原地升级的:界面已是新版,窗格还由旧版 tty7 server 托管。重启 tty7 server 换成新版,代价是窗格里正在跑的进程全部结束。不急,挑窗格空闲时再重启。" + "tty7 已更新,但窗格仍跑在旧版 server 上。重启后换用新版,窗格中运行的进程会全部结束。" } L10nKey::UpdateDialogTitle => "有可用更新", L10nKey::UpdateDialogDetail => { @@ -679,17 +680,13 @@ pub fn translate_zh(key: L10nKey) -> Option<&'static str> { L10nKey::SettingsCheckUpdatesDesc => "无法就地更新的安装方式会改为打开发布页面。", L10nKey::SettingsCheckUpdatesOnLaunch => "启动时检查更新", L10nKey::SettingsCommandLine => "命令行", - L10nKey::SettingsCommandLineDesc => { - "让脚本和 AI agent 使用随应用提供的 tty7 命令。下次启动生效;关闭后不会移除已安装的命令。" - } + L10nKey::SettingsCommandLineDesc => "把 tty7 命令加入 PATH,下次启动生效。", L10nKey::SettingsInstallCliOnPath => "将 tty7 命令安装到 PATH", L10nKey::SettingsServer => "tty7 server", - L10nKey::SettingsServerDesc => "管理这台计算机上的终端会话,让会话在后台持续运行。", + L10nKey::SettingsServerDesc => "让终端会话在后台持续运行。", L10nKey::SettingsRestartServer => "重启 tty7 server…", L10nKey::SettingsAppHttpProxy => "更新代理", - L10nKey::SettingsAppHttpProxyDesc => { - "仅用于 tty7 自身的更新检查和下载,不影响窗格中运行的程序。留空则跟随系统代理。" - } + L10nKey::SettingsAppHttpProxyDesc => "仅用于 tty7 的更新检查,留空跟随系统。", L10nKey::SettingsAppHttpProxyInvalid => "不是有效的代理地址,该值未保存。", L10nKey::SettingsAgentClaudeCode => "Claude Code", L10nKey::SettingsAgentCodex => "Codex", @@ -1655,7 +1652,7 @@ pub fn translate_zh(key: L10nKey) -> Option<&'static str> { L10nKey::Replace => "覆盖", L10nKey::SftpErrorInvalidOctalMode => "无效的八进制模式", L10nKey::SettingsDaemonStaleDescInPlace => { - "tty7 是原地更新的:应用是新的,窗格还跑在旧版上。tty7 server 可以不停机就换成新版,shell 直接延续下来。用 tty7 内置 SSH 客户端的窗格除外——那些连接会断开,需要重新打开。" + "tty7 已更新。server 可原地替换,shell 不受影响;只有内置 SSH 的窗格会断开。" } L10nKey::AppRestartServerBodyInPlace => { "tty7 server 会原地把自己换成当前这个版本:shell 继续运行,窗口稍后自动连回去。用 tty7 内置 SSH 客户端的窗格除外——那些连接会断开,需要重新打开。" @@ -1664,9 +1661,7 @@ pub fn translate_zh(key: L10nKey) -> Option<&'static str> { "已恢复的画面 —— 下面是新的 shell,上面的内容都已不在运行" } L10nKey::SettingsPerPaneHistory => "各窗格使用独立命令历史", - L10nKey::SettingsPerPaneHistoryDescription => { - "上方向键翻的是这个窗格里跑过的命令,而不是所有窗格混在一起。新窗格从已有历史开始,关闭时把新增的写回去。只对 tty7 能接管的 bash 和 zsh 窗格生效;用你自己参数启动的 shell 不受影响。" - } + L10nKey::SettingsPerPaneHistoryDescription => "↑ 只翻本窗格的历史,仅限 bash 和 zsh。", L10nKey::IntegrationNoticeBlocked => { "“{wrapper}”截获了此窗格的 shell 上报,内联补全和 Ctrl+R 菜单不可用。shell 自带的历史搜索仍可使用。" } @@ -1806,6 +1801,18 @@ pub fn translate_zh(key: L10nKey) -> Option<&'static str> { pub fn translate_variant_zh(key: L10nKey, branch: &'static str) -> Option<&'static str> { let res = match (key, branch) { + (L10nKey::SettingsMatchCount, "zero") => "没有结果", + (L10nKey::SettingsMatchCount, "one") => "1 个结果", + (L10nKey::SettingsMatchCount, "other") => "{count} 个结果", + (L10nKey::SettingsRestoreChanged, "zero") => "恢复修改", + (L10nKey::SettingsRestoreChanged, "one") => "恢复 1 项修改", + (L10nKey::SettingsRestoreChanged, "other") => "恢复 {count} 项修改", + (L10nKey::SettingsMoreHosts, "zero") => "没有更多主机", + (L10nKey::SettingsMoreHosts, "one") => "还有 1 台主机", + (L10nKey::SettingsMoreHosts, "other") => "还有 {count} 台主机", + (L10nKey::SettingsMoreAgents, "zero") => "没有更多 Agent", + (L10nKey::SettingsMoreAgents, "one") => "还有 1 个可用 Agent", + (L10nKey::SettingsMoreAgents, "other") => "还有 {count} 个可用 Agent", (L10nKey::SettingsDeleteProfileCascade, "one") => { "有 1 个已保存的远程工作区条目指向 {endpoint},将随配置一并从本机清除;\ 远端机器上的会话不受影响,新建配置连上同一台机器后即可在工作区列表找回。" diff --git a/src/ui/rounding.rs b/src/ui/rounding.rs index 65275b2f..10a8afef 100644 --- a/src/ui/rounding.rs +++ b/src/ui/rounding.rs @@ -11,9 +11,11 @@ pub(crate) trait RoundedCorners: Styled + Sized { impl RoundedCorners for T {} +#[allow(dead_code)] pub(crate) const TRACK_RADIUS: Pixels = px(8.); /// Inset cards, interactive rows, and floating panels share the A style scale. +#[allow(dead_code)] pub(crate) const CARD_RADIUS: Pixels = px(10.); pub(crate) const ROW_RADIUS: Pixels = px(7.); pub(crate) const POPOVER_RADIUS: Pixels = px(10.); diff --git a/src/ui/settings.rs b/src/ui/settings.rs index 838f438c..7ccfcc2d 100644 --- a/src/ui/settings.rs +++ b/src/ui/settings.rs @@ -1,24 +1,15 @@ use gpui::{ - Animation, AnimationExt as _, AnyElement, App, Background, Context, Div, Entity, - Focusable as _, FontWeight, Image, ImageFormat, KeyDownEvent, MouseButton, SharedString, - Stateful, Subscription, Window, div, img, prelude::*, px, relative, rgb, + AnyElement, App, Background, Context, Div, ElementId, Entity, Focusable as _, FontWeight, + KeyDownEvent, MouseButton, SharedString, Stateful, Subscription, Window, div, prelude::*, px, + rgb, }; use gpui_component::InteractiveElementExt as _; -use gpui_component::button::{Button, ButtonCustomVariant, ButtonVariants as _}; use gpui_component::color_picker::{ColorPicker, ColorPickerState}; use gpui_component::input::{Input, InputEvent, InputState}; use gpui_component::link::Link; -use gpui_component::menu::{ContextMenuExt as _, DropdownMenu as _, PopupMenu, PopupMenuItem}; use gpui_component::notification::{Notification, NotificationType}; -use gpui_component::select::{SearchableVec, Select, SelectEvent, SelectState}; -use gpui_component::sidebar::{Sidebar, SidebarCollapsible, SidebarMenu, SidebarMenuItem}; -use gpui_component::slider::{Slider, SliderState}; -use gpui_component::{ - ActiveTheme as _, Disableable as _, Icon, IconName, IndexPath, Selectable as _, Sizable as _, - WindowExt as _, h_flex, v_flex, -}; +use gpui_component::{Icon, Sizable as _, WindowExt as _, h_flex, v_flex}; use std::cell::{Cell, RefCell}; -use std::sync::Arc; use uuid::Uuid; @@ -32,190 +23,57 @@ use crate::core::keychain::{ use crate::core::ssh_profile::{ Algorithms, AuthMode, ForwardKind, ForwardRule, HostPort, SshProfile, to_connect_string, }; -use crate::daemon::protocol::{SshTestNeed, SshTestReport}; use crate::ui::app::{ - FONT_SIZE_STEP, LINE_HEIGHT_STEP, TILE_GLYPH_LINE, TILE_SIZE, TITLE_BAR_HEIGHT, ThemeEdit, - Tty7App, UI_FONT_SIZE_STEP, + FONT_SIZE_STEP, LINE_HEIGHT_STEP, TITLE_BAR_HEIGHT, ThemeEdit, Tty7App, UI_FONT_SIZE_STEP, }; use crate::ui::host_ops::HostId; use crate::ui::i18n::{L10nKey, t, t_fmt, t_plural}; use crate::ui::presets; -use crate::ui::rounding; -use crate::ui::rounding::RoundedCorners as _; -/// The settings nav, the SSH host list, the theme panel, and the padding each -/// page sets — the chrome a row has to share the window with. +mod agents; +mod hosts; +pub(crate) mod kit; +mod pages; +mod shell; +mod shortcuts; +mod theme_picker; + +/// The settings nav, and the page's padding either side of its column. const NAV_W: f32 = 220.; -const SSH_LIST_W: f32 = 280.; -const THEME_PANEL_W: f32 = 300.; -const SSH_DETAIL_PAD: f32 = 64.; -const PAGE_PAD: f32 = 80.; +const PAGE_PAD: f32 = 112.; -/// The narrowest window these numbers have to hold for. +/// The narrowest the nav is still itself: an item that still shows its label +/// beside its icon. /// -/// `ui::windows::MIN_SIZE` declares 720, but the settings window in the report -/// this file was fixed for measured 641pt: `window_min_size` governs dragging, -/// not the bounds a window opens with, so a remembered bound walked straight -/// under it. `ui::windows::at_least_min_size` now closes that path, and this -/// stays below it deliberately — a declared minimum is a claim about the code, -/// and this file would rather be laid out for the window that turns up. -const NARROWEST_WINDOW: f32 = 640.; - -/// The narrowest each list is still itself: a nav item that still shows a label -/// beside its icon (40 of icon, gap and padding, then the longest label), a -/// host row that still shows a name, a theme card that is still a recognisable -/// picture of a theme. -/// -/// The nav floor is sized for the longest nav label in *any* locale, not the -/// one the developer happens to be reading. `SidebarMenuItem` clips its label -/// rather than eliding it, so a floor that fits English cuts a glyph in half in -/// Chinese and Japanese: at 140 the zh-CN "窗口与标签页" lost the right half of -/// its last character. The widest is ja-JP "ウィンドウとタブ" — 8 full-width -/// kana beside the icon, which is 36 more than the 6-glyph Chinese label needs. +/// Sized for the longest nav label in *any* locale, not the one the developer +/// happens to be reading: at 140 the zh-CN "窗口与标签页" lost the right half +/// of its last character. The widest is ja-JP "ウィンドウとタブ". const NAV_W_MIN: f32 = 176.; -const SSH_LIST_W_MIN: f32 = 180.; -const THEME_PANEL_W_MIN: f32 = 240.; -/// The reading column every scrolled page caps itself at. Wider than this and -/// a description stops being a paragraph and becomes a line to scan across. -const READING_COLUMN: f32 = 640.; +/// The reading column every page caps itself at. Wider than this and a +/// description stops being a paragraph and becomes a line to scan across. +const READING_COLUMN: f32 = 620.; /// How far the content scrollbar stays clear of the top and bottom of the -/// window. The page has no chrome of its own to stop at, so a bar drawn to the -/// last pixel runs into the window's rounded corner and looks cut off. +/// window, so it does not run into the window's rounded corner. const SCROLLBAR_WINDOW_INSET: f32 = 12.; -/// What the page gets before any list does, and the floor it may be pushed to -/// when even that cannot be had — the numbers this file did not have. -/// -/// Every list beside the page was a fixed width that never gave anything back, -/// so the page absorbed the entire shortfall. On a half-width window with the -/// theme panel open that ran all the way down: a Chinese description came out -/// one character per line, twenty-five lines tall, and the theme cards under it -/// were slivers clipped by the window edge. -/// -/// `CONTENT_W` holds a stacked row's widest control — the 260px text fields — -/// with a description beside it that still reads as a paragraph. `CONTENT_MIN_W` -/// is not chosen at all: it is what the narrowest window in the wild leaves the -/// SSH page, the one that spends a second list, once both lists are standing on -/// their own floors. A control wider than it has to be able to shrink, which is -/// what `max_w_full` on the wrappers below is for. +/// What the page gets before the nav gives anything back: a row's widest +/// control with a description beside it that still reads as a paragraph. const CONTENT_W: f32 = 420.; -const CONTENT_MIN_W: f32 = NARROWEST_WINDOW - NAV_W_MIN - SSH_LIST_W_MIN - SSH_DETAIL_PAD; -/// What the settings page is made of at a given window width. -#[derive(Clone, Copy, PartialEq, Debug)] -struct SettingsColumns { - nav: f32, - /// Zero off the SSH page. - ssh_list: f32, - /// The width to *draw* the theme panel at, whether it is taking a column or - /// covering one — zero only when it is closed. - theme_panel: f32, - /// The panel no longer fits beside the page, so it lays itself over the - /// page instead of taking width from it. The panel is a temporary layer - /// over one choice; the page underneath is what the window is for. - panel_overlays: bool, +/// How wide the nav is at this window width: its full width while the page +/// beside it still gets `CONTENT_W`, then shrinking toward its floor. +fn nav_width(viewport: f32, scale: f32) -> f32 { + let full = NAV_W * scale.max(1.); + let floor = NAV_W_MIN * scale.max(1.); + let short = (full + CONTENT_W + PAGE_PAD - viewport).max(0.); + (full - short).clamp(floor, full).round() } -/// Hand every list its full width, then take the shortfall back from all of -/// them at once — each in proportion to what it has to spare — until the page -/// between them reaches `CONTENT_W`. Once every list is standing on its own -/// floor the page takes whatever is left, which from `NARROWEST_WINDOW` up is -/// never less than `CONTENT_MIN_W`. The theme panel leaves the row altogether -/// rather than let it come to that. -/// -/// Every width here is one this row can actually have, so the columns always -/// add up to the window. That is deliberate: the fix for a page squeezed to -/// nothing is not a `min_w` the row cannot honour — a floor a flex row cannot -/// meet does not push back, it overflows, and overflow here means content -/// painted off the edge of the window, which is the other half of this bug. -#[cfg(test)] -fn settings_columns( - section: SettingsSection, - theme_panel_open: bool, - viewport: f32, -) -> SettingsColumns { - settings_columns_scaled(section, theme_panel_open, viewport, 1.) -} - -fn settings_columns_scaled( - section: SettingsSection, - theme_panel_open: bool, - viewport: f32, - scale: f32, -) -> SettingsColumns { - // Reserve the same readable label width when the interface font grows. - let nav_width = NAV_W * scale.max(1.); - let nav_floor = NAV_W_MIN * scale.max(1.); - let ssh = matches!(section, SettingsSection::Ssh); - // The panel belongs to Appearance; a stale open flag on any other page is - // not a column, the same way `render_settings` does not draw one. - let theme_panel_open = theme_panel_open && matches!(section, SettingsSection::Appearance); - let pad = if ssh { SSH_DETAIL_PAD } else { PAGE_PAD }; - let page = CONTENT_W + pad; - - // Even with the nav and the panel both at their floors there has to be a - // readable page left between them. Below that width the panel stops being a - // column — this is the one place the *floor* is the test, because the panel - // leaving the row is what buys the page its preferred width back. - let panel_overlays = - theme_panel_open && viewport - nav_floor - THEME_PANEL_W_MIN - PAGE_PAD < CONTENT_MIN_W; - let beside = theme_panel_open && !panel_overlays; - - let mut nav = nav_width; - let mut ssh_list = only_when(ssh, SSH_LIST_W); - let mut theme_panel = only_when(beside, THEME_PANEL_W); - let (nav_slack, list_slack, panel_slack) = ( - nav_width - nav_floor, - only_when(ssh, SSH_LIST_W - SSH_LIST_W_MIN), - only_when(beside, THEME_PANEL_W - THEME_PANEL_W_MIN), - ); - let slack = nav_slack + list_slack + panel_slack; - let short = (nav + ssh_list + theme_panel + page - viewport).max(0.); - if short > 0. && slack > 0. { - let give = (short / slack).min(1.); - nav -= nav_slack * give; - ssh_list -= list_slack * give; - theme_panel -= panel_slack * give; - } - if panel_overlays { - // Covering the page, not replacing it: leave a strip of the page in - // view so the panel reads as something laid on top and dismissible. - theme_panel = THEME_PANEL_W - .min(viewport - nav - CONTENT_MIN_W / 2.) - .max(THEME_PANEL_W_MIN); - } - SettingsColumns { - nav: nav.round(), - ssh_list: ssh_list.round(), - theme_panel: theme_panel.round(), - panel_overlays, - } -} - -/// What a row on this page really has to lay out in. -/// -/// The nav is always in front of it; the SSH page puts its host list there too, -/// the theme panel takes another slice of Appearance for as long as it is open -/// *and* still fits beside it, and only the scrolled pages cap the reading -/// column. -fn settings_row_width( - section: SettingsSection, - theme_panel_open: bool, - viewport: f32, - ui_scale: f32, -) -> f32 { - let cols = settings_columns_scaled(section, theme_panel_open, viewport, ui_scale); - let panel = only_when(!cols.panel_overlays, cols.theme_panel); - match section { - SettingsSection::Ssh => (viewport - cols.nav - cols.ssh_list - SSH_DETAIL_PAD).max(0.), - _ => (viewport - cols.nav - panel - PAGE_PAD).clamp(0., READING_COLUMN * ui_scale), - } -} - -fn only_when(on: bool, w: f32) -> f32 { - if on { w } else { 0. } +/// What a row on the page really has to lay out in. +fn settings_row_width(viewport: f32, scale: f32) -> f32 { + (viewport - nav_width(viewport, scale) - PAGE_PAD).clamp(0., READING_COLUMN * scale) } /// How much wider every piece of text on this page is than the px thresholds @@ -230,49 +88,18 @@ fn ui_scale(cx: &App) -> f32 { cx.global::().ui_font_size / UI_FONT_SIZE_DEFAULT } -/// How wide a control in the right-hand column is. -/// -/// One number for the whole of settings, across every sub-page. It used to be -/// three: text fields took 260, sliders 240 and dropdowns 180, each picked -/// where it was written. Every row still ended on the same right edge, so on -/// any one page the difference read as controls that had been aligned -/// carelessly rather than as controls of different kinds — and moving between -/// Appearance and Terminal, where the mix differs, the column visibly changed -/// width. 260 is the widest of the three because it is the one with a -/// requirement behind it: a font name or a shell path has to be readable -/// without being truncated. -const FIELD_W: f32 = 260.; +/// How wide a text field in the right-hand column is. +const FIELD_W: f32 = 180.; -/// The host editor's own two numbers: the column its labels stand in, and how -/// wide a field beside one grows to. The label column fits the longest field -/// name in any locale at the default interface font; the field is wider than -/// [`FIELD_W`] because the form is what a path, a key file and a hostname are -/// actually typed into. -const SSH_LABEL_W: f32 = 104.; -const FORM_FIELD_W: f32 = 320.; - -/// Width a host-editor row needs before its label column and its field fit -/// side by side. Under it the label goes above the field instead, which is -/// what the narrowest window leaves the SSH page room for. -const STACK_FIELD_ROW_BELOW: f32 = 420.; +/// The host editor's label column, and how wide a field beside one grows to. +const SSH_LABEL_W: f32 = 96.; +const FORM_FIELD_W: f32 = 300.; /// Width a settings row needs before its label and its control fit side by -/// side: a [`FIELD_W`] control, the `gap_8` between them, and enough left for a +/// side: a wide control, the gap between them, and enough left for a /// description to read as prose rather than as a column of words. const STACK_ROW_BELOW: f32 = 500.; -/// Width a port-forwarding rule needs before its kind switch, its two host:port -/// pairs, its description and its remove button all fit on one line: about 580 -/// with every field at its floor, rounded up. Past this the rule takes two -/// lines instead of running off the page. -const SPLIT_FORWARD_ROW_BELOW: f32 = 620.; - -/// And the width below which even `bind → target` is more than one line holds: -/// two host fields at their narrow floor, two ports and the arrow come to about -/// 310, which is more than `CONTENT_MIN_W`. The SSH page reaches this on the -/// window the report came from, so the two ends take a line each. -const STACK_FORWARD_ENDS_BELOW: f32 = 340.; - /// The scrollback presets, and the labels their cells carry, in draw order. /// One list each so the number a cell writes is the number it shows — /// `preset_row_labels_name_the_value_they_write` holds the two together. @@ -405,17 +232,17 @@ impl SettingsSection { } } - fn icon(self) -> Icon { - Icon::new(match self { - Self::General => IconName::Settings2, - Self::Appearance => IconName::Palette, - Self::Terminal => IconName::SquareTerminal, - Self::KeyboardMouse | Self::Keybindings => IconName::CaseSensitive, - Self::Ssh => IconName::Globe, - Self::Agents => IconName::Bot, - Self::WindowTabs => IconName::WindowRestore, - Self::About => return Icon::empty().path("icons/circle-info.svg"), - }) + fn icon_path(self) -> &'static str { + match self { + Self::General => "icons/settings/general.svg", + Self::Appearance => "icons/settings/appearance.svg", + Self::Terminal => "icons/settings/terminal.svg", + Self::KeyboardMouse | Self::Keybindings => "icons/settings/keyboard.svg", + Self::Ssh => "icons/settings/ssh.svg", + Self::Agents => "icons/settings/integrations.svg", + Self::WindowTabs => "icons/settings/window.svg", + Self::About => "icons/settings/about.svg", + } } fn profile_label(self) -> &'static str { @@ -477,7 +304,7 @@ fn settings_search_entries() -> &'static [SearchEntry] { keywords: SettingsSearchAboutKeywords, }, SearchEntry { - section: General, + section: About, title: SettingsServer, keywords: SettingsSearchAboutKeywords, }, @@ -709,11 +536,6 @@ fn settings_search_entries() -> &'static [SearchEntry] { title: WarnBeforeClosing, keywords: SettingsSearchWarnBeforeClosingKeywords, }, - SearchEntry { - section: Ssh, - title: SettingsPortForwarding, - keywords: SettingsSearchPortForwardingKeywords, - }, SearchEntry { section: Agents, title: SettingsAgentClaudeCode, @@ -860,22 +682,22 @@ fn settings_search_entries() -> &'static [SearchEntry] { keywords: SettingsSearchAboutKeywords, }, SearchEntry { - section: General, + section: About, title: SettingsAppHttpProxy, keywords: SettingsSearchAppHttpProxyKeywords, }, SearchEntry { - section: General, + section: About, title: SettingsUpdateChannel, keywords: SettingsSearchUpdateChannelKeywords, }, SearchEntry { - section: General, + section: About, title: SettingsCheckUpdatesOnLaunch, keywords: SettingsSearchCheckUpdatesOnLaunchKeywords, }, SearchEntry { - section: General, + section: About, title: SettingsAutoDownload, keywords: SettingsSearchAutoDownloadKeywords, }, @@ -1236,6 +1058,7 @@ fn row_matches_query(section: SettingsSection, label: &str, query: &str) -> bool .any(|e| e.section == section && t(e.title) == label && entry_matches(e, query)) } +#[cfg(test)] pub(crate) fn total_match_count(query: &str) -> usize { SettingsSection::ALL .into_iter() @@ -1258,7 +1081,6 @@ pub(crate) struct ThemeEditor { pub(crate) for_id: String, pub(crate) seed: Vec<(ThemeEdit, Entity)>, pub(crate) ansi: Vec<(ThemeEdit, Entity)>, - pub(crate) image_opacity_slider: Option>, pub(crate) _subs: Vec, } @@ -1279,47 +1101,71 @@ pub(crate) struct SettingsState { /// claims. Searching tells you "Appearance (2)"; these are what carry you /// to the two, which on a long page start well below the fold. pub(crate) content_scroll: gpui::ScrollHandle, - pub(crate) ssh_master_scroll: gpui::ScrollHandle, - pub(crate) ssh_detail_scroll: gpui::ScrollHandle, - pub(crate) theme_list_scroll: gpui::ScrollHandle, pub(crate) search_anchor: gpui::ScrollAnchor, /// Set when the query or the section changes, and spent by the next render /// that has somewhere to go. A `Cell` because that render only holds `&self`. pub(crate) reveal_first_hit: Cell, - pub(crate) font_select: Entity>>, - pub(crate) font_bold_select: Entity>>, - pub(crate) font_italic_select: Entity>>, - pub(crate) ui_font_select: Entity>>, - pub(crate) language_select: Entity>>, - #[cfg(target_os = "windows")] - pub(crate) window_backdrop_select: Entity>>, + /// The families the font menus list, read once when the page opens. + pub(crate) font_names: std::rc::Rc>, pub(crate) shell_program_input: Entity, pub(crate) shell_args_input: Entity, pub(crate) wd_path_input: Entity, pub(crate) link_file_command_input: Entity, pub(crate) http_proxy_input: Entity, - pub(crate) scroll_slider: Entity, - pub(crate) window_opacity_slider: Entity, pub(crate) theme_editor: Option, pub(crate) theme_draft: Option<(presets::Theme, presets::Theme)>, pub(crate) theme_draft_error: Option, - pub(crate) theme_panel_open: bool, - pub(crate) theme_panel_slot: ThemeSlot, - pub(crate) theme_search: Entity, + /// The one popover open on the page — a dropdown, a theme list, a row's + /// menu — by the id its trigger was drawn with. + pub(crate) menu: Option, + /// The query box inside a popover that has one, and the row the arrow + /// keys have reached in it. + pub(crate) menu_query: Entity, + pub(crate) menu_hi: usize, + pub(crate) menu_scroll: gpui::ScrollHandle, + /// Whatever held keyboard focus when the page was last drawn, so a text + /// field can draw its focus ring from a builder that has no `Window`. + pub(crate) focused: RefCell>, + /// A recorded shortcut that another action already answers to, held until + /// the user says whether to take it over. + pub(crate) kb_conflict: Option, pub(crate) recording: Option, pub(crate) rebinding_note: Option, pub(crate) ssh_form: Option, - pub(crate) ssh_detail: SshDetail, + /// The host whose row is expanded to show its details. + pub(crate) ssh_open: Option, + /// Every host, grouped by where it is defined, rather than the recent few. + pub(crate) ssh_show_all: bool, + /// Remove was pressed once on the host being edited; the second press + /// removes it. + pub(crate) ssh_confirm_remove: bool, + /// The host whose ssh command was just copied, for the moment the button + /// says so. + pub(crate) ssh_copied: Option, pub(crate) ssh_filter: Entity, pub(crate) ssh_collapsed_groups: std::collections::HashSet, - pub(crate) ssh_quick_connect: Entity, pub(crate) agent_hooks_host: HostId, pub(crate) agent_hooks_states: AgentHooksView, pub(crate) agent_hooks_seq: u64, pub(crate) agent_hooks_note: Option<(crate::core::agent_hooks::HookAgent, String)>, + pub(crate) agent_query: Entity, + /// Every agent, not just the ones installed on the selected machine. + pub(crate) agent_show_all: bool, + /// Agents acted on since the list was last narrowed, kept in view so a row + /// does not vanish under the pointer the moment it is uninstalled. + pub(crate) agent_touched: std::collections::HashSet, + /// Agents with an install or removal in flight. + pub(crate) agent_busy: std::collections::HashSet, pub(crate) _subs: Vec, } +/// A recorded chord and the action it would be taken from. +pub(crate) struct KeyConflict { + pub(crate) action: String, + pub(crate) spec: String, + pub(crate) other: String, +} + #[derive(Clone)] pub(crate) enum AgentHooksView { Loading, @@ -1340,18 +1186,12 @@ pub(crate) struct AgentHooksMachine { pub(crate) label: String, } -#[derive(Clone, Copy, PartialEq, Eq)] -pub(crate) enum ThemeSlot { - Manual, +/// The Appearance page's three ways of choosing a theme. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum ThemeMode { Light, Dark, -} - -#[derive(Clone, Copy, PartialEq, Eq)] -pub(crate) enum SshDetail { - None, - Defaults, - Profile(Uuid), + System, } fn ssh_group_key(p: &SshProfile) -> &str { @@ -1408,16 +1248,11 @@ pub(crate) struct SshProfileForm { carry_group: Option, carry_credential_ref: Option, - show_jump: bool, - show_forwards: bool, - show_advanced: bool, - name: Entity, host: Entity, port: Entity, user: Entity, auth: AuthMode, - auth_select: Entity>>, /// The secret half of a connection. Neither of these is part of the /// profile — they live in the system keychain, and the config file holds @@ -1460,18 +1295,9 @@ pub(crate) struct SshProfileForm { verify_host_keys: Option, warn_on_close: Option, - /// The last Test Connection on this form, or `None` when there has not - /// been one — or when an edit since made the old answer a lie. - test: Option, - _subs: Vec, } -pub(crate) enum SshTestState { - Running, - Done(SshTestReport), -} - impl SshProfileForm { /// Whether the group that identifies the host — name, host, port, user — /// is still untouched. Every field notifies on change, so the form @@ -1500,27 +1326,6 @@ impl SshProfileForm { self.password.read(cx).value().as_ref() != self.loaded_password || self.passphrase.read(cx).value().as_ref() != self.loaded_passphrase } - - fn wants_password(&self) -> bool { - auth_uses_password(self.auth) - } - - fn wants_key(&self) -> bool { - auth_uses_key(self.auth) - } -} - -/// Which credential fields a method actually uses — the same split -/// `ssh_connect::build_spec_inner` makes when it decides what to hand the -/// daemon. A password box under "Agent" would be a secret that is stored and -/// then never offered, and a form holding one quietly is worse than a form -/// that has none. -fn auth_uses_password(mode: AuthMode) -> bool { - matches!(mode, AuthMode::Auto | AuthMode::Password) -} - -fn auth_uses_key(mode: AuthMode) -> bool { - matches!(mode, AuthMode::Auto | AuthMode::PublicKey) } /// What saving does to the keychain for the password field: which entry to @@ -1578,18 +1383,6 @@ impl ForwardRuleForm { description: val(&self.description), }) } - - fn is_blank(&self, cx: &App) -> bool { - [ - &self.bind_host, - &self.bind_port, - &self.target_host, - &self.target_port, - &self.description, - ] - .iter() - .all(|e| e.read(cx).value().trim().is_empty()) - } } pub(crate) struct Recording { @@ -1878,119 +1671,6 @@ fn validate_ssh_draft(draft: SshFormDraft, profiles: &[SshProfile]) -> (SshProfi (profile, errors) } -/// The inline complaint under a field: one line, in the danger colour, in the -/// column the control sits in. Built before the row rather than inside a -/// `when` closure so it borrows the app for the length of one call. -fn field_error(message: impl Into, cx: &App) -> Div { - div() - .text_xs() - .text_color(cx.theme().danger) - .child(message.into()) -} - -/// A duration as a test result should read it: milliseconds while the number -/// still means something, seconds once it does not. -fn human_millis(ms: u32) -> String { - match ms < 1000 { - true => format!("{ms} ms"), - false => format!("{:.1} s", f64::from(ms) / 1000.0), - } -} - -/// What the handshake stopped to ask for, as the one line explaining why a -/// reachable host still is not a connected one. -fn ssh_test_need_message(need: SshTestNeed) -> L10nKey { - match need { - SshTestNeed::Password => L10nKey::SettingsTestNeedsPassword, - SshTestNeed::KeyPassphrase => L10nKey::SettingsTestNeedsPassphrase, - SshTestNeed::KeyboardInteractive => L10nKey::SettingsTestNeedsInteractive, - SshTestNeed::HostKeyDecision => L10nKey::SettingsTestNeedsHostKey, - SshTestNeed::HostKeyChanged => L10nKey::SettingsTestHostKeyChanged, - } -} - -/// The authentication methods in the order the form lists them, and the one -/// place that order is written down — the labels, the index the dropdown opens -/// on, and the mode a pick resolves to all read from here. -pub(crate) const AUTH_MODES: [AuthMode; 6] = [ - AuthMode::Auto, - AuthMode::Gssapi, - AuthMode::Password, - AuthMode::PublicKey, - AuthMode::Agent, - AuthMode::KeyboardInteractive, -]; - -fn auth_mode_labels() -> Vec { - AUTH_MODES.iter().map(|m| auth_mode_label(*m)).collect() -} - -fn auth_mode_label(mode: AuthMode) -> String { - match mode { - AuthMode::Auto => t(L10nKey::SettingsAuthModeAuto).to_string(), - AuthMode::Gssapi => "GSSAPI".to_string(), - AuthMode::Password => t(L10nKey::SettingsAuthModePassword).to_string(), - AuthMode::PublicKey => t(L10nKey::SettingsAuthModeKey).to_string(), - AuthMode::Agent => t(L10nKey::SettingsAuthModeAgent).to_string(), - AuthMode::KeyboardInteractive => t(L10nKey::SettingsAuthMode2Fa).to_string(), - } -} - -fn auth_mode_index(mode: AuthMode) -> usize { - AUTH_MODES.iter().position(|m| *m == mode).unwrap_or(0) -} - -/// The same line in the muted colour, for a field that is filled in and -/// legal but will not be the one used. Not an error: nothing is wrong with -/// what was typed, it is just not what the connection will do. -fn field_note(message: impl Into, cx: &App) -> Div { - div() - .text_xs() - .text_color(cx.theme().muted_foreground) - .child(message.into()) -} - -/// Which of the three proxy fields a connection would actually go through. -/// They read as three independent settings and are not: `map_proxy` picks the -/// first one filled, in this order, and ignores the rest without a word. -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -pub(crate) enum ProxyPick { - Command, - Socks, - Http, -} - -impl ProxyPick { - fn of(command: bool, socks: bool, http: bool) -> Option { - match (command, socks, http) { - (true, _, _) => Some(Self::Command), - (_, true, _) => Some(Self::Socks), - (_, _, true) => Some(Self::Http), - _ => None, - } - } - - fn label(self) -> &'static str { - match self { - Self::Command => t(L10nKey::SettingsProxyCommand), - Self::Socks => t(L10nKey::SettingsSocks5Proxy), - Self::Http => t(L10nKey::SettingsHttpProxy), - } - } - - /// The note this field carries when it holds an address that another one - /// outranks. An empty field has nothing to be overridden. - fn overridden_by(self, filled: bool, winner: Option) -> Option { - let winner = winner?; - (filled && winner != self).then(|| { - t_fmt( - L10nKey::SettingsProxyOverridden, - &[("winner", winner.label())], - ) - }) - } -} - fn forward_row_inputs(row: &ForwardRuleForm) -> [&Entity; 5] { [ &row.bind_host, @@ -2050,21 +1730,6 @@ fn seed_input( }) } -fn seed_hinted_multi( - window: &mut Window, - cx: &mut Context, - value: &str, - placeholder: &'static str, -) -> Entity { - let value = value.to_string(); - cx.new(|cx| { - InputState::new(window, cx) - .multi_line(true) - .placeholder(placeholder) - .default_value(value) - }) -} - /// A picked path written the way a config file spells it. `~/.ssh/id_ed25519` /// keeps meaning the right file on another machine, or after the account is /// renamed; the absolute path the system picker hands back does not. @@ -2280,799 +1945,11 @@ impl Tty7App { state.focused_setting = setting; state.reveal_first_hit.set(setting.is_some()); state.content_scroll.set_offset(gpui::point(px(0.), px(0.))); - state.theme_panel_open = false; - if target == SettingsSection::Ssh - && matches!( - setting, - Some(L10nKey::SettingsVerifyHostKeys | L10nKey::WarnBeforeClosing) - ) - { - state.ssh_detail = SshDetail::Defaults; - } + state.menu = None; } self.select_settings_section(target, cx); } - fn render_settings_search(&self, cx: &mut Context) -> AnyElement { - let Some(state) = self.active_settings() else { - return div().into_any_element(); - }; - let query = state.search.read(cx).value().trim().to_lowercase(); - let modified_only = state.modified_only; - *state.search_rows.borrow_mut() = Some(Vec::new()); - // Build once, then retain the matching controls. Discarded page chrome - // never enters the element tree, so controls keep their usual IDs. - for section in SettingsSection::ALL { - if !settings_search_entries() - .iter() - .any(|entry| entry.section == section && entry_matches(entry, &query)) - { - continue; - } - match section { - SettingsSection::General => { - self.render_settings_general(cx); - } - SettingsSection::Appearance => { - self.render_settings_appearance(cx); - } - SettingsSection::Terminal => { - self.render_settings_terminal(cx); - } - SettingsSection::KeyboardMouse => { - self.render_settings_input(cx); - } - SettingsSection::WindowTabs => { - self.render_window_preferences(false, cx); - } - SettingsSection::About => { - self.render_settings_about(cx); - } - // These pages have their own host/action editors. - _ => {} - } - } - let mut controls = self - .active_settings() - .unwrap() - .search_rows - .borrow_mut() - .take() - .unwrap_or_default(); - let cfg = cx.global::(); - let mut matches = settings_search_entries() - .iter() - .filter(|entry| entry_matches(entry, &query) && (!modified_only || entry.modified(cfg))) - .collect::>(); - matches.sort_by_key(|entry| { - ( - entry.rank(&query), - SettingsSection::ALL - .iter() - .position(|&s| s == entry.section) - .unwrap_or(0), - ) - }); - let mut list = v_flex().gap_3(); - for (index, entry) in matches.iter().enumerate() { - let title = entry.title; - let section = if title == L10nKey::SettingsSearchKeybindingsTitle { - SettingsSection::Keybindings - } else { - entry.section - }; - let control = controls - .iter() - .position(|(key, _)| *key == title) - .map(|i| controls.remove(i).1); - let path = format!("{} › {}", t(entry.section.title()), t(title)); - let row = v_flex() - .id(SharedString::from(format!("search-result-{title:?}"))) - .px_4() - .py_3() - .rounded(rounding::CARD_RADIUS) - .border_1() - .border_color(cx.theme().border.opacity(0.65)) - .anchor_scroll( - self.active_settings() - .filter(|s| s.search_selection == index) - .map(|s| s.search_anchor.clone()), - ) - .when( - self.active_settings() - .is_some_and(|s| s.search_selection == index), - |v| v.border_color(cx.theme().primary), - ) - .child( - Button::new(SharedString::from(format!("search-path-{title:?}"))) - .label(path) - .ghost() - .small() - .on_click(cx.listener(move |this, _, window, cx| { - this.navigate_settings(section, Some(title), window, cx) - })), - ) - .child(control.unwrap_or_else(|| { - self.settings_row( - t(title), - entry.description(), - Button::new(SharedString::from(format!("search-open-{title:?}"))) - .label(t(L10nKey::SettingsOpenSetting)) - .small() - .on_click(cx.listener(move |this, _, window, cx| { - this.navigate_settings(section, Some(title), window, cx) - })) - .into_any_element(), - cx, - ) - .into_any_element() - })); - list = list.child(row); - } - if matches.is_empty() && (modified_only || keybinding_match_count(&query) == 0) { - list = list.child( - div() - .text_sm() - .text_color(cx.theme().muted_foreground) - .child(if modified_only { - t(L10nKey::SettingsNoModified).to_string() - } else { - t_fmt(L10nKey::SettingsNothingMatches, &[("query", &query)]) - }), - ); - } - // Action names remain searchable without exposing an entire shortcut - // editor in the results list. - if !query.is_empty() && !modified_only { - let mut index = matches.len(); - for (action, _) in crate::ui::keymap::default_bindings() { - if keybinding_matches_query(&action, &query) { - let (_, label) = crate::ui::keymap::action_entry(&action); - let anchor = self - .active_settings() - .filter(|s| s.search_selection == index) - .map(|s| s.search_anchor.clone()); - let button = Button::new(SharedString::from(format!("search-action-{action}"))) - .label(format!( - "{} › {}", - t(L10nKey::SettingsNavKeybindings), - label - )) - .ghost() - .small() - .selected( - self.active_settings() - .is_some_and(|s| s.search_selection == index), - ) - .on_click(cx.listener(move |this, _, window, cx| { - let action = action.clone(); - this.with_settings_edits_resolved( - window, - cx, - move |this, window, cx| { - this.navigate_settings( - SettingsSection::Keybindings, - None, - window, - cx, - ); - if let Some(s) = this.active_settings() { - s.shortcut_search - .clone() - .update(cx, |s, cx| s.set_value(action, window, cx)); - } - }, - ); - })); - list = list.child( - div() - .id(SharedString::from(format!("search-shortcut-{index}"))) - .anchor_scroll(anchor) - .child(button), - ); - index += 1; - } - } - } - list.into_any_element() - } - - pub(crate) fn render_settings( - &self, - window: &mut Window, - cx: &mut Context, - ) -> impl IntoElement + use<> { - let theme = cx.theme(); - // The settings panel covers the whole window. Paint it on an opaque - // surface so the workspace translucency (window opacity / backdrop - // material) never shows through the settings UI — while keeping the - // preset's gradient fill instead of collapsing to a flat color. - let background: Background = crate::ui::theme::overlay_background(cx); - // That opaque fill also covers the theme background image the - // workspace root paints, so the panel carries its own copy (dimmed by - // the workspace fill, or the settings text would sit straight on the - // wallpaper); without it the image would blink out for as long as - // settings is open. - let background_layers = crate::ui::app::overlay_surface_layers(cx); - let (foreground, header_muted) = (theme.foreground, theme.muted_foreground); - let note_bg = theme.secondary.opacity(0.5); - - let (focus_handle, section, theme_panel_open, search) = match self.active_settings() { - Some(s) => ( - s.focus_handle.clone(), - s.section, - s.theme_panel_open, - s.search.clone(), - ), - None => return div(), - }; - let query = search.read(cx).value().trim().to_lowercase(); - let searching = self.active_settings().is_some_and(|s| s.search_active); - let layout_section = if searching { - SettingsSection::General - } else { - section - }; - let show_theme_panel = - !searching && theme_panel_open && section == SettingsSection::Appearance; - - let viewport_w = window.viewport_size().width.as_f32(); - let ui_scale = ui_scale(cx); - self.settings_viewport_w.set(viewport_w); - let cols = settings_columns_scaled(layout_section, show_theme_panel, viewport_w, ui_scale); - self.settings_row_width.set(settings_row_width( - layout_section, - show_theme_panel, - viewport_w, - ui_scale, - )); - self.settings_hit_anchored.set(false); - - // A query that matched here has to be reachable, not just counted. The - // anchor lands on the first matching row below, and `scroll_to` reads - // where it ended up on the frame after this one — by which time this - // render has been painted and the anchor knows its own origin. - // - // A query that matched nowhere has to be reachable too: the note - // saying so sits at the top of the page, and a reader who searched - // from halfway down would otherwise be left with the untouched page - // the note exists to explain. - if searching - && let Some(s) = self.active_settings() - && s.reveal_first_hit.replace(false) - { - s.search_anchor.scroll_to(window, cx); - } - if let Some(s) = self.active_settings() - && !searching - && s.reveal_first_hit.get() - { - s.reveal_first_hit.set(false); - let matched_here = - section_match_count(section, &query) > 0 || s.focused_setting.is_some(); - let matched_nowhere = total_match_count(&query) == 0; - if s.focused_setting.is_some() - || (!query.is_empty() && (matched_here || matched_nowhere)) - { - s.search_anchor.scroll_to(window, cx); - } - } - - let prof = crate::ui::perf::enabled() - .then(|| (std::time::Instant::now(), section.profile_label())); - - let nav_item = |label: &'static str, target: SettingsSection, icon: Icon| { - let view = cx.entity(); - let count = if query.is_empty() { - 0 - } else { - section_match_count(target, &query) - }; - let item = SidebarMenuItem::new(label) - .icon(icon) - .active(section.navigation_section() == target) - .on_click(move |_, window, cx| { - view.update(cx, |this, cx| { - this.navigate_settings(target, None, window, cx) - }); - }); - if count > 0 { - item.suffix(move |_w, _cx| { - div() - .text_xs() - .text_color(header_muted) - .child(format!("({count})")) - }) - } else { - item - } - }; - - let nav_body = SettingsSection::ALL - .into_iter() - .fold(SidebarMenu::new().gap_2(), |menu, target| { - menu.child(nav_item(t(target.title()), target, target.icon())) - }); - - let sidebar = Sidebar::new("settings-sidebar") - .collapsible(SidebarCollapsible::None) - .w(px(cols.nav)) - // The main window's tab rail fill, so the two sidebars read as - // the same surface. Opaque: settings is an opaque overlay, and the - // rail's translucency rule would let the page behind show through. - .bg(gpui::rgb(cx.global::().rail.base)) - .header( - v_flex() - .w_full() - .px_2() - .gap_2() - .pt(px(crate::ui::app::TITLE_BAR_HEIGHT)) - .pb_1() - .child( - div() - .text_xs() - .font_weight(FontWeight::MEDIUM) - .text_color(header_muted) - .child(t(L10nKey::SettingsHeader)), - ) - .child( - h_flex() - .items_center() - .gap_2() - .child( - Icon::empty() - .path("stock/icons/search.svg") - .size(px(16.)) - .text_color(header_muted), - ) - .child( - div() - .flex_1() - .min_w_0() - .child(Input::new(&search).appearance(false).pl_0()), - ), - ), - ) - .child(nav_body) - .footer( - Button::new("settings-modified-filter") - .label(t(L10nKey::SettingsModifiedOnly)) - .ghost() - .small() - .selected(self.active_settings().is_some_and(|s| s.modified_only)) - .on_click(cx.listener(|this, _, _window, cx| { - if let Some(s) = this.active_settings_mut() { - s.modified_only = !s.modified_only; - } - this.autoselect_settings_search(cx); - })), - ); - - let content = if searching { - self.render_settings_search(cx) - } else { - match section { - SettingsSection::General => self.render_settings_general(cx), - SettingsSection::Appearance => self.render_settings_appearance(cx), - SettingsSection::Terminal => self.render_settings_terminal(cx), - SettingsSection::KeyboardMouse => self.render_settings_input(cx), - SettingsSection::Ssh => self.render_settings_ssh(cx), - SettingsSection::Agents => self.render_settings_agents(cx), - SettingsSection::WindowTabs => self.render_window_preferences(false, cx), - SettingsSection::Keybindings => self.render_settings_keybindings(cx), - SettingsSection::About => self.render_settings_about(cx), - } - }; - - // A query that matches nothing anywhere leaves the nav badge-less and - // `autoselect_settings_search` with nowhere to go, so without this the - // page just sits there looking like the search did nothing. - let no_match_note = (!searching && !query.is_empty() && total_match_count(&query) == 0) - .then(|| { - div() - .id("settings-no-match") - .anchor_scroll(self.active_settings().map(|s| s.search_anchor.clone())) - .mb_6() - .px_3() - .py_2() - .rounded_lg() - .bg(note_bg) - .text_sm() - .text_color(header_muted) - .child(t_fmt( - L10nKey::SettingsNothingMatches, - &[("query", query.as_str())], - )) - }); - - // No fill of its own: the root already paints the opaque surface and - // the background image behind it, and repainting here would hide the - // image again in the one pane that fills most of the panel. - // - // `min_w_0` and not a `CONTENT_MIN_W` floor: `settings_columns` sized - // the chrome so this pane clears it, and a floor a flex row cannot - // honour does not push the nav back — it overflows, and overflow here - // means content painted off the edge of the window, which is the other - // half of the bug this file is fixing. - let content_pane = if !searching && section == SettingsSection::Ssh { - v_flex() - .id("settings-content") - .flex_1() - .min_w_0() - .h_full() - .when_some( - self.active_settings().and_then(|s| s.save_error.clone()), - |v, error| { - v.child( - v_flex() - .p_3() - .gap_2() - .child( - div().text_sm().child(t_fmt( - L10nKey::SettingsSaveError, - &[("error", &error)], - )), - ) - .child( - Button::new("retry-ssh-settings-save") - .label(t(L10nKey::SettingsRetrySave)) - .small() - .on_click(cx.listener(|this, _, _window, cx| { - this.persist_settings_config(cx) - })), - ), - ) - }, - ) - .child(content) - .into_any_element() - } else { - let body = v_flex() - .id("settings-content") - .size_full() - .overflow_y_scroll() - .when_some(self.active_settings(), |pane, s| { - pane.track_scroll(&s.content_scroll) - }) - .child( - // The padding box needs its own width for the reading - // column's `w_full` to resolve against something definite; - // without it the percentage falls back to the content, and - // `max_w` loses to a row that measures wider — which is how - // the theme card came to run the width of the window on the - // Chinese and Japanese pages while every other row stopped - // at the column. - // - // `mx_auto` on the column centres it across the page. The - // cap keeps a description a paragraph rather than a line to - // scan across, but left-aligning what it caps put the whole - // page against the nav: on a window as wide as the display - // it was made for, 640 points of settings sat beside 1600 - // points of nothing. Centred, the page is one column with - // air on both sides at every width, and below the cap — - // where the column is the page — this does nothing at all. - // - // The centring has to come from the margin, not from an - // `items_center` on a flex box here. The scroll pane is a - // flex column and this box is its item: as a block it - // reports the full height of the page it stacks, but as a - // flex box it negotiates a height with the pane and lands - // near the viewport, and `content_size` — which is just - // this box's laid-out bounds — then leaves most of the page - // outside the scroll range. `flex_shrink_0` does not buy - // its way out of that; only staying a block does. - div().w_full().px_10().py_8().child( - div() - .w_full() - .max_w(px(READING_COLUMN * ui_scale)) - .mx_auto() - .children(no_match_note) - .child( - div() - .mb_5() - .text_xl() - .font_weight(FontWeight::SEMIBOLD) - .child(t(if searching { - L10nKey::SettingsSearchResults - } else { - section.title() - })), - ) - .when(self.theme_draft_dirty(), |v| { - v.child( - v_flex() - .mb_4() - .gap_2() - .child( - div().text_sm().child(t(L10nKey::SettingsThemeDraft)), - ) - .when_some( - self.active_settings() - .and_then(|s| s.theme_draft_error.clone()), - |v, error| { - v.child(div().text_sm().child(t_fmt( - L10nKey::SettingsSaveError, - &[("error", &error)], - ))) - }, - ) - .child( - h_flex() - .gap_2() - .child( - Button::new("save-theme-draft") - .label(t(L10nKey::SettingsSaveChanges)) - .small() - .on_click(cx.listener( - |this, _, window, cx| { - this.save_theme_draft(window, cx); - }, - )), - ) - .child( - Button::new("cancel-theme-draft") - .label(t(L10nKey::Cancel)) - .ghost() - .small() - .on_click(cx.listener( - |this, _, window, cx| { - this.cancel_theme_draft(window, cx) - }, - )), - ), - ), - ) - }) - .when_some( - self.active_settings().and_then(|s| s.save_error.clone()), - |v, error| { - v.child( - v_flex() - .mb_4() - .gap_2() - .child(div().text_sm().child(t_fmt( - L10nKey::SettingsSaveError, - &[("error", &error)], - ))) - .child( - Button::new("retry-settings-save") - .label(t(L10nKey::SettingsRetrySave)) - .small() - .on_click(cx.listener( - |this, _, _window, cx| { - this.persist_settings_config(cx) - }, - )), - ), - ) - }, - ) - .child(content), - ), - ); - v_flex() - .flex_1() - .min_w_0() - .h_full() - // No fill here either: the root paints it, and a second one on - // the pane that covers most of the page would hide the theme - // image behind it. - .when_some(self.active_settings(), |pane, s| { - // Inset: this pane reaches both ends of the window, so a - // full-height bar ends up on the rounded corner. - pane.child(crate::ui::scrollbar::with_inset_vertical_scrollbar( - "settings-content-scrollbar", - body, - &s.content_scroll, - px(SCROLLBAR_WINDOW_INSET), - )) - }) - .into_any_element() - }; - - let root = div() - .size_full() - .relative() - .flex() - .flex_row() - .bg(background) - .text_color(foreground) - .track_focus(&focus_handle) - // Escape peels one layer at a time. With the theme picker open that - // layer is the picker: closing the whole page instead threw away a - // panel the user had opened a moment ago, and left them to walk - // back to Appearance to try again. - .capture_key_down(cx.listener(move |this, ev: &KeyDownEvent, window, cx| { - if searching - && this - .active_settings() - .is_some_and(|s| s.search.read(cx).focus_handle(cx).is_focused(window)) - { - let key = ev.keystroke.key.as_str(); - if matches!(key, "up" | "down" | "enter") { - let s = this.active_settings().unwrap(); - let query = s.search.read(cx).value().trim().to_lowercase(); - let mut entries = settings_search_entries() - .iter() - .filter(|e| { - entry_matches(e, &query) - && (!s.modified_only || e.modified(cx.global::())) - }) - .collect::>(); - entries.sort_by_key(|e| { - ( - e.rank(&query), - SettingsSection::ALL - .iter() - .position(|&s| s == e.section) - .unwrap_or(0), - ) - }); - let actions = if s.modified_only { - Vec::new() - } else { - crate::ui::keymap::default_bindings() - .into_iter() - .filter(|(action, _)| keybinding_matches_query(action, &query)) - .map(|(action, _)| action) - .collect::>() - }; - let count = entries.len() + actions.len(); - if count > 0 { - let index = s.search_selection.min(count - 1); - if key == "enter" && index >= entries.len() { - let action = actions[index - entries.len()].clone(); - this.with_settings_edits_resolved( - window, - cx, - move |this, window, cx| { - this.navigate_settings( - SettingsSection::Keybindings, - None, - window, - cx, - ); - if let Some(s) = this.active_settings() { - s.shortcut_search.clone().update(cx, |s, cx| { - s.set_value(action, window, cx) - }); - } - }, - ); - } else if key == "enter" { - let entry = entries[index]; - let target = - if entry.title == L10nKey::SettingsSearchKeybindingsTitle { - SettingsSection::Keybindings - } else { - entry.section - }; - this.navigate_settings(target, Some(entry.title), window, cx); - } else if let Some(s) = this.active_settings_mut() { - s.search_selection = if key == "down" { - (index + 1).min(count - 1) - } else { - index.saturating_sub(1) - }; - s.reveal_first_hit.set(true); - cx.notify(); - } - } - cx.stop_propagation(); - return; - } - } - })) - .on_key_down(cx.listener(move |this, ev: &KeyDownEvent, window, cx| { - if ev.keystroke.key.as_str() != "escape" { - return; - } - if show_theme_panel { - this.close_theme_panel(window, cx); - return; - } - if searching { - if let Some(s) = this.active_settings_mut() { - s.modified_only = false; - } - if let Some(s) = this.active_settings() { - s.search - .clone() - .update(cx, |s, cx| s.set_value("", window, cx)); - } - this.autoselect_settings_search(cx); - cx.stop_propagation(); - return; - } - this.close_settings_checked(window, cx); - })) - .children(background_layers) - .child(sidebar) - .child(content_pane) - .child( - crate::ui::app::window_move_gesture( - div() - .id("settings-titlebar-drag") - .absolute() - .top_0() - .left_0() - .right_0() - .h(px(crate::ui::app::TITLE_BAR_HEIGHT)), - "settings-titlebar-drag", - window, - cx, - ) - .on_double_click(|_, window, _| window.titlebar_double_click()), - ) - // Beside the page while there is room for both, over it when there - // is not. As a column it was taking its 300px from the page and - // from nothing else, which is how a half-width window ended up - // rendering a description one character wide. - .when(show_theme_panel && !cols.panel_overlays, |r| { - r.child(self.render_theme_panel(cx)) - }) - .when(show_theme_panel && cols.panel_overlays, |r| { - r.child( - div() - .absolute() - .top_0() - .right_0() - .bottom_0() - .occlude() - .shadow_lg() - .child(self.render_theme_panel(cx)), - ) - }) - .when(!show_theme_panel, |r| { - r.child( - div() - .absolute() - .top(px((TITLE_BAR_HEIGHT - TILE_SIZE) / 2.)) - .right(px(10.)) - .occlude() - .child( - Button::new("settings-close") - .icon(Icon::new(IconName::Close)) - .ghost() - .with_size(px( - TILE_GLYPH_LINE / crate::ui::tab_strip::BUTTON_ICON_SCALE - )) - .w(px(TILE_SIZE)) - .h(px(TILE_SIZE)) - .rounded_lg() - .tooltip(t(L10nKey::Close)) - .on_click(cx.listener(|this, _, window, cx| { - this.close_settings_checked(window, cx) - })), - ), - ) - }); - - if let Some((start, label)) = prof { - crate::ui::perf::record(label, start.elapsed()); - } - root - } - - /// The column widths this render settled on. `settings_columns` is pure and - /// cheap, so the two pages that draw chrome of their own work them out - /// again rather than have the answer threaded through every builder. - fn settings_columns_now(&self, cx: &App) -> SettingsColumns { - let (section, panel_open) = match self.active_settings() { - Some(s) => ( - s.section, - s.theme_panel_open && s.section == SettingsSection::Appearance, - ), - None => (SettingsSection::Appearance, false), - }; - settings_columns_scaled( - section, - panel_open, - self.settings_viewport_w.get(), - ui_scale(cx), - ) - } - /// Whether the row measured this render came out narrower than a threshold /// quoted at the default interface font — the only way those px thresholds /// mean anything to a reader who scaled the interface up. @@ -3080,26 +1957,6 @@ impl Tty7App { self.settings_row_width.get() < at_default_font * ui_scale(cx) } - fn header_text(&self, title: &str, cx: &Context) -> Div { - div() - .text_base() - .font_weight(FontWeight::SEMIBOLD) - .text_color(cx.theme().foreground) - .child(title.to_string()) - } - - /// A heading *inside* a section — quieter than `section_header`, for - /// breaking a long run of rows into groups you can scan. - fn subgroup_header(&self, key: L10nKey, cx: &Context) -> Div { - div() - .pt_4() - .pb_1() - .text_xs() - .font_weight(FontWeight::MEDIUM) - .text_color(cx.theme().muted_foreground) - .child(t(key)) - } - /// The scroll anchor for the first thing on the page the query matched, /// whatever kind of element that is. A section header can be the only /// match on its page — "ansi", "how shells work" — and while the dimming @@ -3130,1344 +1987,6 @@ impl Tty7App { } } - pub(crate) fn section_header(&self, title: &str, cx: &Context) -> Stateful
{ - self.header_text(title, cx) - .mb_4() - .id(settings_header_id(title)) - .anchor_scroll(self.first_hit_anchor(title, cx)) - } - - fn section_intro( - &self, - title: &str, - desc: impl Into, - cx: &Context, - ) -> Stateful
{ - v_flex() - .mb_4() - .gap_1() - .id(settings_header_id(title)) - .anchor_scroll(self.first_hit_anchor(title, cx)) - .child(self.header_text(title, cx)) - .child( - div() - .text_xs() - .text_color(cx.theme().muted_foreground) - .child(desc.into()), - ) - } - - pub(crate) fn section_rule(&self, cx: &Context) -> Div { - div().h(px(1.)).my_7().bg(cx.theme().sidebar_border) - } - - pub(crate) fn settings_row( - &self, - label: impl Into, - desc: impl Into, - control: AnyElement, - cx: &Context, - ) -> Stateful
{ - self.settings_row_gated_when(label, desc, control, false, cx) - } - - /// The same row, greyed out when `gated` — for a control another setting - /// has switched off, whose own value is still there for when it comes back. - /// - /// Only the text dims. The control draws its own disabled state — a - /// switch's thumb is already down to 35% there — and dimming the whole row - /// on top of that leaves a pill with nothing visible inside it. - pub(crate) fn settings_row_gated_when( - &self, - label: impl Into, - desc: impl Into, - control: AnyElement, - gated: bool, - cx: &Context, - ) -> Stateful
{ - let theme = cx.theme(); - let label = label.into(); - let desc = desc.into(); - let entry = settings_search_entries() - .iter() - .find(|entry| t(entry.title) == label); - let modified = entry.is_some_and(|entry| entry.modified(cx.global::())); - let capture = self - .active_settings() - .is_some_and(|s| s.search_rows.borrow().is_some()); - // Descriptions can contain live status (for example an agent hook target), so they - // must not participate in the identity that preserves GPUI's hover state. - let element_id = settings_row_id(&label, &desc); - // The nav badge says "Appearance (2)"; this is what makes those two - // findable once you are on the page. Only mark rows when the section - // actually holds a match — otherwise a query that landed elsewhere - // would grey out a page the user is simply reading. - let (hit, miss) = match self - .active_settings() - .filter(|s| !s.search_active && !capture) - { - Some(s) => { - let query = s.search.read(cx).value().trim().to_lowercase(); - match query.is_empty() || section_match_count(s.section, &query) == 0 { - true => (false, false), - false => { - let hit = row_matches_query(s.section, &label, &query); - (hit, !hit) - } - } - } - None => (false, false), - }; - let first_hit_anchor = self.first_hit_anchor(&label, cx); - // The control never shrinks, so on a narrow pane it takes the width and - // the label column — which must keep `min_w_0` or long descriptions - // stop wrapping — is squeezed to a letter per line. Below the width - // where both still fit, put the control on its own line instead. - // Measured, not `flex_wrap`: wrapping made the label column size to its - // description, which then ran out past the row on every wide page. - let stacked = self.settings_row_under(STACK_ROW_BELOW, cx); - let labels = v_flex() - .gap_1() - .min_w_0() - .when(gated, |col| col.opacity(0.45)) - .child( - div() - .text_sm() - .font_weight(FontWeight::MEDIUM) - .text_color(theme.foreground) - .child(label), - ) - .when(!desc.is_empty(), |col| { - col.child( - div() - .text_xs() - .text_color(theme.muted_foreground) - .child(desc), - ) - }); - let labels = labels.when(modified, |v| { - v.child( - h_flex() - .gap_2() - .items_center() - .child( - div() - .text_xs() - .text_color(theme.muted_foreground) - .child(t(L10nKey::SettingsModified)), - ) - .when_some( - entry.filter(|e| { - e.title != L10nKey::SettingsSearchKeybindingsTitle - && e.title != L10nKey::SettingsThemeIntroTitle - }), - |v, entry| { - let key = entry.title; - v.child( - Button::new(SharedString::from(format!("reset-setting-{key:?}"))) - .label(t(L10nKey::SettingsResetValue)) - .ghost() - .small() - .on_click(cx.listener(move |this, _, window, cx| { - this.reset_settings_value(key, window, cx) - })), - ) - }, - ), - ) - }); - let row = div() - .id(element_id) - .flex() - .when(stacked, |row| row.flex_col().items_start().gap_2()) - .when(!stacked, |row| { - row.flex_row().items_center().justify_between().gap_8() - }) - .py_3() - .px_3() - .mx_neg_3() - .rounded(rounding::CARD_RADIUS) - .when(hit, |row| row.bg(theme.accent)) - // Only the first hit on the page carries the anchor: it is the one - // the page scrolls to, and a later row claiming it would drag the - // view past the matches above. - .anchor_scroll(first_hit_anchor) - .when(miss, |row| row.opacity(0.45)) - .child(labels) - // Stacked, the control column takes the row: that is what gives a - // `max_w_full` control a definite width to shrink against, and on - // the SSH page the widest of them is 260 in a column that can be - // `CONTENT_MIN_W`. - .child( - h_flex() - .when(stacked, |c| c.w_full()) - .when(!stacked, |c| c.flex_shrink_0()) - .child(control), - ); - if capture { - if let Some(entry) = entry { - self.active_settings() - .unwrap() - .search_rows - .borrow_mut() - .as_mut() - .unwrap() - .push((entry.title, row.into_any_element())); - return div().id("captured-setting"); - } - } - row - } - - pub(crate) fn segmented( - &self, - id: impl Into, - options: &[&str], - selected: usize, - cx: &mut Context, - on_pick: impl Fn(&mut Self, usize, &mut Window, &mut Context) + 'static, - ) -> AnyElement { - let sf = cx.global::().window; - self.segmented_on(sf, id, options, selected, cx, on_pick) - } - - pub(crate) fn segmented_on( - &self, - sf: presets::Surface, - id: impl Into, - options: &[&str], - selected: usize, - cx: &mut Context, - on_pick: impl Fn(&mut Self, usize, &mut Window, &mut Context) + 'static, - ) -> AnyElement { - self.segmented_full(sf, id, options, Some(selected), None, cx, on_pick) - } - - /// A segmented control over a fixed set of values, used where the config - /// accepts anything in a range. When the live value matches a bucket - /// exactly that bucket is highlighted; when it does not, a trailing - /// "Custom (N)" cell carries the highlight instead of the nearest bucket - /// getting a label it does not have — `scrollback_limit: 5000` used to - /// light up "10,000", and clicking that cell silently overwrote the real - /// value with the bucket's (#550). - /// - /// `selected` and `custom_label` come as a pair out of [`preset_choice`]: - /// exactly one of them is `Some`, so exactly one cell is highlighted. The - /// custom cell is not a button — there is no bucket value behind it to - /// write — so it takes neither a click handler nor a pointer cursor, and - /// the buckets beside it stay clickable to move off the custom value. - pub(crate) fn segmented_valued( - &self, - id: impl Into, - options: &[&str], - selected: Option, - custom_label: Option, - cx: &mut Context, - on_pick: impl Fn(&mut Self, usize, &mut Window, &mut Context) + 'static, - ) -> AnyElement { - let sf = cx.global::().window; - self.segmented_full(sf, id, options, selected, custom_label, cx, on_pick) - } - - fn segmented_full( - &self, - sf: presets::Surface, - id: impl Into, - options: &[&str], - selected: Option, - custom_label: Option, - cx: &mut Context, - on_pick: impl Fn(&mut Self, usize, &mut Window, &mut Context) + 'static, - ) -> AnyElement { - let border = cx.theme().border; - let id: SharedString = id.into(); - let on_pick = std::rc::Rc::new(on_pick); - let count = options.len() + usize::from(custom_label.is_some()); - // The display cells: the fixed buckets, then the custom cell if the - // live value matched none of them. - let cells: Vec<(String, Option)> = options - .iter() - .enumerate() - .map(|(i, l)| (l.to_string(), Some(i))) - .chain(custom_label.map(|l| (l, None))) - .collect(); - h_flex() - .id(gpui::ElementId::Name(id.clone())) - .h(px(24.)) - .rounded(rounding::TRACK_RADIUS) - .border_1() - .border_color(border) - .bg(gpui::rgb(sf.base)) - .overflow_hidden() - .children(cells.into_iter().enumerate().map(|(i, (label, bucket))| { - // A bucket is highlighted only on an exact match, and the - // custom cell (`bucket == None`) exactly when no bucket was. - let active = bucket == selected; - let on_pick = on_pick.clone(); - let corners = - rounding::segment_corners(i, count, rounding::TRACK_RADIUS, rounding::HAIRLINE); - let cell = h_flex() - .id(gpui::ElementId::NamedInteger(id.clone(), i as u64)) - .items_center() - .justify_center() - .h_full() - .px_2p5() - .text_sm() - .rounded_corners(corners) - .when(i > 0, |s| s.border_l_1().border_color(border)) - .when(active, |s| { - s.bg(gpui::rgb(sf.selected)) - .text_color(gpui::rgb(sf.text_selected)) - .font_weight(FontWeight::MEDIUM) - }) - .when(!active, |s| { - s.text_color(gpui::rgb(sf.text_resting)) - .hover(|h| h.bg(gpui::rgb(sf.hover))) - }) - .child(label); - match bucket { - Some(ix) => cell - .cursor_pointer() - .active(|s| s.bg(gpui::rgb(sf.pressed))) - .on_click(cx.listener(move |this, _, window, cx| { - on_pick(this, ix, window, cx); - })), - // The custom cell names the current value; it is not a - // button, because there is no bucket value to write. - None => cell, - } - })) - .into_any_element() - } - - fn render_settings_general(&self, cx: &mut Context) -> AnyElement { - let Some(state) = self.active_settings() else { - return div().into_any_element(); - }; - let language_select = state.language_select.clone(); - let foreground = cx.theme().foreground; - let muted_fg = cx.theme().muted_foreground; - let control_h = px(24.); - let language_control = Select::new(&language_select) - .small() - .w(px(FIELD_W)) - .h(control_h) - .menu_max_h(px(224.)) - .into_any_element(); - - v_flex() - .child(self.settings_row(t(L10nKey::SettingsLanguage), t(L10nKey::SettingsLanguageDesc), language_control, cx)) - .child(self.section_rule(cx)) - .child(self.render_window_preferences(true, cx)) - .when(cfg!(target_os = "macos"), |this| { - this.child(self.section_rule(cx)).child( - v_flex() - .gap_2() - .child( - div() - .text_sm() - .font_weight(FontWeight::SEMIBOLD) - .text_color(foreground) - .child(t(L10nKey::SettingsDefaultTerminal)), - ) - .child( - div() - .text_xs() - .text_color(muted_fg) - .child(t(L10nKey::SettingsDefaultTerminalDesc)), - ) - .child( - Button::new("set-default-terminal") - .label(t(L10nKey::SettingsDefaultTerminalSet)) - .small() - .on_click(cx.listener(|_, _, window, cx| { - let message = match crate::core::default_terminal::set_as_default_terminal() { - Ok(()) => t(L10nKey::SettingsDefaultTerminalSetSuccess).to_string(), - Err(error) => t_fmt( - L10nKey::SettingsDefaultTerminalSetFailed, - &[("error", &error)], - ), - }; - window.push_notification(message, cx); - })), - ), - ) - }) - - .child(self.section_rule(cx)) - .child(self.render_settings_maintenance(cx)) - .into_any_element() - } - - fn render_settings_appearance(&self, cx: &mut Context) -> AnyElement { - let theme = cx.theme(); - let foreground = theme.foreground; - let border = theme.border; - let hover_bg = gpui::rgb(cx.global::().window.hover); - let stepper_bg = theme.secondary.opacity(0.35); - let font_size = self.font_size; - let (font_select, font_bold_select, font_italic_select, ui_font_select) = - match self.active_settings() { - Some(s) => ( - s.font_select.clone(), - s.font_bold_select.clone(), - s.font_italic_select.clone(), - s.ui_font_select.clone(), - ), - None => return div().into_any_element(), - }; - let cfg = cx.global::(); - let cursor_style = cfg.cursor_style; - let cursor_blink = cfg.cursor_blink; - let font_thicken = cfg.font_thicken; - let font_ligatures = cfg.font_features.as_ref().is_some_and(|features| { - features.is_calt_enabled() == Some(true) - || features - .tag_value_list() - .iter() - .any(|(tag, value)| tag == "liga" && *value != 0) - }); - - let step = move |id: &'static str, glyph: &'static str, slot: usize| { - let corners = - rounding::segment_corners(slot, 3, rounding::TRACK_RADIUS, rounding::HAIRLINE); - h_flex() - .id(id) - .items_center() - .justify_center() - .h_full() - .px_2p5() - .text_sm() - .cursor_pointer() - .text_color(foreground) - .when(slot > 0, |s| s.border_l_1().border_color(border)) - .rounded_corners(corners) - .hover(|h| h.bg(hover_bg)) - .child(glyph) - }; - let control_h = px(24.); - let stepper_row = move |dec: Stateful
, value: String, inc: Stateful
| { - h_flex() - .items_center() - .gap_3() - .child( - h_flex() - .items_center() - .h(control_h) - .rounded(rounding::TRACK_RADIUS) - .bg(stepper_bg) - .border_1() - .border_color(border) - .overflow_hidden() - .child(dec) - .child( - div() - .min_w(px(40.)) - .border_l_1() - .border_color(border) - .py_1() - .text_center() - .text_sm() - .text_color(foreground) - .child(value), - ) - .child(inc), - ) - .into_any_element() - }; - let font_size_control = stepper_row( - step("font-dec", "−", 0).on_click( - cx.listener(|this, _, _w, cx| this.change_font_size(-FONT_SIZE_STEP, cx)), - ), - format!("{:.0}", font_size), - step("font-inc", "+", 2) - .on_click(cx.listener(|this, _, _w, cx| this.change_font_size(FONT_SIZE_STEP, cx))), - ); - - let ui_font_size = self.ui_font_size(cx); - let ui_font_size_control = stepper_row( - step("ui-font-dec", "−", 0).on_click( - cx.listener(|this, _, _w, cx| this.change_ui_font_size(-UI_FONT_SIZE_STEP, cx)), - ), - format!("{ui_font_size:.0}"), - step("ui-font-inc", "+", 2).on_click( - cx.listener(|this, _, _w, cx| this.change_ui_font_size(UI_FONT_SIZE_STEP, cx)), - ), - ); - - let line_height = self.line_height; - let line_height_control = stepper_row( - step("lh-dec", "−", 0).on_click( - cx.listener(|this, _, _w, cx| this.change_line_height(-LINE_HEIGHT_STEP, cx)), - ), - format!("{:.2}", line_height), - step("lh-inc", "+", 2).on_click( - cx.listener(|this, _, _w, cx| this.change_line_height(LINE_HEIGHT_STEP, cx)), - ), - ); - - let font_dropdown = |state: &Entity>>| { - Select::new(state) - .small() - .w(px(FIELD_W)) - .h(control_h) - .search_placeholder(crate::ui::i18n::t(crate::ui::i18n::L10nKey::SearchFonts)) - .menu_max_h(px(224.)) - .into_any_element() - }; - let font_family_control = font_dropdown(&font_select); - let font_bold_control = font_dropdown(&font_bold_select); - let font_italic_control = font_dropdown(&font_italic_select); - let ui_font_family_control = font_dropdown(&ui_font_select); - let ligature_switch = crate::ui::theme::switch("font-ligatures", cx) - .checked(font_ligatures) - .on_click(cx.listener(|this, on: &bool, _w, cx| this.set_font_ligatures(*on, cx))) - .into_any_element(); - // macOS alone dilates glyph strokes, so elsewhere there is no row. - let thicken_row = cfg!(target_os = "macos").then(|| { - let thicken_switch = crate::ui::theme::switch("font-thicken", cx) - .checked(font_thicken) - .on_click(cx.listener(|this, on: &bool, _w, cx| this.set_font_thicken(*on, cx))) - .into_any_element(); - self.settings_row( - t(L10nKey::SettingsFontThicken), - t(L10nKey::SettingsFontThickenDesc), - thicken_switch, - cx, - ) - }); - - let cursor_idx = match cursor_style { - CursorStyle::Block => 0, - CursorStyle::Bar => 1, - CursorStyle::Underline => 2, - }; - let cursor_style_control = self.segmented( - "cursor-style", - &[ - t(L10nKey::CursorShapeBlock), - t(L10nKey::CursorShapeBar), - t(L10nKey::CursorShapeUnderline), - ], - cursor_idx, - cx, - |this, ix, _w, cx| { - let style = match ix { - 0 => CursorStyle::Block, - 1 => CursorStyle::Bar, - _ => CursorStyle::Underline, - }; - this.set_cursor_style(style, cx); - }, - ); - let blink_switch = crate::ui::theme::switch("cursor-blink", cx) - .checked(cursor_blink) - .on_click(cx.listener(|this, on: &bool, _w, cx| this.set_cursor_blink(*on, cx))) - .into_any_element(); - - v_flex() - .child(self.section_intro( - t(L10nKey::SettingsThemeIntroTitle), - t(L10nKey::SettingsThemeIntroDesc), - cx, - )) - .child(self.render_theme_selection(cx)) - .child(self.render_custom_themes(cx)) - .child(self.section_rule(cx)) - .child(self.render_window_section(cx)) - .child(self.section_rule(cx)) - .child(self.section_header(t(L10nKey::SettingsInterfaceFontGroup), cx)) - .child(self.settings_row( - t(L10nKey::SettingsUiFontFamily), - t(L10nKey::SettingsUiFontFamilyDesc), - ui_font_family_control, - cx, - )) - .child(self.settings_row( - t(L10nKey::SettingsUiFontSize), - t(L10nKey::SettingsUiFontSizeDesc), - ui_font_size_control, - cx, - )) - .child(self.section_rule(cx)) - .child(self.section_header(t(L10nKey::SettingsTerminalFontGroup), cx)) - .child(self.settings_row( - t(L10nKey::SettingsFontFamily), - t(L10nKey::SettingsFontFamilyDesc), - font_family_control, - cx, - )) - .child(self.settings_row( - t(L10nKey::SettingsFontSize), - t(L10nKey::SettingsFontSizeDesc), - font_size_control, - cx, - )) - .child(self.settings_row( - t(L10nKey::SettingsLineHeight), - t(L10nKey::SettingsLineHeightDesc), - line_height_control, - cx, - )) - .child(self.settings_row( - t(L10nKey::SettingsBoldFont), - t(L10nKey::SettingsBoldFontDesc), - font_bold_control, - cx, - )) - .child(self.settings_row( - t(L10nKey::SettingsItalicFont), - t(L10nKey::SettingsItalicFontDesc), - font_italic_control, - cx, - )) - .child(self.settings_row( - t(L10nKey::SettingsFontLigatures), - t(L10nKey::SettingsFontLigaturesDesc), - ligature_switch, - cx, - )) - .when_some(thicken_row, |v, row| v.child(row)) - .child(self.section_rule(cx)) - .child(self.section_header(t(L10nKey::SettingsCursor), cx)) - .child(self.settings_row( - t(L10nKey::SettingsCursorShape), - t(L10nKey::SettingsCursorShapeDesc), - cursor_style_control, - cx, - )) - .child(self.settings_row( - t(L10nKey::SettingsCursorBlink), - t(L10nKey::SettingsCursorBlinkDesc), - blink_switch, - cx, - )) - .into_any_element() - } - - fn render_window_section(&self, cx: &mut Context) -> AnyElement { - let Some(slider) = self - .active_settings() - .map(|s| s.window_opacity_slider.clone()) - else { - return div().into_any_element(); - }; - let config = cx.global::(); - let overridden = window_overrides_active(config, cfg!(target_os = "windows")); - let dim_inactive_panes = config.dim_inactive_panes; - let opacity = Tty7App::effective_window_opacity(cx); - - let opacity_control = h_flex() - .items_center() - .gap_3() - .w(px(FIELD_W)) - .max_w_full() - .child(div().flex_1().child(Slider::new(&slider))) - .child( - div() - .w(px(38.)) - .flex_shrink_0() - .whitespace_nowrap() - .text_right() - .text_sm() - .text_color(cx.theme().foreground) - .child(format!("{:.0}%", opacity * 100.)), - ) - .into_any_element(); - // Windows exposes the native backdrop materials directly; macOS keeps - // the simple blur toggle, which drives its vibrancy. - #[cfg(target_os = "windows")] - let blur_control = { - // Both selects come from the same SettingsState resolved at the - // top of this function (window_opacity_slider), so the None arm - // is unreachable today; fall back to an empty control rather - // than returning from the whole section — a missing select must - // never silently drop the opacity slider and the rest. - match self - .active_settings() - .map(|s| s.window_backdrop_select.clone()) - { - Some(select) => Select::new(&select) - .small() - .w(px(FIELD_W)) - .h(px(24.)) - .menu_max_h(px(224.)) - .into_any_element(), - None => div().into_any_element(), - } - }; - #[cfg(not(target_os = "windows"))] - let blur_control = - { - let theme = presets::by_id(cx, &crate::ui::theme::effective_preset_id(cx)); - let blur = config.window_blur.unwrap_or(theme.blur); - crate::ui::theme::switch("window-blur", cx) - .checked(blur) - .on_click(cx.listener(|this, on: &bool, window, cx| { - this.set_window_blur(*on, window, cx) - })) - .into_any_element() - }; - // `Auto` is the one backdrop that still defers to the legacy blur - // flag, which is shared with the other platforms' vibrancy switch and - // travels with a synced config. Offer that switch here exactly when it - // has an effect — otherwise a stored `window_blur: true` would blur - // the window with no visible control to clear it, short of the reset - // button, which also discards the user's opacity. - #[cfg(target_os = "windows")] - let auto_blur_row = (config.window_backdrop == WindowBackdrop::Auto).then(|| { - let theme = presets::by_id(cx, &crate::ui::theme::effective_preset_id(cx)); - let blur = config.window_blur.unwrap_or(theme.blur); - let control = - crate::ui::theme::switch("window-blur", cx) - .checked(blur) - .on_click(cx.listener(|this, on: &bool, window, cx| { - this.set_window_blur(*on, window, cx) - })) - .into_any_element(); - self.settings_row( - t(L10nKey::SettingsBlur), - // Not `SettingsBlurDesc` — that one describes the switch's - // usual job, blurring whatever sits behind the window. This - // row explains its one remaining job on Windows: feeding the - // `Auto` material. - t(L10nKey::SettingsBlurAutoDesc), - control, - cx, - ) - }); - #[cfg(not(target_os = "windows"))] - let auto_blur_row: Option> = None; - let dim_switch = crate::ui::theme::switch("dim-inactive-panes", cx) - .checked(dim_inactive_panes) - .on_click(cx.listener(|this, on: &bool, _w, cx| this.set_dim_inactive_panes(*on, cx))) - .into_any_element(); - - v_flex() - .child(self.section_header(t(L10nKey::SettingsTransparency), cx)) - .child(self.settings_row( - t(L10nKey::SettingsOpacity), - t(L10nKey::SettingsOpacityDesc), - opacity_control, - cx, - )) - .child(self.settings_row( - t(if cfg!(target_os = "windows") { - L10nKey::SettingsBackdrop - } else { - L10nKey::SettingsBlur - }), - t(if cfg!(target_os = "windows") { - L10nKey::SettingsBackdropDesc - } else { - L10nKey::SettingsBlurDesc - }), - blur_control, - cx, - )) - .children(auto_blur_row) - .when(overridden, |this| { - this.child( - h_flex().mt_2().child( - Button::new("follow-theme-window") - .label(t(L10nKey::FollowTheme)) - .small() - .on_click(cx.listener(|this, _, window, cx| { - this.reset_window_overrides(window, cx) - })), - ), - ) - }) - .child(self.settings_row( - t(L10nKey::SettingsDimInactivePanes), - t(L10nKey::SettingsDimInactivePanesDesc), - dim_switch, - cx, - )) - .into_any_element() - } - - fn render_custom_themes(&self, cx: &mut Context) -> AnyElement { - let editor = self.active_settings().and_then(|s| s.theme_editor.as_ref()); - - let folder_button = Button::new("open-themes-folder") - .label(t(L10nKey::SettingsOpenThemesFolder)) - .small() - .on_click(cx.listener(|this, _, w, cx| this.open_themes_folder(w, cx))); - - if let Some(editor) = editor { - let label_of = |&(edit, ref state): &(ThemeEdit, Entity)| { - ( - crate::ui::app::theme_edit_label(edit).to_string(), - state.clone(), - ) - }; - let seed: Vec<_> = editor.seed.iter().map(label_of).collect(); - let ansi: Vec<_> = editor.ansi.iter().map(label_of).collect(); - let image_opacity_slider = editor.image_opacity_slider.clone(); - - let theme = presets::by_id(cx, &crate::ui::theme::effective_preset_id(cx)); - let image = theme.image.clone(); - let image_name = image.as_ref().map(|i| { - i.path - .file_name() - .map(|n| n.to_string_lossy().to_string()) - .unwrap_or_else(|| i.path.display().to_string()) - }); - let image_control = h_flex() - .items_center() - .gap_2() - .w(px(FIELD_W)) - .child( - Button::new("pick-theme-image") - .label(if image.is_some() { - t(L10nKey::SettingsChangeThemeImage) - } else { - t(L10nKey::SettingsChooseThemeImage) - }) - .small() - .on_click(cx.listener(|this, _, _w, cx| this.pick_theme_image(cx))), - ) - .when_some(image_name, |this, name| { - this.child( - div() - .flex_1() - .min_w_0() - .overflow_hidden() - .text_sm() - .text_color(cx.theme().muted_foreground) - .child(name), - ) - .child( - Button::new("remove-theme-image") - .label(t(L10nKey::SettingsRemoveThemeImage)) - .small() - .on_click(cx.listener(|this, _, window, cx| { - this.remove_theme_image(window, cx) - })), - ) - }) - .into_any_element(); - let image_opacity_row = image_opacity_slider.map(|slider| { - let readout = image.as_ref().map(|i| i.opacity).unwrap_or(0.3); - let control = h_flex() - .items_center() - .gap_3() - .w(px(FIELD_W)) - .child(div().flex_1().child(Slider::new(&slider))) - .child( - div() - .w(px(38.)) - .flex_shrink_0() - .whitespace_nowrap() - .text_right() - .text_sm() - .text_color(cx.theme().foreground) - .child(format!("{:.0}%", readout * 100.)), - ) - .into_any_element(); - self.settings_row( - t(L10nKey::SettingsImageOpacity), - t(L10nKey::SettingsImageOpacityDesc), - control, - cx, - ) - }); - - return v_flex() - .mt_5() - .child(self.section_intro( - t(L10nKey::SettingsEditTheme), - t(L10nKey::SettingsEditThemeIntro), - cx, - )) - .children( - seed.into_iter() - .map(|(label, state)| self.render_theme_color_row(label, state, cx)), - ) - .child(self.settings_row( - t(L10nKey::SettingsBackgroundImage), - t(L10nKey::SettingsBackgroundImageDesc), - image_control, - cx, - )) - .children(image_opacity_row) - .child(self.section_header(t(L10nKey::SettingsAnsiColors), cx)) - .children( - ansi.into_iter() - .map(|(label, state)| self.render_theme_color_row(label, state, cx)), - ) - .child(h_flex().mt_4().child(folder_button)) - .into_any_element(); - } - - v_flex() - .mt_5() - .child(self.section_intro( - t(L10nKey::SettingsCustomThemes), - t(L10nKey::SettingsCustomThemesIntro), - cx, - )) - .child( - h_flex() - .gap_3() - .child( - Button::new("duplicate-theme") - .label(t(L10nKey::SettingsDuplicateToEdit)) - .small() - .on_click(cx.listener(|this, _, window, cx| { - this.fork_active_theme(window, cx) - })), - ) - .child(folder_button), - ) - .into_any_element() - } - - fn render_theme_color_row( - &self, - label: String, - state: Entity, - cx: &mut Context, - ) -> impl IntoElement + use<> { - let control = ColorPicker::new(&state).small().into_any_element(); - self.settings_row(label, "", control, cx) - } - - fn render_settings_ssh(&self, cx: &mut Context) -> AnyElement { - let border = cx.theme().border; - let Some((master_scroll, detail_scroll)) = self - .active_settings() - .map(|s| (s.ssh_master_scroll.clone(), s.ssh_detail_scroll.clone())) - else { - return div().into_any_element(); - }; - let master = v_flex() - .id("ssh-master") - .size_full() - .overflow_y_scroll() - .track_scroll(&master_scroll) - .child(self.render_ssh_master(cx)); - let detail = v_flex() - .id("ssh-detail") - .size_full() - .overflow_y_scroll() - .track_scroll(&detail_scroll) - .child( - div() - .pt(px(crate::ui::app::TITLE_BAR_HEIGHT)) - .px_8() - .pb_8() - .child( - div() - .w_full() - .max_w(px(720.)) - .child(self.render_ssh_detail(cx)), - ), - ); - h_flex() - .size_full() - .items_start() - .child( - v_flex() - .flex_shrink_0() - .w(px(self.settings_columns_now(cx).ssh_list)) - .h_full() - .border_r_1() - .border_color(border) - .child(crate::ui::scrollbar::with_vertical_scrollbar( - "ssh-master-scrollbar", - master, - &master_scroll, - )), - ) - .child(v_flex().flex_1().min_w_0().h_full().child( - crate::ui::scrollbar::with_vertical_scrollbar( - "ssh-detail-scrollbar", - detail, - &detail_scroll, - ), - )) - .into_any_element() - } - - fn render_ssh_master(&self, cx: &mut Context) -> AnyElement { - let muted = cx.theme().muted_foreground; - let sf = cx.global::().window; - let profiles = cx.global::().ssh_profiles.clone(); - let (filter, collapsed, detail) = match self.active_settings() { - Some(s) => ( - s.ssh_filter.clone(), - s.ssh_collapsed_groups.clone(), - s.ssh_detail, - ), - None => return div().into_any_element(), - }; - let query = filter.read(cx).value().trim().to_lowercase(); - let live = self.live_ssh_profiles(cx); - let menu_app = cx.entity().downgrade(); - - let header = v_flex() - .gap_2() - .child(self.header_text(t(L10nKey::SettingsHosts), cx)) - .child( - h_flex() - .items_center() - .gap_2() - .child( - Icon::empty() - .path("stock/icons/search.svg") - .size(px(16.)) - .text_color(muted), - ) - .child( - div() - .flex_1() - .min_w_0() - .child(Input::new(&filter).appearance(false).pl_0()), - ) - .child( - h_flex() - .flex_shrink_0() - .gap_0p5() - .child( - Button::new("ssh-profiles-add") - .icon(Icon::new(IconName::Plus)) - .ghost() - .small() - .tooltip(t(L10nKey::SettingsNewHost)) - .on_click(cx.listener(|this, _, window, cx| { - this.add_new_profile(window, cx) - })), - ) - .child( - Button::new("ssh-profiles-more") - .icon(Icon::empty().path("stock/icons/ellipsis.svg")) - .ghost() - .small() - .tooltip(t(L10nKey::TabTooltipMore)) - .dropdown_menu_with_anchor( - gpui::Anchor::TopRight, - move |menu, _window, _cx| { - Self::ssh_master_menu(menu, &menu_app) - }, - ), - ), - ), - ); - - let mut groups: Vec<(String, Vec)> = Vec::new(); - for p in profiles.iter().filter(|p| ssh_row_matches(p, &query)) { - let key = ssh_group_key(p).to_string(); - match groups.iter_mut().find(|(k, _)| *k == key) { - Some((_, bucket)) => bucket.push(p.clone()), - None => groups.push((key, vec![p.clone()])), - } - } - groups.sort_by(|a, b| { - ssh_group_rank(&a.0) - .cmp(&ssh_group_rank(&b.0)) - .then_with(|| a.0.cmp(&b.0)) - }); - - let mut list = v_flex().gap_0p5().w_full().child(self.render_ssh_row( - "ssh-defaults-row", - t(L10nKey::SettingsDefaults), - t(L10nKey::SettingsInheritedByEveryHost), - detail == SshDetail::Defaults, - None, - sf, - cx.listener(|this, _, window, cx| this.select_ssh_defaults(window, cx)), - None, - cx, - )); - - if profiles.is_empty() { - list = list.child( - div() - .py_4() - // px_2 is what `render_ssh_row` insets its title by: a note - // standing in for the rows starts on their column, not on - // the list's own edge. - .px_2() - .text_sm() - .text_color(muted) - .child(t(L10nKey::SettingsNoSavedHosts)), - ); - } else if groups.is_empty() { - list = list.child( - div() - .py_4() - .px_2() - .text_sm() - .text_color(muted) - .child(t_fmt(L10nKey::SettingsNothingMatches, &[("query", &query)])), - ); - } - - for (key, bucket) in groups { - let is_collapsed = query.is_empty() && collapsed.contains(&key); - let live_here = bucket.iter().filter(|p| live.contains(&p.id)).count(); - list = list.child(self.render_ssh_group_header( - &key, - bucket.len(), - is_collapsed, - live_here, - cx, - )); - if is_collapsed { - continue; - } - for p in &bucket { - list = list.child(self.render_ssh_host_row( - p, - detail == SshDetail::Profile(p.id), - live.contains(&p.id), - sf, - cx, - )); - } - } - - v_flex() - .p_2() - .gap_2() - .pt(px(crate::ui::app::TITLE_BAR_HEIGHT)) - .child(header) - .child(list) - .into_any_element() - } - - fn ssh_master_menu(menu: PopupMenu, app: &gpui::WeakEntity) -> PopupMenu { - menu.min_w(px(200.)) - .item( - PopupMenuItem::new(t(L10nKey::SettingsImportFromSshConfig)).on_click({ - let app = app.clone(); - move |_, window, cx| { - let _ = - app.update(cx, |this, cx| this.import_ssh_config_profiles(window, cx)); - } - }), - ) - .item( - PopupMenuItem::new(t(L10nKey::SettingsExpandAllGroups)).on_click({ - let app = app.clone(); - move |_, _window, cx| { - let _ = app.update(cx, |this, cx| { - if let Some(s) = this.active_settings_mut() { - s.ssh_collapsed_groups.clear(); - } - cx.notify(); - }); - } - }), - ) - } - - fn render_ssh_group_header( - &self, - key: &str, - count: usize, - collapsed: bool, - live_here: usize, - cx: &mut Context, - ) -> AnyElement { - let muted = cx.theme().muted_foreground; - let sf = cx.global::().window; - let owned_key = key.to_string(); - let chevron = if collapsed { - IconName::ChevronRight - } else { - IconName::ChevronDown - }; - h_flex() - .id(SharedString::from(format!("ssh-group-{key}"))) - .items_center() - .gap_1() - .w_full() - .mt_2() - .py_1() - // 8 + 10 + 4 puts the group name on the same column as a host - // title, which sits 8 + 6 + 8 past the list edge — and it hands - // the header the same 8px inset the rows hover with. - .px_2() - .rounded_md() - .cursor_pointer() - .text_xs() - .text_color(muted) - .hover(|s| s.bg(gpui::rgb(sf.hover))) - .on_mouse_down( - MouseButton::Left, - cx.listener(move |this, _, _w, cx| { - cx.stop_propagation(); - this.toggle_ssh_group(owned_key.clone(), cx); - }), - ) - .child(Icon::new(chevron).size(px(10.))) - .child(div().truncate().child(ssh_group_label(key).to_string())) - .child(div().child(format!("· {count}"))) - .child(div().flex_1()) - .when(collapsed && live_here > 0, |row| { - row.child( - h_flex() - .items_center() - .gap_1() - .child(div().size(px(5.)).rounded_full().bg(cx.theme().success)) - .child(div().child(live_here.to_string())), - ) - }) - .into_any_element() - } - - fn render_ssh_host_row( - &self, - p: &SshProfile, - selected: bool, - live: bool, - sf: presets::Surface, - cx: &mut Context, - ) -> AnyElement { - let id = p.id; - let row_idx = id.as_u128() as usize; - let subtitle = to_connect_string(p); - let title = if p.name.is_empty() { - subtitle.clone() - } else { - p.name.clone() - }; - self.render_ssh_row( - SharedString::from(format!("ssh-profile-row-{row_idx}")), - title, - subtitle, - selected, - Some(live), - sf, - cx.listener(move |this, _, window, cx| { - if selected { - return; - } - if let Some(profile) = cx - .global::() - .ssh_profiles - .iter() - .find(|p| p.id == id) - .cloned() - { - this.ssh_form_load(&profile, window, cx); - } - }), - Some(id), - cx, - ) - } - - #[allow(clippy::too_many_arguments)] - fn render_ssh_row( - &self, - element_id: impl Into, - title: impl Into, - subtitle: impl Into, - selected: bool, - dot: Option, - sf: presets::Surface, - on_select: impl Fn(&gpui::MouseDownEvent, &mut Window, &mut App) + 'static, - menu_for: Option, - cx: &mut Context, - ) -> AnyElement { - let muted = cx.theme().muted_foreground; - let success = cx.theme().success; - let border = cx.theme().border; - let title: SharedString = title.into(); - let group_name = SharedString::from(format!("ssh-row-group-{title}")); - let hover_group = group_name.clone(); - - let row = h_flex() - .id(element_id) - .group(group_name) - .items_center() - .gap_2() - .w_full() - .py_2() - .px_2() - .rounded_md() - .when(selected, |r| r.bg(gpui::rgb(sf.selected))) - .when(!selected, |r| r.hover(|s| s.bg(gpui::rgb(sf.hover)))) - .on_mouse_down(MouseButton::Left, move |ev, window, cx| { - cx.stop_propagation(); - on_select(ev, window, cx); - }) - // The gutter is here on every row, dot or no dot. Only hosts carry - // a liveness dot, and skipping the space on the rows that don't — - // Defaults, and nothing else — started their title 14px left of - // every host title under them. - .child( - div() - .flex_shrink_0() - .size(px(6.)) - .when_some(dot, |d, live| { - d.rounded_full() - .when(live, |d| d.bg(success)) - .when(!live, |d| d.border_1().border_color(border)) - }), - ) - .child( - v_flex() - .min_w_0() - .flex_1() - .gap_0p5() - .child( - div() - .text_sm() - .truncate() - .when(selected, |d| { - d.text_color(gpui::rgb(sf.text_selected)) - .font_weight(FontWeight::MEDIUM) - }) - .when(!selected, |d| d.text_color(gpui::rgb(sf.text_resting))) - .child(title), - ) - .child( - div() - .text_xs() - .text_color(muted) - .truncate() - .child(subtitle.into()), - ), - ); - - let Some(id) = menu_for else { - return row.into_any_element(); - }; - let menu_app = cx.entity().downgrade(); - let ctx_app = cx.entity().downgrade(); - let row_idx = id.as_u128() as usize; - row.child( - div() - .flex_shrink_0() - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .when(!selected, move |s| { - s.opacity(0.).group_hover(hover_group, |s| s.opacity(1.)) - }) - .child( - Button::new(("ssh-prof-menu", row_idx)) - .icon(Icon::empty().path("stock/icons/ellipsis.svg")) - .ghost() - .small() - .tooltip(t(L10nKey::TabTooltipMore)) - .dropdown_menu_with_anchor( - gpui::Anchor::TopRight, - move |menu, _window, cx| { - Self::ssh_profile_row_menu(menu, id, cx.theme().danger, &menu_app) - }, - ), - ), - ) - .context_menu(move |menu, _window, cx| { - Self::ssh_profile_row_menu(menu, id, cx.theme().danger, &ctx_app) - }) - .into_any_element() - } - fn live_ssh_profiles(&self, cx: &App) -> std::collections::HashSet { use crate::daemon::protocol::SshPhase; let mut live = std::collections::HashSet::new(); @@ -4489,20 +2008,6 @@ impl Tty7App { live } - pub(crate) fn select_ssh_defaults(&mut self, window: &mut Window, cx: &mut Context) { - if self.ssh_form_dirty(cx) { - self.with_settings_edits_resolved(window, cx, |this, window, cx| { - this.select_ssh_defaults(window, cx) - }); - return; - } - if let Some(s) = self.active_settings_mut() { - s.ssh_form = None; - s.ssh_detail = SshDetail::Defaults; - } - cx.notify(); - } - fn toggle_ssh_group(&mut self, key: String, cx: &mut Context) { if let Some(s) = self.active_settings_mut() { if !s.ssh_collapsed_groups.remove(&key) { @@ -4513,277 +2018,6 @@ impl Tty7App { cx.notify(); } - fn render_ssh_detail(&self, cx: &mut Context) -> AnyElement { - let detail = self - .active_settings() - .map(|s| s.ssh_detail) - .unwrap_or(SshDetail::None); - match detail { - SshDetail::Defaults => self.render_ssh_defaults_detail(cx), - SshDetail::Profile(_) - if self.active_settings().is_some_and(|s| s.ssh_form.is_some()) => - { - self.render_ssh_profile_form(cx) - } - _ => self.render_ssh_empty_state(cx), - } - } - - fn render_ssh_empty_state(&self, cx: &mut Context) -> AnyElement { - let muted = cx.theme().muted_foreground; - let Some(input) = self.active_settings().map(|s| s.ssh_quick_connect.clone()) else { - return div().into_any_element(); - }; - let target = input.read(cx).value().trim().to_string(); - let parsed = crate::core::ssh_profile::parse_quick_connect(&target); - let saved = cx.global::().ssh_profiles.len(); - - let unlinked = { - let known: std::collections::HashSet = cx - .global::() - .ssh_profiles - .iter() - .map(|p| p.name.clone()) - .collect(); - crate::core::ssh_config::import_profiles() - .into_iter() - .filter(|i| !known.contains(&i.profile.name)) - .map(|i| i.profile.name) - .collect::>() - }; - - let heading = if saved == 0 { - t(L10nKey::SettingsNoHostsYet) - } else { - t(L10nKey::SettingsNothingSelected) - }; - - let mut body = v_flex() - .gap_1() - .child(self.header_text(heading, cx)) - .child( - div() - .text_sm() - .text_color(muted) - .child(t(L10nKey::SettingsTypeAddressToConnect)), - ) - .child( - h_flex() - .mt_3() - .w_full() - .max_w(px(380.)) - .gap_2() - .child( - div() - .flex_1() - .min_w_0() - .child(Input::new(&input).small().w_full()), - ) - .child( - Button::new("ssh-quick-connect") - .label(t(L10nKey::Connect)) - .primary() - .small() - .disabled(parsed.is_none()) - .on_click(cx.listener(|this, _, window, cx| { - this.ssh_quick_connect_from_settings(window, cx) - })), - ), - ); - - if !unlinked.is_empty() { - let n = unlinked.len(); - let names = unlinked.join(", "); - body = body.child( - h_flex() - .mt_6() - .gap_3() - .items_center() - .w_full() - .max_w(px(460.)) - .p_3() - .rounded_lg() - .border_1() - .border_color(cx.theme().border) - .child( - v_flex() - .flex_1() - .min_w_0() - .gap_0p5() - .child(div().text_sm().font_weight(FontWeight::MEDIUM).child(t_fmt( - L10nKey::SettingsMoreInSshConfig, - &[("count", &n.to_string())], - ))) - .child(div().text_xs().text_color(muted).truncate().child(names)), - ) - .child( - Button::new("ssh-empty-import") - .label(t(L10nKey::Link)) - .small() - .on_click(cx.listener(|this, _, window, cx| { - this.import_ssh_config_profiles(window, cx) - })), - ), - ); - } - - body.into_any_element() - } - - fn ssh_quick_connect_from_settings(&mut self, window: &mut Window, cx: &mut Context) { - let Some(target) = self - .active_settings() - .map(|s| s.ssh_quick_connect.read(cx).value().trim().to_string()) - else { - return; - }; - let Some(qc) = crate::core::ssh_profile::parse_quick_connect(&target) else { - return; - }; - self.close_settings_then(window, cx, move |this, window, cx| { - this.quick_connect(qc, window, cx) - }); - } - - fn render_ssh_defaults_detail(&self, cx: &mut Context) -> AnyElement { - let muted = cx.theme().muted_foreground; - let imported = cx - .global::() - .ssh_profiles - .iter() - .filter(|p| p.group.as_deref() == Some(crate::core::ssh_config::IMPORTED_GROUP)) - .count(); - - let config_block = v_flex() - .child(self.section_intro( - "~/.ssh/config", - t_plural(L10nKey::SettingsAliasesLinked, imported, &[]), - cx, - )) - .child( - self.settings_row( - t(L10nKey::SettingsImportAliases), - t(L10nKey::SettingsImportAliasesDesc), - Button::new("ssh-defaults-import") - .label(t(L10nKey::SettingsImportNow)) - .small() - .on_click(cx.listener(|this, _, window, cx| { - this.import_ssh_config_profiles(window, cx) - })) - .into_any_element(), - cx, - ), - ); - - v_flex() - .child( - v_flex() - .gap_1() - .mb_6() - .child(self.header_text(t(L10nKey::SettingsDefaults), cx)) - .child( - div() - .text_sm() - .text_color(muted) - .child(t(L10nKey::SettingsDefaultsIntro)), - ), - ) - .child(self.render_ssh_security_block(cx)) - .child(self.section_rule(cx)) - .child(config_block) - .into_any_element() - } - - fn ssh_profile_row_menu( - menu: PopupMenu, - id: Uuid, - danger: gpui::Hsla, - app: &gpui::WeakEntity, - ) -> PopupMenu { - let menu = menu - .min_w(px(180.)) - .item(PopupMenuItem::new(t(L10nKey::Connect)).on_click({ - let app = app.clone(); - move |_, window, cx| { - let _ = app.update(cx, |this, cx| { - this.close_settings_then(window, cx, move |this, window, cx| { - this.connect_ssh_profile(id, window, cx) - }); - }); - } - })) - .item( - PopupMenuItem::new(t(L10nKey::SettingsCopyAddress)).on_click({ - let app = app.clone(); - move |_, _window, cx| { - let _ = app.update(cx, |this, cx| this.copy_profile_connect_string(id, cx)); - } - }), - ) - .item(PopupMenuItem::new(t(L10nKey::SettingsDuplicate)).on_click({ - let app = app.clone(); - move |_, window, cx| { - let _ = app.update(cx, |this, cx| this.duplicate_profile(id, window, cx)); - } - })) - .item( - PopupMenuItem::new(t(L10nKey::SettingsForgetPassword)).on_click({ - let app = app.clone(); - move |_, window, cx| { - let _ = - app.update(cx, |this, cx| this.forget_profile_password(id, window, cx)); - } - }), - ) - .separator(); - - menu.item( - PopupMenuItem::element(move |_window, _cx| { - div().text_color(danger).child(t(L10nKey::Delete)) - }) - .on_click({ - let app = app.clone(); - move |_, window, cx| { - let _ = app.update(cx, |this, cx| this.delete_profile(id, window, cx)); - } - }), - ) - } - - fn render_ssh_security_block(&self, cx: &mut Context) -> AnyElement { - let verify = cx.global::().verify_host_keys; - let verify_switch = crate::ui::theme::switch("ssh-verify-host-keys", cx) - .checked(verify) - .on_click(cx.listener(|this, on: &bool, _w, cx| this.set_verify_host_keys(*on, cx))) - .into_any_element(); - - let warn_on_close = cx.global::().ssh_warn_on_close; - let warn_switch = crate::ui::theme::switch("ssh-warn-on-close", cx) - .checked(warn_on_close) - .on_click(cx.listener(|this, on: &bool, _w, cx| this.set_ssh_warn_on_close(*on, cx))) - .into_any_element(); - - v_flex() - .child(self.section_intro( - t(L10nKey::SettingsSecurity), - t(L10nKey::SettingsSecurityIntro), - cx, - )) - .child(self.settings_row( - t(L10nKey::SettingsVerifyHostKeys), - t(L10nKey::SettingsVerifyHostKeysDesc), - verify_switch, - cx, - )) - .child(self.settings_row( - t(L10nKey::WarnBeforeClosing), - t(L10nKey::SettingsWarnBeforeClosingDesc), - warn_switch, - cx, - )) - .into_any_element() - } - fn ssh_form_mut(&mut self) -> Option<&mut SshProfileForm> { self.active_settings_mut().and_then(|s| s.ssh_form.as_mut()) } @@ -4822,10 +2056,12 @@ impl Tty7App { .iter() .map(|r| seed_forward_row(window, cx, r)) .collect(); - let identity_files = seed_hinted_multi( + // One line, comma-separated: the form is a row of single-line fields, + // and a profile with more than one key is the exception. + let identity_files = seed_hinted( window, cx, - &profile.identity_files.join("\n"), + &profile.identity_files.join(", "), DEFAULT_KEY_HINT, ); @@ -4898,35 +2134,7 @@ impl Tty7App { ); let login_scripts = seed_input(window, cx, &profile.login_scripts.join("\n"), true); - let auth_select = cx.new(|cx| { - SelectState::new( - SearchableVec::new(auth_mode_labels()), - Some(IndexPath::default().row(auth_mode_index(profile.auth))), - window, - cx, - ) - }); - let mut subs = Vec::new(); - subs.push(cx.subscribe_in( - &auth_select, - window, - |this, _select, ev: &SelectEvent>, _window, cx| { - let SelectEvent::Confirm(Some(label)) = ev else { - return; - }; - let picked = auth_mode_labels().iter().position(|l| l == label); - if let (Some(ix), Some(form)) = (picked, this.ssh_form_mut()) { - form.auth = AUTH_MODES[ix]; - // The same reason the typed fields drop it: the answer on - // screen was about a handshake this form would no longer - // make. A green line under a changed method reads as a - // method that was proved, and it was not. - form.test = None; - cx.notify(); - } - }, - )); // The passphrase belongs to whichever key the field above names, so // when that answer changes the box has to change with it. Without this // a form opened on one key and pointed at another would carry the @@ -4970,13 +2178,7 @@ impl Tty7App { subs.push( cx.subscribe_in(input, window, |this, _i, ev: &InputEvent, _w, cx| { if matches!(ev, InputEvent::Change) { - // The test answered for the host as it was typed a - // moment ago. Keeping the green line under a changed - // address would be the form vouching for something it - // never dialled. - if let Some(form) = this.ssh_form_mut() { - form.test = None; - } + let _ = this.ssh_form_mut(); cx.notify(); } }), @@ -4987,15 +2189,11 @@ impl Tty7App { editing: profile.id, carry_group: profile.group.clone(), carry_credential_ref: profile.credential_ref.clone(), - show_jump: profile.jump_host.is_some(), - show_forwards: !profile.forwards.is_empty(), - show_advanced: false, name, host, port, user, auth: profile.auth, - auth_select, password, passphrase, loaded_password, @@ -5024,13 +2222,20 @@ impl Tty7App { remote_clipboard_write: profile.remote_clipboard_write, verify_host_keys: profile.verify_host_keys, warn_on_close: profile.warn_on_close, - test: None, _subs: subs, }; let editing = form.editing; + let known = cx + .global::() + .ssh_profiles + .iter() + .any(|p| p.id == editing); if let Some(s) = self.active_settings_mut() { s.ssh_form = Some(form); - s.ssh_detail = SshDetail::Profile(editing); + s.ssh_confirm_remove = false; + // A saved host edits in its own row; a new one gets a row of its + // own at the top, so nothing else is shown opened. + s.ssh_open = known.then_some(editing); } cx.notify(); } @@ -5057,7 +2262,7 @@ impl Tty7App { socks: val(&form.socks), http: val(&form.http), auth: form.auth, - identity_files: raw(&form.identity_files), + identity_files: raw(&form.identity_files).replace(',', "\n"), agent_forward: form.agent_forward, credential_ref: form.carry_credential_ref.clone(), forwards: form.forwards.iter().filter_map(|r| r.collect(cx)).collect(), @@ -5093,7 +2298,7 @@ impl Tty7App { let Some(form) = self.active_settings().and_then(|s| s.ssh_form.as_ref()) else { return; }; - let files = split_lines(&form.identity_files.read(cx).value()); + let files = split_lines(&form.identity_files.read(cx).value().replace(',', "\n")); let host = form.host.read(cx).value().trim().to_string(); let user = form.user.read(cx).value().trim().to_string(); let key = first_readable_key_in(&files, &host, &user); @@ -5115,39 +2320,6 @@ impl Tty7App { cx.notify(); } - /// Add key files to the profile from the system file picker, one per line - /// alongside whatever is already named. Typing the path still works — this - /// is for the far more common case of knowing the key by sight and not by - /// path. - pub(crate) fn pick_ssh_identity_file(&mut self, window: &mut Window, cx: &mut Context) { - let rx = cx.prompt_for_paths(gpui::PathPromptOptions { - files: true, - directories: false, - multiple: true, - prompt: None, - }); - cx.spawn_in(window, async move |this, cx| { - let Ok(Ok(Some(paths))) = rx.await else { - return; - }; - let _ = this.update_in(cx, |this, window, cx| { - let Some(form) = this.active_settings().and_then(|s| s.ssh_form.as_ref()) else { - return; - }; - let input = form.identity_files.clone(); - let mut lines = split_lines(&input.read(cx).value()); - for path in paths { - let path = tildify(&path.to_string_lossy()); - if !lines.contains(&path) { - lines.push(path); - } - } - input.update(cx, |i, cx| i.set_value(lines.join("\n"), window, cx)); - }); - }) - .detach(); - } - pub(crate) fn save_editing_profile( &mut self, window: &mut Window, @@ -5179,23 +2351,10 @@ impl Tty7App { Some(id) } - fn cancel_ssh_form(&mut self, window: &mut Window, cx: &mut Context) { - let id = self - .active_settings() - .and_then(|s| s.ssh_form.as_ref().map(|form| form.editing)); - let saved = id.and_then(|id| { - cx.global::() - .ssh_profiles - .iter() - .find(|p| p.id == id) - .cloned() - }); + pub(crate) fn cancel_ssh_form(&mut self, cx: &mut Context) { if let Some(s) = self.active_settings_mut() { s.ssh_form = None; - s.ssh_detail = SshDetail::Defaults; - } - if let Some(profile) = saved { - self.ssh_form_load(&profile, window, cx); + s.ssh_confirm_remove = false; } cx.notify(); } @@ -5339,11 +2498,6 @@ impl Tty7App { .any(|p| p.id != except && p.user == user && p.host == host && p.port == port) } - pub(crate) fn save_ssh_form(&mut self, window: &mut Window, cx: &mut Context) { - self.save_editing_profile(window, cx); - cx.notify(); - } - /// Whether the SSH profile form on screen holds edits that were never /// saved. Save is enabled off exactly this, so closing on it is the same /// question the button already answers — and it compares what the form @@ -5371,136 +2525,11 @@ impl Tty7App { }); } - /// Dial the host the form is holding — without saving it, and without - /// spending a tab on the answer. The daemon does the connecting, so this is - /// the same path Connect would take. - pub(crate) fn test_ssh_form_connection(&mut self, window: &mut Window, cx: &mut Context) { - let Some((profile, errors)) = self.ssh_form_collect(cx) else { - return; - }; - if !errors.is_empty() { - return; - } - let mut spec = Box::new(self.native_ssh_spec_for_profile(&profile, cx)); - // The spec is built from the keychain, so without this Test would dial - // with the *saved* password while a new one sits typed on screen — - // and report a failure the form could not explain. - if let Some(form) = self.active_settings().and_then(|s| s.ssh_form.as_ref()) { - if form.wants_password() { - let typed = form.password.read(cx).value().to_string(); - if !typed.is_empty() { - spec.password = Some(typed); - } - } - if form.wants_key() { - let typed = form.passphrase.read(cx).value().to_string(); - if let (false, Some(key)) = (typed.is_empty(), first_readable_key(&profile)) { - spec.key_passphrases - .get_or_insert_with(Default::default) - .insert(key, typed); - } - } - } - let editing = profile.id; - if let Some(form) = self.ssh_form_mut() { - form.test = Some(SshTestState::Running); - } - cx.notify(); - - let probe = cx - .background_executor() - .spawn(async move { crate::terminal::RemoteTerminal::test_ssh(spec) }); - cx.spawn_in(window, async move |this, cx| { - let report = probe.await; - let _ = this.update(cx, |this, cx| { - // The form may have been closed, or moved to another host, in - // the seconds the handshake took. An answer about a host nobody - // is looking at any more is not worth showing. - if let Some(form) = this.ssh_form_mut().filter(|f| f.editing == editing) { - form.test = Some(SshTestState::Done(report)); - cx.notify(); - } - }); - }) - .detach(); - } - - pub(crate) fn save_and_connect_profile(&mut self, window: &mut Window, cx: &mut Context) { - if let Some(id) = self.save_editing_profile(window, cx) { - self.close_settings_then(window, cx, move |this, window, cx| { - this.connect_ssh_profile(id, window, cx) - }); - } - } - pub(crate) fn add_new_profile(&mut self, window: &mut Window, cx: &mut Context) { let profile = SshProfile::new(String::new()); self.ssh_form_load(&profile, window, cx); } - pub(crate) fn duplicate_profile( - &mut self, - id: Uuid, - window: &mut Window, - cx: &mut Context, - ) { - let Some(mut profile) = cx - .global::() - .ssh_profiles - .iter() - .find(|p| p.id == id) - .cloned() - else { - return; - }; - profile.id = Uuid::new_v4(); - profile.name = t_fmt(L10nKey::SettingsProfileCopied, &[("name", &profile.name)]); - self.update_config(cx, |cfg| cfg.ssh_profiles.push(profile.clone())); - self.ssh_form_load(&profile, window, cx); - } - - pub(crate) fn delete_profile(&mut self, id: Uuid, window: &mut Window, cx: &mut Context) { - let Some(profile) = cx - .global::() - .ssh_profiles - .iter() - .find(|p| p.id == id) - .cloned() - else { - return; - }; - let name = profile.name.clone(); - // The entries routing through this profile are forgotten along with - // it (#485) — say so up front, naming the endpoint: once the profile - // is gone, its address is the part nobody can reproduce (the route - // origins are in-memory, the keychain entry goes too). Entries with - // a live or in-flight link are excluded, and nothing is ever sent to - // the machine — the remote sessions keep running. - let cascade = crate::ui::windows::cascade_for_profile(cx, id); - let mut body = t(L10nKey::SettingsDeleteProfileBody).to_string(); - if !cascade.is_empty() { - let endpoint = crate::core::session::RouteSnapshot::of_profile(&profile).endpoint(); - body.push(' '); - body.push_str(&t_plural( - L10nKey::SettingsDeleteProfileCascade, - cascade.len(), - &[("endpoint", endpoint.as_str())], - )); - } - let answer = window.prompt( - gpui::PromptLevel::Warning, - &t_fmt(L10nKey::FileTreeDeleteTitle, &[("name", &name)]), - Some(&body), - &crate::ui::confirm_answers(t(L10nKey::Delete), t(L10nKey::Cancel)), - cx, - ); - cx.spawn_in(window, async move |this, cx| { - let Ok(0) = answer.await else { return }; - let _ = this.update(cx, |this, cx| this.delete_profile_confirmed(id, cx)); - }) - .detach(); - } - fn delete_profile_confirmed(&mut self, id: Uuid, cx: &mut Context) { // "Forget password" lives on the menu that is about to stop existing, // so deleting the profile used to strand its keychain entry with no UI @@ -5559,11 +2588,14 @@ impl Tty7App { cfg.ssh_profiles.retain(|p| p.id != id); cfg.ssh_profile_frecency.remove(&id); }); - let editing_deleted = - self.active_settings().map(|s| s.ssh_detail) == Some(SshDetail::Profile(id)); - if let Some(s) = self.active_settings_mut().filter(|_| editing_deleted) { - s.ssh_form = None; - s.ssh_detail = SshDetail::None; + if let Some(s) = self.active_settings_mut() { + if s.ssh_form.as_ref().is_some_and(|f| f.editing == id) { + s.ssh_form = None; + } + if s.ssh_open == Some(id) { + s.ssh_open = None; + } + s.ssh_confirm_remove = false; } cx.notify(); } @@ -5670,3417 +2702,6 @@ impl Tty7App { } window.push_notification(notification, cx); } - - pub(crate) fn copy_profile_connect_string(&mut self, id: Uuid, cx: &mut Context) { - if let Some(profile) = cx - .global::() - .ssh_profiles - .iter() - .find(|p| p.id == id) - { - let s = to_connect_string(profile); - cx.write_to_clipboard(gpui::ClipboardItem::new_string(s)); - } - } - - pub(crate) fn forget_profile_password( - &mut self, - id: Uuid, - window: &mut Window, - cx: &mut Context, - ) { - let cfg = cx.global::(); - let Some(endpoint) = cfg - .ssh_profiles - .iter() - .find(|p| p.id == id) - .map(|p| format!("{}@{}:{}", p.user, p.host, p.port)) - else { - return; - }; - // One click used to be the whole gesture, and the thing it removed does - // not come back. Worse, the entry is the endpoint's rather than this - // row's, so a menu opened on one host can sign several of them out — - // name that count here instead of letting it turn up at the next - // connect on a host nobody touched. - let others = profiles_sharing_endpoint(cfg, id); - let body = if others == 0 { - t(L10nKey::SettingsForgetPasswordBody).to_string() - } else { - t_plural( - L10nKey::SettingsForgetPasswordSharedBody, - others, - &[("endpoint", &endpoint)], - ) - }; - let answer = window.prompt( - gpui::PromptLevel::Warning, - &t_fmt( - L10nKey::SettingsForgetPasswordTitle, - &[("endpoint", &endpoint)], - ), - Some(&body), - &crate::ui::confirm_answers(t(L10nKey::SettingsForgetPassword), t(L10nKey::Cancel)), - cx, - ); - cx.spawn_in(window, async move |this, cx| { - let Ok(0) = answer.await else { return }; - // The notification is the only sign the keychain was touched, and - // by now the click that asked for it is long gone — so it has to be - // raised from in here, on the window the prompt belonged to. - let _ = this.update_in(cx, |this, window, cx| { - if let Some(msg) = this.forget_profile_password_confirmed(id, cx) { - window.push_notification(msg, cx); - } - }); - }) - .detach(); - } - - fn forget_profile_password_confirmed( - &mut self, - id: Uuid, - cx: &mut Context, - ) -> Option { - use crate::core::keychain::{CredentialStore, OsCredentialStore}; - let (user, host, port) = cx - .global::() - .ssh_profiles - .iter() - .find(|p| p.id == id) - .map(|p| (p.user.clone(), p.host.clone(), p.port))?; - let endpoint = format!("{user}@{host}:{port}"); - Some( - match OsCredentialStore.delete_password(&user, &host, port) { - Ok(()) => t_fmt( - L10nKey::SettingsForgotPasswordFor, - &[("endpoint", &endpoint)], - ), - Err(e) => t_fmt( - L10nKey::SettingsCouldntForgetPassword, - &[("endpoint", &endpoint), ("error", &e.to_string())], - ), - }, - ) - } - - fn render_ssh_profile_form(&self, cx: &mut Context) -> AnyElement { - let Some(form) = self.active_settings().and_then(|s| s.ssh_form.as_ref()) else { - return div().into_any_element(); - }; - let editing = form.editing; - let muted = cx.theme().muted_foreground; - let success = cx.theme().success; - - let saved = cx - .global::() - .ssh_profiles - .iter() - .find(|p| p.id == editing) - .cloned(); - let (collected, errors) = self.ssh_form_collect(cx).unzip(); - let errors = errors.unwrap_or_default(); - // A password is not part of the profile, so a change to one is - // invisible to the comparison above — and Save would sit greyed out - // over a secret the user just typed. - let dirty = collected != saved || form.secrets_changed(cx); - let address = collected - .as_ref() - .map(to_connect_string) - .unwrap_or_default(); - let jump_name = form.jump.read(cx).value().trim().to_string(); - let live = self.live_ssh_profiles(cx).contains(&editing); - let name = form.name.read(cx).value().trim().to_string(); - let host = form.host.read(cx).value().trim().to_string(); - let title = match (name.is_empty(), host.is_empty()) { - (false, _) => name, - (true, false) => host, - (true, true) => t(L10nKey::SettingsNewHost).to_string(), - }; - - let testing = matches!(form.test, Some(SshTestState::Running)); - let test_line = form.test.as_ref().map(|state| match state { - SshTestState::Running => field_note(t(L10nKey::SettingsTestRunning), cx), - SshTestState::Done(report) => match report { - SshTestReport::Authenticated { elapsed_ms } => { - div().text_xs().text_color(success).child(t_fmt( - L10nKey::SettingsTestReached, - &[("time", &human_millis(*elapsed_ms))], - )) - } - SshTestReport::NeedsInput { need, .. } => { - field_note(t(ssh_test_need_message(*need)), cx) - } - SshTestReport::Failed { reason } => field_error( - t_fmt(L10nKey::SettingsTestFailed, &[("reason", reason)]), - cx, - ), - }, - }); - - let header = h_flex() - .w_full() - .when(self.settings_row_under(STACK_ROW_BELOW, cx), |v| { - v.flex_col() - }) - .items_start() - .justify_between() - .gap_4() - .child( - v_flex() - .min_w_0() - .flex_1() - .gap_1() - .child( - div() - .text_lg() - .font_weight(FontWeight::SEMIBOLD) - .truncate() - .child(title), - ) - .child( - h_flex() - .gap_1p5() - .text_xs() - .text_color(muted) - .child(div().truncate().child(address)) - .when(!jump_name.is_empty(), |r| { - r.child(div().child(t_fmt( - L10nKey::SettingsJumpHostVia, - &[("jump_name", &jump_name)], - ))) - }) - .when(live, |r| { - r.child( - div() - .text_color(success) - .child(format!("· {}", t(L10nKey::SettingsConnected))), - ) - }), - ), - ) - .child( - h_flex() - .flex_shrink_0() - .max_w_full() - .flex_wrap() - .gap_2() - .child( - Button::new("ssh-form-cancel") - .label(t(L10nKey::Cancel)) - .ghost() - .small() - .disabled(!dirty) - .on_click( - cx.listener(|this, _, window, cx| this.cancel_ssh_form(window, cx)), - ), - ) - .child( - // Dials the host exactly as Connect would — proxy, jump - // and all — but keeps the answer here instead of - // spending a tab on finding out. - Button::new("ssh-form-test") - .label(t(L10nKey::SettingsTestConnection)) - .small() - .disabled(!errors.is_empty() || testing) - .on_click(cx.listener(|this, _, window, cx| { - this.test_ssh_form_connection(window, cx) - })), - ) - .child( - Button::new("ssh-form-save") - .label(t(L10nKey::Save)) - .small() - .disabled(!dirty || !errors.is_empty()) - .on_click( - cx.listener(|this, _, window, cx| this.save_ssh_form(window, cx)), - ), - ) - .child( - // Connect saves first, so it answers to the same - // rules. Before this it answered to none at all, and - // an empty host reached the socket layer as a DNS - // error about a name nobody typed. - Button::new("ssh-form-connect") - .label(t(L10nKey::Connect)) - .primary() - .small() - .disabled(!errors.is_empty()) - .on_click(cx.listener(|this, _, window, cx| { - this.save_and_connect_profile(window, cx) - })), - ), - ); - - // Every field notifies on change, so this form re-renders on each - // keystroke: telling a brand-new host that it needs a host is - // something it would say before the user had typed a character. Hold - // that one line back until the group it belongs to has something in - // it. A malformed value has nothing to wait for and says so at once. - let core_blank = form.core_is_blank(cx); - let host_error = errors - .host - .as_ref() - .filter(|_| !core_blank) - .map(|e| field_error(e.message(), cx)); - let port_error = errors.port.as_ref().map(|e| field_error(e.message(), cx)); - - // Three fields whose labels say everything a sentence under them - // would: what goes in them is shown in the box itself, as a hint that - // gets out of the way the moment anything is typed. - let core = v_flex() - .gap_1() - .child(self.ssh_field_row( - t(L10nKey::SettingsName), - Input::new(&form.name).small().w_full().into_any_element(), - vec![], - cx, - )) - .child( - self.ssh_field_row( - t(L10nKey::SettingsHost), - h_flex() - .w_full() - .gap_2() - .child(Input::new(&form.host).small().flex_1().min_w_0()) - .child(Input::new(&form.port).small().w(px(64. * ui_scale(cx)))) - .into_any_element(), - host_error - .into_iter() - .chain(port_error) - .map(IntoElement::into_any_element) - .collect(), - cx, - ), - ) - .child(self.ssh_field_row( - t(L10nKey::SettingsUser), - Input::new(&form.user).small().w_full().into_any_element(), - vec![], - cx, - )); - - v_flex() - .gap_4() - .child(header) - // Under the buttons that produced it, on the right, where the eye - // already is after pressing Test. - .when_some(test_line, |col, line| { - col.child(h_flex().w_full().justify_end().child(line)) - }) - .child(core) - .child(self.render_ssh_profile_auth_section(form, cx)) - .child(self.render_ssh_profile_jump_section(form, &errors, cx)) - .child(self.render_ssh_profile_forwards_section(form, cx)) - .child(self.render_ssh_profile_advanced_section(form, &errors, cx)) - .into_any_element() - } - - /// One field of the host editor: its label in a narrow column on the left, - /// the field immediately beside it, and whatever the field has to say — - /// its description, or a complaint about what is in it — underneath the - /// field rather than underneath the label. - /// - /// The settings rows on the rest of this page push their control to the - /// far right edge of the page, which is right for a list of independent - /// switches and wrong for a form: it left a hand's width of nothing - /// between the word "Host" and the box a hostname goes in, and the eye had - /// to cross it once per field. Every SSH client worth borrowing from keeps - /// the two together. - fn ssh_field_row( - &self, - label: &str, - control: AnyElement, - under: Vec, - cx: &Context, - ) -> AnyElement { - let stacked = self.settings_row_under(STACK_FIELD_ROW_BELOW, cx); - let scale = ui_scale(cx); - div() - .flex() - .w_full() - .py_1p5() - .when(stacked, |row| row.flex_col().items_start().gap_1()) - .when(!stacked, |row| row.flex_row().items_start().gap_3()) - .child( - div() - .when(!stacked, |l| { - // Right up against the field, and level with the text - // inside it rather than with the top of its border — - // a left-aligned column of short words would leave a - // different-sized hole after every label. - l.w(px(SSH_LABEL_W * scale)) - .flex_shrink_0() - .pt(px(6.)) - .text_right() - }) - .text_sm() - .font_weight(FontWeight::MEDIUM) - .text_color(cx.theme().foreground) - .child(label.to_string()), - ) - .child( - // A definite width, not `flex_1`: a percentage inside a - // flex-grown box has no definite parent to resolve against, - // and every `w_full` control in here came out at its intrinsic - // size — a hostname field one character wide. - v_flex() - .w(px(FORM_FIELD_W * scale)) - .max_w_full() - .gap_1() - .child(control) - .children(under), - ) - .into_any_element() - } - - /// The credential half of the form, and the only part of it that is not - /// stored in the config file. - /// - /// Which boxes appear follows the method, the way every SSH client does - /// it: a password box under a key-only method would be a secret that is - /// stored and never offered. The split is the one `build_spec_inner` - /// makes when it decides what to hand the daemon. - fn render_ssh_profile_auth_section( - &self, - form: &SshProfileForm, - cx: &mut Context, - ) -> AnyElement { - // Whether there is a key to *store a passphrase against* — which is a - // readable file, not merely a path someone typed. `loaded_key` is that - // answer, kept current by `resync_key_passphrase`. - let has_key = form.loaded_key.is_some(); - v_flex() - .gap_1() - .child(self.subgroup_header(L10nKey::SettingsGroupAuthentication, cx)) - .child( - self.ssh_field_row( - t(L10nKey::SettingsAuth), - // Six methods is more than a segmented control can label - // without squeezing, so a dropdown carries the choice — the - // way the other long-form pickers on this page do. - Select::new(&form.auth_select) - .small() - .w_full() - .into_any_element(), - vec![field_note(t(L10nKey::SettingsAuthDesc), cx).into_any_element()], - cx, - ), - ) - .when(form.wants_password(), |col| { - col.child( - self.ssh_field_row( - t(L10nKey::SettingsPassword), - Input::new(&form.password) - .small() - .mask_toggle() - .w_full() - .into_any_element(), - vec![field_note(t(L10nKey::SettingsPasswordDesc), cx).into_any_element()], - cx, - ), - ) - }) - .when(form.wants_key(), |col| { - col.child( - self.ssh_field_row( - t(L10nKey::SettingsIdentityFiles), - h_flex() - .w_full() - .items_start() - .gap_2() - .child(Input::new(&form.identity_files).small().flex_1().min_w_0()) - .child( - Button::new("ssh-form-browse-key") - .label(t(L10nKey::SettingsBrowseKey)) - .small() - .on_click(cx.listener(|this, _, window, cx| { - this.pick_ssh_identity_file(window, cx) - })), - ) - .into_any_element(), - vec![ - field_note(t(L10nKey::SettingsIdentityFilesDesc), cx) - .into_any_element(), - ], - cx, - ), - ) - .child( - self.ssh_field_row( - t(L10nKey::SettingsKeyPassphrase), - Input::new(&form.passphrase) - .small() - .mask_toggle() - .disabled(!has_key) - .w_full() - .into_any_element(), - vec![ - field_note( - match has_key { - true => t(L10nKey::SettingsKeyPassphraseDesc), - false => t(L10nKey::SettingsPassphraseNeedsKey), - }, - cx, - ) - .into_any_element(), - ], - cx, - ), - ) - }) - .into_any_element() - } - - fn disclosure_header( - &self, - id: &'static str, - label: &str, - summary: &str, - open: bool, - cx: &mut Context, - on_toggle: impl Fn(&mut Self, &mut Context) + 'static, - ) -> AnyElement { - let muted = cx.theme().muted_foreground; - let sf = cx.global::().window; - let caret = if open { "▾" } else { "▸" }; - h_flex() - .id(id) - .items_center() - .gap_2() - .py_2() - // The other collapsible header on this page lights up under the - // pointer; this one only changed the cursor, so the two rows a - // reader folds and unfolds answered differently to the same move. - .px_2p5() - .mx_neg_2p5() - .rounded_lg() - .cursor_pointer() - .hover(|s| s.bg(gpui::rgb(sf.hover))) - .on_mouse_down( - MouseButton::Left, - cx.listener(move |this, _, _w, cx| on_toggle(this, cx)), - ) - .child(div().text_color(muted).child(caret.to_string())) - .child( - div() - .font_weight(gpui::FontWeight::MEDIUM) - .child(label.to_string()), - ) - .child(div().text_xs().text_color(muted).child(summary.to_string())) - .into_any_element() - } - - fn render_ssh_profile_jump_section( - &self, - form: &SshProfileForm, - errors: &SshFormErrors, - cx: &mut Context, - ) -> AnyElement { - let summary = { - let name = form.jump.read(cx).value().trim().to_string(); - if name.is_empty() { - t(L10nKey::SettingsNoneSummary).to_string() - } else { - name - } - }; - // A complaint nobody can see is a Save button that is greyed out for - // no reason the user can read, and the field keeps its text whether - // this section is folded or not — so an error holds it open. - let open = form.show_jump || errors.jump.is_some(); - let mut section = v_flex().child(self.disclosure_header( - "ssh-sec-jump", - t(L10nKey::SettingsJumpHost), - &summary, - open, - cx, - |this, cx| { - if let Some(f) = this.ssh_form_mut() { - f.show_jump = !f.show_jump; - cx.notify(); - } - }, - )); - if open { - let error = errors.jump.as_ref().map(|e| field_error(e.message(), cx)); - section = section.child( - self.settings_row( - t(L10nKey::SettingsJumpHost), - t(L10nKey::SettingsJumpHostDesc), - v_flex() - .gap_1() - .w(px(FIELD_W)) - .max_w_full() - .child(Input::new(&form.jump).small()) - .when_some(error, |col, line| col.child(line)) - .into_any_element(), - cx, - ), - ); - } - section.into_any_element() - } - - fn render_ssh_profile_forwards_section( - &self, - form: &SshProfileForm, - cx: &mut Context, - ) -> AnyElement { - let muted = cx.theme().muted_foreground; - let count = form - .forwards - .iter() - .filter(|r| r.collect(cx).is_some()) - .count(); - let summary = match count { - 0 => t(L10nKey::SettingsNoneSummary).to_string(), - _ => t_plural(L10nKey::SettingsRulesOpenedWithConnection, count, &[]), - }; - let mut section = v_flex().child(self.disclosure_header( - "ssh-sec-fwd", - t(L10nKey::SettingsPortForwarding), - &summary, - form.show_forwards, - cx, - |this, cx| { - if let Some(f) = this.ssh_form_mut() { - f.show_forwards = !f.show_forwards; - cx.notify(); - } - }, - )); - if !form.show_forwards { - return section.into_any_element(); - } - - for (idx, row) in form.forwards.iter().enumerate() { - section = section.child(self.render_forward_rule_row(idx, row, cx)); - } - - section - .child( - h_flex().pt_1p5().child( - Button::new("ssh-fwd-add") - .label(t(L10nKey::SettingsAddRule)) - .ghost() - .small() - .on_click( - cx.listener(|this, _, window, cx| this.add_forward_rule(window, cx)), - ), - ), - ) - .child( - h_flex() - .flex_wrap() - .gap_3() - .pt_1() - .text_xs() - .text_color(muted) - .child(t(L10nKey::SettingsFwdLegendLocal)) - .child(t(L10nKey::SettingsFwdLegendRemote)) - .child(t(L10nKey::SettingsFwdLegendDynamic)), - ) - .into_any_element() - } - - fn render_forward_rule_row( - &self, - idx: usize, - row: &ForwardRuleForm, - cx: &mut Context, - ) -> AnyElement { - let muted = cx.theme().muted_foreground; - let needs_target = row.kind != ForwardKind::Dynamic; - let kind_idx = match row.kind { - ForwardKind::Local => 0, - ForwardKind::Remote => 1, - ForwardKind::Dynamic => 2, - }; - let incomplete = (row.collect(cx).is_none() && !row.is_blank(cx)).then(|| { - field_error( - match needs_target { - true => t(L10nKey::SettingsFwdNeedsBoth), - false => t(L10nKey::SettingsFwdNeedsListen), - }, - cx, - ) - }); - - // Below `SPLIT_FORWARD_ROW_BELOW` the five controls stop fitting on one - // line. The kind switch, the description and the remove button keep the - // first line; the mapping the rule is actually about takes the second, - // where two host fields, two ports and an arrow are what has to fit - // inside `CONTENT_MIN_W` — hence the lower floor on the host field. - let split = self.settings_row_under(SPLIT_FORWARD_ROW_BELOW, cx); - let stack_ends = self.settings_row_under(STACK_FORWARD_ENDS_BELOW, cx); - let host_min = if split { 80. } else { 104. }; - let endpoint = |host: &Entity, port: &Entity| { - h_flex() - .gap_1() - .items_center() - // Was pinned at 104px, which does not hold - // `ip-10-0-3-217.eu-west-1.compute.internal`. Same floor, but - // the field now takes a share of the row's slack instead of - // handing all of it to the free-text description beside it. - .child( - div() - .flex_1() - .min_w(px(host_min)) - .child(Input::new(host).xsmall()), - ) - .child(div().text_xs().text_color(muted).child(":")) - .child(div().w(px(58.)).child(Input::new(port).xsmall())) - }; - let mapping = |line: Div| { - line.child( - div() - .flex_1() - .when(stack_ends, |end| end.w_full()) - .child(endpoint(&row.bind_host, &row.bind_port)), - ) - .child(div().flex_shrink_0().text_xs().text_color(muted).child("→")) - .child( - div() - .flex_1() - .opacity(if needs_target { - 1.0 - } else { - crate::ui::forwards::NO_TARGET_FADE - }) - .when(stack_ends, |end| end.w_full()) - .child(endpoint(&row.target_host, &row.target_port)), - ) - }; - - let kind_switch = div().flex_shrink_0().child(self.segmented( - format!("ssh-fwd-kind-{idx}"), - &["L", "R", "D"], - kind_idx, - cx, - move |this, ix, _w, cx| { - let kind = match ix { - 1 => ForwardKind::Remote, - 2 => ForwardKind::Dynamic, - _ => ForwardKind::Local, - }; - if let Some(f) = this.ssh_form_mut() - && let Some(r) = f.forwards.get_mut(idx) - { - r.kind = kind; - cx.notify(); - } - }, - )); - let description = div() - .flex_1() - .min_w(px(80.)) - .child(Input::new(&row.description).xsmall()); - let remove = crate::ui::tab_strip::hit_target( - Button::new(("ssh-fwd-remove", idx)) - .icon(Icon::new(IconName::Close)) - .ghost() - .xsmall(), - ) - .tooltip(t(L10nKey::SettingsRemoveRule)) - .on_click(cx.listener(move |this, _, _w, cx| this.remove_forward_rule(idx, cx))); - - let rule = match split { - true => v_flex() - .gap_1() - .child( - h_flex() - .gap_2() - .items_center() - .child(kind_switch) - .child(description) - .child(remove), - ) - .child(match stack_ends { - true => mapping(v_flex().gap_1().items_start()), - false => mapping(h_flex().gap_2().items_center()), - }), - false => mapping(h_flex().gap_2().items_center().child(kind_switch)) - .child(description) - .child(remove), - }; - - v_flex() - .gap_0p5() - .py_1() - .child(rule) - .when_some(incomplete, |col, line| col.child(line)) - .into_any_element() - } - - fn add_forward_rule(&mut self, window: &mut Window, cx: &mut Context) { - let row = seed_forward_row(window, cx, &ForwardRule::default()); - let subs: Vec<_> = forward_row_inputs(&row) - .into_iter() - .map(|input| { - cx.subscribe_in(input, window, |_this, _i, ev: &InputEvent, _w, cx| { - if matches!(ev, InputEvent::Change) { - cx.notify(); - } - }) - }) - .collect(); - if let Some(f) = self.ssh_form_mut() { - f.forwards.push(row); - f._subs.extend(subs); - f.show_forwards = true; - } - cx.notify(); - } - - fn remove_forward_rule(&mut self, idx: usize, cx: &mut Context) { - if let Some(f) = self.ssh_form_mut() - && idx < f.forwards.len() - { - f.forwards.remove(idx); - } - cx.notify(); - } - - fn render_ssh_profile_advanced_section( - &self, - form: &SshProfileForm, - errors: &SshFormErrors, - cx: &mut Context, - ) -> AnyElement { - // This section opens folded, and a proxy address saved back when the - // form wrote port 0 is wrong the moment the profile is opened. Let the - // error unfold it, or Save is disabled over something out of sight. - let open = form.show_advanced || errors.socks.is_some() || errors.http.is_some(); - let mut section = v_flex().child(self.disclosure_header( - "ssh-sec-adv", - t(L10nKey::SettingsAdvanced), - t(L10nKey::SettingsAdvancedSummary), - open, - cx, - |this, cx| { - if let Some(f) = this.ssh_form_mut() { - f.show_advanced = !f.show_advanced; - cx.notify(); - } - }, - )); - if !open { - return section.into_any_element(); - } - - let text_row = |this: &Self, - label: &str, - desc: &str, - input: &Entity, - cx: &mut Context| { - this.settings_row( - label.to_string(), - desc.to_string(), - div() - .w(px(FIELD_W)) - .max_w_full() - .child(Input::new(input).small()) - .into_any_element(), - cx, - ) - }; - // The three proxy fields are the only advanced ones with rules of - // their own, so they carry room for a line under the control: a - // complaint when the address is wrong, and otherwise a word about - // which of them the connection is actually going to use. - let proxy_row = |this: &Self, - label: &str, - desc: &str, - input: &Entity, - error: Option<&SshFieldError>, - note: Option, - cx: &mut Context| { - let line = match error { - Some(e) => Some(field_error(e.message(), cx)), - None => note.map(|n| field_note(n, cx)), - }; - this.settings_row( - label.to_string(), - desc.to_string(), - v_flex() - .gap_1() - .w(px(FIELD_W)) - .max_w_full() - .child(Input::new(input).small()) - .when_some(line, |col, line| col.child(line)) - .into_any_element(), - cx, - ) - }; - - // Filling in two of these has always meant one of them doing nothing. - // Which one was left for the user to find out by connecting (#438). - let filled = |input: &Entity| !input.read(cx).value().trim().is_empty(); - let (cmd_set, socks_set, http_set) = ( - filled(&form.proxy_command), - filled(&form.socks), - filled(&form.http), - ); - let pick = ProxyPick::of(cmd_set, socks_set, http_set); - - let on_off = |b: bool| { - if b { - t(L10nKey::SettingsValueOn) - } else { - t(L10nKey::SettingsValueOff) - } - }; - let vhk_default = on_off(cx.global::().verify_host_keys); - let woc_default = on_off(cx.global::().ssh_warn_on_close); - let vhk_idx = match form.verify_host_keys { - None => 0, - Some(true) => 1, - Some(false) => 2, - }; - let woc_idx = match form.warn_on_close { - None => 0, - Some(true) => 1, - Some(false) => 2, - }; - - section = section - // The key file and the two secrets moved up to the Authentication - // block on the form itself — they are what a connection is made - // of, not a corner of it. What is left here is the option that - // hands this host the local agent, which is a decision about - // trust rather than about how to log in. - .child(self.subgroup_header(L10nKey::SettingsGroupAuthentication, cx)) - .child( - self.settings_row( - t(L10nKey::SettingsAgentForwarding), - t(L10nKey::SettingsAgentForwardingDesc), - crate::ui::theme::switch("ssh-form-agent", cx) - .checked(form.agent_forward) - .on_click(cx.listener(|this, on: &bool, _w, cx| { - if let Some(f) = this.ssh_form_mut() { - f.agent_forward = *on; - cx.notify(); - } - })) - .into_any_element(), - cx, - ), - ) - .child(self.subgroup_header(L10nKey::SettingsGroupProxies, cx)) - .child(proxy_row( - self, - t(L10nKey::SettingsProxyCommand), - t(L10nKey::SettingsProxyCommandDesc), - &form.proxy_command, - None, - ProxyPick::Command.overridden_by(cmd_set, pick), - cx, - )) - .child(proxy_row( - self, - t(L10nKey::SettingsSocks5Proxy), - t(L10nKey::SettingsSocks5ProxyDesc), - &form.socks, - errors.socks.as_ref(), - ProxyPick::Socks.overridden_by(socks_set, pick), - cx, - )) - .child(proxy_row( - self, - t(L10nKey::SettingsHttpProxy), - t(L10nKey::SettingsHttpProxyDesc), - &form.http, - errors.http.as_ref(), - ProxyPick::Http.overridden_by(http_set, pick), - cx, - )) - .child(self.subgroup_header(L10nKey::SettingsGroupAlgorithms, cx)) - .child(text_row( - self, - t(L10nKey::SettingsKexAlgorithms), - t(L10nKey::SettingsKexAlgorithmsDesc), - &form.kex, - cx, - )) - .child(text_row( - self, - t(L10nKey::SettingsCiphers), - t(L10nKey::SettingsCiphersDesc), - &form.cipher, - cx, - )) - .child(text_row( - self, - t(L10nKey::SettingsMacs), - t(L10nKey::SettingsMacsDesc), - &form.mac, - cx, - )) - .child(text_row( - self, - t(L10nKey::SettingsHostKeyAlgorithms), - t(L10nKey::SettingsHostKeyAlgorithmsDesc), - &form.hostkey, - cx, - )) - // Compression here is the algorithm list russh negotiates, not - // ssh_config's yes/no switch, so it belongs with the other three - // lists rather than under Connection with the keepalives. - .child(text_row( - self, - t(L10nKey::SettingsCompression), - t(L10nKey::SettingsCompressionDesc), - &form.compression, - cx, - )) - .child(self.subgroup_header(L10nKey::SettingsGroupConnection, cx)) - .child(text_row( - self, - t(L10nKey::SettingsKeepaliveInterval), - t(L10nKey::SettingsKeepaliveIntervalDesc), - &form.keepalive_interval, - cx, - )) - .child(text_row( - self, - t(L10nKey::SettingsKeepaliveCountMax), - t(L10nKey::SettingsKeepaliveCountMaxDesc), - &form.keepalive_count, - cx, - )) - .child(text_row( - self, - t(L10nKey::SettingsConnectTimeout), - t(L10nKey::SettingsConnectTimeoutDesc), - &form.connect_timeout, - cx, - )) - .child(self.subgroup_header(L10nKey::SettingsGroupSession, cx)) - .child( - self.settings_row( - t(L10nKey::SettingsX11Forwarding), - t(L10nKey::SettingsX11ForwardingDesc), - crate::ui::theme::switch("ssh-form-x11", cx) - .checked(form.x11) - .on_click(cx.listener(|this, on: &bool, _w, cx| { - if let Some(f) = this.ssh_form_mut() { - f.x11 = *on; - cx.notify(); - } - })) - .into_any_element(), - cx, - ), - ) - .child( - self.settings_row( - t(L10nKey::SettingsShellIntegration), - t(L10nKey::SettingsShellIntegrationDesc), - crate::ui::theme::switch("ssh-form-shell-integration", cx) - .checked(form.shell_integration) - .on_click(cx.listener(|this, on: &bool, _w, cx| { - if let Some(f) = this.ssh_form_mut() { - f.shell_integration = *on; - cx.notify(); - } - })) - .into_any_element(), - cx, - ), - ) - .child(text_row( - self, - t(L10nKey::SettingsLoginScripts), - t(L10nKey::SettingsLoginScriptsDesc), - &form.login_scripts, - cx, - )) - .child( - self.settings_row( - t(L10nKey::SettingsSkipBanner), - t(L10nKey::SettingsSkipBannerDesc), - crate::ui::theme::switch("ssh-form-banner", cx) - .checked(form.skip_banner) - .on_click(cx.listener(|this, on: &bool, _w, cx| { - if let Some(f) = this.ssh_form_mut() { - f.skip_banner = *on; - cx.notify(); - } - })) - .into_any_element(), - cx, - ), - ) - .child(self.subgroup_header(L10nKey::SettingsGroupSecurity, cx)) - .child( - self.settings_row( - t(L10nKey::SettingsRemoteClipboardWrite), - t(L10nKey::SettingsRemoteClipboardWriteDesc), - crate::ui::theme::switch("ssh-form-remote-clipboard-write", cx) - .checked(form.remote_clipboard_write) - .on_click(cx.listener(|this, on: &bool, _w, cx| { - if let Some(f) = this.ssh_form_mut() { - f.remote_clipboard_write = *on; - cx.notify(); - } - })) - .into_any_element(), - cx, - ), - ) - .child(self.settings_row( - t(L10nKey::SettingsVerifyHostKeys), - t_fmt( - L10nKey::SettingsDefaultFollowsDefaults, - &[("value", vhk_default)], - ), - self.segmented( - "ssh-form-vhk", - &[ - t(L10nKey::SettingsDefault), - t(L10nKey::SettingsOn), - t(L10nKey::SettingsOff), - ], - vhk_idx, - cx, - |this, ix, _w, cx| { - if let Some(f) = this.ssh_form_mut() { - f.verify_host_keys = match ix { - 1 => Some(true), - 2 => Some(false), - _ => None, - }; - cx.notify(); - } - }, - ), - cx, - )) - .child(self.settings_row( - t(L10nKey::WarnBeforeClosing), - t_fmt( - L10nKey::SettingsDefaultFollowsDefaults, - &[("value", woc_default)], - ), - self.segmented( - "ssh-form-woc", - &[ - t(L10nKey::SettingsDefault), - t(L10nKey::SettingsOn), - t(L10nKey::SettingsOff), - ], - woc_idx, - cx, - |this, ix, _w, cx| { - if let Some(f) = this.ssh_form_mut() { - f.warn_on_close = match ix { - 1 => Some(true), - 2 => Some(false), - _ => None, - }; - cx.notify(); - } - }, - ), - cx, - )); - section.into_any_element() - } - - fn render_shell_group(&self, cx: &mut Context) -> AnyElement { - let muted_fg = cx.theme().muted_foreground; - let (program_input, args_input, wd_path_input) = match self.active_settings() { - Some(s) => ( - s.shell_program_input.clone(), - s.shell_args_input.clone(), - s.wd_path_input.clone(), - ), - None => return div().into_any_element(), - }; - let wd_strategy = cx.global::().working_directory.strategy; - - let platform_default = if cfg!(windows) { - "PowerShell" - } else { - t(L10nKey::SettingsShellDefaultLoginShell) - }; - - // tty7 already knows which shells are installed — it lists them on the - // new-tab button. Settings asked you to type one from memory instead, - // so the same choice was a menu in one place and a blind text field in - // the other. The field stays: a shell tty7 did not find still has to be - // reachable by path. - // Detected shells only. A `custom_shells` row is a menu extra rather - // than a candidate for the platform default, and this picker hands its - // choice on as a program alone — so offering one here would set the - // default to a bare program and drop the arguments the user wrote it - // for, silently. - let shells: Vec<_> = self - .shells - .shells - .iter() - .filter(|shell| !shell.user_authored) - .cloned() - .collect(); - let current_program = program_input.read(cx).value().trim().to_string(); - let platform_default_item: SharedString = if cfg!(windows) { - "PowerShell".into() - } else { - t(L10nKey::AppPlaceholderLoginShell).into() - }; - let picker_app = cx.entity().downgrade(); - let picker_input = program_input.clone(); - // The chevron rides inside the field rather than beside it: hung on the - // outside it would either push the box narrower than the Arguments box - // directly below or push past the column every other control ends on. - let program_picker = crate::ui::tab_strip::hit_target( - Button::new("shell-program-detected") - .icon(IconName::ChevronDown) - // No fill in any state, so it reads the way `Select` draws its - // own chevron: a mark inside the field, not a control sitting - // on top of one. `ghost` gave it a filled rounded rectangle - // while the menu was open, and `hit_target` sizes it to the - // 24px accessibility floor — which is exactly the field's inner - // height, so that fill met the border top and bottom and looked - // like a patch stuck over the field's right end. The field's - // own border and the tooltip carry the affordance. - .custom(ButtonCustomVariant::new(cx).foreground(muted_fg)) - .xsmall(), - ) - .disabled(shells.is_empty()) - .tooltip(t(L10nKey::SettingsShellDetected)) - .dropdown_menu_with_anchor(gpui::Anchor::TopRight, move |menu, _window, _cx| { - // As wide as the field it drops out of. Anchored `TopRight` on a - // chevron that sits *inside* the field, a 200px menu hung off the - // field's right half with its left edge 110px in from the field's - // own — a menu that looked like it belonged to something else. - let mut menu = menu.min_w(px(FIELD_W)); - let pick = |program: String| { - let app = picker_app.clone(); - let input = picker_input.clone(); - move |_: &_, window: &mut Window, cx: &mut App| { - input.update(cx, |state, cx| state.set_value(program.clone(), window, cx)); - if let Some(app) = app.upgrade() { - app.update(cx, |this, cx| this.commit_shell_from_picker(cx)); - } - } - }; - menu = menu.item( - PopupMenuItem::new(platform_default_item.clone()) - .checked(current_program.is_empty()) - .on_click(pick(String::new())), - ); - if !shells.is_empty() { - menu = menu.item(PopupMenuItem::separator()); - } - for shell in &shells { - menu = menu.item( - PopupMenuItem::new(shell.label.clone()) - .checked(current_program == shell.program) - .on_click(pick(shell.program.clone())), - ); - } - menu - }); - let program_control = div() - .w(px(FIELD_W)) - .max_w_full() - .child(Input::new(&program_input).small().suffix(program_picker)) - .into_any_element(); - // Args become argv verbatim, so a quote that never closes is a value - // that cannot be saved at all — `commit_shell` refuses it, and this - // line is the explanation (#551). The proxy row's pattern, including - // its caveat: the input commits on Enter/blur and this parent renders - // on that commit, so a half-typed quote is never marked wrong - // mid-keystroke. - let args_value = args_input.read(cx).value(); - let args_error = crate::ui::app::split_shell_args(&args_value) - .is_err() - .then(|| field_error(t(L10nKey::SettingsArgumentsInvalid), cx)); - let args_control = v_flex() - .gap_1() - .w(px(FIELD_W)) - .max_w_full() - .child(Input::new(&args_input).small()) - .when_some(args_error, |this, line| this.child(line)) - .into_any_element(); - - use crate::core::config::WdStrategy; - let wd_idx = match wd_strategy { - WdStrategy::Inherit => 0, - WdStrategy::Home => 1, - WdStrategy::Custom => 2, - }; - let wd_radio = self.segmented( - "wd-strategy", - &[ - t(L10nKey::SettingsWdInherit), - t(L10nKey::SettingsWdHome), - t(L10nKey::SettingsWdCustom), - ], - wd_idx, - cx, - |this, ix, _w, cx| { - let s = match ix { - 0 => WdStrategy::Inherit, - 1 => WdStrategy::Home, - _ => WdStrategy::Custom, - }; - this.set_working_directory_strategy(s, cx); - }, - ); - let wd_path_control = if wd_strategy == WdStrategy::Custom { - // Same pattern as the Arguments row above, with its caveat: the - // input commits on Enter/blur and this parent renders on that - // commit, so a half-typed path is never marked wrong - // mid-keystroke. `commit_working_directory_path` refuses the same - // value through the same predicate, so the red line and the - // not-saved config always agree (#601). - let wd_path_value = wd_path_input.read(cx).value(); - let wd_path_error = (!crate::ui::app::wd_path_saveable(&wd_path_value)) - .then(|| field_error(t(L10nKey::SettingsWdPathInvalid), cx)); - v_flex() - .gap_1() - .w(px(FIELD_W)) - .max_w_full() - .child(Input::new(&wd_path_input).small()) - .when_some(wd_path_error, |this, line| this.child(line)) - .into_any_element() - } else { - div().into_any_element() - }; - - v_flex() - .child(self.section_intro( - t(L10nKey::SettingsShell), - t_fmt( - L10nKey::SettingsShellIntro, - &[("default", platform_default)], - ), - cx, - )) - .child(self.settings_row( - t(L10nKey::SettingsProgram), - t(L10nKey::SettingsProgramDesc), - program_control, - cx, - )) - .child(self.settings_row( - t(L10nKey::SettingsArguments), - t(L10nKey::SettingsArgumentsDesc), - args_control, - cx, - )) - .child(self.settings_row( - t(L10nKey::SettingsStartIn), - t(L10nKey::SettingsStartInDesc), - wd_radio, - cx, - )) - .when( - wd_strategy == crate::core::config::WdStrategy::Custom, - |v| { - v.child(self.settings_row( - t(L10nKey::SettingsCustomPath), - t(L10nKey::SettingsCustomPathDesc), - wd_path_control, - cx, - )) - }, - ) - .child( - div() - .mt_3() - .text_xs() - .text_color(muted_fg) - .child(t(L10nKey::SettingsShellFooter)), - ) - .into_any_element() - } - - fn render_settings_terminal(&self, cx: &mut Context) -> AnyElement { - let foreground = cx.theme().foreground; - let cfg = cx.global::(); - let link_url = cfg.link_url; - let ssh_loopback_forward = cfg.ssh_loopback_forward; - let scroll_mult = cfg.mouse_scroll_multiplier; - let smooth_scroll = cfg.smooth_scroll; - let bell = cfg.bell; - // A bucket highlights only on an exact match; any other value gets a - // "Custom (N)" cell so the highlight never claims a number the config - // does not have, and clicking that cell cannot overwrite it (#550). - // Read off `cfg` here, with the rest of the copies: the control itself - // is built further down, past calls that borrow `cx` mutably. - let (scrollback_sel, scrollback_custom) = - preset_choice(&SCROLLBACK_BUCKETS, cfg.scrollback_limit, group_thousands); - let scroll_slider = match self.active_settings() { - Some(s) => s.scroll_slider.clone(), - None => return div().into_any_element(), - }; - let link_file_command_input = match self.active_settings() { - Some(s) => s.link_file_command_input.clone(), - None => return div().into_any_element(), - }; - - let link_switch = crate::ui::theme::switch("term-link-url", cx) - .checked(link_url) - .on_click(cx.listener(|this, on: &bool, _w, cx| this.set_link_url(*on, cx))) - .into_any_element(); - let ssh_loopback_switch = crate::ui::theme::switch("term-ssh-loopback-forward", cx) - .checked(ssh_loopback_forward) - .on_click(cx.listener(|this, on: &bool, _w, cx| this.set_ssh_loopback_forward(*on, cx))) - .into_any_element(); - let link_file_open = cfg.file_open_mode(); - let link_file_open_radio = self.segmented( - "term-link-file-open", - &[ - t(L10nKey::SettingsOpenFilesInternal), - t(L10nKey::SettingsOpenFilesSystem), - t(L10nKey::SettingsOpenFilesCommand), - ], - match link_file_open { - LinkFileOpen::Internal => 0, - LinkFileOpen::System => 1, - LinkFileOpen::Command => 2, - }, - cx, - |this, ix, _w, cx| { - let mode = match ix { - 0 => LinkFileOpen::Internal, - 1 => LinkFileOpen::System, - _ => LinkFileOpen::Command, - }; - this.set_link_file_open(mode, cx); - }, - ); - // Only shown under `Command`: an empty box next to two working modes - // reads as "this is what file links do", which is the one thing it is - // not unless the mode above says so. - let link_file_command_control = (link_file_open == LinkFileOpen::Command).then(|| { - div() - .w(px(300.)) - .max_w_full() - .child(Input::new(&link_file_command_input).small()) - .into_any_element() - }); - let scrollback_radio = self.segmented_valued( - "term-scrollback", - &SCROLLBACK_LABELS, - scrollback_sel, - scrollback_custom, - cx, - |this, ix, _w, cx| { - let lines = SCROLLBACK_BUCKETS - .get(ix) - .copied() - .unwrap_or(Config::default().scrollback_limit); - this.set_scrollback_limit(lines, cx); - }, - ); - - let bell_idx = match bell { - BellMode::None => 0, - BellMode::Visual => 1, - BellMode::Audible => 2, - BellMode::Both => 3, - }; - let bell_control = self.segmented( - "term-bell", - &[ - t(L10nKey::SettingsBellModeOff), - t(L10nKey::SettingsBellModeVisual), - t(L10nKey::SettingsBellModeAudible), - t(L10nKey::SettingsBellModeBoth), - ], - bell_idx, - cx, - |this, ix, _w, cx| { - let mode = match ix { - 0 => BellMode::None, - 1 => BellMode::Visual, - 2 => BellMode::Audible, - 3 => BellMode::Both, - _ => BellMode::default(), - }; - this.set_bell_mode(mode, cx); - }, - ); - let scroll_control = h_flex() - .items_center() - .gap_3() - .w(px(FIELD_W)) - .max_w_full() - .child(div().flex_1().child(Slider::new(&scroll_slider))) - .child( - div() - .w(px(38.)) - .flex_shrink_0() - .whitespace_nowrap() - .text_right() - .text_sm() - .text_color(foreground) - .child(format!("{scroll_mult:.2}×")), - ) - .into_any_element(); - let smooth_scroll_switch = crate::ui::theme::switch("term-smooth-scroll", cx) - .checked(smooth_scroll) - .on_click(cx.listener(|this, on: &bool, _w, cx| this.set_smooth_scroll(*on, cx))) - .into_any_element(); - - v_flex() - .child(self.render_shell_group(cx)) - .child(self.section_rule(cx)) - .child(self.render_input_groups(true, cx)) - .child(self.section_rule(cx)) - .child(self.section_header(t(L10nKey::SettingsScrolling), cx)) - .child(self.settings_row( - t(L10nKey::SettingsScrollback), - t(L10nKey::SettingsScrollbackDesc), - scrollback_radio, - cx, - )) - .child(self.settings_row( - t(L10nKey::SettingsScrollSpeed), - t(L10nKey::SettingsScrollSpeedDesc), - scroll_control, - cx, - )) - .child(self.settings_row( - t(L10nKey::SettingsSmoothScroll), - t(L10nKey::SettingsSmoothScrollDesc), - smooth_scroll_switch, - cx, - )) - .child(self.section_rule(cx)) - .child(self.section_header(t(L10nKey::SettingsBell), cx)) - .child(self.settings_row( - t(L10nKey::SettingsTerminalBell), - t(L10nKey::SettingsTerminalBellDesc), - bell_control, - cx, - )) - .child(self.section_rule(cx)) - .child(self.section_header(t(L10nKey::SettingsLinks), cx)) - .child(self.settings_row( - t(L10nKey::DetectUrls), - t_fmt( - L10nKey::SettingsDetectUrlsDesc, - &[("modifier", LINK_MODIFIER_LABEL)], - ), - link_switch, - cx, - )) - .child(self.settings_row( - t(L10nKey::ForwardSshLoopbackLinks), - t(L10nKey::SettingsForwardSshLoopbackLinksDesc), - ssh_loopback_switch, - cx, - )) - .child(self.settings_row( - t(L10nKey::OpenFilesWith), - t_fmt( - L10nKey::SettingsOpenFilesModeDesc, - &[("modifier", LINK_MODIFIER_LABEL)], - ), - link_file_open_radio, - cx, - )) - .children(link_file_command_control.map(|control| { - self.settings_row( - t(L10nKey::SettingsOpenFilesCommand), - t_fmt( - L10nKey::SettingsOpenFilesWithDesc, - &[ - ("modifier", LINK_MODIFIER_LABEL), - ("path", "{path}"), - ("line", "{line}"), - ("column", "{column}"), - ], - ), - control, - cx, - ) - })) - .into_any_element() - } - - fn render_settings_input(&self, cx: &mut Context) -> AnyElement { - let cfg = cx.global::(); - let mouse_hide = cfg.mouse_hide_while_typing; - let focus_follows = cfg.focus_follows_mouse; - let mouse_reporting = cfg.mouse_reporting; - let mouse_zoom = cfg.mouse_zoom_modifier; - let focus_switch = crate::ui::theme::switch("term-focus-follows", cx) - .checked(focus_follows) - .on_click(cx.listener(|this, on: &bool, _w, cx| this.set_focus_follows_mouse(*on, cx))) - .into_any_element(); - let mouse_hide_switch = crate::ui::theme::switch("term-mouse-hide", cx) - .checked(mouse_hide) - .on_click( - cx.listener(|this, on: &bool, _w, cx| this.set_mouse_hide_while_typing(*on, cx)), - ) - .into_any_element(); - let mouse_report_switch = crate::ui::theme::switch("term-mouse-report", cx) - .checked(mouse_reporting) - .on_click(cx.listener(|this, on: &bool, _w, cx| this.set_mouse_reporting(*on, cx))) - .into_any_element(); - // Ctrl only earns a cell where it is a different key from the - // platform modifier: off macOS the two are the same key, and a - // segmented control with the same key twice is a bug the user has to - // decode. A config that names `ctrl` there still highlights it, in the - // one cell that means it. - let mac = cfg!(target_os = "macos"); - let zoom_labels: Vec<&str> = if mac { - vec!["⌘", "⌃", "⌥", t(L10nKey::SettingsMouseZoomOff)] - } else { - vec!["Ctrl", "Alt", t(L10nKey::SettingsMouseZoomOff)] - }; - let zoom_idx = match (mouse_zoom, mac) { - (MouseZoomModifier::Platform, _) => 0, - (MouseZoomModifier::Ctrl, true) => 1, - (MouseZoomModifier::Ctrl, false) => 0, - (MouseZoomModifier::Alt, true) => 2, - (MouseZoomModifier::Alt, false) => 1, - (MouseZoomModifier::None, true) => 3, - (MouseZoomModifier::None, false) => 2, - }; - let zoom_control = self.segmented( - "term-mouse-zoom", - &zoom_labels, - zoom_idx, - cx, - move |this, ix, _w, cx| { - let modifier = match (ix, mac) { - (0, _) => MouseZoomModifier::Platform, - (1, true) => MouseZoomModifier::Ctrl, - (1, false) => MouseZoomModifier::Alt, - (2, true) => MouseZoomModifier::Alt, - _ => MouseZoomModifier::None, - }; - this.set_mouse_zoom_modifier(modifier, cx); - }, - ); - v_flex() - .child( - self.settings_row( - t(L10nKey::SettingsSearchKeybindingsTitle), - t(L10nKey::SettingsKeybindingsIntroDesc), - Button::new("open-keybindings") - .label(t(L10nKey::SettingsEditShortcuts)) - .small() - .on_click(cx.listener(|this, _, window, cx| { - this.navigate_settings(SettingsSection::Keybindings, None, window, cx) - })) - .into_any_element(), - cx, - ), - ) - .child(self.render_input_groups(false, cx)) - .child(self.section_rule(cx)) - .child(self.section_header(t(L10nKey::SettingsMouse), cx)) - .child(self.settings_row( - t(L10nKey::SettingsFocusFollowsMouse), - t(L10nKey::SettingsFocusFollowsMouseDesc), - focus_switch, - cx, - )) - .child(self.settings_row( - t(L10nKey::SettingsHideMouseWhileTyping), - t(L10nKey::SettingsHideMouseWhileTypingDesc), - mouse_hide_switch, - cx, - )) - .child(self.settings_row( - t(L10nKey::SettingsReportMouseToApps), - t(L10nKey::SettingsReportMouseToAppsDesc), - mouse_report_switch, - cx, - )) - .child(self.settings_row( - t(L10nKey::SettingsMouseZoom), - t(L10nKey::SettingsMouseZoomDesc), - zoom_control, - cx, - )) - .into_any_element() - } - - fn render_input_groups(&self, prompt: bool, cx: &mut Context) -> AnyElement { - let cfg = cx.global::(); - let option_as_alt = cfg.macos_option_as_alt; - let prompt_editor = cfg.prompt_editor; - let tab_completion = cfg.tab_completion; - let history_search = cfg.history_search; - let per_pane_history = cfg.per_pane_history; - let smart_select = cfg.smart_select; - let copy_on_select = cfg.copy_on_select; - let clip_trim = cfg.clipboard_trim_trailing_spaces; - - // Tab completion and history search are menus tty7 opens *inside* its - // own prompt editor. With the editor off, both keys already belong to - // the shell, so the switches have nothing left to switch: grey them - // out and say why, rather than leave two controls that quietly do - // nothing. Their stored values are untouched and come back with it. - let gated = |desc: L10nKey| match prompt_editor { - true => t(desc).to_string(), - false => format!("{} {}", t(desc), t(L10nKey::SettingsNeedsPromptEditor)), - }; - - let prompt_editor_switch = crate::ui::theme::switch("term-prompt-editor", cx) - .checked(prompt_editor) - .on_click(cx.listener(|this, on: &bool, _w, cx| this.set_prompt_editor(*on, cx))) - .into_any_element(); - let tab_completion_switch = crate::ui::theme::switch("term-tab-completion", cx) - .checked(tab_completion) - .disabled(!prompt_editor) - .on_click(cx.listener(|this, on: &bool, _w, cx| this.set_tab_completion(*on, cx))) - .into_any_element(); - let history_search_switch = crate::ui::theme::switch("term-history-search", cx) - .checked(history_search) - .disabled(!prompt_editor) - .on_click(cx.listener(|this, on: &bool, _w, cx| this.set_history_search(*on, cx))) - .into_any_element(); - let per_pane_history_switch = crate::ui::theme::switch("term-per-pane-history", cx) - .checked(per_pane_history) - .on_click(cx.listener(|this, on: &bool, _w, cx| this.set_per_pane_history(*on, cx))) - .into_any_element(); - let smart_select_switch = crate::ui::theme::switch("term-smart-select", cx) - .checked(smart_select) - .on_click(cx.listener(|this, on: &bool, _w, cx| this.set_smart_select(*on, cx))) - .into_any_element(); - let copy_on_select_switch = crate::ui::theme::switch("term-copy-on-select", cx) - .checked(copy_on_select) - .on_click(cx.listener(|this, on: &bool, _w, cx| this.set_copy_on_select(*on, cx))) - .into_any_element(); - let trim_switch = crate::ui::theme::switch("term-clip-trim", cx) - .checked(clip_trim) - .on_click(cx.listener(|this, on: &bool, _w, cx| this.set_clipboard_trim(*on, cx))) - .into_any_element(); - let option_alt_row = cfg!(target_os = "macos").then(|| { - let switch = crate::ui::theme::switch("term-option-as-alt", cx) - .checked(option_as_alt) - .on_click( - cx.listener(|this, on: &bool, _w, cx| this.set_macos_option_as_alt(*on, cx)), - ) - .into_any_element(); - self.settings_row( - t(L10nKey::SettingsOptionAsMeta), - t(L10nKey::SettingsOptionAsMetaDesc), - switch, - cx, - ) - }); - - v_flex() - .when(prompt, |v| { - v.child(self.section_intro( - t(L10nKey::SettingsPrompt), - t(L10nKey::SettingsPromptIntro), - cx, - )) - .child(self.settings_row( - t(L10nKey::SettingsPromptEditor), - t(L10nKey::SettingsPromptEditorDesc), - prompt_editor_switch, - cx, - )) - .child(self.settings_row_gated_when( - t(L10nKey::SettingsTabCompletion), - gated(L10nKey::SettingsTabCompletionDesc), - tab_completion_switch, - !prompt_editor, - cx, - )) - .child(self.settings_row_gated_when( - t(L10nKey::SettingsHistorySearch), - gated(L10nKey::SettingsHistorySearchDesc), - history_search_switch, - !prompt_editor, - cx, - )) - .child(self.settings_row( - t(L10nKey::SettingsPerPaneHistory), - t(L10nKey::SettingsPerPaneHistoryDescription), - per_pane_history_switch, - cx, - )) - }) - .when(!prompt, |v| { - v.child(self.section_rule(cx)) - .child(self.section_header(t(L10nKey::SettingsSelectionClipboard), cx)) - .child(self.settings_row( - t(L10nKey::SettingsSmartSelection), - t(L10nKey::SettingsSmartSelectionDesc), - smart_select_switch, - cx, - )) - .child(self.settings_row( - t(L10nKey::SettingsCopyOnSelect), - t(L10nKey::SettingsCopyOnSelectDesc), - copy_on_select_switch, - cx, - )) - .child(self.settings_row( - t(L10nKey::SettingsTrimTrailingSpaces), - t(L10nKey::SettingsTrimTrailingSpacesDesc), - trim_switch, - cx, - )) - .when_some(option_alt_row, |v, row| { - v.child(self.section_rule(cx)) - .child(self.section_header(t(L10nKey::SettingsKeyboard), cx)) - .child(row) - }) - }) - .into_any_element() - } - - fn render_settings_agents(&self, cx: &mut Context) -> AnyElement { - use crate::core::agent_hooks::HooksState; - - let theme = cx.theme(); - let (foreground, muted_fg) = (theme.foreground, theme.muted_foreground); - let (success, warning) = (theme.success, theme.warning); - let (view, note, selected_host) = match self.active_settings() { - Some(s) => ( - s.agent_hooks_states.clone(), - s.agent_hooks_note.clone(), - s.agent_hooks_host, - ), - None => (AgentHooksView::Loading, None, HostId::LOCAL), - }; - let stacked = self.settings_row_under(STACK_ROW_BELOW, cx); - let mut page = v_flex().child(self.section_intro( - t(L10nKey::SettingsAgentsIntro), - t(L10nKey::SettingsAgentsIntroDesc), - cx, - )); - - page = page.children(self.agent_hooks_machine_picker(selected_host, cx)); - - // The hook rows describe whichever machine is selected above; the - // command-line section below is always about this GUI's own host, so it - // is appended after the match rather than inside the ready arm. - match view { - AgentHooksView::Loading => { - page = page.child( - div() - .py_4() - .text_sm() - .text_color(muted_fg) - .child(t(L10nKey::SettingsReadingAgentConfig)), - ); - } - AgentHooksView::Unavailable(reason) => { - page = page.child(div().py_4().text_sm().text_color(warning).child(reason)); - } - AgentHooksView::Ready(rows) => { - for (i, row) in rows.into_iter().enumerate() { - let agent = row.agent; - let (dot_color, status_text) = match row.state { - HooksState::NotInstalled => { - (muted_fg, t(L10nKey::SettingsStatusNotInstalled)) - } - HooksState::Installed => (success, t(L10nKey::SettingsStatusInstalled)), - HooksState::Outdated => (warning, t(L10nKey::SettingsStatusOutdated)), - }; - let primary_label = match row.state { - HooksState::NotInstalled => t(L10nKey::SettingsInstall), - HooksState::Installed => t(L10nKey::SettingsReinstall), - HooksState::Outdated => t(L10nKey::SettingsUpdate), - }; - let row_note = note - .as_ref() - .filter(|(for_agent, _)| *for_agent == agent) - .map(|(_, text)| text.clone()); - - // Right-aligned beside its label, left-aligned under it — - // `settings_row` gives the control column the whole row - // once it stacks, and buttons flush to the far edge of a - // row whose label starts at the near one read as unrelated. - let control = v_flex() - .gap_2() - .when(!stacked, |c| c.items_end()) - .child( - h_flex() - .gap_2() - .items_center() - .child(div().size_2().rounded_full().bg(dot_color)) - .child(div().text_sm().text_color(foreground).child(status_text)), - ) - .child( - h_flex() - .gap_2() - .child( - Button::new(("agent-hooks-install", i)) - .label(primary_label) - .small() - .on_click(cx.listener(move |this, _, _w, cx| { - this.settings_install_agent_hooks(agent, cx) - })), - ) - .when(row.state != HooksState::NotInstalled, |r| { - r.child( - Button::new(("agent-hooks-uninstall", i)) - .label(t(L10nKey::SettingsUninstall)) - .small() - .on_click(cx.listener(move |this, _, _w, cx| { - this.settings_uninstall_agent_hooks(agent, cx) - })), - ) - }), - ) - .when_some(row_note, |col, text| { - col.child( - div() - // One cap, not two: `max_w` holds a single - // length, so stating both left the note - // sized against a shrink-proof column that - // is itself sized to the note — no cap at - // all, and a long error (Codex's missing - // `codex` binary) inflated the row until - // the label column, `min_w_0`, came out one - // character per line. Stacked, the control - // column *is* the row, so a relative cap - // resolves; beside the label it cannot, and - // 320 is what the row has room for. - .when(stacked, |note| note.max_w_full()) - .when(!stacked, |note| note.max_w_80()) - .text_xs() - .when(!stacked, |note| note.text_right()) - .text_color(muted_fg) - .child(text), - ) - }) - .into_any_element(); - - page = page.child(self.settings_row( - agent.display_name(), - row.target, - control, - cx, - )); - } - } - } - - let install_cli_on_path = cx.global::().install_cli_on_path; - let cli_switch = crate::ui::theme::switch("install-cli-on-path", cx) - .checked(install_cli_on_path) - .on_click(cx.listener(|this, on: &bool, _w, cx| this.set_install_cli_on_path(*on, cx))); - // Built from the same pieces as every other setting in the app: a - // section header, then a row whose label and description sit left of - // its control. Hand-rolled, this was the one switch that stood to the - // left of its own label — and the one row the settings search could - // neither highlight nor dim, so a query that counted it in the nav - // badge left nothing on the page looking like the match. - page.child(self.section_rule(cx)) - .child(self.section_header(t(L10nKey::SettingsCommandLine), cx)) - .child(self.settings_row( - t(L10nKey::SettingsInstallCliOnPath), - t(L10nKey::SettingsCommandLineDesc), - cli_switch.into_any_element(), - cx, - )) - .into_any_element() - } - - fn agent_hooks_machine_picker(&self, selected: HostId, cx: &mut Context) -> Option
{ - let sf = cx.global::().window; - let border = cx.theme().border; - let muted_fg = cx.theme().muted_foreground; - let machines = self.agent_hooks_machines(cx); - let offline = self.agent_hooks_offline_count(cx); - if machines.len() < 2 && offline == 0 { - return None; - } - - Some( - v_flex() - .gap_2() - .mb_4() - .child( - h_flex() - .flex_wrap() - .gap_1p5() - .children(machines.into_iter().map(|machine| { - let active = machine.host == selected; - let host = machine.host; - h_flex() - .id(("agent-hooks-machine", host.0 as usize)) - .h(px(24.)) - .px_2p5() - .items_center() - .rounded_lg() - .border_1() - .border_color(border) - .bg(rgb(sf.base)) - .text_sm() - .cursor_pointer() - .when(active, |s| { - s.bg(rgb(sf.selected)) - .text_color(rgb(sf.text_selected)) - .font_weight(FontWeight::MEDIUM) - }) - .when(!active, |s| { - s.text_color(rgb(sf.text_resting)) - .hover(|h| h.bg(rgb(sf.hover))) - }) - .active(|s| s.bg(rgb(sf.pressed))) - .child(machine.label) - .on_click(cx.listener(move |this, _, _w, cx| { - this.select_agent_hooks_host(host, cx) - })) - })), - ) - .when(offline > 0, |col| { - col.child(div().text_xs().text_color(muted_fg).child(t_plural( - L10nKey::SettingsOfflineMachines, - offline, - &[], - ))) - }), - ) - } - - fn render_window_preferences(&self, general: bool, cx: &mut Context) -> AnyElement { - let cfg = cx.global::(); - let startup_idx = match cfg.startup_mode { - crate::core::config::StartupMode::Normal => 0, - crate::core::config::StartupMode::Maximized => 1, - crate::core::config::StartupMode::Fullscreen => 2, - }; - let new_tab_idx = match cfg.new_tab_position { - NewTabPosition::AfterCurrent => 0, - NewTabPosition::End => 1, - }; - let restore_session = cfg.restore_session; - let remember_window_size = cfg.remember_window_size; - let show_tray_icon = cfg.show_tray_icon; - let tab_bar_idx = match cfg.tab_bar_position { - TabBarPosition::Top => 0, - TabBarPosition::Left => 1, - }; - let sidebar_diff_preview = cfg.sidebar_diff_preview; - let sidebar_grouping_idx = match cfg.sidebar_grouping { - crate::core::config::SidebarGrouping::Repo => 0, - crate::core::config::SidebarGrouping::RepoOrDirectory => 1, - crate::core::config::SidebarGrouping::None => 2, - }; - let notify_idx = match cfg.notify_on_command_finish { - NotifyMode::Never => 0, - NotifyMode::Unfocused => 1, - NotifyMode::Always => 2, - }; - // Exact-match highlight with a "Custom (Ns)" fallback, same as the - // scrollback row: a hand-set 20s used to light up "30s" (#550). - let (threshold_sel, threshold_custom) = preset_choice( - &NOTIFY_THRESHOLD_BUCKETS, - cfg.notify_threshold_secs, - |secs| format!("{secs}s"), - ); - let notify_radio = self.segmented( - "wt-notify", - &[ - t(L10nKey::NotifyModeNever), - t(L10nKey::NotifyModeUnfocused), - t(L10nKey::NotifyModeAlways), - ], - notify_idx, - cx, - |this, ix, _w, cx| { - let mode = match ix { - 0 => NotifyMode::Never, - 1 => NotifyMode::Unfocused, - _ => NotifyMode::Always, - }; - this.set_notify_mode(mode, cx); - }, - ); - let threshold_radio = self.segmented_valued( - "wt-notify-threshold", - &NOTIFY_THRESHOLD_LABELS, - threshold_sel, - threshold_custom, - cx, - |this, ix, _w, cx| { - let secs = NOTIFY_THRESHOLD_BUCKETS - .get(ix) - .copied() - .unwrap_or(Config::default().notify_threshold_secs); - this.set_notify_threshold(secs, cx); - }, - ); - - let restore_switch = crate::ui::theme::switch("wt-restore-session", cx) - .checked(restore_session) - .on_click(cx.listener(|this, on: &bool, _w, cx| this.set_restore_session(*on, cx))) - .into_any_element(); - let remember_window_switch = crate::ui::theme::switch("wt-remember-window", cx) - .checked(remember_window_size) - .on_click(cx.listener(|this, on: &bool, _w, cx| this.set_remember_window_size(*on, cx))) - .into_any_element(); - let tray_switch = crate::ui::theme::switch("wt-tray-icon", cx) - .checked(show_tray_icon) - .on_click(cx.listener(|this, on: &bool, _w, cx| this.set_show_tray_icon(*on, cx))) - .into_any_element(); - let startup_radio = self.segmented( - "wt-startup", - &[ - t(L10nKey::SettingsStartupNormal), - t(L10nKey::SettingsStartupMaximized), - t(L10nKey::SettingsStartupFullscreen), - ], - startup_idx, - cx, - |this, ix, _w, cx| { - let mode = match ix { - 0 => crate::core::config::StartupMode::Normal, - 1 => crate::core::config::StartupMode::Maximized, - _ => crate::core::config::StartupMode::Fullscreen, - }; - this.set_startup_mode(mode, cx); - }, - ); - let new_tab_radio = self.segmented( - "wt-new-tab-pos", - &[t(L10nKey::SettingsAfterCurrent), t(L10nKey::SettingsAtEnd)], - new_tab_idx, - cx, - |this, ix, _w, cx| { - let pos = if ix == 0 { - NewTabPosition::AfterCurrent - } else { - NewTabPosition::End - }; - this.set_new_tab_position(pos, cx); - }, - ); - let tab_bar_radio = self.segmented( - "wt-tab-bar-pos", - &[t(L10nKey::SettingsTop), t(L10nKey::SettingsLeft)], - tab_bar_idx, - cx, - |this, ix, _w, cx| { - let pos = if ix == 0 { - TabBarPosition::Top - } else { - TabBarPosition::Left - }; - this.set_tab_bar_position(pos, cx); - }, - ); - let sidebar_diff_switch = crate::ui::theme::switch("wt-sidebar-diff-preview", cx) - .checked(sidebar_diff_preview) - .on_click(cx.listener(|this, on: &bool, _w, cx| this.set_sidebar_diff_preview(*on, cx))) - .into_any_element(); - let sidebar_grouping_radio = self.segmented( - "wt-sidebar-grouping", - &[ - t(L10nKey::SettingsByRepo), - t(L10nKey::SettingsByRepoOrFolder), - t(L10nKey::SettingsFlat), - ], - sidebar_grouping_idx, - cx, - |this, ix, _w, cx| { - let grouping = match ix { - 0 => crate::core::config::SidebarGrouping::Repo, - 1 => crate::core::config::SidebarGrouping::RepoOrDirectory, - _ => crate::core::config::SidebarGrouping::None, - }; - this.set_sidebar_grouping(grouping, cx); - }, - ); - - v_flex() - .when(general, |v| { - v.child(self.section_header(t(L10nKey::SettingsWindow), cx)) - .child(self.settings_row( - t(L10nKey::SettingsStartupWindow), - t(L10nKey::SettingsStartupWindowDesc), - startup_radio, - cx, - )) - .child(self.settings_row( - t(L10nKey::SettingsRememberWindowSize), - t(L10nKey::SettingsRememberWindowSizeDesc), - remember_window_switch, - cx, - )) - .child(self.settings_row( - t(L10nKey::SettingsRestoreLastLayout), - t(L10nKey::SettingsRestoreLastLayoutDesc), - restore_switch, - cx, - )) - .child(self.settings_row( - t(L10nKey::SettingsShowTrayIcon), - t(L10nKey::SettingsShowTrayIconDesc), - tray_switch, - cx, - )) - }) - .when(!general, |v| { - v.child(self.section_rule(cx)) - .child(self.section_header(t(L10nKey::SettingsTabs), cx)) - .child(self.settings_row( - t(L10nKey::SettingsNewTabPosition), - t(L10nKey::SettingsNewTabPositionDesc), - new_tab_radio, - cx, - )) - .child(self.settings_row( - t(L10nKey::SettingsTabBarPosition), - t(L10nKey::SettingsTabBarPositionDesc), - tab_bar_radio, - cx, - )) - .child(self.settings_row( - t(L10nKey::SettingsSidebarGrouping), - t(L10nKey::SettingsSidebarGroupingDesc), - sidebar_grouping_radio, - cx, - )) - .child(self.settings_row( - t(L10nKey::SettingsDiffPreviewFromCounts), - t(L10nKey::SettingsDiffPreviewFromCountsDesc), - sidebar_diff_switch, - cx, - )) - }) - .when(general, |v| { - v.child(self.section_rule(cx)) - .child(self.section_header(t(L10nKey::SettingsNotifications), cx)) - .child(self.settings_row( - t(L10nKey::SettingsNotifyOnCommandFinish), - t(L10nKey::SettingsNotifyOnCommandFinishDesc), - notify_radio, - cx, - )) - .child(self.settings_row( - t(L10nKey::SettingsNotifyThreshold), - t(L10nKey::SettingsNotifyThresholdDesc), - threshold_radio, - cx, - )) - }) - .into_any_element() - } - - fn theme_preview(&self, p: &presets::Theme) -> Div { - let to_u32 = |(r, g, b): (u8, u8, u8)| (r as u32) << 16 | (g as u32) << 8 | b as u32; - let accent = rgb(p.accent); - let ansi = |i: usize| rgb(to_u32(p.ansi16[i])); - let fg = rgb(p.foreground); - let bar = |frac: f32, color: gpui::Rgba| { - div().h(px(4.)).w(relative(frac)).rounded(px(1.5)).bg(color) - }; - - v_flex() - .w_full() - .bg(rgb(p.background_color())) - .rounded(rounding::TRACK_RADIUS) - .overflow_hidden() - .px_3() - .py_3() - .gap(px(10.)) - .child( - h_flex() - .items_center() - .gap_2() - .child(div().text_size(px(11.)).text_color(accent).child("❯")) - .child(bar(0.5, fg)), - ) - .child( - h_flex() - .gap_2() - .child(bar(0.2, ansi(2))) - .child(bar(0.36, ansi(4))) - .child(bar(0.12, ansi(3))), - ) - .child( - h_flex() - .gap_2() - .child(bar(0.14, ansi(1))) - .child(bar(0.44, fg)), - ) - .child( - h_flex() - .gap_2() - .child(bar(0.1, ansi(6))) - .child(bar(0.32, accent)), - ) - } - - fn render_theme_selection(&self, cx: &mut Context) -> AnyElement { - let follow = cx.global::().theme_follow_system; - let follow_switch = crate::ui::theme::switch("theme-follow-system", cx) - .checked(follow) - .on_click(cx.listener(|this, on: &bool, window, cx| { - this.set_theme_follow_system(*on, window, cx) - })) - .into_any_element(); - let legible = cx.global::().theme_legible_palette; - let legible_switch = crate::ui::theme::switch("theme-legible-palette", cx) - .checked(legible) - .on_click(cx.listener(|this, on: &bool, window, cx| { - this.set_theme_legible_palette(*on, window, cx) - })) - .into_any_element(); - let root = v_flex() - .child(self.settings_row( - t(L10nKey::SettingsSyncWithSystem), - t(L10nKey::SettingsSyncWithSystemDesc), - follow_switch, - cx, - )) - .child(self.settings_row( - t(L10nKey::SettingsLegiblePalette), - t(L10nKey::SettingsLegiblePaletteDesc), - legible_switch, - cx, - )); - if follow { - root.child(self.render_theme_card(ThemeSlot::Light, cx)) - .child(self.render_theme_card(ThemeSlot::Dark, cx)) - .into_any_element() - } else { - root.child(self.render_theme_card(ThemeSlot::Manual, cx)) - .into_any_element() - } - } - - fn render_theme_card(&self, slot: ThemeSlot, cx: &mut Context) -> AnyElement { - let theme = cx.theme(); - let border = theme.border; - let foreground = theme.foreground; - let muted_fg = theme.muted_foreground; - let hover_bg = gpui::rgb(cx.global::().window.hover); - let surface = theme.secondary.opacity(0.28); - - let config = cx.global::(); - let (card_id, active_id) = match slot { - ThemeSlot::Manual => ("theme-card-manual", config.theme_preset.clone()), - ThemeSlot::Light => ("theme-card-light", config.theme_preset_light.clone()), - ThemeSlot::Dark => ("theme-card-dark", config.theme_preset_dark.clone()), - }; - let active = presets::by_id(cx, &active_id); - let name = active.name.clone(); - let kind = if active.path.is_some() { - t(L10nKey::SettingsCustom) - } else { - t(L10nKey::SettingsBuiltIn) - }; - let mode = if active.dark { - t(L10nKey::SettingsDark) - } else { - t(L10nKey::SettingsLight) - }; - let mode_label = if active.dark { - t(L10nKey::SettingsDarkMode) - } else { - t(L10nKey::SettingsLightMode) - }; - let caption = match slot { - ThemeSlot::Manual => format!("{kind} · {mode}"), - ThemeSlot::Light if !crate::ui::theme::system_dark(cx) => { - format!("{mode_label} · {kind} · {}", t(L10nKey::SettingsActive)) - } - ThemeSlot::Light => format!("{mode_label} · {kind}"), - ThemeSlot::Dark if crate::ui::theme::system_dark(cx) => { - format!("{mode_label} · {kind} · {}", t(L10nKey::SettingsActive)) - } - ThemeSlot::Dark => format!("{mode_label} · {kind}"), - }; - let to_u32 = |(r, g, b): (u8, u8, u8)| (r as u32) << 16 | (g as u32) << 8 | b as u32; - let swatches = h_flex().gap_1().mt_1p5().children((1..=6).map(|i| { - div() - .w(px(10.)) - .h(px(10.)) - .rounded(px(3.)) - .bg(rgb(to_u32(active.ansi16[i]))) - })); - // Inset inside the card's border, the way the same preview is inset - // inside the same card in the theme panel. - let preview = self.theme_preview(&active).rounded(rounding::inner_radius( - rounding::TRACK_RADIUS, - rounding::HAIRLINE, - )); - let open = self - .active_settings() - .is_some_and(|s| s.theme_panel_open && s.theme_panel_slot == slot); - // The same width a row stacks at: the card is a row too, just one whose - // control happens to be a whole preview. - let narrow = self.settings_row_under(STACK_ROW_BELOW, cx); - - div() - .id(card_id) - .mt_1() - .mb_2() - .w_full() - .cursor_pointer() - .on_click( - cx.listener(move |this, _, window, cx| this.toggle_theme_panel(slot, window, cx)), - ) - .child( - h_flex() - .w_full() - .items_center() - .gap_4() - .p_3() - .rounded(rounding::TRACK_RADIUS) - .border_1() - .border_color(if open { - foreground.opacity(0.35) - } else { - border - }) - .bg(surface) - .hover(|h| h.bg(hover_bg)) - // The preview is the first thing to go: it is a picture of a - // choice the two lines beside it already name, and at the - // width where it stops fitting it was pushing the "change - // theme" affordance off the card. - .when(!narrow, |card| { - card.child(div().w(px(150.)).flex_shrink_0().child(preview)) - }) - .child( - v_flex() - .flex_1() - .min_w_0() - .gap_0p5() - .child(div().text_xs().text_color(muted_fg).child(caption)) - .child( - div() - .text_sm() - .font_weight(FontWeight::SEMIBOLD) - .text_color(foreground) - .child(name), - ) - .child(swatches), - ) - .child( - h_flex() - .flex_shrink_0() - .items_center() - .gap_1() - .text_sm() - .text_color(muted_fg) - .child(t(L10nKey::SettingsChangeTheme)) - .child(Icon::new(IconName::ChevronRight).small()), - ), - ) - .into_any_element() - } - - fn render_theme_panel(&self, cx: &mut Context) -> AnyElement { - let theme = cx.theme(); - let border = theme.border; - let foreground = theme.foreground; - let muted_fg = theme.muted_foreground; - let bg = theme.sidebar; - - let (search, query, slot) = match self.active_settings() { - Some(s) => ( - s.theme_search.clone(), - s.theme_search.read(cx).value().trim().to_lowercase(), - s.theme_panel_slot, - ), - None => return div().into_any_element(), - }; - let list_scroll = self.active_settings().map(|s| s.theme_list_scroll.clone()); - let config = cx.global::(); - let slot = match (config.theme_follow_system, slot) { - (false, _) => ThemeSlot::Manual, - (true, ThemeSlot::Manual) => { - if crate::ui::theme::system_dark(cx) { - ThemeSlot::Dark - } else { - ThemeSlot::Light - } - } - (true, s) => s, - }; - let active_id = match slot { - ThemeSlot::Manual => config.theme_preset.clone(), - ThemeSlot::Light => config.theme_preset_light.clone(), - ThemeSlot::Dark => config.theme_preset_dark.clone(), - }; - - let header = h_flex() - .items_center() - .justify_between() - .px_4() - .pt_4() - .pb_1() - .child( - div() - .text_base() - .font_weight(FontWeight::SEMIBOLD) - .text_color(foreground) - .child(t(L10nKey::SettingsThemes)), - ) - .child( - div().occlude().child( - Button::new("theme-panel-close") - .icon(IconName::Close) - .ghost() - .small() - .tooltip(t(L10nKey::SettingsThemesCloseTooltip)) - .on_click( - cx.listener(|this, _, window, cx| this.close_theme_panel(window, cx)), - ), - ), - ); - - let subtitle = div() - .px_4() - .pb_3() - .text_xs() - .text_color(muted_fg) - .child(match slot { - ThemeSlot::Manual => t(L10nKey::SettingsThemePanelManual), - ThemeSlot::Light => t(L10nKey::SettingsThemePanelLight), - ThemeSlot::Dark => t(L10nKey::SettingsThemePanelDark), - }); - - let search_box = div().px_4().pb_3().child( - div().w_full().child( - Input::new(&search).small().prefix( - Icon::empty() - .path("stock/icons/search.svg") - .small() - .text_color(muted_fg), - ), - ), - ); - - // A theme file that fails to parse used to log a warning and then just - // not be in the list. This is a folder the user opens and drops files - // into; "it isn't there" needs a reason attached to it. - let rejected = presets::rejected(cx); - let rejected_note = (!rejected.is_empty() && query.is_empty()).then(|| { - let mut note = v_flex() - .mx_4() - .mb_4() - .p_3() - .gap_1p5() - .rounded(rounding::TRACK_RADIUS) - .border_1() - .border_color(theme.danger.opacity(0.4)) - .child( - div() - .text_xs() - .font_weight(FontWeight::MEDIUM) - .text_color(foreground) - .child(t(L10nKey::SettingsThemesRejected)), - ); - for (name, why) in &rejected { - note = note.child( - v_flex() - .gap_0p5() - .child(div().text_xs().text_color(theme.danger).child(name.clone())) - .child(div().text_xs().text_color(muted_fg).child(why.clone())), - ); - } - note - }); - - let mut list = v_flex().px_4().pb_4().gap_4(); - // Filtering every preset out left the panel blank under its own search - // box — the one filter in the app that said nothing about it. - let mut any_themes = false; - for p in presets::all(cx) { - if !query.is_empty() && !p.name.to_lowercase().contains(&query) { - continue; - } - any_themes = true; - let id = p.id.clone(); - let is_active = active_id == id; - let preview = self.theme_preview(&p).rounded(rounding::inner_radius( - rounding::TRACK_RADIUS, - rounding::HAIRLINE, - )); - let click_id = id.clone(); - list = list.child( - v_flex() - .id(SharedString::from(format!("panel-theme-{id}"))) - .gap_1p5() - .cursor_pointer() - .child( - div() - .w_full() - .rounded(rounding::TRACK_RADIUS) - .overflow_hidden() - .border_1() - .border_color(if is_active { - foreground.opacity(0.5) - } else { - border - }) - .when(is_active, |s| s.shadow_md()) - .when(!is_active, |s| { - s.hover(|h| h.border_color(foreground.opacity(0.25))) - }) - .child(preview), - ) - .child( - h_flex() - .items_center() - .gap_1p5() - .w_full() - .child( - div() - .truncate() - .text_sm() - .font_weight(if is_active { - FontWeight::SEMIBOLD - } else { - FontWeight::MEDIUM - }) - .text_color(if is_active { foreground } else { muted_fg }) - .child(p.name.clone()), - ) - .when(is_active, |s| { - s.child( - Icon::new(IconName::Check) - .small() - .flex_shrink_0() - .text_color(foreground), - ) - }), - ) - .on_click(cx.listener(move |this, _, window, cx| match slot { - ThemeSlot::Manual => this.set_preset(&click_id, window, cx), - ThemeSlot::Light => this.set_slot_preset(false, &click_id, window, cx), - ThemeSlot::Dark => this.set_slot_preset(true, &click_id, window, cx), - })), - ); - } - - if !any_themes { - list = list.child(div().py_2().text_sm().text_color(muted_fg).child(t_fmt( - L10nKey::SettingsNothingMatches, - &[("query", query.as_str())], - ))); - } - - v_flex() - .w(px(self.settings_columns_now(cx).theme_panel)) - .h_full() - .flex_shrink_0() - .bg(bg) - .border_l_1() - .border_color(border) - .child(header) - .child(subtitle) - .child(search_box) - .when_some(list_scroll, |panel, scroll| { - panel.child(crate::ui::scrollbar::with_vertical_scrollbar( - "theme-panel-scrollbar", - v_flex() - .id("theme-panel-list") - .size_full() - .overflow_y_scroll() - .track_scroll(&scroll) - .children(rejected_note) - .child(list), - &scroll, - )) - }) - .into_any_element() - } - - fn render_settings_keybindings(&self, cx: &mut Context) -> AnyElement { - let section = SettingsSection::Keybindings; - let query = self - .active_settings() - .map(|s| s.shortcut_search.read(cx).value().trim().to_lowercase()) - .unwrap_or_default(); - let (foreground, muted, border, kbd_bg, accent) = { - let t = cx.theme(); - ( - t.foreground, - t.muted_foreground, - t.border, - t.secondary.opacity(0.6), - t.primary, - ) - }; - - let (preset, prefix, overridden) = { - let cfg = cx.global::(); - let overridden: std::collections::HashSet = - cfg.keybindings.keys().cloned().collect(); - ( - cfg.keybinding_preset.clone(), - cfg.prefix.clone(), - overridden, - ) - }; - let tmux = preset == "tmux"; - let effective = crate::ui::keymap::effective_chords(cx); - - let recording = self - .active_settings() - .and_then(|s| s.recording.as_ref()) - .map(|r| (r.action.clone(), r.chords.clone())); - let record_gen = self.record_gen; - let note = self - .active_settings() - .and_then(|s| s.rebinding_note.clone()); - - let keycap = move |tok: String| { - div() - .flex() - .items_center() - .justify_center() - .min_w(px(22.)) - .h(px(22.)) - .px_1p5() - .rounded_md() - .bg(kbd_bg) - .border_1() - .border_color(border) - .text_xs() - .text_color(foreground) - .child(tok) - }; - - let preset_control = self.segmented( - "kb-preset", - &[t(L10nKey::SettingsDefault), "tmux"], - usize::from(tmux), - cx, - |this, ix, _w, cx| { - this.set_keybinding_preset(if ix == 0 { "default" } else { "tmux" }, cx) - }, - ); - let prefix_control = self.segmented( - "kb-prefix", - &["Ctrl-B", "Ctrl-A"], - usize::from(prefix == "ctrl-a"), - cx, - |this, ix, _w, cx| { - this.set_keybinding_prefix(if ix == 0 { "ctrl-b" } else { "ctrl-a" }, cx) - }, - ); - - // The label column has to be allowed to shrink, or its description sets - // the row's width and the control it belongs to is pushed off the page. - // `settings_row` does this for every other row in Settings; these two - // are hand-rolled and were missing it. They take its breakpoint too: - // the segmented controls beside them are the widest on the page. - let stacked = self.settings_row_under(STACK_ROW_BELOW, cx); - let hand_rolled_row = |row: Div| { - row.w_full() - .flex() - .when(stacked, |r| r.flex_col().items_start().gap_2()) - .when(!stacked, |r| { - r.flex_row().items_center().justify_between().gap_8() - }) - }; - let preset_row = hand_rolled_row(div().py_2()) - .child( - v_flex() - .min_w_0() - .gap_0p5() - .child( - div() - .text_sm() - .font_weight(FontWeight::MEDIUM) - .text_color(foreground) - .child(t(L10nKey::SettingsPreset)), - ) - .child( - div() - .text_xs() - .text_color(muted) - .child(t(L10nKey::SettingsPresetDesc)), - ), - ) - .child(h_flex().flex_shrink_0().child(preset_control)); - - let prefix_row = hand_rolled_row(div().py_2()) - .child( - div() - .min_w_0() - .text_sm() - .font_weight(FontWeight::MEDIUM) - .text_color(foreground) - .child(t(L10nKey::SettingsPrefix)), - ) - .child(h_flex().flex_shrink_0().child(prefix_control)); - - // Eighty-nine undivided rows, in the order the binding table happens to - // be written. Read them in the same seven sections the command palette - // uses, so a shortcut is found by where it belongs rather than by - // scrolling. - // - // With a query that this page answers, the page *is* the answer: the - // rows that match, and nothing else. Every other page greys its misses - // instead, which works when a page is a dozen rows and does not when it - // is eighty-nine — the reader would still be scrolling for the grey to - // stop. Filtering also takes the preset control and the destructive - // "restore all" button out of a view that is a search result and not a - // page anyone is configuring. - let filtering = !query.is_empty() && section_match_count(section, &query) > 0; - let mut grouped: Vec<( - crate::ui::palette::CommandGroup, - Vec<(String, Vec, String)>, - )> = Vec::new(); - for (action, key) in effective { - if filtering && !keybinding_matches_query(&action, &query) { - continue; - } - let (group, label) = crate::ui::keymap::action_entry(&action); - let slot = match grouped.iter_mut().find(|(g, _)| *g == group) { - Some(slot) => slot, - None => { - grouped.push((group, Vec::new())); - grouped.last_mut().expect("just pushed") - } - }; - slot.1.push((action, key, label)); - } - grouped.sort_by_key(|(g, _)| { - crate::ui::palette::CommandGroup::ORDER - .iter() - .position(|o| o == g) - .unwrap_or(usize::MAX) - }); - let rows: Vec<(String, Vec, String)> = grouped - .iter() - .flat_map(|(_, rows)| rows.iter().cloned()) - .collect(); - let heading_at: std::collections::HashMap = { - let mut map = std::collections::HashMap::new(); - let mut at = 0usize; - for (group, rows) in &grouped { - map.insert(at, group.title()); - at += rows.len(); - } - map - }; - let count = rows.len(); - let mut list = v_flex().mt_2(); - for (i, (action, key, label)) in rows.into_iter().enumerate() { - let is_recording = recording.as_ref().is_some_and(|(a, _)| a == &action); - let is_overridden = overridden.contains(&action); - - // Wrapping, because a four-chord binding is wider than the column a - // narrow window leaves for it, and the alternative to a second line - // is a first one that runs off the page. - let keycaps = |spec: &str| { - h_flex().flex_wrap().gap_2().children( - crate::ui::keymap::key_chords(spec) - .into_iter() - .map(|chord| h_flex().gap_1().children(chord.into_iter().map(&keycap))), - ) - }; - - let captured: gpui::AnyElement = if is_recording { - let chords = recording - .as_ref() - .map(|(_, c)| c.clone()) - .unwrap_or_default(); - let row = h_flex().gap_2().items_center(); - let row = if chords.is_empty() { - row.child( - div() - .text_xs() - .text_color(accent) - .child(t(L10nKey::SettingsPressKeys)), - ) - } else { - // The binding commits on a pause, and the pause was - // invisible: the hint asked people to time something they - // could not see. The bar runs the same clock the commit - // does, and restarts with every extra chord. - row.child(keycaps(&chords.join(" "))).child( - v_flex() - .gap(px(3.)) - .child( - div() - .text_xs() - .text_color(muted) - .child(t(L10nKey::SettingsPauseToSaveEsc)), - ) - .child( - div() - .h(px(2.)) - .w_full() - .overflow_hidden() - .rounded_full() - .bg(border) - .child( - div().h_full().rounded_full().bg(accent).with_animation( - ("kb-record-countdown", record_gen as usize), - Animation::new(std::time::Duration::from_millis( - crate::ui::app::RECORD_COMMIT_DELAY_MS, - )), - |bar, delta| bar.w(relative(delta)), - ), - ), - ), - ) - }; - row.into_any_element() - } else if key.is_empty() { - div() - .text_sm() - .text_color(muted) - .child("—") - .into_any_element() - } else { - // An action can answer to more than one chord — its default and - // one added beside it in config.json (#868) — and this is the - // one page that lists them, so a row shows every one. - h_flex() - .flex_wrap() - .items_center() - .gap_2() - .children(key.iter().enumerate().map(|(n, spec)| { - h_flex() - .items_center() - .gap_2() - .when(n > 0, |d| { - d.child(div().text_xs().text_color(muted).child("/")) - }) - .child(keycaps(spec)) - })) - .into_any_element() - }; - - let action_for_click = action.clone(); - let capture = div() - .id(SharedString::from(format!("kb-{action}"))) - .flex() - .items_center() - .gap_2() - .px_2() - .py_1() - .rounded_md() - .cursor_pointer() - .when(is_recording, |d| d.border_1().border_color(accent)) - .hover(|d| d.bg(kbd_bg)) - .child(captured) - .on_click(cx.listener(move |this, _, window, cx| { - this.start_recording_key(action_for_click.clone(), window, cx) - })); - - let action_for_reset = action.clone(); - let right = h_flex() - .items_center() - .gap_1() - .child(capture) - .when(is_overridden, |r| { - r.child( - Button::new(SharedString::from(format!("reset-{action}"))) - .label(t(L10nKey::Reset)) - .small() - .on_click(cx.listener(move |this, _, _w, cx| { - this.reset_keybinding(action_for_reset.clone(), cx) - })), - ) - }); - - if let Some(title) = heading_at.get(&i) { - list = list.child( - div() - .pt_5() - .pb_1p5() - .text_xs() - .font_weight(FontWeight::MEDIUM) - .text_color(muted) - .child(*title), - ); - } - let last_in_group = heading_at.contains_key(&(i + 1)) || i + 1 == count; - list = list.child( - hand_rolled_row(div().py_1p5()) - .when(!last_in_group, |s| s.border_b_1().border_color(border)) - // An action name is a line, never a paragraph: wrapped, it - // came out one or three CJK glyphs a line on Linux (#919), - // spilling over the rows below it while the keycaps beside - // it had room to spare. Beside the keycaps the name takes - // what they leave rather than sizing itself to its own - // measured text, so its box no longer depends on that - // measurement either; stacked, it has the whole row. - .child( - div() - .when(!stacked, |d| d.flex_1()) - .min_w_0() - .whitespace_nowrap() - .text_sm() - .text_color(foreground) - .child(label), - ) - .child(right.flex_shrink_0()), - ); - } - - v_flex() - .when_some(self.active_settings(), |v, s| { - v.child(Input::new(&s.shortcut_search).small()) - .child(self.section_rule(cx)) - }) - .child(self.section_intro( - t(L10nKey::SettingsNavKeybindings), - t(L10nKey::SettingsKeybindingsIntroDesc), - cx, - )) - .when(!filtering, |v| { - v.child(preset_row) - .when(tmux, |v| v.child(prefix_row)) - .when(tmux, |v| { - v.child( - div() - .py_1() - .text_xs() - .text_color(muted) - .child(t(L10nKey::SettingsPrefixNote)), - ) - }) - }) - // The rebinding note is the answer to something the reader just - // did, so it outlives the filter that a stale query would hide it - // behind. - .when_some(note, |v, note| { - v.child(div().py_1().text_xs().text_color(accent).child(note)) - }) - .when(!filtering, |v| { - v.child( - h_flex().justify_end().py_2().child( - Button::new("kb-restore-all") - .label(t(L10nKey::SettingsRestoreAllDefaults)) - .small() - .on_click(cx.listener(|this, _, window, cx| { - this.restore_default_keybindings(window, cx) - })), - ), - ) - }) - .child(list) - .into_any_element() - } - - fn render_settings_maintenance(&self, cx: &mut Context) -> AnyElement { - let foreground = cx.theme().foreground; - let muted_fg = cx.theme().muted_foreground; - let stale_daemon = crate::daemon::spawn::local_daemon_stale_build(); - // Whether picking up the new build costs the user their running panes - // decides what this offer is, so it decides what it says. - let stale_daemon_note = if crate::daemon::spawn::local_daemon_supports( - crate::daemon::protocol::FEATURE_HANDOFF, - ) { - L10nKey::SettingsDaemonStaleDescInPlace - } else { - L10nKey::SettingsDaemonStaleDesc - }; - let check_for_updates = cx.global::().check_for_updates; - let auto_download = cx.global::().auto_download_updates; - let channel_idx = match cx.global::().update_channel { - UpdateChannel::Stable => 0, - UpdateChannel::Nightly => 1, - }; - let channel_picker = self.segmented( - "wt-update-channel", - &[ - t(L10nKey::SettingsUpdateChannelStable), - t(L10nKey::SettingsUpdateChannelNightly), - ], - channel_idx, - cx, - |this, ix, _w, cx| { - let channel = match ix { - 0 => UpdateChannel::Stable, - _ => UpdateChannel::Nightly, - }; - this.set_update_channel(channel, cx); - }, - ); - let http_proxy_input = match self.active_settings() { - Some(s) => s.http_proxy_input.clone(), - None => return div().into_any_element(), - }; - // Only flags a committed value: the input commits on Enter/blur, so a - // half-typed address is never marked wrong mid-keystroke. - let http_proxy_value = http_proxy_input.read(cx).value().trim().to_string(); - let http_proxy_invalid = !http_proxy_value.is_empty() - && !tty7_core::daemon::install::proxy::is_valid_manual(&http_proxy_value); - let http_proxy_error = - http_proxy_invalid.then(|| field_error(t(L10nKey::SettingsAppHttpProxyInvalid), cx)); - let http_proxy_control = v_flex() - .gap_1() - .w(px(FIELD_W)) - .max_w_full() - .child(Input::new(&http_proxy_input).small()) - .when_some(http_proxy_error, |this, line| this.child(line)) - .into_any_element(); - - v_flex() - .child(self.section_header(t(L10nKey::SettingsUpdates), cx)) - .child(self.settings_row( - t(L10nKey::SettingsUpdateChannel), - t(L10nKey::SettingsUpdateChannelDesc), - channel_picker, - cx, - )) - .child( - self.settings_row( - t(L10nKey::SettingsCheckUpdatesOnLaunch), - t(L10nKey::SettingsCheckUpdatesDesc), - crate::ui::theme::switch("check-updates", cx) - .checked(check_for_updates) - .on_click(cx.listener(|this, on: &bool, _w, cx| { - this.set_check_for_updates(*on, cx) - })) - .into_any_element(), - cx, - ), - ) - .child( - self.settings_row( - t(L10nKey::SettingsAutoDownload), - t(L10nKey::SettingsAutoDownloadDesc), - crate::ui::theme::switch("auto-download-updates", cx) - .checked(auto_download) - .on_click(cx.listener(|this, on: &bool, _w, cx| { - this.set_auto_download_updates(*on, cx) - })) - .into_any_element(), - cx, - ), - ) - .child(self.settings_row( - t(L10nKey::SettingsAppHttpProxy), - t(L10nKey::SettingsAppHttpProxyDesc), - http_proxy_control, - cx, - )) - .child(self.section_rule(cx)) - .child(self.section_header(t(L10nKey::SettingsServer), cx)) - .child( - v_flex() - .gap_2() - // The other half of an in-place update: the app is new, the - // process serving every pane is not. Said here rather than - // beside the update controls, so the one button that offers - // to pick the new build up stays the only one on the page. - .when_some(stale_daemon.as_deref(), |this, build| { - this.child( - div() - .text_sm() - .text_color(foreground) - .child(t_fmt(L10nKey::SettingsDaemonStale, &[("build", build)])), - ) - }) - .child( - div() - .text_sm() - .text_color(muted_fg) - // A stale server has a more specific thing to say - // than the section's standing description, and it - // ends with the same button. - .child(t(if stale_daemon.is_some() { - stale_daemon_note - } else { - L10nKey::SettingsServerDesc - })), - ) - .child( - h_flex().child( - Button::new("restart-daemon") - .label(t(L10nKey::SettingsRestartServer)) - .small() - .on_click(cx.listener(|this, _, window, cx| { - this.restart_daemon(window, cx) - })), - ), - ), - ) - .into_any_element() - } - - fn render_settings_about(&self, cx: &mut Context) -> AnyElement { - // Copy colors before constructing controls that borrow `cx` mutably. - let (foreground, muted_fg, danger) = { - let theme = cx.theme(); - (theme.foreground, theme.muted_foreground, theme.danger) - }; - - let update_status = cx - .try_global::() - .cloned() - .unwrap_or_default(); - let update = update_status.available.clone(); - let update_busy = matches!( - update_status.phase, - crate::core::update::UpdatePhase::Checking - | crate::core::update::UpdatePhase::Downloading { .. } - | crate::core::update::UpdatePhase::Verifying - | crate::core::update::UpdatePhase::Installing - ); - let transferring = matches!( - update_status.phase, - crate::core::update::UpdatePhase::Downloading { .. } - | crate::core::update::UpdatePhase::Verifying - ); - // A staged package whose directory has since been swept away is not an - // offer worth making. - let ready = update_status - .ready - .clone() - .filter(crate::core::update::PendingUpdate::is_usable); - // "You're running the latest version" directly above "27.0.0 is ready - // to install" is a contradiction, and a reachable one: a release that - // gets pulled after someone downloaded it leaves exactly this pair. - // The staged package is the more useful of the two claims. - let phase_text = localized_update_phase(&update_status.phase).filter(|_| { - ready.is_none() - || !matches!( - update_status.phase, - crate::core::update::UpdatePhase::UpToDate - ) - }); - let failure = update_status.failure.clone(); - let logo = Arc::new(Image::from_bytes( - ImageFormat::Png, - include_bytes!("../../assets/logo@256.png").to_vec(), - )); - - v_flex() - .child( - h_flex() - .gap_4() - .items_center() - .child(img(logo).size_12().rounded_lg()) - .child( - v_flex() - .gap_0p5() - .child( - div() - .text_xl() - .font_weight(FontWeight::SEMIBOLD) - .text_color(foreground) - .child("tty7"), - ) - .child(div().text_sm().text_color(muted_fg).child(format!( - "{} {}", - t(L10nKey::SettingsVersion), - env!("CARGO_PKG_VERSION") - ))) - .child( - Link::new("about-github") - .href("https://github.com/l0ng-ai/tty7") - .text_sm() - .child("github.com/l0ng-ai/tty7"), - ), - ), - ) - .child( - div() - .mt_4() - .text_sm() - .text_color(muted_fg) - .child(t(L10nKey::SettingsAboutDesc1)), - ) - .child(self.section_rule(cx)) - .child(self.section_header(t(L10nKey::SettingsUpdates), cx)) - .child( - v_flex() - // The section can carry several stacked states at once — - // a failure, a staged package, a skipped version. At gap_2 - // they read as one paragraph. - .gap_3() - // A failure the user can act on. Persisted, so it is still - // here tomorrow — the old in-memory phase died with the - // process and took the only evidence with it. - .when_some(failure, |this, failure| { - this.child( - v_flex() - .gap_1() - .child(div().text_sm().text_color(danger).child(t_fmt( - L10nKey::SettingsUpdateFailedTitle, - &[("version", &failure.version)], - ))) - .child( - div() - .text_xs() - .text_color(muted_fg) - .child(failure.detail.clone()), - ) - .child( - h_flex() - .gap_2() - .child( - Button::new("update-retry") - .label(t(L10nKey::SettingsUpdateRetry)) - .small() - .disabled(update_busy) - .on_click(cx.listener(|_, _, _window, cx| { - crate::core::update::dismiss_failure(cx); - crate::core::update::install_available(cx); - })), - ) - .child( - Button::new("update-manual") - .label(t(L10nKey::SettingsUpdateDownloadManually)) - .small() - .on_click(cx.listener(|_, _, _window, _cx| { - crate::core::update::open_releases_page() - })), - ) - .child( - Button::new("update-dismiss") - .label(t(L10nKey::SettingsUpdateDismiss)) - .small() - .on_click(cx.listener(|_, _, _window, cx| { - crate::core::update::dismiss_failure(cx) - })), - ), - ), - ) - }) - // Downloaded and verified: the decision left is "may I - // restart", not "will you spend five minutes on this". - .when_some(ready.clone(), |this, pending| { - this.child( - v_flex() - .gap_1() - .child(div().text_sm().text_color(foreground).child(t_fmt( - L10nKey::SettingsUpdateReady, - &[("version", &pending.version)], - ))) - .when(pending.apply_on_launch, |this| { - this.child( - div() - .text_xs() - .text_color(muted_fg) - .child(t(L10nKey::SettingsUpdateReadyNextLaunch)), - ) - }) - .child( - h_flex() - .gap_2() - .child( - Button::new("install-ready") - .label(t(L10nKey::SettingsUpdateInstallNow)) - .small() - .disabled(update_busy) - .on_click(cx.listener(|_, _, _window, cx| { - crate::core::update::install_available(cx) - })), - ) - .child( - Button::new("discard-ready") - .label(t(L10nKey::SettingsUpdateDiscard)) - .small() - .disabled(update_busy) - .on_click(cx.listener(|_, _, _window, cx| { - crate::core::update::discard_pending(cx) - })), - ), - ), - ) - }) - // One action, not the three that used to crowd this row. - // The update dialog covers the rest, but it is a moment - // rather than a place: after "Later" it does not come back - // for days, and where the package cannot be installed for - // the user — Linux, an unsupported install — the release - // page is the whole update path. That cannot live only in a - // dialog that has already been dismissed. - .when_some(update.filter(|_| ready.is_none()), |this, upd| { - let availability = t_fmt( - L10nKey::SettingsVersionAvailable, - &[("version", &upd.version)], - ); - // `install_available` opens the release page by itself - // when there is nothing to install, so both labels lead - // to the one call. - let action = if upd.installable { - t(L10nKey::SettingsUpdateAndRelaunch) - } else { - t(L10nKey::SettingsUpdateViewRelease) - }; - this.child( - v_flex() - .gap_2() - .child( - h_flex() - .gap_3() - .items_center() - .child( - div() - .text_sm() - .text_color(foreground) - .child(availability), - ) - .child( - Button::new("install-update") - .label(action) - .small() - .disabled(update_busy) - .on_click(cx.listener(|_, _, _window, cx| { - crate::core::update::install_available(cx) - })), - ), - ) - .when_some(upd.install_hint, |this, hint| { - this.child( - div() - .text_xs() - .text_color(muted_fg) - .child(localized_update_install_hint(&hint)), - ) - }), - ) - }) - .when_some(phase_text, |this, text| { - this.child(div().text_sm().text_color(muted_fg).child(text)) - }) - .child( - h_flex() - .gap_2() - .child( - Button::new("check-update-now") - .label( - if matches!( - update_status.phase, - crate::core::update::UpdatePhase::Checking - ) { - t(L10nKey::SettingsUpdateChecking) - } else { - t(L10nKey::SettingsUpdateCheckNow) - }, - ) - .small() - .disabled(update_busy) - .on_click(cx.listener(|_, _, _window, cx| { - crate::core::update::spawn_check_forced(cx) - })), - ) - // Thirty megabytes on a slow link is exactly the - // download someone wants to call off; without this - // the only way out was to kill the app. - .when(transferring, |this| { - this.child( - Button::new("cancel-update-download") - .label(t(L10nKey::SettingsUpdateCancel)) - .small() - .on_click(cx.listener(|_, _, _window, cx| { - crate::core::update::cancel_download(cx) - })), - ) - }), - ), - ) - .into_any_element() - } } #[cfg(test)] @@ -9218,55 +2839,6 @@ mod tests { assert_eq!(section_match_count(kb, "no such action anywhere"), 0); } - /// Every outcome of a test has a line of its own, and the timing reads as - /// a number a person can compare rather than four digits of milliseconds. - #[test] - fn a_test_result_reads_as_one_line_per_outcome() { - crate::ui::i18n::set_locale("en"); - assert_eq!(human_millis(640), "640 ms"); - assert_eq!(human_millis(999), "999 ms"); - assert_eq!(human_millis(1000), "1.0 s"); - assert_eq!(human_millis(12_400), "12.4 s"); - - let needs = [ - SshTestNeed::Password, - SshTestNeed::KeyPassphrase, - SshTestNeed::KeyboardInteractive, - SshTestNeed::HostKeyDecision, - SshTestNeed::HostKeyChanged, - ]; - let lines: Vec<&str> = needs.iter().map(|n| t(ssh_test_need_message(*n))).collect(); - assert!(lines.iter().all(|l| !l.is_empty())); - assert_eq!( - lines.iter().collect::>().len(), - lines.len(), - "each thing the handshake can stop for gets said differently" - ); - } - - /// The credential boxes the form shows have to be the ones the connection - /// will actually offer. `build_spec_inner` sends a password for Auto and - /// Password and key passphrases for Auto and Key, and nothing for the - /// rest — a box outside that split collects a secret, stores it in the - /// keychain, and never hands it to anybody. - #[test] - fn a_credential_box_only_appears_where_the_handshake_would_use_it() { - for mode in AUTH_MODES { - assert_eq!( - auth_uses_password(mode), - matches!(mode, AuthMode::Auto | AuthMode::Password), - "{mode:?} password box" - ); - assert_eq!( - auth_uses_key(mode), - matches!(mode, AuthMode::Auto | AuthMode::PublicKey), - "{mode:?} key boxes" - ); - } - assert!(!auth_uses_password(AuthMode::Agent)); - assert!(!auth_uses_key(AuthMode::Gssapi)); - } - /// The password lives in the keychain under the address, not in the /// profile — so saving has to decide two things the config file cannot /// record: whether the entry the form read is now stranded, and whether @@ -9396,196 +2968,18 @@ mod tests { std::fs::remove_dir_all(&dir).ok(); } - /// The dropdown resolves a pick by its row index, so the row a mode opens - /// on and the mode that row saves have to be the same one. A list that - /// drifted out of step would quietly save the wrong method. - #[test] - fn every_auth_mode_opens_on_its_own_row() { - crate::ui::i18n::set_locale("en"); - let labels = auth_mode_labels(); - assert_eq!(labels.len(), AUTH_MODES.len()); - for mode in AUTH_MODES { - let ix = auth_mode_index(mode); - assert_eq!(AUTH_MODES[ix], mode); - assert_eq!(labels[ix], auth_mode_label(mode)); - } - assert_eq!( - labels - .iter() - .collect::>() - .len(), - labels.len(), - "two methods sharing a label would resolve to whichever comes first" - ); - } - - /// The three proxy fields look independent and are not — one connection - /// goes through one proxy. The note under the losing field is the only - /// thing saying so, so it has to name the same winner `map_proxy` picks - /// when the profile is dialled, and has to stay quiet where there is no - /// contest. - #[test] - fn a_proxy_field_says_when_another_one_outranks_it() { - crate::ui::i18n::set_locale("en"); - let note = |me: ProxyPick, filled: bool, (c, s, h): (bool, bool, bool)| { - me.overridden_by(filled, ProxyPick::of(c, s, h)) - }; - - assert_eq!(ProxyPick::of(true, true, true), Some(ProxyPick::Command)); - assert_eq!(ProxyPick::of(false, true, true), Some(ProxyPick::Socks)); - assert_eq!(ProxyPick::of(false, false, true), Some(ProxyPick::Http)); - assert_eq!(ProxyPick::of(false, false, false), None); - - assert!( - note(ProxyPick::Socks, true, (true, true, false)).is_some(), - "a proxy command outranks a SOCKS address" - ); - assert!( - note(ProxyPick::Http, true, (false, true, true)).is_some(), - "so does a SOCKS address over an HTTP one" - ); - assert!( - note(ProxyPick::Command, true, (true, true, true)).is_none(), - "the field being used has nothing to apologise for" - ); - assert!( - note(ProxyPick::Http, false, (true, false, false)).is_none(), - "an empty field is not being overridden, it is just empty" - ); - assert!(note(ProxyPick::Socks, true, (false, true, false)).is_none()); - } - - /// The row keeps its side-by-side shape while both halves fit, and stacks - /// once they do not. The SSH page reaches that point first — it spends its - /// host list before the row gets anything. - #[test] - fn enlarged_settings_text_gets_room_in_the_navigation() { - for scale in [1.25, 1.5] { - let columns = settings_columns_scaled(SettingsSection::Appearance, false, 1440., scale); - assert!(columns.nav >= NAV_W_MIN * scale); - let row = settings_row_width(SettingsSection::Appearance, false, 1440., scale); - assert!(row >= STACK_ROW_BELOW * scale); - let with_picker = - settings_columns_scaled(SettingsSection::Appearance, true, 720., scale); - assert!( - with_picker.panel_overlays, - "the picker must not squeeze enlarged labels" - ); - } - } - #[test] fn a_row_stacks_once_its_label_and_control_stop_fitting() { - use SettingsSection::*; - assert!(settings_row_width(Terminal, false, 1440., 1.) >= STACK_ROW_BELOW); - assert!(settings_row_width(Terminal, false, 900., 1.) >= STACK_ROW_BELOW); - // At the narrowest window that turns up the page is 420 wide, which is - // under the width where a label and a control still share a line. - assert!(settings_row_width(Terminal, false, NARROWEST_WINDOW, 1.) < STACK_ROW_BELOW); + assert!(settings_row_width(1440., 1.) >= STACK_ROW_BELOW); + assert!(settings_row_width(900., 1.) >= STACK_ROW_BELOW); + // At the narrowest window that turns up the nav gives back what it can + // and the page is still under the width a label and a control share. + assert_eq!(nav_width(640., 1.), NAV_W_MIN); + assert!(settings_row_width(640., 1.) < STACK_ROW_BELOW); // Capped at the reading column, so a wider window never widens the row. - assert_eq!( - settings_row_width(Terminal, false, 4000., 1.), - READING_COLUMN - ); - // SSH crosses over while the window is still wide — it is the page that - // spends a host list before its rows get anything. - assert!(settings_row_width(Ssh, false, 1440., 1.) >= STACK_ROW_BELOW); - assert!(settings_row_width(Ssh, false, 900., 1.) < STACK_ROW_BELOW); + assert_eq!(settings_row_width(4000., 1.), READING_COLUMN); // And never goes negative on a window narrower than its own chrome. - assert_eq!(settings_row_width(Ssh, false, 100., 1.), 0.); - } - - /// Every list gives width back before the page does, and no combination of - /// page and panel leaves the page below the width it is derived to keep. - /// 641pt is the window the report came from — under the declared 720 —- so - /// that is the case that has to hold, not the one the manifest promises. - #[test] - fn the_page_keeps_a_readable_width_at_every_window_that_turns_up() { - use SettingsSection::*; - for section in SettingsSection::ALL { - for panel_open in [false, true] { - for viewport in [NARROWEST_WINDOW, 641., 720., 900., 1100., 1440., 2560.] { - let cols = settings_columns(section, panel_open, viewport); - let pad = match section { - Ssh => SSH_DETAIL_PAD, - _ => PAGE_PAD, - }; - let panel = only_when(!cols.panel_overlays, cols.theme_panel); - let page = viewport - cols.nav - cols.ssh_list - panel - pad; - assert!( - page >= CONTENT_MIN_W, - "{viewport}px, {panel_open}: page got {page}, floor is {CONTENT_MIN_W}" - ); - // And the columns add up to the window rather than past it, - // which is what keeps the rightmost one on screen. - assert!(cols.nav + cols.ssh_list + panel + pad + page <= viewport + 1.); - assert!(cols.nav >= NAV_W_MIN && cols.nav <= NAV_W); - } - } - } - } - - /// The three screenshots in the report, by the numbers measured off them. - /// Every one of them is the same 641pt window. - #[test] - fn the_reported_window_lays_out_without_running_off_the_screen() { - use SettingsSection::*; - const REPORTED: f32 = 641.; - - // Shot 1 — SSH. Nav 220 and host list 280 left the detail 141pt and its - // empty state painted ~270 past the window edge. Both lists now stand - // on their floors and the detail keeps the rest. - let ssh = settings_columns(Ssh, false, REPORTED); - assert_eq!((ssh.nav, ssh.ssh_list), (NAV_W_MIN, SSH_LIST_W_MIN)); - let detail = settings_row_width(Ssh, false, REPORTED, 1.); - assert!(detail >= CONTENT_MIN_W, "SSH detail got {detail}"); - - // Shot 2 — Appearance, panel closed. The opacity row measured a 78pt - // label beside a 240pt slider; at this width the row has to stack. - // The page does not reach its preferred `CONTENT_W` here: the nav floor - // is sized to show a Japanese nav label whole, and at 641 that costs the - // page the difference. Readable and stacked is the property that matters. - let page = settings_row_width(Appearance, false, REPORTED, 1.); - assert_eq!(page, REPORTED - NAV_W_MIN - PAGE_PAD); - assert!(page >= CONTENT_MIN_W, "the page got {page}"); - assert!( - page < STACK_ROW_BELOW, - "the opacity row has to stack at 641" - ); - - // Shot 3 — Appearance with the theme panel. 220 + 300 of chrome left - // the page ~125pt, one Chinese character per line. The panel now lifts - // off the row entirely and the page is back to shot 2's width. - assert!(settings_columns(Appearance, true, REPORTED).panel_overlays); - assert_eq!(settings_row_width(Appearance, true, REPORTED, 1.), page); - } - - /// The list that has to give the most is the one the window has the least - /// room for, and no list is ever asked for more than it has to spare. - #[test] - fn the_lists_shrink_together_and_stop_at_their_floors() { - use SettingsSection::*; - // Wide enough for everyone: nothing moves. - let wide = settings_columns(Ssh, false, 1440.); - assert_eq!((wide.nav, wide.ssh_list), (NAV_W, SSH_LIST_W)); - // The reported window — half of a 1440pt screen, three columns on SSH. - // Both lists give, neither past its floor, and the detail comes out at - // its preferred width instead of the 336 it used to be left with. - let half = settings_columns(Ssh, false, 900.); - assert!(half.nav < NAV_W && half.ssh_list < SSH_LIST_W); - assert!(half.nav >= NAV_W_MIN && half.ssh_list >= SSH_LIST_W_MIN); - assert_eq!( - settings_row_width(Ssh, false, 900., 1.).round(), - CONTENT_W, - "the SSH detail should get its preferred width at 900pt" - ); - // The narrowest window that turns up: both at the floor, page readable. - let tiny = settings_columns(Ssh, false, NARROWEST_WINDOW); - assert_eq!((tiny.nav, tiny.ssh_list), (NAV_W_MIN, SSH_LIST_W_MIN)); - assert_eq!( - settings_row_width(Ssh, false, NARROWEST_WINDOW, 1.), - CONTENT_MIN_W - ); + assert_eq!(settings_row_width(100., 1.), 0.); } /// A preset row lights up the bucket the value *is*, and nothing when it @@ -9660,54 +3054,18 @@ mod tests { #[test] fn the_stacking_width_follows_the_interface_font() { use crate::core::config::UI_FONT_SIZE_MAX; - use SettingsSection::*; let large = UI_FONT_SIZE_MAX / UI_FONT_SIZE_DEFAULT; // Side by side at the default font... - assert!(settings_row_width(Appearance, false, 900., 1.) >= STACK_ROW_BELOW); + assert!(settings_row_width(900., 1.) >= STACK_ROW_BELOW); // ...and stacked at the largest, where the same row holds half as much. assert!( - settings_row_width(Appearance, false, 900., large) < STACK_ROW_BELOW * large, + settings_row_width(900., large) < STACK_ROW_BELOW * large, "a 900pt window at the largest interface font has to stack" ); + // The nav keeps its labels readable at the larger font. + assert!(nav_width(1440., large) > NAV_W); // The reading column grows with the font, so a wide window does not. - assert!(settings_row_width(Appearance, false, 1600., large) >= STACK_ROW_BELOW * large); - } - - /// The theme panel took its 300px from the page and from nothing else, so - /// a half-width window with it open rendered a description one character - /// wide. It now shrinks with everything else, and stops being a column at - /// all once even that is not enough. - #[test] - fn the_theme_panel_yields_before_the_page_does() { - use SettingsSection::*; - assert!(settings_row_width(Appearance, true, 900., 1.) < STACK_ROW_BELOW); - assert!( - settings_row_width(Appearance, true, 900., 1.) - < settings_row_width(Appearance, false, 900., 1.) - ); - // Beside the page while both fit — which, with the panel and the nav - // both allowed down to their floors, still holds at 720. - assert!(!settings_columns(Appearance, true, 900.).panel_overlays); - assert!(!settings_columns(Appearance, true, 720.).panel_overlays); - // ...and over it once they do not, at which point the page is back to - // the width it has with the panel closed. - assert!(settings_columns(Appearance, true, 641.).panel_overlays); - assert_eq!( - settings_row_width(Appearance, true, 641., 1.), - settings_row_width(Appearance, false, 641., 1.) - ); - // The panel is the only chrome that can leave, so it has to leave in - // time: at 641 there is no arrangement in which it and a readable page - // both fit in a row. - assert!( - NARROWEST_WINDOW - NAV_W_MIN - THEME_PANEL_W_MIN - PAGE_PAD < CONTENT_MIN_W, - "the overlay threshold has to fire at the narrowest window" - ); - // Wide enough and the cap is the reading column either way. - assert_eq!( - settings_row_width(Appearance, true, 1600., 1.), - READING_COLUMN - ); + assert!(settings_row_width(1600., large) >= STACK_ROW_BELOW * large); } #[test] @@ -9829,13 +3187,13 @@ mod tests { ("symlink", Agents), // Rows the index had no entry for at all, so the query counted // nothing, no badge appeared and no row lit up: the whole Updates - // group on General, and Smooth scrolling between two rows that were - // both findable. + // group, and Smooth scrolling between two rows that were both + // findable. ("smooth", Terminal), - ("nightly", General), - ("channel", General), - ("metered", General), - ("automatic", General), + ("nightly", About), + ("channel", About), + ("metered", About), + ("automatic", About), // A headline feature the index had never heard of: "background // image" matched nothing, and typing it walked the page to About // because "background" alone hits Download updates in the @@ -10345,7 +3703,7 @@ mod gpui_tests { assert_eq!(form.host.read(cx).value().as_str(), "new.example.com"); }); app.update_in(&mut vcx, |app, window, cx| { - app.cancel_ssh_form(window, cx); + app.cancel_ssh_form(cx); app.open_ssh_profile_in_settings(id, window, cx); let input = app .active_settings() @@ -10552,8 +3910,9 @@ mod gpui_tests { vcx.run_until_parked(); app.update_in(&mut vcx, |app, _, cx| { + // The theme menu open: its popover has to lay out beside the page. if let Some(s) = app.active_settings_mut() { - s.theme_panel_open = true; + s.menu = Some("theme-slot-dark".into()); } cx.notify(); }); @@ -10563,7 +3922,7 @@ mod gpui_tests { let section = vcx.update(|_, cx| app.read(cx).active_settings().map(|s| s.section)); assert!( matches!(section, Some(SettingsSection::Appearance)), - "the panel should still be on Appearance after two paint passes", + "the page should still be on Appearance after two paint passes", ); } diff --git a/src/ui/settings/agents.rs b/src/ui/settings/agents.rs new file mode 100644 index 00000000..177c3004 --- /dev/null +++ b/src/ui/settings/agents.rs @@ -0,0 +1,525 @@ +//! Integrations: the agent hooks that put each agent's live status in the +//! sidebar, per machine, and the `tty7` command on PATH. + +use crate::core::agent_hooks::{HookAgent, HooksState}; + +use super::kit::{self, BtnKind, Tk, fs}; +use super::shell::MenuEntry; +use super::*; + +/// The agent the tab bar draws for this hook, so the two show the same mark. +fn cli_agent(agent: HookAgent) -> crate::core::cli_agent::CLIAgent { + use crate::core::cli_agent::CLIAgent as C; + match agent { + HookAgent::Claude => C::Claude, + HookAgent::Codex => C::Codex, + HookAgent::TraeCode => C::TraeCode, + HookAgent::Copilot => C::Copilot, + HookAgent::OpenCode => C::OpenCode, + HookAgent::Pi => C::Pi, + HookAgent::Grok => C::Grok, + HookAgent::OhMyPi => C::OhMyPi, + HookAgent::Gemini => C::Gemini, + HookAgent::Droid => C::Droid, + HookAgent::Qwen => C::Qwen, + HookAgent::Goose => C::Goose, + HookAgent::Kimi => C::Kimi, + HookAgent::QoderCLI => C::QoderCLI, + HookAgent::Crush => C::Crush, + HookAgent::CodeBuddy => C::CodeBuddy, + HookAgent::Cursor => C::Cursor, + } +} + +impl Tty7App { + pub(crate) fn render_settings_agents(&self, cx: &mut Context) -> AnyElement { + Self::settings_page([ + self.render_agent_hooks_group(cx), + self.render_command_line_rows(cx), + ]) + } + + pub(crate) fn render_command_line_rows(&self, cx: &mut Context) -> AnyElement { + let on = cx.global::().install_cli_on_path; + let control = self.settings_switch("install-cli-on-path", on, cx, |this, on, _, cx| { + this.set_install_cli_on_path(on, cx) + }); + self.settings_group( + Some(t(L10nKey::SettingsCommandLine)), + None, + [self + .settings_row( + t(L10nKey::SettingsInstallCliOnPath), + t(L10nKey::SettingsCommandLineDesc), + control, + cx, + ) + .into_any_element()], + cx, + ) + } + + fn render_agent_hooks_group(&self, cx: &mut Context) -> AnyElement { + let tk = Tk::of(cx); + let Some(s) = self.active_settings() else { + return div().into_any_element(); + }; + let view = s.agent_hooks_states.clone(); + let note = s.agent_hooks_note.clone(); + let selected = s.agent_hooks_host; + let query_input = s.agent_query.clone(); + let query = query_input.read(cx).value().trim().to_lowercase(); + let show_all = s.agent_show_all; + let touched = s.agent_touched.clone(); + let busy = s.agent_busy.clone(); + let focused = s.focused_setting; + let menu_open = s.menu.clone(); + + // The machine the hooks below belong to. + let machines = self.agent_hooks_machines(cx); + let offline = self.agent_hooks_offline_count(cx); + let current = machines + .iter() + .find(|m| m.host == selected) + .map(|m| m.label.clone()) + .unwrap_or_default(); + let rows: Vec = match &view { + AgentHooksView::Ready(rows) => rows.clone(), + _ => Vec::new(), + }; + let installed = rows + .iter() + .filter(|r| r.state != HooksState::NotInstalled) + .count(); + let mut entries = vec![MenuEntry::Heading( + t(L10nKey::SettingsConnectedMachines).into(), + )]; + for m in &machines { + let host = m.host; + entries.push(MenuEntry::Item { + label: m.label.clone().into(), + checked: host == selected, + font: None, + danger: false, + trailing: (host == selected && matches!(view, AgentHooksView::Ready(_))).then( + || { + t_fmt( + L10nKey::SettingsInstalledCount, + &[("count", &installed.to_string())], + ) + .into() + }, + ), + on_pick: std::rc::Rc::new(move |this, _w, cx| { + if let Some(s) = this.active_settings_mut() { + s.agent_touched.clear(); + } + this.select_agent_hooks_host(host, cx) + }), + }); + } + if offline > 0 { + entries.push(MenuEntry::Separator); + entries.push(MenuEntry::Note( + t_plural(L10nKey::SettingsOfflineMachines, offline, &[]).into(), + )); + } + let machine_icon = Icon::empty() + .path(if selected.is_local() { + "icons/settings/machine-local.svg" + } else { + "icons/settings/machine-remote.svg" + }) + .size(px(12.)) + .text_color(tk.k5) + .into_any_element(); + let machine = self.settings_dropdown( + "agent-hooks-machine", + current.clone(), + Some(machine_icon), + entries, + cx, + ); + let machine_desc = if selected.is_local() { + t(L10nKey::SettingsMachineLocalDesc).to_string() + } else { + t_fmt(L10nKey::SettingsMachineRemoteDesc, &[("name", ¤t)]) + }; + let machine_row = h_flex() + .min_h(px(52.)) + .py(px(12.)) + .gap(px(32.)) + .items_center() + .justify_between() + .child( + v_flex() + .min_w_0() + .gap(px(2.)) + .child(div().text_size(fs(13.)).child(t(L10nKey::SettingsMachine))) + .child( + div() + .text_size(fs(12.)) + .line_height(px(17.)) + .text_color(tk.k5) + .child(machine_desc), + ), + ) + .child(machine) + .into_any_element(); + + let total = HookAgent::ALL.len(); + let toolbar = h_flex() + .gap(px(12.)) + .items_center() + .pt(px(10.)) + .pb(px(8.)) + .child( + kit::search_field(&query_input, &tk) + .w(px(240.)) + .capture_key_down(cx.listener(|this, ev: &KeyDownEvent, window, cx| { + if ev.keystroke.key.as_str() == "escape" { + let input = this.active_settings().map(|s| s.agent_query.clone()); + if let Some(input) = input + && !input.read(cx).value().is_empty() + { + input.update(cx, |i, cx| i.set_value("", window, cx)); + cx.stop_propagation(); + } + } + })), + ) + .child(div().flex_1()) + .when(matches!(view, AgentHooksView::Ready(_)), |r| { + r.child(div().text_size(fs(12.)).text_color(tk.k45).child(t_fmt( + L10nKey::SettingsAgentsInstalledSummary, + &[ + ("count", &installed.to_string()), + ("total", &total.to_string()), + ], + ))) + }) + .into_any_element(); + + let mut body: Vec = vec![machine_row, toolbar]; + match &view { + AgentHooksView::Loading => body.push( + div() + .h(px(44.)) + .flex() + .items_center() + .text_color(tk.k35) + .child(t(L10nKey::SettingsReadingAgentConfig)) + .into_any_element(), + ), + AgentHooksView::Unavailable(reason) => body.push( + div() + .py(px(12.)) + .text_size(fs(12.5)) + .text_color(tk.warn_text) + .child(reason.clone()) + .into_any_element(), + ), + AgentHooksView::Ready(rows) => { + let has = |r: &AgentHookRow| r.state != HooksState::NotInstalled; + let is_focused = + |r: &AgentHookRow| focused.is_some_and(|k| t(k) == r.agent.display_name()); + let mut list: Vec<&AgentHookRow> = rows + .iter() + .filter(|r| { + if !query.is_empty() { + return format!("{} {}", r.agent.display_name(), r.target) + .to_lowercase() + .contains(&query); + } + show_all || has(r) || touched.contains(&r.agent) || is_focused(r) + }) + .collect(); + let rank = |r: &AgentHookRow| match r.state { + HooksState::Outdated => 0, + HooksState::Installed => 1, + HooksState::NotInstalled => 2, + }; + list.sort_by_key(|r| { + ( + rank(r), + HookAgent::ALL + .iter() + .position(|a| *a == r.agent) + .unwrap_or(0), + ) + }); + let none = list.is_empty(); + let mut col = v_flex() + .id("agent-hook-list") + .when(!query.is_empty() || show_all, |c| { + c.max_h(px(416.)).overflow_y_scroll() + }); + for (i, row) in list.into_iter().enumerate() { + let row_note = note + .as_ref() + .filter(|(a, _)| *a == row.agent) + .map(|(_, text)| text.clone()); + col = col.child(self.render_agent_row( + i, + row, + busy.contains(&row.agent), + row_note, + menu_open.as_deref(), + cx, + )); + } + body.push(col.into_any_element()); + if none { + body.push( + div() + .h(px(44.)) + .flex() + .items_center() + .text_color(tk.k35) + .child(if query.is_empty() { + t(L10nKey::SettingsNoAgentsInstalled).to_string() + } else { + t_fmt(L10nKey::SettingsNoAgentsMatch, &[("query", &query)]) + }) + .into_any_element(), + ); + } + let rest = total - installed; + if query.is_empty() && rest > 0 { + body.push( + h_flex() + .h(px(40.)) + .gap(px(8.)) + .items_center() + .text_size(fs(12.)) + .text_color(tk.k45) + .when(!show_all, |r| { + r.child(t_plural(L10nKey::SettingsMoreAgents, rest, &[])) + }) + .child( + kit::button( + "agent-show-all", + if show_all { + t(L10nKey::SettingsShowInstalledOnly) + } else { + t(L10nKey::SettingsShowAll) + }, + BtnKind::Link, + ) + .on_click(cx.listener( + |this, _, _w, cx| { + if let Some(s) = this.active_settings_mut() { + s.agent_show_all = !s.agent_show_all; + s.agent_touched.clear(); + } + cx.notify(); + }, + )), + ) + .into_any_element(), + ); + } + } + } + + self.settings_group( + Some(t(L10nKey::SettingsAgentsIntro)), + Some(t(L10nKey::SettingsAgentsIntroDesc).to_string()), + body, + cx, + ) + } + + fn render_agent_row( + &self, + i: usize, + row: &AgentHookRow, + busy: bool, + note: Option, + menu_open: Option<&str>, + cx: &mut Context, + ) -> AnyElement { + let tk = Tk::of(cx); + let agent = row.agent; + let mark = cli_agent(agent); + let (status, dot) = if busy { + (Some(t(L10nKey::SettingsWorking)), tk.k3) + } else { + match row.state { + HooksState::Installed => (Some(t(L10nKey::SettingsStatusInstalled)), tk.ok), + HooksState::Outdated => (Some(t(L10nKey::SettingsUpdateAvailable)), tk.warn), + HooksState::NotInstalled => (None, tk.k3), + } + }; + let action = (!busy) + .then(|| match row.state { + HooksState::NotInstalled => Some(t(L10nKey::SettingsInstall)), + HooksState::Outdated => Some(t(L10nKey::SettingsUpdate)), + HooksState::Installed => None, + }) + .flatten(); + let has_menu = row.state != HooksState::NotInstalled && !busy; + let menu_id: SharedString = format!("agent-menu-{i}").into(); + let open = menu_open == Some(menu_id.as_ref()); + let local = self + .active_settings() + .is_some_and(|s| s.agent_hooks_host.is_local()); + let target = row.target.clone(); + let menu = has_menu.then(|| { + let mut entries = vec![MenuEntry::item( + t(L10nKey::SettingsReinstall), + false, + move |this, _w, cx| this.settings_install_agent_hooks(agent, cx), + )]; + if local { + entries.push(MenuEntry::item( + t(L10nKey::SettingsRevealHookFile), + false, + move |_this, _w, cx| { + let path = crate::core::ssh_profile::expand_tilde(&target); + cx.reveal_path(std::path::Path::new(&path)); + }, + )); + } + entries.push(MenuEntry::Item { + label: t(L10nKey::SettingsUninstall).into(), + checked: false, + font: None, + danger: true, + trailing: None, + on_pick: std::rc::Rc::new(move |this, _w, cx| { + this.settings_uninstall_agent_hooks(agent, cx) + }), + }); + let toggle = menu_id.clone(); + div() + .relative() + .child( + div() + .id(ElementId::Name(SharedString::from(format!( + "{menu_id}-trigger" + )))) + .size(px(26.)) + .rounded(px(6.)) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .when(open, |d| d.bg(tk.k05)) + .hover(move |s| s.bg(tk.k05)) + .child( + Icon::empty() + .path("icons/settings/more.svg") + .size(px(12.)) + .text_color(tk.k5), + ) + .on_click(cx.listener(move |this, _, window, cx| { + this.toggle_settings_menu(toggle.clone(), 0, false, window, cx) + })), + ) + .when(open, |d| { + // Built only while open: the entries hold callbacks, and + // the panel is where they are wired to the rows. + d.child(kit::popover_below( + true, + 4., + self.settings_menu_panel(&menu_id, entries, cx) + .min_w(px(170.)), + )) + }) + }); + + v_flex() + .id(SharedString::from(format!("agent-row-{i}"))) + .anchor_scroll(self.first_hit_anchor(agent.display_name(), cx)) + .child( + h_flex() + .min_h(px(52.)) + .py(px(8.)) + .gap(px(12.)) + .items_center() + .child( + // The tab bar's agent disc: the brand field, the mark + // on it, and a hairline where the field is the page. + div() + .size(px(20.)) + .flex_shrink_0() + .rounded_full() + .bg(rgb(mark.accent_rgb())) + .when(presets::needs_edge(mark.accent_rgb(), tk.page), |d| { + d.shadow(vec![kit::ring(tk.k15, 0.5, false)]) + }) + .flex() + .items_center() + .justify_center() + .child( + gpui::svg() + .path(mark.icon_path()) + .size(px(11.)) + .text_color(rgb(mark.icon_rgb())), + ), + ) + .child( + v_flex() + .flex_1() + .min_w_0() + .gap(px(2.)) + .child(agent.display_name()) + .child( + div() + .font_family(Tk::mono(cx)) + .text_size(fs(11.5)) + .text_color(tk.k45) + .truncate() + .child(row.target.clone()), + ), + ) + .child( + h_flex() + .flex_shrink_0() + .gap(px(10.)) + .items_center() + .when_some(status, |r, text| { + r.child( + h_flex() + .gap(px(6.)) + .items_center() + .text_size(fs(12.)) + .text_color(tk.k5) + .whitespace_nowrap() + .child(div().size(px(6.)).rounded_full().bg(dot)) + .child(text), + ) + }) + .when_some(action, |r, label| { + r.child( + kit::button( + ("agent-hooks-install", i), + label, + BtnKind::Secondary, + ) + .on_click(cx.listener( + move |this, _, _w, cx| { + this.settings_install_agent_hooks(agent, cx) + }, + )), + ) + }) + .children(menu), + ), + ) + .when_some(note, |col, text| { + col.child( + div() + .pl(px(32.)) + .pb(px(8.)) + .mt(px(-4.)) + .text_size(fs(12.)) + .line_height(px(17.)) + .text_color(tk.k45) + .child(text), + ) + }) + .into_any_element() + } +} diff --git a/src/ui/settings/hosts.rs b/src/ui/settings/hosts.rs new file mode 100644 index 00000000..2b2b2404 --- /dev/null +++ b/src/ui/settings/hosts.rs @@ -0,0 +1,872 @@ +//! The SSH page: one column of hosts — the few used most recently, or every +//! one grouped by where it came from, or whatever a search finds — each of +//! which opens in place to show its details or to be edited. + +use super::kit::{self, BtnKind, Tk, fs}; +use super::*; + +/// How many hosts the page shows before "Show all". +const RECENT_HOSTS: usize = 5; + +/// A list line: a group's heading, or a host. +enum HostLine { + Head { + key: String, + count: usize, + collapsed: bool, + }, + Host(SshProfile), +} + +impl Tty7App { + pub(crate) fn render_settings_ssh(&self, cx: &mut Context) -> AnyElement { + Self::settings_page([ + self.render_hosts_group(cx), + self.render_ssh_connection_rows(cx), + ]) + } + + /// The settings that are rows: they are what search finds on this page. + pub(crate) fn render_ssh_connection_rows(&self, cx: &mut Context) -> AnyElement { + let cfg = cx.global::(); + let (verify, warn) = (cfg.verify_host_keys, cfg.ssh_warn_on_close); + let verify = self.settings_switch("ssh-verify-host-keys", verify, cx, |this, on, _, cx| { + this.set_verify_host_keys(on, cx) + }); + let warn = self.settings_switch("ssh-warn-on-close", warn, cx, |this, on, _, cx| { + this.set_ssh_warn_on_close(on, cx) + }); + self.settings_group( + Some(t(L10nKey::SettingsSecurity)), + Some(t(L10nKey::SettingsSecurityIntro).to_string()), + [ + self.settings_row( + t(L10nKey::SettingsVerifyHostKeys), + t(L10nKey::SettingsVerifyHostKeysDesc), + verify, + cx, + ), + self.settings_row( + t(L10nKey::WarnBeforeClosing), + t(L10nKey::SettingsWarnBeforeClosingDesc), + warn, + cx, + ), + ] + .map(IntoElement::into_any_element), + cx, + ) + } + + fn render_hosts_group(&self, cx: &mut Context) -> AnyElement { + let tk = Tk::of(cx); + let Some(s) = self.active_settings() else { + return div().into_any_element(); + }; + let filter = s.ssh_filter.clone(); + let query = filter.read(cx).value().trim().to_lowercase(); + let show_all = s.ssh_show_all; + let collapsed = s.ssh_collapsed_groups.clone(); + let editing = s.ssh_form.as_ref().map(|f| f.editing); + let cfg = cx.global::(); + let profiles = cfg.ssh_profiles.clone(); + let adding = editing.filter(|id| !profiles.iter().any(|p| p.id == *id)); + let by_name = |a: &SshProfile, b: &SshProfile| { + host_title(a) + .to_lowercase() + .cmp(&host_title(b).to_lowercase()) + }; + + // The recent few: the ones actually connected to, most-used first, + // topped up alphabetically on a fresh install. + let recent: Vec = crate::ui::ssh_connect::ssh_profiles_by_frecency(cx) + .into_iter() + .take(RECENT_HOSTS) + .collect(); + let mut lines: Vec = Vec::new(); + if !query.is_empty() { + let mut hits: Vec = profiles + .iter() + .filter(|p| ssh_row_matches(p, &query)) + .cloned() + .collect(); + hits.sort_by(by_name); + lines.extend(hits.into_iter().map(HostLine::Host)); + } else if show_all { + let mut groups: Vec<(String, Vec)> = Vec::new(); + for p in &profiles { + let key = ssh_group_key(p).to_string(); + match groups.iter_mut().find(|(k, _)| *k == key) { + Some((_, bucket)) => bucket.push(p.clone()), + None => groups.push((key, vec![p.clone()])), + } + } + groups.sort_by(|a, b| { + ssh_group_rank(&a.0) + .cmp(&ssh_group_rank(&b.0)) + .then_with(|| a.0.cmp(&b.0)) + }); + for (key, mut bucket) in groups { + bucket.sort_by(by_name); + let is_collapsed = collapsed.contains(&key); + lines.push(HostLine::Head { + key, + count: bucket.len(), + collapsed: is_collapsed, + }); + if !is_collapsed { + lines.extend(bucket.into_iter().map(HostLine::Host)); + } + } + } else { + lines.extend(recent.iter().cloned().map(HostLine::Host)); + } + let visible: Vec = lines + .iter() + .filter_map(|l| match l { + HostLine::Host(p) => Some(p.id), + _ => None, + }) + .collect(); + + let total = profiles.len(); + let files = profiles + .iter() + .map(|p| ssh_group_key(p).to_string()) + .collect::>() + .len(); + let rest = total.saturating_sub(recent.len()); + + let toolbar = h_flex() + .gap(px(12.)) + .items_center() + .pb(px(8.)) + .child( + kit::search_field(&filter, &tk) + .w(px(240.)) + .capture_key_down(cx.listener(move |this, ev: &KeyDownEvent, window, cx| { + let key = ev.keystroke.key.as_str(); + match key { + "down" | "up" if !visible.is_empty() => { + let current = this.active_settings().and_then(|s| s.ssh_open); + let at = + current.and_then(|id| visible.iter().position(|v| *v == id)); + let next = match (at, key) { + (None, _) => 0, + (Some(i), "down") => (i + 1).min(visible.len() - 1), + (Some(i), _) => i.saturating_sub(1), + }; + if this.active_settings().is_some_and(|s| s.ssh_form.is_none()) { + if let Some(s) = this.active_settings_mut() { + s.ssh_open = Some(visible[next]); + } + } + cx.stop_propagation(); + cx.notify(); + } + "escape" => { + let filter = this.active_settings().map(|s| s.ssh_filter.clone()); + if let Some(filter) = filter + && !filter.read(cx).value().is_empty() + { + filter.update(cx, |f, cx| f.set_value("", window, cx)); + cx.stop_propagation(); + } + } + _ => {} + } + })), + ) + .child(div().flex_1()) + .child( + kit::button( + "ssh-import-config", + t(L10nKey::SettingsImportFromSshConfig), + BtnKind::Link, + ) + .text_size(fs(12.5)) + .on_click( + cx.listener(|this, _, window, cx| this.import_ssh_config_profiles(window, cx)), + ), + ) + .child( + kit::button( + "ssh-add-host", + t(L10nKey::SettingsAddHost), + BtnKind::Secondary, + ) + .icon("icons/settings/plus.svg") + .dimmed(adding.is_some()) + .on_click(cx.listener(|this, _, window, cx| { + if this + .active_settings() + .and_then(|s| s.ssh_form.as_ref()) + .is_some_and(|f| { + !cx.global::() + .ssh_profiles + .iter() + .any(|p| p.id == f.editing) + }) + { + return; + } + let filter = this.active_settings().map(|s| s.ssh_filter.clone()); + if let Some(filter) = filter { + filter.update(cx, |f, cx| f.set_value("", window, cx)); + } + this.add_new_profile(window, cx); + })), + ); + + let mut list = v_flex() + .id("ssh-host-list") + .mx(px(-10.)) + .px(px(10.)) + .when(!query.is_empty() || show_all, |l| { + l.max_h(px(360.)).overflow_y_scroll() + }); + if let Some(id) = adding { + list = list.child(self.render_host_row(None, id, cx)); + } + for line in lines { + list = match line { + HostLine::Head { + key, + count, + collapsed, + } => list.child(self.render_host_group_head(&key, count, collapsed, cx)), + HostLine::Host(p) => list.child(self.render_host_row(Some(&p), p.id, cx)), + }; + } + + let empty = visible_is_empty(&profiles, &query) && adding.is_none(); + let footer = if !query.is_empty() { + empty.then(|| { + div() + .h(px(40.)) + .flex() + .items_center() + .text_color(tk.k35) + .child(t_fmt(L10nKey::SettingsNoHostsMatch, &[("query", &query)])) + .into_any_element() + }) + } else if total == 0 && adding.is_none() { + Some( + div() + .h(px(40.)) + .flex() + .items_center() + .text_color(tk.k35) + .child(t(L10nKey::SettingsNoHostsYet)) + .into_any_element(), + ) + } else if rest > 0 || show_all { + Some( + h_flex() + .h(px(36.)) + .mt(px(6.)) + .gap(px(8.)) + .items_center() + .text_size(fs(12.)) + .text_color(tk.k45) + .child(if show_all { + t_fmt( + L10nKey::SettingsHostsFromFiles, + &[("count", &total.to_string()), ("files", &files.to_string())], + ) + } else { + t_plural(L10nKey::SettingsMoreHosts, rest, &[]) + }) + .child( + kit::button( + "ssh-show-all", + if show_all { + t(L10nKey::SettingsShowRecentOnly) + } else { + t(L10nKey::SettingsShowAll) + }, + BtnKind::Link, + ) + .on_click(cx.listener(|this, _, _w, cx| { + if let Some(s) = this.active_settings_mut() { + s.ssh_show_all = !s.ssh_show_all; + } + cx.notify(); + })), + ) + .into_any_element(), + ) + } else { + None + }; + + self.settings_group( + Some(t(L10nKey::SettingsHosts)), + Some(t(L10nKey::SettingsHostsDesc).to_string()), + [v_flex() + .pt(px(2.)) + .child(toolbar) + .child(list) + .children(footer) + .into_any_element()], + cx, + ) + } + + fn render_host_group_head( + &self, + key: &str, + count: usize, + collapsed: bool, + cx: &mut Context, + ) -> AnyElement { + let tk = Tk::of(cx); + let owned = key.to_string(); + h_flex() + .id(SharedString::from(format!("ssh-group-{key}"))) + .h(px(34.)) + .flex_shrink_0() + .items_end() + .pb(px(7.)) + .gap(px(6.)) + .cursor_pointer() + .text_size(fs(11.5)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(tk.heading) + .hover(move |s| s.text_color(tk.fg)) + .child( + div().mb(px(1.)).child( + Icon::empty() + .path(if collapsed { + "icons/settings/chevron-right.svg" + } else { + "icons/settings/chevron-down.svg" + }) + .size(px(9.)), + ), + ) + .child( + div() + .flex_1() + .truncate() + .child(ssh_group_label(key).to_string()), + ) + .child( + div() + .font_weight(FontWeight::NORMAL) + .text_color(tk.k35) + .child(count.to_string()), + ) + .on_click(cx.listener(move |this, _, _w, cx| this.toggle_ssh_group(owned.clone(), cx))) + .into_any_element() + } + + /// One host: the row, and under it either the host's details or, while it + /// is being edited, the editor. `p` is `None` for a host not saved yet. + fn render_host_row( + &self, + p: Option<&SshProfile>, + id: Uuid, + cx: &mut Context, + ) -> AnyElement { + let tk = Tk::of(cx); + let Some(s) = self.active_settings() else { + return div().into_any_element(); + }; + let editing = s.ssh_form.as_ref().is_some_and(|f| f.editing == id); + let open = editing || s.ssh_open == Some(id); + let live = self.live_ssh_profiles(cx).contains(&id); + let dirty = editing && self.ssh_form_dirty(cx); + + // While editing, the row shows what the form would save. + let (title, address) = match (editing, p) { + (true, _) => { + let form = s.ssh_form.as_ref().unwrap(); + let name = form.name.read(cx).value().trim().to_string(); + let host = form.host.read(cx).value().trim().to_string(); + let user = form.user.read(cx).value().trim().to_string(); + let port = form.port.read(cx).value().trim().to_string(); + let jump = form.jump.read(cx).value().trim().to_string(); + let mut addr = String::new(); + if !user.is_empty() { + addr.push_str(&user); + addr.push('@'); + } + addr.push_str(if host.is_empty() { "…" } else { &host }); + if !port.is_empty() && port != "22" { + addr.push(':'); + addr.push_str(&port); + } + if !jump.is_empty() { + addr.push_str(&format!(" via {jump}")); + } + let host_empty = host.is_empty(); + let title = match (name.is_empty(), host_empty) { + (false, _) => name, + (true, false) => host, + (true, true) => t(L10nKey::SettingsNewHost).to_string(), + }; + ( + title, + if host_empty { + "user@hostname".to_string() + } else { + addr + }, + ) + } + (false, Some(p)) => (host_title(p), host_address(p, cx)), + (false, None) => (t(L10nKey::SettingsNewHost).to_string(), String::new()), + }; + let blank_title = editing && p.is_none() && title == t(L10nKey::SettingsNewHost); + let (meta, meta_color) = if dirty { + (t(L10nKey::SettingsUnsaved).to_string(), tk.warn_text) + } else if live { + (t(L10nKey::SettingsLive).to_string(), tk.ok) + } else { + let used = cx + .global::() + .ssh_profile_frecency + .get(&id) + .map(|u| u.last_used) + .filter(|&t| t > 0); + let text = match (used, p) { + (_, None) => String::new(), + (Some(then), _) => { + crate::ui::home::relative_time(crate::core::config::unix_now(), then) + } + (None, _) => t(L10nKey::SettingsNever).to_string(), + }; + (text, tk.k4) + }; + + let head = div() + .id(SharedString::from(format!("ssh-host-{}", id.as_u128()))) + .h(px(40.)) + .px(px(10.)) + .flex() + .items_center() + .gap(px(12.)) + .rounded(px(8.)) + .cursor_pointer() + .when(!open, |r| r.hover(move |s| s.bg(tk.k04))) + .child( + v_flex() + .flex_1() + .min_w_0() + .gap(px(1.)) + .child( + div() + .line_height(px(17.)) + .truncate() + .when(open, |d| d.font_weight(FontWeight::MEDIUM)) + .text_color(if blank_title { tk.k4 } else { tk.fg }) + .child(title), + ) + .child( + div() + .font_family(Tk::mono(cx)) + .text_size(fs(11.)) + .line_height(px(15.)) + .text_color(tk.k45) + .truncate() + .child(address), + ), + ) + .child( + div() + .flex_shrink_0() + .whitespace_nowrap() + .text_size(fs(12.)) + .text_color(meta_color) + .child(meta), + ) + .child( + div().size(px(10.)).flex_shrink_0().child( + Icon::empty() + .path(if open { + "icons/settings/chevron-down.svg" + } else { + "icons/settings/chevron-right.svg" + }) + .size(px(10.)) + .text_color(tk.k35), + ), + ) + .on_click(cx.listener(move |this, _, _w, cx| { + if this + .active_settings() + .and_then(|s| s.ssh_form.as_ref()) + .is_some_and(|f| f.editing == id) + { + return; + } + if let Some(s) = this.active_settings_mut() { + s.ssh_open = if s.ssh_open == Some(id) { + None + } else { + Some(id) + }; + } + cx.notify(); + })); + + let body = if editing { + Some(self.render_host_editor(p.is_some(), cx)) + } else if open { + p.map(|p| self.render_host_details(p, cx)) + } else { + None + }; + v_flex() + .flex_shrink_0() + .mx(px(-10.)) + .rounded(px(8.)) + .when(open, |d| d.bg(tk.k04)) + .child(head) + .children(body) + .into_any_element() + } + + fn render_host_details(&self, p: &SshProfile, cx: &mut Context) -> AnyElement { + let tk = Tk::of(cx); + let id = p.id; + let cfg = cx.global::(); + let jump = p.jump_host.and_then(|j| { + cfg.ssh_profiles + .iter() + .find(|q| q.id == j) + .map(|q| host_title(q)) + }); + let fields: Vec<(&str, String)> = [ + ("HostName", Some(p.host.clone())), + ( + "User", + Some(if p.user.is_empty() { + "$USER".to_string() + } else { + p.user.clone() + }), + ), + ("Port", Some(p.port.to_string())), + ("IdentityFile", p.identity_files.first().cloned()), + ("ProxyJump", jump), + ( + t(L10nKey::SettingsDefinedIn), + Some(ssh_group_label(ssh_group_key(p)).to_string()), + ), + ] + .into_iter() + .filter_map(|(k, v)| v.filter(|v| !v.is_empty()).map(|v| (k, v))) + .collect(); + let copied = self.active_settings().and_then(|s| s.ssh_copied) == Some(id); + let command = ssh_command(p); + let mono = Tk::mono(cx); + v_flex() + .gap(px(14.)) + .px(px(10.)) + .pt(px(4.)) + .pb(px(14.)) + .child( + v_flex() + .gap(px(6.)) + .text_size(fs(12.)) + .children(fields.into_iter().map(|(k, v)| { + h_flex() + .line_height(px(17.)) + .child( + div() + .w(px(96.)) + .flex_shrink_0() + .text_color(tk.k45) + .child(k.to_string()), + ) + .child( + div() + .flex_1() + .min_w_0() + .truncate() + .font_family(mono.clone()) + .text_size(fs(11.5)) + .text_color(tk.fg) + .child(v), + ) + })), + ) + .child( + h_flex() + .gap(px(8.)) + .items_center() + .child( + kit::button( + "ssh-host-connect", + t(L10nKey::SettingsConnectInNewTab), + BtnKind::Primary, + ) + .on_click(cx.listener( + move |this, _, window, cx| { + this.close_settings_then(window, cx, move |this, window, cx| { + this.connect_ssh_profile(id, window, cx) + }); + }, + )), + ) + .child( + kit::button( + "ssh-host-edit", + t(L10nKey::SettingsEditHost), + BtnKind::Secondary, + ) + .on_click(cx.listener( + move |this, _, window, cx| { + if let Some(profile) = cx + .global::() + .ssh_profiles + .iter() + .find(|p| p.id == id) + .cloned() + { + this.ssh_form_load(&profile, window, cx); + } + }, + )), + ) + .child(div().flex_1()) + .child( + kit::button( + "ssh-host-copy", + if copied { + t(L10nKey::SettingsCopied) + } else { + t(L10nKey::SettingsCopySshCommand) + }, + BtnKind::Link, + ) + .on_click(cx.listener(move |this, _, _w, cx| { + cx.write_to_clipboard(gpui::ClipboardItem::new_string(command.clone())); + if let Some(s) = this.active_settings_mut() { + s.ssh_copied = Some(id); + } + cx.notify(); + cx.spawn(async move |this, cx| { + smol::Timer::after(std::time::Duration::from_millis(1500)).await; + let _ = this.update(cx, |this, cx| { + if let Some(s) = this.active_settings_mut() + && s.ssh_copied == Some(id) + { + s.ssh_copied = None; + cx.notify(); + } + }); + }) + .detach(); + })), + ), + ) + .into_any_element() + } + + fn render_host_editor(&self, saved: bool, cx: &mut Context) -> AnyElement { + let tk = Tk::of(cx); + let Some(form) = self.active_settings().and_then(|s| s.ssh_form.as_ref()) else { + return div().into_any_element(); + }; + let id = form.editing; + let confirm_remove = self.active_settings().is_some_and(|s| s.ssh_confirm_remove); + let (_, errors) = self.ssh_form_collect(cx).unzip(); + let errors = errors.unwrap_or_default(); + let dirty = self.ssh_form_dirty(cx); + // A brand-new host is not told it needs a host before anyone had the + // chance to type one; a malformed value says so at once. + let core_blank = form.core_is_blank(cx); + let host_error = errors.host.as_ref().filter(|_| !core_blank); + let error = host_error + .or(errors.port.as_ref()) + .or(errors.jump.as_ref()) + .or(errors.socks.as_ref()) + .or(errors.http.as_ref()) + .map(|e| e.message()); + let can_save = errors.is_empty() && (dirty || !saved); + + let field = |label: &'static str, input: &Entity, bad: bool| { + let focused = self.settings_input_focused(input, cx); + h_flex() + .items_center() + .child( + div() + .w(px(SSH_LABEL_W)) + .flex_shrink_0() + .text_size(fs(12.)) + .text_color(tk.k45) + .child(label), + ) + .child( + kit::text_field(input, focused, bad, &tk, cx) + .bg(tk.page) + .text_size(fs(11.5)) + .flex_1() + .max_w(px(FORM_FIELD_W)), + ) + }; + let fields = v_flex() + .gap(px(6.)) + .child(field("Alias", &form.name, false)) + .child(field("HostName", &form.host, host_error.is_some())) + .child(field("User", &form.user, false)) + .child(field("Port", &form.port, errors.port.is_some())) + .child(field("IdentityFile", &form.identity_files, false)) + .child(field("ProxyJump", &form.jump, errors.jump.is_some())); + + v_flex() + .gap(px(14.)) + .px(px(10.)) + .pt(px(4.)) + .pb(px(14.)) + .capture_key_down(cx.listener(move |this, ev: &KeyDownEvent, window, cx| { + match ev.keystroke.key.as_str() { + "enter" => { + this.save_host_form(window, cx); + cx.stop_propagation(); + } + "escape" => { + this.cancel_ssh_form(cx); + cx.stop_propagation(); + } + _ => {} + } + })) + .child(fields) + .when_some(error, |v, e| { + v.child(div().text_size(fs(12.)).text_color(tk.danger).child(e)) + }) + .child( + h_flex() + .gap(px(8.)) + .items_center() + .child( + kit::button( + "ssh-form-save", + if saved { + t(L10nKey::Save) + } else { + t(L10nKey::SettingsAddHost) + }, + BtnKind::Primary, + ) + .dimmed(!can_save) + .on_click( + cx.listener(|this, _, window, cx| this.save_host_form(window, cx)), + ), + ) + .child( + kit::button("ssh-form-cancel", t(L10nKey::Cancel), BtnKind::Secondary) + .on_click(cx.listener(|this, _, _w, cx| this.cancel_ssh_form(cx))), + ) + .child( + div() + .pl(px(4.)) + .text_size(fs(11.5)) + .text_color(tk.k4) + .child(t(L10nKey::SettingsStoredInTty7)), + ) + .child(div().flex_1()) + .when(saved, |r| { + r.child( + kit::button( + "ssh-form-remove", + if confirm_remove { + t(L10nKey::SettingsClickAgainToRemove) + } else { + t(L10nKey::SettingsRemoveHost) + }, + if confirm_remove { + BtnKind::Danger + } else { + BtnKind::Link + }, + ) + .on_click(cx.listener( + move |this, _, _w, cx| { + let confirmed = this + .active_settings() + .is_some_and(|s| s.ssh_confirm_remove); + if confirmed { + this.delete_profile_confirmed(id, cx); + } else if let Some(s) = this.active_settings_mut() { + s.ssh_confirm_remove = true; + cx.notify(); + } + }, + )), + ) + }), + ) + .into_any_element() + } + + fn save_host_form(&mut self, window: &mut Window, cx: &mut Context) { + if let Some(id) = self.save_editing_profile(window, cx) { + if let Some(s) = self.active_settings_mut() { + s.ssh_form = None; + s.ssh_open = Some(id); + s.ssh_confirm_remove = false; + } + cx.notify(); + } else { + cx.notify(); + } + } +} + +fn host_title(p: &SshProfile) -> String { + if p.name.is_empty() { + to_connect_string(p) + } else { + p.name.clone() + } +} + +/// `user@host:port via jump`, the way the row's second line reads. +fn host_address(p: &SshProfile, cx: &App) -> String { + let mut addr = String::new(); + if !p.user.is_empty() { + addr.push_str(&p.user); + addr.push('@'); + } + addr.push_str(&p.host); + if p.port != DEFAULT_SSH_PORT { + addr.push_str(&format!(":{}", p.port)); + } + if let Some(jump) = p.jump_host.and_then(|j| { + cx.global::() + .ssh_profiles + .iter() + .find(|q| q.id == j) + .map(host_title) + }) { + addr.push_str(&format!(" via {jump}")); + } + addr +} + +/// The command a terminal elsewhere would reach this host with. +fn ssh_command(p: &SshProfile) -> String { + let mut cmd = String::from("ssh"); + if p.port != DEFAULT_SSH_PORT { + cmd.push_str(&format!(" -p {}", p.port)); + } + if let Some(key) = p.identity_files.first() { + cmd.push_str(&format!(" -i {key}")); + } + cmd.push(' '); + if !p.user.is_empty() { + cmd.push_str(&p.user); + cmd.push('@'); + } + cmd.push_str(&p.host); + cmd +} + +fn visible_is_empty(profiles: &[SshProfile], query: &str) -> bool { + !profiles.iter().any(|p| ssh_row_matches(p, query)) +} diff --git a/src/ui/settings/kit.rs b/src/ui/settings/kit.rs new file mode 100644 index 00000000..2058fcf6 --- /dev/null +++ b/src/ui/settings/kit.rs @@ -0,0 +1,804 @@ +//! The settings page's own controls. +//! +//! Settings is drawn to one design, and that design is quieter than the rest +//! of the app: ink at a handful of fixed strengths instead of the theme's named +//! roles, hairline rings instead of borders, and controls that sit on the page +//! rather than on cards. Everything here derives from the active theme's +//! foreground and background, so the page follows every theme — light, dark, +//! and the tinted ones in between — without a palette of its own. +//! +//! Sizes are in rems off a 16px base, written as the pixel sizes the design +//! calls for, so the page still grows with the interface font. + +use std::rc::Rc; + +use gpui::{ + AnyElement, App, BoxShadow, ClickEvent, Div, ElementId, FontWeight, Hsla, IntoElement, + MouseButton, Rems, SharedString, Stateful, Window, div, point, prelude::*, px, rems, +}; +use gpui_component::input::{Input, InputState}; +use gpui_component::{ActiveTheme as _, Icon, h_flex, v_flex}; + +/// A size from the design, in pixels at the default 16px interface font. +pub(crate) fn fs(px_at_16: f32) -> Rems { + rems(px_at_16 / 16.) +} + +/// The page's ink at the strengths the design uses, plus the few surfaces it +/// lifts off the page. +#[derive(Clone, Copy)] +pub(crate) struct Tk { + pub dark: bool, + pub fg: Hsla, + pub page: Hsla, + pub k04: Hsla, + pub k05: Hsla, + pub k06: Hsla, + pub k07: Hsla, + pub k08: Hsla, + pub k15: Hsla, + pub k3: Hsla, + pub k35: Hsla, + pub k4: Hsla, + pub k45: Hsla, + pub k5: Hsla, + pub k6: Hsla, + /// A group heading: quieter than a label, but still read at a glance. + pub heading: Hsla, + /// A nav item at rest. + pub nav: Hsla, + /// A raised button's fill. + pub btn: Hsla, + /// A popover's fill. + pub menu: Hsla, + /// A switch or slider knob at rest. + pub knob: Hsla, + /// The chosen cell of a segmented control. + pub chip: Hsla, + pub warn: Hsla, + pub warn_text: Hsla, + pub danger: Hsla, + pub ok: Hsla, +} + +fn lift(c: Hsla, by: f32) -> Hsla { + Hsla { + l: (c.l + by).clamp(0., 1.), + ..c + } +} + +impl Tk { + pub(crate) fn of(cx: &App) -> Self { + let theme = cx.theme(); + let dark = theme.is_dark(); + let fg = theme.foreground; + let page = theme.background; + let a = |light: f32, dark_a: f32| fg.opacity(if dark { dark_a } else { light }); + let white = gpui::white(); + Self { + dark, + fg, + page, + k04: a(0.04, 0.055), + k05: a(0.05, 0.07), + k06: a(0.06, 0.08), + k07: a(0.07, 0.09), + k08: a(0.08, 0.08), + k15: a(0.15, 0.16), + k3: a(0.3, 0.3), + k35: a(0.35, 0.36), + k4: a(0.4, 0.45), + k45: a(0.45, 0.5), + k5: a(0.5, 0.55), + k6: a(0.6, 0.65), + heading: a(0.9, 0.9), + nav: a(0.82, 0.8), + btn: if dark { fg.opacity(0.1) } else { white }, + menu: if dark { lift(page, 0.06) } else { white }, + knob: if dark { fg } else { white }, + chip: if dark { fg.opacity(0.16) } else { white }, + warn: gpui::rgb(0xe0a100).into(), + warn_text: gpui::rgb(0xb07d00).into(), + danger: gpui::rgb(0xd93025).into(), + ok: gpui::rgb(0x34a853).into(), + } + } + + /// The hairline ring and the faint drop a raised control sits on. + pub(crate) fn raised(&self) -> Vec { + if self.dark { + vec![ring(self.fg.opacity(0.1), 0.5, false)] + } else { + vec![ + ring(gpui::black().opacity(0.08), 0.5, false), + drop(gpui::black().opacity(0.06), 1., 2., 0.), + ] + } + } + + /// The same, a step firmer, for a hovered raised control. + pub(crate) fn raised_hover(&self) -> Vec { + if self.dark { + vec![ring(self.fg.opacity(0.2), 0.5, false)] + } else { + vec![ + ring(gpui::black().opacity(0.16), 0.5, false), + drop(gpui::black().opacity(0.08), 1., 2., 0.), + ] + } + } + + pub(crate) fn popover(&self) -> Vec { + if self.dark { + vec![ + ring(self.fg.opacity(0.12), 0.5, false), + drop(gpui::black().opacity(0.6), 16., 40., -8.), + ] + } else { + vec![ + ring(gpui::black().opacity(0.12), 0.5, false), + drop(gpui::black().opacity(0.22), 16., 40., -8.), + ] + } + } + + pub(crate) fn mono(cx: &App) -> SharedString { + cx.theme().mono_font_family.clone() + } +} + +pub(crate) fn ring(color: Hsla, width: f32, inset: bool) -> BoxShadow { + BoxShadow { + color, + offset: point(px(0.), px(0.)), + blur_radius: px(0.), + spread_radius: px(width), + inset, + } +} + +pub(crate) fn drop(color: Hsla, y: f32, blur: f32, spread: f32) -> BoxShadow { + BoxShadow { + color, + offset: point(px(0.), px(y)), + blur_radius: px(blur), + spread_radius: px(spread), + inset: false, + } +} + +type ClickHandler = Rc; +type ToggleHandler = Rc; + +/// An on/off switch: ink when on, a hairline track when off. +#[derive(IntoElement)] +pub(crate) struct Switch { + id: ElementId, + on: bool, + disabled: bool, + small: bool, + handler: Option, +} + +pub(crate) fn switch(id: impl Into) -> Switch { + Switch { + id: id.into(), + on: false, + disabled: false, + small: false, + handler: None, + } +} + +impl Switch { + pub(crate) fn checked(mut self, on: bool) -> Self { + self.on = on; + self + } + pub(crate) fn disabled(mut self, disabled: bool) -> Self { + self.disabled = disabled; + self + } + pub(crate) fn small(mut self) -> Self { + self.small = true; + self + } + pub(crate) fn on_click(mut self, f: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self { + self.handler = Some(Rc::new(f)); + self + } +} + +impl RenderOnce for Switch { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let tk = Tk::of(cx); + let (w, h, knob) = if self.small { + (26., 16., 12.) + } else { + (30., 18., 14.) + }; + let on = self.on; + let left = if on { w - knob - 2. } else { 2. }; + div() + .id(self.id) + .flex_shrink_0() + .relative() + .w(px(w)) + .h(px(h)) + .rounded(px(h / 2.)) + .bg(if on { tk.fg } else { tk.k15 }) + .when(self.disabled, |d| d.opacity(0.4)) + .child( + div() + .absolute() + .top(px(2.)) + .left(px(left)) + .size(px(knob)) + .rounded_full() + .bg(if on { tk.page } else { tk.knob }) + .shadow(vec![drop(gpui::black().opacity(0.2), 1., 2., 0.)]), + ) + .when_some(self.handler.filter(|_| !self.disabled), |d, handler| { + d.cursor_pointer() + .on_click(move |_, window, cx| handler(&!on, window, cx)) + }) + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum BtnKind { + /// A raised button on the page. + Secondary, + /// Solid ink: the one action a block exists for. + Primary, + /// Text that darkens on hover, for actions beside other actions. + Link, + /// A link in red, for the destructive one. + Danger, +} + +#[derive(IntoElement)] +pub(crate) struct Btn { + id: ElementId, + label: SharedString, + kind: BtnKind, + disabled: bool, + dimmed: bool, + icon: Option, + size: Option, + handler: Option, +} + +pub(crate) fn button( + id: impl Into, + label: impl Into, + kind: BtnKind, +) -> Btn { + Btn { + id: id.into(), + label: label.into(), + kind, + disabled: false, + dimmed: false, + icon: None, + size: None, + handler: None, + } +} + +impl Btn { + pub(crate) fn disabled(mut self, disabled: bool) -> Self { + self.disabled = disabled; + self + } + /// Clickable, but drawn at rest — a Save with nothing to save yet. + pub(crate) fn dimmed(mut self, dimmed: bool) -> Self { + self.dimmed = dimmed; + self + } + pub(crate) fn icon(mut self, path: impl Into) -> Self { + self.icon = Some(path.into()); + self + } + pub(crate) fn text_size(mut self, size: Rems) -> Self { + self.size = Some(size); + self + } + pub(crate) fn on_click( + mut self, + f: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static, + ) -> Self { + self.handler = Some(Rc::new(f)); + self + } +} + +impl RenderOnce for Btn { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let tk = Tk::of(cx); + let kind = self.kind; + let base = h_flex() + .id(self.id) + .flex_shrink_0() + .items_center() + .gap(px(6.)) + .whitespace_nowrap(); + let el = match kind { + BtnKind::Secondary => base + .h(px(26.)) + .px(px(12.)) + .when(self.icon.is_some(), |b| b.pl(px(9.)).pr(px(11.))) + .rounded(px(6.)) + .bg(tk.btn) + .shadow(tk.raised()) + .text_size(self.size.unwrap_or(fs(12.5))) + .text_color(tk.fg) + .when(!self.disabled, |b| { + b.hover(move |s| s.shadow(tk.raised_hover())) + .active(move |s| s.bg(tk.k05)) + }), + BtnKind::Primary => base + .h(px(26.)) + .px(px(12.)) + .rounded(px(6.)) + .bg(tk.fg) + .text_size(self.size.unwrap_or(fs(12.5))) + .font_weight(FontWeight::MEDIUM) + .text_color(tk.page) + .when(!self.disabled, |b| b.hover(|s| s.opacity(0.88))), + BtnKind::Link | BtnKind::Danger => base + .text_size(self.size.unwrap_or(fs(12.))) + .text_color(if kind == BtnKind::Danger { + tk.danger + } else { + tk.k6 + }) + .when(!self.disabled, |b| { + b.hover(move |s| { + s.text_color(if kind == BtnKind::Danger { + tk.danger + } else { + tk.fg + }) + }) + }), + }; + el.when(self.disabled, |b| b.opacity(0.45)) + .when(self.dimmed && !self.disabled, |b| b.opacity(0.55)) + .when_some(self.icon, |b, path| { + b.child(Icon::empty().path(path).size(px(10.)).text_color(tk.k6)) + }) + .child(self.label) + .when_some(self.handler.filter(|_| !self.disabled), |b, handler| { + b.cursor_pointer() + .on_click(move |ev, window, cx| handler(ev, window, cx)) + }) + } +} + +/// A key on a keycap: `⌘`, `T`, `Space`. +pub(crate) fn keycap(key: impl Into, tk: &Tk) -> Div { + div() + .flex_shrink_0() + .min_w(px(20.)) + .h(px(20.)) + .px(px(5.)) + .rounded(px(4.)) + .bg(tk.k05) + .shadow(vec![BoxShadow { + color: tk.k15, + offset: point(px(0.), px(-0.5)), + blur_radius: px(0.), + spread_radius: px(0.), + inset: true, + }]) + .flex() + .items_center() + .justify_center() + .text_size(fs(11.5)) + .text_color(tk.k6) + .child(key.into()) +} + +/// A search glass the size the design draws it beside a field. +pub(crate) fn search_glass(size: f32, tk: &Tk) -> Icon { + Icon::empty() + .path("icons/settings/search.svg") + .size(px(size)) + .text_color(tk.k35) +} + +/// A search field with a hairline ring, for filtering a list on the page. +pub(crate) fn search_field(input: &gpui::Entity, tk: &Tk) -> Div { + h_flex() + .h(px(26.)) + .px(px(8.)) + .gap(px(6.)) + .items_center() + .rounded(px(6.)) + .shadow(vec![ring(tk.k15, 0.5, true)]) + .child(search_glass(10., tk)) + .child( + div() + .flex_1() + .min_w_0() + .text_size(fs(12.5)) + .child(Input::new(input).appearance(false).px_0().py_0().h(px(24.))), + ) +} + +/// A text field the way the page draws one: a hairline ring on the page, in +/// the terminal's monospace, with a firmer ring while it has focus. +pub(crate) fn text_field( + input: &gpui::Entity, + focused: bool, + invalid: bool, + tk: &Tk, + cx: &App, +) -> Div { + let ring_color = if invalid { + tk.danger + } else if focused { + tk.k45 + } else { + tk.k15 + }; + div() + .h(px(26.)) + .px(px(10.)) + .flex() + .items_center() + .rounded(px(6.)) + .shadow(vec![ring( + ring_color, + if focused || invalid { 1. } else { 0.5 }, + true, + )]) + .font_family(Tk::mono(cx)) + .text_size(fs(12.)) + .text_color(tk.fg) + .child( + div() + .flex_1() + .min_w_0() + .child(Input::new(input).appearance(false).px_0().py_0().h(px(24.))), + ) +} + +/// A group's heading and, when it has one, the sentence under it. +pub(crate) fn section_head(title: &str, desc: Option, tk: &Tk) -> Div { + v_flex() + .gap(px(3.)) + .pb(px(8.)) + .child( + div() + .text_size(fs(11.5)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(tk.heading) + .child(title.to_string()), + ) + .when_some(desc.filter(|d| !d.is_empty()), |col, desc| { + col.child( + div() + .text_size(fs(12.)) + .line_height(px(17.)) + .text_color(tk.k6) + .child(desc), + ) + }) +} + +/// The trigger of a dropdown: a raised button with the current value, an +/// optional mark before it, and a chevron. +pub(crate) fn select_trigger( + id: impl Into, + label: impl Into, + leading: Option, + open: bool, + tk: &Tk, +) -> Stateful
{ + h_flex() + .id(id) + .h(px(26.)) + .min_w(px(148.)) + .max_w(px(260.)) + .pl(px(if leading.is_some() { 8. } else { 10. })) + .pr(px(7.)) + .gap(px(8.)) + .items_center() + .rounded(px(6.)) + .bg(if open { tk.k05 } else { tk.btn }) + .shadow(tk.raised()) + .hover(move |s| s.shadow(tk.raised_hover())) + .cursor_pointer() + .text_size(fs(12.5)) + .text_color(tk.fg) + .whitespace_nowrap() + .children(leading) + .child(div().flex_1().min_w_0().truncate().child(label.into())) + .child(chevron_down(tk)) +} + +pub(crate) fn chevron_down(tk: &Tk) -> Icon { + Icon::empty() + .path("icons/settings/chevron-down.svg") + .size(px(10.)) + .text_color(tk.k45) +} + +pub(crate) fn check_mark(visible: bool, tk: &Tk) -> Div { + div().size(px(12.)).flex_shrink_0().when(visible, |d| { + d.child( + Icon::empty() + .path("icons/settings/check.svg") + .size(px(12.)) + .text_color(tk.fg), + ) + }) +} + +/// A popover's surface. +pub(crate) fn menu_panel(tk: &Tk) -> Div { + v_flex() + .p(px(4.)) + .gap(px(1.)) + .rounded(px(8.)) + .bg(tk.menu) + .shadow(tk.popover()) + .text_size(fs(12.5)) + .text_color(tk.fg) +} + +/// One pickable row in a popover menu. +pub(crate) fn menu_row(id: impl Into, highlighted: bool, tk: &Tk) -> Stateful
{ + h_flex() + .id(id) + .flex_shrink_0() + .h(px(26.)) + .pl(px(6.)) + .pr(px(12.)) + .gap(px(6.)) + .items_center() + .rounded(px(5.)) + .whitespace_nowrap() + .cursor_pointer() + .when(highlighted, |r| r.bg(tk.k06)) + .hover(move |s| s.bg(tk.k06)) +} + +pub(crate) fn menu_heading(label: impl Into, tk: &Tk) -> Div { + div() + .h(px(24.)) + .px(px(8.)) + .flex() + .items_center() + .text_size(fs(11.)) + .font_weight(FontWeight::MEDIUM) + .text_color(tk.k45) + .child(label.into()) +} + +pub(crate) fn menu_separator(tk: &Tk) -> Div { + div().h(px(1.)).mx(px(6.)).my(px(4.)).bg(tk.k08) +} + +/// Where a trigger's popover hangs: under the trigger, its right edge on the +/// trigger's (or its left on the trigger's), painted over the rest of the page +/// and pushed back inside the window when it would run off it. +pub(crate) fn popover_below(align_right: bool, gap: f32, content: impl IntoElement) -> Div { + let anchor = if align_right { + gpui::Anchor::TopRight + } else { + gpui::Anchor::TopLeft + }; + div() + .absolute() + .top(px(26. + gap)) + .when(align_right, |d| d.right_0()) + .when(!align_right, |d| d.left_0()) + .child( + gpui::deferred( + gpui::anchored() + .anchor(anchor) + .snap_to_window_with_margin(px(8.)) + .child( + div() + .occlude() + // A click inside the popover is not a click on the + // page under it, which would close it. + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .child(content), + ), + ) + .with_priority(2), + ) +} + +/// The stepper: − value +, one raised control with hairline dividers. +pub(crate) struct Stepper { + pub value: String, + pub unit: String, + pub can_dec: bool, + pub can_inc: bool, +} + +pub(crate) fn stepper( + id: &'static str, + s: Stepper, + tk: &Tk, + on_dec: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static, + on_inc: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static, +) -> AnyElement { + let end = |suffix: &'static str, glyph: &'static str, enabled: bool| { + div() + .id(SharedString::from(format!("{id}-{suffix}"))) + .w(px(28.)) + .h(px(26.)) + .flex() + .items_center() + .justify_center() + .text_size(fs(13.)) + .text_color(tk.k6) + .when(!enabled, |d| d.opacity(0.35)) + .when(enabled, |d| { + d.cursor_pointer().active(move |s| s.bg(tk.k05)) + }) + .child(glyph) + }; + let divider = || div().h(px(14.)).w(px(1.)).bg(tk.k15); + h_flex() + .id(id) + .h(px(26.)) + .items_center() + .rounded(px(6.)) + .bg(tk.btn) + .shadow(tk.raised()) + .child( + end("dec", "−", s.can_dec) + .rounded_l(px(6.)) + .when(s.can_dec, |d| d.on_click(on_dec)), + ) + .child(divider()) + .child( + h_flex() + .min_w(px(52.)) + .px(px(6.)) + .justify_center() + .text_size(fs(12.5)) + .text_color(tk.fg) + .child(s.value) + .child(div().text_color(tk.k4).child(s.unit)), + ) + .child(divider()) + .child( + end("inc", "+", s.can_inc) + .rounded_r(px(6.)) + .when(s.can_inc, |d| d.on_click(on_inc)), + ) + .into_any_element() +} + +/// What a slider is being dragged by; the id tells two sliders apart. +#[derive(Clone)] +pub(crate) struct SliderDrag(pub SharedString); + +impl Render for SliderDrag { + fn render(&mut self, _: &mut Window, _: &mut gpui::Context) -> impl IntoElement { + div() + } +} + +/// A thin track with an ink fill and a raised knob, 148 wide, with its value +/// read out beside it. `on_set` takes the fraction along the track the pointer +/// is at; `on_release` is where a drag's value gets written down for good. +pub(crate) fn slider( + id: impl Into, + fraction: f32, + readout: String, + tk: &Tk, + on_set: Rc, + on_release: Rc, +) -> AnyElement { + let id: SharedString = id.into(); + let f = fraction.clamp(0., 1.); + const W: f32 = 148.; + let frac_at = |bounds: gpui::Bounds, x: gpui::Pixels| -> f32 { + let w = bounds.size.width.as_f32().max(1.); + ((x - bounds.origin.x).as_f32() / w).clamp(0., 1.) + }; + let set_down = on_set.clone(); + let set_move = on_set; + let drag_id = id.clone(); + let release_up = on_release.clone(); + let release_out = on_release; + let bounds = Rc::new(std::cell::Cell::new(gpui::Bounds::::default())); + h_flex() + .gap(px(8.)) + .items_center() + .child( + div() + .id(ElementId::Name(id.clone())) + .relative() + .w(px(W)) + .h(px(18.)) + .cursor_pointer() + .child( + div() + .absolute() + .left_0() + .right_0() + .top(px(8.)) + .h(px(2.)) + .rounded(px(1.)) + .bg(tk.k15), + ) + .child( + div() + .absolute() + .left_0() + .top(px(8.)) + .h(px(2.)) + .w(px(W * f)) + .rounded(px(1.)) + .bg(tk.fg), + ) + .child( + div() + .absolute() + .top(px(2.)) + .left(px(W * f - 7.)) + .size(px(14.)) + .rounded_full() + .bg(tk.knob) + .shadow(vec![ + ring(gpui::black().opacity(0.18), 0.5, false), + drop(gpui::black().opacity(0.18), 1., 3., 0.), + ]), + ) + .child({ + // The track's bounds for a click that never becomes a + // drag: a mouse-down event carries a position but not the + // box it landed in. + let bounds = bounds.clone(); + gpui::canvas(move |b, _, _| bounds.set(b), |_, _, _, _| {}) + .absolute() + .size_full() + }) + .on_mouse_down(MouseButton::Left, { + let bounds = bounds.clone(); + move |ev: &gpui::MouseDownEvent, window, cx| { + set_down(frac_at(bounds.get(), ev.position.x), window, cx); + } + }) + .on_drag(SliderDrag(drag_id), |drag, _, _, cx| { + cx.new(|_| drag.clone()) + }) + .on_drag_move({ + let id = id.clone(); + move |ev: &gpui::DragMoveEvent, window, cx| { + if ev.drag(cx).0 != id { + return; + } + set_move(frac_at(ev.bounds, ev.event.position.x), window, cx); + } + }) + .on_mouse_up(MouseButton::Left, move |_, window, cx| { + release_up(window, cx) + }) + .on_mouse_up_out(MouseButton::Left, move |_, window, cx| { + release_out(window, cx) + }), + ) + .child( + div() + .w(px(40.)) + .flex_shrink_0() + .text_right() + .whitespace_nowrap() + .text_size(fs(12.5)) + .text_color(tk.k6) + .child(readout), + ) + .into_any_element() +} diff --git a/src/ui/settings/pages.rs b/src/ui/settings/pages.rs new file mode 100644 index 00000000..bd305651 --- /dev/null +++ b/src/ui/settings/pages.rs @@ -0,0 +1,1775 @@ +//! The pages that are rows and nothing else: General, the text and window +//! halves of Appearance, Terminal, Keyboard & Mouse, Window & Tabs, and About. + +use std::rc::Rc; + +use super::kit::{self, BtnKind, Stepper, Tk, fs}; +use super::shell::{MenuEntry, SearchOption}; +use super::*; + +impl Tty7App { + pub(crate) fn render_settings_general(&self, cx: &mut Context) -> AnyElement { + let cfg = cx.global::(); + let current_lang = Self::normalize_gui_language(&cfg.gui_language); + let language = self.settings_dropdown( + "settings-language", + crate::ui::i18n::SUPPORTED_LANGUAGES + .iter() + .find(|lang| lang.code == current_lang) + .map(|lang| t(lang.label_key)) + .unwrap_or_default(), + None, + crate::ui::i18n::SUPPORTED_LANGUAGES + .iter() + .map(|lang| { + let code = lang.code; + MenuEntry::item( + t(lang.label_key), + code == current_lang, + move |this, window, cx| this.set_gui_language(code, window, cx), + ) + }) + .collect(), + cx, + ); + let mut first = vec![ + self.settings_row( + t(L10nKey::SettingsLanguage), + t(L10nKey::SettingsLanguageDesc), + language, + cx, + ) + .into_any_element(), + ]; + if cfg!(target_os = "macos") { + let set_default = self + .settings_button( + "set-default-terminal", + t(L10nKey::SettingsDefaultTerminalSet), + cx, + |_, window, cx| { + let message = match crate::core::default_terminal::set_as_default_terminal() + { + Ok(()) => t(L10nKey::SettingsDefaultTerminalSetSuccess).to_string(), + Err(error) => t_fmt( + L10nKey::SettingsDefaultTerminalSetFailed, + &[("error", &error)], + ), + }; + window.push_notification(message, cx); + }, + ) + .into_any_element(); + first.push( + self.settings_row( + t(L10nKey::SettingsDefaultTerminal), + t(L10nKey::SettingsDefaultTerminalDesc), + set_default, + cx, + ) + .into_any_element(), + ); + } + + let cfg = cx.global::(); + let startup_idx = match cfg.startup_mode { + crate::core::config::StartupMode::Normal => 0, + crate::core::config::StartupMode::Maximized => 1, + crate::core::config::StartupMode::Fullscreen => 2, + }; + let restore_session = cfg.restore_session; + let remember_window_size = cfg.remember_window_size; + let show_tray_icon = cfg.show_tray_icon; + let notify_idx = match cfg.notify_on_command_finish { + NotifyMode::Never => 0, + NotifyMode::Unfocused => 1, + NotifyMode::Always => 2, + }; + // Exact-match highlight with a "Custom (Ns)" fallback: a hand-set 20s + // used to light up "30s" (#550). + let (threshold_sel, threshold_custom) = preset_choice( + &NOTIFY_THRESHOLD_BUCKETS, + cfg.notify_threshold_secs, + |secs| format!("{secs}s"), + ); + + let startup = self.segmented( + "wt-startup", + &[ + t(L10nKey::SettingsStartupNormal), + t(L10nKey::SettingsStartupMaximized), + t(L10nKey::SettingsStartupFullscreen), + ], + startup_idx, + cx, + |this, ix, _w, cx| { + let mode = match ix { + 0 => crate::core::config::StartupMode::Normal, + 1 => crate::core::config::StartupMode::Maximized, + _ => crate::core::config::StartupMode::Fullscreen, + }; + this.set_startup_mode(mode, cx); + }, + ); + let remember = self.settings_switch( + "wt-remember-window", + remember_window_size, + cx, + |this, on, _, cx| this.set_remember_window_size(on, cx), + ); + let restore = self.settings_switch( + "wt-restore-session", + restore_session, + cx, + |this, on, _, cx| this.set_restore_session(on, cx), + ); + let tray = self.settings_switch("wt-tray-icon", show_tray_icon, cx, |this, on, _, cx| { + this.set_show_tray_icon(on, cx) + }); + let notify = self.segmented( + "wt-notify", + &[ + t(L10nKey::NotifyModeNever), + t(L10nKey::NotifyModeUnfocused), + t(L10nKey::NotifyModeAlways), + ], + notify_idx, + cx, + |this, ix, _w, cx| { + let mode = match ix { + 0 => NotifyMode::Never, + 1 => NotifyMode::Unfocused, + _ => NotifyMode::Always, + }; + this.set_notify_mode(mode, cx); + }, + ); + let threshold = self.segmented_valued( + "wt-notify-threshold", + &NOTIFY_THRESHOLD_LABELS, + threshold_sel, + threshold_custom, + cx, + |this, ix, _w, cx| { + let secs = NOTIFY_THRESHOLD_BUCKETS + .get(ix) + .copied() + .unwrap_or(Config::default().notify_threshold_secs); + this.set_notify_threshold(secs, cx); + }, + ); + + Self::settings_page([ + self.settings_group(None, None, first, cx), + self.settings_group( + Some(t(L10nKey::SettingsStartupRestore)), + None, + [ + self.settings_row( + t(L10nKey::SettingsStartupWindow), + t(L10nKey::SettingsStartupWindowDesc), + startup, + cx, + ), + self.settings_row( + t(L10nKey::SettingsRememberWindowSize), + t(L10nKey::SettingsRememberWindowSizeDesc), + remember, + cx, + ), + self.settings_row( + t(L10nKey::SettingsRestoreLastLayout), + t(L10nKey::SettingsRestoreLastLayoutDesc), + restore, + cx, + ), + self.settings_row( + t(L10nKey::SettingsShowTrayIcon), + t(L10nKey::SettingsShowTrayIconDesc), + tray, + cx, + ), + ] + .map(IntoElement::into_any_element), + cx, + ), + self.settings_group( + Some(t(L10nKey::SettingsNotifications)), + None, + [ + self.settings_row( + t(L10nKey::SettingsNotifyOnCommandFinish), + t(L10nKey::SettingsNotifyOnCommandFinishDesc), + notify, + cx, + ), + self.settings_row( + t(L10nKey::SettingsNotifyThreshold), + t(L10nKey::SettingsNotifyThresholdDesc), + threshold, + cx, + ), + ] + .map(IntoElement::into_any_element), + cx, + ), + ]) + } + + /// A font menu over every installed family. `default_label` names the + /// first row for the menus whose empty value means "follow something + /// else". + fn font_dropdown( + &self, + id: &'static str, + current: Option<&str>, + default_label: Option<&'static str>, + cx: &mut Context, + commit: impl Fn(&mut Self, String, &mut Window, &mut Context) + 'static, + ) -> AnyElement { + let names = self + .active_settings() + .map(|s| s.font_names.clone()) + .unwrap_or_default(); + let mut options: Vec = Vec::with_capacity(names.len() + 1); + let mut values: Vec = Vec::with_capacity(names.len() + 1); + if let Some(label) = default_label { + options.push(SearchOption { + label: label.into(), + font: None, + }); + values.push(label.to_string()); + } + for name in names.iter() { + options.push(SearchOption { + label: name.clone().into(), + font: Some(name.clone().into()), + }); + values.push(name.clone()); + } + let selected = match current { + Some(name) => values.iter().position(|v| v == name), + None => default_label.map(|_| 0), + }; + let label = current + .map(str::to_string) + .or(default_label.map(str::to_string)) + .unwrap_or_default(); + let values = Rc::new(values); + self.settings_search_dropdown( + id, + label, + Rc::new(options), + selected, + Rc::new(move |this, ix, window, cx| { + if let Some(value) = values.get(ix) { + commit(this, value.clone(), window, cx); + } + }), + cx, + ) + } + + fn stepper_control( + &self, + id: &'static str, + value: String, + unit: &str, + (can_dec, can_inc): (bool, bool), + cx: &mut Context, + step: impl Fn(&mut Self, f32, &mut Context) + 'static, + ) -> AnyElement { + let tk = Tk::of(cx); + let step = Rc::new(step); + let (dec, inc) = (step.clone(), step); + kit::stepper( + id, + Stepper { + value, + unit: unit.to_string(), + can_dec, + can_inc, + }, + &tk, + cx.listener(move |this, _, _w, cx| dec(this, -1., cx)), + cx.listener(move |this, _, _w, cx| inc(this, 1., cx)), + ) + } + + pub(crate) fn render_settings_appearance(&self, cx: &mut Context) -> AnyElement { + use crate::core::config::{ + FONT_SIZE_MAX, FONT_SIZE_MIN, LINE_HEIGHT_MAX, LINE_HEIGHT_MIN, UI_FONT_SIZE_MAX, + UI_FONT_SIZE_MIN, + }; + let cfg = cx.global::(); + let cursor_style = cfg.cursor_style; + let cursor_blink = cfg.cursor_blink; + let font_thicken = cfg.font_thicken; + let font_family = cfg.font_family.clone(); + let font_bold = cfg.font_family_bold.clone(); + let font_italic = cfg.font_family_italic.clone(); + let ui_font = cfg.ui_font_family.clone(); + let font_ligatures = cfg.font_features.as_ref().is_some_and(|features| { + features.is_calt_enabled() == Some(true) + || features + .tag_value_list() + .iter() + .any(|(tag, value)| tag == "liga" && *value != 0) + }); + let font_size = self.font_size; + let line_height = self.line_height; + let ui_font_size = self.ui_font_size(cx); + + let font_family_control = self.font_dropdown( + "font-family", + Some(&font_family), + None, + cx, + |this, name, _w, cx| this.commit_font_family(name, cx), + ); + let font_bold_control = self.font_dropdown( + "font-family-bold", + font_bold.as_deref(), + Some(font_default_label()), + cx, + |this, name, _w, cx| this.commit_font_family_emphasis(true, name, cx), + ); + let font_italic_control = self.font_dropdown( + "font-family-italic", + font_italic.as_deref(), + Some(font_default_label()), + cx, + |this, name, _w, cx| this.commit_font_family_emphasis(false, name, cx), + ); + let ui_font_control = self.font_dropdown( + "ui-font-family", + ui_font.as_deref(), + Some(ui_font_default_label()), + cx, + |this, name, window, cx| this.commit_ui_font_family(name, window, cx), + ); + let font_size_control = self.stepper_control( + "font-size", + format!("{font_size:.0}"), + " pt", + (font_size > FONT_SIZE_MIN, font_size < FONT_SIZE_MAX), + cx, + |this, dir, cx| this.change_font_size(dir * FONT_SIZE_STEP, cx), + ); + let line_height_control = self.stepper_control( + "line-height", + format!("{line_height:.2}"), + "", + (line_height > LINE_HEIGHT_MIN, line_height < LINE_HEIGHT_MAX), + cx, + |this, dir, cx| this.change_line_height(dir * LINE_HEIGHT_STEP, cx), + ); + let ui_font_size_control = self.stepper_control( + "ui-font-size", + format!("{ui_font_size:.0}"), + " pt", + ( + ui_font_size > UI_FONT_SIZE_MIN, + ui_font_size < UI_FONT_SIZE_MAX, + ), + cx, + |this, dir, cx| this.change_ui_font_size(dir * UI_FONT_SIZE_STEP, cx), + ); + let ligatures = + self.settings_switch("font-ligatures", font_ligatures, cx, |this, on, _, cx| { + this.set_font_ligatures(on, cx) + }); + // macOS alone dilates glyph strokes, so elsewhere there is no row. + let thicken_row = cfg!(target_os = "macos").then(|| { + let control = + self.settings_switch("font-thicken", font_thicken, cx, |this, on, _, cx| { + this.set_font_thicken(on, cx) + }); + self.settings_row( + t(L10nKey::SettingsFontThicken), + t(L10nKey::SettingsFontThickenDesc), + control, + cx, + ) + .into_any_element() + }); + + let cursor_idx = match cursor_style { + CursorStyle::Block => 0, + CursorStyle::Bar => 1, + CursorStyle::Underline => 2, + }; + let cursor_style_control = self.segmented( + "cursor-style", + &[ + t(L10nKey::CursorShapeBlock), + t(L10nKey::CursorShapeBar), + t(L10nKey::CursorShapeUnderline), + ], + cursor_idx, + cx, + |this, ix, _w, cx| { + let style = match ix { + 0 => CursorStyle::Block, + 1 => CursorStyle::Bar, + _ => CursorStyle::Underline, + }; + this.set_cursor_style(style, cx); + }, + ); + let blink = self.settings_switch("cursor-blink", cursor_blink, cx, |this, on, _, cx| { + this.set_cursor_blink(on, cx) + }); + + let mut groups = vec![self.render_theme_group(cx)]; + groups.extend(self.render_theme_editor_group(cx)); + groups.push( + self.settings_group( + Some(t(L10nKey::SettingsTerminalFontGroup)), + None, + [ + self.settings_row( + t(L10nKey::SettingsFontFamily), + t(L10nKey::SettingsFontFamilyDesc), + font_family_control, + cx, + ) + .into_any_element(), + self.settings_row( + t(L10nKey::SettingsFontSize), + t(L10nKey::SettingsFontSizeDesc), + font_size_control, + cx, + ) + .into_any_element(), + self.settings_row( + t(L10nKey::SettingsLineHeight), + t(L10nKey::SettingsLineHeightDesc), + line_height_control, + cx, + ) + .into_any_element(), + self.settings_row( + t(L10nKey::SettingsBoldFont), + t(L10nKey::SettingsBoldFontDesc), + font_bold_control, + cx, + ) + .into_any_element(), + self.settings_row( + t(L10nKey::SettingsItalicFont), + t(L10nKey::SettingsItalicFontDesc), + font_italic_control, + cx, + ) + .into_any_element(), + self.settings_row( + t(L10nKey::SettingsFontLigatures), + t(L10nKey::SettingsFontLigaturesDesc), + ligatures, + cx, + ) + .into_any_element(), + ] + .into_iter() + .chain(thicken_row), + cx, + ), + ); + groups.push( + self.settings_group( + Some(t(L10nKey::SettingsInterfaceFontGroup)), + None, + [ + self.settings_row( + t(L10nKey::SettingsUiFontFamily), + t(L10nKey::SettingsUiFontFamilyDesc), + ui_font_control, + cx, + ), + self.settings_row( + t(L10nKey::SettingsUiFontSize), + t(L10nKey::SettingsUiFontSizeDesc), + ui_font_size_control, + cx, + ), + ] + .map(IntoElement::into_any_element), + cx, + ), + ); + groups.push( + self.settings_group( + Some(t(L10nKey::SettingsCursor)), + None, + [ + self.settings_row( + t(L10nKey::SettingsCursorShape), + t(L10nKey::SettingsCursorShapeDesc), + cursor_style_control, + cx, + ), + self.settings_row( + t(L10nKey::SettingsCursorBlink), + t(L10nKey::SettingsCursorBlinkDesc), + blink, + cx, + ), + ] + .map(IntoElement::into_any_element), + cx, + ), + ); + groups.push(self.render_window_section(cx)); + Self::settings_page(groups) + } + + fn render_window_section(&self, cx: &mut Context) -> AnyElement { + let tk = Tk::of(cx); + let config = cx.global::(); + let overridden = window_overrides_active(config, cfg!(target_os = "windows")); + let dim_inactive_panes = config.dim_inactive_panes; + let opacity = Tty7App::effective_window_opacity(cx); + + const MIN: f32 = 0.2; + const MAX: f32 = 1.0; + let app = cx.entity().downgrade(); + let release_app = app.clone(); + let opacity_control = kit::slider( + "window-opacity", + (opacity - MIN) / (MAX - MIN), + format!("{:.0}%", opacity * 100.), + &tk, + Rc::new(move |f, window, cx| { + let v = ((MIN + f * (MAX - MIN)) * 100.).round() / 100.; + cx.global_mut::().window_opacity = Some(v.clamp(MIN, MAX)); + crate::ui::theme::apply_theme(Some(window), cx); + let _ = app.update(cx, |_, cx| cx.notify()); + }), + Rc::new(move |_window, cx| { + let _ = release_app.update(cx, |this, cx| this.persist_settings_config(cx)); + }), + ); + + // Windows exposes the native backdrop materials directly; macOS keeps + // the simple blur toggle, which drives its vibrancy. + #[cfg(target_os = "windows")] + let blur_control = { + let current = config.window_backdrop; + let entries = crate::ui::theme::backdrop_options(current) + .into_iter() + .map(|backdrop| { + MenuEntry::item( + t(crate::ui::app::window_backdrop_label_key(backdrop)), + backdrop == current, + move |this, window, cx| this.set_window_backdrop(backdrop, window, cx), + ) + }) + .collect(); + self.settings_dropdown( + "window-backdrop", + t(crate::ui::app::window_backdrop_label_key(current)), + None, + entries, + cx, + ) + }; + #[cfg(not(target_os = "windows"))] + let blur_control = { + let theme = presets::by_id(cx, &crate::ui::theme::effective_preset_id(cx)); + let blur = cx.global::().window_blur.unwrap_or(theme.blur); + self.settings_switch("window-blur", blur, cx, |this, on, window, cx| { + this.set_window_blur(on, window, cx) + }) + }; + // `Auto` is the one backdrop that still defers to the legacy blur + // flag. Offer that switch exactly when it has an effect — otherwise a + // stored `window_blur: true` would blur the window with no control to + // clear it. + #[cfg(target_os = "windows")] + let auto_blur_row = + (cx.global::().window_backdrop == WindowBackdrop::Auto).then(|| { + let theme = presets::by_id(cx, &crate::ui::theme::effective_preset_id(cx)); + let blur = cx.global::().window_blur.unwrap_or(theme.blur); + let control = + self.settings_switch("window-blur", blur, cx, |this, on, window, cx| { + this.set_window_blur(on, window, cx) + }); + self.settings_row( + t(L10nKey::SettingsBlur), + t(L10nKey::SettingsBlurAutoDesc), + control, + cx, + ) + .into_any_element() + }); + #[cfg(not(target_os = "windows"))] + let auto_blur_row: Option = None; + let dim = self.settings_switch( + "dim-inactive-panes", + dim_inactive_panes, + cx, + |this, on, _, cx| this.set_dim_inactive_panes(on, cx), + ); + let follow_theme = overridden.then(|| { + h_flex() + .pt(px(4.)) + .pb(px(8.)) + .child( + kit::button( + "follow-theme-window", + t(L10nKey::FollowTheme), + BtnKind::Link, + ) + .on_click( + cx.listener(|this, _, window, cx| this.reset_window_overrides(window, cx)), + ), + ) + .into_any_element() + }); + + let mut rows = vec![ + self.settings_row( + t(L10nKey::SettingsOpacity), + t(L10nKey::SettingsOpacityDesc), + opacity_control, + cx, + ) + .into_any_element(), + self.settings_row( + t(if cfg!(target_os = "windows") { + L10nKey::SettingsBackdrop + } else { + L10nKey::SettingsBlur + }), + t(if cfg!(target_os = "windows") { + L10nKey::SettingsBackdropDesc + } else { + L10nKey::SettingsBlurDesc + }), + blur_control, + cx, + ) + .into_any_element(), + ]; + rows.extend(auto_blur_row); + rows.extend(follow_theme); + rows.push( + self.settings_row( + t(L10nKey::SettingsDimInactivePanes), + t(L10nKey::SettingsDimInactivePanesDesc), + dim, + cx, + ) + .into_any_element(), + ); + self.settings_group(Some(t(L10nKey::SettingsTransparency)), None, rows, cx) + } + + fn render_shell_group(&self, cx: &mut Context) -> AnyElement { + let tk = Tk::of(cx); + let (program_input, args_input, wd_path_input) = match self.active_settings() { + Some(s) => ( + s.shell_program_input.clone(), + s.shell_args_input.clone(), + s.wd_path_input.clone(), + ), + None => return div().into_any_element(), + }; + let wd_strategy = cx.global::().working_directory.strategy; + let platform_default = if cfg!(windows) { + "PowerShell" + } else { + t(L10nKey::SettingsShellDefaultLoginShell) + }; + + // tty7 already knows which shells are installed — it lists them on the + // new-tab button — so the field carries a menu of them. The field + // stays: a shell tty7 did not find still has to be reachable by path. + // Detected shells only: a `custom_shells` row carries arguments this + // picker would silently drop. + let shells: Vec<_> = self + .shells + .shells + .iter() + .filter(|shell| !shell.user_authored) + .cloned() + .collect(); + let current_program = program_input.read(cx).value().trim().to_string(); + let platform_default_item: SharedString = if cfg!(windows) { + "PowerShell".into() + } else { + t(L10nKey::AppPlaceholderLoginShell).into() + }; + let pick = |program: String, input: Entity| { + move |this: &mut Self, window: &mut Window, cx: &mut Context| { + input.update(cx, |state, cx| state.set_value(program.clone(), window, cx)); + this.commit_shell_from_picker(cx); + } + }; + let mut entries = vec![MenuEntry::item( + platform_default_item, + current_program.is_empty(), + pick(String::new(), program_input.clone()), + )]; + if !shells.is_empty() { + entries.push(MenuEntry::Separator); + } + for shell in &shells { + entries.push(MenuEntry::item( + shell.label.clone(), + current_program == shell.program, + pick(shell.program.clone(), program_input.clone()), + )); + } + let menu_id: SharedString = "shell-program-detected".into(); + let open = self.settings_menu_open(&menu_id); + let picker = (!shells.is_empty()).then(|| { + let toggle = menu_id.clone(); + div() + .id("shell-program-detected-trigger") + .flex_shrink_0() + .ml(px(4.)) + .mr(px(-4.)) + .size(px(18.)) + .rounded(px(4.)) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .hover(move |s| s.bg(tk.k05)) + .when(open, |d| d.bg(tk.k05)) + .child(kit::chevron_down(&tk)) + .on_click(cx.listener(move |this, _, window, cx| { + this.toggle_settings_menu(toggle.clone(), 0, false, window, cx) + })) + }); + let program_control = div() + .relative() + .child( + self.settings_text_input(&program_input, FIELD_W, false, cx) + .children(picker), + ) + .when(open, |d| { + d.child(kit::popover_below( + true, + 4., + self.settings_menu_panel(&menu_id, entries, cx) + .min_w(px(FIELD_W)), + )) + }) + .into_any_element(); + // Args become argv verbatim, so a quote that never closes is a value + // that cannot be saved at all — `commit_shell` refuses it, and this + // line is the explanation (#551). The input commits on Enter/blur, so + // a half-typed quote is never marked wrong mid-keystroke. + let args_value = args_input.read(cx).value(); + let args_error = crate::ui::app::split_shell_args(&args_value) + .is_err() + .then(|| t(L10nKey::SettingsArgumentsInvalid).to_string()); + let args_control = self.settings_checked_input(&args_input, FIELD_W, args_error, cx); + + use crate::core::config::WdStrategy; + let wd_idx = match wd_strategy { + WdStrategy::Inherit => 0, + WdStrategy::Home => 1, + WdStrategy::Custom => 2, + }; + let wd_radio = self.segmented( + "wd-strategy", + &[ + t(L10nKey::SettingsWdInherit), + t(L10nKey::SettingsWdHome), + t(L10nKey::SettingsWdCustom), + ], + wd_idx, + cx, + |this, ix, _w, cx| { + let s = match ix { + 0 => WdStrategy::Inherit, + 1 => WdStrategy::Home, + _ => WdStrategy::Custom, + }; + this.set_working_directory_strategy(s, cx); + }, + ); + let mut rows = vec![ + self.settings_row( + t(L10nKey::SettingsProgram), + t(L10nKey::SettingsProgramDesc), + program_control, + cx, + ) + .into_any_element(), + self.settings_row( + t(L10nKey::SettingsArguments), + t(L10nKey::SettingsArgumentsDesc), + args_control, + cx, + ) + .into_any_element(), + self.settings_row( + t(L10nKey::SettingsStartIn), + t(L10nKey::SettingsStartInDesc), + wd_radio, + cx, + ) + .into_any_element(), + ]; + if wd_strategy == WdStrategy::Custom { + // `commit_working_directory_path` refuses the same value through + // the same predicate, so the red line and the not-saved config + // always agree (#601). + let value = wd_path_input.read(cx).value(); + let error = (!crate::ui::app::wd_path_saveable(&value)) + .then(|| t(L10nKey::SettingsWdPathInvalid).to_string()); + let control = self.settings_checked_input(&wd_path_input, 240., error, cx); + rows.push( + self.settings_row( + t(L10nKey::SettingsCustomPath), + t(L10nKey::SettingsCustomPathDesc), + control, + cx, + ) + .into_any_element(), + ); + } + rows.push( + div() + .pt(px(4.)) + .text_size(fs(12.)) + .line_height(px(17.)) + .text_color(tk.k6) + .child(t(L10nKey::SettingsShellFooter)) + .into_any_element(), + ); + self.settings_group( + Some(t(L10nKey::SettingsShell)), + Some(t_fmt( + L10nKey::SettingsShellIntro, + &[("default", platform_default)], + )), + rows, + cx, + ) + } + + pub(crate) fn render_settings_terminal(&self, cx: &mut Context) -> AnyElement { + let tk = Tk::of(cx); + let cfg = cx.global::(); + let link_url = cfg.link_url; + let ssh_loopback_forward = cfg.ssh_loopback_forward; + let scroll_mult = cfg.mouse_scroll_multiplier; + let smooth_scroll = cfg.smooth_scroll; + let bell = cfg.bell; + let link_file_open = cfg.file_open_mode(); + // A bucket highlights only on an exact match; any other value gets a + // "Custom (N)" cell so the highlight never claims a number the config + // does not have (#550). + let (scrollback_sel, scrollback_custom) = + preset_choice(&SCROLLBACK_BUCKETS, cfg.scrollback_limit, group_thousands); + let Some(link_file_command_input) = self + .active_settings() + .map(|s| s.link_file_command_input.clone()) + else { + return div().into_any_element(); + }; + + let link_switch = self.settings_switch("term-link-url", link_url, cx, |this, on, _, cx| { + this.set_link_url(on, cx) + }); + let loopback_switch = self.settings_switch( + "term-ssh-loopback-forward", + ssh_loopback_forward, + cx, + |this, on, _, cx| this.set_ssh_loopback_forward(on, cx), + ); + let link_file_open_radio = self.segmented( + "term-link-file-open", + &[ + t(L10nKey::SettingsOpenFilesInternal), + t(L10nKey::SettingsOpenFilesSystem), + t(L10nKey::SettingsOpenFilesCommand), + ], + match link_file_open { + LinkFileOpen::Internal => 0, + LinkFileOpen::System => 1, + LinkFileOpen::Command => 2, + }, + cx, + |this, ix, _w, cx| { + let mode = match ix { + 0 => LinkFileOpen::Internal, + 1 => LinkFileOpen::System, + _ => LinkFileOpen::Command, + }; + this.set_link_file_open(mode, cx); + }, + ); + // Only shown under `Command`: an empty box next to two working modes + // reads as "this is what file links do". + let link_file_command_row = (link_file_open == LinkFileOpen::Command).then(|| { + let control = self + .settings_text_input(&link_file_command_input, 240., false, cx) + .into_any_element(); + self.settings_row( + t(L10nKey::SettingsOpenFilesCommand), + t_fmt( + L10nKey::SettingsOpenFilesWithDesc, + &[ + ("modifier", LINK_MODIFIER_LABEL), + ("path", "{path}"), + ("line", "{line}"), + ("column", "{column}"), + ], + ), + control, + cx, + ) + .into_any_element() + }); + let scrollback = self.segmented_valued( + "term-scrollback", + &SCROLLBACK_LABELS, + scrollback_sel, + scrollback_custom, + cx, + |this, ix, _w, cx| { + let lines = SCROLLBACK_BUCKETS + .get(ix) + .copied() + .unwrap_or(Config::default().scrollback_limit); + this.set_scrollback_limit(lines, cx); + }, + ); + let bell_idx = match bell { + BellMode::None => 0, + BellMode::Visual => 1, + BellMode::Audible => 2, + BellMode::Both => 3, + }; + let bell_control = self.segmented( + "term-bell", + &[ + t(L10nKey::SettingsBellModeOff), + t(L10nKey::SettingsBellModeVisual), + t(L10nKey::SettingsBellModeAudible), + t(L10nKey::SettingsBellModeBoth), + ], + bell_idx, + cx, + |this, ix, _w, cx| { + let mode = match ix { + 0 => BellMode::None, + 1 => BellMode::Visual, + 2 => BellMode::Audible, + 3 => BellMode::Both, + _ => BellMode::default(), + }; + this.set_bell_mode(mode, cx); + }, + ); + const MIN: f32 = 0.5; + const MAX: f32 = 5.0; + const STEP: f32 = 0.25; + let app = cx.entity().downgrade(); + let release_app = app.clone(); + let scroll_control = kit::slider( + "term-scroll-speed", + (scroll_mult - MIN) / (MAX - MIN), + format!("{scroll_mult:.2}×"), + &tk, + Rc::new(move |f, _window, cx| { + let v = ((MIN + f * (MAX - MIN)) / STEP).round() * STEP; + cx.global_mut::().mouse_scroll_multiplier = v.clamp(MIN, MAX); + let _ = app.update(cx, |_, cx| cx.notify()); + }), + Rc::new(move |_window, cx| { + let _ = release_app.update(cx, |this, cx| this.persist_settings_config(cx)); + }), + ); + let smooth = self.settings_switch( + "term-smooth-scroll", + smooth_scroll, + cx, + |this, on, _, cx| this.set_smooth_scroll(on, cx), + ); + + Self::settings_page([ + self.render_shell_group(cx), + self.render_prompt_group(cx), + self.settings_group( + Some(t(L10nKey::SettingsScrolling)), + None, + [ + self.settings_row( + t(L10nKey::SettingsScrollback), + t(L10nKey::SettingsScrollbackDesc), + scrollback, + cx, + ), + self.settings_row( + t(L10nKey::SettingsScrollSpeed), + t(L10nKey::SettingsScrollSpeedDesc), + scroll_control, + cx, + ), + self.settings_row( + t(L10nKey::SettingsSmoothScroll), + t(L10nKey::SettingsSmoothScrollDesc), + smooth, + cx, + ), + ] + .map(IntoElement::into_any_element), + cx, + ), + self.settings_group( + Some(t(L10nKey::SettingsBell)), + None, + [self + .settings_row( + t(L10nKey::SettingsTerminalBell), + t(L10nKey::SettingsTerminalBellDesc), + bell_control, + cx, + ) + .into_any_element()], + cx, + ), + self.settings_group( + Some(t(L10nKey::SettingsLinks)), + None, + [ + self.settings_row( + t(L10nKey::DetectUrls), + t_fmt( + L10nKey::SettingsDetectUrlsDesc, + &[("modifier", LINK_MODIFIER_LABEL)], + ), + link_switch, + cx, + ) + .into_any_element(), + self.settings_row( + t(L10nKey::ForwardSshLoopbackLinks), + t(L10nKey::SettingsForwardSshLoopbackLinksDesc), + loopback_switch, + cx, + ) + .into_any_element(), + self.settings_row( + t(L10nKey::OpenFilesWith), + t_fmt( + L10nKey::SettingsOpenFilesModeDesc, + &[("modifier", LINK_MODIFIER_LABEL)], + ), + link_file_open_radio, + cx, + ) + .into_any_element(), + ] + .into_iter() + .chain(link_file_command_row), + cx, + ), + ]) + } + + fn render_prompt_group(&self, cx: &mut Context) -> AnyElement { + let cfg = cx.global::(); + let prompt_editor = cfg.prompt_editor; + let tab_completion = cfg.tab_completion; + let history_search = cfg.history_search; + let per_pane_history = cfg.per_pane_history; + // Tab completion and history search are menus tty7 opens *inside* its + // own prompt editor. With the editor off both keys belong to the + // shell, so the switches grey out and say why; their stored values + // are untouched and come back with it. + let gated = |desc: L10nKey| match prompt_editor { + true => t(desc).to_string(), + false => format!("{} {}", t(desc), t(L10nKey::SettingsNeedsPromptEditor)), + }; + let editor = self.settings_switch( + "term-prompt-editor", + prompt_editor, + cx, + |this, on, _, cx| this.set_prompt_editor(on, cx), + ); + let completion = kit::switch("term-tab-completion") + .checked(tab_completion) + .disabled(!prompt_editor) + .on_click(cx.listener(|this, on: &bool, _w, cx| this.set_tab_completion(*on, cx))) + .into_any_element(); + let history = kit::switch("term-history-search") + .checked(history_search) + .disabled(!prompt_editor) + .on_click(cx.listener(|this, on: &bool, _w, cx| this.set_history_search(*on, cx))) + .into_any_element(); + let per_pane = self.settings_switch( + "term-per-pane-history", + per_pane_history, + cx, + |this, on, _, cx| this.set_per_pane_history(on, cx), + ); + self.settings_group( + Some(t(L10nKey::SettingsPrompt)), + Some(t(L10nKey::SettingsPromptIntro).to_string()), + [ + self.settings_row( + t(L10nKey::SettingsPromptEditor), + t(L10nKey::SettingsPromptEditorDesc), + editor, + cx, + ), + self.settings_row_gated_when( + t(L10nKey::SettingsTabCompletion), + gated(L10nKey::SettingsTabCompletionDesc), + completion, + !prompt_editor, + cx, + ), + self.settings_row_gated_when( + t(L10nKey::SettingsHistorySearch), + gated(L10nKey::SettingsHistorySearchDesc), + history, + !prompt_editor, + cx, + ), + self.settings_row( + t(L10nKey::SettingsPerPaneHistory), + t(L10nKey::SettingsPerPaneHistoryDescription), + per_pane, + cx, + ), + ] + .map(IntoElement::into_any_element), + cx, + ) + } + + pub(crate) fn render_settings_input(&self, cx: &mut Context) -> AnyElement { + let cfg = cx.global::(); + let mouse_hide = cfg.mouse_hide_while_typing; + let focus_follows = cfg.focus_follows_mouse; + let mouse_reporting = cfg.mouse_reporting; + let mouse_zoom = cfg.mouse_zoom_modifier; + let option_as_alt = cfg.macos_option_as_alt; + let smart_select = cfg.smart_select; + let copy_on_select = cfg.copy_on_select; + let clip_trim = cfg.clipboard_trim_trailing_spaces; + + let focus = self.settings_switch( + "term-focus-follows", + focus_follows, + cx, + |this, on, _, cx| this.set_focus_follows_mouse(on, cx), + ); + let hide = self.settings_switch("term-mouse-hide", mouse_hide, cx, |this, on, _, cx| { + this.set_mouse_hide_while_typing(on, cx) + }); + let report = self.settings_switch( + "term-mouse-report", + mouse_reporting, + cx, + |this, on, _, cx| this.set_mouse_reporting(on, cx), + ); + let smart = + self.settings_switch("term-smart-select", smart_select, cx, |this, on, _, cx| { + this.set_smart_select(on, cx) + }); + let copy = self.settings_switch( + "term-copy-on-select", + copy_on_select, + cx, + |this, on, _, cx| this.set_copy_on_select(on, cx), + ); + let trim = self.settings_switch("term-clip-trim", clip_trim, cx, |this, on, _, cx| { + this.set_clipboard_trim(on, cx) + }); + // Ctrl only earns a cell where it is a different key from the platform + // modifier: off macOS the two are the same key. A config that names + // `ctrl` there still highlights it, in the one cell that means it. + let mac = cfg!(target_os = "macos"); + let zoom_labels: Vec<&str> = if mac { + vec!["⌘", "⌃", "⌥", t(L10nKey::SettingsMouseZoomOff)] + } else { + vec!["Ctrl", "Alt", t(L10nKey::SettingsMouseZoomOff)] + }; + let zoom_idx = match (mouse_zoom, mac) { + (MouseZoomModifier::Platform, _) => 0, + (MouseZoomModifier::Ctrl, true) => 1, + (MouseZoomModifier::Ctrl, false) => 0, + (MouseZoomModifier::Alt, true) => 2, + (MouseZoomModifier::Alt, false) => 1, + (MouseZoomModifier::None, true) => 3, + (MouseZoomModifier::None, false) => 2, + }; + let zoom = self.segmented( + "term-mouse-zoom", + &zoom_labels, + zoom_idx, + cx, + move |this, ix, _w, cx| { + let modifier = match (ix, mac) { + (0, _) => MouseZoomModifier::Platform, + (1, true) => MouseZoomModifier::Ctrl, + (1, false) => MouseZoomModifier::Alt, + (2, true) => MouseZoomModifier::Alt, + _ => MouseZoomModifier::None, + }; + this.set_mouse_zoom_modifier(modifier, cx); + }, + ); + let shortcuts = self + .settings_button( + "open-keybindings", + t(L10nKey::SettingsEditShortcuts), + cx, + |this, window, cx| { + this.navigate_settings(SettingsSection::Keybindings, None, window, cx) + }, + ) + .into_any_element(); + let option_group = mac.then(|| { + let control = self.settings_switch( + "term-option-as-alt", + option_as_alt, + cx, + |this, on, _, cx| this.set_macos_option_as_alt(on, cx), + ); + self.settings_group( + Some(t(L10nKey::SettingsKeyboard)), + None, + [self + .settings_row( + t(L10nKey::SettingsOptionAsMeta), + t(L10nKey::SettingsOptionAsMetaDesc), + control, + cx, + ) + .into_any_element()], + cx, + ) + }); + + let mut groups = vec![ + self.settings_group( + None, + None, + [self + .settings_row( + t(L10nKey::SettingsSearchKeybindingsTitle), + t(L10nKey::SettingsKeybindingsIntroDesc), + shortcuts, + cx, + ) + .into_any_element()], + cx, + ), + self.settings_group( + Some(t(L10nKey::SettingsSelectionClipboard)), + None, + [ + self.settings_row( + t(L10nKey::SettingsSmartSelection), + t(L10nKey::SettingsSmartSelectionDesc), + smart, + cx, + ), + self.settings_row( + t(L10nKey::SettingsCopyOnSelect), + t(L10nKey::SettingsCopyOnSelectDesc), + copy, + cx, + ), + self.settings_row( + t(L10nKey::SettingsTrimTrailingSpaces), + t(L10nKey::SettingsTrimTrailingSpacesDesc), + trim, + cx, + ), + ] + .map(IntoElement::into_any_element), + cx, + ), + ]; + groups.extend(option_group); + groups.push( + self.settings_group( + Some(t(L10nKey::SettingsMouse)), + None, + [ + self.settings_row( + t(L10nKey::SettingsFocusFollowsMouse), + t(L10nKey::SettingsFocusFollowsMouseDesc), + focus, + cx, + ), + self.settings_row( + t(L10nKey::SettingsHideMouseWhileTyping), + t(L10nKey::SettingsHideMouseWhileTypingDesc), + hide, + cx, + ), + self.settings_row( + t(L10nKey::SettingsReportMouseToApps), + t(L10nKey::SettingsReportMouseToAppsDesc), + report, + cx, + ), + self.settings_row( + t(L10nKey::SettingsMouseZoom), + t(L10nKey::SettingsMouseZoomDesc), + zoom, + cx, + ), + ] + .map(IntoElement::into_any_element), + cx, + ), + ); + Self::settings_page(groups) + } + + pub(crate) fn render_window_preferences(&self, cx: &mut Context) -> AnyElement { + let cfg = cx.global::(); + let new_tab_idx = match cfg.new_tab_position { + NewTabPosition::AfterCurrent => 0, + NewTabPosition::End => 1, + }; + let tab_bar_idx = match cfg.tab_bar_position { + TabBarPosition::Top => 0, + TabBarPosition::Left => 1, + }; + let sidebar_diff_preview = cfg.sidebar_diff_preview; + let grouping_idx = match cfg.sidebar_grouping { + crate::core::config::SidebarGrouping::Repo => 0, + crate::core::config::SidebarGrouping::RepoOrDirectory => 1, + crate::core::config::SidebarGrouping::None => 2, + }; + let new_tab = self.segmented( + "wt-new-tab-pos", + &[t(L10nKey::SettingsAfterCurrent), t(L10nKey::SettingsAtEnd)], + new_tab_idx, + cx, + |this, ix, _w, cx| { + this.set_new_tab_position( + if ix == 0 { + NewTabPosition::AfterCurrent + } else { + NewTabPosition::End + }, + cx, + ); + }, + ); + let tab_bar = self.segmented( + "wt-tab-bar-pos", + &[t(L10nKey::SettingsTop), t(L10nKey::SettingsLeft)], + tab_bar_idx, + cx, + |this, ix, _w, cx| { + this.set_tab_bar_position( + if ix == 0 { + TabBarPosition::Top + } else { + TabBarPosition::Left + }, + cx, + ); + }, + ); + let grouping = self.segmented( + "wt-sidebar-grouping", + &[ + t(L10nKey::SettingsByRepo), + t(L10nKey::SettingsByRepoOrFolder), + t(L10nKey::SettingsFlat), + ], + grouping_idx, + cx, + |this, ix, _w, cx| { + let grouping = match ix { + 0 => crate::core::config::SidebarGrouping::Repo, + 1 => crate::core::config::SidebarGrouping::RepoOrDirectory, + _ => crate::core::config::SidebarGrouping::None, + }; + this.set_sidebar_grouping(grouping, cx); + }, + ); + let diff = self.settings_switch( + "wt-sidebar-diff-preview", + sidebar_diff_preview, + cx, + |this, on, _, cx| this.set_sidebar_diff_preview(on, cx), + ); + Self::settings_page([self.settings_group( + Some(t(L10nKey::SettingsTabs)), + None, + [ + self.settings_row( + t(L10nKey::SettingsNewTabPosition), + t(L10nKey::SettingsNewTabPositionDesc), + new_tab, + cx, + ), + self.settings_row( + t(L10nKey::SettingsTabBarPosition), + t(L10nKey::SettingsTabBarPositionDesc), + tab_bar, + cx, + ), + self.settings_row( + t(L10nKey::SettingsSidebarGrouping), + t(L10nKey::SettingsSidebarGroupingDesc), + grouping, + cx, + ), + self.settings_row( + t(L10nKey::SettingsDiffPreviewFromCounts), + t(L10nKey::SettingsDiffPreviewFromCountsDesc), + diff, + cx, + ), + ] + .map(IntoElement::into_any_element), + cx, + )]) + } + + pub(crate) fn render_settings_about(&self, cx: &mut Context) -> AnyElement { + use crate::core::update::UpdatePhase; + let tk = Tk::of(cx); + let status = cx + .try_global::() + .cloned() + .unwrap_or_default(); + let busy = matches!( + status.phase, + UpdatePhase::Checking + | UpdatePhase::Downloading { .. } + | UpdatePhase::Verifying + | UpdatePhase::Installing + ); + let transferring = matches!( + status.phase, + UpdatePhase::Downloading { .. } | UpdatePhase::Verifying + ); + // A staged package whose directory has since been swept away is not an + // offer worth making. + let ready = status + .ready + .clone() + .filter(crate::core::update::PendingUpdate::is_usable); + // "You're running the latest version" above "27.0.0 is ready to + // install" is a contradiction, and a reachable one; the staged package + // is the more useful claim. + let phase_text = localized_update_phase(&status.phase) + .filter(|_| ready.is_none() || !matches!(status.phase, UpdatePhase::UpToDate)); + let version_desc = match &phase_text { + Some(text) => format!("{} · {text}", env!("CARGO_PKG_VERSION")), + None => env!("CARGO_PKG_VERSION").to_string(), + }; + + let check = h_flex() + .gap(px(8.)) + .when(transferring, |r| { + r.child( + kit::button( + "cancel-update-download", + t(L10nKey::SettingsUpdateCancel), + BtnKind::Link, + ) + .on_click(cx.listener(|_, _, _w, cx| crate::core::update::cancel_download(cx))), + ) + }) + .child( + kit::button( + "check-update-now", + if matches!(status.phase, UpdatePhase::Checking) { + t(L10nKey::SettingsUpdateChecking) + } else { + t(L10nKey::SettingsUpdateCheckNow) + }, + BtnKind::Secondary, + ) + .disabled(busy) + .on_click(cx.listener(|_, _, _w, cx| crate::core::update::spawn_check_forced(cx))), + ) + .into_any_element(); + let mut rows = vec![ + self.settings_row(t(L10nKey::SettingsVersion), version_desc, check, cx) + .into_any_element(), + ]; + // A failure the user can act on. Persisted, so it is still here + // tomorrow. + if let Some(failure) = status.failure.clone() { + let control = h_flex() + .gap(px(12.)) + .child( + kit::button( + "update-dismiss", + t(L10nKey::SettingsUpdateDismiss), + BtnKind::Link, + ) + .on_click(cx.listener(|_, _, _w, cx| crate::core::update::dismiss_failure(cx))), + ) + .child( + kit::button( + "update-manual", + t(L10nKey::SettingsUpdateDownloadManually), + BtnKind::Link, + ) + .on_click( + cx.listener(|_, _, _w, _cx| crate::core::update::open_releases_page()), + ), + ) + .child( + kit::button( + "update-retry", + t(L10nKey::SettingsUpdateRetry), + BtnKind::Secondary, + ) + .disabled(busy) + .on_click(cx.listener(|_, _, _w, cx| { + crate::core::update::dismiss_failure(cx); + crate::core::update::install_available(cx); + })), + ) + .into_any_element(); + rows.push( + self.settings_row( + t_fmt( + L10nKey::SettingsUpdateFailedTitle, + &[("version", &failure.version)], + ), + failure.detail.clone(), + control, + cx, + ) + .into_any_element(), + ); + } + // Downloaded and verified: the decision left is "may I restart". + if let Some(pending) = ready.clone() { + let control = h_flex() + .gap(px(12.)) + .child( + kit::button( + "discard-ready", + t(L10nKey::SettingsUpdateDiscard), + BtnKind::Link, + ) + .disabled(busy) + .on_click(cx.listener(|_, _, _w, cx| crate::core::update::discard_pending(cx))), + ) + .child( + kit::button( + "install-ready", + t(L10nKey::SettingsUpdateInstallNow), + BtnKind::Primary, + ) + .disabled(busy) + .on_click( + cx.listener(|_, _, _w, cx| crate::core::update::install_available(cx)), + ), + ) + .into_any_element(); + rows.push( + self.settings_row( + t_fmt( + L10nKey::SettingsUpdateReady, + &[("version", &pending.version)], + ), + if pending.apply_on_launch { + t(L10nKey::SettingsUpdateReadyNextLaunch).to_string() + } else { + String::new() + }, + control, + cx, + ) + .into_any_element(), + ); + } + // Where the package cannot be installed for the user, the release page + // is the whole update path; that cannot live only in a dialog that has + // already been dismissed. + if let Some(upd) = status.available.clone().filter(|_| ready.is_none()) { + let action = if upd.installable { + t(L10nKey::SettingsUpdateAndRelaunch) + } else { + t(L10nKey::SettingsUpdateViewRelease) + }; + let control = kit::button("install-update", action, BtnKind::Primary) + .disabled(busy) + .on_click(cx.listener(|_, _, _w, cx| crate::core::update::install_available(cx))) + .into_any_element(); + rows.push( + self.settings_row( + t_fmt( + L10nKey::SettingsVersionAvailable, + &[("version", &upd.version)], + ), + upd.install_hint + .map(|hint| localized_update_install_hint(&hint)) + .unwrap_or_default(), + control, + cx, + ) + .into_any_element(), + ); + } + let settings_file = crate::core::config::config_path("config.json"); + if let Some(path) = settings_file { + let shown = tildify(&path.to_string_lossy()); + let reveal = self + .settings_button( + "reveal-settings-file", + t(L10nKey::SettingsReveal), + cx, + move |_, _, cx| { + if !path.exists() { + cx.global::().save(); + } + cx.reveal_path(&path); + }, + ) + .into_any_element(); + rows.push( + self.settings_row(t(L10nKey::SettingsSettingsFile), shown, reveal, cx) + .into_any_element(), + ); + } + + let mut groups = vec![self.settings_group(None, None, rows, cx)]; + groups.push(self.render_settings_maintenance(cx)); + groups.push( + v_flex() + .gap(px(6.)) + .text_size(fs(12.)) + .line_height(px(17.)) + .text_color(tk.k45) + .child(t(L10nKey::SettingsAboutDesc1)) + .child( + Link::new("about-github") + .href("https://github.com/l0ng-ai/tty7") + .text_color(tk.k6) + .child("github.com/l0ng-ai/tty7"), + ) + .into_any_element(), + ); + Self::settings_page(groups) + } + + fn render_settings_maintenance(&self, cx: &mut Context) -> AnyElement { + let stale_daemon = crate::daemon::spawn::local_daemon_stale_build(); + // Whether picking up the new build costs the user their running panes + // decides what this offer is, so it decides what it says. + let stale_daemon_note = if crate::daemon::spawn::local_daemon_supports( + crate::daemon::protocol::FEATURE_HANDOFF, + ) { + L10nKey::SettingsDaemonStaleDescInPlace + } else { + L10nKey::SettingsDaemonStaleDesc + }; + let cfg = cx.global::(); + let check_for_updates = cfg.check_for_updates; + let auto_download = cfg.auto_download_updates; + let channel_idx = match cfg.update_channel { + UpdateChannel::Stable => 0, + UpdateChannel::Nightly => 1, + }; + let channel = self.segmented( + "wt-update-channel", + &[ + t(L10nKey::SettingsUpdateChannelStable), + t(L10nKey::SettingsUpdateChannelNightly), + ], + channel_idx, + cx, + |this, ix, _w, cx| { + this.set_update_channel( + match ix { + 0 => UpdateChannel::Stable, + _ => UpdateChannel::Nightly, + }, + cx, + ); + }, + ); + let Some(http_proxy_input) = self.active_settings().map(|s| s.http_proxy_input.clone()) + else { + return div().into_any_element(); + }; + // Only flags a committed value: the input commits on Enter/blur. + let http_proxy_value = http_proxy_input.read(cx).value().trim().to_string(); + let http_proxy_error = (!http_proxy_value.is_empty() + && !tty7_core::daemon::install::proxy::is_valid_manual(&http_proxy_value)) + .then(|| t(L10nKey::SettingsAppHttpProxyInvalid).to_string()); + let http_proxy = + self.settings_checked_input(&http_proxy_input, FIELD_W, http_proxy_error, cx); + let check = + self.settings_switch("check-updates", check_for_updates, cx, |this, on, _, cx| { + this.set_check_for_updates(on, cx) + }); + let auto = self.settings_switch( + "auto-download-updates", + auto_download, + cx, + |this, on, _, cx| this.set_auto_download_updates(on, cx), + ); + let restart = self + .settings_button( + "restart-daemon", + t(L10nKey::SettingsRestartServer), + cx, + |this, window, cx| this.restart_daemon(window, cx), + ) + .into_any_element(); + // A stale server has a more specific thing to say than the row's + // standing description, and it ends with the same button. + let server_desc = match stale_daemon.as_deref() { + Some(build) => format!( + "{} {}", + t_fmt(L10nKey::SettingsDaemonStale, &[("build", build)]), + t(stale_daemon_note) + ), + None => t(L10nKey::SettingsServerDesc).to_string(), + }; + self.settings_group( + Some(t(L10nKey::SettingsUpdates)), + None, + [ + self.settings_row( + t(L10nKey::SettingsAutoDownload), + t(L10nKey::SettingsAutoDownloadDesc), + auto, + cx, + ), + self.settings_row( + t(L10nKey::SettingsCheckUpdatesOnLaunch), + t(L10nKey::SettingsCheckUpdatesDesc), + check, + cx, + ), + self.settings_row( + t(L10nKey::SettingsUpdateChannel), + t(L10nKey::SettingsUpdateChannelDesc), + channel, + cx, + ), + self.settings_row( + t(L10nKey::SettingsAppHttpProxy), + t(L10nKey::SettingsAppHttpProxyDesc), + http_proxy, + cx, + ), + self.settings_row(t(L10nKey::SettingsServer), server_desc, restart, cx), + ] + .map(IntoElement::into_any_element), + cx, + ) + } +} diff --git a/src/ui/settings/shell.rs b/src/ui/settings/shell.rs new file mode 100644 index 00000000..fbcd292c --- /dev/null +++ b/src/ui/settings/shell.rs @@ -0,0 +1,1597 @@ +//! The settings window's frame: the navigation, the page header, the rows and +//! groups every page is built from, the popovers controls open, and the +//! search and "modified" views that stand in for a page. + +use std::rc::Rc; + +use super::kit::{self, BtnKind, Tk, fs}; +use super::*; + +/// What a menu row does when picked. +pub(crate) type PickFn = Rc)>; + +/// One line of a dropdown's menu. +pub(crate) enum MenuEntry { + Item { + label: SharedString, + checked: bool, + /// Draw the label in this family — a font menu shows each font. + font: Option, + danger: bool, + trailing: Option, + on_pick: PickFn, + }, + Heading(SharedString), + Separator, + Note(SharedString), +} + +impl MenuEntry { + pub(crate) fn item( + label: impl Into, + checked: bool, + on_pick: impl Fn(&mut Tty7App, &mut Window, &mut Context) + 'static, + ) -> Self { + MenuEntry::Item { + label: label.into(), + checked, + font: None, + danger: false, + trailing: None, + on_pick: Rc::new(on_pick), + } + } +} + +/// A searchable menu's rows: what each says, and the family to draw it in. +pub(crate) struct SearchOption { + pub label: SharedString, + pub font: Option, +} + +impl Tty7App { + // ── Popovers ───────────────────────────────────────────────────────── + + pub(crate) fn settings_menu_open(&self, id: &str) -> bool { + self.active_settings() + .and_then(|s| s.menu.as_ref()) + .is_some_and(|m| m.as_ref() == id) + } + + /// Opens the popover `id` — closing whichever one was open — or closes it + /// when it is the one already open. `highlight` is the row the arrow keys + /// start from; a popover with a query box gets the caret in it. + pub(crate) fn toggle_settings_menu( + &mut self, + id: SharedString, + highlight: usize, + with_query: bool, + window: &mut Window, + cx: &mut Context, + ) { + let Some(s) = self.active_settings_mut() else { + return; + }; + if s.menu.as_ref() == Some(&id) { + s.menu = None; + let handle = s.focus_handle.clone(); + window.focus(&handle, cx); + cx.notify(); + return; + } + s.menu = Some(id); + s.menu_hi = highlight; + let query = s.menu_query.clone(); + let scroll = s.menu_scroll.clone(); + query.update(cx, |q, cx| q.set_value("", window, cx)); + if let Some(s) = self.active_settings_mut() { + // Clearing the query resets the highlight; put it back. + s.menu_hi = highlight; + } + scroll.scroll_to_item(highlight); + if with_query { + let handle = query.read(cx).focus_handle(cx); + window.focus(&handle, cx); + } + cx.notify(); + } + + pub(crate) fn close_settings_menu(&mut self, window: &mut Window, cx: &mut Context) { + let Some(s) = self.active_settings_mut() else { + return; + }; + if s.menu.take().is_some() { + let handle = s.focus_handle.clone(); + window.focus(&handle, cx); + cx.notify(); + } + } + + /// A dropdown: the trigger showing the current value, and while open, its + /// menu hanging from the trigger's right edge. + pub(crate) fn settings_dropdown( + &self, + id: impl Into, + label: impl Into, + leading: Option, + entries: Vec, + cx: &mut Context, + ) -> AnyElement { + let tk = Tk::of(cx); + let id: SharedString = id.into(); + let open = self.settings_menu_open(&id); + let checked_at = entries + .iter() + .position(|e| matches!(e, MenuEntry::Item { checked: true, .. })) + .unwrap_or(0); + let toggle_id = id.clone(); + let trigger = kit::select_trigger( + ElementId::Name(SharedString::from(format!("{id}-trigger"))), + label, + leading, + open, + &tk, + ) + .on_click(cx.listener(move |this, _, window, cx| { + this.toggle_settings_menu(toggle_id.clone(), checked_at, false, window, cx) + })); + div() + .relative() + .flex_shrink_0() + .child(trigger) + .when(open, |d| { + d.child(kit::popover_below( + true, + 4., + self.settings_menu_panel(&id, entries, cx).min_w(px(148.)), + )) + }) + .into_any_element() + } + + pub(crate) fn settings_menu_panel( + &self, + id: &str, + entries: Vec, + cx: &mut Context, + ) -> Div { + let tk = Tk::of(cx); + let mut panel = kit::menu_panel(&tk); + for (i, entry) in entries.into_iter().enumerate() { + panel = match entry { + MenuEntry::Item { + label, + checked, + font, + danger, + trailing, + on_pick, + } => panel.child( + kit::menu_row( + ElementId::Name(SharedString::from(format!("{id}-item-{i}"))), + false, + &tk, + ) + .child(kit::check_mark(checked, &tk)) + .child( + div() + .flex_1() + .when_some(font, |d, f| d.font_family(f)) + .when(danger, |d| d.text_color(tk.danger)) + .child(label), + ) + .when_some(trailing, |r, text| { + r.child( + div() + .pl(px(12.)) + .text_size(fs(11.5)) + .text_color(tk.k4) + .child(text), + ) + }) + .on_click(cx.listener(move |this, _, window, cx| { + this.close_settings_menu(window, cx); + on_pick(this, window, cx); + })), + ), + MenuEntry::Heading(text) => panel.child(kit::menu_heading(text, &tk)), + MenuEntry::Separator => panel.child(kit::menu_separator(&tk)), + MenuEntry::Note(text) => panel.child( + div() + .px(px(8.)) + .pt(px(4.)) + .pb(px(6.)) + .text_size(fs(11.5)) + .line_height(px(16.)) + .text_color(tk.k45) + .child(text), + ), + }; + } + panel + } + + /// A dropdown over a long list — the font menus — with a query box at the + /// top and the arrow keys to walk what it leaves. + pub(crate) fn settings_search_dropdown( + &self, + id: impl Into, + label: impl Into, + options: Rc>, + current: Option, + on_pick: Rc)>, + cx: &mut Context, + ) -> AnyElement { + let tk = Tk::of(cx); + let id: SharedString = id.into(); + let open = self.settings_menu_open(&id); + let toggle_id = id.clone(); + let start = current.unwrap_or(0); + let trigger = kit::select_trigger( + ElementId::Name(SharedString::from(format!("{id}-trigger"))), + label, + None, + open, + &tk, + ) + .on_click(cx.listener(move |this, _, window, cx| { + this.toggle_settings_menu(toggle_id.clone(), start, true, window, cx) + })); + let popover = open.then(|| { + let Some(s) = self.active_settings() else { + return div(); + }; + let query = s.menu_query.read(cx).value().trim().to_lowercase(); + let visible: Rc> = Rc::new( + options + .iter() + .enumerate() + .filter(|(_, o)| query.is_empty() || o.label.to_lowercase().contains(&query)) + .map(|(i, _)| i) + .collect(), + ); + let hi = s.menu_hi.min(visible.len().saturating_sub(1)); + let keys_visible = visible.clone(); + let keys_pick = on_pick.clone(); + let mut list = v_flex() + .id(ElementId::Name(SharedString::from(format!("{id}-list")))) + .max_h(px(240.)) + .overflow_y_scroll() + .track_scroll(&s.menu_scroll) + .p(px(4.)) + .gap(px(1.)); + for (row, &ix) in visible.iter().enumerate() { + let option = &options[ix]; + let pick = on_pick.clone(); + list = list.child( + kit::menu_row( + ElementId::NamedInteger(id.clone(), ix as u64), + row == hi, + &tk, + ) + .h(px(28.)) + .child(kit::check_mark(Some(ix) == current, &tk)) + .child( + div() + .flex_1() + .min_w_0() + .truncate() + .when_some(option.font.clone(), |d, f| d.font_family(f)) + .child(option.label.clone()), + ) + .on_mouse_move(cx.listener(move |this, _, _, cx| { + if let Some(s) = this.active_settings_mut() + && s.menu_hi != row + { + s.menu_hi = row; + cx.notify(); + } + })) + .on_click(cx.listener(move |this, _, window, cx| { + this.close_settings_menu(window, cx); + pick(this, ix, window, cx); + })), + ); + } + if visible.is_empty() { + list = list.child( + div() + .h(px(28.)) + .px(px(8.)) + .flex() + .items_center() + .text_color(tk.k35) + .child(t(L10nKey::SettingsNoMatchesShort)), + ); + } + kit::menu_panel(&tk) + .w(px(260.)) + .p_0() + .gap_0() + .overflow_hidden() + .capture_key_down(cx.listener(move |this, ev: &KeyDownEvent, window, cx| { + let key = ev.keystroke.key.as_str(); + let len = keys_visible.len(); + match key { + "down" | "up" => { + if let Some(s) = this.active_settings_mut() { + let hi = s.menu_hi.min(len.saturating_sub(1)); + s.menu_hi = if key == "down" { + (hi + 1).min(len.saturating_sub(1)) + } else { + hi.saturating_sub(1) + }; + s.menu_scroll.scroll_to_item(s.menu_hi); + } + cx.stop_propagation(); + cx.notify(); + } + "enter" => { + let hi = this.active_settings().map(|s| s.menu_hi).unwrap_or(0); + if let Some(&ix) = keys_visible.get(hi.min(len.saturating_sub(1))) { + this.close_settings_menu(window, cx); + keys_pick(this, ix, window, cx); + } + cx.stop_propagation(); + } + "escape" => { + this.close_settings_menu(window, cx); + cx.stop_propagation(); + } + _ => {} + } + })) + .child( + h_flex() + .h(px(32.)) + .px(px(12.)) + .gap(px(7.)) + .items_center() + .border_b_1() + .border_color(tk.k08) + .child(kit::search_glass(11., &tk)) + .child( + div().flex_1().min_w_0().child( + Input::new(&s.menu_query) + .appearance(false) + .px_0() + .py_0() + .h(px(28.)), + ), + ) + .child(div().text_size(fs(11.)).text_color(tk.k35).child("↑↓ ↵")), + ) + .child(list) + }); + div() + .relative() + .flex_shrink_0() + .child(trigger) + .when_some(popover, |d, p| d.child(kit::popover_below(true, 4., p))) + .into_any_element() + } + + // ── Rows and groups ────────────────────────────────────────────────── + + /// A group of rows under a quiet heading, with the sentence that explains + /// the group when it needs one. + pub(crate) fn settings_group( + &self, + title: Option<&str>, + desc: Option, + body: impl IntoIterator, + cx: &Context, + ) -> AnyElement { + let tk = Tk::of(cx); + v_flex() + .when_some(title, |col, title| { + col.child( + kit::section_head(title, desc, &tk) + .id(settings_header_id(title)) + .anchor_scroll(self.first_hit_anchor(title, cx)), + ) + }) + .children(body) + .into_any_element() + } + + /// A page: its groups, forty points apart. + pub(crate) fn settings_page(groups: impl IntoIterator) -> AnyElement { + v_flex().gap(px(40.)).children(groups).into_any_element() + } + + pub(crate) fn settings_row( + &self, + label: impl Into, + desc: impl Into, + control: AnyElement, + cx: &Context, + ) -> Stateful
{ + self.settings_row_gated_when(label, desc, control, false, cx) + } + + /// The same row, greyed out when `gated` — for a control another setting + /// has switched off, whose own value is still there for when it comes back. + /// + /// Only the text dims. The control draws its own disabled state. + pub(crate) fn settings_row_gated_when( + &self, + label: impl Into, + desc: impl Into, + control: AnyElement, + gated: bool, + cx: &Context, + ) -> Stateful
{ + let tk = Tk::of(cx); + let label = label.into(); + let desc = desc.into(); + let entry = settings_search_entries() + .iter() + .find(|entry| t(entry.title) == label); + let modified = entry.is_some_and(|entry| entry.modified(cx.global::())); + let capture = self + .active_settings() + .is_some_and(|s| s.search_rows.borrow().is_some()); + // Descriptions can carry live status, so they must not take part in + // the identity that preserves GPUI's hover state. + let element_id = settings_row_id(&label, &desc); + let (hit, miss) = match self + .active_settings() + .filter(|s| !s.search_active && !capture) + { + Some(s) => { + let query = s.search.read(cx).value().trim().to_lowercase(); + let focused = s.focused_setting.is_some_and(|k| t(k) == label); + match query.is_empty() || section_match_count(s.section, &query) == 0 { + true => (focused, false), + false => { + let hit = row_matches_query(s.section, &label, &query); + (hit, !hit) + } + } + } + None => (false, false), + }; + let first_hit_anchor = self.first_hit_anchor(&label, cx); + // The control never shrinks, so on a narrow pane it would squeeze the + // label column to a letter per line. Below the width where both still + // fit, the control goes on a line of its own instead. + let stacked = self.settings_row_under(STACK_ROW_BELOW, cx); + // The reset sits on the label's own line, beside the name it resets, + // so a changed row keeps the height of an unchanged one. Rows the + // catalog cannot reset in place still say they differ. + let resettable = entry.filter(|e| { + e.title != L10nKey::SettingsSearchKeybindingsTitle + && e.title != L10nKey::SettingsThemeIntroTitle + }); + let title_line = h_flex() + .gap(px(8.)) + .items_center() + .min_w_0() + .child(div().text_size(fs(13.)).text_color(tk.fg).child(label)) + .when(modified, |line| match resettable { + Some(entry) => { + let key = entry.title; + line.child( + div() + .id(SharedString::from(format!("reset-setting-{key:?}"))) + .flex_shrink_0() + .text_size(fs(11.5)) + .text_color(tk.k4) + .cursor_pointer() + .hover(move |s| s.text_color(tk.fg)) + .child(t(L10nKey::Reset)) + .on_click(cx.listener(move |this, _, window, cx| { + this.reset_settings_value(key, window, cx) + })), + ) + } + None => line.child( + div() + .flex_shrink_0() + .text_size(fs(11.5)) + .text_color(tk.k4) + .child(t(L10nKey::SettingsModified)), + ), + }); + let labels = v_flex() + .gap(px(2.)) + .min_w_0() + .when(gated, |col| col.opacity(0.45)) + .child(title_line) + .when(!desc.is_empty(), |col| { + col.child( + div() + .text_size(fs(12.)) + .line_height(px(17.)) + .text_color(tk.k5) + .child(desc), + ) + }); + let row = div() + .id(element_id) + .flex() + .when(stacked, |row| row.flex_col().items_start().gap(px(8.))) + .when(!stacked, |row| { + row.flex_row().items_center().justify_between().gap(px(32.)) + }) + .min_h(px(52.)) + .py(px(12.)) + .when(hit, |row| { + row.bg(tk.k04).rounded(px(7.)).mx(px(-8.)).px(px(8.)) + }) + // Only the first hit on the page carries the anchor: it is the one + // the page scrolls to. + .anchor_scroll(first_hit_anchor) + .when(miss, |row| row.opacity(0.45)) + .child(labels) + .child( + h_flex() + .when(stacked, |c| c.w_full()) + .when(!stacked, |c| c.flex_shrink_0().justify_end()) + .gap(px(8.)) + .child(control), + ); + if capture { + if let Some(entry) = entry { + self.active_settings() + .unwrap() + .search_rows + .borrow_mut() + .as_mut() + .unwrap() + .push((entry.title, row.into_any_element())); + return div().id("captured-setting"); + } + } + row + } + + /// A text field for the right-hand column, with its focus ring. + pub(crate) fn settings_text_input( + &self, + input: &Entity, + width: f32, + invalid: bool, + cx: &App, + ) -> Div { + let tk = Tk::of(cx); + let focused = self.settings_input_focused(input, cx); + kit::text_field(input, focused, invalid, &tk, cx) + .w(px(width)) + .max_w_full() + } + + pub(crate) fn settings_input_focused(&self, input: &Entity, cx: &App) -> bool { + let handle = input.read(cx).focus_handle(cx); + self.active_settings() + .and_then(|s| s.focused.borrow().clone()) + .is_some_and(|f| f == handle) + } + + /// A text field with the line that says what is wrong with it. + pub(crate) fn settings_checked_input( + &self, + input: &Entity, + width: f32, + error: Option, + cx: &App, + ) -> AnyElement { + let tk = Tk::of(cx); + let invalid = error.is_some(); + v_flex() + .items_end() + .gap(px(4.)) + .child(self.settings_text_input(input, width, invalid, cx)) + .when_some(error, |col, e| { + col.child( + div() + .max_w(px(width.max(220.))) + .text_size(fs(12.)) + .text_color(tk.danger) + .child(e), + ) + }) + .into_any_element() + } + + pub(crate) fn segmented( + &self, + id: impl Into, + options: &[&str], + selected: usize, + cx: &mut Context, + on_pick: impl Fn(&mut Self, usize, &mut Window, &mut Context) + 'static, + ) -> AnyElement { + self.segmented_full(id, options, Some(selected), None, cx, on_pick) + } + + /// A segmented control over a fixed set of values, used where the config + /// accepts anything in a range. When the live value matches a bucket + /// exactly that bucket is highlighted; when it does not, a trailing + /// "Custom (N)" cell carries the highlight instead of the nearest bucket + /// getting a label it does not have (#550). + /// + /// The custom cell is not a button — there is no bucket value behind it to + /// write — so it takes neither a click handler nor a pointer cursor. + pub(crate) fn segmented_valued( + &self, + id: impl Into, + options: &[&str], + selected: Option, + custom_label: Option, + cx: &mut Context, + on_pick: impl Fn(&mut Self, usize, &mut Window, &mut Context) + 'static, + ) -> AnyElement { + self.segmented_full(id, options, selected, custom_label, cx, on_pick) + } + + fn segmented_full( + &self, + id: impl Into, + options: &[&str], + selected: Option, + custom_label: Option, + cx: &mut Context, + on_pick: impl Fn(&mut Self, usize, &mut Window, &mut Context) + 'static, + ) -> AnyElement { + let tk = Tk::of(cx); + let id: SharedString = id.into(); + let on_pick = Rc::new(on_pick); + let cells: Vec<(String, Option)> = options + .iter() + .enumerate() + .map(|(i, l)| (l.to_string(), Some(i))) + .chain(custom_label.map(|l| (l, None))) + .collect(); + h_flex() + .id(ElementId::Name(id.clone())) + .flex_shrink_0() + .p(px(2.)) + .gap(px(2.)) + .rounded(px(7.)) + .bg(tk.k05) + .children(cells.into_iter().enumerate().map(|(i, (label, bucket))| { + // A bucket is highlighted only on an exact match, and the + // custom cell (`bucket == None`) exactly when no bucket was. + let active = bucket == selected; + let on_pick = on_pick.clone(); + let cell = h_flex() + .id(ElementId::NamedInteger(id.clone(), i as u64)) + .items_center() + .justify_center() + .h(px(22.)) + .px(px(10.)) + .rounded(px(5.)) + .whitespace_nowrap() + .text_size(fs(12.)) + .when(active, |s| { + s.bg(tk.chip).shadow(tk.raised()).text_color(tk.fg) + }) + .when(!active, |s| { + s.text_color(tk.k5).hover(move |h| h.text_color(tk.fg)) + }) + .child(label); + match bucket { + Some(ix) => { + cell.cursor_pointer() + .on_click(cx.listener(move |this, _, window, cx| { + on_pick(this, ix, window, cx); + })) + } + None => cell, + } + })) + .into_any_element() + } + + /// A switch bound to a setter. + pub(crate) fn settings_switch( + &self, + id: &'static str, + on: bool, + cx: &mut Context, + set: impl Fn(&mut Self, bool, &mut Window, &mut Context) + 'static, + ) -> AnyElement { + kit::switch(id) + .checked(on) + .on_click(cx.listener(move |this, on: &bool, window, cx| set(this, *on, window, cx))) + .into_any_element() + } + + pub(crate) fn settings_button( + &self, + id: impl Into, + label: impl Into, + cx: &mut Context, + act: impl Fn(&mut Self, &mut Window, &mut Context) + 'static, + ) -> kit::Btn { + kit::button(id, label, BtnKind::Secondary) + .on_click(cx.listener(move |this, _, window, cx| act(this, window, cx))) + } + + // ── The frame ──────────────────────────────────────────────────────── + + pub(crate) fn render_settings( + &self, + window: &mut Window, + cx: &mut Context, + ) -> impl IntoElement + use<> { + let tk = Tk::of(cx); + // Opaque, so workspace translucency never shows through the page, but + // with the preset's gradient rather than a flat color. + let background: Background = crate::ui::theme::overlay_background(cx); + // That fill also covers the theme's background image, so the page + // carries its own copy, dimmed the way the workspace dims it. + let background_layers = crate::ui::app::overlay_surface_layers(cx); + + let (focus_handle, section, search) = match self.active_settings() { + Some(s) => (s.focus_handle.clone(), s.section, s.search.clone()), + None => return div(), + }; + if let Some(s) = self.active_settings() { + s.focused.replace(window.focused(cx)); + } + let query = search.read(cx).value().trim().to_lowercase(); + let searching = self.active_settings().is_some_and(|s| s.search_active); + let menu_open = self.active_settings().is_some_and(|s| s.menu.is_some()); + + let viewport_w = window.viewport_size().width.as_f32(); + let scale = ui_scale(cx); + self.settings_viewport_w.set(viewport_w); + self.settings_row_width + .set(settings_row_width(viewport_w, scale)); + self.settings_hit_anchored.set(false); + + // A query that matched here has to be reachable, not just counted: the + // anchor lands on the first matching row, and `scroll_to` reads where + // it ended up on the frame after this one. + if searching + && let Some(s) = self.active_settings() + && s.reveal_first_hit.replace(false) + { + s.search_anchor.scroll_to(window, cx); + } + if let Some(s) = self.active_settings() + && !searching + && s.reveal_first_hit.get() + { + s.reveal_first_hit.set(false); + let matched_here = + section_match_count(section, &query) > 0 || s.focused_setting.is_some(); + if s.focused_setting.is_some() || (!query.is_empty() && matched_here) { + s.search_anchor.scroll_to(window, cx); + } + } + + let prof = crate::ui::perf::enabled() + .then(|| (std::time::Instant::now(), section.profile_label())); + + let nav = self.render_settings_nav(nav_width(viewport_w, scale), searching, cx); + + let (title, subtitle, content) = if searching { + self.render_settings_results(cx) + } else { + let content = match section { + SettingsSection::General => self.render_settings_general(cx), + SettingsSection::Appearance => self.render_settings_appearance(cx), + SettingsSection::Terminal => self.render_settings_terminal(cx), + SettingsSection::KeyboardMouse => self.render_settings_input(cx), + SettingsSection::Ssh => self.render_settings_ssh(cx), + SettingsSection::Agents => self.render_settings_agents(cx), + SettingsSection::WindowTabs => self.render_window_preferences(cx), + SettingsSection::Keybindings => self.render_settings_keybindings(cx), + SettingsSection::About => self.render_settings_about(cx), + }; + (t(section.title()).to_string(), None, content) + }; + + let back = (!searching && section == SettingsSection::Keybindings).then(|| { + h_flex() + .id("settings-back") + .mt(px(-20.)) + .mb(px(-24.)) + .ml(px(-2.)) + .gap(px(4.)) + .items_center() + .text_size(fs(12.)) + .text_color(tk.k5) + .cursor_pointer() + .hover(move |s| s.text_color(tk.fg)) + .child(Icon::empty().path("icons/settings/back.svg").size(px(10.))) + .child(t(L10nKey::SettingsNavInput)) + .on_click(cx.listener(|this, _, window, cx| { + this.navigate_settings(SettingsSection::KeyboardMouse, None, window, cx) + })) + }); + + let header = h_flex() + .items_baseline() + .gap(px(10.)) + .child( + div() + .text_size(fs(20.)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(tk.fg) + .child(title), + ) + .when_some(subtitle, |row, sub| { + row.child(div().text_size(fs(12.)).text_color(tk.k4).child(sub)) + }); + + let notices = self.render_settings_notices(cx); + + let body = v_flex() + .id("settings-content") + .size_full() + .overflow_y_scroll() + .when_some(self.active_settings(), |pane, s| { + pane.track_scroll(&s.content_scroll) + }) + .child( + // A block, not a flex box: as a flex item it would negotiate a + // height with the pane and leave most of the page outside the + // scroll range. + div().w_full().px(px(56.)).pb(px(48.)).child( + v_flex() + .w_full() + .max_w(px(READING_COLUMN * scale)) + .gap(px(40.)) + .children(back) + .child(header) + .children(notices) + .child(content), + ), + ); + let main = v_flex() + .flex_1() + .min_w_0() + .h_full() + .child(div().h(px(TITLE_BAR_HEIGHT)).flex_shrink_0()) + .when_some(self.active_settings(), |pane, s| { + pane.child(crate::ui::scrollbar::with_inset_vertical_scrollbar( + "settings-content-scrollbar", + body, + &s.content_scroll, + px(SCROLLBAR_WINDOW_INSET), + )) + }); + + let root = div() + .size_full() + .relative() + .flex() + .flex_row() + .bg(background) + .text_color(tk.fg) + .text_size(fs(13.)) + .track_focus(&focus_handle) + .capture_key_down(cx.listener(move |this, ev: &KeyDownEvent, window, cx| { + this.settings_capture_key(searching, ev, window, cx) + })) + .on_key_down(cx.listener(move |this, ev: &KeyDownEvent, window, cx| { + if ev.keystroke.key.as_str() != "escape" { + return; + } + // Escape peels one layer at a time: an open popover, a + // pending shortcut conflict, the search, then the window. + if menu_open { + this.close_settings_menu(window, cx); + cx.stop_propagation(); + return; + } + if let Some(s) = this.active_settings_mut() + && s.kb_conflict.take().is_some() + { + cx.notify(); + cx.stop_propagation(); + return; + } + if searching { + if let Some(s) = this.active_settings_mut() { + s.modified_only = false; + } + if let Some(s) = this.active_settings() { + s.search + .clone() + .update(cx, |s, cx| s.set_value("", window, cx)); + } + this.autoselect_settings_search(cx); + cx.stop_propagation(); + return; + } + this.close_settings_checked(window, cx); + })) + .children(background_layers) + .child(nav) + .child(main) + .child( + crate::ui::app::window_move_gesture( + div() + .id("settings-titlebar-drag") + .absolute() + .top_0() + .left_0() + .right_0() + .h(px(TITLE_BAR_HEIGHT)), + "settings-titlebar-drag", + window, + cx, + ) + .on_double_click(|_, window, _| window.titlebar_double_click()), + ) + .child( + div() + .id("settings-close") + .absolute() + .top(px((TITLE_BAR_HEIGHT - 26.) / 2.)) + .right(px(12.)) + .size(px(26.)) + .rounded(px(6.)) + .flex() + .items_center() + .justify_center() + .occlude() + .cursor_pointer() + .hover(move |s| s.bg(tk.k05)) + .child( + Icon::empty() + .path("icons/settings/close.svg") + .size(px(10.)) + .text_color(tk.k45), + ) + .tooltip(|window, cx| { + gpui_component::tooltip::Tooltip::new(t(L10nKey::Close)).build(window, cx) + }) + .on_click( + cx.listener(|this, _, window, cx| this.close_settings_checked(window, cx)), + ), + ) + // While a popover is open the page under it only takes one click: + // the one that closes it. + .when(menu_open, |r| { + r.child( + div() + .id("settings-popover-scrim") + .absolute() + .top_0() + .left_0() + .size_full() + .occlude() + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, _, window, cx| this.close_settings_menu(window, cx)), + ) + .on_mouse_down( + MouseButton::Right, + cx.listener(|this, _, window, cx| this.close_settings_menu(window, cx)), + ), + ) + }); + + if let Some((start, label)) = prof { + crate::ui::perf::record(label, start.elapsed()); + } + root + } + + /// The save failures and the unsaved theme draft, said at the top of the + /// page with what can be done about them. + fn render_settings_notices(&self, cx: &mut Context) -> Vec { + let tk = Tk::of(cx); + let mut out = Vec::new(); + let notice = |text: String, tk: &Tk| { + div() + .text_size(fs(12.5)) + .line_height(px(18.)) + .text_color(tk.fg) + .child(text) + }; + if self.theme_draft_dirty() { + let error = self + .active_settings() + .and_then(|s| s.theme_draft_error.clone()); + out.push( + v_flex() + .gap(px(10.)) + .child(notice(t(L10nKey::SettingsThemeDraft).to_string(), &tk)) + .when_some(error, |v, error| { + v.child( + div() + .text_size(fs(12.)) + .text_color(tk.danger) + .child(t_fmt(L10nKey::SettingsSaveError, &[("error", &error)])), + ) + }) + .child( + h_flex() + .gap(px(8.)) + .child( + kit::button( + "save-theme-draft", + t(L10nKey::SettingsSaveChanges), + BtnKind::Primary, + ) + .on_click(cx.listener( + |this, _, window, cx| { + this.save_theme_draft(window, cx); + }, + )), + ) + .child( + kit::button( + "cancel-theme-draft", + t(L10nKey::Cancel), + BtnKind::Secondary, + ) + .on_click(cx.listener( + |this, _, window, cx| this.cancel_theme_draft(window, cx), + )), + ), + ) + .into_any_element(), + ); + } + if let Some(error) = self.active_settings().and_then(|s| s.save_error.clone()) { + out.push( + v_flex() + .gap(px(10.)) + .child( + div() + .text_size(fs(12.5)) + .text_color(tk.danger) + .child(t_fmt(L10nKey::SettingsSaveError, &[("error", &error)])), + ) + .child( + h_flex().child( + kit::button( + "retry-settings-save", + t(L10nKey::SettingsRetrySave), + BtnKind::Secondary, + ) + .on_click( + cx.listener(|this, _, _window, cx| { + this.persist_settings_config(cx) + }), + ), + ), + ) + .into_any_element(), + ); + } + out + } + + fn render_settings_nav( + &self, + width: f32, + searching: bool, + cx: &mut Context, + ) -> AnyElement { + let tk = Tk::of(cx); + let Some(s) = self.active_settings() else { + return div().into_any_element(); + }; + let section = s.section.navigation_section(); + let search = s.search.clone(); + let modified_only = s.modified_only; + let cfg = cx.global::(); + let modified_in = |target: SettingsSection| { + settings_search_entries() + .iter() + .filter(|e| e.section == target && e.modified(cfg)) + .count() + }; + let counts: Vec<(SettingsSection, usize)> = SettingsSection::ALL + .iter() + .map(|&target| (target, modified_in(target))) + .collect(); + let total: usize = counts.iter().map(|(_, n)| n).sum(); + let search_focused = self.settings_input_focused(&search, cx); + + let items = counts.into_iter().map(|(target, count)| { + let active = !searching && section == target; + h_flex() + .id(SharedString::from(format!( + "settings-nav-{}", + target.profile_label() + ))) + .h(px(28.)) + .px(px(8.)) + .gap(px(10.)) + .items_center() + .rounded(px(7.)) + .cursor_pointer() + .when(active, |r| r.bg(tk.k07)) + .when(!active, |r| r.hover(move |s| s.bg(tk.k04))) + .child( + Icon::empty() + .path(target.icon_path()) + .size(px(14.)) + .text_color(if active { tk.fg } else { tk.nav }), + ) + .child( + div() + .flex_1() + .min_w_0() + .truncate() + .text_color(if active { tk.fg } else { tk.nav }) + .when(active, |d| d.font_weight(FontWeight::MEDIUM)) + .child(t(target.title())), + ) + .when(count > 0, |r| { + r.child( + div() + .text_size(fs(11.5)) + .text_color(tk.k4) + .child(count.to_string()), + ) + }) + .on_click(cx.listener(move |this, _, window, cx| { + this.navigate_settings(target, None, window, cx) + })) + }); + + v_flex() + .w(px(width)) + .flex_shrink_0() + .h_full() + // The main window's tab rail fill, so the two sidebars read as the + // same surface. Opaque: the rail's translucency rule would let the + // page behind show through. + .bg(gpui::rgb(cx.global::().rail.base)) + .border_r_1() + .border_color(tk.k08) + .child(div().h(px(TITLE_BAR_HEIGHT)).flex_shrink_0()) + .child( + div() + .px(px(12.)) + .pt(px(4.)) + .pb(px(16.)) + .flex_shrink_0() + .child( + h_flex() + .h(px(28.)) + .px(px(8.)) + .gap(px(7.)) + .items_center() + .rounded(px(7.)) + .bg(tk.k04) + .child(kit::search_glass(11., &tk)) + .child( + div().flex_1().min_w_0().child( + Input::new(&search) + .appearance(false) + .px_0() + .py_0() + .h(px(26.)), + ), + ) + .when(!search_focused, |r| { + r.child(div().text_size(fs(11.)).text_color(tk.k35).child( + if cfg!(target_os = "macos") { + "⌘F" + } else { + "Ctrl F" + }, + )) + }), + ), + ) + .child( + v_flex() + .id("settings-nav") + .flex_1() + .min_h_0() + .overflow_y_scroll() + .px(px(12.)) + .gap(px(1.)) + .children(items), + ) + .child( + div().p(px(12.)).border_t_1().border_color(tk.k08).child( + h_flex() + .id("settings-modified-filter") + .h(px(28.)) + .px(px(8.)) + .gap(px(10.)) + .items_center() + .rounded(px(7.)) + .cursor_pointer() + .hover(move |s| s.bg(tk.k05)) + .child( + div() + .flex_1() + .min_w_0() + .truncate() + .text_color(tk.k6) + .child(t(L10nKey::SettingsModifiedOnly)), + ) + .when(total > 0, |r| { + r.child( + div() + .text_size(fs(11.5)) + .text_color(tk.k4) + .child(total.to_string()), + ) + }) + .child( + kit::switch("settings-modified-switch") + .small() + .checked(modified_only), + ) + .on_click(cx.listener(|this, _, _window, cx| { + if let Some(s) = this.active_settings_mut() { + s.modified_only = !s.modified_only; + } + this.autoselect_settings_search(cx); + })), + ), + ) + .into_any_element() + } + + /// Keys the page handles before any control sees them: ⌘F to the search, + /// and the arrows and Enter walking the search results. + fn settings_capture_key( + &mut self, + searching: bool, + ev: &KeyDownEvent, + window: &mut Window, + cx: &mut Context, + ) { + let key = ev.keystroke.key.as_str(); + if key == "f" && ev.keystroke.modifiers.secondary() && !ev.keystroke.modifiers.shift { + if let Some(s) = self.active_settings() { + let handle = s.search.read(cx).focus_handle(cx); + window.focus(&handle, cx); + if let Some(s) = self.active_settings_mut() { + s.menu = None; + } + cx.stop_propagation(); + cx.notify(); + } + return; + } + if !searching + || !self + .active_settings() + .is_some_and(|s| s.search.read(cx).focus_handle(cx).is_focused(window)) + || !matches!(key, "up" | "down" | "enter") + { + return; + } + let Some(s) = self.active_settings() else { + return; + }; + let query = s.search.read(cx).value().trim().to_lowercase(); + let entries = search_result_order(&query, s.modified_only, cx.global::()); + let actions = search_result_actions(&query, s.modified_only); + let count = entries.len() + actions.len(); + if count > 0 { + let index = s.search_selection.min(count - 1); + if key == "enter" && index >= entries.len() { + let action = actions[index - entries.len()].clone(); + self.open_shortcut_search(action, window, cx); + } else if key == "enter" { + let entry = entries[index]; + let target = if entry.title == L10nKey::SettingsSearchKeybindingsTitle { + SettingsSection::Keybindings + } else { + entry.section + }; + self.navigate_settings(target, Some(entry.title), window, cx); + } else if let Some(s) = self.active_settings_mut() { + s.search_selection = if key == "down" { + (index + 1).min(count - 1) + } else { + index.saturating_sub(1) + }; + s.reveal_first_hit.set(true); + cx.notify(); + } + } + cx.stop_propagation(); + } + + /// Opens the shortcut editor filtered to one action. + pub(crate) fn open_shortcut_search( + &mut self, + action: String, + window: &mut Window, + cx: &mut Context, + ) { + self.with_settings_edits_resolved(window, cx, move |this, window, cx| { + this.navigate_settings(SettingsSection::Keybindings, None, window, cx); + if let Some(s) = this.active_settings() { + s.shortcut_search + .clone() + .update(cx, |s, cx| s.set_value(action, window, cx)); + } + }); + } + + /// Search results and the "modified" filter: the matching rows, live, + /// grouped under the page each lives on. + fn render_settings_results( + &self, + cx: &mut Context, + ) -> (String, Option, AnyElement) { + let tk = Tk::of(cx); + let Some(state) = self.active_settings() else { + return (String::new(), None, div().into_any_element()); + }; + let query = state.search.read(cx).value().trim().to_lowercase(); + let modified_only = state.modified_only; + let selection = state.search_selection; + *state.search_rows.borrow_mut() = Some(Vec::new()); + // Build each page that has a match once, and keep only the matching + // rows. Discarded page chrome never enters the element tree, so the + // controls keep their usual ids. + for section in SettingsSection::ALL { + if !settings_search_entries().iter().any(|entry| { + entry.section == section + && entry_matches(entry, &query) + && (!modified_only || entry.modified(cx.global::())) + }) { + continue; + } + match section { + SettingsSection::General => { + self.render_settings_general(cx); + } + SettingsSection::Appearance => { + self.render_settings_appearance(cx); + } + SettingsSection::Terminal => { + self.render_settings_terminal(cx); + } + SettingsSection::KeyboardMouse => { + self.render_settings_input(cx); + } + SettingsSection::WindowTabs => { + self.render_window_preferences(cx); + } + SettingsSection::Ssh => { + self.render_ssh_connection_rows(cx); + } + SettingsSection::Agents => { + self.render_command_line_rows(cx); + } + SettingsSection::About => { + self.render_settings_about(cx); + } + SettingsSection::Keybindings => {} + } + } + let mut controls = self + .active_settings() + .unwrap() + .search_rows + .borrow_mut() + .take() + .unwrap_or_default(); + let matches = search_result_order(&query, modified_only, cx.global::()); + let actions = search_result_actions(&query, modified_only); + + let mut groups: Vec = Vec::new(); + let mut index = 0usize; + for section in SettingsSection::ALL { + let here: Vec<&&SearchEntry> = + matches.iter().filter(|e| e.section == section).collect(); + if here.is_empty() { + continue; + } + let mut rows = Vec::new(); + for entry in here { + let title = entry.title; + let target = if title == L10nKey::SettingsSearchKeybindingsTitle { + SettingsSection::Keybindings + } else { + entry.section + }; + let control = controls + .iter() + .position(|(key, _)| *key == title) + .map(|i| controls.remove(i).1); + let selected = index == selection; + let row = control.unwrap_or_else(|| { + self.settings_row( + t(title), + entry.description(), + kit::button( + SharedString::from(format!("search-open-{title:?}")), + t(L10nKey::SettingsOpenSetting), + BtnKind::Secondary, + ) + .on_click(cx.listener(move |this, _, window, cx| { + this.navigate_settings(target, Some(title), window, cx) + })) + .into_any_element(), + cx, + ) + .into_any_element() + }); + rows.push( + div() + .id(SharedString::from(format!("search-result-{title:?}"))) + .when(selected, |d| { + d.bg(tk.k04).rounded(px(7.)).mx(px(-8.)).px(px(8.)) + }) + .when_some( + self.active_settings() + .filter(|_| selected) + .map(|s| s.search_anchor.clone()), + |d, anchor| d.anchor_scroll(Some(anchor)), + ) + .child(row) + .into_any_element(), + ); + index += 1; + } + groups.push( + v_flex() + .child( + div() + .id(SharedString::from(format!( + "search-page-{}", + section.profile_label() + ))) + .pb(px(8.)) + .text_size(fs(11.5)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(tk.heading) + .cursor_pointer() + .hover(move |s| s.text_color(tk.fg)) + .child(t(section.title())) + .on_click(cx.listener(move |this, _, window, cx| { + this.navigate_settings(section, None, window, cx) + })), + ) + .children(rows) + .into_any_element(), + ); + } + + // Action names stay searchable without a whole shortcut editor in the + // results: each one is a row that opens the editor on it. + if !actions.is_empty() { + let effective = crate::ui::keymap::effective_chords(cx); + let mut rows = Vec::new(); + for action in actions.iter() { + let (_, label) = crate::ui::keymap::action_entry(action); + let chords = effective + .iter() + .find(|(a, _)| a == action) + .and_then(|(_, keys)| keys.first().cloned()) + .unwrap_or_default(); + let selected = index == selection; + let action = action.clone(); + rows.push( + h_flex() + .id(SharedString::from(format!("search-shortcut-{index}"))) + .h(px(34.)) + .mx(px(-8.)) + .px(px(8.)) + .gap(px(16.)) + .items_center() + .rounded(px(7.)) + .cursor_pointer() + .when(selected, |d| d.bg(tk.k04)) + .hover(move |s| s.bg(tk.k04)) + .when_some( + self.active_settings() + .filter(|_| selected) + .map(|s| s.search_anchor.clone()), + |d, anchor| d.anchor_scroll(Some(anchor)), + ) + .child(div().flex_1().min_w_0().truncate().child(label)) + .child(Self::keycap_row(&chords, &tk)) + .on_click(cx.listener(move |this, _, window, cx| { + this.open_shortcut_search(action.clone(), window, cx) + })) + .into_any_element(), + ); + index += 1; + } + groups.push( + v_flex() + .child(kit::section_head( + t(L10nKey::SettingsSearchKeybindingsTitle), + None, + &tk, + )) + .children(rows) + .into_any_element(), + ); + } + + let total = index; + let title = if modified_only && query.is_empty() { + t(L10nKey::SettingsModifiedTitle).to_string() + } else { + t(L10nKey::SettingsSearchResults).to_string() + }; + let subtitle = (!(modified_only && query.is_empty())) + .then(|| t_plural(L10nKey::SettingsMatchCount, total, &[])); + if groups.is_empty() { + let text = if modified_only && query.is_empty() { + t(L10nKey::SettingsNothingModified).to_string() + } else if modified_only { + t(L10nKey::SettingsNoModified).to_string() + } else { + t_fmt(L10nKey::SettingsNothingMatches, &[("query", &query)]) + }; + groups.push( + div() + .py(px(24.)) + .text_color(tk.k35) + .child(text) + .into_any_element(), + ); + } + (title, subtitle, Self::settings_page(groups)) + } + + /// A shortcut as keycaps: `⌘ T`, `⌃B then X`. + pub(crate) fn keycap_row(spec: &str, tk: &Tk) -> Div { + let chords = crate::ui::keymap::key_chords(spec); + h_flex() + .flex_shrink_0() + .gap(px(5.)) + .items_center() + .children(chords.into_iter().enumerate().map(|(i, chord)| { + h_flex() + .gap(px(5.)) + .items_center() + .when(i > 0, |d| { + d.child( + div() + .text_size(fs(11.)) + .text_color(tk.k4) + .child(t(L10nKey::SettingsKeyThen)), + ) + }) + .child( + h_flex() + .gap(px(2.)) + .children(chord.into_iter().map(|key| kit::keycap(key, tk))), + ) + })) + } +} + +/// The search results in the order the page draws them: grouped by page in +/// nav order, best match first within each. +pub(crate) fn search_result_order<'a>( + query: &str, + modified_only: bool, + cfg: &Config, +) -> Vec<&'a SearchEntry> { + let mut matches: Vec<&SearchEntry> = settings_search_entries() + .iter() + .filter(|entry| entry_matches(entry, query) && (!modified_only || entry.modified(cfg))) + .collect(); + matches.sort_by_key(|entry| { + ( + SettingsSection::ALL + .iter() + .position(|&s| s == entry.section) + .unwrap_or(0), + entry.rank(query), + ) + }); + matches +} + +/// The shortcut actions a query names, after the settings it matched. +pub(crate) fn search_result_actions(query: &str, modified_only: bool) -> Vec { + if query.is_empty() || modified_only { + return Vec::new(); + } + crate::ui::keymap::default_bindings() + .into_iter() + .filter(|(action, _)| keybinding_matches_query(action, query)) + .map(|(action, _)| action.to_string()) + .collect() +} diff --git a/src/ui/settings/shortcuts.rs b/src/ui/settings/shortcuts.rs new file mode 100644 index 00000000..1763826d --- /dev/null +++ b/src/ui/settings/shortcuts.rs @@ -0,0 +1,339 @@ +//! Keyboard shortcuts: every action in the palette's groups, each with its +//! keys as keycaps. Click the keys to record new ones; a chord another action +//! already has asks before it is taken over. + +use super::kit::{BtnKind, Tk, fs}; +use super::*; + +impl Tty7App { + pub(crate) fn render_settings_keybindings(&self, cx: &mut Context) -> AnyElement { + let tk = Tk::of(cx); + let Some(s) = self.active_settings() else { + return div().into_any_element(); + }; + let search = s.shortcut_search.clone(); + let query = search.read(cx).value().trim().to_lowercase(); + let recording = s + .recording + .as_ref() + .map(|r| (r.action.clone(), r.chords.clone())); + let conflict = s + .kb_conflict + .as_ref() + .map(|c| (c.action.clone(), c.spec.clone(), c.other.clone())); + let note = s.rebinding_note.clone(); + + let (preset, prefix, overridden) = { + let cfg = cx.global::(); + let overridden: std::collections::HashSet = + cfg.keybindings.keys().cloned().collect(); + ( + cfg.keybinding_preset.clone(), + cfg.prefix.clone(), + overridden, + ) + }; + let tmux = preset == "tmux"; + let changed = overridden.len(); + let effective = crate::ui::keymap::effective_chords(cx); + + // The toolbar: the filter, a way back from every change at once, and + // the preset the whole table starts from. + let presets = self.segmented( + "kb-preset", + &[t(L10nKey::SettingsDefault), "tmux"], + usize::from(tmux), + cx, + |this, ix, _w, cx| { + this.set_keybinding_preset(if ix == 0 { "default" } else { "tmux" }, cx) + }, + ); + let toolbar = + h_flex() + .gap(px(12.)) + .items_center() + .child( + kit::search_field(&search, &tk) + .h(px(28.)) + .flex_1() + .max_w(px(300.)), + ) + .child(div().flex_1()) + .when(changed > 0, |r| { + r.child( + kit::button( + "kb-restore-all", + t_plural(L10nKey::SettingsRestoreChanged, changed, &[]), + BtnKind::Link, + ) + .on_click(cx.listener(|this, _, _w, cx| { + this.restore_default_keybindings_confirmed(cx) + })), + ) + }) + .child(presets); + let hint = div() + .text_size(fs(12.)) + .line_height(px(17.)) + .text_color(tk.k45) + .child(if tmux { + t(L10nKey::SettingsShortcutsHintTmux) + } else { + t(L10nKey::SettingsShortcutsHint) + }); + let prefix_row = tmux.then(|| { + h_flex() + .gap(px(10.)) + .items_center() + .child( + div() + .text_size(fs(12.)) + .text_color(tk.k5) + .child(t(L10nKey::SettingsPrefix)), + ) + .child(self.segmented( + "kb-prefix", + &["⌃B", "⌃A"], + usize::from(prefix == "ctrl-a"), + cx, + |this, ix, _w, cx| { + this.set_keybinding_prefix(if ix == 0 { "ctrl-b" } else { "ctrl-a" }, cx) + }, + )) + }); + let intro = v_flex() + .mt(px(-12.)) + .gap(px(10.)) + .child(toolbar) + .child(hint) + .children(prefix_row) + .when_some(note, |v, note| { + v.child(div().text_size(fs(12.)).text_color(tk.fg).child(note)) + }) + .into_any_element(); + + // The rows, in the palette's groups. + let mut grouped: Vec<( + crate::ui::palette::CommandGroup, + Vec<(String, Vec, String)>, + )> = Vec::new(); + for (action, keys) in effective { + let (group, label) = crate::ui::keymap::action_entry(&action); + if !query.is_empty() + && !keybinding_matches_query(&action, &query) + && !label.to_lowercase().contains(&query) + { + continue; + } + match grouped.iter_mut().find(|(g, _)| *g == group) { + Some((_, rows)) => rows.push((action, keys, label)), + None => grouped.push((group, vec![(action, keys, label)])), + } + } + grouped.sort_by_key(|(g, _)| { + crate::ui::palette::CommandGroup::ORDER + .iter() + .position(|o| o == g) + .unwrap_or(usize::MAX) + }); + + let mut groups = vec![intro]; + let none = grouped.is_empty(); + for (group, rows) in grouped { + let mut section = v_flex().child( + div() + .pb(px(6.)) + .text_size(fs(11.5)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(tk.heading) + .child(group.title()), + ); + for (action, keys, label) in rows { + let is_recording = recording.as_ref().is_some_and(|(a, _)| *a == action); + let conflict_here = conflict.as_ref().filter(|(a, _, _)| *a == action); + let shown: Vec = match (&recording, conflict_here) { + (Some((a, chords)), _) if *a == action => vec![chords.join(" ")] + .into_iter() + .filter(|c| !c.is_empty()) + .collect(), + (_, Some((_, spec, _))) => vec![spec.clone()], + _ => keys, + }; + let modified = overridden.contains(&action) && !is_recording; + let ring = if is_recording { + vec![kit::ring(tk.fg, 1., true)] + } else if conflict_here.is_some() { + vec![kit::ring(tk.warn, 1., true)] + } else { + Vec::new() + }; + let hover_ring = if is_recording || conflict_here.is_some() { + vec![kit::ring(tk.fg, 1., true)] + } else { + vec![kit::ring(tk.k15, 0.5, true)] + }; + let record_action = action.clone(); + let keys_button = h_flex() + .id(SharedString::from(format!("kb-{action}"))) + .h(px(26.)) + .min_w(px(72.)) + .pl(px(8.)) + .pr(px(4.)) + .gap(px(5.)) + .items_center() + .justify_end() + .rounded(px(6.)) + .cursor_pointer() + .when(is_recording, |b| b.bg(tk.page)) + .shadow(ring) + .hover(move |b| b.shadow(hover_ring.clone())) + .when(is_recording && shown.is_empty(), |b| { + b.child( + div() + .pr(px(2.)) + .text_size(fs(12.)) + .text_color(tk.k45) + .child(t(L10nKey::SettingsPressKeysShort)), + ) + }) + .children(shown.iter().enumerate().map(|(n, spec)| { + h_flex() + .gap(px(5.)) + .items_center() + .when(n > 0, |d| { + d.child(div().text_size(fs(11.)).text_color(tk.k4).child("/")) + }) + .child(Self::keycap_row(spec, &tk)) + })) + .when(!is_recording && shown.is_empty(), |b| { + b.child( + div() + .pr(px(4.)) + .text_size(fs(12.)) + .text_color(tk.k3) + .child("—"), + ) + }) + .on_click(cx.listener(move |this, _, window, cx| { + let already = this + .active_settings() + .and_then(|s| s.recording.as_ref()) + .is_some_and(|r| r.action == record_action); + if already { + if let Some(s) = this.active_settings_mut() { + s.recording = None; + } + cx.notify(); + } else { + this.start_recording_key(record_action.clone(), window, cx) + } + })); + let reset_action = action.clone(); + let row = h_flex() + .h(px(34.)) + .px(px(8.)) + .gap(px(16.)) + .items_center() + .justify_between() + .rounded(px(7.)) + .when(conflict_here.is_none(), |r| r.hover(move |s| s.bg(tk.k04))) + .child( + h_flex() + .flex_1() + .min_w_0() + .gap(px(8.)) + .items_center() + .child(div().min_w_0().truncate().child(label)) + .when(modified, |r| { + r.child( + div() + .id(SharedString::from(format!("reset-{action}"))) + .flex_shrink_0() + .text_size(fs(11.5)) + .text_color(tk.k4) + .cursor_pointer() + .hover(move |s| s.text_color(tk.fg)) + .child(t(L10nKey::Reset)) + .on_click(cx.listener(move |this, _, _w, cx| { + this.reset_keybinding(reset_action.clone(), cx) + })), + ) + }), + ) + .child(keys_button); + let conflict_line = conflict_here.map(|(_, spec, other)| { + let keys = crate::ui::keymap::key_chords(spec) + .into_iter() + .map(|chord| chord.concat()) + .collect::>() + .join(&format!(" {} ", t(L10nKey::SettingsKeyThen))); + let other = crate::ui::keymap::action_entry(other) + .1 + .trim_end_matches('…') + .to_string(); + h_flex() + .px(px(8.)) + .pt(px(2.)) + .pb(px(10.)) + .gap(px(8.)) + .items_center() + .text_size(fs(12.)) + .text_color(tk.k6) + .child( + div() + .size(px(6.)) + .flex_shrink_0() + .rounded_full() + .bg(tk.warn), + ) + .child(div().flex_1().min_w_0().child(t_fmt( + L10nKey::SettingsShortcutConflict, + &[("keys", &keys), ("action", &other)], + ))) + .child( + kit::button( + "kb-conflict-replace", + t(L10nKey::SettingsReplace), + BtnKind::Primary, + ) + .text_size(fs(12.)) + .on_click(cx.listener( + |this, _, _w, cx| this.resolve_keybinding_conflict(true, cx), + )), + ) + .child( + kit::button( + "kb-conflict-cancel", + t(L10nKey::Cancel), + BtnKind::Secondary, + ) + .text_size(fs(12.)) + .on_click(cx.listener( + |this, _, _w, cx| this.resolve_keybinding_conflict(false, cx), + )), + ) + }); + section = section.child( + v_flex() + .mx(px(-8.)) + .rounded(px(7.)) + .when(conflict_line.is_some(), |d| d.bg(tk.k04)) + .child(row) + .children(conflict_line), + ); + } + groups.push(section.into_any_element()); + } + if none { + groups.push( + div() + .text_color(tk.k35) + .child(t_fmt(L10nKey::SettingsNoActionsMatch, &[("query", &query)])) + .into_any_element(), + ); + } + Self::settings_page(groups) + } +} + +use super::kit; diff --git a/src/ui/settings/theme_picker.rs b/src/ui/settings/theme_picker.rs new file mode 100644 index 00000000..d2c5e115 --- /dev/null +++ b/src/ui/settings/theme_picker.rs @@ -0,0 +1,695 @@ +//! Appearance's Theme group: the Light / Dark / System cards, one dropdown +//! per theme slot with a live preview of the theme under the pointer, and the +//! editor a duplicated theme opens. + +use std::rc::Rc; + +use super::kit::{self, BtnKind, Tk, fs}; +use super::*; + +fn rgb_of((r, g, b): (u8, u8, u8)) -> gpui::Rgba { + rgb((r as u32) << 16 | (g as u32) << 8 | b as u32) +} + +/// The colors a theme is recognised by at a glance. +struct Swatch { + bg: gpui::Rgba, + fg: gpui::Rgba, + dim: gpui::Rgba, + ansi: [gpui::Rgba; 16], +} + +impl Swatch { + fn of(p: &presets::Theme) -> Self { + let ansi = std::array::from_fn(|i| rgb_of(p.ansi16[i])); + Self { + bg: rgb(p.background_color()), + fg: rgb(p.foreground), + dim: rgb_of(p.ansi16[8]), + ansi, + } + } +} + +impl Tty7App { + fn theme_mode(cx: &App) -> ThemeMode { + let cfg = cx.global::(); + if cfg.theme_follow_system { + ThemeMode::System + } else if presets::by_id(cx, &cfg.theme_preset).dark { + ThemeMode::Dark + } else { + ThemeMode::Light + } + } + + pub(crate) fn render_theme_group(&self, cx: &mut Context) -> AnyElement { + let tk = Tk::of(cx); + let mode = Self::theme_mode(cx); + let cfg = cx.global::(); + let (light_id, dark_id) = ( + cfg.theme_preset_light.clone(), + cfg.theme_preset_dark.clone(), + ); + let legible = cfg.theme_legible_palette; + let light = Swatch::of(&presets::by_id(cx, &light_id)); + let dark = Swatch::of(&presets::by_id(cx, &dark_id)); + + let modes = [ + (ThemeMode::Light, t(L10nKey::SettingsLight), vec![&light]), + (ThemeMode::Dark, t(L10nKey::SettingsDark), vec![&dark]), + ( + ThemeMode::System, + t(L10nKey::SettingsThemeModeSystem), + vec![&light, &dark], + ), + ]; + let mode_cards = h_flex() + .gap(px(14.)) + .children(modes.into_iter().map(|(m, label, halves)| { + let on = m == mode; + let bar = |w: f32, c: gpui::Rgba| div().w(px(w)).h(px(3.)).rounded(px(1.)).bg(c); + v_flex() + .id(SharedString::from(format!("theme-mode-{m:?}"))) + .items_center() + .gap(px(7.)) + .cursor_pointer() + .child( + h_flex() + .w(px(76.)) + .h(px(50.)) + .rounded(px(6.)) + .overflow_hidden() + .shadow(if on { + vec![kit::ring(tk.page, 1., false), kit::ring(tk.fg, 2.5, false)] + } else { + vec![kit::ring(tk.k15, 0.5, false)] + }) + .children(halves.into_iter().map(|s| { + v_flex() + .flex_1() + .min_w_0() + .h_full() + .bg(s.bg) + .justify_center() + .gap(px(5.)) + .px(px(9.)) + .overflow_hidden() + .child( + h_flex() + .gap(px(3.)) + .child(bar(4., s.ansi[2])) + .child(bar(26., s.fg)), + ) + .child( + h_flex() + .gap(px(3.)) + .child(bar(10., s.ansi[4])) + .child(bar(16., s.dim)), + ) + .child( + h_flex() + .gap(px(3.)) + .child(bar(6., s.ansi[3])) + .child(bar(20., s.dim)), + ) + })), + ) + .child( + div() + .text_size(fs(12.)) + .text_color(if on { tk.fg } else { tk.k5 }) + .when(on, |d| d.font_weight(FontWeight::MEDIUM)) + .child(label), + ) + .on_click( + cx.listener(move |this, _, window, cx| this.set_theme_mode(m, window, cx)), + ) + })) + .into_any_element(); + let mode_desc = match mode { + ThemeMode::System => t(L10nKey::SettingsThemeModeSystemDesc), + ThemeMode::Light => t(L10nKey::SettingsThemeModeLightDesc), + ThemeMode::Dark => t(L10nKey::SettingsThemeModeDarkDesc), + }; + + let mut rows = vec![ + self.settings_row( + t(L10nKey::SettingsSyncWithSystem), + mode_desc, + mode_cards, + cx, + ) + .into_any_element(), + ]; + let slots: Vec = match mode { + ThemeMode::System => vec![false, true], + ThemeMode::Light => vec![false], + ThemeMode::Dark => vec![true], + }; + for dark_slot in slots { + let desc = match (mode, dark_slot) { + (ThemeMode::System, false) => t(L10nKey::SettingsThemeSlotLightDesc), + (ThemeMode::System, true) => t(L10nKey::SettingsThemeSlotDarkDesc), + _ => t(L10nKey::SettingsThemeSlotDesc), + }; + let label = if dark_slot { + t(L10nKey::SettingsDarkThemeLabel) + } else { + t(L10nKey::SettingsLightThemeLabel) + }; + let control = self.theme_slot_dropdown(dark_slot, cx); + rows.push( + h_flex() + .min_h(px(52.)) + .py(px(12.)) + .gap(px(32.)) + .items_center() + .justify_between() + .child( + v_flex() + .min_w_0() + .gap(px(2.)) + .child(div().text_size(fs(13.)).child(label)) + .child( + div() + .text_size(fs(12.)) + .line_height(px(17.)) + .text_color(tk.k5) + .child(desc), + ), + ) + .child(control) + .into_any_element(), + ); + } + let legible = self.settings_switch( + "theme-legible-palette", + legible, + cx, + |this, on, window, cx| this.set_theme_legible_palette(on, window, cx), + ); + rows.push( + self.settings_row( + t(L10nKey::SettingsLegiblePalette), + t(L10nKey::SettingsLegiblePaletteDesc), + legible, + cx, + ) + .into_any_element(), + ); + self.settings_group(Some(t(L10nKey::SettingsThemeIntroTitle)), None, rows, cx) + } + + fn theme_slot_dropdown(&self, dark_slot: bool, cx: &mut Context) -> AnyElement { + let tk = Tk::of(cx); + let cfg = cx.global::(); + let current_id = match (cfg.theme_follow_system, dark_slot) { + (false, _) => cfg.theme_preset.clone(), + (true, true) => cfg.theme_preset_dark.clone(), + (true, false) => cfg.theme_preset_light.clone(), + }; + let current = presets::by_id(cx, ¤t_id); + let id: SharedString = if dark_slot { + "theme-slot-dark" + } else { + "theme-slot-light" + } + .into(); + let open = self.settings_menu_open(&id); + + let mut themes: Vec = presets::all(cx) + .into_iter() + .filter(|p| p.dark == dark_slot || p.id == current_id) + .collect(); + themes.sort_by_key(|p| p.path.is_some()); + let start = themes.iter().position(|p| p.id == current_id).unwrap_or(0); + + let sw = Swatch::of(¤t); + let leading = div() + .w(px(16.)) + .h(px(12.)) + .flex_shrink_0() + .rounded(px(3.)) + .bg(sw.bg) + .shadow(vec![kit::ring(tk.k15, 0.5, true)]) + .flex() + .items_center() + .px(px(3.)) + .child(div().w(px(6.)).h(px(2.)).rounded(px(1.)).bg(sw.fg)) + .into_any_element(); + let toggle = id.clone(); + let trigger = kit::select_trigger( + ElementId::Name(SharedString::from(format!("{id}-trigger"))), + current.name.clone(), + Some(leading), + open, + &tk, + ) + .on_click(cx.listener(move |this, _, window, cx| { + this.toggle_settings_menu(toggle.clone(), start, true, window, cx) + })); + + let popover = open.then(|| self.theme_popover(&id, dark_slot, ¤t_id, themes, cx)); + div() + .relative() + .flex_shrink_0() + .child(trigger) + .when_some(popover, |d, p| d.child(kit::popover_below(true, 6., p))) + .into_any_element() + } + + fn theme_popover( + &self, + id: &SharedString, + dark_slot: bool, + current_id: &str, + themes: Vec, + cx: &mut Context, + ) -> Div { + let tk = Tk::of(cx); + let Some(s) = self.active_settings() else { + return div(); + }; + let query = s.menu_query.read(cx).value().trim().to_lowercase(); + let visible: Vec = themes + .into_iter() + .filter(|p| query.is_empty() || p.name.to_lowercase().contains(&query)) + .collect(); + let hi = s.menu_hi.min(visible.len().saturating_sub(1)); + let preview_theme = visible + .get(hi) + .cloned() + .unwrap_or_else(|| presets::by_id(cx, current_id)); + let pv = Swatch::of(&preview_theme); + + // What the highlighted theme does to a shell session, before it is + // picked. + let (fg, dim) = (pv.fg, pv.dim); + let [_, r, g, y, b, m, ..] = pv.ansi; + let lines: [Vec<(&str, gpui::Rgba)>; 5] = [ + vec![ + ("~/code/orbit ", b), + ("main ", m), + ("❯ ", g), + ("git status -s", fg), + ], + vec![(" M ", y), ("src/server.ts", fg)], + vec![("?? ", r), ("notes.md", fg)], + vec![ + ("~/code/orbit ", b), + ("main ", m), + ("❯ ", g), + ("npm test", fg), + ], + vec![ + ("✓ 42 passed", g), + (" ", fg), + ("✗ 1 failed", r), + (" 0.8s", dim), + ], + ]; + let preview = div().p(px(8.)).child( + v_flex() + .rounded(px(6.)) + .bg(pv.bg) + .shadow(vec![kit::ring(tk.k08, 0.5, true)]) + .px(px(11.)) + .py(px(9.)) + .font_family(Tk::mono(cx)) + .text_size(fs(10.5)) + .line_height(px(16.)) + .children(lines.into_iter().map(|spans| { + h_flex().whitespace_nowrap().overflow_hidden().children( + spans + .into_iter() + .map(|(text, c)| div().text_color(c).child(text)), + ) + })), + ); + + let picks: Rc> = Rc::new(visible.iter().map(|p| p.id.clone()).collect()); + let mut list = v_flex() + .id(ElementId::Name(SharedString::from(format!("{id}-list")))) + .max_h(px(196.)) + .overflow_y_scroll() + .track_scroll(&s.menu_scroll) + .px(px(6.)) + .py(px(4.)) + .gap(px(1.)); + for (row, p) in visible.iter().enumerate() { + let sw = Swatch::of(p); + let pick = p.id.clone(); + list = list.child( + h_flex() + .id(ElementId::Name(SharedString::from(format!( + "theme-pick-{}", + p.id + )))) + .h(px(28.)) + .flex_shrink_0() + .px(px(8.)) + .gap(px(9.)) + .items_center() + .rounded(px(6.)) + .cursor_pointer() + .when(row == hi, |r| r.bg(tk.k06)) + .child(kit::check_mark(p.id == current_id, &tk)) + .child(div().flex_1().min_w_0().truncate().child(p.name.clone())) + .when(p.path.is_some(), |r| { + r.child( + div() + .text_size(fs(11.)) + .text_color(tk.k4) + .child(t(L10nKey::SettingsCustom)), + ) + }) + .child( + h_flex() + .gap(px(2.)) + .px(px(4.)) + .py(px(3.)) + .rounded(px(3.)) + .bg(sw.bg) + .shadow(vec![kit::ring(tk.k08, 0.5, true)]) + .children( + (1..=6).map(|i| div().size(px(5.)).rounded_full().bg(sw.ansi[i])), + ), + ) + .on_mouse_move(cx.listener(move |this, _, _, cx| { + if let Some(s) = this.active_settings_mut() + && s.menu_hi != row + { + s.menu_hi = row; + cx.notify(); + } + })) + .on_click(cx.listener(move |this, _, window, cx| { + this.close_settings_menu(window, cx); + this.pick_slot_theme(dark_slot, &pick, window, cx); + })), + ); + } + if visible.is_empty() { + list = list.child( + div() + .h(px(28.)) + .px(px(8.)) + .flex() + .items_center() + .text_color(tk.k35) + .child(t(L10nKey::SettingsNoThemesMatch)), + ); + } + // A theme file that fails to parse used to just not be in the list. + // This is a folder the user drops files into; "it isn't there" needs a + // reason attached. + let rejected = presets::rejected(cx); + let rejected_note = (!rejected.is_empty() && query.is_empty()).then(|| { + v_flex() + .px(px(14.)) + .py(px(8.)) + .gap(px(4.)) + .border_t_1() + .border_color(tk.k08) + .text_size(fs(11.5)) + .child( + div() + .text_color(tk.fg) + .child(t(L10nKey::SettingsThemesRejected)), + ) + .children(rejected.into_iter().map(|(name, why)| { + v_flex() + .child(div().text_color(tk.danger).child(name)) + .child(div().text_color(tk.k45).child(why)) + })) + }); + let fork_from = current_id.to_string(); + let key_picks = picks.clone(); + + kit::menu_panel(&tk) + .w(px(300.)) + .p_0() + .gap_0() + .overflow_hidden() + .capture_key_down(cx.listener(move |this, ev: &KeyDownEvent, window, cx| { + let key = ev.keystroke.key.as_str(); + let len = key_picks.len(); + match key { + "down" | "up" => { + if let Some(s) = this.active_settings_mut() { + let hi = s.menu_hi.min(len.saturating_sub(1)); + s.menu_hi = if key == "down" { + (hi + 1).min(len.saturating_sub(1)) + } else { + hi.saturating_sub(1) + }; + s.menu_scroll.scroll_to_item(s.menu_hi); + } + cx.stop_propagation(); + cx.notify(); + } + "enter" => { + let hi = this.active_settings().map(|s| s.menu_hi).unwrap_or(0); + if let Some(pick) = key_picks.get(hi.min(len.saturating_sub(1))).cloned() { + this.close_settings_menu(window, cx); + this.pick_slot_theme(dark_slot, &pick, window, cx); + } + cx.stop_propagation(); + } + "escape" => { + this.close_settings_menu(window, cx); + cx.stop_propagation(); + } + _ => {} + } + })) + .child(preview) + .child( + h_flex() + .h(px(32.)) + .px(px(14.)) + .gap(px(7.)) + .items_center() + .border_t_1() + .border_b_1() + .border_color(tk.k08) + .child(kit::search_glass(11., &tk)) + .child( + div().flex_1().min_w_0().child( + Input::new(&s.menu_query) + .appearance(false) + .px_0() + .py_0() + .h(px(28.)), + ), + ) + .child(div().text_size(fs(11.)).text_color(tk.k35).child("↑↓ ↵")), + ) + .child(list) + .children(rejected_note) + .child( + h_flex() + .h(px(34.)) + .px(px(14.)) + .gap(px(14.)) + .items_center() + .border_t_1() + .border_color(tk.k08) + .child( + kit::button( + "theme-duplicate", + t(L10nKey::SettingsDuplicateToEdit), + BtnKind::Link, + ) + .on_click(cx.listener( + move |this, _, window, cx| { + this.close_settings_menu(window, cx); + this.fork_slot_theme(dark_slot, &fork_from, window, cx); + }, + )), + ) + .child( + kit::button( + "theme-open-folder", + t(L10nKey::SettingsOpenThemesFolder), + BtnKind::Link, + ) + .on_click(cx.listener(|this, _, window, cx| { + this.close_settings_menu(window, cx); + this.open_themes_folder(window, cx); + })), + ), + ) + } + + /// Copies a slot's theme to a file of its own and puts the copy in the + /// slot, where the editor below picks it up. + fn fork_slot_theme( + &mut self, + dark_slot: bool, + id: &str, + window: &mut Window, + cx: &mut Context, + ) { + let theme = presets::by_id(cx, id); + match presets::fork_to_file(&theme) { + Ok(new_id) => { + presets::load_registry(cx); + self.pick_slot_theme(dark_slot, &new_id, window, cx); + } + Err(e) => { + log::warn!("failed to duplicate theme: {e}"); + crate::ui::host_ops::HostOps::notify_err( + window, + cx, + t(L10nKey::ThemeDuplicateFailed), + &e, + ); + } + } + } + + /// The editor a custom theme opens: its colors, its background image, and + /// the sixteen ANSI colors. + pub(crate) fn render_theme_editor_group(&self, cx: &mut Context) -> Option { + let tk = Tk::of(cx); + let editor = self + .active_settings() + .and_then(|s| s.theme_editor.as_ref())?; + let seed: Vec<(String, Entity)> = editor + .seed + .iter() + .map(|(edit, state)| { + ( + crate::ui::app::theme_edit_label(*edit).to_string(), + state.clone(), + ) + }) + .collect(); + let ansi: Vec> = + editor.ansi.iter().map(|(_, s)| s.clone()).collect(); + + let theme = presets::by_id(cx, &crate::ui::theme::effective_preset_id(cx)); + let image = theme.image.clone(); + let image_name = image.as_ref().map(|i| { + i.path + .file_name() + .map(|n| n.to_string_lossy().to_string()) + .unwrap_or_else(|| i.path.display().to_string()) + }); + + let mut rows: Vec = seed + .into_iter() + .map(|(label, state)| { + self.settings_row( + label, + "", + ColorPicker::new(&state).small().into_any_element(), + cx, + ) + .into_any_element() + }) + .collect(); + + let image_control = h_flex() + .gap(px(12.)) + .items_center() + .when_some(image_name.clone(), |r, name| { + r.child( + div() + .max_w(px(160.)) + .truncate() + .text_size(fs(12.)) + .text_color(tk.k5) + .child(name), + ) + .child( + kit::button( + "remove-theme-image", + t(L10nKey::SettingsRemoveThemeImage), + BtnKind::Link, + ) + .on_click( + cx.listener(|this, _, window, cx| this.remove_theme_image(window, cx)), + ), + ) + }) + .child( + kit::button( + "pick-theme-image", + if image.is_some() { + t(L10nKey::SettingsChangeThemeImage) + } else { + t(L10nKey::SettingsChooseThemeImage) + }, + BtnKind::Secondary, + ) + .on_click(cx.listener(|this, _, _w, cx| this.pick_theme_image(cx))), + ) + .into_any_element(); + rows.push( + self.settings_row( + t(L10nKey::SettingsBackgroundImage), + t(L10nKey::SettingsBackgroundImageDesc), + image_control, + cx, + ) + .into_any_element(), + ); + if let Some(img) = image { + let app = cx.entity().downgrade(); + let control = kit::slider( + "theme-image-opacity", + img.opacity, + format!("{:.0}%", img.opacity * 100.), + &tk, + Rc::new(move |f, window, cx| { + let v = (f * 100.).round() / 100.; + let _ = app.update(cx, |this, cx| this.set_theme_image_opacity(v, window, cx)); + }), + Rc::new(|_, _| {}), + ); + rows.push( + self.settings_row( + t(L10nKey::SettingsImageOpacity), + t(L10nKey::SettingsImageOpacityDesc), + control, + cx, + ) + .into_any_element(), + ); + } + let ansi_grid = v_flex() + .gap(px(6.)) + .children(ansi.chunks(8).map(|chunk| { + h_flex() + .gap(px(6.)) + .children(chunk.iter().map(|state| ColorPicker::new(state).small())) + })) + .into_any_element(); + rows.push( + self.settings_row(t(L10nKey::SettingsAnsiColors), "", ansi_grid, cx) + .into_any_element(), + ); + rows.push( + h_flex() + .pt(px(4.)) + .child( + kit::button( + "open-themes-folder", + t(L10nKey::SettingsOpenThemesFolder), + BtnKind::Link, + ) + .on_click(cx.listener(|this, _, w, cx| this.open_themes_folder(w, cx))), + ) + .into_any_element(), + ); + Some(self.settings_group( + Some(t(L10nKey::SettingsEditTheme)), + Some(t(L10nKey::SettingsEditThemeIntro).to_string()), + rows, + cx, + )) + } +} diff --git a/src/ui/theme.rs b/src/ui/theme.rs index 70a88d70..a4eaea3e 100644 --- a/src/ui/theme.rs +++ b/src/ui/theme.rs @@ -977,12 +977,6 @@ pub(crate) fn inverted_button( .active(ink.blend(surface.opacity(0.24))) } -/// On-state shares the accent role with sliders and primary actions. -pub(crate) fn switch(id: impl Into, cx: &App) -> gpui_component::switch::Switch { - let accent = cx.global::().0; - gpui_component::switch::Switch::new(id).color(Hsla::from(rgb(accent))) -} - pub(crate) fn apply_cursor_hide_mode(cx: &mut App) { let mode = if cx.global::().mouse_hide_while_typing { gpui::CursorHideMode::OnTypingAndAction