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.

feat(gui): right-click paste, rounded selection, copy light

RoversX79a8bed27c60
diff --git a/docs/thinkterm/recording-overlay.md b/docs/thinkterm/recording-overlay.md
index 882c779e..066c474b 100644
--- a/docs/thinkterm/recording-overlay.md
+++ b/docs/thinkterm/recording-overlay.md
@@ -2,7 +2,9 @@
Right-click a terminal and choose **Edit Recording Masks…**. If a terminal
application captures the mouse, hold the mouse-reporting bypass modifier
-(Shift by default) while right-clicking.
+(Shift by default) while right-clicking. If **Settings → Terminal → Right
+click** is set to anything but Menu, hold Control (Ctrl on Windows and Linux)
+as well to get the menu.
- The floating toolbar starts near the bottom of the window. Drag its top handle
or the gaps between buttons to move it.
diff --git a/thinkterm-i18n/i18n/de-DE.ftl b/thinkterm-i18n/i18n/de-DE.ftl
index e2e67eab..f56982e2 100644
--- a/thinkterm-i18n/i18n/de-DE.ftl
+++ b/thinkterm-i18n/i18n/de-DE.ftl
@@ -167,6 +167,13 @@ settings-local-sessions-via-mux-description-windows = Lokale Terminals laufen in
settings-terminal-heading = Terminal-Konfiguration
settings-terminal-font-heading = Schrift
settings-terminal-display-heading = Anzeige
+settings-terminal-mouse-heading = Maus und Zwischenablage
+settings-selection-style = Auswahlform
+settings-selection-style-description = Die Form der Auswahl: Abgerundet verbindet die gewählten Zeilen zu einer Fläche, Eckig gibt jeder Zeile einen eigenen Block.
+settings-selection-style-rounded = Abgerundet
+settings-selection-style-square = Eckig
+settings-copy-on-select = Beim Auswählen kopieren
+settings-copy-on-select-description = Ausgewählter Text kommt sofort in die Zwischenablage. Aus: Auswählen wählt nur aus, kopiert wird mit dem Kopierkürzel oder per Rechtsklick.
settings-terminal-quote-heading = Zitate
settings-terminal-font-size-from-lua = Hier gespeichert und sofort auf offene Terminals angewendet. thinkterm.lua gibt { $value } an.
settings-quotes-file = Zitatdatei
@@ -193,6 +200,17 @@ 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-right-click = Rechtsklick
+settings-right-click-description = Was ein Rechtsklick im Terminal tut. „Kopieren oder einfügen“ kopiert die Auswahl, wenn es eine gibt, und fügt sonst ein. Mit gedrückter Strg-Taste öffnet ein Rechtsklick immer das Menü. In Programmen, die die Maus selbst nutzen, etwa vim oder tmux, zusätzlich die Umschalttaste halten.
+settings-right-click-description-macos = Was ein Rechtsklick im Terminal tut. „Kopieren oder einfügen“ kopiert die Auswahl, wenn es eine gibt, und fügt sonst ein. Mit gedrückter Control-Taste öffnet ein Rechtsklick immer das Menü. In Programmen, die die Maus selbst nutzen, etwa vim oder tmux, zusätzlich die Umschalttaste halten.
+settings-right-click-menu = Menü
+settings-right-click-paste = Einfügen
+settings-right-click-copy-or-paste = Kopieren oder einfügen
+settings-copy-effect = Effekt beim Kopieren und Einfügen
+settings-copy-effect-description = Beim Kopieren oder Einfügen laufen zwei Lichter oben und unten am Text entlang, von dem Ende, an dem die Auswahl begonnen wurde, bis zum anderen. So sieht man, was kopiert wurde und wo es gelandet ist.
+settings-copy-effect-off = Aus
+settings-copy-effect-white = Weiß
+settings-copy-effect-color = Farbig
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
@@ -694,6 +712,8 @@ settings-status-download-error = Der Download-Ordner konnte nicht gespeichert we
settings-status-window-restore-on = Wiederherstellen des Fensterrahmens für neue macOS-Fenster aktiviert.
settings-status-notification-sounds-on = Mitteilungstöne aktiviert.
settings-status-notification-sounds-off = Mitteilungstöne ausgeschaltet.
+settings-status-copy-on-select-on = Auswählen kopiert den Text.
+settings-status-copy-on-select-off = Auswählen kopiert den Text nicht mehr.
settings-status-notification-sounds-error = Die Einstellung für Mitteilungstöne konnte nicht gespeichert werden: { $error }
settings-status-remote-update-keep-sessions-on = Remote-Updates übergeben Sitzungen an die neue Version.
settings-status-remote-update-keep-sessions-off = Remote-Updates fragen nach, bevor der Server gestoppt wird.
diff --git a/thinkterm-i18n/i18n/en-US.ftl b/thinkterm-i18n/i18n/en-US.ftl
index 6e84f60c..f328283c 100644
--- a/thinkterm-i18n/i18n/en-US.ftl
+++ b/thinkterm-i18n/i18n/en-US.ftl
@@ -167,6 +167,13 @@ settings-local-sessions-via-mux-description-windows = Local terminals run in a m
settings-terminal-heading = Terminal configuration
settings-terminal-font-heading = Font
settings-terminal-display-heading = Display
+settings-terminal-mouse-heading = Mouse and clipboard
+settings-selection-style = Selection style
+settings-selection-style-description = The shape of the selection: rounded joins the selected rows into one shape, square gives each row its own block.
+settings-selection-style-rounded = Rounded
+settings-selection-style-square = Square
+settings-copy-on-select = Copy on select
+settings-copy-on-select-description = Selected text goes straight to the clipboard. Off, selecting only selects: copy with the copy shortcut or a right click.
settings-terminal-quote-heading = Quotes
settings-terminal-font-size-from-lua = Saved here and applied to open terminals at once. thinkterm.lua says { $value }.
settings-quotes-file = Quotes file
@@ -193,6 +200,17 @@ 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-right-click = Right click
+settings-right-click-description = What a right click in the terminal does. Copy or paste copies the selection when there is one and pastes otherwise. Hold Ctrl while right-clicking to get the menu whichever you pick. In programs that use the mouse themselves, such as vim or tmux, hold Shift as well.
+settings-right-click-description-macos = What a right click in the terminal does. Copy or paste copies the selection when there is one and pastes otherwise. Hold Control while right-clicking to get the menu whichever you pick. In programs that use the mouse themselves, such as vim or tmux, hold Shift as well.
+settings-right-click-menu = Menu
+settings-right-click-paste = Paste
+settings-right-click-copy-or-paste = Copy or paste
+settings-copy-effect = Copy and paste effect
+settings-copy-effect-description = Two lights run along the top and the bottom of the text you copy or paste, from the end you started selecting at to the other, so you can see what was copied and where it went.
+settings-copy-effect-off = Off
+settings-copy-effect-white = White
+settings-copy-effect-color = Color
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
@@ -694,6 +712,8 @@ settings-status-download-error = Unable to save the download folder: { $error }
settings-status-window-restore-on = Main window frame restore enabled for new macOS windows.
settings-status-notification-sounds-on = Notification sounds enabled.
settings-status-notification-sounds-off = Notification sounds turned off.
+settings-status-copy-on-select-on = Selecting text copies it.
+settings-status-copy-on-select-off = Selecting text no longer copies it.
settings-status-notification-sounds-error = Could not save the notification sound setting: { $error }
settings-status-remote-update-keep-sessions-on = Remote updates will hand sessions over to the new version.
settings-status-remote-update-keep-sessions-off = Remote updates will ask before stopping the server.
diff --git a/thinkterm-i18n/i18n/fr-FR.ftl b/thinkterm-i18n/i18n/fr-FR.ftl
index eb2329b3..c3ca7100 100644
--- a/thinkterm-i18n/i18n/fr-FR.ftl
+++ b/thinkterm-i18n/i18n/fr-FR.ftl
@@ -167,6 +167,13 @@ settings-local-sessions-via-mux-description-windows = Les terminaux locaux tourn
settings-terminal-heading = Configuration du terminal
settings-terminal-font-heading = Police
settings-terminal-display-heading = Affichage
+settings-terminal-mouse-heading = Souris et presse-papiers
+settings-selection-style = Forme de la sélection
+settings-selection-style-description = La forme de la sélection : arrondie, les lignes choisies forment une seule forme ; carrée, chaque ligne a son propre bloc.
+settings-selection-style-rounded = Arrondie
+settings-selection-style-square = Carrée
+settings-copy-on-select = Copier à la sélection
+settings-copy-on-select-description = Le texte sélectionné va directement dans le presse-papiers. Désactivé, sélectionner ne fait que sélectionner : copiez avec le raccourci de copie ou un clic droit.
settings-terminal-quote-heading = Citations
settings-terminal-font-size-from-lua = Enregistrée ici et appliquée aussitôt aux terminaux ouverts. thinkterm.lua indique { $value }.
settings-quotes-file = Fichier des citations
@@ -193,6 +200,17 @@ 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-right-click = Clic droit
+settings-right-click-description = Ce que fait un clic droit dans le terminal. « Copier ou coller » copie la sélection s’il y en a une et colle sinon. Avec Ctrl enfoncé, un clic droit ouvre toujours le menu. Dans les programmes qui utilisent eux-mêmes la souris, comme vim ou tmux, maintenez aussi Maj.
+settings-right-click-description-macos = Ce que fait un clic droit dans le terminal. « Copier ou coller » copie la sélection s’il y en a une et colle sinon. Avec Contrôle enfoncé, un clic droit ouvre toujours le menu. Dans les programmes qui utilisent eux-mêmes la souris, comme vim ou tmux, maintenez aussi Maj.
+settings-right-click-menu = Menu
+settings-right-click-paste = Coller
+settings-right-click-copy-or-paste = Copier ou coller
+settings-copy-effect = Effet de copie et de collage
+settings-copy-effect-description = Quand vous copiez ou collez, deux lumières longent le haut et le bas du texte, du bout où la sélection a commencé jusqu’à l’autre : on voit ce qui a été copié et où il est arrivé.
+settings-copy-effect-off = Désactivé
+settings-copy-effect-white = Blanc
+settings-copy-effect-color = Couleur
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é
@@ -694,6 +712,8 @@ settings-status-download-error = Impossible d’enregistrer le dossier de télé
settings-status-window-restore-on = Restauration de la taille et position activée pour les nouvelles fenêtres macOS.
settings-status-notification-sounds-on = Sons de notification activés.
settings-status-notification-sounds-off = Sons de notification désactivés.
+settings-status-copy-on-select-on = Sélectionner du texte le copie.
+settings-status-copy-on-select-off = Sélectionner du texte ne le copie plus.
settings-status-notification-sounds-error = Impossible d’enregistrer le réglage des sons de notification : { $error }
settings-status-remote-update-keep-sessions-on = Les mises à jour distantes transmettront les sessions à la nouvelle version.
settings-status-remote-update-keep-sessions-off = Les mises à jour distantes demanderont avant d’arrêter le serveur.
diff --git a/thinkterm-i18n/i18n/ja-JP.ftl b/thinkterm-i18n/i18n/ja-JP.ftl
index a2d48821..044625fb 100644
--- a/thinkterm-i18n/i18n/ja-JP.ftl
+++ b/thinkterm-i18n/i18n/ja-JP.ftl
@@ -164,6 +164,13 @@ settings-local-sessions-via-mux-description-windows = ローカル端末はこ
settings-terminal-heading = ターミナル設定
settings-terminal-font-heading = フォント
settings-terminal-display-heading = 表示
+settings-terminal-mouse-heading = マウスとクリップボード
+settings-selection-style = 選択範囲の形
+settings-selection-style-description = 選択範囲の形です。角丸は選んだ行をひとつの形につなげ、四角は行ごとに四角形を描きます。
+settings-selection-style-rounded = 角丸
+settings-selection-style-square = 四角
+settings-copy-on-select = 選択時にコピー
+settings-copy-on-select-description = 選択した文字をそのままクリップボードに入れます。オフにすると選択するだけになり、コピーはコピーのショートカットか右クリックで行います。
settings-terminal-quote-heading = 引用文
settings-terminal-font-size-from-lua = ここで保存し、開いているターミナルにすぐ適用します。thinkterm.lua の値は { $value } です。
settings-quotes-file = 引用文ファイル
@@ -190,6 +197,17 @@ settings-scroll-mode = スクロール方式
settings-scroll-mode-description = スムーズはトラックパッド・指・ホイールの移動量どおりにテキストを動かし、ステップは 1 行ずつ移動します。
settings-scroll-mode-stepped = ステップ
settings-scroll-mode-smooth = スムーズ
+settings-right-click = 右クリック
+settings-right-click-description = ターミナルで右クリックしたときの動作です。「コピーまたは貼り付け」は選択があればコピーし、なければ貼り付けます。どれを選んでも、Ctrl を押しながら右クリックするとメニューが開きます。vim や tmux のようにマウスを自分で使うプログラムでは、Shift も一緒に押してください。
+settings-right-click-description-macos = ターミナルで右クリックしたときの動作です。「コピーまたは貼り付け」は選択があればコピーし、なければ貼り付けます。どれを選んでも、Control を押しながら右クリックするとメニューが開きます。vim や tmux のようにマウスを自分で使うプログラムでは、Shift も一緒に押してください。
+settings-right-click-menu = メニュー
+settings-right-click-paste = 貼り付け
+settings-right-click-copy-or-paste = コピーまたは貼り付け
+settings-copy-effect = コピーと貼り付けの効果
+settings-copy-effect-description = コピーや貼り付けのとき、二筋の光が文字の上下を、選択を始めた側から反対側まで走ります。何をコピーしてどこに貼ったかがわかります。
+settings-copy-effect-off = オフ
+settings-copy-effect-white = 白
+settings-copy-effect-color = カラー
settings-text-contrast = 文字の最低コントラスト
settings-text-contrast-description = 文字と実際の背景とのコントラスト比を下回らないようにし、別の背景を前提に選ばれた前景色を塗り直します。自前で背景を描くプログラムには手を出しません。上げると、意図的に淡くした部分の階調も失われます。
settings-text-contrast-off = オフ
@@ -685,6 +703,8 @@ settings-status-download-error = ダウンロードフォルダーを保存で
settings-status-window-restore-on = 新しい macOS ウィンドウで位置とサイズの復元を有効にしました。
settings-status-notification-sounds-on = 通知音を有効にしました。
settings-status-notification-sounds-off = 通知音を無効にしました。
+settings-status-copy-on-select-on = 選択すると自動でコピーされます。
+settings-status-copy-on-select-off = 選択しても自動でコピーされなくなりました。
settings-status-notification-sounds-error = 通知音の設定を保存できませんでした: { $error }
settings-status-remote-update-keep-sessions-on = リモート更新時にセッションを新しいバージョンへ引き継ぎます。
settings-status-remote-update-keep-sessions-off = リモート更新時はサーバーを停止する前に確認します。
diff --git a/thinkterm-i18n/i18n/zh-CN.ftl b/thinkterm-i18n/i18n/zh-CN.ftl
index a0b386c9..d32622b9 100644
--- a/thinkterm-i18n/i18n/zh-CN.ftl
+++ b/thinkterm-i18n/i18n/zh-CN.ftl
@@ -164,6 +164,13 @@ settings-local-sessions-via-mux-description-windows = 本地终端跑在本机
settings-terminal-heading = 终端配置
settings-terminal-font-heading = 字体
settings-terminal-display-heading = 显示
+settings-terminal-mouse-heading = 鼠标与剪贴板
+settings-selection-style = 选中样式
+settings-selection-style-description = 选中文字时高亮的形状:圆角会把选中的几行连成一整块,直角是每行一个方块。
+settings-selection-style-rounded = 圆角
+settings-selection-style-square = 直角
+settings-copy-on-select = 选中时自动复制
+settings-copy-on-select-description = 选中的文字直接放进剪贴板。关掉后,选中只是选中,要复制就用复制快捷键或右键。
settings-terminal-quote-heading = 语录
settings-terminal-font-size-from-lua = 在这里保存,立即应用到已打开的终端。thinkterm.lua 中为 { $value }。
settings-quotes-file = 语录文件
@@ -190,6 +197,17 @@ settings-scroll-mode = 滚动方式
settings-scroll-mode-description = 平滑:文本按触控板、手指或滚轮的实际位移移动;逐行:每次跳一整行。
settings-scroll-mode-stepped = 逐行
settings-scroll-mode-smooth = 平滑
+settings-right-click = 右键
+settings-right-click-description = 在终端里点右键做什么。“复制或粘贴”:有选中时复制,没有时粘贴。不管选哪种,按住 Ctrl 再右键都会弹出菜单。在自己用鼠标的程序里(比如 vim、tmux),还要同时按住 Shift。
+settings-right-click-description-macos = 在终端里点右键做什么。“复制或粘贴”:有选中时复制,没有时粘贴。不管选哪种,按住 Control 再右键都会弹出菜单。在自己用鼠标的程序里(比如 vim、tmux),还要同时按住 Shift。
+settings-right-click-menu = 弹出菜单
+settings-right-click-paste = 粘贴
+settings-right-click-copy-or-paste = 复制或粘贴
+settings-copy-effect = 复制粘贴效果
+settings-copy-effect-description = 复制或粘贴时,两道光沿着那段文字的上下两边,从你开始选的那一头跑到另一头,看得出复制了什么、粘到了哪里。
+settings-copy-effect-off = 关
+settings-copy-effect-white = 白光
+settings-copy-effect-color = 彩光
settings-text-contrast = 最低文字对比度
settings-text-contrast-description = 按文字与其所在背景的对比度兜底,重画那些程序按别的背景挑好的前景色。自己画背景的程序不受影响。调高也会抹掉程序故意画淡的层次。
settings-text-contrast-off = 关
@@ -685,6 +703,8 @@ settings-status-download-error = 无法保存下载文件夹:{ $error }
settings-status-window-restore-on = 已为新的 macOS 窗口启用主窗口位置与大小恢复。
settings-status-notification-sounds-on = 已开启提示音。
settings-status-notification-sounds-off = 已关闭提示音。
+settings-status-copy-on-select-on = 选中文字会自动复制。
+settings-status-copy-on-select-off = 选中文字不再自动复制。
settings-status-notification-sounds-error = 无法保存提示音设置:{ $error }
settings-status-remote-update-keep-sessions-on = 已开启:更新远端时会把会话交给新版本。
settings-status-remote-update-keep-sessions-off = 已关闭:更新远端时会先询问是否停止 server。
diff --git a/wezterm-gui/src/native_settings.rs b/wezterm-gui/src/native_settings.rs
index 911a7704..2eb2b830 100644
--- a/wezterm-gui/src/native_settings.rs
+++ b/wezterm-gui/src/native_settings.rs
@@ -249,6 +249,66 @@ impl NativeScrollMode {
pub(crate) const ALL: [Self; 2] = [Self::Smooth, Self::Stepped];
}
+/// How the selection is drawn: one shape with rounded corners, or a plain
+/// block per row as it always was.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub(crate) enum NativeSelectionStyle {
+ Rounded,
+ Square,
+}
+
+impl Default for NativeSelectionStyle {
+ fn default() -> Self {
+ Self::Rounded
+ }
+}
+
+impl NativeSelectionStyle {
+ pub(crate) const ALL: [Self; 2] = [Self::Rounded, Self::Square];
+}
+
+/// What a right click in a terminal does when no mouse binding claims it.
+/// Whichever is picked, Control with the right click opens the menu.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub(crate) enum NativeRightClick {
+ Menu,
+ Paste,
+ /// Copy the selection when there is one (and let it go), else paste.
+ CopyOrPaste,
+}
+
+impl Default for NativeRightClick {
+ fn default() -> Self {
+ Self::Menu
+ }
+}
+
+impl NativeRightClick {
+ pub(crate) const ALL: [Self; 3] = [Self::Menu, Self::Paste, Self::CopyOrPaste];
+}
+
+/// The light that runs round copied or pasted text. Off unless chosen:
+/// what a new version changes for everyone is only the rounded selection.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub(crate) enum NativeCopyEffect {
+ Off,
+ White,
+ Color,
+}
+
+impl Default for NativeCopyEffect {
+ fn default() -> Self {
+ Self::Off
+ }
+}
+
+impl NativeCopyEffect {
+ pub(crate) const ALL: [Self; 3] = [Self::Off, Self::White, Self::Color];
+}
+
/// 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
@@ -315,6 +375,20 @@ where
})
}
+/// The same for any of the plain choices: one this build cannot read (a
+/// newer build's, or a typo) reads as its default, and the file is kept.
+fn choice_or_default<'de, D, T>(deserializer: D) -> Result<T, D::Error>
+where
+ D: serde::Deserializer<'de>,
+ T: serde::de::DeserializeOwned + Default,
+{
+ let raw = serde_json::Value::deserialize(deserializer)?;
+ Ok(T::deserialize(&raw).unwrap_or_else(|_| {
+ log::warn!("unknown choice {raw} in the settings; using the default");
+ T::default()
+ }))
+}
+
impl Default for NativeBottomQuoteMode {
fn default() -> Self {
Self::Timed
@@ -520,6 +594,16 @@ pub(crate) struct NativeTerminalSettings {
pub(crate) font_family: Option<String>,
pub(crate) remote_pane_resize_mode: NativeRemotePaneResizeMode,
pub(crate) scroll_mode: NativeScrollMode,
+ #[serde(deserialize_with = "choice_or_default")]
+ pub(crate) selection_style: NativeSelectionStyle,
+ /// A selection let go of is copied to the clipboard, as WezTerm and
+ /// iTerm2 do; off, it only selects, as in Apple's Terminal.
+ #[serde(default = "default_true")]
+ pub(crate) copy_on_select: bool,
+ #[serde(deserialize_with = "choice_or_default")]
+ pub(crate) right_click: NativeRightClick,
+ #[serde(deserialize_with = "choice_or_default")]
+ pub(crate) copy_effect: NativeCopyEffect,
/// See [`NativeTextContrast`]. `Off` defers to the Lua
/// `text_min_contrast_ratio`, which is itself off unless set.
#[serde(deserialize_with = "text_contrast_or_default")]
@@ -541,6 +625,10 @@ impl Default for NativeTerminalSettings {
font_family: None,
remote_pane_resize_mode: NativeRemotePaneResizeMode::default(),
scroll_mode: NativeScrollMode::default(),
+ selection_style: NativeSelectionStyle::default(),
+ copy_on_select: true,
+ right_click: NativeRightClick::default(),
+ copy_effect: NativeCopyEffect::default(),
text_contrast: NativeTextContrast::default(),
bottom_quote_enabled: false,
bottom_quote_mode: NativeBottomQuoteMode::default(),
@@ -561,6 +649,26 @@ pub(crate) fn scroll_mode() -> NativeScrollMode {
load_shared().terminal.scroll_mode
}
+/// Read whenever a selection is let go of, through the shared handle.
+pub(crate) fn copy_on_select() -> bool {
+ load_shared().terminal.copy_on_select
+}
+
+/// Read for every pane drawn, through the shared handle.
+pub(crate) fn selection_rounded() -> bool {
+ load_shared().terminal.selection_style == NativeSelectionStyle::Rounded
+}
+
+/// Read on every right click, through the shared handle.
+pub(crate) fn right_click() -> NativeRightClick {
+ load_shared().terminal.right_click
+}
+
+/// Read on every copy and paste, through the shared handle.
+pub(crate) fn copy_effect() -> NativeCopyEffect {
+ load_shared().terminal.copy_effect
+}
+
/// 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.
@@ -2845,6 +2953,45 @@ mod tests {
assert_eq!(settings.onboarding.seen_version, 7);
}
+ /// The mouse and clipboard choices too: a typo, or a newer build's
+ /// value, costs that one field and nothing else; a field this build no
+ /// longer has is passed over.
+ #[test]
+ fn unknown_mouse_and_clipboard_choices_do_not_take_the_rest_with_them() {
+ let json = r#"{
+ "version": 1,
+ "terminal": {
+ "selection_style": "pill",
+ "right_click": "copy-or-paste",
+ "copy_effect": "colour",
+ "copy_effect_path": "around",
+ "scroll_mode": "stepped"
+ },
+ "localization": { "language": "ja-JP" }
+ }"#;
+ let settings: ThinkTermNativeSettings =
+ serde_json::from_str(json).expect("the file has to survive");
+ assert_eq!(settings.terminal.selection_style, NativeSelectionStyle::default());
+ assert_eq!(settings.terminal.right_click, NativeRightClick::default());
+ assert_eq!(settings.terminal.copy_effect, NativeCopyEffect::default());
+ assert_eq!(settings.terminal.scroll_mode, NativeScrollMode::Stepped);
+ assert_eq!(settings.localization.language.as_deref(), Some("ja-JP"));
+
+ // Selecting copies unless turned off.
+ assert!(settings.terminal.copy_on_select);
+
+ // The ones this build knows still read as written.
+ let json = r#"{ "version": 1, "terminal": {
+ "selection_style": "square", "copy_on_select": false, "right_click": "copy_or_paste",
+ "copy_effect": "color"
+ } }"#;
+ let settings: ThinkTermNativeSettings = serde_json::from_str(json).unwrap();
+ assert!(!settings.terminal.copy_on_select);
+ assert_eq!(settings.terminal.selection_style, NativeSelectionStyle::Square);
+ assert_eq!(settings.terminal.right_click, NativeRightClick::CopyOrPaste);
+ assert_eq!(settings.terminal.copy_effect, NativeCopyEffect::Color);
+ }
+
/// The four this build does know still round-trip.
#[test]
fn every_theme_mode_round_trips_through_the_settings_file() {
diff --git a/wezterm-gui/src/overlay/copy.rs b/wezterm-gui/src/overlay/copy.rs
index e74f338c..1d0b84cc 100644
--- a/wezterm-gui/src/overlay/copy.rs
+++ b/wezterm-gui/src/overlay/copy.rs
@@ -517,6 +517,8 @@ impl CopyRenderable {
let mut selection = term_window.selection(pane_id);
selection.origin = Some(start);
selection.range = Some(range);
+ // Its range runs from the anchor to the cursor.
+ selection.backwards = false;
selection.rectangular = mode == SelectionMode::Block;
window.invalidate();
})));
diff --git a/wezterm-gui/src/overlay/quickselect.rs b/wezterm-gui/src/overlay/quickselect.rs
index 0b1de1ba..cdc70c7f 100644
--- a/wezterm-gui/src/overlay/quickselect.rs
+++ b/wezterm-gui/src/overlay/quickselect.rs
@@ -941,6 +941,7 @@ impl QuickSelectRenderable {
let mut selection = term_window.selection(pane_id);
let start = SelectionCoordinate::x_y(result.start_x, result.start_y);
selection.origin = Some(start);
+ selection.backwards = false;
selection.range = Some(SelectionRange {
start,
// inclusive range for selection, but the result
@@ -958,7 +959,10 @@ impl QuickSelectRenderable {
let text = term_window.selection_text(&pane);
if !text.is_empty() {
if paste {
- let _ = pane.send_paste(&text);
+ let cursor = pane.get_cursor_position();
+ if pane.send_paste(&text).is_ok() {
+ term_window.light_up_paste(&pane, &text, cursor);
+ }
}
if let Some(action) = action {
if !paste || !skip_action_on_paste {
@@ -969,6 +973,7 @@ impl QuickSelectRenderable {
ClipboardCopyDestination::ClipboardAndPrimarySelection,
text,
);
+ term_window.light_up_selection(&pane, false);
}
}
}
diff --git a/wezterm-gui/src/selection.rs b/wezterm-gui/src/selection.rs
index 53b2d62b..8235e7d4 100644
--- a/wezterm-gui/src/selection.rs
+++ b/wezterm-gui/src/selection.rs
@@ -19,6 +19,9 @@ pub struct Selection {
pub seqno: SequenceNo,
/// Whether the selection is rectangular
pub rectangular: bool,
+ /// It was dragged back from where it was begun, by word, line or zone:
+ /// those keep `range` in order, so it does not say.
+ pub backwards: bool,
}
pub use config::keyassignment::SelectionMode;
@@ -27,11 +30,13 @@ impl Selection {
pub fn clear(&mut self) {
self.range = None;
self.origin = None;
+ self.backwards = false;
}
pub fn begin(&mut self, origin: SelectionCoordinate) {
self.range = None;
self.origin = Some(origin);
+ self.backwards = false;
}
pub fn is_empty(&self) -> bool {
diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rs
index f5dee6e6..74920146 100644
--- a/wezterm-gui/src/settings_window.rs
+++ b/wezterm-gui/src/settings_window.rs
@@ -911,6 +911,16 @@ impl SettingsSection {
"Quote Interval",
"Open Quotes JSON",
"Reset Quotes JSON",
+ "Selection Style",
+ "Rounded",
+ "Copy on Select",
+ "Right Click",
+ "Mouse",
+ "Clipboard",
+ "Paste",
+ "Copy",
+ "Copy Effect",
+ "Selection",
"Terminal",
],
Self::Workspaces => &[
@@ -1075,6 +1085,17 @@ impl SettingsSection {
&& crate::i18n::tr("settings-window-opacity")
.to_lowercase()
.contains(query))
+ || (self == Self::Terminal
+ && [
+ "settings-terminal-mouse-heading",
+ "settings-selection-style",
+ "settings-copy-on-select",
+ "settings-right-click",
+ "settings-right-click-paste",
+ "settings-copy-effect",
+ ]
+ .iter()
+ .any(|id| crate::i18n::tr(id).to_lowercase().contains(query)))
}
}
@@ -1089,6 +1110,24 @@ mod settings_search_tests {
assert!(SettingsSection::General.matches_search(&localized_label));
}
+ #[test]
+ fn terminal_is_found_by_its_mouse_and_clipboard_card() {
+ for query in [
+ "right click",
+ "mouse",
+ "clipboard",
+ "paste",
+ "copy",
+ "selection style",
+ "rounded",
+ "copy on select",
+ ] {
+ assert!(SettingsSection::Terminal.matches_search(query), "{}", query);
+ }
+ let localized_label = crate::i18n::tr("settings-right-click").to_lowercase();
+ assert!(SettingsSection::Terminal.matches_search(&localized_label));
+ }
+
#[test]
fn tailscale_is_found_by_a_search_but_listed_nowhere() {
// Its settings are in Remote Hosts; a search for them leads there.
@@ -1242,6 +1281,32 @@ fn localized_scroll_mode_label(mode: crate::native_settings::NativeScrollMode) -
})
}
+fn localized_selection_style_label(style: crate::native_settings::NativeSelectionStyle) -> String {
+ use crate::native_settings::NativeSelectionStyle;
+ crate::i18n::tr(match style {
+ NativeSelectionStyle::Rounded => "settings-selection-style-rounded",
+ NativeSelectionStyle::Square => "settings-selection-style-square",
+ })
+}
+
+fn localized_right_click_label(mode: crate::native_settings::NativeRightClick) -> String {
+ use crate::native_settings::NativeRightClick;
+ crate::i18n::tr(match mode {
+ NativeRightClick::Menu => "settings-right-click-menu",
+ NativeRightClick::Paste => "settings-right-click-paste",
+ NativeRightClick::CopyOrPaste => "settings-right-click-copy-or-paste",
+ })
+}
+
+fn localized_copy_effect_label(effect: crate::native_settings::NativeCopyEffect) -> String {
+ use crate::native_settings::NativeCopyEffect;
+ crate::i18n::tr(match effect {
+ NativeCopyEffect::Off => "settings-copy-effect-off",
+ NativeCopyEffect::White => "settings-copy-effect-white",
+ NativeCopyEffect::Color => "settings-copy-effect-color",
+ })
+}
+
fn localized_text_contrast_label(mode: crate::native_settings::NativeTextContrast) -> String {
use crate::native_settings::NativeTextContrast;
crate::i18n::tr(match mode {
@@ -1538,6 +1603,10 @@ enum SettingsAction {
ToggleBottomQuote,
SetRemotePaneResizeMode(NativeRemotePaneResizeMode),
SetScrollMode(crate::native_settings::NativeScrollMode),
+ SetSelectionStyle(crate::native_settings::NativeSelectionStyle),
+ ToggleCopyOnSelect,
+ SetRightClick(crate::native_settings::NativeRightClick),
+ SetCopyEffect(crate::native_settings::NativeCopyEffect),
/// Hand the choosing to the command palette's scheme list, which already
/// has the search and the live preview a thousand entries need.
OpenColorSchemePicker,
@@ -4920,6 +4989,48 @@ impl SettingsWindow {
}
}
+ /// Save one of the mouse and clipboard choices. Merged into the freshest
+ /// settings for the reason `apply_text_contrast` gives; each is read
+ /// where it is used, so nothing needs telling.
+ fn apply_terminal_choice(
+ &mut self,
+ setting: &str,
+ value: String,
+ write: impl FnOnce(&mut crate::native_settings::NativeTerminalSettings),
+ ) {
+ let done = settings_tr(
+ "settings-status-value-now",
+ &[("setting", crate::i18n::tr(setting)), ("value", value)],
+ );
+ self.apply_terminal_change(setting, done, write);
+ }
+
+ /// `apply_terminal_choice` with the line to show once it is saved.
+ fn apply_terminal_change(
+ &mut self,
+ setting: &str,
+ done: String,
+ write: impl FnOnce(&mut crate::native_settings::NativeTerminalSettings),
+ ) {
+ self.ui.open_dropdown = None;
+ let mut merged = crate::native_settings::load();
+ write(&mut merged.terminal);
+ self.set_native_settings(merged);
+ match crate::native_settings::save(&self.native_settings) {
+ Ok(()) => {
+ self.status = done;
+ }
+ Err(err) => {
+ // Not kept: the choice shown goes back to the one in force.
+ self.set_native_settings(crate::native_settings::load());
+ self.status = settings_tr(
+ "settings-status-save-error",
+ &[("setting", crate::i18n::tr(setting)), ("error", format!("{err:#}"))],
+ );
+ }
+ }
+ }
+
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
@@ -5846,6 +5957,32 @@ impl SettingsWindow {
}
}
SettingsAction::SetScrollMode(mode) => self.apply_scroll_mode(mode),
+ SettingsAction::ToggleCopyOnSelect => {
+ let on = !self.native_settings.terminal.copy_on_select;
+ let done = crate::i18n::tr(if on {
+ "settings-status-copy-on-select-on"
+ } else {
+ "settings-status-copy-on-select-off"
+ });
+ self.apply_terminal_change("settings-copy-on-select", done, |terminal| {
+ terminal.copy_on_select = on
+ })
+ }
+ SettingsAction::SetSelectionStyle(style) => self.apply_terminal_choice(
+ "settings-selection-style",
+ localized_selection_style_label(style),
+ |terminal| terminal.selection_style = style,
+ ),
+ SettingsAction::SetRightClick(mode) => {
+ self.apply_terminal_choice("settings-right-click", localized_right_click_label(mode), |terminal| {
+ terminal.right_click = mode
+ })
+ }
+ SettingsAction::SetCopyEffect(effect) => self.apply_terminal_choice(
+ "settings-copy-effect",
+ localized_copy_effect_label(effect),
+ |terminal| terminal.copy_effect = effect,
+ ),
SettingsAction::SetWindowOpacity(opacity) => self.apply_window_opacity(opacity),
// Handled as a drag, on press and release.
SettingsAction::WindowOpacitySlider => {}
@@ -12504,6 +12641,124 @@ impl SettingsWindow {
Ok(rows.bottom)
})?;
+ let card_y = self.paint_card_heading(
+ layers,
+ x,
+ bottom,
+ max_width,
+ &crate::i18n::tr("settings-terminal-mouse-heading"),
+ )?;
+ let bottom = self.paint_card(layers, x, card_y, max_width, |this, layers, top| {
+ use crate::native_settings::{NativeCopyEffect, NativeRightClick, NativeSelectionStyle};
+ let mut rows = RowCursor::new(top, this);
+ let terminal = &this.native_settings.terminal;
+ let (style, right_click, effect) =
+ (terminal.selection_style, terminal.right_click, terminal.copy_effect);
+
+ let options: Vec<(String, SettingsAction)> = NativeSelectionStyle::ALL
+ .iter()
+ .map(|s| (localized_selection_style_label(*s), SettingsAction::SetSelectionStyle(*s)))
+ .collect();
+ let selected = NativeSelectionStyle::ALL.iter().position(|s| *s == style).unwrap_or(0);
+ let (tx, tw) = this.paint_row_tile(
+ layers,
+ row_x,
+ rows.y,
+ row_width,
+ SvgIcon::SquareRoundCorner,
+ TileColor::Indigo,
+ )?;
+ rows.add(this.paint_segmented_setting_row(
+ layers,
+ tx,
+ rows.y,
+ tw,
+ &crate::i18n::tr("settings-selection-style"),
+ &crate::i18n::tr("settings-selection-style-description"),
+ &options,
+ selected,
+ rows.rule(),
+ )?);
+
+ let copy_on_select = this.native_settings.terminal.copy_on_select;
+ let (tx, tw) = this.paint_row_tile(
+ layers,
+ row_x,
+ rows.y,
+ row_width,
+ SvgIcon::ClipboardCopy,
+ TileColor::Teal,
+ )?;
+ rows.add(this.paint_toggle_setting_row(
+ layers,
+ tx,
+ rows.y,
+ tw,
+ &crate::i18n::tr("settings-copy-on-select"),
+ &crate::i18n::tr("settings-copy-on-select-description"),
+ copy_on_select,
+ SettingsAction::ToggleCopyOnSelect,
+ rows.rule(),
+ )?);
+
+ let options: Vec<(String, SettingsAction)> = NativeRightClick::ALL
+ .iter()
+ .map(|mode| (localized_right_click_label(*mode), SettingsAction::SetRightClick(*mode)))
+ .collect();
+ let selected = NativeRightClick::ALL.iter().position(|mode| *mode == right_click).unwrap_or(0);
+ let (tx, tw) = this.paint_row_tile(
+ layers,
+ row_x,
+ rows.y,
+ row_width,
+ SvgIcon::ClipboardPaste,
+ TileColor::Teal,
+ )?;
+ rows.add(this.paint_segmented_setting_row(
+ layers,
+ tx,
+ rows.y,
+ tw,
+ &crate::i18n::tr("settings-right-click"),
+ // The key is Control on a Mac, Ctrl (or Strg) elsewhere.
+ &crate::i18n::tr(if cfg!(target_os = "macos") {
+ "settings-right-click-description-macos"
+ } else {
+ "settings-right-click-description"
+ }),
+ &options,
+ selected,
+ rows.rule(),
+ )?);
+
+ let options: Vec<(String, SettingsAction)> = NativeCopyEffect::ALL
+ .iter()
+ .map(|effect| (localized_copy_effect_label(*effect), SettingsAction::SetCopyEffect(*effect)))
+ .collect();
+ let selected = NativeCopyEffect::ALL.iter().position(|e| *e == effect).unwrap_or(0);
+ let (tx, tw) = this.paint_row_tile(
+ layers,
+ row_x,
+ rows.y,
+ row_width,
+ SvgIcon::Copy,
+ TileColor::Blue,
+ )?;
+ rows.add(this.paint_segmented_setting_row(
+ layers,
+ tx,
+ rows.y,
+ tw,
+ &crate::i18n::tr("settings-copy-effect"),
+ &crate::i18n::tr("settings-copy-effect-description"),
+ &options,
+ selected,
+ rows.rule(),
+ )?);
+
+ Ok(rows.bottom)
+ })?;
+
let quote_font_size_label = self.bottom_quote_font_size_label();
let quote_interval_label = self.bottom_quote_interval_label();
let card_y = self.paint_card_heading(
diff --git a/wezterm-gui/src/termwindow/clipboard.rs b/wezterm-gui/src/termwindow/clipboard.rs
index 2b44cc13..2b119bdc 100644
--- a/wezterm-gui/src/termwindow/clipboard.rs
+++ b/wezterm-gui/src/termwindow/clipboard.rs
@@ -93,7 +93,7 @@ impl TermWindow {
if text.is_empty() {
return;
}
- if let Some(pane) = self
+ let pane = self
.pane_state(pane_id)
.overlay
.as_ref()
@@ -101,9 +101,28 @@ impl TermWindow {
.or_else(|| {
let mux = Mux::get();
mux.get_pane(pane_id)
- })
- {
- pane.send_paste(text).ok();
+ });
+ if let Some(pane) = pane {
+ // Where the paste goes in, read before it does.
+ let cursor = pane.get_cursor_position();
+ if pane.send_paste(text).is_ok() {
+ self.light_up_terminal_paste(&pane, text, cursor);
+ }
+ }
+ }
+
+ /// Light up `text`, pasted into `pane` at `cursor`, if it went to the
+ /// terminal: an overlay over it takes a paste in itself (copy mode's
+ /// search line) or drops it (quick select), and the terminal's own text
+ /// there is not the paste.
+ pub(crate) fn light_up_terminal_paste(
+ &mut self,
+ pane: &Arc<dyn Pane>,
+ text: &str,
+ cursor: mux::renderable::StableCursorPosition,
+ ) {
+ if self.pane_state(pane.pane_id()).overlay.is_none() {
+ self.light_up_paste(pane, text, cursor);
}
}
}
diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs
index 2cb83494..1d4ac472 100644
--- a/wezterm-gui/src/termwindow/mod.rs
+++ b/wezterm-gui/src/termwindow/mod.rs
@@ -3047,6 +3047,13 @@ pub struct TermWindow {
ui_items: Vec<UIItem>,
context_menu: Option<ui::context_menu::ContextMenuState>,
+ /// Lights running round copied or pasted text, and a paste waiting to
+ /// show up for one (see `render::edge_light`).
+ edge_lights: Vec<render::edge_light::EdgeLight>,
+ pending_paste: Option<render::edge_light::PendingPaste>,
+ /// A mouse binding took the right button's press: its release does not
+ /// run the built-in right click as well.
+ right_press_claimed: bool,
recording_overlay: ui::recording_overlay::RecordingOverlay,
command_palette: Option<ui::command_palette::CommandPaletteState>,
/// The contrast floor text is held to, or `None` to leave the
@@ -4053,12 +4060,37 @@ impl TermWindow {
/// paint and the unfocused repaint throttle must agree on this set,
/// so both read it from here: a state added to one but not the other
/// silently strands frames or throttles what must not be throttled.
+ /// A selection was let go of: copied to `dest` while the setting has
+ /// selecting copy, and lit up for it. Otherwise only the primary
+ /// selection follows it where there is one (X11, Wayland), as every
+ /// program there keeps it for the middle button; macOS and Windows have
+ /// none, writing that would reach the clipboard.
+ fn copy_selection_let_go(
+ &mut self,
+ pane: &Arc<dyn Pane>,
+ dest: config::keyassignment::ClipboardCopyDestination,
+ text: String,
+ ) {
+ use config::keyassignment::ClipboardCopyDestination;
+ if crate::native_settings::copy_on_select() {
+ self.copy_to_clipboard(dest, text);
+ self.light_up_selection(pane, false);
+ } else if cfg!(not(any(windows, target_os = "macos"))) {
+ self.copy_to_clipboard(ClipboardCopyDestination::PrimarySelection, text);
+ }
+ }
+
pub(crate) fn owes_frames_regardless_of_focus(&self) -> bool {
self.content_view_fade.is_some()
|| self.active_content_view_index().is_some()
|| self.workspace_sidebar_hover.needs_frames()
|| self.right_sidebar_hover.needs_frames()
|| self.overlay_scrollbar_owes_frames()
+ // A light still running, or a paste still to show up for one:
+ // copying and then switching to the app to paste it in is the
+ // usual way, and a light left frozen on screen would stay.
+ || !self.edge_lights.is_empty()
+ || self.pending_paste.is_some()
}
/// An overlay scrollbar that is still up has a fade to finish; the
@@ -4771,6 +4803,9 @@ impl TermWindow {
semantic_zones: HashMap::new(),
ui_items: vec![],
context_menu: None,
+ edge_lights: vec![],
+ pending_paste: None,
+ right_press_claimed: false,
recording_overlay: Default::default(),
command_palette: None,
text_min_contrast: crate::native_settings::text_min_contrast_ratio(&config),
@@ -5493,7 +5528,9 @@ impl TermWindow {
Some(pane) => pane,
None => return Ok(true),
};
+ let cursor = pane.get_cursor_position();
pane.send_paste(text.as_str())?;
+ self.light_up_terminal_paste(&pane, &text, cursor);
Ok(true)
}
WindowEvent::DroppedUrl(urls) => {
@@ -5507,7 +5544,9 @@ impl TermWindow {
.collect::<Vec<_>>()
.join(" ")
+ " ";
+ let cursor = pane.get_cursor_position();
pane.send_paste(urls.as_str())?;
+ self.light_up_terminal_paste(&pane, &urls, cursor);
Ok(true)
}
WindowEvent::DroppedFile { paths, coords } => {
@@ -5596,7 +5635,9 @@ impl TermWindow {
.collect::<Vec<_>>()
.join(" ")
+ " ";
+ let cursor = pane.get_cursor_position();
pane.send_paste(&paths)?;
+ self.light_up_terminal_paste(&pane, &paths, cursor);
Ok(true)
}
WindowEvent::DraggedFile { coords, .. } => {
@@ -10501,6 +10542,7 @@ impl TermWindow {
let text = self.selection_text(pane);
if !text.is_empty() {
self.copy_to_clipboard(*destination, text);
+ self.light_up_selection(pane, false);
return Ok(PerformAssignmentResult::Handled);
}
if let Some(text) = self.right_sidebar_file_preview_selected_text() {
@@ -10967,7 +11009,7 @@ impl TermWindow {
// system clipboard just from selecting/clicking.
let text = self.selection_text(pane);
if !text.is_empty() {
- self.copy_to_clipboard(*dest, text);
+ self.copy_selection_let_go(pane, *dest, text);
let window = self.window.as_ref().unwrap();
window.invalidate();
} else {
@@ -10977,7 +11019,7 @@ impl TermWindow {
CompleteSelection(dest) => {
let text = self.selection_text(pane);
if !text.is_empty() {
- self.copy_to_clipboard(*dest, text);
+ self.copy_selection_let_go(pane, *dest, text);
let window = self.window.as_ref().unwrap();
window.invalidate();
}
diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rs
index c66724da..df0f0086 100644
--- a/wezterm-gui/src/termwindow/mouseevent.rs
+++ b/wezterm-gui/src/termwindow/mouseevent.rs
@@ -1589,7 +1589,7 @@ impl super::TermWindow {
true
}
- fn resolve_ui_item(&self, event: &MouseEvent) -> Option<UIItem> {
+ pub(crate) fn resolve_ui_item(&self, event: &MouseEvent) -> Option<UIItem> {
let x = event.coords.x;
let y = event.coords.y;
self.ui_items
@@ -2538,7 +2538,11 @@ impl super::TermWindow {
}
return;
};
- if event.kind == WMEK::Press(MousePress::Left) && self.right_sidebar_has_text_focus() {
+ // A right click pastes or copies in the terminal too, which a
+ // sidebar field still holding the keys would take instead.
+ if matches!(event.kind, WMEK::Press(MousePress::Left | MousePress::Right))
+ && self.right_sidebar_has_text_focus()
+ {
self.clear_right_sidebar_text_focus();
context.invalidate();
}
@@ -8664,6 +8668,48 @@ impl super::TermWindow {
}
}
+ /// A right click in a terminal that no mouse binding claimed: what the
+ /// settings ask for, or the menu while Control is held.
+ fn terminal_right_click(
+ &mut self,
+ pane: &Arc<dyn Pane>,
+ context: &dyn WindowOps,
+ coords: ::window::Point,
+ modifiers: ::window::Modifiers,
+ ) {
+ use crate::native_settings::NativeRightClick;
+ let assignments = match right_click_mode(modifiers) {
+ NativeRightClick::Menu => {
+ let items = self.terminal_context_menu_items();
+ self.show_term_context_menu(context, coords, items);
+ return;
+ }
+ NativeRightClick::CopyOrPaste => {
+ // A selection of nothing but blank cells copies as nothing:
+ // that is a paste, not a copy that would empty the clipboard.
+ let text = self.selection_text(pane);
+ if text.is_empty() {
+ vec![KeyAssignment::PasteFrom(ClipboardPasteSource::Clipboard)]
+ } else {
+ // As other terminals do it: the copy lets the selection
+ // go, so the next right click pastes. Its block fades out
+ // with the light rather than vanishing under it.
+ self.copy_to_clipboard(ClipboardCopyDestination::Clipboard, text);
+ self.light_up_selection(pane, true);
+ vec![KeyAssignment::ClearSelection]
+ }
+ }
+ NativeRightClick::Paste => {
+ vec![KeyAssignment::PasteFrom(ClipboardPasteSource::Clipboard)]
+ }
+ };
+ for assignment in assignments {
+ if let Err(err) = self.perform_key_assignment(pane, &assignment) {
+ log::warn!("right click {assignment:?}: {err:#}");
+ }
+ }
+ }
+
fn terminal_context_menu_items(&mut self) -> Vec<ContextMenuItem> {
fn split_item(
label: String,
@@ -9182,6 +9228,9 @@ impl super::TermWindow {
}),
};
+ if matches!(event.kind, WMEK::Press(MousePress::Right)) {
+ self.right_press_claimed = false;
+ }
if allow_action {
if let Some(mut event_trigger_type) = event_trigger_type {
self.current_event = Some(event_trigger_type.to_dynamic());
@@ -9250,6 +9299,9 @@ impl super::TermWindow {
};
if let Some(action) = self.input_map.lookup_mouse(event_trigger_type, mouse_mods) {
+ if matches!(event.kind, WMEK::Press(MousePress::Right)) {
+ self.right_press_claimed = true;
+ }
self.perform_key_assignment(&pane, &action).ok();
return;
}
@@ -9263,9 +9315,11 @@ impl super::TermWindow {
{
// Own both halves of the click so the terminal application never
// receives a press whose release opens our menu instead.
- if matches!(event.kind, WMEK::Release(MousePress::Right)) {
- let items = self.terminal_context_menu_items();
- self.show_term_context_menu(context, event.coords, items);
+ // A binding that took the press took the click.
+ if matches!(event.kind, WMEK::Release(MousePress::Right))
+ && !std::mem::take(&mut self.right_press_claimed)
+ {
+ self.terminal_right_click(&pane, context, event.coords, event.modifiers);
}
return;
}
@@ -9331,6 +9385,16 @@ impl super::TermWindow {
}
}
+/// What a right click in a terminal does with `modifiers` held: what the
+/// settings ask for, or the menu while Control is held.
+pub(crate) fn right_click_mode(modifiers: ::window::Modifiers) -> crate::native_settings::NativeRightClick {
+ if modifiers.contains(::window::Modifiers::CTRL) {
+ crate::native_settings::NativeRightClick::Menu
+ } else {
+ crate::native_settings::right_click()
+ }
+}
+
fn mouse_press_to_tmb(press: &MousePress) -> TMB {
match press {
MousePress::Left => TMB::Left,
diff --git a/wezterm-gui/src/termwindow/render/edge_light.rs b/wezterm-gui/src/termwindow/render/edge_light.rs
new file mode 100644
index 00000000..096cc31c
--- /dev/null
+++ b/wezterm-gui/src/termwindow/render/edge_light.rs
@@ -0,0 +1,772 @@
+//! The light that runs round copied and pasted text.
+//!
+//! A copy lights up the selection it took. A paste lights up the text it put
+//! in, once the program has echoed it at the cursor where the paste went --
+//! text that never shows up there (a password prompt, an editor in a mode
+//! that takes keys as commands) gets no light rather than a wrong one.
+//! Either way the light follows the rounded outline the selection is drawn
+//! with (`selection_shape`), and the setting picks white, colour or none.
+//! Two lights run along its top and bottom from where the selection was
+//! begun to its other end: a selection made backwards (dragged right to
+//! left, or up) lights from its end.
+
+use crate::customglyph::{BlockAlpha, BlockCoord, Poly, PolyCommand, PolyStyle};
+use crate::quad::{QuadTrait, TripleLayerQuadAllocator};
+use crate::termwindow::render::selection_shape::{corner_radius, selected_span, Outline};
+use crate::termwindow::TermWindowNotif;
+use ::window::WindowOps;
+use mux::pane::{Pane, PaneId};
+use mux::renderable::StableCursorPosition;
+use std::convert::TryFrom;
+use std::ops::Range;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+use termwiz::color::LinearRgba;
+use termwiz::surface::Line;
+use wezterm_term::StableRowIndex;
+
+/// One light goes round, at this speed in UI points a second: a longer
+/// outline takes longer, within these bounds.
+const SPEED: f32 = 700.;
+const MIN_DURATION: Duration = Duration::from_millis(700);
+const MAX_DURATION: Duration = Duration::from_millis(1600);
+/// The fade at the end, the light's and a pasted block's.
+const FADE: Duration = Duration::from_millis(250);
+/// The longest a light's tail gets, in UI points.
+const MAX_TAIL: f32 = 110.;
+const LINE_WIDTH: f32 = 2.;
+/// Any gap between the text's block and the line the light runs on, in UI
+/// points. None: the line hugs the block from outside, its inner edge on
+/// the block's edge.
+const OUTSET: f32 = 0.;
+/// How long a paste has to show up before its light is given up.
+const PASTE_WAIT: Duration = Duration::from_millis(1000);
+/// Longer pastes are not looked for on screen.
+const PASTE_MAX_CHARS: usize = 4000;
+/// Lights running at once, at most; another replaces the oldest.
+const MAX_LIGHTS: usize = 8;
+/// The light is a run of round dots, so it bends round the outline's
+/// corners, and its halo with it, instead of squaring them off.
+const DOT: &[Poly] = &[Poly {
+ path: &[PolyCommand::Circle {
+ center: (BlockCoord::Frac(1, 2), BlockCoord::Frac(1, 2)),
+ radius: BlockCoord::Frac(1, 2),
+ }],
+ intensity: BlockAlpha::Full,
+ style: PolyStyle::Fill,
+}];
+
+/// One light, on rows of one pane.
+pub struct EdgeLight {
+ pane_id: PaneId,
+ started: Instant,
+ first_row: StableRowIndex,
+ /// What each row from `first_row` covers, in cells; a selection's run on
+ /// to the end of the row, cut to the columns drawn when painted.
+ spans: Vec<Range<usize>>,
+ /// The selection runs on above the first of `spans` and below the last,
+ /// off the screen it was copied on.
+ continues: (bool, bool),
+ colored: bool,
+ /// It runs from the end back to the start: the selection was made
+ /// backwards.
+ reversed: bool,
+ /// The text's block fades out with the light: a paste's, or a selection
+ /// that was let go as it was copied.
+ fill: bool,
+ /// How long it takes, from the length of its outline when first
+ /// painted; until then, the longest it could.
+ duration: Option<Duration>,
+}
+
+impl EdgeLight {
+ fn duration(&self) -> Duration {
+ self.duration.unwrap_or(MAX_DURATION)
+ }
+
+ /// Still on its way round, not yet fading.
+ fn running(&self, now: Instant) -> bool {
+ now.duration_since(self.started) < self.duration()
+ }
+
+ fn finished(&self, now: Instant) -> bool {
+ now.duration_since(self.started) >= self.duration() + FADE
+ }
+}
+
+/// Where a pane's rows are drawn, for the lights on them.
+pub struct LightArea {
+ /// The rows drawn, the first with its top at `origin`.
+ pub rows: Range<StableRowIndex>,
+ pub origin: (f32, f32),
+ pub cell: (f32, f32),
+ /// The columns drawn.
+ pub cols: usize,
+ /// The pane's edges, as left, top, right, bottom: where a light would
+ /// run past one, it runs just inside it.
+ pub bounds: (f32, f32, f32, f32),
+ /// Those of the rows drawn of double width (or height), whose cells
+ /// are twice as wide.
+ pub double_width: Vec<StableRowIndex>,
+ /// The selection is drawn with rounded corners, and so is the light.
+ pub rounded: bool,
+}
+
+/// A paste whose text is still to appear on screen.
+pub struct PendingPaste {
+ pane_id: PaneId,
+ asked: Instant,
+ row: StableRowIndex,
+ col: usize,
+ text: String,
+ colored: bool,
+}
+
+/// Whether the light is coloured, or `None` when it is off.
+fn light_setting() -> Option<bool> {
+ use crate::native_settings::NativeCopyEffect;
+ match crate::native_settings::copy_effect() {
+ NativeCopyEffect::Off => None,
+ NativeCopyEffect::White => Some(false),
+ NativeCopyEffect::Color => Some(true),
+ }
+}
+
+/// Where `text` ends if it is what the cells from `col` of the first of
+/// `lines` read (running on across wrapped rows): the line it ends on and
+/// the column just past it. `None` while they do not read it (yet).
+pub fn pasted_extent(lines: &[&Line], col: usize, text: &str) -> Option<(usize, usize)> {
+ let mut matched = 0;
+ for (index, line) in lines.iter().enumerate() {
+ let from = if index == 0 { col } else { 0 };
+ for cell in line.visible_cells().filter(|cell| cell.cell_index() >= from) {
+ let piece = cell.str();
+ if !text[matched..].starts_with(piece) {
+ return None;
+ }
+ matched += piece.len();
+ if matched == text.len() {
+ return Some((index, cell.cell_index() + cell.width()));
+ }
+ }
+ if !line.last_cell_was_wrapped() {
+ return None;
+ }
+ }
+ None
+}
+
+/// The rows a paste from `col` to `end` (line, column) covers, as spans.
+fn pasted_spans(col: usize, end: (usize, usize), cols: usize) -> Vec<Range<usize>> {
+ (0..=end.0)
+ .map(|row| {
+ let start = if row == 0 { col } else { 0 };
+ let stop = if row == end.0 { end.1 } else { cols };
+ start..stop.max(start)
+ })
+ .collect()
+}
+
+/// The alpha for each of the dots `step` apart, `size` across, that pile
+/// up to `alpha` where they overlap: about `size / step` cover any point.
+fn overlapped_alpha(alpha: f32, step: f32, size: f32) -> f32 {
+ let alpha = alpha.clamp(0., 1.);
+ if alpha >= 1. {
+ return 1.;
+ }
+ 1. - (1. - alpha).powf(step / size.max(step))
+}
+
+/// How one light (or two) is drawn on an outline this frame.
+struct LightStyle {
+ /// How far through its run, eased.
+ progress: f32,
+ fade: f32,
+ colored: bool,
+ reversed: bool,
+ light_background: bool,
+}
+
+/// The two lights on an outline `total` long, `progress` of the way through
+/// their run down both sides from its start to `meet` (`reversed`, from
+/// `meet` back to the start): each as (where its head is, which way it runs,
+/// the point its tail may not reach back past), and how far the longer side
+/// goes.
+fn light_heads(total: f32, meet: f32, progress: f32, reversed: bool) -> ([(f32, f32, f32); 2], f32) {
+ let heads = if reversed {
+ [(meet - progress * meet, -1., meet), (meet + progress * (total - meet), 1., meet)]
+ } else {
+ [(progress * meet, 1., 0.), (total - progress * (total - meet), -1., total)]
+ };
+ (heads, meet.max(total - meet))
+}
+
+fn ease_in_out(t: f32) -> f32 {
+ if t < 0.5 {
+ 4. * t * t * t
+ } else {
+ 1. - (-2. * t + 2.).powi(3) / 2.
+ }
+}
+
+/// The coloured light's colours, evenly along it left to right: blue,
+/// violet, pink, amber.
+const COLOR_STOPS: [(u8, u8, u8); 4] = [
+ (0x5a, 0xa0, 0xff),
+ (0xb9, 0x6e, 0xff),
+ (0xff, 0x6e, 0xaa),
+ (0xff, 0xb4, 0x5a),
+];
+
+/// The light's colours, converted once for all of a frame's dots: the
+/// coloured light's, and the plain one's on a dark and a light background.
+struct LightColors {
+ stops: [LinearRgba; 4],
+ white: LinearRgba,
+ graphite: LinearRgba,
+}
+
+impl LightColors {
+ fn new() -> Self {
+ Self {
+ stops: COLOR_STOPS.map(|(r, g, b)| LinearRgba::with_srgba(r, g, b, 255)),
+ white: LinearRgba::with_srgba(255, 255, 255, 255),
+ graphite: LinearRgba::with_srgba(72, 72, 78, 255),
+ }
+ }
+}
+
+/// The colour along the coloured light, `across` from its left (0) to its
+/// right (1). The plain light is white, or graphite on a light background,
+/// where white outside the block would not show.
+fn light_color(colors: &LightColors, colored: bool, across: f32, light_background: bool) -> LinearRgba {
+ if !colored {
+ return if light_background {
+ colors.graphite
+ } else {
+ colors.white
+ };
+ }
+ let stops = &colors.stops;
+ let at = across.clamp(0., 1.) * (stops.len() - 1) as f32;
+ let index = (at.floor() as usize).min(stops.len() - 2);
+ let t = at - index as f32;
+ let (a, b) = (stops[index], stops[index + 1]);
+ LinearRgba::with_components(
+ a.0 + (b.0 - a.0) * t,
+ a.1 + (b.1 - a.1) * t,
+ a.2 + (b.2 - a.2) * t,
+ 1.,
+ )
+}
+
+impl crate::TermWindow {
+ fn add_edge_light(&mut self, light: EdgeLight) {
+ let now = Instant::now();
+ // The same rows lit again while their light is on its way round --
+ // a drag let go, then copied with the keys -- keep that light, with
+ // the block if this one has it.
+ if let Some(running) = self.edge_lights.iter_mut().find(|running| {
+ running.pane_id == light.pane_id
+ && running.first_row == light.first_row
+ && running.spans == light.spans
+ && running.running(now)
+ }) {
+ running.fill |= light.fill;
+ return;
+ }
+ // A new selection's light takes over from an earlier selection's on
+ // the pane (a triple click lights the word, then its line); a block
+ // fading out finishes.
+ if !light.fill {
+ self.edge_lights
+ .retain(|running| running.pane_id != light.pane_id || running.fill);
+ }
+ if self.edge_lights.len() >= MAX_LIGHTS {
+ self.edge_lights.remove(0);
+ }
+ self.edge_lights.push(light);
+ if let Some(window) = self.window.as_ref() {
+ window.invalidate();
+ }
+ }
+
+ /// Light up `pane`'s selection, as much of it as is on screen, because
+ /// it was just copied. `fill` keeps its block fading with the light, for
+ /// a selection about to be let go.
+ pub fn light_up_selection(&mut self, pane: &Arc<dyn Pane>, fill: bool) {
+ let Some(colored) = light_setting() else {
+ return;
+ };
+ let (range, rectangular, backwards) = {
+ let selection = self.selection(pane.pane_id());
+ (selection.range, selection.rectangular, selection.backwards)
+ };
+ let Some(range) = range else {
+ return;
+ };
+ let reversed = backwards || (range.start.y, range.start.x) > (range.end.y, range.end.x);
+ let range = range.normalize();
+ let dims = pane.get_dimensions();
+ let top = self.get_viewport(pane.pane_id()).unwrap_or(dims.physical_top);
+ // One row past the viewport: a smooth scroll shows part of it.
+ let shown = top..top + dims.viewport_rows as StableRowIndex + 1;
+ let selected = range.rows();
+ let rows = selected.start.max(shown.start)..selected.end.min(shown.end);
+ if rows.is_empty() {
+ return;
+ }
+ let continues = (selected.start < rows.start, selected.end > rows.end);
+ let first_row = rows.start;
+ let spans = rows
+ .map(|row| selected_span(&range, row, rectangular, usize::MAX))
+ .collect();
+ self.add_edge_light(EdgeLight {
+ pane_id: pane.pane_id(),
+ started: Instant::now(),
+ first_row,
+ spans,
+ continues,
+ colored,
+ reversed,
+ fill,
+ duration: None,
+ });
+ }
+
+ /// `text` was just pasted into `pane`, whose cursor was at `cursor`
+ /// before it: light it up once it shows there. Only a single line is
+ /// looked for; a paste of many runs commands, and what those print is
+ /// not the paste.
+ pub fn light_up_paste(&mut self, pane: &Arc<dyn Pane>, text: &str, cursor: StableCursorPosition) {
+ let Some(colored) = light_setting() else {
+ return;
+ };
+ let text = text.strip_suffix('\n').unwrap_or(text);
+ let text = text.strip_suffix('\r').unwrap_or(text);
+ // Not the space a dropped path is followed by.
+ let text = text.trim_end_matches([' ', '\t']);
+ if text.is_empty() || text.contains(['\n', '\r']) || text.chars().count() > PASTE_MAX_CHARS {
+ return;
+ }
+ let asked = Instant::now();
+ self.pending_paste = Some(PendingPaste {
+ pane_id: pane.pane_id(),
+ asked,
+ row: cursor.y,
+ col: cursor.x,
+ text: text.to_string(),
+ colored,
+ });
+ if let Some(window) = self.window.clone() {
+ window.invalidate();
+ // Let go once it is given up even if its pane is never drawn
+ // again: the text may be a password typed where nothing echoes.
+ promise::spawn::spawn(async move {
+ smol::Timer::after(PASTE_WAIT).await;
+ window.notify(TermWindowNotif::Apply(Box::new(move |myself| {
+ if myself.pending_paste.as_ref().is_some_and(|p| p.asked == asked) {
+ myself.pending_paste = None;
+ }
+ })));
+ })
+ .detach();
+ }
+ }
+
+ /// Look for the pending paste among the drawn `lines` of `pane_id`
+ /// (from `stable_top`), and light it up once it is there.
+ pub fn find_pending_paste(
+ &mut self,
+ pane_id: PaneId,
+ stable_top: StableRowIndex,
+ lines: &[&mut Line],
+ cols: usize,
+ ) {
+ let Some(pending) = self.pending_paste.as_ref().filter(|p| p.pane_id == pane_id) else {
+ return;
+ };
+ let now = Instant::now();
+ if now.duration_since(pending.asked) > PASTE_WAIT {
+ self.pending_paste = None;
+ return;
+ }
+ let found = usize::try_from(pending.row - stable_top)
+ .ok()
+ .filter(|first| *first < lines.len())
+ .and_then(|first| {
+ let lines: Vec<&Line> = lines[first..].iter().map(|line| &**line).collect();
+ pasted_extent(&lines, pending.col, &pending.text)
+ });
+ let Some(end) = found else {
+ self.update_next_frame_time(Some(now + Duration::from_millis(30)));
+ return;
+ };
+ let pending = self.pending_paste.take().expect("checked above");
+ self.add_edge_light(EdgeLight {
+ pane_id,
+ started: now,
+ first_row: pending.row,
+ spans: pasted_spans(pending.col, end, cols),
+ continues: (false, false),
+ colored: pending.colored,
+ // Typed in from its start.
+ reversed: false,
+ fill: true,
+ duration: None,
+ });
+ }
+
+ /// The cells of `rows` whose text a light's block lies under, cut to
+ /// `cols`, one span per row: that text keeps the selection's colours
+ /// while the block is still more than half there. Empty (and not
+ /// allocated) when there is none.
+ pub fn light_block_spans(
+ &self,
+ pane_id: PaneId,
+ rows: Range<StableRowIndex>,
+ cols: usize,
+ ) -> Vec<Range<usize>> {
+ let now = Instant::now();
+ let mut spans = vec![];
+ for light in &self.edge_lights {
+ if light.pane_id != pane_id
+ || !light.fill
+ || now.duration_since(light.started) >= light.duration() + FADE / 2
+ {
+ continue;
+ }
+ for (index, span) in light.spans.iter().enumerate() {
+ let row = light.first_row + index as StableRowIndex;
+ if !rows.contains(&row) {
+ continue;
+ }
+ if spans.is_empty() {
+ spans = vec![0..0; (rows.end - rows.start) as usize];
+ }
+ let end = span.end.min(cols);
+ let slot = (row - rows.start) as usize;
+ if spans[slot].is_empty() {
+ spans[slot] = span.start.min(end)..end;
+ }
+ }
+ }
+ spans
+ }
+
+ /// Paint the lights running on `pane_id`, drawn in `area`; a filled
+ /// block in `block_color`. On a light `background` the white light's
+ /// halo is a shadow, which is what gives it an edge there.
+ pub fn paint_edge_lights(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator,
+ pane_id: PaneId,
+ area: &LightArea,
+ block_color: LinearRgba,
+ background: LinearRgba,
+ ) -> anyhow::Result<()> {
+ let light_background =
+ 0.2126 * background.0 + 0.7152 * background.1 + 0.0722 * background.2 > 0.4;
+ if self.edge_lights.is_empty() {
+ return Ok(());
+ }
+ let now = Instant::now();
+ self.edge_lights.retain(|light| !light.finished(now));
+ if self.edge_lights.is_empty() {
+ return Ok(());
+ }
+ self.update_next_frame_time(Some(now + Duration::from_millis(16)));
+ let lights: Vec<usize> = (0..self.edge_lights.len())
+ .filter(|&index| self.edge_lights[index].pane_id == pane_id)
+ .collect();
+ for index in lights {
+ let light = &self.edge_lights[index];
+ // Only the rows on screen, from the first of them.
+ let light_rows = light.first_row..light.first_row + light.spans.len() as StableRowIndex;
+ let shown = light_rows.start.max(area.rows.start)..light_rows.end.min(area.rows.end);
+ if shown.is_empty() {
+ continue;
+ }
+ let skip = (shown.start - light.first_row) as usize;
+ // Cut to the columns drawn as the selection is, and counted in
+ // single cells: a double-width row's are twice as wide.
+ let spans: Vec<Range<usize>> = light.spans[skip..skip + (shown.end - shown.start) as usize]
+ .iter()
+ .zip(shown.clone())
+ .map(|(span, row)| {
+ let scale = if area.double_width.contains(&row) { 2 } else { 1 };
+ let end = span.end.min(area.cols / scale);
+ span.start.min(end) * scale..end * scale
+ })
+ .collect();
+ let top = area.origin.1 + (shown.start - area.rows.start) as f32 * area.cell.1;
+ // Where the selection runs on past what is drawn, its edge there
+ // is a cut, square, not a corner.
+ let cut = (
+ light.continues.0 || shown.start > light_rows.start,
+ light.continues.1 || shown.end < light_rows.end,
+ );
+ let (colored, reversed, fill) = (light.colored, light.reversed, light.fill);
+ let started = light.started;
+
+ let radius = if area.rounded {
+ corner_radius(area.cell.0, area.cell.1)
+ } else {
+ 0.
+ };
+ let width = self.ui_f32(LINE_WIDTH).max(1.);
+ // A ring round the outside of the block, the light's middle half
+ // its width out from the block's edge -- inside the pane, where
+ // that would cross its edge, the rows being cut short of it.
+ let reach = self.ui_f32(OUTSET) + width;
+ let inset = -(self.ui_f32(OUTSET) + width / 2.);
+ let within = (
+ area.bounds.0 + reach,
+ area.bounds.1 + reach,
+ area.bounds.2 - reach,
+ area.bounds.3 - reach,
+ );
+ let outlines = Outline::of_rows(
+ &spans,
+ (area.origin.0, top),
+ area.cell,
+ radius,
+ inset,
+ within,
+ cut,
+ );
+ let duration = match light.duration {
+ Some(duration) => duration,
+ None => {
+ // The longer of the two sides, at a steady speed.
+ let way = outlines
+ .iter()
+ .map(|outline| outline.meet.max(outline.length() - outline.meet))
+ .fold(0., f32::max);
+ let seconds = way / self.ui_f32(SPEED).max(1.);
+ let duration = Duration::from_secs_f32(seconds)
+ .clamp(MIN_DURATION, MAX_DURATION);
+ self.edge_lights[index].duration = Some(duration);
+ duration
+ }
+ };
+ let elapsed = now.duration_since(started);
+ let fade = if elapsed > duration {
+ 1. - (elapsed - duration).as_secs_f32() / FADE.as_secs_f32()
+ } else {
+ 1.
+ };
+ let progress = ease_in_out((elapsed.as_secs_f32() / duration.as_secs_f32()).min(1.));
+
+ if fill {
+ let color = block_color.mul_alpha(fade.clamp(0., 1.));
+ let last = spans.len().saturating_sub(1);
+ for (row, span) in spans.iter().enumerate() {
+ // Running on past an edge, as the selection was drawn.
+ let above = match row {
+ 0 if cut.0 => span.clone(),
+ 0 => 0..0,
+ _ => spans[row - 1].clone(),
+ };
+ let below = match spans.get(row + 1) {
+ Some(next) => next.clone(),
+ None if row == last && cut.1 => span.clone(),
+ None => 0..0,
+ };
+ self.paint_selection_row(
+ layers,
+ 0,
+ area.origin.0,
+ top + row as f32 * area.cell.1,
+ area.cell.0,
+ area.cell.1,
+ span,
+ &(above, below),
+ color,
+ area.rounded,
+ None,
+ )?;
+ }
+ }
+ let style = LightStyle {
+ progress,
+ fade: fade.clamp(0., 1.),
+ colored,
+ reversed,
+ light_background,
+ };
+ for outline in &outlines {
+ self.paint_light_on(layers, outline, &style)?;
+ }
+ }
+ Ok(())
+ }
+
+ /// A round dot of `size` centred on `at`.
+ fn paint_dot(
+ &self,
+ layers: &mut TripleLayerQuadAllocator,
+ at: (f32, f32),
+ size: f32,
+ color: LinearRgba,
+ ) -> anyhow::Result<()> {
+ let mut quad = self.poly_quad(
+ layers,
+ 2,
+ euclid::point2(at.0 - size / 2., at.1 - size / 2.),
+ DOT,
+ 0,
+ euclid::size2(size, size),
+ color,
+ )?;
+ quad.set_grayscale();
+ quad.set_hsv(None);
+ Ok(())
+ }
+
+ /// The lights on one outline, as far along and as faded as `style` says.
+ fn paint_light_on(
+ &self,
+ layers: &mut TripleLayerQuadAllocator,
+ outline: &Outline,
+ style: &LightStyle,
+ ) -> anyhow::Result<()> {
+ let LightStyle {
+ progress,
+ fade,
+ colored,
+ reversed,
+ light_background,
+ } = *style;
+ let total = outline.length();
+ if total <= 0. || fade <= 0. {
+ return Ok(());
+ }
+ let (heads, travel) = light_heads(total, outline.meet, progress, reversed);
+ let tail = self.ui_f32(MAX_TAIL).min(travel * 0.33);
+ let width = self.ui_f32(LINE_WIDTH).max(1.);
+ // A dot every pixel, each overlapping the next, reads as one
+ // continuous line; spaced wider the tail breaks into a dotted one.
+ let step = 1.;
+ let (x_lo, x_hi) = outline.x_range;
+ let across = |x: f32| if x_hi > x_lo { (x - x_lo) / (x_hi - x_lo) } else { 0. };
+ let colors = LightColors::new();
+ for (head, direction, limit) in heads {
+ let mut back = 0.;
+ while back < tail {
+ let along = head - direction * back;
+ let beyond = if direction > 0. { along < limit } else { along > limit };
+ if beyond {
+ break;
+ }
+ let (x, y) = outline.point_at(along);
+ let left = 1. - back / tail;
+ let color = light_color(&colors, colored, across(x), light_background);
+ let size = (width * (0.65 + 0.35 * left)).max(2.);
+ let core = overlapped_alpha(left.powf(1.4) * fade, step, size);
+ self.paint_dot(layers, (x, y), size, color.mul_alpha(core))?;
+ // A soft halo round the brightest part, two rings of it:
+ // light on a dark background, a shadow under white light on
+ // a light one.
+ if left > 0.7 {
+ let (halo_color, strength) = if light_background && !colored {
+ (LinearRgba::with_srgba(0, 0, 0, 255), 0.12)
+ } else {
+ (color, 0.08)
+ };
+ let strength = strength * (left - 0.7) / 0.3 * fade;
+ let (outer, inner) = (width * 3.4, width * 2.2);
+ let outer_alpha = overlapped_alpha(strength * 0.6, step, outer);
+ let inner_alpha = overlapped_alpha(strength, step, inner);
+ self.paint_dot(layers, (x, y), outer, halo_color.mul_alpha(outer_alpha))?;
+ self.paint_dot(layers, (x, y), inner, halo_color.mul_alpha(inner_alpha))?;
+ }
+ back += step;
+ }
+ }
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use termwiz::surface::SEQ_ZERO;
+
+ fn line(text: &str, wrapped: bool) -> Line {
+ let mut line = Line::from_text(text, &Default::default(), SEQ_ZERO, None);
+ line.set_last_cell_was_wrapped(wrapped, SEQ_ZERO);
+ line
+ }
+
+ #[test]
+ fn a_paste_is_found_where_it_was_typed_and_only_there() {
+ let shown = line("$ git status --short", false);
+ let lines = vec![&shown];
+ assert_eq!(pasted_extent(&lines, 2, "git status"), Some((0, 12)));
+ assert_eq!(pasted_extent(&lines, 2, "git status --short"), Some((0, 20)));
+ // Not (yet) what was pasted.
+ assert_eq!(pasted_extent(&lines, 2, "git stash"), None);
+ assert_eq!(pasted_extent(&lines, 2, "git status --short --branch"), None);
+ }
+
+ #[test]
+ fn a_paste_runs_on_across_a_wrapped_row() {
+ let first = line("$ abcdef", true);
+ let second = line("ghij", false);
+ let lines = vec![&first, &second];
+ assert_eq!(pasted_extent(&lines, 2, "abcdefgh"), Some((1, 2)));
+ assert_eq!(pasted_spans(2, (1, 2), 8), vec![2..8, 0..2]);
+ // A row that ends without wrapping stops it.
+ let unwrapped = line("$ abcdef", false);
+ let lines = vec![&unwrapped, &second];
+ assert_eq!(pasted_extent(&lines, 2, "abcdefgh"), None);
+ }
+
+ #[test]
+ fn the_coloured_light_goes_blue_to_amber() {
+ let colors = LightColors::new();
+ let start = light_color(&colors, true, 0., false);
+ let end = light_color(&colors, true, 1., false);
+ assert!(start.2 > start.0, "blue at the left");
+ assert!(end.0 > end.2, "amber at the right");
+ assert_eq!(light_color(&colors, false, 0.5, false), LinearRgba::with_srgba(255, 255, 255, 255));
+ // White would vanish on a light background: graphite there.
+ let plain = light_color(&colors, false, 0.5, true);
+ assert!(plain.0 < 0.2 && plain.1 < 0.2 && plain.2 < 0.2);
+ }
+
+ #[test]
+ fn overlapping_dots_add_up_to_the_alpha_asked_for() {
+ let each = overlapped_alpha(0.5, 1., 4.);
+ // Four of them over one point leave what one at 0.5 would.
+ assert!((1. - (1. - each).powi(4) - 0.5).abs() < 1e-5);
+ assert_eq!(overlapped_alpha(1., 1., 4.), 1.);
+ assert_eq!(overlapped_alpha(0., 1., 4.), 0.);
+ // A dot no wider than the step overlaps nothing.
+ assert!((overlapped_alpha(0.3, 2., 1.) - 0.3).abs() < 1e-6);
+ }
+
+ #[test]
+ fn a_light_runs_from_where_the_selection_was_begun() {
+ // An outline 100 long whose far end (the middle of the last row's
+ // right side) is 40 along it.
+ let heads = |progress, reversed| light_heads(100., 40., progress, reversed).0;
+ // Forwards they leave the start and meet at the far end.
+ assert_eq!(heads(0., false), [(0., 1., 0.), (100., -1., 100.)]);
+ assert_eq!(heads(1., false), [(40., 1., 0.), (40., -1., 100.)]);
+ // Backwards they leave the far end and meet at the start.
+ assert_eq!(heads(0., true), [(40., -1., 40.), (40., 1., 40.)]);
+ assert_eq!(heads(1., true), [(0., -1., 40.), (100., 1., 40.)]);
+ // Either way the longer side sets how far they go.
+ assert_eq!(light_heads(100., 40., 0.5, true).1, 60.);
+ }
+
+ #[test]
+ fn the_light_eases_in_and_out() {
+ assert_eq!(ease_in_out(0.), 0.);
+ assert_eq!(ease_in_out(1.), 1.);
+ assert!((ease_in_out(0.5) - 0.5).abs() < 1e-6);
+ assert!(ease_in_out(0.1) < 0.1 && ease_in_out(0.9) > 0.9);
+ }
+}
diff --git a/wezterm-gui/src/termwindow/render/mod.rs b/wezterm-gui/src/termwindow/render/mod.rs
index 7267d86e..1b727bc9 100644
--- a/wezterm-gui/src/termwindow/render/mod.rs
+++ b/wezterm-gui/src/termwindow/render/mod.rs
@@ -44,11 +44,13 @@ use window::color::LinearRgba;
pub mod borders;
pub mod corners;
pub mod draw;
+pub mod edge_light;
pub mod fancy_tab_bar;
pub mod hover;
pub mod paint;
pub mod pane;
pub mod screen_line;
+pub mod selection_shape;
pub mod split;
pub mod tab_bar;
pub mod window_buttons;
@@ -69,6 +71,13 @@ pub struct LineQuadCacheKey {
/// Only set if cursor.y == stable_row
pub composing: Option<String>,
pub selection: Range<usize>,
+ /// The selection on the rows above and below: this row's part of the
+ /// shape depends on them (see `selection_shape`).
+ pub selection_neighbors: (Range<usize>, Range<usize>),
+ /// The selection colours only the text: a light draws the block.
+ pub selection_text_only: bool,
+ /// Its corners are rounded (see `selection_shape`); only with one.
+ pub selection_rounded: bool,
pub shape_hash: [u8; 16],
pub font_identity: u64,
pub top_pixel_y: NotNan<f32>,
@@ -210,6 +219,14 @@ pub struct RenderScreenLineParams<'a> {
pub stable_line_idx: Option<StableRowIndex>,
pub line: &'a Line,
pub selection: Range<usize>,
+ /// The selection on the rows above and below, for the shape of this
+ /// row's part of it; empty where there is none.
+ pub selection_neighbors: (Range<usize>, Range<usize>),
+ /// Only the text in `selection` takes its colours; its block is drawn
+ /// by a light (see `edge_light`).
+ pub selection_text_only: bool,
+ /// The selection's corners are rounded, or square as they always were.
+ pub selection_rounded: bool,
pub cursor: &'a StableCursorPosition,
pub palette: &'a ColorPalette,
pub dims: &'a RenderableDimensions,
@@ -1482,6 +1499,9 @@ mod line_quad_cache_tests {
quad_generation: 0,
composing: None,
selection: 0..0,
+ selection_neighbors: (0..0, 0..0),
+ selection_text_only: false,
+ selection_rounded: false,
shape_hash: [0; 16],
font_identity: 0,
top_pixel_y: NotNan::new(0.0).unwrap(),
diff --git a/wezterm-gui/src/termwindow/render/paint.rs b/wezterm-gui/src/termwindow/render/paint.rs
index e4341446..88c59641 100644
--- a/wezterm-gui/src/termwindow/render/paint.rs
+++ b/wezterm-gui/src/termwindow/render/paint.rs
@@ -2926,6 +2926,9 @@ impl crate::TermWindow {
stable_line_idx: Some(pane.resolved_top + line_idx as isize),
line,
selection: 0..0,
+ selection_neighbors: (0..0, 0..0),
+ selection_text_only: false,
+ selection_rounded: false,
cursor: &hidden_cursor,
palette,
dims: &render_dims,
diff --git a/wezterm-gui/src/termwindow/render/pane.rs b/wezterm-gui/src/termwindow/render/pane.rs
index 66405eb1..5468ef57 100644
--- a/wezterm-gui/src/termwindow/render/pane.rs
+++ b/wezterm-gui/src/termwindow/render/pane.rs
@@ -9,6 +9,8 @@ use crate::termwindow::render::{
same_hyperlink, CursorProperties, LineQuadCacheKey, LineQuadCacheValue, LineToEleShapeCacheKey,
RenderScreenLineParams,
};
+use crate::termwindow::render::edge_light::LightArea;
+use crate::termwindow::render::selection_shape::{drawn_neighbours, selected_span};
use crate::agent_status::{AgentEvidence, AgentState, ProgramReportState};
use crate::termwindow::ui::agent_panel::{AGENT_BLOCKED_COLOR, AGENT_DONE_COLOR};
use crate::termwindow::ui::icons::SvgIcon;
@@ -2007,6 +2009,11 @@ impl crate::TermWindow {
filled_box: TextureRect,
window_is_transparent: bool,
layers: &'a mut TripleLayerQuadAllocator<'b>,
+ /// The drawn rows of double width, noted for the lights while
+ /// any are running.
+ double_width_rows: Vec<StableRowIndex>,
+ /// The selection's corners are rounded (the setting).
+ selection_rounded: bool,
error: Option<anyhow::Error>,
}
@@ -2100,22 +2107,70 @@ impl crate::TermWindow {
filled_box,
window_is_transparent,
layers,
+ double_width_rows: vec![],
+ selection_rounded: crate::native_settings::selection_rounded(),
error: None,
};
+ /// What of the selection one drawn row shows.
+ struct RowSelection {
+ span: std::ops::Range<usize>,
+ /// The spans of the rows above and below, as far as they
+ /// shape this row's part.
+ neighbours: (std::ops::Range<usize>, std::ops::Range<usize>),
+ /// Only the text takes the selection's colours: the block
+ /// under it is a light's, fading out.
+ text_only: bool,
+ }
+
impl<'a, 'b> LineRender<'a, 'b> {
+ /// The selection on each drawn row, with the rows just
+ /// beyond the first and the last at either end: one more
+ /// entry before the first line and one after the last.
+ /// Empty (and not allocated) with no selection.
+ fn selection_spans(
+ &self,
+ stable_top: StableRowIndex,
+ lines: &[&mut Line],
+ ) -> Vec<std::ops::Range<usize>> {
+ let Some(sel) = self.selrange.filter(|_| !lines.is_empty()) else {
+ return vec![];
+ };
+ let selected = |stable_row: StableRowIndex| {
+ selected_span(&sel, stable_row, self.rectangular, self.dims.cols)
+ };
+ let mut spans = Vec::with_capacity(lines.len() + 2);
+ spans.push(0..0);
+ spans.extend(
+ (0..lines.len()).map(|line_idx| selected(stable_top + line_idx as StableRowIndex)),
+ );
+ // Past the drawn rows the selection only runs straight on:
+ // the edge cut there is not a corner.
+ if !selected(stable_top - 1).is_empty() {
+ spans[0] = spans[1].clone();
+ }
+ let after = stable_top + lines.len() as StableRowIndex;
+ spans.push(if selected(after).is_empty() {
+ 0..0
+ } else {
+ spans[lines.len()].clone()
+ });
+ spans
+ }
+
fn render_line(
&mut self,
stable_top: StableRowIndex,
line_idx: usize,
line: &&mut Line,
+ selection: RowSelection,
) -> anyhow::Result<()> {
let stable_row = stable_top + line_idx as StableRowIndex;
- let selrange = self
- .selrange
- .map_or(0..0, |sel| sel.cols_for_row(stable_row, self.rectangular));
- // Constrain to the pane width!
- let selrange = selrange.start..selrange.end.min(self.dims.cols);
+ let RowSelection {
+ span: selrange,
+ neighbours: selection_neighbors,
+ text_only: selection_text_only,
+ } = selection;
let (cursor, composing, password_input) = if self.cursor.y == stable_row {
(
@@ -2172,6 +2227,9 @@ impl crate::TermWindow {
font_identity: self.font_identity,
composing: composing.clone(),
selection: selrange.clone(),
+ selection_neighbors: selection_neighbors.clone(),
+ selection_text_only,
+ selection_rounded: self.selection_rounded && !selrange.is_empty(),
cursor,
shape_hash,
top_pixel_y: NotNan::new(self.top_pixel_y).unwrap()
@@ -2265,6 +2323,9 @@ impl crate::TermWindow {
stable_line_idx: Some(stable_row),
line: &line,
selection: selrange.clone(),
+ selection_neighbors: selection_neighbors.clone(),
+ selection_text_only,
+ selection_rounded: self.selection_rounded,
cursor: &self.cursor,
palette: &self.palette,
dims: &self.dims,
@@ -2350,8 +2411,56 @@ impl crate::TermWindow {
impl<'a, 'b> WithPaneLines for LineRender<'a, 'b> {
fn with_lines_mut(&mut self, stable_top: StableRowIndex, lines: &mut [&mut Line]) {
+ self.term_window
+ .find_pending_paste(self.pane_id, stable_top, lines, self.dims.cols);
+ let spans = self.selection_spans(stable_top, lines);
+ let span = |index: usize| spans.get(index).cloned().unwrap_or(0..0);
+ let double = |line_idx: usize| {
+ lines.get(line_idx).is_some_and(|line| !line.is_single_width())
+ };
+ let rows = stable_top..stable_top + lines.len() as StableRowIndex;
+ let blocks = if self.term_window.edge_lights.is_empty() {
+ vec![]
+ } else {
+ // The light's outline counts their cells twice.
+ self.double_width_rows = (0..lines.len())
+ .filter(|line_idx| double(*line_idx))
+ .map(|line_idx| stable_top + line_idx as StableRowIndex)
+ .collect();
+ self.term_window
+ .light_block_spans(self.pane_id, rows, self.dims.cols)
+ };
for (line_idx, line) in lines.iter().enumerate() {
- if let Err(err) = self.render_line(stable_top, line_idx, line) {
+ let own = span(line_idx + 1);
+ let selection = if own.is_empty() {
+ let block = blocks.get(line_idx).cloned().unwrap_or(0..0);
+ RowSelection {
+ text_only: !block.is_empty(),
+ span: block,
+ neighbours: (0..0, 0..0),
+ }
+ } else if !self.selection_rounded {
+ // Square, a row's block is its own alone.
+ RowSelection {
+ span: own,
+ neighbours: (0..0, 0..0),
+ text_only: false,
+ }
+ } else {
+ let above = span(line_idx);
+ let below = span(line_idx + 2);
+ RowSelection {
+ neighbours: drawn_neighbours(
+ &own,
+ (&above, line_idx > 0 && double(line_idx - 1)),
+ (&below, double(line_idx + 1)),
+ double(line_idx),
+ ),
+ span: own,
+ text_only: false,
+ }
+ };
+ if let Err(err) = self.render_line(stable_top, line_idx, line, selection) {
self.error.replace(err);
return;
}
@@ -2372,6 +2481,41 @@ impl crate::TermWindow {
return Err(error).context("error while calling with_lines_mut");
}
+ // The light round copied or pasted text, over the rows, cut to
+ // the pane like they are; where it would run past the pane's
+ // edge it runs just inside it.
+ if !render.term_window.edge_lights.is_empty() {
+ let mut lights = HeapQuadAllocator::default();
+ let area = LightArea {
+ rows: stable_range.clone(),
+ origin: (left_pixel_x, pane_top_pixel_y - scroll_px),
+ cell: (
+ pane_render_metrics.cell_size.width as f32,
+ pane_render_metrics.cell_size.height as f32,
+ ),
+ cols: render_dims.cols,
+ bounds: (
+ left_pixel_x,
+ content_top,
+ left_pixel_x
+ + render_dims.cols as f32 * pane_render_metrics.cell_size.width as f32,
+ pane_top_pixel_y
+ + render_dims.viewport_rows as f32
+ * pane_render_metrics.cell_size.height as f32,
+ ),
+ double_width: std::mem::take(&mut render.double_width_rows),
+ rounded: render.selection_rounded,
+ };
+ render.term_window.paint_edge_lights(
+ &mut TripleLayerQuadAllocator::Heap(&mut lights),
+ pane_id,
+ &area,
+ selection_bg,
+ default_bg,
+ )?;
+ lights.apply_to_clipped_at(render.layers, 0.0, 0.0, render.pane_clip, 1.0)?;
+ }
+
// The overlay scrollbar goes on after the text it sits over.
if !render.term_window.show_scroll_bar && crate::native_settings::overlay_scrollbar() {
let content_bottom = pane_top_pixel_y
diff --git a/wezterm-gui/src/termwindow/render/screen_line.rs b/wezterm-gui/src/termwindow/render/screen_line.rs
index ec080756..8e07ffd6 100644
--- a/wezterm-gui/src/termwindow/render/screen_line.rs
+++ b/wezterm-gui/src/termwindow/render/screen_line.rs
@@ -311,16 +311,24 @@ impl crate::TermWindow {
let selection_pixel_range = if !params.selection.is_empty() {
let start = params.left_pixel_x + (params.selection.start as f32 * cell_width);
let width = (params.selection.end - params.selection.start) as f32 * cell_width;
- let mut quad = self
- .filled_rectangle(
+ // This row's piece of the one rounded shape the selection makes;
+ // none where a light draws the block (fading out) itself.
+ if !params.selection_text_only {
+ self.paint_selection_row(
layers,
0,
- euclid::rect(start, params.top_pixel_y, width, cell_height),
+ params.left_pixel_x,
+ params.top_pixel_y,
+ cell_width,
+ cell_height,
+ &params.selection,
+ &params.selection_neighbors,
params.selection_bg,
+ params.selection_rounded,
+ hsv,
)
- .context("filled_rectangle")?;
-
- quad.set_hsv(hsv);
+ .context("paint_selection_row")?;
+ }
start..start + width
} else {
diff --git a/wezterm-gui/src/termwindow/render/selection_shape.rs b/wezterm-gui/src/termwindow/render/selection_shape.rs
new file mode 100644
index 00000000..c4f06b82
--- /dev/null
+++ b/wezterm-gui/src/termwindow/render/selection_shape.rs
@@ -0,0 +1,642 @@
+//! The selection drawn as one rounded shape instead of a strip per row.
+//!
+//! Each row paints its own part from three spans -- its own and its two
+//! neighbours' -- so the line quad cache keeps working row by row. A corner
+//! with nothing beyond it is rounded outward; where a neighbour reaches
+//! further, the corner between them gets an inward curve, painted within
+//! this row's height just outside its span.
+
+use crate::quad::{QuadTrait, TripleLayerQuadAllocator};
+use crate::selection::SelectionRange;
+use crate::termwindow::render::corners::{
+ BOTTOM_LEFT_ROUNDED_CORNER, BOTTOM_LEFT_ROUNDED_CORNER_MASK, BOTTOM_RIGHT_ROUNDED_CORNER,
+ BOTTOM_RIGHT_ROUNDED_CORNER_MASK, TOP_LEFT_ROUNDED_CORNER, TOP_LEFT_ROUNDED_CORNER_MASK,
+ TOP_RIGHT_ROUNDED_CORNER, TOP_RIGHT_ROUNDED_CORNER_MASK,
+};
+use config::HsbTransform;
+use std::ops::Range;
+use termwiz::color::LinearRgba;
+use wezterm_term::StableRowIndex;
+
+/// Corner indices: the right corner of a side is the one after its left.
+const TOP_LEFT: usize = 0;
+const BOTTOM_LEFT: usize = 2;
+
+/// The columns of `row` that `selection` covers, cut to the `cols` drawn:
+/// the one rule the selection and the light round it are both drawn by.
+pub fn selected_span(
+ selection: &SelectionRange,
+ row: StableRowIndex,
+ rectangular: bool,
+ cols: usize,
+) -> Range<usize> {
+ let span = selection.cols_for_row(row, rectangular);
+ let end = span.end.min(cols);
+ span.start.min(end)..end
+}
+
+/// The neighbours a row's part of the shape is drawn against: none round an
+/// empty row, and its own span on a side where it or the neighbour is of
+/// double width -- their cells do not line up, so the edge runs straight.
+pub fn drawn_neighbours(
+ own: &Range<usize>,
+ above: (&Range<usize>, bool),
+ below: (&Range<usize>, bool),
+ double: bool,
+) -> (Range<usize>, Range<usize>) {
+ if own.is_empty() {
+ return (0..0, 0..0);
+ }
+ let side = |(span, neighbour_double): (&Range<usize>, bool)| {
+ if double || neighbour_double {
+ own.clone()
+ } else {
+ span.clone()
+ }
+ };
+ (side(above), side(below))
+}
+
+/// What each corner of a row's span does, as top left, top right, bottom
+/// left, bottom right.
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
+pub struct RowCorners {
+ /// Rounded outward: the shape does not go on past it.
+ pub round: [bool; 4],
+ /// The neighbour on that side reaches past this end of the span: an
+ /// inward curve just outside it. Neither means the edge runs straight on.
+ pub inward: [bool; 4],
+}
+
+pub fn row_corners(row: &Range<usize>, above: &Range<usize>, below: &Range<usize>) -> RowCorners {
+ let mut corners = RowCorners::default();
+ if row.is_empty() {
+ return corners;
+ }
+ let covers = |span: &Range<usize>, col: usize| span.start <= col && col < span.end;
+ // Inward only where the neighbour runs on past this end AND over it: a
+ // neighbour that merely touches the corner leaves two pieces, each
+ // rounded there, as the light's outline has them.
+ for (left, neighbour) in [(TOP_LEFT, above), (BOTTOM_LEFT, below)] {
+ let right = left + 1;
+ if row.start > 0 && covers(neighbour, row.start - 1) && covers(neighbour, row.start) {
+ corners.inward[left] = true;
+ } else if !covers(neighbour, row.start) {
+ corners.round[left] = true;
+ }
+ if covers(neighbour, row.end) && covers(neighbour, row.end - 1) {
+ corners.inward[right] = true;
+ } else if !covers(neighbour, row.end - 1) {
+ corners.round[right] = true;
+ }
+ }
+ corners
+}
+
+/// The radius of the selection's corners: a quarter of a row, but never
+/// more than half a cell, so the inward curve beside a one-cell step fits.
+pub fn corner_radius(cell_width: f32, cell_height: f32) -> f32 {
+ (cell_height * 0.25).min(cell_width * 0.5).floor()
+}
+
+/// One stretch of an outline: a straight edge, or the arc round a corner.
+#[derive(Debug, Clone, Copy, PartialEq)]
+enum Stretch {
+ Line { from: (f32, f32), to: (f32, f32) },
+ Arc { center: (f32, f32), radius: f32, from_angle: f32, sweep: f32 },
+}
+
+impl Stretch {
+ fn length(&self) -> f32 {
+ match *self {
+ Stretch::Line { from, to } => (to.0 - from.0).hypot(to.1 - from.1),
+ Stretch::Arc { radius, sweep, .. } => radius * sweep.abs(),
+ }
+ }
+
+ fn point_at(&self, along: f32) -> (f32, f32) {
+ let length = self.length();
+ let t = if length > 0. { (along / length).clamp(0., 1.) } else { 0. };
+ match *self {
+ Stretch::Line { from, to } => (from.0 + (to.0 - from.0) * t, from.1 + (to.1 - from.1) * t),
+ Stretch::Arc { center, radius, from_angle, sweep } => {
+ let angle = from_angle + sweep * t;
+ (center.0 + radius * angle.cos(), center.1 + radius * angle.sin())
+ }
+ }
+ }
+}
+
+/// The rounded outline of one connected piece of a selection, clockwise
+/// from the middle of the first row's left side.
+#[derive(Debug, Clone, PartialEq)]
+pub struct Outline {
+ stretches: Vec<Stretch>,
+ /// The distance along the outline at which each stretch ends.
+ ends: Vec<f32>,
+ /// Where lights running down both sides meet: the middle of the last
+ /// row's right side.
+ pub meet: f32,
+ /// The left and right edges, for colouring along the width.
+ pub x_range: (f32, f32),
+}
+
+impl Outline {
+ pub fn length(&self) -> f32 {
+ self.ends.last().copied().unwrap_or(0.)
+ }
+
+ /// The point `along` the outline from its start; past either end it
+ /// goes on round, as the outline is closed.
+ pub fn point_at(&self, along: f32) -> (f32, f32) {
+ let total = self.length();
+ if total <= 0. {
+ return self.stretches.first().map_or((0., 0.), |s| s.point_at(0.));
+ }
+ let along = along.rem_euclid(total);
+ let index = self.ends.partition_point(|end| *end < along).min(self.stretches.len() - 1);
+ let start = if index == 0 { 0. } else { self.ends[index - 1] };
+ self.stretches[index].point_at(along - start)
+ }
+
+ /// The outlines of the shape `spans` make, one row of `cell` size each
+ /// from `origin` down, drawn `inset` inside its edge, its rows first cut
+ /// to `within` (left, top, right, bottom): one per connected piece (rows
+ /// whose spans do not overlap the next row's start a new one). `cut`
+ /// says the shape runs on above the first row and below the last, past
+ /// what is drawn: its corners there are square, as the selection's are.
+ pub fn of_rows(
+ spans: &[Range<usize>],
+ origin: (f32, f32),
+ cell: (f32, f32),
+ radius: f32,
+ inset: f32,
+ within: (f32, f32, f32, f32),
+ cut: (bool, bool),
+ ) -> Vec<Outline> {
+ // Each row as (left, right, top, bottom), or none where nothing of
+ // it is left inside `within`.
+ let rows: Vec<Option<(f32, f32, f32, f32)>> = spans
+ .iter()
+ .enumerate()
+ .map(|(row, span)| {
+ let top = origin.1 + row as f32 * cell.1;
+ let edges = (
+ (origin.0 + span.start as f32 * cell.0).max(within.0),
+ (origin.0 + span.end as f32 * cell.0).min(within.2),
+ top.max(within.1),
+ (top + cell.1).min(within.3),
+ );
+ if span.is_empty() || edges.0 >= edges.1 || edges.2 >= edges.3 {
+ None
+ } else {
+ Some(edges)
+ }
+ })
+ .collect();
+ let mut outlines = vec![];
+ let mut first = 0;
+ while first < rows.len() {
+ if rows[first].is_none() {
+ first += 1;
+ continue;
+ }
+ let mut last = first;
+ while let (Some(a), Some(Some(b))) = (rows[last], rows.get(last + 1)) {
+ if a.0.max(b.0) >= a.1.min(b.1) {
+ break;
+ }
+ last += 1;
+ }
+ let piece: Vec<(f32, f32, f32, f32)> = rows[first..=last].iter().flatten().copied().collect();
+ let square = (cut.0 && first == 0, cut.1 && last + 1 == rows.len());
+ outlines.push(Self::of_piece(&piece, radius, inset, square));
+ first = last + 1;
+ }
+ outlines
+ }
+
+ /// `rows` as (left, right, top, bottom), each overlapping the next; the
+ /// corners of the first row's top and the last row's bottom square as
+ /// `square` says.
+ fn of_piece(
+ rows: &[(f32, f32, f32, f32)],
+ radius: f32,
+ inset: f32,
+ square: (bool, bool),
+ ) -> Outline {
+ let n = rows.len();
+ let (x0, x1, y0, y1) = (|r: usize| rows[r].0, |r: usize| rows[r].1, |r: usize| rows[r].2, |r: usize| rows[r].3);
+ // The corners, clockwise from the top left.
+ let mut corners = vec![(x0(0), y0(0)), (x1(0), y0(0))];
+ for row in 0..n - 1 {
+ if x1(row + 1) != x1(row) {
+ corners.push((x1(row), y1(row)));
+ corners.push((x1(row + 1), y1(row)));
+ }
+ }
+ let bottom_right = corners.len();
+ corners.push((x1(n - 1), y1(n - 1)));
+ corners.push((x0(n - 1), y1(n - 1)));
+ for row in (1..n).rev() {
+ if x0(row - 1) != x0(row) {
+ corners.push((x0(row), y0(row)));
+ corners.push((x0(row - 1), y0(row)));
+ }
+ }
+ let count = corners.len();
+ let unit = |from: (f32, f32), to: (f32, f32)| {
+ let length = (to.0 - from.0).hypot(to.1 - from.1);
+ ((to.0 - from.0) / length, (to.1 - from.1) / length, length)
+ };
+ // Inset: every edge moves inward, to the right of the way it runs
+ // (clockwise, y down), and each corner to where its two edges meet.
+ let corners: Vec<(f32, f32)> = (0..count)
+ .map(|i| {
+ let (prev, here, next) = (corners[(i + count - 1) % count], corners[i], corners[(i + 1) % count]);
+ let (ix, iy, _) = unit(prev, here);
+ let (ox, oy, _) = unit(here, next);
+ (here.0 + (-iy - oy) * inset, here.1 + (ix + ox) * inset)
+ })
+ .collect();
+ // Each corner becomes an arc between points this far along its edges:
+ // from `a` to `b` round `center`, `r` out.
+ struct Turn {
+ a: (f32, f32),
+ b: (f32, f32),
+ center: (f32, f32),
+ r: f32,
+ }
+ let turns: Vec<Turn> = (0..count)
+ .map(|i| {
+ let (prev, here, next) = (corners[(i + count - 1) % count], corners[i], corners[(i + 1) % count]);
+ let (ix, iy, in_len) = unit(prev, here);
+ let (ox, oy, out_len) = unit(here, next);
+ // Drawn `inset` in, an outer corner's curve tightens by that
+ // much and an inner one's widens, so both stay concentric
+ // with the shape's own; out (a negative inset) the other way
+ // round, an inner curve kept to at least half its radius.
+ let turns_right = ix * oy - iy * ox > 0.;
+ let r = if turns_right { radius - inset } else { radius + inset };
+ let r = r.max(radius * 0.5).min(in_len / 2.).min(out_len / 2.);
+ let cut_here = (square.0 && i < 2)
+ || (square.1 && (i == bottom_right || i == bottom_right + 1));
+ let r = if cut_here { 0. } else { r };
+ let a = (here.0 - ix * r, here.1 - iy * r);
+ let b = (here.0 + ox * r, here.1 + oy * r);
+ // The edges meet square, so the centre is `r` from `a`
+ // towards where the outline turns.
+ let center = (a.0 + ox * r, a.1 + oy * r);
+ Turn { a, b, center, r }
+ })
+ .collect();
+
+ let start = (x0(0) + inset, (y0(0) + y1(0)) / 2.);
+ let meet_point = (x1(n - 1) - inset, (y0(n - 1) + y1(n - 1)) / 2.);
+ let mut stretches = vec![];
+ let mut ends = vec![];
+ let mut total = 0.;
+ let mut meet = 0.;
+ let mut push = |stretch: Stretch, stretches: &mut Vec<Stretch>, ends: &mut Vec<f32>| {
+ total += stretch.length();
+ stretches.push(stretch);
+ ends.push(total);
+ total
+ };
+ let mut at = start;
+ for (i, &Turn { a, b, center, r }) in turns.iter().enumerate() {
+ let before = push(Stretch::Line { from: at, to: a }, &mut stretches, &mut ends);
+ if i == bottom_right {
+ // The meeting point is on the edge that ends here.
+ meet = before - (a.0 - meet_point.0).hypot(a.1 - meet_point.1);
+ }
+ if r > 0. {
+ let from_angle = (a.1 - center.1).atan2(a.0 - center.0);
+ let to_angle = (b.1 - center.1).atan2(b.0 - center.0);
+ let mut sweep = to_angle - from_angle;
+ if sweep > std::f32::consts::PI {
+ sweep -= 2. * std::f32::consts::PI;
+ } else if sweep < -std::f32::consts::PI {
+ sweep += 2. * std::f32::consts::PI;
+ }
+ push(Stretch::Arc { center, radius: r, from_angle, sweep }, &mut stretches, &mut ends);
+ }
+ at = b;
+ }
+ push(Stretch::Line { from: at, to: start }, &mut stretches, &mut ends);
+ let x_range = rows.iter().fold((f32::MAX, f32::MIN), |(lo, hi), r| (lo.min(r.0), hi.max(r.1)));
+ Outline {
+ stretches,
+ ends,
+ meet,
+ x_range,
+ }
+ }
+}
+
+impl crate::TermWindow {
+ /// Paint one row's part of the selection, `span` in cells from
+ /// `left_x`, in the row whose top is `top_y`; unless `rounded`, the
+ /// plain block it always was.
+ #[allow(clippy::too_many_arguments)]
+ pub fn paint_selection_row(
+ &self,
+ layers: &mut TripleLayerQuadAllocator,
+ layer: usize,
+ left_x: f32,
+ top_y: f32,
+ cell_width: f32,
+ cell_height: f32,
+ span: &Range<usize>,
+ neighbours: &(Range<usize>, Range<usize>),
+ color: LinearRgba,
+ rounded: bool,
+ hsv: Option<HsbTransform>,
+ ) -> anyhow::Result<()> {
+ if span.is_empty() {
+ return Ok(());
+ }
+ let x0 = left_x + span.start as f32 * cell_width;
+ let x1 = left_x + span.end as f32 * cell_width;
+ let y0 = top_y;
+ let y1 = top_y + cell_height;
+ let r = if rounded { corner_radius(cell_width, cell_height) } else { 0. };
+ let fill = |layers: &mut TripleLayerQuadAllocator, x: f32, y: f32, w: f32, h: f32| {
+ if w > 0. && h > 0. {
+ self.filled_rectangle(layers, layer, euclid::rect(x, y, w, h), color)?
+ .set_hsv(hsv);
+ }
+ anyhow::Ok(())
+ };
+ if r < 1. {
+ return fill(layers, x0, y0, x1 - x0, cell_height);
+ }
+
+ let corners = row_corners(span, &neighbours.0, &neighbours.1);
+ // The middle, the sides between the corners, then the corners.
+ fill(layers, x0 + r, y0, x1 - x0 - 2. * r, cell_height)?;
+ fill(layers, x0, y0 + r, r, cell_height - 2. * r)?;
+ fill(layers, x1 - r, y0 + r, r, cell_height - 2. * r)?;
+ let size = euclid::size2(r, r);
+ let corner_at = [(x0, y0), (x1 - r, y0), (x0, y1 - r), (x1 - r, y1 - r)];
+ let rounded = [
+ TOP_LEFT_ROUNDED_CORNER,
+ TOP_RIGHT_ROUNDED_CORNER,
+ BOTTOM_LEFT_ROUNDED_CORNER,
+ BOTTOM_RIGHT_ROUNDED_CORNER,
+ ];
+ for (corner, (&(x, y), shape)) in corner_at.iter().zip(rounded).enumerate() {
+ if corners.round[corner] {
+ let mut quad = self.poly_quad(layers, layer, euclid::point2(x, y), shape, 0, size, color)?;
+ quad.set_grayscale();
+ quad.set_hsv(hsv);
+ } else {
+ fill(layers, x, y, r, r)?;
+ }
+ }
+ // Each inward curve sits in the square beside the span whose corner
+ // touching the span is the vertex: the wedge in that corner of it.
+ let inward_at = [
+ ((x0 - r, y0), TOP_RIGHT_ROUNDED_CORNER_MASK),
+ ((x1, y0), TOP_LEFT_ROUNDED_CORNER_MASK),
+ ((x0 - r, y1 - r), BOTTOM_RIGHT_ROUNDED_CORNER_MASK),
+ ((x1, y1 - r), BOTTOM_LEFT_ROUNDED_CORNER_MASK),
+ ];
+ for (&inward, &((x, y), wedge)) in corners.inward.iter().zip(&inward_at) {
+ if inward {
+ let mut quad = self.poly_quad(layers, layer, euclid::point2(x, y), wedge, 0, size, color)?;
+ quad.set_grayscale();
+ quad.set_hsv(hsv);
+ }
+ }
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// No pane edge anywhere near.
+ const OPEN: (f32, f32, f32, f32) = (f32::MIN, f32::MIN, f32::MAX, f32::MAX);
+ /// The whole shape is drawn: nothing runs on past it.
+ const WHOLE: (bool, bool) = (false, false);
+
+ fn round(c: RowCorners) -> [bool; 4] {
+ c.round
+ }
+
+ fn close(a: (f32, f32), b: (f32, f32)) -> bool {
+ (a.0 - b.0).abs() < 0.01 && (a.1 - b.1).abs() < 0.01
+ }
+
+ #[test]
+ fn the_outline_of_one_row_goes_round_its_rounded_box() {
+ // Cells of 10x20 from the origin, columns 1..5: a box 40 wide at x 10.
+ let outlines = Outline::of_rows(&[1..5], (0., 0.), (10., 20.), 4., 0., OPEN, WHOLE);
+ assert_eq!(outlines.len(), 1);
+ let outline = &outlines[0];
+ // A 40x20 box with corners of 4: the straight parts plus a circle.
+ let expected = 2. * (40. - 8.) + 2. * (20. - 8.) + 2. * std::f32::consts::PI * 4.;
+ assert!((outline.length() - expected).abs() < 0.01, "{}", outline.length());
+ // It starts in the middle of the left side and goes up first.
+ assert!(close(outline.point_at(0.), (10., 10.)));
+ assert!(close(outline.point_at(6.), (10., 4.)));
+ // Lights down both sides meet in the middle of the right side,
+ // exactly half way round a symmetric box.
+ assert!((outline.meet - expected / 2.).abs() < 0.01);
+ assert!(close(outline.point_at(outline.meet), (50., 10.)));
+ // Closed: going on past the end comes round again.
+ assert!(close(outline.point_at(outline.length() + 6.), (10., 4.)));
+ assert_eq!(outline.x_range, (10., 50.));
+ }
+
+ #[test]
+ fn a_staircase_is_one_outline_and_rows_apart_are_two() {
+ let staircase = Outline::of_rows(&[5..10, 0..12, 0..7], (0., 0.), (10., 20.), 4., 0., OPEN, WHOLE);
+ assert_eq!(staircase.len(), 1);
+ // Every point of it is on the shape's edge, inside its bounds.
+ let outline = &staircase[0];
+ let mut along = 0.;
+ while along < outline.length() {
+ let (x, y) = outline.point_at(along);
+ assert!((0. ..=120.).contains(&x) && (0. ..=60.).contains(&y), "{},{}", x, y);
+ along += 1.;
+ }
+ assert!(close(outline.point_at(outline.meet), (70., 50.)));
+
+ // The second row ends before the first starts: they do not touch.
+ let apart = Outline::of_rows(&[8..12, 0..3], (0., 0.), (10., 20.), 4., 0., OPEN, WHOLE);
+ assert_eq!(apart.len(), 2);
+ // An empty row in between splits a selection too.
+ assert_eq!(Outline::of_rows(&[0..4, 0..0, 0..4], (0., 0.), (10., 20.), 4., 0., OPEN, WHOLE).len(), 2);
+ }
+
+ #[test]
+ fn an_inset_outline_runs_inside_the_shape() {
+ let outline = &Outline::of_rows(&[5..10, 0..12, 0..7], (0., 0.), (10., 20.), 4., 1., OPEN, WHOLE)[0];
+ assert!(close(outline.point_at(0.), (51., 10.)));
+ assert!(close(outline.point_at(outline.meet), (69., 50.)));
+ // A point on every straight part is one pixel in from the edge: the
+ // top of the first row is now at y 1.
+ let top = (0..outline.length() as usize)
+ .map(|along| outline.point_at(along as f32).1)
+ .fold(f32::MAX, f32::min);
+ assert!((top - 1.).abs() < 0.01, "{}", top);
+ }
+
+ #[test]
+ fn a_row_alone_is_rounded_all_round() {
+ let c = row_corners(&(3..9), &(0..0), &(0..0));
+ assert_eq!(round(c), [true; 4]);
+ assert_eq!(c.inward, [false; 4]);
+ }
+
+ #[test]
+ fn rows_of_a_staircase_meet_with_inward_curves() {
+ // First row from column 5, the next from 0 to 12, the last to 7:
+ // ┌─────┐
+ // ┌──┘ └─┐
+ // └──────┐ ┌─┘ (the last row ends before the middle one)
+ let first = 5..10;
+ let middle = 0..12;
+ let last = 0..7;
+ let c = row_corners(&first, &(0..0), &middle);
+ assert_eq!(round(c), [true, true, false, false]);
+ // The middle row reaches past both ends below.
+ assert_eq!(c.inward, [false, false, true, true]);
+
+ let c = row_corners(&middle, &first, &last);
+ // Above, it reaches past the first row: its own top corners are
+ // the outer ones. Below, it shares the left edge with the last row
+ // and reaches past it on the right.
+ assert_eq!(round(c), [true, true, false, true]);
+ assert_eq!(c.inward, [false; 4]);
+
+ let c = row_corners(&last, &middle, &(0..0));
+ assert_eq!(round(c), [false, false, true, true]);
+ assert_eq!(c.inward, [false, true, false, false]);
+ }
+
+ #[test]
+ fn rows_that_only_touch_at_a_corner_are_two_rounded_pieces() {
+ // From column 10 of one row to column 9 of the next.
+ let first = 10..80;
+ let second = 0..10;
+ let c = row_corners(&first, &(0..0), &second);
+ assert_eq!(round(c), [true; 4]);
+ assert_eq!(c.inward, [false; 4]);
+ let c = row_corners(&second, &first, &(0..0));
+ assert_eq!(round(c), [true; 4]);
+ assert_eq!(c.inward, [false; 4]);
+ assert_eq!(Outline::of_rows(&[first, second], (0., 0.), (10., 20.), 4., 0., OPEN, WHOLE).len(), 2);
+ }
+
+ #[test]
+ fn a_classic_selection_is_one_staircase() {
+ // From column 30 to the end, two whole rows, then up to column 12.
+ let rows = [30..80, 0..80, 0..80, 0..12];
+ let c = row_corners(&rows[0], &(0..0), &rows[1]);
+ assert_eq!(round(c), [true, true, false, false]);
+ assert_eq!(c.inward, [false, false, true, false]);
+ let c = row_corners(&rows[3], &rows[2], &(0..0));
+ assert_eq!(round(c), [false, false, true, true]);
+ assert_eq!(c.inward, [false, true, false, false]);
+ assert_eq!(Outline::of_rows(&rows, (0., 0.), (10., 20.), 4., 0., OPEN, WHOLE).len(), 1);
+ }
+
+ #[test]
+ fn a_straight_edge_is_no_corner() {
+ let c = row_corners(&(2..8), &(2..8), &(2..8));
+ assert_eq!(c, RowCorners::default());
+ }
+
+ #[test]
+ fn corners_fit_a_one_cell_step() {
+ assert_eq!(corner_radius(8., 17.), 4.);
+ assert_eq!(corner_radius(17., 34.), 8.);
+ assert_eq!(corner_radius(5., 30.), 2.);
+ }
+
+ #[test]
+ fn an_outline_cut_to_the_pane_runs_inside_its_edges() {
+ // A pane of 8x3 cells of 10x20; the line one pixel out from the
+ // block, cut two pixels in from the pane's edges as the light is.
+ let outline =
+ &Outline::of_rows(&[0..8, 0..8, 0..3], (0., 0.), (10., 20.), 4., -1., (2., 2., 78., 58.), WHOLE)[0];
+ let mut along = 0.;
+ while along < outline.length() {
+ let (x, y) = outline.point_at(along);
+ assert!((1. ..=79.).contains(&x) && (1. ..=59.).contains(&y), "{},{}", x, y);
+ along += 1.;
+ }
+ // Along the pane's left edge it is inside the block (from the middle
+ // of the first row's part inside the pane); where the last row ends,
+ // short of the edge, it is out past the block as usual.
+ assert!(close(outline.point_at(0.), (1., 11.)));
+ assert!(close(outline.point_at(outline.meet), (31., 49.)));
+ }
+
+ #[test]
+ fn a_row_with_nothing_inside_the_pane_is_left_out() {
+ // The first row is all above the top: the outline is the second's.
+ let outlines = Outline::of_rows(&[0..4, 0..4], (0., 0.), (10., 20.), 4., 0., (-100., 25., 100., 100.), WHOLE);
+ assert_eq!(outlines.len(), 1);
+ let top = (0..outlines[0].length() as usize)
+ .map(|along| outlines[0].point_at(along as f32).1)
+ .fold(f32::MAX, f32::min);
+ assert!((top - 25.).abs() < 0.01, "{}", top);
+ // Nothing of either left: no outline at all.
+ assert!(Outline::of_rows(&[0..4, 0..4], (0., 0.), (10., 20.), 4., 0., (50., 0., 100., 100.), WHOLE).is_empty());
+ }
+
+ #[test]
+ fn the_selected_span_is_cut_to_the_columns_drawn() {
+ use crate::selection::SelectionCoordinate;
+ // Made backwards, from column 5 of row 12 up to column 3 of row 10.
+ let selection = SelectionRange {
+ start: SelectionCoordinate::x_y(5, 12),
+ end: SelectionCoordinate::x_y(3, 10),
+ }
+ .normalize();
+ assert_eq!(selected_span(&selection, 10, false, 80), 3..80);
+ assert_eq!(selected_span(&selection, 11, false, 80), 0..80);
+ assert_eq!(selected_span(&selection, 12, false, 80), 0..6);
+ assert_eq!(selected_span(&selection, 13, false, 80), 0..0);
+ // Uncut, it runs to the end of the row.
+ assert_eq!(selected_span(&selection, 11, false, usize::MAX), 0..usize::MAX);
+ // A selection starting past the columns drawn shows nothing there.
+ let wide = SelectionRange {
+ start: SelectionCoordinate::x_y(90, 10),
+ end: SelectionCoordinate::x_y(95, 10),
+ };
+ assert!(selected_span(&wide, 10, false, 80).is_empty());
+ }
+
+ #[test]
+ fn a_shape_cut_off_by_the_screen_has_square_corners_there() {
+ // A 40x20 box with corners of 4, running on above it: square at the
+ // top, rounded at the bottom.
+ let cut_top = &Outline::of_rows(&[1..5], (0., 0.), (10., 20.), 4., 0., OPEN, (true, false))[0];
+ let quarter_saved = 2. * 4. - std::f32::consts::FRAC_PI_2 * 4.;
+ let whole_box = 2. * (40. + 20.);
+ assert!((cut_top.length() - (whole_box - 2. * quarter_saved)).abs() < 0.01, "{}", cut_top.length());
+ // The corner itself is on it.
+ assert!((0..cut_top.length() as usize).any(|along| close(cut_top.point_at(along as f32), (10., 0.))));
+ // Running on both ways, the box's own four sides.
+ let both = &Outline::of_rows(&[1..5], (0., 0.), (10., 20.), 4., 0., OPEN, (true, true))[0];
+ assert!((both.length() - whole_box).abs() < 0.01, "{}", both.length());
+ }
+
+ #[test]
+ fn rows_beside_a_double_width_row_meet_it_straight() {
+ let (own, above, below) = (2..8, 0..10, 4..6);
+ assert_eq!(drawn_neighbours(&own, (&above, false), (&below, false), false), (0..10, 4..6));
+ // The row itself double: its own span both ways, a plain box.
+ assert_eq!(drawn_neighbours(&own, (&above, false), (&below, false), true), (2..8, 2..8));
+ // The neighbour below double: straight on that side only.
+ assert_eq!(drawn_neighbours(&own, (&above, false), (&below, true), false), (0..10, 2..8));
+ // An empty row has no shape to draw against anything.
+ assert_eq!(drawn_neighbours(&(0..0), (&above, false), (&below, false), false), (0..0, 0..0));
+ }
+}
diff --git a/wezterm-gui/src/termwindow/render/tab_bar.rs b/wezterm-gui/src/termwindow/render/tab_bar.rs
index 25a90fb4..424c221a 100644
--- a/wezterm-gui/src/termwindow/render/tab_bar.rs
+++ b/wezterm-gui/src/termwindow/render/tab_bar.rs
@@ -189,6 +189,9 @@ impl crate::TermWindow {
stable_line_idx: None,
line: self.terminal_bar.line(),
selection: 0..0,
+ selection_neighbors: (0..0, 0..0),
+ selection_text_only: false,
+ selection_rounded: false,
cursor: &Default::default(),
palette: &palette,
dims: &RenderableDimensions {
diff --git a/wezterm-gui/src/termwindow/selection.rs b/wezterm-gui/src/termwindow/selection.rs
index c93377cf..0e8c350f 100644
--- a/wezterm-gui/src/termwindow/selection.rs
+++ b/wezterm-gui/src/termwindow/selection.rs
@@ -133,6 +133,9 @@ impl super::TermWindow {
.unwrap_or(SelectionCoordinate::x_y(x, y));
self.selection(pane.pane_id()).origin = Some(origin);
self.selection(pane.pane_id()).rectangular = mode == SelectionMode::Block;
+ // Its range runs from the origin to the pointer, which says
+ // which way it went.
+ self.selection(pane.pane_id()).backwards = false;
// Compute the start and end horizontall cell of the selection.
// The selection extent depends on the mouse cursor position in relation
@@ -194,6 +197,8 @@ impl super::TermWindow {
let selection_range = start_word.extend_with(end_word);
self.selection(pane.pane_id()).range = Some(selection_range);
self.selection(pane.pane_id()).rectangular = false;
+ self.selection(pane.pane_id()).backwards = (end_word.start.y, end_word.start.x)
+ < (start_word.start.y, start_word.start.x);
}
SelectionMode::Line => {
let end_line = SelectionRange::line_around(SelectionCoordinate::x_y(x, y), &**pane);
@@ -208,6 +213,7 @@ impl super::TermWindow {
let selection_range = start_line.extend_with(end_line);
self.selection(pane.pane_id()).range = Some(selection_range);
self.selection(pane.pane_id()).rectangular = false;
+ self.selection(pane.pane_id()).backwards = end_line.start.y < start_line.start.y;
}
SelectionMode::SemanticZone => {
let end_word = SelectionRange::zone_around(SelectionCoordinate::x_y(x, y), &**pane);
@@ -222,6 +228,8 @@ impl super::TermWindow {
let selection_range = start_word.extend_with(end_word);
self.selection(pane.pane_id()).range = Some(selection_range);
self.selection(pane.pane_id()).rectangular = false;
+ self.selection(pane.pane_id()).backwards = (end_word.start.y, end_word.start.x)
+ < (start_word.start.y, start_word.start.x);
}
}
@@ -253,6 +261,7 @@ impl super::TermWindow {
self.selection(pane.pane_id()).origin = Some(start);
self.selection(pane.pane_id()).range = Some(selection_range);
self.selection(pane.pane_id()).rectangular = false;
+ self.selection(pane.pane_id()).backwards = false;
}
SelectionMode::Word => {
let selection_range =
@@ -261,6 +270,7 @@ impl super::TermWindow {
self.selection(pane.pane_id()).origin = Some(selection_range.start);
self.selection(pane.pane_id()).range = Some(selection_range);
self.selection(pane.pane_id()).rectangular = false;
+ self.selection(pane.pane_id()).backwards = false;
}
SelectionMode::SemanticZone => {
let selection_range =
@@ -269,6 +279,7 @@ impl super::TermWindow {
self.selection(pane.pane_id()).origin = Some(selection_range.start);
self.selection(pane.pane_id()).range = Some(selection_range);
self.selection(pane.pane_id()).rectangular = false;
+ self.selection(pane.pane_id()).backwards = false;
}
SelectionMode::Cell | SelectionMode::Block => {
self.selection(pane.pane_id())
diff --git a/wezterm-gui/src/termwindow/ui/context_menu.rs b/wezterm-gui/src/termwindow/ui/context_menu.rs
index 9ebed6c4..f11139c3 100644
--- a/wezterm-gui/src/termwindow/ui/context_menu.rs
+++ b/wezterm-gui/src/termwindow/ui/context_menu.rs
@@ -603,7 +603,19 @@ impl crate::TermWindow {
}
self.dismiss_fallback_context_menu();
context.invalidate();
- false
+ // A right click goes on to open the menu of whatever it is on
+ // -- a tab, a sidebar row, or a terminal set to show its menu --
+ // where it is. One on a terminal that would paste or copy
+ // only closes this one.
+ let on_terminal = self.resolve_ui_item(event).is_none();
+ if !on_terminal
+ || crate::termwindow::mouseevent::right_click_mode(event.modifiers)
+ == crate::native_settings::NativeRightClick::Menu
+ {
+ return false;
+ }
+ self.context_menu_suppressed_release = Some(MousePress::Right);
+ true
}
MouseEventKind::Release(_)
| MouseEventKind::VertWheel(_)
diff --git a/wezterm-gui/src/termwindow/ui/icons.rs b/wezterm-gui/src/termwindow/ui/icons.rs
index 84e517b6..51bf6d08 100644
--- a/wezterm-gui/src/termwindow/ui/icons.rs
+++ b/wezterm-gui/src/termwindow/ui/icons.rs
@@ -24,6 +24,7 @@ pub enum SvgIcon {
ChevronRight,
Cloud,
CodeXml,
+ ClipboardCopy,
ClipboardPaste,
Copy,
Cpu,
@@ -94,6 +95,7 @@ pub enum SvgIcon {
CirclePlus,
SquarePlus,
Square,
+ SquareRoundCorner,
SquareStack,
SquareTerminal,
SplitHorizontal,
@@ -228,6 +230,9 @@ impl SvgIcon {
}
Self::Cloud => include_bytes!("../../../../third_party/lucide/icons/cloud.svg"),
Self::CodeXml => include_bytes!("../../../../third_party/lucide/icons/code-xml.svg"),
+ Self::ClipboardCopy => {
+ include_bytes!("../../../../third_party/lucide/icons/clipboard-copy.svg")
+ }
Self::ClipboardPaste => {
include_bytes!("../../../../third_party/lucide/icons/clipboard-paste.svg")
}
@@ -347,6 +352,9 @@ impl SvgIcon {
include_bytes!("../../../../third_party/lucide/icons/circle-plus.svg")
}
Self::Square => include_bytes!("../../../../third_party/lucide/icons/square.svg"),
+ Self::SquareRoundCorner => {
+ include_bytes!("../../../../third_party/lucide/icons/square-round-corner.svg")
+ }
Self::SquarePlus => {
include_bytes!("../../../../third_party/lucide/icons/square-plus.svg")
}
@@ -903,6 +911,7 @@ mod tests {
SvgIcon::CircleX,
SvgIcon::CirclePlus,
SvgIcon::Square,
+ SvgIcon::SquareRoundCorner,
SvgIcon::SquareTerminal,
SvgIcon::SplitHorizontal,
SvgIcon::SplitVertical,