Skip to content

A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.

wezterm-gui: the interface follows the terminal's colours

RoversX4297748fef57
diff --git a/docs/thinkterm/ui-colors.md b/docs/thinkterm/ui-colors.md
new file mode 100644
index 00000000..f6d12fe3
--- /dev/null
+++ b/docs/thinkterm/ui-colors.md
@@ -0,0 +1,109 @@
+# Interface colours
+
+**Status:** both `config.ui_colors` and Settings → Appearance → Theme →
+*Follow terminal colours* have landed.
+
+ThinkTerm paints two sets of colours. [`colors`](../config/lua/config/colors.md)
+and `color_scheme` set the palette your *programs* draw with. `ui_colors` sets
+the colours ThinkTerm draws *around* them: the sidebars, the tab bar, the bars
+above each pane, the settings window and the menus.
+
+The interface ships two hand-tuned palettes, one light and one dark, chosen by
+Settings → Appearance → Theme. A fourth choice there, **Follow terminal
+colours**, derives them from whichever scheme the terminal is using instead, so
+a Gruvbox terminal gets a Gruvbox sidebar. `ui_colors` overrides either, slot by
+slot.
+
+## Follow terminal colours
+
+The derivation does not invent a palette per scheme. It takes the hand-tuned
+one and *moves* it onto the scheme's background, keeping every relationship
+that palette already encodes -- which surface sits above which, by how much, at
+what alpha -- and taking the scheme's tint. Light or dark is then read off the
+scheme's own background rather than being a separate choice.
+
+Two deliberate limits:
+
+- **The accent stays.** A scheme's own blue is frequently unreadable against
+ its own background, and the accent is the one slot where being wrong is loud.
+ `accent`, `accent_hover`, `on_accent`, `selected_bg`, `danger` and
+ `spelling_error` keep their values; set them through `ui_colors` if you want
+ them to match too.
+- **Text is held to a contrast floor** against the hardest of the surfaces it
+ is read on -- 7:1 for primary, 4.5:1 for secondary, 3:1 for muted. The
+ Spaces strip is recessed from the window, so a colour held to its floor
+ against the window alone would sit under it on the strip. A scheme whose
+ foreground sits close to its background would otherwise produce a sidebar
+ whose secondary text is a rumour. This is why a derived colour is sometimes
+ not exactly the shade the arithmetic asked for.
+- **The ramp is slid to fit, not clipped.** On a scheme whose background is at
+ the very top or bottom of the range there is no room above or below it for
+ every surface, so the whole set moves together rather than each surface
+ pinning to the end on its own. A pure-white scheme therefore gets a faintly
+ grey sidebar: the alternative is a control, its hover state and a card all
+ being the same white.
+
+Previewing a scheme in the command palette moves the interface too, so what
+you see while arrowing through the list is what you get when you press Enter.
+The preview is shown, never sent: a remote pane renders it without telling the
+mux server, and Escape leaves nothing behind.
+
+One thing does not follow yet:
+
+- **The Live Overview** draws from its own set of colours.
+
+## Setting it
+
+Every field is optional and overrides exactly one slot. Whatever you leave
+unset keeps the colour the interface would have used, so a file that names two
+colours changes two colours:
+
+```lua
+config.ui_colors = {
+ sidebar_bg = '#282828',
+ accent = '#d79921',
+}
+```
+
+Colours are written the same way as everywhere else in the configuration:
+`#RGB`, `#RRGGBB`, `#RRGGBBAA`, `rgb:`/`rgba:`, `hsl:`, or a CSS colour name.
+
+Use `wezterm.config_builder()` and a misspelled slot is a startup error that
+names the closest matches; with a plain table it is silently ignored, as it is
+for every other option.
+
+## The slots
+
+**Surfaces** -- `window_bg` (the ground behind everything), `sidebar_bg`,
+`workspace_sidebar_bg` (the Spaces strip, recessed from the sidebar),
+`header_bg` (the strip above the tabs), `card_bg` (a grouped card floating on
+`window_bg`).
+
+**Controls** -- `control_bg` at rest, `control_hover_bg` under the pointer,
+`control_pressed_bg` while held, `control_border` for the hairline outline,
+`track_off` for the off half of a switch, `separator` for rules.
+
+**The sidebar** -- `sidebar_button_bg` and `sidebar_button_hover_bg` for the
+round buttons; `sidebar_row_hover_bg`, `sidebar_row_pressed_bg`,
+`sidebar_row_active_bg` and `sidebar_row_active_border` for thread rows.
+
+**Accent and state** -- `accent` (focus rings, switches, the active state),
+`accent_hover`, `on_accent` (what is drawn on top of the accent), `selected_bg`,
+`danger`.
+
+**Text** -- `text`, `secondary_text`, `muted_text`, `selected_text`,
+`scrollbar_thumb`, `spelling_error`.
+
+## Two things to know
+
+A colour you name wins over everything else, including the tuning the context
+and command menus apply to their own cards. If you set `control_bg`, every
+control gets it.
+
+Some slots are translucent by default -- `separator`, `control_border`,
+`card_bg` and `scrollbar_thumb` among them -- so that they pick up whatever is
+painted behind. A value you set replaces the whole colour, alpha included, so
+give an opaque colour only if you want an opaque result.
+
+Like every other option this can be set per window from lua:
+`window:set_config_overrides { ui_colors = { ... } }`.
diff --git a/thinkterm-i18n/i18n/de-DE.ftl b/thinkterm-i18n/i18n/de-DE.ftl
index 444edc8f..5456035c 100644
--- a/thinkterm-i18n/i18n/de-DE.ftl
+++ b/thinkterm-i18n/i18n/de-DE.ftl
@@ -62,6 +62,7 @@ settings-theme-description = Legen Sie fest, ob ThinkTerm-Fenster dem Systemdesi
settings-theme-system = System
settings-theme-light = Hell
settings-theme-dark = Dunkel
+settings-theme-follow-terminal = Terminalfarben folgen
settings-theme-changed = Design-Modus ist jetzt { $mode }.
settings-theme-save-error = Design-Modus konnte nicht gespeichert werden: { $error }
settings-main-renderer = Renderer des Hauptfensters
@@ -81,7 +82,10 @@ settings-app-icon-note = Funktioniert derzeit nur unter macOS.
settings-app-icon-simple = Schlicht
settings-app-icon-classic = Klassisch
settings-effective-color-scheme = Aktives Farbschema
-settings-effective-color-scheme-description = Das derzeit von thinkterm.lua ausgewählte Farbschema.
+settings-effective-color-scheme-description = Die Farben des Terminals. Zum Auswählen klicken.
+settings-color-scheme-inline = Eigene Farben aus der Konfiguration
+settings-color-scheme-default = Standardpalette
+settings-color-scheme-needs-a-window = Öffnen Sie zuerst ein Terminalfenster — die Vorschau läuft darin.
settings-typography-heading = Typografie
settings-font-size-settings = Schriftgröße der Einstellungen
settings-font-size-settings-description = Ändert die Textgröße im gesamten Einstellungsfenster.
@@ -136,6 +140,12 @@ settings-scroll-mode = Scrollen
settings-scroll-mode-description = Weich bewegt den Text genau so weit, wie Trackpad, Finger oder Rad sich bewegt haben; Zeilenweise springt jeweils eine ganze Zeile.
settings-scroll-mode-stepped = Zeilenweise
settings-scroll-mode-smooth = Weich
+settings-text-contrast = Mindestkontrast für Text
+settings-text-contrast-description = Hält Text auf einem Kontrastverhältnis zu seinem tatsächlichen Hintergrund und übermalt Vordergrundfarben, die für einen anderen Hintergrund gewählt wurden. Programme, die ihren eigenen Hintergrund zeichnen, bleiben unberührt. Ein höherer Wert nimmt auch bewusst gedämpften Stellen ihre Abstufung.
+settings-text-contrast-off = Aus
+settings-text-contrast-3 = 3:1
+settings-text-contrast-45 = 4.5:1
+settings-text-contrast-7 = 7:1
settings-overlay-scrollbar = Bildlaufleiste
settings-overlay-scrollbar-description = Beim Scrollen erscheint am rechten Rand des Fensterbereichs eine schmale Bildlaufleiste, die danach ausblendet; sie lässt sich ziehen.
settings-bottom-quote = Zitat am unteren Rand
diff --git a/thinkterm-i18n/i18n/en-US.ftl b/thinkterm-i18n/i18n/en-US.ftl
index a5cddd51..a0d5e0a7 100644
--- a/thinkterm-i18n/i18n/en-US.ftl
+++ b/thinkterm-i18n/i18n/en-US.ftl
@@ -62,6 +62,7 @@ settings-theme-description = Choose whether ThinkTerm windows follow the system
settings-theme-system = System
settings-theme-light = Light
settings-theme-dark = Dark
+settings-theme-follow-terminal = Follow terminal colours
settings-theme-changed = Theme mode is now { $mode }.
settings-theme-save-error = Unable to save theme mode: { $error }
settings-main-renderer = Main Window Renderer
@@ -81,7 +82,10 @@ settings-app-icon-note = Currently only works on macOS.
settings-app-icon-simple = Simple
settings-app-icon-classic = Classic
settings-effective-color-scheme = Effective Color Scheme
-settings-effective-color-scheme-description = The color scheme currently selected by thinkterm.lua.
+settings-effective-color-scheme-description = What the terminal is painted in. Click to choose.
+settings-color-scheme-inline = Custom inline colors
+settings-color-scheme-default = Default palette
+settings-color-scheme-needs-a-window = Open a terminal window first -- the list previews on one.
settings-typography-heading = Typography
settings-font-size-settings = Settings UI Font Size
settings-font-size-settings-description = Changes the text size throughout the Settings window.
@@ -136,6 +140,12 @@ settings-scroll-mode = Scrolling
settings-scroll-mode-description = Smooth moves the text by the exact distance a trackpad, touch or wheel travelled; Stepped jumps a whole line at a time.
settings-scroll-mode-stepped = Stepped
settings-scroll-mode-smooth = Smooth
+settings-text-contrast = Minimum text contrast
+settings-text-contrast-description = Hold text to a contrast ratio against whatever it is drawn on, repainting foregrounds an application picked for a different background. Programs that paint their own background are left alone. Raising it also flattens what an application dimmed on purpose.
+settings-text-contrast-off = Off
+settings-text-contrast-3 = 3:1
+settings-text-contrast-45 = 4.5:1
+settings-text-contrast-7 = 7:1
settings-overlay-scrollbar = Scrollbar
settings-overlay-scrollbar-description = A thin scrollbar appears over the right edge of a pane while it scrolls and fades out afterwards; it can be dragged.
settings-bottom-quote = Bottom Quote
diff --git a/thinkterm-i18n/i18n/fr-FR.ftl b/thinkterm-i18n/i18n/fr-FR.ftl
index a059e63c..8c9bc7db 100644
--- a/thinkterm-i18n/i18n/fr-FR.ftl
+++ b/thinkterm-i18n/i18n/fr-FR.ftl
@@ -62,6 +62,7 @@ settings-theme-description = Choisissez de suivre l’apparence du système ou d
settings-theme-system = Système
settings-theme-light = Clair
settings-theme-dark = Sombre
+settings-theme-follow-terminal = Suivre les couleurs du terminal
settings-theme-changed = Le thème est maintenant { $mode }.
settings-theme-save-error = Impossible d’enregistrer le thème : { $error }
settings-main-renderer = Moteur de rendu de la fenêtre principale
@@ -81,7 +82,10 @@ settings-app-icon-note = Fonctionne actuellement uniquement sur macOS.
settings-app-icon-simple = Simple
settings-app-icon-classic = Classique
settings-effective-color-scheme = Jeu de couleurs actif
-settings-effective-color-scheme-description = Jeu de couleurs actuellement sélectionné par thinkterm.lua.
+settings-effective-color-scheme-description = Les couleurs du terminal. Cliquez pour choisir.
+settings-color-scheme-inline = Couleurs personnalisées du fichier
+settings-color-scheme-default = Palette par défaut
+settings-color-scheme-needs-a-window = Ouvrez d'abord une fenêtre de terminal : l'aperçu se fait dessus.
settings-typography-heading = Typographie
settings-font-size-settings = Taille de police des réglages
settings-font-size-settings-description = Modifie la taille du texte dans toute la fenêtre Réglages.
@@ -136,6 +140,12 @@ settings-scroll-mode = Défilement
settings-scroll-mode-description = Fluide déplace le texte exactement de la distance parcourue par le pavé tactile, le doigt ou la molette ; Par ligne saute une ligne entière à la fois.
settings-scroll-mode-stepped = Par ligne
settings-scroll-mode-smooth = Fluide
+settings-text-contrast = Contraste minimal du texte
+settings-text-contrast-description = Maintient un rapport de contraste entre le texte et ce sur quoi il est dessiné, en repeignant les couleurs choisies pour un autre fond. Les programmes qui peignent leur propre fond ne sont pas touchés. L'augmenter efface aussi ce qu'une application a volontairement atténué.
+settings-text-contrast-off = Désactivé
+settings-text-contrast-3 = 3:1
+settings-text-contrast-45 = 4.5:1
+settings-text-contrast-7 = 7:1
settings-overlay-scrollbar = Barre de défilement
settings-overlay-scrollbar-description = Une fine barre de défilement apparaît sur le bord droit du volet pendant le défilement puis disparaît en fondu ; elle peut être glissée.
settings-bottom-quote = Citation inférieure
diff --git a/thinkterm-i18n/i18n/ja-JP.ftl b/thinkterm-i18n/i18n/ja-JP.ftl
index 419934f8..82883e32 100644
--- a/thinkterm-i18n/i18n/ja-JP.ftl
+++ b/thinkterm-i18n/i18n/ja-JP.ftl
@@ -59,6 +59,7 @@ settings-theme-description = システムの外観に合わせるか、ライト
settings-theme-system = システム
settings-theme-light = ライト
settings-theme-dark = ダーク
+settings-theme-follow-terminal = ターミナルの配色に合わせる
settings-theme-changed = テーマモードを{ $mode}に変更しました。
settings-theme-save-error = テーマモードを保存できません:{ $error }
settings-main-renderer = メインウィンドウのレンダラー
@@ -78,7 +79,10 @@ settings-app-icon-note = 現在は macOS のみ対応しています。
settings-app-icon-simple = シンプル
settings-app-icon-classic = クラシック
settings-effective-color-scheme = 有効なカラースキーム
-settings-effective-color-scheme-description = thinkterm.lua で現在選択されているカラースキームです。
+settings-effective-color-scheme-description = ターミナルの配色です。クリックで選択します。
+settings-color-scheme-inline = 設定ファイル内のカスタム色
+settings-color-scheme-default = 既定の配色
+settings-color-scheme-needs-a-window = 先にターミナルウィンドウを開いてください。一覧はその上でプレビューします。
settings-typography-heading = タイポグラフィ
settings-font-size-settings = 設定 UI のフォントサイズ
settings-font-size-settings-description = 設定ウィンドウ全体の文字サイズを変更します。
@@ -133,6 +137,12 @@ settings-scroll-mode = スクロール方式
settings-scroll-mode-description = スムーズはトラックパッド・指・ホイールの移動量どおりにテキストを動かし、ステップは 1 行ずつ移動します。
settings-scroll-mode-stepped = ステップ
settings-scroll-mode-smooth = スムーズ
+settings-text-contrast = 文字の最低コントラスト
+settings-text-contrast-description = 文字と実際の背景とのコントラスト比を下回らないようにし、別の背景を前提に選ばれた前景色を塗り直します。自前で背景を描くプログラムには手を出しません。上げると、意図的に淡くした部分の階調も失われます。
+settings-text-contrast-off = オフ
+settings-text-contrast-3 = 3:1
+settings-text-contrast-45 = 4.5:1
+settings-text-contrast-7 = 7:1
settings-overlay-scrollbar = スクロールバー
settings-overlay-scrollbar-description = スクロール中はペインの右端に細いスクロールバーが表示され、その後フェードアウトします。ドラッグもできます。
settings-bottom-quote = 下部の引用文
diff --git a/thinkterm-i18n/i18n/zh-CN.ftl b/thinkterm-i18n/i18n/zh-CN.ftl
index 20e1c179..ad50b170 100644
--- a/thinkterm-i18n/i18n/zh-CN.ftl
+++ b/thinkterm-i18n/i18n/zh-CN.ftl
@@ -59,6 +59,7 @@ settings-theme-description = 选择跟随系统外观,或固定使用浅色或
settings-theme-system = 跟随系统
settings-theme-light = 浅色
settings-theme-dark = 深色
+settings-theme-follow-terminal = 跟随终端配色
settings-theme-changed = 主题模式已切换为{ $mode }。
settings-theme-save-error = 无法保存主题模式:{ $error }
settings-main-renderer = 主窗口渲染器
@@ -78,7 +79,10 @@ settings-app-icon-note = 目前仅支持 macOS。
settings-app-icon-simple = 简约
settings-app-icon-classic = 经典
settings-effective-color-scheme = 当前配色方案
-settings-effective-color-scheme-description = thinkterm.lua 当前选择的配色方案。
+settings-effective-color-scheme-description = 终端当前用的配色。点击选择。
+settings-color-scheme-inline = 配置文件里的自定义颜色
+settings-color-scheme-default = 默认配色
+settings-color-scheme-needs-a-window = 先开一个终端窗口 —— 这个列表要在终端上预览。
settings-typography-heading = 字体排版
settings-font-size-settings = 设置界面字号
settings-font-size-settings-description = 调整整个设置窗口的文字大小。
@@ -133,6 +137,12 @@ settings-scroll-mode = 滚动方式
settings-scroll-mode-description = 平滑:文本按触控板、手指或滚轮的实际位移移动;逐行:每次跳一整行。
settings-scroll-mode-stepped = 逐行
settings-scroll-mode-smooth = 平滑
+settings-text-contrast = 最低文字对比度
+settings-text-contrast-description = 按文字与其所在背景的对比度兜底,重画那些程序按别的背景挑好的前景色。自己画背景的程序不受影响。调高也会抹掉程序故意画淡的层次。
+settings-text-contrast-off = 关
+settings-text-contrast-3 = 3:1
+settings-text-contrast-45 = 4.5:1
+settings-text-contrast-7 = 7:1
settings-overlay-scrollbar = 滚动条
settings-overlay-scrollbar-description = 滚动时在面板右侧显示一条细滚动条,停止后自动淡出;可以拖动。
settings-bottom-quote = 底部语录
diff --git a/wezterm-gui/src/native_settings.rs b/wezterm-gui/src/native_settings.rs
index 500a2412..61f37f01 100644
--- a/wezterm-gui/src/native_settings.rs
+++ b/wezterm-gui/src/native_settings.rs
@@ -1,10 +1,11 @@
+use config::ConfigHandle;
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use std::fs;
use std::io;
use std::path::PathBuf;
use std::sync::{Arc, OnceLock};
-use window::{Appearance, Connection, ConnectionOps};
+use window::{Appearance, Connection, ConnectionOps, WindowOps};
// One point is one logical pixel on macOS but 4/3 px at 96dpi, so the
// non-mac size is 0.75x for the same visual size (14px UI text).
@@ -46,6 +47,10 @@ pub(crate) enum NativeThemeMode {
System,
Light,
Dark,
+ /// Take the interface's colours from the terminal's own colour scheme.
+ /// Light or dark is then the scheme's business, not a separate choice.
+ #[serde(rename = "follow_terminal")]
+ FollowTerminal,
}
impl Default for NativeThemeMode {
@@ -59,9 +64,19 @@ impl Default for NativeThemeMode {
}
impl NativeThemeMode {
+ /// Light or dark, for everything that needs one of the two.
+ ///
+ /// `FollowTerminal` answers `system` here, and under that mode `system`
+ /// is not the desktop: [`apply_preferred_appearance`] pushes the scheme's
+ /// own side onto the connection, so `system_appearance` -- and therefore
+ /// this -- reports the side the scheme is on. That is the point. Reading
+ /// the scheme a second time here would be the same answer arrived at
+ /// twice, and would be wrong in the window between a scheme changing and
+ /// that push landing. The interface's own colours go through
+ /// [`chrome_palette`], which reads the scheme directly.
pub(crate) fn effective_appearance(self, system: Appearance) -> Appearance {
match self {
- Self::System => system,
+ Self::System | Self::FollowTerminal => system,
Self::Light => Appearance::Light,
Self::Dark => Appearance::Dark,
}
@@ -69,11 +84,43 @@ impl NativeThemeMode {
pub(crate) fn preferred_app_appearance(self) -> Option<Appearance> {
match self {
- Self::System => None,
+ Self::System | Self::FollowTerminal => None,
Self::Light => Some(Appearance::Light),
Self::Dark => Some(Appearance::Dark),
}
}
+
+ /// Every mode, in the order the settings window offers them.
+ pub(crate) const ALL: [Self; 4] = [
+ Self::System,
+ Self::Light,
+ Self::Dark,
+ Self::FollowTerminal,
+ ];
+}
+
+/// Read a theme mode, falling back to the default rather than failing.
+///
+/// A value this build does not know -- a newer one wrote it -- would
+/// otherwise fail the whole file, and `load_from_disk` answers a parse failure
+/// with `Default::default()`. The next save then writes those defaults back
+/// over the user's language, fonts and everything else. One unreadable field
+/// must not cost the file.
+fn theme_mode_or_default<'de, D>(deserializer: D) -> Result<NativeThemeMode, D::Error>
+where
+ D: serde::Deserializer<'de>,
+{
+ let raw = String::deserialize(deserializer)?;
+ Ok(match raw.as_str() {
+ "system" => NativeThemeMode::System,
+ "light" => NativeThemeMode::Light,
+ "dark" => NativeThemeMode::Dark,
+ "follow_terminal" => NativeThemeMode::FollowTerminal,
+ other => {
+ log::warn!("unknown theme_mode {other:?} in the settings; using the default");
+ NativeThemeMode::default()
+ }
+ })
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
@@ -190,6 +237,72 @@ impl NativeScrollMode {
pub(crate) const ALL: [Self; 2] = [Self::Smooth, Self::Stepped];
}
+/// The floor the terminal holds text to against whatever it is drawn on.
+///
+/// A program that paints its own background is self-consistent and is never
+/// touched by this: the check is per cell, against that cell's real
+/// background. What it catches is the half-and-half case -- an application
+/// that leaves the background to the terminal but picks its foregrounds for
+/// a dark one. btop on a light colour scheme is the example: it hands the
+/// background back and then writes in near-white.
+///
+/// The ratios are WCAG 2.0: 3:1 is the floor for large text, 4.5:1 for body
+/// text (AA), 7:1 is AAA.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub(crate) enum NativeTextContrast {
+ /// Leave every colour as the application asked for it -- and leave the
+ /// Lua `text_min_contrast_ratio` in charge, the way `font_size: None`
+ /// leaves the configured font size in charge.
+ Off,
+ Ratio3,
+ Ratio45,
+ Ratio7,
+}
+
+impl Default for NativeTextContrast {
+ fn default() -> Self {
+ // Raising contrast also flattens what an application dimmed on
+ // purpose -- disabled entries, the unfilled half of a meter, comment
+ // colouring. That is a trade the user has to choose, not inherit.
+ Self::Off
+ }
+}
+
+impl NativeTextContrast {
+ /// Every choice, in the order the settings window offers them.
+ pub(crate) const ALL: [Self; 4] = [Self::Off, Self::Ratio3, Self::Ratio45, Self::Ratio7];
+
+ pub(crate) fn ratio(self) -> Option<f32> {
+ match self {
+ Self::Off => None,
+ Self::Ratio3 => Some(3.0),
+ Self::Ratio45 => Some(4.5),
+ Self::Ratio7 => Some(7.0),
+ }
+ }
+}
+
+/// A value this build does not know about must not cost the user the rest of
+/// their settings, so an unreadable choice reads as the default rather than
+/// failing the whole file. Same reasoning as `theme_mode_or_default`.
+fn text_contrast_or_default<'de, D>(deserializer: D) -> Result<NativeTextContrast, D::Error>
+where
+ D: serde::Deserializer<'de>,
+{
+ let raw = String::deserialize(deserializer)?;
+ Ok(match raw.as_str() {
+ "off" => NativeTextContrast::Off,
+ "ratio3" => NativeTextContrast::Ratio3,
+ "ratio45" => NativeTextContrast::Ratio45,
+ "ratio7" => NativeTextContrast::Ratio7,
+ other => {
+ log::warn!("unknown text_contrast {other:?} in the settings; using the default");
+ NativeTextContrast::default()
+ }
+ })
+}
+
impl Default for NativeBottomQuoteMode {
fn default() -> Self {
Self::Timed
@@ -204,6 +317,7 @@ impl NativeBottomQuoteMode {
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default)]
pub(crate) struct NativeAppearanceSettings {
+ #[serde(deserialize_with = "theme_mode_or_default")]
pub(crate) theme_mode: NativeThemeMode,
pub(crate) app_icon: NativeAppIcon,
/// Color scheme picked in the command palette; overrides the config's
@@ -227,6 +341,10 @@ pub(crate) struct NativeTerminalSettings {
pub(crate) font_family: Option<String>,
pub(crate) remote_pane_resize_mode: NativeRemotePaneResizeMode,
pub(crate) scroll_mode: NativeScrollMode,
+ /// See [`NativeTextContrast`]. `Off` defers to the Lua
+ /// `text_min_contrast_ratio`, which is itself off unless set.
+ #[serde(deserialize_with = "text_contrast_or_default")]
+ pub(crate) text_contrast: NativeTextContrast,
pub(crate) bottom_quote_enabled: bool,
pub(crate) bottom_quote_mode: NativeBottomQuoteMode,
pub(crate) bottom_quote_interval_minutes: Option<u32>,
@@ -244,6 +362,7 @@ impl Default for NativeTerminalSettings {
font_family: None,
remote_pane_resize_mode: NativeRemotePaneResizeMode::default(),
scroll_mode: NativeScrollMode::default(),
+ text_contrast: NativeTextContrast::default(),
bottom_quote_enabled: false,
bottom_quote_mode: NativeBottomQuoteMode::default(),
bottom_quote_interval_minutes: None,
@@ -263,6 +382,20 @@ pub(crate) fn scroll_mode() -> NativeScrollMode {
load_shared().terminal.scroll_mode
}
+/// The contrast floor in force, or `None` to leave colours alone. The
+/// settings window wins when it names a ratio; `Off` hands the question back
+/// to the configuration file.
+///
+/// Resolved once per window rather than per cell -- see
+/// `TermWindow::text_min_contrast`.
+pub(crate) fn text_min_contrast_ratio(config: &ConfigHandle) -> Option<f32> {
+ load_shared()
+ .terminal
+ .text_contrast
+ .ratio()
+ .or(config.text_min_contrast_ratio)
+}
+
/// Read once per painted pane, through the shared handle.
pub(crate) fn overlay_scrollbar() -> bool {
load_shared().terminal.overlay_scrollbar
@@ -808,11 +941,271 @@ pub(crate) fn effective_appearance() -> Appearance {
.effective_appearance(system_appearance())
}
+/// The interface's colours for `appearance`, with the user's `ui_colors`
+/// overrides applied on top.
+///
+/// The overrides live here rather than in `ui::tokens` so that module stays
+/// free of the configuration crate, and they are applied last so a colour the
+/// user named wins over everything derived.
+/// `mode` is handed in rather than read back out of the saved settings: the
+/// settings window previews a theme mode from its own copy before saving it,
+/// and reading the saved one there would derive the preview from the mode
+/// being left rather than the one being chosen.
+pub(crate) fn chrome_palette(
+ mode: NativeThemeMode,
+ appearance: Appearance,
+ config: &config::ConfigHandle,
+ preview_ground: Option<window::color::LinearRgba>,
+) -> crate::ui::UiPalette {
+ let mut palette = match mode {
+ NativeThemeMode::FollowTerminal => {
+ // `preview_ground` is the scheme the command palette is showing
+ // but the user has not chosen. Without it the interface would keep
+ // the configured scheme's colours while the terminal in front of
+ // it changed -- a preview that does not preview the thing this
+ // mode exists for.
+ let ground = preview_ground.unwrap_or_else(|| terminal_ground(config));
+ crate::ui::UiPalette::for_scheme(ground)
+ }
+ _ => crate::ui::UiPalette::for_appearance(appearance),
+ };
+ // The strip the tabs sit on is the terminal's header, not another piece of
+ // sidebar: a seam where one ends and the other begins is the thing people
+ // notice first. It takes the ground the terminal is actually painted with,
+ // which in a dark interface is already the chrome's own colour (see
+ // `dark_chrome_background` in `render/pane.rs`) and otherwise is the
+ // scheme's background.
+ palette.header_bg = match appearance {
+ Appearance::Dark | Appearance::DarkHighContrast => palette.sidebar_bg,
+ Appearance::Light | Appearance::LightHighContrast => {
+ let ground = preview_ground.unwrap_or_else(|| terminal_ground(config));
+ // Only when the scheme is on the same side as the interface. A
+ // light interface with an explicitly chosen dark scheme would
+ // otherwise get a dark strip carrying the light palette's dark
+ // text -- Nord's background against it is about 1.4:1. A seam is
+ // unavoidable when the two sides disagree; an unreadable tab bar
+ // is not.
+ if crate::ui::UiPalette::appearance_of(ground) == Appearance::Light {
+ ground
+ } else {
+ palette.sidebar_bg
+ }
+ }
+ };
+ // Applied last so a colour the user named wins over everything derived,
+ // `header_bg` included.
+ apply_ui_colors(&mut palette, config.ui_colors.as_ref());
+ palette
+}
+
+/// The colour scheme in force: the one the user picked, or -- when they have
+/// picked none -- the one that goes with the side the interface is on.
+///
+/// The two are one decision to the person making it. Choosing a light
+/// interface and being handed a terminal whose text was chosen for a black
+/// background is not a combination anyone asks for; it is what you get when
+/// the two settings are free to disagree and neither has a default that knows
+/// about the other.
+///
+/// An explicit choice always wins -- from the palette, from the settings
+/// window, or from `color_scheme` in the configuration file. Only the default
+/// has a side. `FollowTerminal` is left out on purpose: there the scheme is
+/// what decides the interface's side, so taking the default from that side
+/// would be circular.
+pub(crate) fn effective_color_scheme(
+ settings: &ThinkTermNativeSettings,
+ config: &ConfigHandle,
+) -> Option<String> {
+ resolve_color_scheme(
+ settings.appearance.color_scheme.as_deref(),
+ settings.appearance.theme_mode,
+ settings
+ .appearance
+ .theme_mode
+ .effective_appearance(system_appearance()),
+ config.color_scheme.as_deref(),
+ config.colors.is_some(),
+ )
+}
+
+/// The decision itself, off the settings and the configuration so its rules
+/// are testable without either.
+fn resolve_color_scheme(
+ picked: Option<&str>,
+ mode: NativeThemeMode,
+ appearance: Appearance,
+ config_scheme: Option<&str>,
+ config_has_inline_colors: bool,
+) -> Option<String> {
+ if let Some(picked) = picked {
+ return Some(picked.to_string());
+ }
+ if mode == NativeThemeMode::FollowTerminal {
+ return None;
+ }
+ // On macOS `color_scheme` is filled in with the dark default when the file
+ // names none, so "is it set" cannot tell a choice from that fill.
+ let chosen_in_the_file = match config_scheme {
+ Some(name) => name != config::MACOS_DEFAULT_COLOR_SCHEME,
+ None => config_has_inline_colors,
+ };
+ if chosen_in_the_file {
+ return None;
+ }
+ match appearance {
+ Appearance::Light | Appearance::LightHighContrast => {
+ Some(config::MACOS_LIGHT_COLOR_SCHEME.to_string())
+ }
+ // The configuration's own default is already the dark one; leaving it
+ // alone keeps the file in charge of everything it can be.
+ Appearance::Dark | Appearance::DarkHighContrast => None,
+ }
+}
+
+/// The terminal's own background: what the interface is being asked to sit
+/// next to. Falls back to the appearance's ground when the scheme names no
+/// background, which is what `resolved_palette` leaves for a configuration
+/// that sets neither `colors` nor `color_scheme`.
+/// A scheme's background as the terminal will actually paint it.
+///
+/// `colors` in the configuration overlays a scheme -- the precedence
+/// `resolved_palette` is built with -- so reading the scheme raw gets the
+/// wrong answer for anyone who sets both. A dark scheme with an inline white
+/// background was classified as dark, which under "follow terminal colours"
+/// put a dark interface behind black terminal text.
+pub(crate) fn scheme_background(
+ config: &config::ConfigHandle,
+ scheme: &config::Palette,
+) -> Option<window::color::LinearRgba> {
+ config
+ .colors
+ .as_ref()
+ .and_then(|colors| colors.background)
+ .or(scheme.background)
+ .map(|color| color.to_linear())
+}
+
+fn terminal_ground(config: &config::ConfigHandle) -> window::color::LinearRgba {
+ // A scheme picked in the command palette is kept here, not in the
+ // configuration: it reaches a terminal window through that window's own
+ // overrides. The settings window has no overrides, so reading only
+ // `config` would derive its colours from the scheme in the file while the
+ // terminal in front of it showed the one that was picked.
+ if let Some(name) = effective_color_scheme(&load(), config) {
+ let picked = config
+ .color_schemes
+ .get(&name)
+ .or_else(|| config::COLOR_SCHEMES.get(&name));
+ if let Some(background) = picked.and_then(|palette| scheme_background(config, palette)) {
+ return background;
+ }
+ }
+ match config.resolved_palette.background {
+ Some(background) => background.to_linear(),
+ None => crate::ui::UiPalette::for_appearance(system_appearance()).window_bg,
+ }
+}
+
+/// Paint the user's chosen colours over `palette`, leaving every slot they did
+/// not name alone.
+pub(crate) fn apply_ui_colors(
+ palette: &mut crate::ui::UiPalette,
+ overrides: Option<&config::UiColors>,
+) {
+ let Some(colors) = overrides else {
+ return;
+ };
+ macro_rules! apply_color {
+ ($name:ident) => {
+ if let Some(color) = colors.$name {
+ palette.$name = color.to_linear();
+ }
+ };
+ }
+ apply_color!(window_bg);
+ apply_color!(sidebar_bg);
+ apply_color!(workspace_sidebar_bg);
+ apply_color!(header_bg);
+ apply_color!(separator);
+ apply_color!(control_bg);
+ apply_color!(control_hover_bg);
+ apply_color!(control_pressed_bg);
+ apply_color!(control_border);
+ apply_color!(sidebar_button_bg);
+ apply_color!(sidebar_button_hover_bg);
+ apply_color!(sidebar_row_hover_bg);
+ apply_color!(sidebar_row_pressed_bg);
+ apply_color!(sidebar_row_active_bg);
+ apply_color!(sidebar_row_active_border);
+ apply_color!(selected_bg);
+ apply_color!(accent);
+ apply_color!(accent_hover);
+ apply_color!(on_accent);
+ apply_color!(danger);
+ apply_color!(track_off);
+ apply_color!(card_bg);
+ apply_color!(text);
+ apply_color!(secondary_text);
+ apply_color!(muted_text);
+ apply_color!(selected_text);
+ apply_color!(scrollbar_thumb);
+ apply_color!(spelling_error);
+}
+
+/// Tell the platform which appearance to present its own chrome in.
+///
+/// Under "follow terminal colours" that is the side the *scheme* is on, not
+/// the desktop's. The native chrome takes its tint from this: the title bar,
+/// and on macOS the sidebar button, which is an `NSButton` drawing a template
+/// SF Symbol. Left following the system it renders a white symbol onto the
+/// white interface a light scheme produces, and the button disappears.
+///
+/// Called when the theme mode changes and again when the scheme does, since a
+/// scheme change can move which side the interface is on.
+pub(crate) fn apply_preferred_appearance(mode: NativeThemeMode) {
+ let Some(conn) = Connection::get() else {
+ return;
+ };
+ let preferred = match mode {
+ NativeThemeMode::FollowTerminal => Some(crate::ui::UiPalette::appearance_of(
+ terminal_ground(&config::configuration()),
+ )),
+ mode => mode.preferred_app_appearance(),
+ };
+ conn.set_preferred_appearance(preferred);
+}
+
pub(crate) fn apply_to_app(settings: &ThinkTermNativeSettings) {
crate::i18n::activate_from_settings(settings);
- if let Some(conn) = Connection::get() {
- conn.set_preferred_appearance(settings.appearance.theme_mode.preferred_app_appearance());
+ apply_preferred_appearance(settings.appearance.theme_mode);
+ // Tell the windows directly rather than waiting for the appearance event
+ // the line above will eventually produce. That event is the normal route
+ // and it also reloads the configuration, but macOS drops it when the
+ // window is already dispatching something else (see
+ // `view_did_change_effective_appearance`), and a window that missed it
+ // would go on painting the old chrome. Refreshing twice costs a struct
+ // copy; refreshing never is a visibly stale sidebar.
+ // Moving between Light and Dark moves the *default* colour scheme with it
+ // (see `effective_color_scheme`), so the terminal has to be re-pointed at
+ // it, not just repainted. Applying a scheme the window already has is a
+ // no-op, so the common case -- a mode change that does not move the
+ // default -- costs nothing.
+ let scheme = effective_color_scheme(settings, &config::configuration());
+ if let Some(front_end) = crate::frontend::try_front_end() {
+ for gui_window in front_end.gui_windows() {
+ let scheme = scheme.clone();
+ gui_window
+ .window
+ .notify(crate::termwindow::TermWindowNotif::Apply(Box::new(
+ move |term_window| {
+ term_window.apply_color_scheme_override(scheme);
+ term_window.refresh_chrome();
+ },
+ )));
+ }
}
+ // The settings window is standalone and in no broadcast list of its own.
+ crate::settings_window::refresh_open_settings_window_chrome();
#[cfg(target_os = "macos")]
if let Some(path) = app_icon_path(settings.appearance.app_icon) {
@@ -1114,6 +1507,281 @@ pub(crate) fn main_window_renderer(
mod tests {
use super::*;
+ use config::UiColors;
+ use std::convert::TryFrom;
+ use window::Appearance;
+
+ fn color(hex: &str) -> config::RgbaColor {
+ config::RgbaColor::try_from(hex.to_string()).unwrap()
+ }
+
+ /// A file written before this setting existed has to keep working, and
+ /// keep meaning "leave the application's colours alone".
+ #[test]
+ fn a_settings_file_without_a_contrast_choice_reads_as_off() {
+ let json = r#"{
+ "version": 1,
+ "terminal": { "scroll_mode": "smooth" }
+ }"#;
+ let settings: ThinkTermNativeSettings =
+ serde_json::from_str(json).expect("the file has to survive");
+ assert_eq!(settings.terminal.text_contrast, NativeTextContrast::Off);
+ assert_eq!(settings.terminal.text_contrast.ratio(), None);
+ assert!(settings.terminal.scroll_mode == NativeScrollMode::Smooth);
+ }
+
+ #[test]
+ fn a_contrast_choice_round_trips_through_the_file() {
+ for (written, expected, ratio) in [
+ ("off", NativeTextContrast::Off, None),
+ ("ratio3", NativeTextContrast::Ratio3, Some(3.0)),
+ ("ratio45", NativeTextContrast::Ratio45, Some(4.5)),
+ ("ratio7", NativeTextContrast::Ratio7, Some(7.0)),
+ ] {
+ let json = format!(r#"{{"terminal": {{"text_contrast": "{written}"}}}}"#);
+ let settings: ThinkTermNativeSettings =
+ serde_json::from_str(&json).expect("the file has to survive");
+ assert_eq!(settings.terminal.text_contrast, expected, "{written}");
+ assert_eq!(settings.terminal.text_contrast.ratio(), ratio, "{written}");
+
+ let out = serde_json::to_string(&settings).expect("serialises");
+ assert!(
+ out.contains(&format!("\"text_contrast\":\"{written}\"")),
+ "{written} has to survive a save: {out}"
+ );
+ }
+ }
+
+ /// Same reasoning as the theme mode below: a ratio a newer build offers
+ /// must not cost this one the rest of the file.
+ #[test]
+ fn an_unknown_contrast_choice_falls_back_without_failing_the_file() {
+ let json = r#"{
+ "version": 1,
+ "terminal": { "text_contrast": "ratio21", "scroll_mode": "stepped" },
+ "localization": { "language": "fr-FR" }
+ }"#;
+ let settings: ThinkTermNativeSettings =
+ serde_json::from_str(json).expect("the file has to survive");
+ assert_eq!(settings.terminal.text_contrast, NativeTextContrast::Off);
+ assert_eq!(settings.terminal.scroll_mode, NativeScrollMode::Stepped);
+ assert_eq!(settings.localization.language.as_deref(), Some("fr-FR"));
+ }
+
+ /// A settings file written by a newer build names a theme this one has
+ /// never heard of. Failing the parse would be answered by
+ /// `load_from_disk` with `Default::default()`, and the next save would
+ /// write those defaults back over the language, the fonts and everything
+ /// else. One unreadable field must not cost the file.
+ #[test]
+ fn an_unknown_theme_mode_does_not_take_the_rest_of_the_settings_with_it() {
+ let json = r#"{
+ "version": 1,
+ "appearance": { "theme_mode": "some_future_theme" },
+ "localization": { "language": "ja-JP" },
+ "onboarding": { "seen_version": 7 }
+ }"#;
+ let settings: ThinkTermNativeSettings =
+ serde_json::from_str(json).expect("the file has to survive");
+ assert_eq!(
+ settings.appearance.theme_mode,
+ NativeThemeMode::default(),
+ "the unreadable field falls back"
+ );
+ assert_eq!(
+ settings.localization.language.as_deref(),
+ Some("ja-JP"),
+ "everything else is kept"
+ );
+ assert_eq!(settings.onboarding.seen_version, 7);
+ }
+
+ /// The four this build does know still round-trip.
+ #[test]
+ fn every_theme_mode_round_trips_through_the_settings_file() {
+ for mode in NativeThemeMode::ALL {
+ let mut settings = ThinkTermNativeSettings::default();
+ settings.appearance.theme_mode = mode;
+ let json = serde_json::to_string(&settings).unwrap();
+ let back: ThinkTermNativeSettings = serde_json::from_str(&json).unwrap();
+ assert_eq!(back.appearance.theme_mode, mode, "{mode:?}");
+ }
+ }
+
+ /// A file that names two colours has to change two colours. The interface
+ /// has twenty-eight slots and nobody is going to write them all out.
+ #[test]
+ fn ui_colors_change_only_the_slots_they_name() {
+ let untouched = crate::ui::UiPalette::for_appearance(Appearance::Dark);
+ let mut palette = untouched;
+
+ let colors = UiColors {
+ sidebar_bg: Some(color("#282828")),
+ accent: Some(color("#d79921")),
+ ..UiColors::default()
+ };
+ apply_ui_colors(&mut palette, Some(&colors));
+
+ assert_eq!(palette.sidebar_bg, color("#282828").to_linear());
+ assert_eq!(palette.accent, color("#d79921").to_linear());
+ assert_eq!(palette.window_bg, untouched.window_bg);
+ assert_eq!(palette.text, untouched.text);
+ assert_eq!(palette.card_bg, untouched.card_bg);
+ }
+
+ fn resolved(
+ picked: Option<&str>,
+ mode: NativeThemeMode,
+ appearance: Appearance,
+ config_scheme: Option<&str>,
+ ) -> Option<String> {
+ resolve_color_scheme(picked, mode, appearance, config_scheme, false)
+ }
+
+ /// The interface's side and the terminal's colours are one decision.
+ /// Nothing picked plus a light interface has to mean a light terminal, or
+ /// the text is chosen for a background it is not on.
+ #[test]
+ fn a_light_interface_with_nothing_picked_gets_the_light_scheme() {
+ assert_eq!(
+ resolved(
+ None,
+ NativeThemeMode::Light,
+ Appearance::Light,
+ Some(config::MACOS_DEFAULT_COLOR_SCHEME)
+ ),
+ Some(config::MACOS_LIGHT_COLOR_SCHEME.to_string())
+ );
+ }
+
+ /// Dark hands the question back to the configuration, whose own default is
+ /// already the dark one. Nothing to override.
+ #[test]
+ fn a_dark_interface_leaves_the_configuration_in_charge() {
+ assert_eq!(
+ resolved(
+ None,
+ NativeThemeMode::Dark,
+ Appearance::Dark,
+ Some(config::MACOS_DEFAULT_COLOR_SCHEME)
+ ),
+ None
+ );
+ }
+
+ #[test]
+ fn a_picked_scheme_beats_the_side_the_interface_is_on() {
+ assert_eq!(
+ resolved(
+ Some("Gruvbox Dark (Gogh)"),
+ NativeThemeMode::Light,
+ Appearance::Light,
+ None
+ ),
+ Some("Gruvbox Dark (Gogh)".to_string())
+ );
+ }
+
+ /// A scheme written in the configuration file is a choice too, and the
+ /// macOS fill-in is not -- by the time this runs the two look the same, so
+ /// the fill-in has to be recognised by name.
+ #[test]
+ fn a_scheme_named_in_the_configuration_is_left_alone() {
+ assert_eq!(
+ resolved(
+ None,
+ NativeThemeMode::Light,
+ Appearance::Light,
+ Some("Nord (base16)")
+ ),
+ None
+ );
+ assert_eq!(
+ resolve_color_scheme(None, NativeThemeMode::Light, Appearance::Light, None, true),
+ None,
+ "inline `colors` is a choice as much as a named scheme"
+ );
+ }
+
+ /// Under "follow terminal colours" the scheme is what decides the
+ /// interface's side, so taking the default from that side is circular.
+ #[test]
+ fn follow_terminal_does_not_pick_a_scheme_for_itself() {
+ assert_eq!(
+ resolved(
+ None,
+ NativeThemeMode::FollowTerminal,
+ Appearance::Light,
+ Some(config::MACOS_DEFAULT_COLOR_SCHEME)
+ ),
+ None
+ );
+ }
+
+ /// The light half has to be a scheme that resolves, or the override names
+ /// nothing and the terminal silently keeps the dark one.
+ #[test]
+ fn the_light_half_is_a_scheme_we_ship_and_is_light() {
+ let palette = config::COLOR_SCHEMES
+ .get(config::MACOS_LIGHT_COLOR_SCHEME)
+ .expect("the light default has to be a scheme we ship");
+ let ground = palette
+ .background
+ .expect("it needs a background")
+ .to_linear();
+ assert_eq!(
+ crate::ui::UiPalette::appearance_of(ground),
+ Appearance::Light,
+ "the light half has to be on the light side"
+ );
+ }
+
+ /// The slot list is written out by hand in `UiColors`, again in
+ /// `apply_ui_colors` and again in the documentation, and nothing makes
+ /// the three agree. This catches the half that matters: a field the user
+ /// can name in their configuration that the code then never reads, which
+ /// would be a silently ignored setting rather than an error.
+ #[test]
+ fn every_slot_a_user_can_name_is_one_the_code_applies() {
+ use wezterm_dynamic::{FromDynamic, ToDynamic, Value};
+
+ for name in UiColors::possible_field_names() {
+ let mut object = wezterm_dynamic::Object::default();
+ object.insert(name.to_dynamic(), "#ff00ff".to_dynamic());
+ let colors = UiColors::from_dynamic(&Value::Object(object), Default::default())
+ .unwrap_or_else(|err| panic!("{} should deserialise: {:#}", name, err));
+
+ let untouched = crate::ui::UiPalette::for_appearance(Appearance::Dark);
+ let mut palette = untouched;
+ apply_ui_colors(&mut palette, Some(&colors));
+ assert_ne!(
+ palette, untouched,
+ "ui_colors.{} is a name the user can set and the code never reads",
+ name
+ );
+ }
+ }
+
+ /// No `ui_colors` at all is the common case and must cost nothing.
+ #[test]
+ fn no_ui_colors_leaves_the_palette_alone() {
+ let untouched = crate::ui::UiPalette::for_appearance(Appearance::Light);
+ let mut palette = untouched;
+ apply_ui_colors(&mut palette, None);
+ assert_eq!(palette.window_bg, untouched.window_bg);
+ assert_eq!(palette.accent, untouched.accent);
+ }
+
+ /// An empty table is not the same as no table, and must behave the same.
+ #[test]
+ fn an_empty_ui_colors_table_leaves_the_palette_alone() {
+ let untouched = crate::ui::UiPalette::for_appearance(Appearance::Dark);
+ let mut palette = untouched;
+ apply_ui_colors(&mut palette, Some(&UiColors::default()));
+ assert_eq!(palette.window_bg, untouched.window_bg);
+ assert_eq!(palette.muted_text, untouched.muted_text);
+ }
+
#[test]
fn onboarding_is_required_before_current_version() {
let mut settings = ThinkTermNativeSettings::default();
diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rs
index b6269269..0f99725f 100644
--- a/wezterm-gui/src/settings_window.rs
+++ b/wezterm-gui/src/settings_window.rs
@@ -16,6 +16,7 @@ use crate::ui::{
};
use crate::utilsprites::RenderMetrics;
use anyhow::{Context, Error};
+use mux::window::WindowId as MuxWindowId;
use config::{configuration, Dimension, GeometryOrigin};
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
@@ -107,6 +108,11 @@ thread_local! {
/// Updates opens Settings straight onto Software Update. Consumed by the
/// next window to open, and only ever set when one is about to be.
static PENDING_SECTION: Cell<Option<SettingsSection>> = const { Cell::new(None) };
+ /// The window Settings was opened from. The colour-scheme row hands the
+ /// choosing back to that window's command palette, and a preview belongs
+ /// in the terminal the user was looking at rather than in whichever
+ /// window happens to sort first.
+ static OPENED_FROM: Cell<Option<MuxWindowId>> = const { Cell::new(None) };
}
enum SettingsWindowSlot {
@@ -148,6 +154,33 @@ pub(crate) fn invalidate_open_settings_window() {
});
}
+/// Re-resolve the open settings window's chrome colours and repaint it.
+///
+/// Same reason as `invalidate_open_settings_window`: this window is standalone
+/// and the broadcasts that reach the terminal windows do not reach it. It
+/// needs this whenever the colours it derives from move -- the theme mode, or
+/// the terminal colour scheme, which under "follow terminal colours" is what
+/// its own surfaces are built from.
+pub(crate) fn refresh_open_settings_window_chrome() {
+ SETTINGS_WINDOW.with(|slot| {
+ if let SettingsWindowSlot::Open { settings, .. } = &*slot.borrow() {
+ // `try_borrow_mut` because this can be reached from inside the
+ // settings window's own event handling, where it is already
+ // borrowed; there the refresh that follows covers it anyway.
+ if let Ok(mut settings) = settings.try_borrow_mut() {
+ // The snapshot too, not just the colours: the scheme just
+ // changed underneath this window, and a row that shows it --
+ // or a save that writes the whole struct back -- would
+ // otherwise be working from the value it was opened with.
+ settings.set_native_settings(crate::native_settings::load());
+ if let Some(window) = settings.window.as_ref() {
+ window.invalidate();
+ }
+ }
+ }
+ });
+}
+
fn settings_window_for_instance(instance_id: u64) -> Option<Rc<RefCell<SettingsWindow>>> {
SETTINGS_WINDOW.with(|slot| match &*slot.borrow() {
SettingsWindowSlot::Open {
@@ -707,6 +740,7 @@ fn localized_theme_mode_label(mode: NativeThemeMode) -> String {
NativeThemeMode::System => "settings-theme-system",
NativeThemeMode::Light => "settings-theme-light",
NativeThemeMode::Dark => "settings-theme-dark",
+ NativeThemeMode::FollowTerminal => "settings-theme-follow-terminal",
})
}
@@ -762,6 +796,32 @@ fn localized_scroll_mode_label(mode: crate::native_settings::NativeScrollMode) -
})
}
+fn localized_text_contrast_label(mode: crate::native_settings::NativeTextContrast) -> String {
+ use crate::native_settings::NativeTextContrast;
+ crate::i18n::tr(match mode {
+ NativeTextContrast::Off => "settings-text-contrast-off",
+ NativeTextContrast::Ratio3 => "settings-text-contrast-3",
+ NativeTextContrast::Ratio45 => "settings-text-contrast-45",
+ NativeTextContrast::Ratio7 => "settings-text-contrast-7",
+ })
+}
+
+/// The groove and the selected segment of a segmented control, which have to
+/// be told apart.
+///
+/// The dark palette does it by making the selection lighter than the groove.
+/// The light one cannot: its `control_bg` is already white, and its selected
+/// fill is white at 78% -- white on white, which is what the four choices in
+/// the Terminal pane looked like. So on the light side the groove is the grey
+/// and the selection is the white, which is also how the platform draws it.
+fn segmented_track_and_fill(palette: &SettingsPalette) -> (LinearRgba, LinearRgba) {
+ if palette.is_dark {
+ (palette.control_bg, palette.nav_selected_bg)
+ } else {
+ (palette.track_off, palette.control_bg)
+ }
+}
+
fn settings_tr(id: &'static str, values: &[(&'static str, String)]) -> String {
let mut args = FluentArgs::new();
for (name, value) in values {
@@ -868,6 +928,10 @@ enum SettingsAction {
ToggleBottomQuote,
SetRemotePaneResizeMode(NativeRemotePaneResizeMode),
SetScrollMode(crate::native_settings::NativeScrollMode),
+ /// Hand the choosing to the command palette's scheme list, which already
+ /// has the search and the live preview a thousand entries need.
+ OpenColorSchemePicker,
+ SetTextContrast(crate::native_settings::NativeTextContrast),
ToggleOverlayScrollbar,
SetBottomQuoteMode(NativeBottomQuoteMode),
DecreaseBottomQuoteFontSize,
@@ -1889,6 +1953,11 @@ struct SettingsPalette {
nav_selected_bg: LinearRgba,
nav_selected_border: LinearRgba,
control_bg: LinearRgba,
+ /// The groove a segmented control's segments sit in, and whether this
+ /// palette is a dark one -- the two together decide which way a selected
+ /// segment has to go to be seen. See `segmented_track_and_fill`.
+ track_off: LinearRgba,
+ is_dark: bool,
control_hover_bg: LinearRgba,
control_pressed_bg: LinearRgba,
control_border: LinearRgba,
@@ -1930,6 +1999,12 @@ pub fn show_update_page() {
show();
}
+/// Open Settings, remembering which window asked. See `OPENED_FROM`.
+pub fn show_from(mux_window_id: MuxWindowId) {
+ OPENED_FROM.with(|slot| slot.set(Some(mux_window_id)));
+ show();
+}
+
pub fn show() {
let action = SETTINGS_WINDOW.with(|slot| {
let mut slot = slot.borrow_mut();
@@ -2036,6 +2111,13 @@ struct SettingsWindow {
/// Last system appearance seen. Not used for painting -- see
/// `effective_appearance` -- only to notice that a repaint is due.
appearance: Appearance,
+ /// The chrome's colours, resolved when the appearance they come from
+ /// moves rather than on each of the fifty-six `palette()` calls a paint
+ /// makes. Two things move it: the system appearance (the event below) and
+ /// this window's own `theme_mode`, which a dropdown edits directly so that
+ /// a pick previews before it is saved. `refresh_chrome` is called from
+ /// both.
+ chrome_palette: UiPalette,
selected: SettingsSection,
agents_expanded: Option<&'static str>,
native_settings: ThinkTermNativeSettings,
@@ -2169,6 +2251,15 @@ impl SettingsWindow {
render_state: None,
webgpu: None,
appearance,
+ chrome_palette: crate::native_settings::chrome_palette(
+ native_settings.appearance.theme_mode,
+ native_settings
+ .appearance
+ .theme_mode
+ .effective_appearance(appearance),
+ &config,
+ None,
+ ),
selected: initial_section(),
agents_expanded: initial_expanded_agent(),
native_settings,
@@ -2362,6 +2453,7 @@ impl SettingsWindow {
}
WindowEvent::AppearanceChanged(appearance) => {
self.appearance = appearance;
+ self.refresh_chrome();
window.invalidate();
Ok(true)
}
@@ -3187,7 +3279,7 @@ impl SettingsWindow {
self.ui.open_dropdown = None;
match crate::native_settings::set_remote_download_directory(path) {
Ok(()) => {
- self.native_settings = crate::native_settings::load();
+ self.set_native_settings(crate::native_settings::load());
self.status = settings_tr(
"settings-status-download-path",
&[("path", self.remote_download_directory_label())],
@@ -3427,6 +3519,49 @@ impl SettingsWindow {
}
}
+ fn apply_text_contrast(&mut self, mode: crate::native_settings::NativeTextContrast) {
+ self.ui.open_dropdown = None;
+ // Merge into the freshest settings rather than writing this window's
+ // whole clone: the colour-scheme row hands the choosing to the command
+ // palette, which writes `appearance.color_scheme` while Settings is
+ // still open. A full write from a snapshot taken before that would put
+ // the old scheme back, and the revert would only show up in the next
+ // window or the next launch. Same reasoning as
+ // `save_command_palette_settings`.
+ let mut merged = crate::native_settings::load();
+ merged.terminal.text_contrast = mode;
+ self.set_native_settings(merged);
+ match crate::native_settings::save(&self.native_settings) {
+ Ok(()) => {
+ // Every open window resolves the floor for itself and retires
+ // the quads that were built under the old one; a plain repaint
+ // would redraw them in the colours they were already baked in.
+ if let Some(front_end) = crate::frontend::try_front_end() {
+ for gui_window in front_end.gui_windows() {
+ gui_window.window.notify(
+ crate::termwindow::TermWindowNotif::Apply(Box::new(|term_window| {
+ term_window.refresh_text_min_contrast();
+ })),
+ );
+ }
+ }
+ self.status = settings_tr(
+ "settings-status-value-now",
+ &[
+ ("setting", crate::i18n::tr("settings-text-contrast")),
+ ("value", localized_text_contrast_label(mode)),
+ ],
+ );
+ }
+ Err(err) => {
+ self.status = settings_tr(
+ "settings-status-terminal-error",
+ &[("error", format!("{err:#}"))],
+ );
+ }
+ }
+ }
+
fn apply_remote_pane_resize_mode(&mut self, mode: NativeRemotePaneResizeMode) {
self.ui.open_dropdown = None;
self.native_settings.terminal.remote_pane_resize_mode = mode;
@@ -3531,13 +3666,52 @@ impl SettingsWindow {
.effective_appearance(crate::native_settings::system_appearance())
}
+ /// Re-resolve the cached chrome colours. Call after anything that moves
+ /// `effective_appearance`: the system appearance, or this window's own
+ /// `theme_mode`.
+ /// The window to hand the colour-scheme palette to: the one Settings was
+ /// opened from if it is still there, otherwise any terminal window, so
+ /// the row still works when that window has since been closed.
+ fn color_scheme_picker_target(&self) -> Option<crate::scripting::guiwin::GuiWin> {
+ let front_end = crate::frontend::try_front_end()?;
+ let windows = front_end.gui_windows();
+ let wanted = OPENED_FROM.with(|slot| slot.get());
+ windows
+ .iter()
+ .find(|gui_window| Some(gui_window.mux_window_id) == wanted)
+ .cloned()
+ .or_else(|| windows.into_iter().next())
+ }
+
+ fn refresh_chrome(&mut self) {
+ // The standalone window has no per-window overrides of its own, so it
+ // reads the configuration file's `ui_colors` rather than a terminal
+ // window's, which may carry a scheme picked only for that window.
+ self.chrome_palette = crate::native_settings::chrome_palette(
+ self.native_settings.appearance.theme_mode,
+ self.effective_appearance(),
+ &config::configuration(),
+ None,
+ );
+ }
+
+ /// Replace this window's copy of the settings, keeping the cached chrome
+ /// in step. Assign through here rather than to the field directly: the
+ /// merge-then-write helpers reload the shared settings, so a theme another
+ /// window picked arrives this way and the cache would otherwise be stale
+ /// until the next appearance event.
+ fn set_native_settings(&mut self, settings: ThinkTermNativeSettings) {
+ self.native_settings = settings;
+ self.refresh_chrome();
+ }
+
/// Every field reads a `UiPalette` token, so Settings tracks the main
/// window by construction. It stopped doing that once: two arms that
/// differed only in a hand-written `card_bg`, which was the token's value
/// copied out by hand and would have gone stale the first time the token
/// moved.
fn palette(&self) -> SettingsPalette {
- let ui = UiPalette::for_appearance(self.effective_appearance());
+ let ui = self.chrome_palette;
SettingsPalette {
window_bg: ui.window_bg,
sidebar_bg: ui.workspace_sidebar_bg,
@@ -3547,6 +3721,8 @@ impl SettingsWindow {
nav_hover_bg: ui.sidebar_row_hover_bg,
nav_pressed_bg: ui.sidebar_row_pressed_bg,
nav_selected_bg: ui.sidebar_row_active_bg,
+ track_off: ui.track_off,
+ is_dark: ui.is_dark(),
nav_selected_border: ui.sidebar_row_active_border,
control_bg: ui.control_bg,
control_hover_bg: ui.control_hover_bg,
@@ -3996,7 +4172,7 @@ impl SettingsWindow {
// the next terminal opened uses the new shell.
match crate::native_settings::save(&pending) {
Ok(()) => {
- self.native_settings = pending;
+ self.set_native_settings(pending);
self.status = settings_tr(
"settings-status-value-now",
&[
@@ -4104,6 +4280,7 @@ impl SettingsWindow {
}
}
SettingsAction::SetScrollMode(mode) => self.apply_scroll_mode(mode),
+ SettingsAction::SetTextContrast(mode) => self.apply_text_contrast(mode),
SettingsAction::SetRemotePaneResizeMode(mode) => {
self.apply_remote_pane_resize_mode(mode)
}
@@ -4579,6 +4756,26 @@ impl SettingsWindow {
Some(SettingsDropdown::ThemeMode)
};
}
+ SettingsAction::OpenColorSchemePicker => {
+ self.ui.open_dropdown = None;
+ self.set_focused_input(None);
+ match self.color_scheme_picker_target() {
+ Some(gui_window) => {
+ // Bring it forward first: the palette it is about to
+ // open is a preview, and a preview behind the settings
+ // window previews nothing.
+ gui_window.window.focus();
+ gui_window.window.notify(
+ crate::termwindow::TermWindowNotif::Apply(Box::new(|term_window| {
+ term_window.open_color_scheme_picker();
+ })),
+ );
+ }
+ None => {
+ self.status = crate::i18n::tr("settings-color-scheme-needs-a-window");
+ }
+ }
+ }
SettingsAction::ToggleCommandPaletteHotkeyMenu => {
self.ui.open_dropdown =
if self.ui.open_dropdown == Some(SettingsDropdown::CommandPaletteHotkey) {
@@ -4661,6 +4858,10 @@ impl SettingsWindow {
SettingsAction::SetThemeMode(mode) => {
let previous_mode = self.native_settings.appearance.theme_mode;
self.native_settings.appearance.theme_mode = mode;
+ // The pick previews from this window's own copy, so the cached
+ // chrome has to follow it here rather than waiting for an
+ // appearance event that only a system theme change sends.
+ self.refresh_chrome();
self.ui.open_dropdown = None;
match crate::native_settings::save(&self.native_settings) {
Ok(()) => {
@@ -4677,6 +4878,7 @@ impl SettingsWindow {
// new mode, so leaving it here would have this window
// previewing a theme that was never saved.
self.native_settings.appearance.theme_mode = previous_mode;
+ self.refresh_chrome();
let mut args = FluentArgs::new();
args.set("error", format!("{err:#}"));
self.status = crate::i18n::tr_args("settings-theme-save-error", &args);
@@ -5805,14 +6007,16 @@ impl SettingsWindow {
true,
)?;
y += row_step + app_icon_note_space;
- self.paint_setting_row(
+ let color_scheme_label = self.effective_color_scheme_label(&config);
+ self.paint_action_setting_row(
layers,
row_x,
y,
row_width,
&crate::i18n::tr("settings-effective-color-scheme"),
&crate::i18n::tr("settings-effective-color-scheme-description"),
- Self::effective_color_scheme_label(&config),
+ &color_scheme_label,
+ SettingsAction::OpenColorSchemePicker,
true,
)?;
y += row_step;
@@ -6717,7 +6921,7 @@ impl SettingsWindow {
fn save_web_settings(&mut self) {
let mut merged = crate::native_settings::load();
merged.web = self.native_settings.web.clone();
- self.native_settings = merged;
+ self.set_native_settings(merged);
if let Err(err) = crate::native_settings::save(&self.native_settings) {
log::error!("failed to save the browser link expiry: {err:#}");
}
@@ -6730,7 +6934,7 @@ impl SettingsWindow {
// write here would silently revert that choice.
let mut merged = crate::native_settings::load();
merged.command_palette = self.native_settings.command_palette.clone();
- self.native_settings = merged;
+ self.set_native_settings(merged);
match crate::native_settings::save(&self.native_settings) {
Ok(()) => {
// The palette re-reads its settings on every paint; a repaint
@@ -6994,11 +7198,11 @@ impl SettingsWindow {
let row_step = self.settings_row_step();
let section_y = self.ui_px(CONTENT_SECTION_Y) - scroll;
// Each settings card owns its row count because rows are painted manually.
- // Terminal currently paints eleven rows below; the count drives card height and scroll extent.
+ // Terminal currently paints twelve rows below; the count drives card height and scroll extent.
// What must stay in sync with paint_open_dropdown_overlay is not this
// number but each row's `row_step * N` multiplier, which that function
// copies by hand to place an open menu.
- let row_count = 11;
+ let row_count = 12;
let (card_y, first_row_y) = self.settings_card_geometry(section_y, row_count);
let card_height = self.settings_card_height(row_count);
let button_y = card_y + card_height + self.settings_section_card_gap();
@@ -7075,7 +7279,7 @@ impl SettingsWindow {
true,
)?;
{
- use crate::native_settings::NativeScrollMode;
+ use crate::native_settings::{NativeScrollMode, NativeTextContrast};
let resize_modes = NativeRemotePaneResizeMode::ALL;
let resize_options: Vec<(String, SettingsAction)> = resize_modes
.iter()
@@ -7126,11 +7330,36 @@ impl SettingsWindow {
scroll_selected,
true,
)?;
+ let contrast_modes = NativeTextContrast::ALL;
+ let contrast_options: Vec<(String, SettingsAction)> = contrast_modes
+ .iter()
+ .map(|mode| {
+ (
+ localized_text_contrast_label(*mode),
+ SettingsAction::SetTextContrast(*mode),
+ )
+ })
+ .collect();
+ let contrast_selected = contrast_modes
+ .iter()
+ .position(|mode| *mode == self.native_settings.terminal.text_contrast)
+ .unwrap_or(0);
+ self.paint_segmented_setting_row(
+ layers,
+ row_x,
+ first_row_y + row_step * 6.0,
+ row_width,
+ &crate::i18n::tr("settings-text-contrast"),
+ &crate::i18n::tr("settings-text-contrast-description"),
+ &contrast_options,
+ contrast_selected,
+ true,
+ )?;
}
self.paint_toggle_setting_row(
layers,
row_x,
- first_row_y + row_step * 6.0,
+ first_row_y + row_step * 7.0,
row_width,
&crate::i18n::tr("settings-overlay-scrollbar"),
&crate::i18n::tr("settings-overlay-scrollbar-description"),
@@ -7141,7 +7370,7 @@ impl SettingsWindow {
self.paint_toggle_setting_row(
layers,
row_x,
- first_row_y + row_step * 7.0,
+ first_row_y + row_step * 8.0,
row_width,
&crate::i18n::tr("settings-bottom-quote"),
&crate::i18n::tr("settings-bottom-quote-description"),
@@ -7152,7 +7381,7 @@ impl SettingsWindow {
self.paint_font_size_stepper_row(
layers,
row_x,
- first_row_y + row_step * 8.0,
+ first_row_y + row_step * 9.0,
row_width,
&crate::i18n::tr("settings-quote-font-size"),
&crate::i18n::tr("settings-quote-font-size-description"),
@@ -7181,7 +7410,7 @@ impl SettingsWindow {
self.paint_segmented_setting_row(
layers,
row_x,
- first_row_y + row_step * 9.0,
+ first_row_y + row_step * 10.0,
row_width,
&crate::i18n::tr("settings-quote-rotation"),
&crate::i18n::tr("settings-quote-rotation-description"),
@@ -7193,7 +7422,7 @@ impl SettingsWindow {
self.paint_font_size_stepper_row(
layers,
row_x,
- first_row_y + row_step * 10.0,
+ first_row_y + row_step * 11.0,
row_width,
&crate::i18n::tr("settings-quote-interval"),
&crate::i18n::tr("settings-quote-interval-description"),
@@ -8888,7 +9117,7 @@ impl SettingsWindow {
)),
Some(UpdateInstall::Failed { error }) => notes.push((
settings_tr("settings-update-install-failed", &[("error", error.clone())]),
- crate::ui::tokens::UiPalette::for_appearance(appearance).danger,
+ self.chrome_palette.danger,
)),
None => {}
}
@@ -9186,7 +9415,7 @@ impl SettingsWindow {
// Shared with the in-window switch, which this cannot call: that one
// draws through a DrawContext and this window has its own primitives.
let track = crate::ui::widgets::toggle_track_color(
- UiPalette::for_appearance(self.effective_appearance()),
+ self.chrome_palette,
enabled,
hovered,
pressed,
@@ -9437,10 +9666,16 @@ impl SettingsWindow {
if draw_top_rule {
self.paint_separator(layers, x, y - self.ui_px(28.0), width)?;
}
- // A button sized to its label and pushed to the column's right
- // edge, like System Settings; the column width is only a cap.
+ // A button sized to its label and pushed to the column's right edge,
+ // like System Settings. The column is the target, but a value can be
+ // longer than it offers -- a colour scheme name runs to forty
+ // characters -- so let the button borrow from the label side before
+ // the label is ellipsised, the same trade `paint_segmented_setting_row`
+ // makes.
let column_width = self.settings_control_width(width);
- let control_width = self.button_width_for_label(value, 0.0).min(column_width);
+ let control_width = self
+ .button_width_for_label(value, 0.0)
+ .min(column_width.max(width * 0.45));
let control_x = x + width - control_width;
let control_y = y + self.ui_px(4.0);
let text_width = (control_x - x - self.ui_px(24.0)).max(width * 0.45);
@@ -9481,6 +9716,7 @@ impl SettingsWindow {
if draw_top_rule {
self.paint_separator(layers, x, y - self.ui_px(28.0), width)?;
}
+ let (track_bg, segment_fill) = segmented_track_and_fill(&palette);
let column_width = self.settings_control_width(width);
let control_y = y + self.ui_px(4.0);
let control_height = self.ui_px(CONTROL_HEIGHT);
@@ -9526,7 +9762,7 @@ impl SettingsWindow {
control_y,
control_width,
control_height,
- palette.control_bg,
+ track_bg,
palette.control_border,
self.ui_px(CONTROL_RADIUS),
)?;
@@ -9546,7 +9782,7 @@ impl SettingsWindow {
let hovered = self.ui.interaction.hovered == Some(*action);
let pressed = self.ui.interaction.pressed == Some(*action);
let fill = if is_selected {
- Some(palette.nav_selected_bg)
+ Some(segment_fill)
} else if pressed {
Some(palette.control_pressed_bg)
} else if hovered {
@@ -9598,7 +9834,12 @@ impl SettingsWindow {
column_width: f32,
label: &str,
) -> window::RectF {
- let natural = self.measure_text_width(&self.ui_font, label) + self.ui_px(60.0);
+ // The 60 is what `paint_dropdown_pill` takes back out of the width for
+ // the inset and the chevron, so a label sized to exactly `text + 60`
+ // is handed a budget of exactly its own width -- which lands on the
+ // truncation boundary and loses its last character. "Dark" drew as
+ // "Dar". The slack is for that boundary, not for looks.
+ let natural = self.measure_text_width(&self.ui_font, label) + self.ui_px(68.0);
let pill_width = natural.max(self.ui_px(120.0)).min(column_width);
rect(
control_x + column_width - pill_width,
@@ -10938,23 +11179,17 @@ impl SettingsWindow {
y: f32,
width: f32,
) -> anyhow::Result<()> {
- let options = [
- (
- localized_theme_mode_label(NativeThemeMode::System),
- SettingsAction::SetThemeMode(NativeThemeMode::System),
- self.native_settings.appearance.theme_mode == NativeThemeMode::System,
- ),
- (
- localized_theme_mode_label(NativeThemeMode::Light),
- SettingsAction::SetThemeMode(NativeThemeMode::Light),
- self.native_settings.appearance.theme_mode == NativeThemeMode::Light,
- ),
- (
- localized_theme_mode_label(NativeThemeMode::Dark),
- SettingsAction::SetThemeMode(NativeThemeMode::Dark),
- self.native_settings.appearance.theme_mode == NativeThemeMode::Dark,
- ),
- ];
+ let chosen = self.native_settings.appearance.theme_mode;
+ let options: Vec<_> = NativeThemeMode::ALL
+ .iter()
+ .map(|mode| {
+ (
+ localized_theme_mode_label(*mode),
+ SettingsAction::SetThemeMode(*mode),
+ chosen == *mode,
+ )
+ })
+ .collect();
self.paint_dropdown_menu(layers, x, y, width, &options)
}
@@ -11271,7 +11506,7 @@ impl SettingsWindow {
if !visible {
return Ok(());
}
- let ui_palette = UiPalette::for_appearance(self.effective_appearance());
+ let ui_palette = self.chrome_palette;
let spec = ScrollbarSpec::from_area(area, self.ui.tokens);
if let Some((thumb_y, thumb_h)) = scroll.thumb(spec.y, spec.height) {
self.draw_rounded_rect(
@@ -11297,7 +11532,13 @@ impl SettingsWindow {
label: &str,
action: SettingsAction,
) -> anyhow::Result<()> {
- let width = width.max(self.button_width_for_label(label, 0.0));
+ // The width given is the width drawn. This used to be
+ // `width.max(button_width_for_label(..))` -- a button whose label did
+ // not fit grew to the right and out of whatever was holding it, which
+ // is exactly what a caller passing a *capped* width is trying to
+ // prevent. The label is ellipsised to fit below instead. Every other
+ // caller already passes a width sized to its own label, so nothing
+ // else moves.
let button = ButtonSpec {
label,
action,
@@ -11318,7 +11559,7 @@ impl SettingsWindow {
.push(button.rect, button.kind, button.action);
let palette = self.palette();
- let ui_palette = UiPalette::for_appearance(self.effective_appearance());
+ let ui_palette = self.chrome_palette;
let (background, border) = button.state.colors(ui_palette);
// Fully rounded rather than CONTROL_RADIUS: a pill reads as a
// button, which is what distinguishes it from the value pills and
@@ -12281,14 +12522,24 @@ return config
out
}
- fn effective_color_scheme_label(config: &config::ConfigHandle) -> &str {
+ /// What the terminal is actually painted in.
+ ///
+ /// The picked scheme first: a scheme chosen here or in the command palette
+ /// lives in the native settings and reaches a window as that window's own
+ /// override, so it is never in the configuration handle. Reading only the
+ /// handle showed the file's scheme while the terminal in front of the user
+ /// showed the one they picked.
+ fn effective_color_scheme_label(&self, config: &config::ConfigHandle) -> String {
+ if let Some(name) = self.native_settings.appearance.color_scheme.as_deref() {
+ return name.to_string();
+ }
if let Some(name) = config.color_scheme.as_deref() {
- name
- } else if config.colors.is_some() {
- "Custom inline colors"
- } else {
- "Default palette"
+ return name.to_string();
+ }
+ if config.colors.is_some() {
+ return crate::i18n::tr("settings-color-scheme-inline");
}
+ crate::i18n::tr("settings-color-scheme-default")
}
fn effective_font_family(config: &config::ConfigHandle) -> String {
diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs
index fe8462a3..c3b5f7a7 100644
--- a/wezterm-gui/src/termwindow/mod.rs
+++ b/wezterm-gui/src/termwindow/mod.rs
@@ -2380,6 +2380,15 @@ pub struct TermWindow {
current_highlight: Option<Arc<Hyperlink>>,
quad_generation: usize,
+ /// The chrome's colours, resolved once per configuration rather than once
+ /// per draw. Deriving them is cheap, but the appearance they are derived
+ /// from was not: `native_settings::effective_appearance()` deep-clones the
+ /// whole settings struct and asks the platform for its appearance, and the
+ /// paint path was calling it nineteen times a frame.
+ ///
+ /// Refreshed in `config_was_reloaded`, which is also where a colour scheme
+ /// override and an appearance change both land.
+ chrome_palette: crate::ui::UiPalette,
shape_generation: usize,
shape_cache: RefCell<LfuCache<ShapeCacheKey, anyhow::Result<Rc<Vec<ShapedInfo>>>>>,
/// Per-domain shaping caches for proportional UI text (chrome / Note /
@@ -2414,6 +2423,24 @@ pub struct TermWindow {
ui_items: Vec<UIItem>,
context_menu: Option<ui::context_menu::ContextMenuState>,
command_palette: Option<ui::command_palette::CommandPaletteState>,
+ /// The contrast floor text is held to, or `None` to leave the
+ /// application's colours alone. Resolved from the settings window's
+ /// choice and the configuration file once per reload rather than per
+ /// cell; see `native_settings::text_min_contrast_ratio`.
+ text_min_contrast: Option<f32>,
+ /// Adjusted foregrounds for the contrast floor, keyed on the
+ /// (foreground, background, ratio) that produced them. See
+ /// `ensure_min_contrast`.
+ min_contrast_memo: RefCell<HashMap<[u32; 9], LinearRgba>>,
+ /// The terminal background of a scheme being previewed, so the chrome can
+ /// follow a pick before it is made. `None` outside a preview.
+ scheme_preview_ground: Option<LinearRgba>,
+ /// The colour scheme the command palette is showing but the user has not
+ /// chosen: `Some(None)` the configured default, `Some(Some(name))` a named
+ /// scheme, `None` no preview. Lives here rather than on the palette state
+ /// because every path that closes the palette has already taken that state
+ /// away, and closing is exactly when the preview must be undone.
+ scheme_preview: Option<Option<String>>,
context_menu_application_actions: HashMap<u64, ContextMenuApplicationAction>,
next_context_menu_application_action_id: u64,
context_menu_suppressed_release: Option<MousePress>,
@@ -3591,15 +3618,20 @@ impl TermWindow {
let native_settings = crate::native_settings::load();
// A palette-picked color scheme applies from the first frame; seeding
// config_overrides here is what makes it stick for new windows.
- let (config, config_overrides) = match native_settings.appearance.color_scheme.clone() {
+ let (config, config_overrides) = match crate::native_settings::effective_color_scheme(
+ &native_settings,
+ &config,
+ ) {
Some(scheme) => {
use wezterm_dynamic::ToDynamic;
// Deliberately louder than trace: this silently overrides
// `color_scheme` from the config file, and "why doesn't my
// config change do anything" needs a breadcrumb.
log::info!(
- "color scheme overridden to {scheme:?} by the command palette choice; \
- pick \"Use configured default\" there to follow the config file again"
+ "color scheme overridden to {scheme:?} -- either picked in the command \
+ palette or in Settings, or the light default that goes with a light \
+ interface; pick \"Use configured default\" in the palette to follow the \
+ config file again"
);
let mut obj = wezterm_dynamic::Object::default();
obj.insert("color_scheme".to_dynamic(), scheme.to_dynamic());
@@ -3834,6 +3866,12 @@ impl TermWindow {
last_mouse_click: None,
current_highlight: None,
quad_generation: 0,
+ chrome_palette: crate::native_settings::chrome_palette(
+ crate::native_settings::load_shared().appearance.theme_mode,
+ crate::native_settings::effective_appearance(),
+ &config,
+ None,
+ ),
shape_generation: 0,
shape_cache: RefCell::new(LfuCache::new_weighted(
"shape_cache.hit.rate",
@@ -3902,6 +3940,10 @@ impl TermWindow {
ui_items: vec![],
context_menu: None,
command_palette: None,
+ text_min_contrast: crate::native_settings::text_min_contrast_ratio(&config),
+ min_contrast_memo: RefCell::new(HashMap::new()),
+ scheme_preview: None,
+ scheme_preview_ground: None,
context_menu_application_actions: HashMap::new(),
next_context_menu_application_action_id: 1,
context_menu_suppressed_release: None,
@@ -4355,7 +4397,27 @@ impl TermWindow {
// be nasty for folks with a lot of windows.
// <https://github.com/wezterm/wezterm/issues/2295>
config::reload();
- self.config_was_reloaded();
+ // The scheme the interface defaults to has a side (see
+ // `native_settings::effective_color_scheme`), and the side just
+ // moved. Under System theme with nothing picked, a window
+ // opened in light appearance has the light scheme sitting in
+ // its `config_overrides`; a reload alone keeps it there, so the
+ // desktop going dark would leave a dark interface in front of a
+ // light scheme's black-on-white text.
+ //
+ // Safe to recompute rather than remember: the only writer of
+ // `color_scheme` in the overrides is this pairing and the
+ // explicit picks it defers to, and `effective_color_scheme`
+ // returns the pick unchanged.
+ let reloaded = self.apply_color_scheme_override(
+ crate::native_settings::effective_color_scheme(
+ &crate::native_settings::load(),
+ &self.config,
+ ),
+ );
+ if !reloaded {
+ self.config_was_reloaded();
+ }
Ok(true)
}
WindowEvent::PerformKeyAssignment(action) => {
@@ -6207,6 +6269,47 @@ impl TermWindow {
}
impl TermWindow {
+ /// The chrome's colours: the sidebars, the tab bar, the pane nav bars and
+ /// every other surface this window paints around the terminal.
+ ///
+ /// Resolved in `config_was_reloaded` rather than here, so a draw costs a
+ /// copy of a `Copy` struct. Distinct from [`Self::palette`] below, which is
+ /// the *terminal's* colours.
+ pub(crate) fn chrome(&self) -> crate::ui::UiPalette {
+ self.chrome_palette
+ }
+
+ /// Re-resolve the contrast floor and retire the quads that were built
+ /// under the old one. `config_was_reloaded` re-resolves it too; this is
+ /// the direct route, for the settings window, which writes the choice to
+ /// its own file and never touches the configuration.
+ pub(crate) fn refresh_text_min_contrast(&mut self) {
+ let next = crate::native_settings::text_min_contrast_ratio(&self.config);
+ if next == self.text_min_contrast {
+ return;
+ }
+ self.text_min_contrast = next;
+ // Colours are baked into the quad and shape cache *values* while the
+ // keys carry only this generation, so bumping it is what retires
+ // them. The memo below is keyed on the ratio and so cannot go stale.
+ self.shape_generation += 1;
+ self.shape_cache.borrow_mut().clear();
+ self.invalidate_window();
+ }
+
+ /// Re-resolve the cached chrome colours. `config_was_reloaded` does this
+ /// too; this is the direct route, for when the appearance moved without a
+ /// configuration reload behind it.
+ pub(crate) fn refresh_chrome(&mut self) {
+ self.chrome_palette = crate::native_settings::chrome_palette(
+ crate::native_settings::load_shared().appearance.theme_mode,
+ crate::native_settings::effective_appearance(),
+ &self.config,
+ self.scheme_preview_ground,
+ );
+ self.invalidate_window();
+ }
+
fn palette(&mut self) -> &ColorPalette {
if self.palette.is_none() {
self.palette
@@ -6218,7 +6321,10 @@ impl TermWindow {
/// Apply (or clear) a color-scheme override on this window without
/// touching persistence — the same mechanism as
/// `window:set_config_overrides`. A no-op when nothing changes.
- pub(crate) fn apply_color_scheme_override(&mut self, name: Option<String>) {
+ /// True when the overrides moved, which means `config_was_reloaded` has
+ /// already run. Callers about to reload anyway can use that to not do it
+ /// twice -- a reload re-runs the Lua configuration from disk.
+ pub(crate) fn apply_color_scheme_override(&mut self, name: Option<String>) -> bool {
use wezterm_dynamic::{ToDynamic, Value};
let mut map = match &self.config_overrides {
Value::Object(obj) => obj.clone(),
@@ -6238,10 +6344,11 @@ impl TermWindow {
|| (matches!(&next, Value::Object(obj) if obj.is_empty())
&& matches!(&self.config_overrides, Value::Null))
{
- return;
+ return false;
}
self.config_overrides = next;
self.config_was_reloaded();
+ true
}
/// The command palette's theme switch: apply to this window, persist the
@@ -6249,8 +6356,27 @@ impl TermWindow {
/// window follow. The broadcast reaches this window too; the second
/// application no-ops on the unchanged overrides.
fn set_color_scheme_override(&mut self, name: Option<String>) {
- self.apply_color_scheme_override(name.clone());
+ // Persisted *before* the override is applied. Applying it reloads the
+ // configuration, which re-resolves the chrome, which under "follow
+ // terminal colours" reads the chosen scheme back out of the settings.
+ // Saving second meant that read saw the previous scheme: the interface
+ // flashed the colours it was leaving before arriving at the ones it
+ // was asked for.
crate::native_settings::save_color_scheme(name.clone());
+ // A scheme can move which side the interface is on, and the platform's
+ // own chrome takes its tint from that.
+ crate::native_settings::apply_preferred_appearance(
+ crate::native_settings::load_shared().appearance.theme_mode,
+ );
+ self.apply_color_scheme_override(name.clone());
+ // `apply_color_scheme_override` is a no-op when this window's
+ // overrides already name the scheme -- which is exactly the case after
+ // a preview -- so the chrome is refreshed here rather than relying on
+ // the reload that call may not perform.
+ self.refresh_chrome();
+ // The settings window derives its own surfaces from this scheme too,
+ // and is in no broadcast list of its own.
+ crate::settings_window::refresh_open_settings_window_chrome();
if let Some(front_end) = crate::frontend::try_front_end() {
for gui_window in front_end.gui_windows() {
let name = name.clone();
@@ -6283,6 +6409,38 @@ impl TermWindow {
};
self.config = config.clone();
self.palette.take();
+ // One place for all three ways the chrome's colours can move: a
+ // configuration reload, a colour scheme override, and an appearance
+ // change (which routes here too).
+ //
+ // Above the `mux.get_window` bail below, not after it: a window that
+ // outlives its mux window still paints, and nothing else re-resolves
+ // these two -- the settings-window routes reach them only through
+ // their own notifies.
+ self.chrome_palette = crate::native_settings::chrome_palette(
+ crate::native_settings::load_shared().appearance.theme_mode,
+ crate::native_settings::effective_appearance(),
+ &config,
+ self.scheme_preview_ground,
+ );
+ self.text_min_contrast = crate::native_settings::text_min_contrast_ratio(&config);
+ // Under "follow terminal colours" a scheme changed in the
+ // configuration file moves which side the interface is on, and the
+ // platform's own chrome -- title bar, native buttons, menus -- takes
+ // its tint from the connection's appearance, which only
+ // `apply_preferred_appearance` moves. The settings window and the
+ // command palette call it on their own routes; this is the file's.
+ // Guarded on an actual change because setting it feeds an appearance
+ // event back through here.
+ {
+ let mode = crate::native_settings::load_shared().appearance.theme_mode;
+ if mode == crate::native_settings::NativeThemeMode::FollowTerminal
+ && self.chrome_palette.appearance
+ != crate::native_settings::effective_appearance()
+ {
+ crate::native_settings::apply_preferred_appearance(mode);
+ }
+ }
let mux = Mux::get();
let window = match mux.get_window(self.mux_window_id) {
@@ -9723,7 +9881,7 @@ impl TermWindow {
wezterm_open_url::open_url(link);
}
OpenSettings => {
- crate::settings_window::show();
+ crate::settings_window::show_from(self.mux_window_id);
}
QuitAndStopSessionServer => {
// The stop happens after the loop ends; the quit itself
diff --git a/wezterm-gui/src/termwindow/onboarding.rs b/wezterm-gui/src/termwindow/onboarding.rs
index 45d3871a..3ba7b39f 100644
--- a/wezterm-gui/src/termwindow/onboarding.rs
+++ b/wezterm-gui/src/termwindow/onboarding.rs
@@ -860,7 +860,12 @@ impl OnboardingView {
)?;
}
NativeThemeMode::Light => self.paint_face(ctx, layers, inner, skin, true, fit)?,
- NativeThemeMode::Dark => self.paint_face(ctx, layers, inner, skin, false, fit)?,
+ // Onboarding offers three tiles and builds the list itself, so
+ // `FollowTerminal` never reaches here; drawn as dark rather than
+ // left to panic if that list ever grows.
+ NativeThemeMode::Dark | NativeThemeMode::FollowTerminal => {
+ self.paint_face(ctx, layers, inner, skin, false, fit)?
+ }
}
let text_w = ctx.measure_text_width(font, label).min(tile.size.width);
diff --git a/wezterm-gui/src/termwindow/render/borders.rs b/wezterm-gui/src/termwindow/render/borders.rs
index 68e66d54..ceb6069a 100644
--- a/wezterm-gui/src/termwindow/render/borders.rs
+++ b/wezterm-gui/src/termwindow/render/borders.rs
@@ -1,5 +1,4 @@
use crate::quad::TripleLayerQuadAllocator;
-use crate::ui::UiPalette;
use crate::utilsprites::RenderMetrics;
use ::window::ULength;
use config::{ConfigHandle, DimensionContext};
@@ -19,7 +18,7 @@ impl crate::TermWindow {
let height = self.dimensions.pixel_height as f32;
let width = self.dimensions.pixel_width as f32;
let chrome_border_color = self.config.use_fancy_tab_bar.then(|| {
- UiPalette::for_appearance(crate::native_settings::effective_appearance()).sidebar_bg
+ self.chrome().sidebar_bg
});
let border_top = border_dimensions.top.get() as f32;
diff --git a/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs b/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs
index 9a39909d..0ca9f0a4 100644
--- a/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs
+++ b/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs
@@ -32,6 +32,7 @@ const WINDOW_TAB_ICON_GAP: usize = 8;
const WINDOW_TAB_MIN_TEXT_COLS: usize = 3;
const UI_SHAPE_CACHE_FONT_IDENTITY_BIT: u64 = 1u64 << 63;
+
impl crate::TermWindow {
pub fn invalidate_fancy_tab_bar(&mut self) {
self.fancy_tab_bar.take();
@@ -41,7 +42,7 @@ impl crate::TermWindow {
&mut self,
layers: &mut TripleLayerQuadAllocator,
) -> anyhow::Result<Vec<UIItem>> {
- let chrome = UiPalette::for_appearance(crate::native_settings::effective_appearance());
+ let chrome = self.chrome();
let row_height = self.tab_bar_pixel_height()?.ceil() as usize;
if row_height == 0 {
return Ok(vec![]);
@@ -53,7 +54,7 @@ impl crate::TermWindow {
let metrics = RenderMetrics::with_font_metrics(&font.metrics());
let tab_width = self.window_tab_width_pixels().ceil() as usize;
- let background = chrome.sidebar_bg;
+ let background = chrome.header_bg;
let foreground = chrome.text;
let muted_fg = chrome.secondary_text;
@@ -427,7 +428,7 @@ impl crate::TermWindow {
}];
if self.fancy_tab_bar_shows_window_buttons() {
- let chrome = UiPalette::for_appearance(crate::native_settings::effective_appearance());
+ let chrome = self.chrome();
let content_top_spacer = self.ui_px(WINDOW_TAB_TOP_SPACER).min(row_height);
let content_row_y = row_y + content_top_spacer;
let content_row_height = row_height.saturating_sub(content_top_spacer);
@@ -754,7 +755,7 @@ impl crate::TermWindow {
let hover_width = visible_width.max(0.0) as usize;
let is_hovered = self.is_pointer_over_ui_rect(hover_x, row_y, hover_width, row_height);
let tab_surface_color = if active {
- chrome.control_bg
+ chrome.active_tab_surface()
} else if is_hovered && !is_renaming {
chrome.control_hover_bg
} else {
@@ -988,7 +989,7 @@ impl crate::TermWindow {
row_height,
);
let surface = if active {
- chrome.control_bg
+ chrome.active_tab_surface()
} else if is_hovered {
chrome.control_hover_bg
} else {
@@ -1129,7 +1130,7 @@ impl crate::TermWindow {
let press_inset = if pressed { 1 } else { 0 };
let visual_size = button_size.saturating_sub(press_inset * 2);
if hovered {
- let chrome = UiPalette::for_appearance(crate::native_settings::effective_appearance());
+ let chrome = self.chrome();
let fill = if pressed {
chrome.control_pressed_bg
} else {
@@ -1200,7 +1201,7 @@ impl crate::TermWindow {
let press_inset = if pressed { 1 } else { 0 };
let visual_size = button_size.saturating_sub(press_inset * 2);
if hovered {
- let chrome = UiPalette::for_appearance(crate::native_settings::effective_appearance());
+ let chrome = self.chrome();
let fill = if pressed {
chrome.control_pressed_bg
} else {
diff --git a/wezterm-gui/src/termwindow/render/mod.rs b/wezterm-gui/src/termwindow/render/mod.rs
index d0b26b0e..c91bd832 100644
--- a/wezterm-gui/src/termwindow/render/mod.rs
+++ b/wezterm-gui/src/termwindow/render/mod.rs
@@ -787,13 +787,46 @@ impl crate::TermWindow {
self.dedicated_image_cell.set(Some((layer_num, cell_idx)));
}
+ /// Beyond this the memo is cleared rather than grown. A frame draws from
+ /// a palette, so the distinct (foreground, background, ratio) triples in
+ /// flight are the ANSI colours against one or two backgrounds -- tens, not
+ /// one per cell. A number well above that only ever means something
+ /// unusual is on screen, and starting over costs a few misses.
+ const MIN_CONTRAST_MEMO_MAX: usize = 512;
+
fn ensure_min_contrast(&self, fg_color: LinearRgba, bg_color: LinearRgba) -> LinearRgba {
- match self.config.text_min_contrast_ratio {
- Some(ratio) => fg_color
- .ensure_contrast_ratio(&bg_color, ratio)
- .unwrap_or(fg_color),
- None => fg_color,
+ let Some(ratio) = self.text_min_contrast else {
+ return fg_color;
+ };
+
+ // Memoised because this is per cell, and finding a readable colour
+ // costs a short binary search through OkLab. `ensure_contrast_ratio`
+ // is a pure function of these three, so an entry cannot go stale and
+ // the map never needs invalidating -- only bounding.
+ let key = [
+ fg_color.0.to_bits(),
+ fg_color.1.to_bits(),
+ fg_color.2.to_bits(),
+ fg_color.3.to_bits(),
+ bg_color.0.to_bits(),
+ bg_color.1.to_bits(),
+ bg_color.2.to_bits(),
+ bg_color.3.to_bits(),
+ ratio.to_bits(),
+ ];
+ if let Some(hit) = self.min_contrast_memo.borrow().get(&key) {
+ return *hit;
+ }
+
+ let adjusted = fg_color
+ .ensure_contrast_ratio(&bg_color, ratio)
+ .unwrap_or(fg_color);
+ let mut memo = self.min_contrast_memo.borrow_mut();
+ if memo.len() >= Self::MIN_CONTRAST_MEMO_MAX {
+ memo.clear();
}
+ memo.insert(key, adjusted);
+ adjusted
}
pub fn compute_cell_fg_bg(&self, params: ComputeCellFgBgParams) -> ComputeCellFgBgResult {
diff --git a/wezterm-gui/src/termwindow/render/paint.rs b/wezterm-gui/src/termwindow/render/paint.rs
index d1927393..7c1e86c7 100644
--- a/wezterm-gui/src/termwindow/render/paint.rs
+++ b/wezterm-gui/src/termwindow/render/paint.rs
@@ -4,7 +4,7 @@ use crate::quad::{
use crate::termwindow::content_view::{ContentViewTypography, TerminalPreviewRequest};
use crate::termwindow::render::{LineToEleShapeCacheKey, RenderScreenLineParams};
use crate::termwindow::{PaintOutcome, RenderFrame, TermWindowNotif, UIItem, UIItemType};
-use crate::ui::{DrawContext, UiPalette};
+use crate::ui::DrawContext;
use ::window::bitmaps::atlas::OutOfTextureSpace;
use ::window::color::LinearRgba;
use ::window::RectF;
@@ -611,7 +611,7 @@ impl crate::TermWindow {
// fully draw-on-demand.
self.update_next_frame_time(Some(now + Duration::from_millis(125)));
let area = self.content_view_area();
- let palette = UiPalette::for_appearance(crate::native_settings::effective_appearance());
+ let palette = self.chrome();
self.filled_rectangle(layers, 0, area, palette.window_bg)
.context("frontend handoff opaque background")?;
@@ -706,7 +706,7 @@ impl crate::TermWindow {
if used_w >= area.size.width && used_h >= area.size.height {
return Ok(());
}
- let palette = UiPalette::for_appearance(crate::native_settings::effective_appearance());
+ let palette = self.chrome();
let line = palette.muted_text.mul_alpha(0.10);
let right_x = area.origin.x + used_w;
let bottom_y = area.origin.y + used_h;
@@ -1610,7 +1610,7 @@ impl crate::TermWindow {
let render_metrics =
crate::utilsprites::RenderMetrics::with_font_metrics(&ui_font.metrics());
let dimensions = self.dimensions;
- let palette = UiPalette::for_appearance(crate::native_settings::effective_appearance());
+ let palette = self.chrome();
// Occupy the terminal content area between the workspace and right
// sidebars, below the top tab bar and above a bottom tab bar.
@@ -3005,7 +3005,7 @@ impl crate::TermWindow {
// From the shared chrome palette, not a hand-picked grey: the tag sits
// directly against the sidebar it overhangs, so anything lighter than
// the sidebar's own controls reads as a foreign surface.
- let chrome = UiPalette::for_appearance(crate::native_settings::effective_appearance());
+ let chrome = self.chrome();
let gl_state = self.render_state.as_ref().unwrap();
let layer = gl_state
@@ -3680,7 +3680,7 @@ impl crate::TermWindow {
crate::native_settings::effective_appearance(),
window::Appearance::Dark | window::Appearance::DarkHighContrast
) {
- UiPalette::for_appearance(crate::native_settings::effective_appearance())
+ self.chrome()
.sidebar_bg
.mul_alpha(self.config.window_background_opacity)
} else if panes.len() == 1 {
@@ -3716,7 +3716,7 @@ impl crate::TermWindow {
let border = self.get_os_border();
let header_height = border.top.get() as f32;
if header_height > 0.0 {
- let chrome = UiPalette::for_appearance(crate::native_settings::effective_appearance());
+ let chrome = self.chrome();
self.filled_rectangle(
&mut layers,
0,
@@ -4083,7 +4083,7 @@ impl crate::TermWindow {
let hint_width =
self.ui_px(crate::termwindow::ui::tokens::SIDEBAR_HOVER_HINT_WIDTH) as f32;
let palette =
- UiPalette::for_appearance(crate::native_settings::effective_appearance());
+ self.chrome();
let mut hint_layers = layer.quad_allocator();
self.filled_rectangle(
&mut hint_layers,
diff --git a/wezterm-gui/src/termwindow/render/pane.rs b/wezterm-gui/src/termwindow/render/pane.rs
index 584c2c5f..365fd484 100644
--- a/wezterm-gui/src/termwindow/render/pane.rs
+++ b/wezterm-gui/src/termwindow/render/pane.rs
@@ -18,7 +18,6 @@ use crate::termwindow::ui::tokens::{
TAB_VERTICAL_PADDING,
};
use crate::termwindow::{PaneNavAction, ScrollHit, ScrollTrack, UIItem, UIItemType};
-use crate::ui::UiPalette;
use crate::utilsprites::RenderMetrics;
use ::window::bitmaps::TextureRect;
use ::window::{DeadKeyStatus, RectF};
@@ -290,7 +289,7 @@ impl crate::TermWindow {
layout: CollapsedPaneLayout,
) -> anyhow::Result<usize> {
let pane_rect = self.pane_frame_rect(pos)?;
- let chrome = UiPalette::for_appearance(crate::native_settings::effective_appearance());
+ let chrome = self.chrome();
let foreground = chrome.text;
let muted_fg = chrome.secondary_text;
@@ -470,7 +469,7 @@ impl crate::TermWindow {
let is_hovered = !suppress_hover
&& self.is_pointer_over_ui_rect(hover_x, tab_y, hover_width, tab_height);
let tab_surface_color = if selected_tab {
- chrome.control_bg
+ chrome.active_tab_surface()
} else if is_hovered && !is_renaming_tab {
chrome.control_hover_bg
} else {
@@ -739,8 +738,12 @@ impl crate::TermWindow {
}
let (pane_x, pane_width) = self.pane_chrome_span(pos)?;
- let chrome = UiPalette::for_appearance(crate::native_settings::effective_appearance());
- let background = chrome.sidebar_bg;
+ let chrome = self.chrome();
+ // Between the tab strip and the terminal, so it belongs to the
+ // terminal's header rather than to the sidebar -- same reasoning as
+ // the tab strip itself. `header_bg` is the chrome's own colour in a
+ // dark interface, so nothing moves there.
+ let background = chrome.header_bg;
let foreground = chrome.text;
let muted_fg = chrome.secondary_text;
let tab_fg = if pos.is_active { foreground } else { muted_fg };
@@ -864,7 +867,7 @@ impl crate::TermWindow {
let is_hovered = !suppress_hover
&& self.is_pointer_over_ui_rect(hover_x, tab_y, hover_width, tab_height);
let tab_surface_color = if selected_tab {
- chrome.control_bg
+ chrome.active_tab_surface()
} else if is_hovered && !is_renaming_tab {
chrome.control_hover_bg
} else {
@@ -1120,7 +1123,7 @@ impl crate::TermWindow {
let press_inset = if pressed { 1 } else { 0 };
let visual_size = button_size.saturating_sub(press_inset * 2);
if hovered {
- let chrome = UiPalette::for_appearance(crate::native_settings::effective_appearance());
+ let chrome = self.chrome();
let fill = if pressed {
chrome.control_pressed_bg
} else {
@@ -1249,7 +1252,7 @@ impl crate::TermWindow {
let tokens = crate::ui::UiTokens::for_dpi(self.dimensions.dpi);
let ui_palette =
- crate::ui::UiPalette::for_appearance(crate::native_settings::effective_appearance());
+ self.chrome();
let track_top = content_top + tokens.scrollbar_margin_y;
let track_height =
(content_bottom - content_top - 2.0 * tokens.scrollbar_margin_y).max(0.0);
@@ -1466,7 +1469,7 @@ impl crate::TermWindow {
window::Appearance::Dark | window::Appearance::DarkHighContrast
)
.then(|| {
- UiPalette::for_appearance(crate::native_settings::effective_appearance()).sidebar_bg
+ self.chrome().sidebar_bg
});
let default_bg = dark_chrome_background
.unwrap_or_else(|| palette.resolve_bg(ColorAttribute::Default).to_linear())
diff --git a/wezterm-gui/src/termwindow/ui/command_palette.rs b/wezterm-gui/src/termwindow/ui/command_palette.rs
index 6057605d..29d2a84e 100644
--- a/wezterm-gui/src/termwindow/ui/command_palette.rs
+++ b/wezterm-gui/src/termwindow/ui/command_palette.rs
@@ -8,6 +8,9 @@
//! before the terminal's).
use crate::commands::ExpandedCommand;
+use config::TermConfig;
+use std::sync::Arc;
+use wezterm_term::TerminalConfiguration;
use crate::overlay::selector::{matcher_pattern, matcher_score};
use crate::workspace_threads::{ThreadSearchEntry, WorkspaceThreadWorkStatus};
use crate::termwindow::palette::{build_commands, format_key_label, frecency_scores, save_recent};
@@ -318,6 +321,28 @@ impl CommandPaletteState {
}
}
+ /// The command an entry runs, borrowed. `command_for_entry` clones a
+ /// whole `ExpandedCommand` -- two strings and a key vector -- which is
+ /// waste on the paths that only want to look at the action, and those
+ /// paths run on every pointer move across the list.
+ fn action_for_entry(&self, order_idx: usize) -> Option<&KeyAssignment> {
+ match self.entry(order_idx)? {
+ MatchEntry::Item(idx) => match self.current_items().get(idx)? {
+ PaletteItem::Leaf(cmd) => Some(&cmd.action),
+ PaletteItem::Group(_) | PaletteItem::Header(_) => None,
+ },
+ MatchEntry::Nested(group_idx, child_idx) => {
+ match self.current_items().get(group_idx)? {
+ PaletteItem::Group(group) => match group.items.get(child_idx)? {
+ PaletteItem::Leaf(cmd) => Some(&cmd.action),
+ PaletteItem::Group(_) | PaletteItem::Header(_) => None,
+ },
+ PaletteItem::Leaf(_) | PaletteItem::Header(_) => None,
+ }
+ }
+ }
+ }
+
fn command_for_entry(&self, order_idx: usize) -> Option<ExpandedCommand> {
match self.entry(order_idx)? {
MatchEntry::Item(idx) => match self.current_items().get(idx)? {
@@ -873,29 +898,64 @@ fn thread_leaf(entry: ThreadSearchEntry, archived_suffix: &str) -> (ExpandedComm
/// The floating-menu palette, tuned like `context_menu_palette` so the card
/// reads as native chrome in both appearances.
-fn command_palette_colors(appearance: Appearance) -> UiPalette {
- let mut palette = UiPalette::for_appearance(appearance);
- match appearance {
- Appearance::Dark | Appearance::DarkHighContrast => {
- palette.control_bg = LinearRgba::with_srgba(30, 30, 32, 255);
- palette.control_hover_bg = LinearRgba::with_srgba(255, 255, 255, 255).mul_alpha(0.08);
- palette.control_border = LinearRgba::with_srgba(118, 118, 128, 255).mul_alpha(0.34);
- palette.separator = LinearRgba::with_srgba(84, 84, 88, 255).mul_alpha(0.36);
- palette.text = LinearRgba::with_srgba(242, 242, 247, 255);
- palette.secondary_text = LinearRgba::with_srgba(226, 226, 232, 255);
- palette.muted_text = LinearRgba::with_srgba(150, 150, 156, 255);
- palette.selected_bg = LinearRgba::with_srgba(70, 70, 74, 255);
- }
- Appearance::Light | Appearance::LightHighContrast => {
- palette.control_bg = LinearRgba::with_srgba(246, 246, 248, 255);
- palette.control_hover_bg = LinearRgba::with_srgba(60, 60, 67, 255).mul_alpha(0.08);
- palette.control_border = LinearRgba::with_srgba(60, 60, 67, 255).mul_alpha(0.22);
- palette.separator = LinearRgba::with_srgba(60, 60, 67, 255).mul_alpha(0.20);
- }
+fn command_palette_colors(palette: UiPalette) -> UiPalette {
+ let mut palette = palette.as_menu_card();
+ // The one place this card differs from a context menu: its rows carry a
+ // selection, and the menu's own dark grey reads better under one than the
+ // sidebar's does.
+ if !palette.derived && palette.is_dark() {
+ palette.selected_bg = LinearRgba::with_srgba(70, 70, 74, 255);
}
palette
}
+/// Whether running `action` installs the scheme `preview` is showing, in which
+/// case winding the preview down can skip the restore -- the colours are about
+/// to be replaced by the same colours, and a restore in between would flash the
+/// old ones for a frame.
+///
+/// Everything else has to restore: a different scheme, a command that has
+/// nothing to do with colours, or no preview to begin with.
+fn execution_replaces_preview(
+ action: &KeyAssignment,
+ preview: &Option<Option<String>>,
+) -> bool {
+ match (action, preview) {
+ (KeyAssignment::SetColorScheme(name), Some(shown)) => name == shown,
+ _ => false,
+ }
+}
+
+/// What a preview step has to do to get from what is on screen to what the
+/// selection is asking for.
+#[derive(Debug, PartialEq, Eq)]
+enum PreviewStep {
+ /// Already right; touch nothing.
+ Nothing,
+ /// Show the wanted scheme.
+ Show,
+ /// Nothing is wanted any more; put the configuration's own colours back.
+ Restore,
+}
+
+/// `wanted` and `showing` are both "which scheme", where `None` means the
+/// selection is not on a scheme at all and `Some(None)` means the scheme list's
+/// "use the configured default" row.
+///
+/// Split out from the window so the four cases can be read, and tested,
+/// without one.
+fn preview_transition(
+ wanted: &Option<Option<String>>,
+ showing: &Option<Option<String>>,
+) -> PreviewStep {
+ match (wanted, showing) {
+ (None, None) => PreviewStep::Nothing,
+ (Some(w), Some(s)) if w == s => PreviewStep::Nothing,
+ (Some(_), _) => PreviewStep::Show,
+ (None, Some(_)) => PreviewStep::Restore,
+ }
+}
+
enum PaletteOutcome {
Keep,
Close,
@@ -969,6 +1029,171 @@ impl crate::TermWindow {
state.enter_group(idx);
}
+ /// The settings window's colour-scheme row: open the palette already
+ /// inside the scheme group.
+ ///
+ /// Settings does not carry a picker of its own. A thousand schemes need a
+ /// search box and a live preview to choose between, and this list already
+ /// is one -- building a second, worse one next to it is how two lists
+ /// drift apart.
+ pub(crate) fn open_color_scheme_picker(&mut self) {
+ self.open_command_palette();
+ let Some(state) = self.command_palette.as_mut() else {
+ return;
+ };
+ let Some(idx) = state.root.iter().position(|item| {
+ matches!(item, PaletteItem::Group(group) if group.kind == PaletteGroupKind::ColorScheme)
+ }) else {
+ return;
+ };
+ state.enter_group(idx);
+ }
+
+ /// Show the colour scheme the selection is sitting on, without choosing
+ /// it. Answers the difference between what the selection asks for and what
+ /// is already being shown, so calling it every paint is free when nothing
+ /// moved.
+ ///
+ /// Deliberately not `set_color_scheme_override`: that persists the choice,
+ /// broadcasts it, and reloads the configuration from disk -- which closes
+ /// this palette. Preview swaps the panes' palette and repaints, nothing
+ /// more.
+ fn drive_color_scheme_preview(&mut self, state: &CommandPaletteState) {
+ let wanted = state
+ .action_for_entry(state.selected)
+ .and_then(|action| match action {
+ KeyAssignment::SetColorScheme(name) => Some(name.clone()),
+ _ => None,
+ });
+
+ match preview_transition(&wanted, &self.scheme_preview) {
+ PreviewStep::Nothing => return,
+ PreviewStep::Show => {
+ if !self.show_scheme_preview(wanted.as_ref().unwrap().as_deref()) {
+ // Nothing was shown, so nothing may be recorded as shown:
+ // a record naming a scheme the panes never took makes the
+ // next step onto that row a no-op and strands whatever is
+ // actually on screen. Fall back to no preview at all,
+ // which is a state the screen and the record agree on.
+ self.restore_scheme_preview();
+ self.scheme_preview = None;
+ return;
+ }
+ }
+ PreviewStep::Restore => self.restore_scheme_preview(),
+ }
+ self.scheme_preview = wanted;
+ }
+
+ /// Paint every pane of this window in `name`, or in the configuration's
+ /// own scheme when `None`. False when `name` is a scheme we do not have,
+ /// in which case nothing was touched.
+ fn show_scheme_preview(&mut self, name: Option<&str>) -> bool {
+ let palette = match name {
+ Some(name) => match self
+ .config
+ .color_schemes
+ .get(name)
+ .or_else(|| config::COLOR_SCHEMES.get(name))
+ {
+ Some(palette) => palette.clone(),
+ None => {
+ log::warn!("colour scheme {name} is not one we know; not previewing it");
+ return false;
+ }
+ },
+ // The *configuration's* scheme, not this window's: `self.config`
+ // already carries the `color_scheme` override this row exists to
+ // take off, so previewing from it would show the override the user
+ // is leaving and then jump to something they never saw on Enter.
+ None => config::configuration().resolved_palette.clone(),
+ };
+ // The interface follows too when it is set to: previewing a scheme
+ // that repaints the terminal but leaves the sidebar on the old one
+ // shows the user half of what they are choosing.
+ // Through the same overlay as the committed configuration, so the
+ // interface does not decide it is on one side while the scheme it is
+ // previewing lands on the other. (The pane palette below is still the
+ // scheme raw: previewing "what this scheme looks like" is the point,
+ // and merging the whole `colors` table is `Config::resolve`'s job.)
+ self.scheme_preview_ground =
+ crate::native_settings::scheme_background(&self.config, &palette);
+ self.refresh_chrome();
+ self.push_pane_palette(Some(palette.into()));
+ true
+ }
+
+ /// Wind the preview down on the way into executing `command`.
+ ///
+ /// Skipping the restore is only right when the command is about to install
+ /// the very scheme being shown -- then a restore in between would flash the
+ /// old colours for a frame. A click can land on a row the selection was
+ /// never on, and the scheme it names may already be the one in
+ /// `config_overrides`, which makes applying it a no-op: without this the
+ /// palette closed with the *previewed* scheme still on the panes and the
+ /// clicked one saved. Anything else -- another scheme, or a command that
+ /// has nothing to do with colours -- has to put the panes back first.
+ fn finish_scheme_preview(&mut self, command: &ExpandedCommand) {
+ if !execution_replaces_preview(&command.action, &self.scheme_preview) {
+ self.restore_scheme_preview();
+ }
+ self.scheme_preview = None;
+ self.scheme_preview_ground = None;
+ }
+
+ /// Undo a preview: the panes go back to reading the configuration.
+ fn restore_scheme_preview(&mut self) {
+ self.scheme_preview_ground = None;
+ self.refresh_chrome();
+ self.push_pane_palette(None);
+ }
+
+ /// Hand every pane of this window a terminal configuration carrying
+ /// `palette` (or none, to follow the configuration again), then retire the
+ /// quads that were built with the old colours.
+ ///
+ /// The same three loops `config_was_reloaded` uses, because an overlay is
+ /// as much a pane as the terminal under it.
+ fn push_pane_palette(&mut self, palette: Option<wezterm_term::color::ColorPalette>) {
+ let term_config = TermConfig::with_config(self.config.clone());
+ match palette {
+ // A preview, not a choice: a remote pane renders it but does not
+ // carry it to the mux server. See `TermConfig::set_preview_palette`.
+ Some(palette) => term_config.set_preview_palette(palette),
+ None => term_config.clear_client_palette(),
+ }
+ let term_config: Arc<dyn TerminalConfiguration> = Arc::new(term_config);
+
+ let mux = Mux::get();
+ if let Some(window) = mux.get_window(self.mux_window_id) {
+ for tab in window.iter() {
+ for pane in tab.iter_panes_ignoring_zoom() {
+ pane.pane.set_config(Arc::clone(&term_config));
+ }
+ }
+ }
+ for state in self.pane_state.borrow().values() {
+ if let Some(overlay) = &state.overlay {
+ overlay.pane.set_config(Arc::clone(&term_config));
+ }
+ }
+ for state in self.tab_state.borrow().values() {
+ if let Some(overlay) = &state.overlay {
+ overlay.pane.set_config(Arc::clone(&term_config));
+ }
+ }
+
+ // Colours are baked into the quad and shape cache *values* while the
+ // keys carry only this generation, so bumping it is what retires them.
+ // The UI text caches are deliberately left alone: their keys have no
+ // colours, and clearing them would re-shape the whole sidebar on every
+ // arrow key.
+ self.shape_generation += 1;
+ self.shape_cache.borrow_mut().clear();
+ self.invalidate_modal();
+ self.invalidate_window();
+ }
+
pub(crate) fn close_command_palette(&mut self) {
if self.command_palette.take().is_some() {
self.remove_command_palette_ui_items();
@@ -977,6 +1202,16 @@ impl crate::TermWindow {
}
fn remove_command_palette_ui_items(&mut self) {
+ // Every way the palette closes comes through here -- Escape, the
+ // toggle chord, Ctrl-G, a click outside, a modal taking over, losing
+ // window focus, a configuration reload -- so this is the one place a
+ // preview can be sure of being undone. The activation paths clear
+ // `scheme_preview` first, because what they are about to apply is the
+ // very thing a restore would throw away.
+ if self.scheme_preview.take().is_some() {
+ self.restore_scheme_preview();
+ }
+ debug_assert!(self.scheme_preview_ground.is_none());
self.last_ui_item = None;
self.ui_items
.retain(|item| !matches!(item.item_type, UIItemType::CommandPalette));
@@ -1443,12 +1678,23 @@ impl crate::TermWindow {
match outcome {
PaletteOutcome::Keep => {
+ // The selection has settled; show the scheme it landed on.
+ // Driven from here rather than from the paint because the
+ // preview bumps `shape_generation` and clears the shape cache,
+ // which a paint already part-way through must not have pulled
+ // out from under it. `ensure_matches` first because typing
+ // only marks the match cache stale -- the reselect to the top
+ // of the new results happens inside it.
+ let mut state = state;
+ state.ensure_matches();
+ self.drive_color_scheme_preview(&state);
self.command_palette = Some(state);
}
PaletteOutcome::Close => {
self.remove_command_palette_ui_items();
}
PaletteOutcome::Execute(cmd) => {
+ self.finish_scheme_preview(&cmd);
self.remove_command_palette_ui_items();
self.execute_palette_command(cmd);
}
@@ -1577,6 +1823,16 @@ impl crate::TermWindow {
match outcome {
PaletteOutcome::Keep => {
+ // The selection has settled; show the scheme it landed on.
+ // Driven from here rather than from the paint because the
+ // preview bumps `shape_generation` and clears the shape cache,
+ // which a paint already part-way through must not have pulled
+ // out from under it. `ensure_matches` first because typing
+ // only marks the match cache stale -- the reselect to the top
+ // of the new results happens inside it.
+ let mut state = state;
+ state.ensure_matches();
+ self.drive_color_scheme_preview(&state);
self.command_palette = Some(state);
}
PaletteOutcome::Close => {
@@ -1585,6 +1841,10 @@ impl crate::TermWindow {
context.invalidate();
}
PaletteOutcome::Execute(cmd) => {
+ // A click can land on a row the selection never reached, so
+ // this one really can be executing something other than what is
+ // on screen.
+ self.finish_scheme_preview(&cmd);
self.remove_command_palette_ui_items();
self.execute_palette_command(cmd);
context.set_cursor(Some(MouseCursor::Arrow));
@@ -1655,8 +1915,10 @@ impl crate::TermWindow {
let list_metrics = RenderMetrics::with_font_metrics(&list_font.metrics());
let search_metrics = RenderMetrics::with_font_metrics(&search_font.metrics());
- let mut palette =
- command_palette_colors(crate::native_settings::effective_appearance());
+ let mut palette = command_palette_colors(self.chrome());
+ // Last word to the user: the card tuning above overwrites slots the
+ // chrome already resolved, `ui_colors` among them.
+ crate::native_settings::apply_ui_colors(&mut palette, self.config.ui_colors.as_ref());
// The legacy config colors default to a dark-only pairing that would
// wreck light mode; honour them only when the user changed them.
let fg = self.config.command_palette_fg_color.to_linear();
@@ -2273,6 +2535,109 @@ impl crate::TermWindow {
#[cfg(test)]
mod tests {
+
+ fn named(name: &str) -> Option<Option<String>> {
+ Some(Some(name.to_string()))
+ }
+
+ /// Holding an arrow key walks the list; every step that lands on the same
+ /// scheme it is already showing has to cost nothing, or a thousand-entry
+ /// list would re-theme every pane per keypress.
+ /// A click can land on a row the keyboard selection never reached, so the
+ /// command being run is not always the one on screen. Getting this wrong
+ /// closed the palette with the *previewed* scheme on the panes and the
+ /// *clicked* one saved -- and applying the clicked one was a no-op,
+ /// because it was already the configured scheme.
+ #[test]
+ fn only_the_scheme_being_shown_may_skip_the_restore() {
+ let shown = Some(Some("Nord (base16)".to_string()));
+ assert!(execution_replaces_preview(
+ &KeyAssignment::SetColorScheme(Some("Nord (base16)".to_string())),
+ &shown
+ ));
+ assert!(
+ !execution_replaces_preview(
+ &KeyAssignment::SetColorScheme(Some("3024 Day".to_string())),
+ &shown
+ ),
+ "a different scheme has to put the panes back first"
+ );
+ assert!(
+ !execution_replaces_preview(&KeyAssignment::SetColorScheme(None), &shown),
+ "\"use the configured default\" is a different scheme too"
+ );
+ assert!(
+ !execution_replaces_preview(&KeyAssignment::ActivateCommandPalette, &shown),
+ "a command with nothing to do with colours has to restore"
+ );
+ assert!(
+ !execution_replaces_preview(
+ &KeyAssignment::SetColorScheme(Some("Nord (base16)".to_string())),
+ &None
+ ),
+ "nothing is being shown, so there is nothing to skip"
+ );
+ }
+
+ #[test]
+ fn a_selection_that_did_not_move_off_its_scheme_does_nothing() {
+ assert_eq!(
+ preview_transition(&named("Gruvbox"), &named("Gruvbox")),
+ PreviewStep::Nothing
+ );
+ assert_eq!(
+ preview_transition(&Some(None), &Some(None)),
+ PreviewStep::Nothing
+ );
+ }
+
+ /// Every other group in the palette, every keypress. Must not touch the
+ /// panes.
+ #[test]
+ fn a_selection_that_is_not_a_scheme_and_never_was_does_nothing() {
+ assert_eq!(preview_transition(&None, &None), PreviewStep::Nothing);
+ }
+
+ #[test]
+ fn moving_between_schemes_shows_the_new_one() {
+ assert_eq!(
+ preview_transition(&named("Nord"), &named("Gruvbox")),
+ PreviewStep::Show
+ );
+ }
+
+ #[test]
+ fn arriving_on_the_scheme_list_shows_the_first_one() {
+ assert_eq!(preview_transition(&named("Nord"), &None), PreviewStep::Show);
+ }
+
+ /// "Use the configured default" is a row like any other and previews like
+ /// one -- it is not the same as leaving the list.
+ #[test]
+ fn the_configured_default_row_is_a_preview_of_its_own() {
+ assert_eq!(
+ preview_transition(&Some(None), &named("Nord")),
+ PreviewStep::Show
+ );
+ assert_eq!(
+ preview_transition(&named("Nord"), &Some(None)),
+ PreviewStep::Show
+ );
+ }
+
+ /// Backing out of the scheme group, or typing a query that selects
+ /// something else: the terminal goes back to the configured colours.
+ #[test]
+ fn leaving_the_scheme_list_puts_the_configuration_back() {
+ assert_eq!(
+ preview_transition(&None, &named("Gruvbox")),
+ PreviewStep::Restore
+ );
+ assert_eq!(
+ preview_transition(&None, &Some(None)),
+ PreviewStep::Restore
+ );
+ }
use super::*;
fn leaf(brief: &str) -> PaletteItem {
diff --git a/wezterm-gui/src/termwindow/ui/context_menu.rs b/wezterm-gui/src/termwindow/ui/context_menu.rs
index 7184b5be..71af7c59 100644
--- a/wezterm-gui/src/termwindow/ui/context_menu.rs
+++ b/wezterm-gui/src/termwindow/ui/context_menu.rs
@@ -5,8 +5,8 @@ use crate::ui::UiPalette;
use crate::utilsprites::RenderMetrics;
use ::window::color::LinearRgba;
use ::window::{
- Appearance, ContextMenuAction, ContextMenuIcon, ContextMenuItem, MouseCursor, MouseEvent,
- MouseEventKind, MousePress, WindowOps,
+ ContextMenuAction, ContextMenuIcon, ContextMenuItem, MouseCursor, MouseEvent, MouseEventKind,
+ MousePress, WindowOps,
};
use anyhow::Context;
use mux::pane::Pane;
@@ -574,7 +574,10 @@ impl crate::TermWindow {
let ui_metrics = RenderMetrics::with_font_metrics(&ui_font.metrics());
let row_height = (ui_metrics.cell_size.height as usize + self.ui_px(MENU_ROW_EXTRA_HEIGHT))
.max(self.ui_px(44));
- let palette = context_menu_palette(crate::native_settings::effective_appearance());
+ let mut palette = context_menu_palette(self.chrome());
+ // Last word to the user: the menu tuning above overwrites slots the
+ // chrome already resolved, `ui_colors` among them.
+ crate::native_settings::apply_ui_colors(&mut palette, self.config.ui_colors.as_ref());
let gl_state = self.render_state.as_ref().unwrap();
let layer = gl_state.layer_for_zindex(0).context("context menu layer")?;
@@ -1083,26 +1086,12 @@ fn paint_menu_rows(
Ok(())
}
-fn context_menu_palette(appearance: Appearance) -> UiPalette {
- let mut palette = UiPalette::for_appearance(appearance);
- match appearance {
- Appearance::Dark | Appearance::DarkHighContrast => {
- palette.control_bg = LinearRgba::with_srgba(30, 30, 32, 255);
- palette.control_hover_bg = LinearRgba::with_srgba(255, 255, 255, 255).mul_alpha(0.08);
- palette.control_border = LinearRgba::with_srgba(118, 118, 128, 255).mul_alpha(0.34);
- palette.separator = LinearRgba::with_srgba(84, 84, 88, 255).mul_alpha(0.36);
- palette.text = LinearRgba::with_srgba(242, 242, 247, 255);
- palette.secondary_text = LinearRgba::with_srgba(226, 226, 232, 255);
- palette.muted_text = LinearRgba::with_srgba(150, 150, 156, 255);
- }
- Appearance::Light | Appearance::LightHighContrast => {
- palette.control_bg = LinearRgba::with_srgba(246, 246, 248, 255);
- palette.control_hover_bg = LinearRgba::with_srgba(60, 60, 67, 255).mul_alpha(0.08);
- palette.control_border = LinearRgba::with_srgba(60, 60, 67, 255).mul_alpha(0.22);
- palette.separator = LinearRgba::with_srgba(60, 60, 67, 255).mul_alpha(0.20);
- }
- }
- palette
+/// The chrome's colours, tuned for a floating menu card.
+///
+/// Takes the window's palette rather than an appearance so the caller pays for
+/// resolving it once per configuration instead of once per menu paint.
+fn context_menu_palette(palette: UiPalette) -> UiPalette {
+ palette.as_menu_card()
}
fn menu_icon(icon: &ContextMenuIcon) -> Option<SvgIcon> {
diff --git a/wezterm-gui/src/termwindow/ui/right_sidebar.rs b/wezterm-gui/src/termwindow/ui/right_sidebar.rs
index 0f987072..098e0259 100644
--- a/wezterm-gui/src/termwindow/ui/right_sidebar.rs
+++ b/wezterm-gui/src/termwindow/ui/right_sidebar.rs
@@ -6208,7 +6208,7 @@ impl crate::TermWindow {
None => return Ok(()),
};
let rect = self.right_sidebar_tree_rect(total_rect);
- let chrome = UiPalette::for_appearance(crate::native_settings::effective_appearance());
+ let chrome = self.chrome();
let foreground = chrome.text;
let muted_fg = chrome.secondary_text;
let sidebar_bg = chrome.workspace_sidebar_bg;
diff --git a/wezterm-gui/src/termwindow/ui/sidebar.rs b/wezterm-gui/src/termwindow/ui/sidebar.rs
index 133578e8..2f71720e 100644
--- a/wezterm-gui/src/termwindow/ui/sidebar.rs
+++ b/wezterm-gui/src/termwindow/ui/sidebar.rs
@@ -1095,7 +1095,7 @@ impl crate::TermWindow {
None => return Ok(()),
};
- let chrome = UiPalette::for_appearance(crate::native_settings::effective_appearance());
+ let chrome = self.chrome();
let foreground = chrome.text;
let sidebar_bg = chrome.workspace_sidebar_bg;
let sidebar_separator = chrome.separator;