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.

function update

RoversX05d7b892a111
diff --git a/.gitignore b/.gitignore
index 9ef35b78..1080df2d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -19,6 +19,7 @@ dhat-heap.json
/termwiz/codegen/Cargo.lock
/gh_pages/
/.cache/
+/.soul/
/docs/releases.json
/docs/SUMMARY.md
/docs/cli/cli/index.md
diff --git a/.gitmodules b/.gitmodules
index 677e6c69..5b42f9ed 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -10,3 +10,6 @@
[submodule "freetype2"]
path = deps/freetype/freetype2
url = https://github.com/freetype/freetype2.git
+[submodule "third_party/lucide"]
+ path = third_party/lucide
+ url = https://github.com/lucide-icons/lucide.git
diff --git a/Cargo.lock b/Cargo.lock
index f7d9599f..99632057 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1232,6 +1232,12 @@ version = "2.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a2330da5de22e8a3cb63252ce2abb30116bf5265e89c0e01bc17015ce30a476"
+[[package]]
+name = "data-url"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"
+
[[package]]
name = "deltae"
version = "0.3.2"
@@ -1767,6 +1773,12 @@ dependencies = [
"miniz_oxide 0.8.9",
]
+[[package]]
+name = "float-cmp"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
+
[[package]]
name = "float-cmp"
version = "0.10.0"
@@ -2718,6 +2730,12 @@ dependencies = [
"quick-error",
]
+[[package]]
+name = "imagesize"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "edcd27d72f2f071c64249075f42e205ff93c9a4c5f6c6da53e79ed9f9832c285"
+
[[package]]
name = "imgref"
version = "1.12.0"
@@ -2957,6 +2975,17 @@ dependencies = [
"libc",
]
+[[package]]
+name = "kurbo"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c62026ae44756f8a599ba21140f350303d4f08dcdcc71b5ad9c9bb8128c13c62"
+dependencies = [
+ "arrayvec",
+ "euclid",
+ "smallvec",
+]
+
[[package]]
name = "lab"
version = "0.11.0"
@@ -4153,6 +4182,12 @@ dependencies = [
"siphasher",
]
+[[package]]
+name = "pico-args"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315"
+
[[package]]
name = "pin-project-lite"
version = "0.2.16"
@@ -4345,7 +4380,7 @@ checksum = "a5d19ee57562043d37e82899fade9a22ebab7be9cef5026b07fda9cdd4293573"
dependencies = [
"anstyle",
"difflib",
- "float-cmp",
+ "float-cmp 0.10.0",
"normalize-line-endings",
"predicates-core",
"regex",
@@ -4800,6 +4835,20 @@ dependencies = [
"rgb",
]
+[[package]]
+name = "resvg"
+version = "0.45.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a8928798c0a55e03c9ca6c4c6846f76377427d2c1e1f7e6de3c06ae57942df43"
+dependencies = [
+ "log",
+ "pico-args",
+ "rgb",
+ "svgtypes",
+ "tiny-skia",
+ "usvg",
+]
+
[[package]]
name = "rgb"
version = "0.8.52"
@@ -4829,6 +4878,12 @@ version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3582f63211428f83597b51b2ddb88e2a91a9d52d12831f9d08f5e624e8977422"
+[[package]]
+name = "roxmltree"
+version = "0.20.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"
+
[[package]]
name = "rstest"
version = "0.21.0"
@@ -5284,6 +5339,15 @@ dependencies = [
"quote",
]
+[[package]]
+name = "simplecss"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c"
+dependencies = [
+ "log",
+]
+
[[package]]
name = "siphasher"
version = "1.0.1"
@@ -5488,6 +5552,9 @@ name = "strict-num"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731"
+dependencies = [
+ "float-cmp 0.9.0",
+]
[[package]]
name = "strip-ansi-escapes"
@@ -5537,6 +5604,16 @@ version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0193cc4331cfd2f3d2011ef287590868599a2f33c3e69bc22c1a3d3acf9e02fb"
+[[package]]
+name = "svgtypes"
+version = "0.15.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "68c7541fff44b35860c1a7a47a7cadf3e4a304c457b58f9870d9706ece028afc"
+dependencies = [
+ "kurbo",
+ "siphasher",
+]
+
[[package]]
name = "syn"
version = "1.0.109"
@@ -6305,6 +6382,28 @@ dependencies = [
"wezterm-dynamic",
]
+[[package]]
+name = "usvg"
+version = "0.45.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "80be9b06fbae3b8b303400ab20778c80bbaf338f563afe567cf3c9eea17b47ef"
+dependencies = [
+ "base64 0.22.1",
+ "data-url",
+ "flate2",
+ "imagesize",
+ "kurbo",
+ "log",
+ "pico-args",
+ "roxmltree",
+ "simplecss",
+ "siphasher",
+ "strict-num",
+ "svgtypes",
+ "tiny-skia-path",
+ "xmlwriter",
+]
+
[[package]]
name = "utf8_iter"
version = "1.0.4"
@@ -6919,6 +7018,7 @@ dependencies = [
"ratelim",
"rayon",
"regex",
+ "resvg",
"serde",
"serde_json",
"shared_library",
@@ -7385,6 +7485,7 @@ dependencies = [
"downcast-rs",
"euclid",
"filedescriptor",
+ "foreign-types 0.5.0",
"futures-lite",
"futures-util",
"gl_generator",
@@ -8070,6 +8171,12 @@ version = "0.8.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ae8337f8a065cfc972643663ea4279e04e7256de865aa66fe25cec5fb912d3f"
+[[package]]
+name = "xmlwriter"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
+
[[package]]
name = "yasna"
version = "0.5.2"
diff --git a/Cargo.toml b/Cargo.toml
index 980ebad9..d7991631 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -97,6 +97,7 @@ fixed = "1.23"
fixedbitset = {version="0.4", default-features=false}
flume = "0.11"
fnv = "1.0"
+foreign-types = "0.5"
fontconfig = { path = "deps/fontconfig" }
frecency = { path = "frecency" }
freetype = { path = "deps/freetype" }
@@ -183,6 +184,7 @@ rcgen = "0.12"
regex = "1"
reqwest = "0.12"
resize = "0.5"
+resvg = { version = "0.45.1", default-features = false }
rstest = "0.21"
rusqlite = "0.32"
serde = {version="1.0", default-features=false, features = ["derive"]}
diff --git a/assets/icon/ThinkTerm.icns b/assets/icon/ThinkTerm.icns
new file mode 100644
index 00000000..ca9ccaaf
Binary files /dev/null and b/assets/icon/ThinkTerm.icns differ
diff --git a/assets/icon/ThinkTerm.png b/assets/icon/ThinkTerm.png
new file mode 100644
index 00000000..44f32c66
Binary files /dev/null and b/assets/icon/ThinkTerm.png differ
diff --git a/assets/icon/update.sh b/assets/icon/update.sh
index c166b3c9..f4e0ec23 100755
--- a/assets/icon/update.sh
+++ b/assets/icon/update.sh
@@ -5,6 +5,7 @@ set -x
cd $(git rev-parse --show-toplevel)/assets/icon
src=wezterm-icon.svg
+macos_icns=ThinkTerm.icns
conv_opts="-colors 256 -background none -density 300"
@@ -15,13 +16,20 @@ for dim in 16 32 128 256 512 1024 ; do
# convert is the imagemagick convert utility
convert $conv_opts -border '10%' -bordercolor 'rgba(0,0,0,0)' -resize "!${dim}x${dim}" "$src" "icon_${dim}px.png"
done
-# png2icns is part of the libicns-utils on Fedora systems.
-# It glues together the various png files into a macOS .icns file
-png2icns ../macos/WezTerm.app/Contents/Resources/terminal.icns icon_*px.png
+# Prefer the hand-authored ThinkTerm macOS icon when present.
+# png2icns is part of the libicns-utils on Fedora systems and is kept as a fallback.
+mkdir -p ../macos/ThinkTerm.app/Contents/Resources
+if [ -f "$macos_icns" ]; then
+ cp "$macos_icns" ../macos/ThinkTerm.app/Contents/Resources/ThinkTerm.icns
+ if command -v sips >/dev/null 2>&1 ; then
+ sips -z 512 512 -s format png "$macos_icns" --out ThinkTerm.png
+ fi
+else
+ png2icns ../macos/ThinkTerm.app/Contents/Resources/ThinkTerm.icns icon_*px.png
+fi
# Clean up
rm -f icon_*px.png
# The Windows icon
convert $conv_opts -define icon:auto-resize=256,128,96,64,48,32,16 $src ../windows/terminal.ico
-
diff --git a/assets/macos/WezTerm.app/Contents/Info.plist b/assets/macos/ThinkTerm.app/Contents/Info.plist
similarity index 62%
rename from assets/macos/WezTerm.app/Contents/Info.plist
rename to assets/macos/ThinkTerm.app/Contents/Info.plist
index 36ff95b4..5ac687e1 100644
--- a/assets/macos/WezTerm.app/Contents/Info.plist
+++ b/assets/macos/ThinkTerm.app/Contents/Info.plist
@@ -7,11 +7,11 @@
<key>CFBundleExecutable</key>
<string>wezterm-gui</string>
<key>CFBundleIdentifier</key>
- <string>com.github.wez.wezterm</string>
+ <string>com.roversx.thinkterm</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
- <string>WezTerm</string>
+ <string>ThinkTerm</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
@@ -23,7 +23,7 @@
<key>CFBundleVersion</key>
<string>1</string>
<key>CFBundleIconFile</key>
- <string>terminal.icns</string>
+ <string>ThinkTerm.icns</string>
<key>LSApplicationCategoryType</key>
<string>public.app-category.utilities</string>
<key>NSHighResolutionCapable</key>
@@ -33,35 +33,35 @@
<key>NSSupportsAutomaticGraphicsSwitching</key>
<true/>
<key>CFBundleDisplayName</key>
- <string>WezTerm</string>
+ <string>ThinkTerm</string>
<key>NSRequiresAquaSystemAppearance</key>
<string>NO</string>
<key>NSAppleEventsUsageDescription</key>
- <string>An application launched via WezTerm would like to access AppleScript.</string>
+ <string>An application launched via ThinkTerm would like to access AppleScript.</string>
<key>NSCalendarsUsageDescription</key>
- <string>An application launched via WezTerm would like to access calendar data.</string>
+ <string>An application launched via ThinkTerm would like to access calendar data.</string>
<key>NSCameraUsageDescription</key>
- <string>An application launched via WezTerm would like to access the camera.</string>
+ <string>An application launched via ThinkTerm would like to access the camera.</string>
<key>NSContactsUsageDescription</key>
- <string>An application launched via WezTerm wants to access your contacts.</string>
+ <string>An application launched via ThinkTerm wants to access your contacts.</string>
<key>NSLocationAlwaysUsageDescription</key>
- <string>An application launched via WezTerm would like to access your location information, even in the background.</string>
+ <string>An application launched via ThinkTerm would like to access your location information, even in the background.</string>
<key>NSLocationUsageDescription</key>
- <string>An application launched via WezTerm would like to access your location information.</string>
+ <string>An application launched via ThinkTerm would like to access your location information.</string>
<key>NSLocationWhenInUseUsageDescription</key>
- <string>An application launched via WezTerm would like to access your location information while active.</string>
+ <string>An application launched via ThinkTerm would like to access your location information while active.</string>
<key>NSMicrophoneUsageDescription</key>
- <string>An application launched via WezTerm would like to access your microphone.</string>
+ <string>An application launched via ThinkTerm would like to access your microphone.</string>
<key>NSRemindersUsageDescription</key>
- <string>An application launched via WezTerm would like to access your reminders.</string>
+ <string>An application launched via ThinkTerm would like to access your reminders.</string>
<key>NSDocumentsFolderUsageDescription</key>
- <string>An application launched via WezTerm would like to access your Documents folder.</string>
+ <string>An application launched via ThinkTerm would like to access your Documents folder.</string>
<key>NSDownloadsFolderUsageDescription</key>
- <string>An application launched via WezTerm would like to access your Downloads folder.</string>
+ <string>An application launched via ThinkTerm would like to access your Downloads folder.</string>
<key>NSSystemAdministrationUsageDescription</key>
- <string>An application launched via WezTerm requires elevated permission.</string>
+ <string>An application launched via ThinkTerm requires elevated permission.</string>
<key>NSLocalNetworkUsageDescription</key>
- <string>An application launched via WezTerm would like to access the local network.</string>
+ <string>An application launched via ThinkTerm would like to access the local network.</string>
<key>CFBundleDocumentTypes</key>
<array>
<dict>
@@ -70,7 +70,7 @@
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleTypeIconFile</key>
- <string>terminal.icns</string>
+ <string>ThinkTerm.icns</string>
<key>CFBundleTypeExtensions</key>
<array>
<string>command</string>
diff --git a/assets/macos/ThinkTerm.app/Contents/Resources/ThinkTerm.icns b/assets/macos/ThinkTerm.app/Contents/Resources/ThinkTerm.icns
new file mode 100644
index 00000000..ca9ccaaf
Binary files /dev/null and b/assets/macos/ThinkTerm.app/Contents/Resources/ThinkTerm.icns differ
diff --git a/assets/macos/WezTerm.app/Contents/Resources/terminal.icns b/assets/macos/ThinkTerm.app/Contents/Resources/terminal.icns
similarity index 100%
rename from assets/macos/WezTerm.app/Contents/Resources/terminal.icns
rename to assets/macos/ThinkTerm.app/Contents/Resources/terminal.icns
diff --git a/assets/macos/WezTerm.app/libEGL.dylib b/assets/macos/ThinkTerm.app/libEGL.dylib
similarity index 100%
rename from assets/macos/WezTerm.app/libEGL.dylib
rename to assets/macos/ThinkTerm.app/libEGL.dylib
diff --git a/assets/macos/WezTerm.app/libGLESv1_CM.dylib b/assets/macos/ThinkTerm.app/libGLESv1_CM.dylib
similarity index 100%
rename from assets/macos/WezTerm.app/libGLESv1_CM.dylib
rename to assets/macos/ThinkTerm.app/libGLESv1_CM.dylib
diff --git a/assets/macos/WezTerm.app/libGLESv2.dylib b/assets/macos/ThinkTerm.app/libGLESv2.dylib
similarity index 100%
rename from assets/macos/WezTerm.app/libGLESv2.dylib
rename to assets/macos/ThinkTerm.app/libGLESv2.dylib
diff --git a/ci/deploy.sh b/ci/deploy.sh
index fbe9c152..7b8f2326 100755
--- a/ci/deploy.sh
+++ b/ci/deploy.sh
@@ -19,36 +19,36 @@ fi
case $OSTYPE in
darwin*)
- zipdir=WezTerm-macos-$TAG_NAME
+ zipdir=ThinkTerm-macos-$TAG_NAME
if [[ "$BUILD_REASON" == "Schedule" ]] ; then
- zipname=WezTerm-macos-nightly.zip
+ zipname=ThinkTerm-macos-nightly.zip
else
zipname=$zipdir.zip
fi
rm -rf $zipdir $zipname
mkdir $zipdir
- cp -r assets/macos/WezTerm.app $zipdir/
+ cp -r assets/macos/ThinkTerm.app $zipdir/
# Omit MetalANGLE for now; it's a bit laggy compared to CGL,
# and on M1/Big Sur, CGL is implemented in terms of Metal anyway
- rm $zipdir/WezTerm.app/*.dylib
- mkdir -p $zipdir/WezTerm.app/Contents/MacOS
- mkdir -p $zipdir/WezTerm.app/Contents/Resources
- cp -r assets/shell-integration/* $zipdir/WezTerm.app/Contents/Resources
- cp -r assets/shell-completion $zipdir/WezTerm.app/Contents/Resources
- tic -xe wezterm -o $zipdir/WezTerm.app/Contents/Resources/terminfo termwiz/data/wezterm.terminfo
+ rm $zipdir/ThinkTerm.app/*.dylib
+ mkdir -p $zipdir/ThinkTerm.app/Contents/MacOS
+ mkdir -p $zipdir/ThinkTerm.app/Contents/Resources
+ cp -r assets/shell-integration/* $zipdir/ThinkTerm.app/Contents/Resources
+ cp -r assets/shell-completion $zipdir/ThinkTerm.app/Contents/Resources
+ tic -xe wezterm -o $zipdir/ThinkTerm.app/Contents/Resources/terminfo termwiz/data/wezterm.terminfo
for bin in wezterm wezterm-mux-server wezterm-gui strip-ansi-escapes ; do
# If the user ran a simple `cargo build --release`, then we want to allow
# a single-arch package to be built
if [[ -f $TARGET_DIR/release/$bin ]] ; then
- cp $TARGET_DIR/release/$bin $zipdir/WezTerm.app/Contents/MacOS/$bin
+ cp $TARGET_DIR/release/$bin $zipdir/ThinkTerm.app/Contents/MacOS/$bin
else
# The CI runs `cargo build --target XXX --release` which means that
# the binaries will be deployed in `$TARGET_DIR/XXX/release` instead of
# the plain path above.
# In that situation, we have two architectures to assemble into a
# Universal ("fat") binary, so we use the `lipo` tool for that.
- lipo $TARGET_DIR/*/release/$bin -output $zipdir/WezTerm.app/Contents/MacOS/$bin -create
+ lipo $TARGET_DIR/*/release/$bin -output $zipdir/ThinkTerm.app/Contents/MacOS/$bin -create
fi
done
@@ -79,7 +79,7 @@ case $OSTYPE in
security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$MACOS_PW" build.keychain
echo "Codesign"
/usr/bin/codesign --keychain build.keychain --force --options runtime \
- --entitlements ci/macos-entitlement.plist --deep --sign "$MACOS_TEAM_ID" $zipdir/WezTerm.app/
+ --entitlements ci/macos-entitlement.plist --deep --sign "$MACOS_TEAM_ID" $zipdir/ThinkTerm.app/
echo "Restore default keychain"
security default-keychain -d user -s $def_keychain
echo "Remove build.keychain"
diff --git a/ci/wezterm-homebrew-macos.rb.template b/ci/wezterm-homebrew-macos.rb.template
index 464f25a7..7b987205 100644
--- a/ci/wezterm-homebrew-macos.rb.template
+++ b/ci/wezterm-homebrew-macos.rb.template
@@ -1,43 +1,46 @@
# Note: if you are viewing this from the tap repo, this file is automatically
# updated from:
-# https://github.com/wezterm/wezterm/blob/main/ci/wezterm-homebrew-macos.rb.template
-# by automation in the wezterm repo.
+# https://github.com/RoversX/thinkterm/blob/main/ci/wezterm-homebrew-macos.rb.template
+# by automation in the thinkterm repo.
# vim:ft=ruby:
-cask "wezterm" do
+cask "thinkterm" do
version "@TAG@"
sha256 "@SHA256@"
- url "https://github.com/wezterm/wezterm/releases/download/#{version}/WezTerm-macos-#{version}.zip"
- name "WezTerm"
- desc "A GPU-accelerated cross-platform terminal emulator and multiplexer written by @wez and implemented in Rust"
- homepage "https://wezterm.org/"
+ url "https://github.com/RoversX/thinkterm/releases/download/#{version}/ThinkTerm-macos-#{version}.zip"
+ name "ThinkTerm"
+ desc "A workspace-first terminal based on WezTerm"
+ homepage "https://github.com/RoversX/thinkterm"
- conflicts_with cask: "wezterm/wezterm/wezterm-nightly"
+ conflicts_with cask: [
+ "wezterm/wezterm/wezterm",
+ "wezterm/wezterm/wezterm-nightly",
+ ]
# Unclear what the minimal OS version is
# depends_on macos: ">= :sierra"
- app "WezTerm.app"
+ app "ThinkTerm.app"
[
"wezterm",
"wezterm-gui",
"wezterm-mux-server",
"strip-ansi-escapes"
].each do |tool|
- binary "#{appdir}/WezTerm.app/Contents/MacOS/#{tool}"
+ binary "#{appdir}/ThinkTerm.app/Contents/MacOS/#{tool}"
end
preflight do
- # Move "WezTerm-macos-#{version}/WezTerm.app" out of the subfolder
- staged_subfolder = staged_path.glob(["WezTerm-*", "wezterm-*"]).first
+ # Move "ThinkTerm-macos-#{version}/ThinkTerm.app" out of the subfolder
+ staged_subfolder = staged_path.glob(["ThinkTerm-*", "thinkterm-*"]).first
if staged_subfolder
- FileUtils.mv(staged_subfolder/"WezTerm.app", staged_path)
+ FileUtils.mv(staged_subfolder/"ThinkTerm.app", staged_path)
FileUtils.rm_rf(staged_subfolder)
end
end
zap trash: [
- "~/Library/Saved Application State/com.github.wez.wezterm.savedState",
+ "~/Library/Saved Application State/com.roversx.thinkterm.savedState",
]
def caveats; <<~EOS
diff --git a/codec/src/lib.rs b/codec/src/lib.rs
index 7869a47b..1c00dec6 100644
--- a/codec/src/lib.rs
+++ b/codec/src/lib.rs
@@ -441,7 +441,7 @@ macro_rules! pdu {
/// The overall version of the codec.
/// This must be bumped when backwards incompatible changes
/// are made to the types and protocol.
-pub const CODEC_VERSION: usize = 45;
+pub const CODEC_VERSION: usize = 46;
// Defines the Pdu enum.
// Each struct has an explicit identifying number.
diff --git a/config/src/config.rs b/config/src/config.rs
index 0431cdec..5b302735 100644
--- a/config/src/config.rs
+++ b/config/src/config.rs
@@ -48,6 +48,8 @@ use wezterm_input_types::{
};
use wezterm_term::TerminalSize;
+const MACOS_DEFAULT_COLOR_SCHEME: &str = "Apple System Colors";
+
#[derive(Debug, Clone, FromDynamic, ToDynamic, ConfigMeta)]
pub struct Config {
/// The font size, measured in points
@@ -753,7 +755,7 @@ pub struct Config {
#[dynamic(default)]
pub window_close_confirmation: WindowCloseConfirmation,
- #[dynamic(default)]
+ #[dynamic(default = "default_true")]
pub native_macos_fullscreen_mode: bool,
#[dynamic(default)]
@@ -1387,6 +1389,14 @@ impl Config {
cfg.load_color_schemes(&cfg.compute_color_scheme_dirs())
.ok();
+ if cfg!(target_os = "macos") && cfg.color_scheme.is_none() && cfg.colors.is_none() {
+ cfg.color_scheme = Some(MACOS_DEFAULT_COLOR_SCHEME.to_string());
+ }
+
+ if cfg!(target_os = "macos") && cfg.adjust_window_size_when_changing_font_size.is_none() {
+ cfg.adjust_window_size_when_changing_font_size = Some(false);
+ }
+
if let Some(scheme) = cfg.color_scheme.as_ref() {
match cfg.resolve_color_scheme() {
None => {
diff --git a/config/src/keyassignment.rs b/config/src/keyassignment.rs
index efd36fd8..13723305 100644
--- a/config/src/keyassignment.rs
+++ b/config/src/keyassignment.rs
@@ -534,6 +534,7 @@ fn default_message() -> String {
#[derive(Debug, Clone, PartialEq, FromDynamic, ToDynamic)]
pub enum KeyAssignment {
SpawnTab(SpawnTabDomain),
+ SpawnTabToRight(SpawnTabDomain),
SpawnWindow,
ToggleFullScreen,
ToggleAlwaysOnTop,
@@ -572,6 +573,8 @@ pub enum KeyAssignment {
ScrollToTop,
ScrollToBottom,
ShowTabNavigator,
+ PromptRenameTab,
+ PromptRenamePaneTab(usize),
ShowDebugOverlay,
HideApplication,
QuitApplication,
@@ -639,6 +642,7 @@ pub enum KeyAssignment {
ResetTerminal,
OpenUri(String),
+ OpenSettings,
ActivateCommandPalette,
ActivateWindow(usize),
ActivateWindowRelative(isize),
diff --git a/docs/config/lua/config/native_macos_fullscreen_mode.md b/docs/config/lua/config/native_macos_fullscreen_mode.md
index 7dd1bf30..629790e5 100644
--- a/docs/config/lua/config/native_macos_fullscreen_mode.md
+++ b/docs/config/lua/config/native_macos_fullscreen_mode.md
@@ -2,18 +2,20 @@
tags:
- appearance
---
-# `native_macos_fullscreen_mode = false`
+# `native_macos_fullscreen_mode = true`
Specifies whether the [ToggleFullScreen](../../lua/keyassignment/ToggleFullScreen.md)
key assignment uses the native macOS full-screen application support or not.
-The default is `false` which will simply (and very quickly!) toggle between a
-window that covers the full screen, with no decorations and a regularly sized
-window.
+The default is `true`, which uses macOS native full screen mode.
When `true`, transitioning to full screen will use the macOS native full screen
mode, which in more recent versions of macOS, will allocate a separate Space
for the wezterm application and then slowly animate the wezterm window moving
into to that full screen Space on the monitor.
+When set to `false`, fullscreen will simply and very quickly toggle between a
+window that covers the full screen, with no decorations, and a regularly sized
+window.
+
This option only has an effect when running on macOS.
diff --git a/mux/src/client.rs b/mux/src/client.rs
index 92a5e27c..581a50a4 100644
--- a/mux/src/client.rs
+++ b/mux/src/client.rs
@@ -56,20 +56,29 @@ pub struct ClientInfo {
impl ClientInfo {
pub fn new(client_id: Arc<ClientId>) -> Self {
+ let now = utc_now();
Self {
client_id,
- connected_at: Utc::now(),
+ connected_at: now,
active_workspace: None,
- last_input: Utc::now(),
+ last_input: now,
focused_pane_id: None,
}
}
pub fn update_last_input(&mut self) {
- self.last_input = Utc::now();
+ self.last_input = utc_now();
}
pub fn update_focused_pane(&mut self, pane_id: PaneId) {
self.focused_pane_id.replace(pane_id);
}
}
+
+fn utc_now() -> DateTime<Utc> {
+ let duration = SystemTime::now()
+ .duration_since(SystemTime::UNIX_EPOCH)
+ .unwrap_or_default();
+ DateTime::<Utc>::from_timestamp(duration.as_secs() as i64, duration.subsec_nanos())
+ .expect("system time should fit chrono timestamp range")
+}
diff --git a/mux/src/domain.rs b/mux/src/domain.rs
index 12109666..32666039 100644
--- a/mux/src/domain.rs
+++ b/mux/src/domain.rs
@@ -84,12 +84,8 @@ pub trait Domain: Downcast + Send + Sync {
None => anyhow::bail!("Invalid tab id {}", tab),
};
- let pane_index = match tab
- .iter_panes_ignoring_zoom()
- .iter()
- .find(|p| p.pane.pane_id() == pane_id)
- {
- Some(p) => p.index,
+ let pane_index = match tab.pane_index_for_pane(pane_id) {
+ Some(index) => index,
None => anyhow::bail!("invalid pane id {}", pane_id),
};
@@ -128,12 +124,8 @@ pub trait Domain: Downcast + Send + Sync {
};
// pane_index may have changed if src_pane was also in the same tab
- let final_pane_index = match tab
- .iter_panes_ignoring_zoom()
- .iter()
- .find(|p| p.pane.pane_id() == pane_id)
- {
- Some(p) => p.index,
+ let final_pane_index = match tab.pane_index_for_pane(pane_id) {
+ Some(index) => index,
None => anyhow::bail!("invalid pane id {}", pane_id),
};
diff --git a/mux/src/lib.rs b/mux/src/lib.rs
index 566d54e5..b0ed3d3c 100644
--- a/mux/src/lib.rs
+++ b/mux/src/lib.rs
@@ -836,8 +836,8 @@ impl Mux {
}
let mut pane_ids = vec![];
- for pos in tab.iter_panes_ignoring_zoom() {
- pane_ids.push(pos.pane.pane_id());
+ for pane in tab.iter_all_panes() {
+ pane_ids.push(pane.pane_id());
}
log::debug!("panes to remove: {pane_ids:?}");
for pane_id in pane_ids {
@@ -856,8 +856,8 @@ impl Mux {
// Gather all the domains referenced by this window
let mut domains_of_window = HashSet::new();
for tab in window.iter() {
- for pane in tab.iter_panes_ignoring_zoom() {
- domains_of_window.insert(pane.pane.domain_id());
+ for pane in tab.iter_all_panes() {
+ domains_of_window.insert(pane.domain_id());
}
}
@@ -1071,9 +1071,9 @@ impl Mux {
pub fn resolve_pane_id(&self, pane_id: PaneId) -> Option<(DomainId, WindowId, TabId)> {
let mut ids = None;
for tab in self.tabs.read().values() {
- for p in tab.iter_panes_ignoring_zoom() {
- if p.pane.pane_id() == pane_id {
- ids = Some((tab.tab_id(), p.pane.domain_id()));
+ for pane in tab.iter_all_panes() {
+ if pane.pane_id() == pane_id {
+ ids = Some((tab.tab_id(), pane.domain_id()));
break;
}
}
@@ -1083,6 +1083,26 @@ impl Mux {
Some((domain_id, window_id, tab_id))
}
+ pub fn pane_stack_tabs(&self, pane_id: PaneId) -> Vec<crate::tab::PaneStackTab> {
+ let Some((_domain_id, _window_id, tab_id)) = self.resolve_pane_id(pane_id) else {
+ return vec![];
+ };
+ self.get_tab(tab_id)
+ .map(|tab| tab.pane_stack_tabs(pane_id))
+ .unwrap_or_default()
+ }
+
+ pub fn activate_pane_in_stack(&self, pane_id: PaneId) -> anyhow::Result<()> {
+ let (_domain_id, _window_id, tab_id) = self
+ .resolve_pane_id(pane_id)
+ .ok_or_else(|| anyhow!("pane_id {} invalid", pane_id))?;
+ let tab = self
+ .get_tab(tab_id)
+ .ok_or_else(|| anyhow!("tab_id {} invalid", tab_id))?;
+ tab.activate_pane_in_stack(pane_id)?;
+ Ok(())
+ }
+
pub fn domain_was_detached(&self, domain: DomainId) {
let mut dead_panes = vec![];
for pane in self.panes.read().values() {
@@ -1245,6 +1265,70 @@ impl Mux {
Ok((pane, size))
}
+ pub async fn spawn_pane_in_stack(
+ &self,
+ pane_id: PaneId,
+ domain: SpawnTabDomain,
+ command: Option<CommandBuilder>,
+ command_dir: Option<String>,
+ size: TerminalSize,
+ ) -> anyhow::Result<Arc<dyn Pane>> {
+ let (pane_domain_id, window_id, tab_id) = self
+ .resolve_pane_id(pane_id)
+ .ok_or_else(|| anyhow!("pane_id {} invalid", pane_id))?;
+ let tab = self
+ .get_tab(tab_id)
+ .ok_or_else(|| anyhow!("tab_id {} invalid", tab_id))?;
+
+ if tab.get_zoomed_pane().is_some() {
+ anyhow::bail!("cannot create pane tab while zoomed");
+ }
+ if tab.pane_index_for_pane(pane_id).is_none() {
+ anyhow::bail!("pane_id {} is not in tab {}", pane_id, tab_id);
+ }
+
+ let domain = self
+ .resolve_spawn_tab_domain(Some(pane_id), &domain)
+ .context("resolve_spawn_tab_domain")?;
+
+ if domain.state() == DomainState::Detached {
+ domain.attach(Some(window_id)).await?;
+ }
+
+ let current_pane = self
+ .get_pane(pane_id)
+ .ok_or_else(|| anyhow!("pane_id {} is invalid", pane_id))?;
+ let term_config = current_pane.get_config();
+ let cwd = self.resolve_cwd(
+ command_dir,
+ if pane_domain_id == domain.domain_id() {
+ Some(current_pane)
+ } else {
+ None
+ },
+ domain.domain_id(),
+ CachePolicy::FetchImmediate,
+ );
+
+ let pane = domain
+ .spawn_pane(size, command.clone(), cwd.clone())
+ .await
+ .with_context(|| {
+ format!(
+ "Spawning pane in domain `{}`: {size:?} command={command:?} cwd={cwd:?}",
+ domain.domain_name()
+ )
+ })?;
+
+ if let Some(config) = term_config {
+ pane.set_config(config);
+ }
+
+ tab.add_pane_to_stack(pane_id, Arc::clone(&pane))?;
+
+ Ok(pane)
+ }
+
pub async fn move_pane_to_new_tab(
&self,
pane_id: PaneId,
diff --git a/mux/src/tab.rs b/mux/src/tab.rs
index c421fb2a..88f5725a 100644
--- a/mux/src/tab.rs
+++ b/mux/src/tab.rs
@@ -14,10 +14,12 @@ use std::sync::Arc;
use url::Url;
use wezterm_term::{StableRowIndex, TerminalSize};
-pub type Tree = bintree::Tree<Arc<dyn Pane>, SplitDirectionAndSize>;
-pub type Cursor = bintree::Cursor<Arc<dyn Pane>, SplitDirectionAndSize>;
+pub type PaneStackId = usize;
+pub type Tree = bintree::Tree<PaneStack, SplitDirectionAndSize>;
+pub type Cursor = bintree::Cursor<PaneStack, SplitDirectionAndSize>;
static TAB_ID: ::std::sync::atomic::AtomicUsize = ::std::sync::atomic::AtomicUsize::new(0);
+static PANE_STACK_ID: ::std::sync::atomic::AtomicUsize = ::std::sync::atomic::AtomicUsize::new(0);
pub type TabId = usize;
#[derive(Default)]
@@ -37,6 +39,144 @@ impl Recency {
}
}
+#[derive(Clone)]
+pub struct PaneStack {
+ id: PaneStackId,
+ panes: Vec<Arc<dyn Pane>>,
+ active: usize,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct PaneStackTab {
+ pub pane_id: PaneId,
+ pub title: String,
+ pub is_active: bool,
+}
+
+impl PaneStack {
+ fn new(pane: Arc<dyn Pane>) -> Self {
+ Self::from_panes(vec![pane], 0)
+ }
+
+ fn from_panes(panes: Vec<Arc<dyn Pane>>, active: usize) -> Self {
+ Self {
+ id: PANE_STACK_ID.fetch_add(1, ::std::sync::atomic::Ordering::Relaxed),
+ active: active.min(panes.len().saturating_sub(1)),
+ panes,
+ }
+ }
+
+ pub fn id(&self) -> PaneStackId {
+ self.id
+ }
+
+ fn len(&self) -> usize {
+ self.panes.len()
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.panes.is_empty()
+ }
+
+ fn active_index(&self) -> usize {
+ self.active.min(self.panes.len().saturating_sub(1))
+ }
+
+ fn active_pane(&self) -> Option<Arc<dyn Pane>> {
+ self.panes.get(self.active_index()).map(Arc::clone)
+ }
+
+ fn contains_pane(&self, pane_id: PaneId) -> bool {
+ self.panes.iter().any(|pane| pane.pane_id() == pane_id)
+ }
+
+ fn pane_index(&self, pane_id: PaneId) -> Option<usize> {
+ self.panes.iter().position(|pane| pane.pane_id() == pane_id)
+ }
+
+ fn set_active_pane(&mut self, pane_id: PaneId) -> bool {
+ match self.pane_index(pane_id) {
+ Some(index) => {
+ self.active = index;
+ true
+ }
+ None => false,
+ }
+ }
+
+ fn push_and_activate(&mut self, pane: Arc<dyn Pane>) {
+ self.panes.push(pane);
+ self.active = self.panes.len().saturating_sub(1);
+ }
+
+ fn resize(&self, size: TerminalSize) -> anyhow::Result<()> {
+ for pane in &self.panes {
+ pane.resize(size)?;
+ }
+ Ok(())
+ }
+
+ fn tabs(&self) -> Vec<PaneStackTab> {
+ let active = self.active_index();
+ self.panes
+ .iter()
+ .enumerate()
+ .map(|(idx, pane)| PaneStackTab {
+ pane_id: pane.pane_id(),
+ title: pane.get_title(),
+ is_active: idx == active,
+ })
+ .collect()
+ }
+
+ fn remove_matching<F>(
+ &mut self,
+ pane_index: usize,
+ f: &F,
+ zoomed_pane: Option<PaneId>,
+ ) -> (Vec<Arc<dyn Pane>>, bool)
+ where
+ F: Fn(usize, &Arc<dyn Pane>) -> bool,
+ {
+ let mut removed = vec![];
+ let mut idx = 0;
+ let active = self.active_index();
+ let mut removed_before_active = 0;
+ let mut removed_active = false;
+
+ self.panes.retain(|pane| {
+ let should_remove = f(pane_index, pane);
+ if should_remove {
+ if idx < active {
+ removed_before_active += 1;
+ }
+ if idx == active || Some(pane.pane_id()) == zoomed_pane {
+ removed_active = true;
+ }
+ removed.push(Arc::clone(pane));
+ }
+ idx += 1;
+ !should_remove
+ });
+
+ if self.panes.is_empty() {
+ self.active = 0;
+ } else if removed_active {
+ self.active = self
+ .active_index()
+ .saturating_sub(1)
+ .min(self.panes.len().saturating_sub(1));
+ } else {
+ self.active = active
+ .saturating_sub(removed_before_active)
+ .min(self.panes.len().saturating_sub(1));
+ }
+
+ let became_empty = self.panes.is_empty();
+ (removed, became_empty)
+ }
+}
+
struct TabInner {
id: TabId,
pane: Option<Tree>,
@@ -223,6 +363,44 @@ fn pane_tree(
left_col: usize,
top_row: usize,
) -> PaneNode {
+ fn pane_entry(
+ pane: &Arc<dyn Pane>,
+ tab_id: TabId,
+ window_id: WindowId,
+ active: Option<&Arc<dyn Pane>>,
+ zoomed: Option<&Arc<dyn Pane>>,
+ workspace: &str,
+ left_col: usize,
+ top_row: usize,
+ ) -> PaneEntry {
+ let dims = pane.get_dimensions();
+ let working_dir = pane.get_current_working_dir(CachePolicy::AllowStale);
+ let cursor_pos = pane.get_cursor_position();
+
+ PaneEntry {
+ window_id,
+ tab_id,
+ pane_id: pane.pane_id(),
+ title: pane.get_title(),
+ is_active_pane: is_pane(pane, &active),
+ is_zoomed_pane: is_pane(pane, &zoomed),
+ size: TerminalSize {
+ cols: dims.cols,
+ rows: dims.viewport_rows,
+ pixel_height: dims.pixel_height,
+ pixel_width: dims.pixel_width,
+ dpi: dims.dpi,
+ },
+ working_dir: working_dir.map(Into::into),
+ workspace: workspace.to_string(),
+ cursor_pos,
+ physical_top: dims.physical_top,
+ left_col,
+ top_row,
+ tty_name: pane.tty_name(),
+ }
+ }
+
match tree {
Tree::Empty => PaneNode::Empty,
Tree::Node { left, right, data } => {
@@ -252,39 +430,31 @@ fn pane_tree(
node: data,
}
}
- Tree::Leaf(pane) => {
- let dims = pane.get_dimensions();
- let working_dir = pane.get_current_working_dir(CachePolicy::AllowStale);
- let cursor_pos = pane.get_cursor_position();
+ Tree::Leaf(stack) => {
+ let entries: Vec<_> = stack
+ .panes
+ .iter()
+ .map(|pane| {
+ pane_entry(
+ pane, tab_id, window_id, active, zoomed, workspace, left_col, top_row,
+ )
+ })
+ .collect();
- PaneNode::Leaf(PaneEntry {
- window_id,
- tab_id,
- pane_id: pane.pane_id(),
- title: pane.get_title(),
- is_active_pane: is_pane(pane, &active),
- is_zoomed_pane: is_pane(pane, &zoomed),
- size: TerminalSize {
- cols: dims.cols,
- rows: dims.viewport_rows,
- pixel_height: dims.pixel_height,
- pixel_width: dims.pixel_width,
- dpi: dims.dpi,
- },
- working_dir: working_dir.map(Into::into),
- workspace: workspace.to_string(),
- cursor_pos,
- physical_top: dims.physical_top,
- left_col,
- top_row,
- tty_name: pane.tty_name(),
- })
+ if entries.len() == 1 {
+ PaneNode::Leaf(entries.into_iter().next().unwrap())
+ } else {
+ PaneNode::Stack(PaneStackEntry {
+ active: stack.active_index(),
+ panes: entries,
+ })
+ }
}
}
}
fn build_from_pane_tree<F>(
- tree: bintree::Tree<PaneEntry, SplitDirectionAndSize>,
+ tree: bintree::Tree<PaneStackEntry, SplitDirectionAndSize>,
active: &mut Option<Arc<dyn Pane>>,
zoomed: &mut Option<Arc<dyn Pane>>,
make_pane: &mut F,
@@ -300,16 +470,27 @@ where
data,
},
bintree::Tree::Leaf(entry) => {
- let is_zoomed_pane = entry.is_zoomed_pane;
- let is_active_pane = entry.is_active_pane;
- let pane = make_pane(entry);
- if is_zoomed_pane {
- zoomed.replace(Arc::clone(&pane));
+ let active_index = entry.active.min(entry.panes.len().saturating_sub(1));
+ let mut panes = vec![];
+
+ for pane_entry in entry.panes {
+ let is_zoomed_pane = pane_entry.is_zoomed_pane;
+ let is_active_pane = pane_entry.is_active_pane;
+ let pane = make_pane(pane_entry);
+ if is_zoomed_pane {
+ zoomed.replace(Arc::clone(&pane));
+ }
+ if is_active_pane {
+ active.replace(Arc::clone(&pane));
+ }
+ panes.push(pane);
}
- if is_active_pane {
- active.replace(Arc::clone(&pane));
+
+ if panes.is_empty() {
+ Tree::Empty
+ } else {
+ Tree::Leaf(PaneStack::from_panes(panes, active_index))
}
- Tree::Leaf(pane)
}
}
}
@@ -478,22 +659,23 @@ fn adjust_y_size(tree: &mut Tree, mut y_adjust: isize, cell_dimensions: &Termina
}
}
-fn apply_sizes_from_splits(tree: &Tree, size: &TerminalSize) {
+fn apply_sizes_from_splits(tree: &Tree, size: &TerminalSize) -> anyhow::Result<()> {
match tree {
- Tree::Empty => return,
- Tree::Node { data: None, .. } => return,
+ Tree::Empty => return Ok(()),
+ Tree::Node { data: None, .. } => return Ok(()),
Tree::Node {
left,
right,
data: Some(data),
} => {
- apply_sizes_from_splits(&*left, &data.first);
- apply_sizes_from_splits(&*right, &data.second);
+ apply_sizes_from_splits(&*left, &data.first)?;
+ apply_sizes_from_splits(&*right, &data.second)?;
}
- Tree::Leaf(pane) => {
- pane.resize(*size).ok();
+ Tree::Leaf(stack) => {
+ stack.resize(*size)?;
}
}
+ Ok(())
}
fn cell_dimensions(size: &TerminalSize) -> TerminalSize {
@@ -581,6 +763,18 @@ impl Tab {
self.inner.lock().iter_panes_ignoring_zoom()
}
+ pub fn iter_all_panes(&self) -> Vec<Arc<dyn Pane>> {
+ self.inner.lock().iter_all_panes()
+ }
+
+ pub fn pane_stack_tabs(&self, pane_id: PaneId) -> Vec<PaneStackTab> {
+ self.inner.lock().pane_stack_tabs(pane_id)
+ }
+
+ pub fn pane_index_for_pane(&self, pane_id: PaneId) -> Option<usize> {
+ self.inner.lock().pane_index_for_pane(pane_id)
+ }
+
pub fn rotate_counter_clockwise(&self) {
self.inner.lock().rotate_counter_clockwise()
}
@@ -706,6 +900,18 @@ impl Tab {
self.inner.lock().set_active_idx(pane_index)
}
+ pub fn add_pane_to_stack(
+ &self,
+ base_pane_id: PaneId,
+ pane: Arc<dyn Pane>,
+ ) -> anyhow::Result<usize> {
+ self.inner.lock().add_pane_to_stack(base_pane_id, pane)
+ }
+
+ pub fn activate_pane_in_stack(&self, pane_id: PaneId) -> anyhow::Result<usize> {
+ self.inner.lock().activate_pane_in_stack(pane_id)
+ }
+
/// Assigns the root pane.
/// This is suitable when creating a new tab and then assigning
/// the initial pane
@@ -784,8 +990,8 @@ impl TabInner {
// Resolve the active pane to its index
let mut index = 0;
loop {
- if let Some(pane) = cursor.leaf_mut() {
- if active.pane_id() == pane.pane_id() {
+ if let Some(stack) = cursor.leaf_mut() {
+ if stack.set_active_pane(active.pane_id()) {
// Found it
self.active = index;
self.recency.tag(index);
@@ -865,7 +1071,7 @@ impl TabInner {
loop {
if cursor.is_leaf() {
- count += 1;
+ count += cursor.leaf_mut().unwrap().len();
}
match cursor.preorder_next() {
Ok(c) => cursor = c,
@@ -904,7 +1110,9 @@ impl TabInner {
self.size_before_zoom = size;
if let Some(pane) = self.get_active_pane() {
pane.set_zoomed(true);
- pane.resize(size).ok();
+ if let Err(err) = pane.resize(size) {
+ log::error!("failed to resize zoomed pane: {err:#}");
+ }
self.zoomed.replace(pane);
}
}
@@ -916,7 +1124,7 @@ impl TabInner {
match tree {
Tree::Empty => false,
Tree::Node { left, right, .. } => contains(left, pane) || contains(right, pane),
- Tree::Leaf(p) => p.pane_id() == pane,
+ Tree::Leaf(stack) => stack.contains_pane(pane),
}
}
match &self.pane {
@@ -937,23 +1145,111 @@ impl TabInner {
self.iter_panes_impl(false)
}
+ fn iter_all_panes(&mut self) -> Vec<Arc<dyn Pane>> {
+ let mut panes = vec![];
+ let mut cursor = self.pane.take().unwrap().cursor();
+
+ loop {
+ if cursor.is_leaf() {
+ panes.extend(cursor.leaf_mut().unwrap().panes.iter().cloned());
+ }
+
+ match cursor.preorder_next() {
+ Ok(c) => cursor = c,
+ Err(c) => {
+ self.pane.replace(c.tree());
+ break;
+ }
+ }
+ }
+
+ panes
+ }
+
+ fn pane_stack_tabs(&mut self, pane_id: PaneId) -> Vec<PaneStackTab> {
+ let mut tabs = vec![];
+ let mut cursor = self.pane.take().unwrap().cursor();
+
+ loop {
+ if cursor.is_leaf() {
+ let stack = cursor.leaf_mut().unwrap();
+ if stack.contains_pane(pane_id) {
+ tabs = stack.tabs();
+ }
+ }
+
+ match cursor.preorder_next() {
+ Ok(c) if tabs.is_empty() => cursor = c,
+ Ok(c) | Err(c) => {
+ self.pane.replace(c.tree());
+ break;
+ }
+ }
+ }
+
+ tabs
+ }
+
+ fn pane_index_for_pane(&mut self, pane_id: PaneId) -> Option<usize> {
+ let mut cursor = self.pane.take().unwrap().cursor();
+ let mut pane_index = 0;
+ let mut found = None;
+
+ loop {
+ if cursor.is_leaf() {
+ if cursor.leaf_mut().unwrap().contains_pane(pane_id) {
+ found = Some(pane_index);
+ }
+ pane_index += 1;
+ }
+
+ match cursor.preorder_next() {
+ Ok(c) if found.is_none() => cursor = c,
+ Ok(c) | Err(c) => {
+ self.pane.replace(c.tree());
+ break;
+ }
+ }
+ }
+
+ found
+ }
+
+ fn iter_stacks(&mut self) -> Vec<PaneStack> {
+ let mut stacks = vec![];
+ let mut cursor = self.pane.take().unwrap().cursor();
+
+ loop {
+ if cursor.is_leaf() {
+ stacks.push(cursor.leaf_mut().unwrap().clone());
+ }
+
+ match cursor.preorder_next() {
+ Ok(c) => cursor = c,
+ Err(c) => {
+ self.pane.replace(c.tree());
+ break;
+ }
+ }
+ }
+
+ stacks
+ }
+
fn rotate_counter_clockwise(&mut self) {
- let panes = self.iter_panes_ignoring_zoom();
- if panes.is_empty() {
+ let stacks = self.iter_stacks();
+ if stacks.is_empty() {
// Shouldn't happen, but we check for this here so that the
// expect below cannot trigger a panic
return;
}
- let mut pane_to_swap = panes
- .first()
- .map(|p| p.pane.clone())
- .expect("at least one pane");
+ let mut stack_to_swap = stacks.first().cloned().expect("at least one pane");
let mut cursor = self.pane.take().unwrap().cursor();
loop {
if cursor.is_leaf() {
- std::mem::swap(&mut pane_to_swap, cursor.leaf_mut().unwrap());
+ std::mem::swap(&mut stack_to_swap, cursor.leaf_mut().unwrap());
}
match cursor.postorder_next() {
@@ -961,7 +1257,9 @@ impl TabInner {
Err(c) => {
self.pane.replace(c.tree());
let size = self.size;
- apply_sizes_from_splits(self.pane.as_mut().unwrap(), &size);
+ if let Err(err) = apply_sizes_from_splits(self.pane.as_mut().unwrap(), &size) {
+ log::error!("failed to resize panes after rotation: {err:#}");
+ }
break;
}
}
@@ -969,22 +1267,19 @@ impl TabInner {
}
fn rotate_clockwise(&mut self) {
- let panes = self.iter_panes_ignoring_zoom();
- if panes.is_empty() {
+ let stacks = self.iter_stacks();
+ if stacks.is_empty() {
// Shouldn't happen, but we check for this here so that the
// expect below cannot trigger a panic
return;
}
- let mut pane_to_swap = panes
- .last()
- .map(|p| p.pane.clone())
- .expect("at least one pane");
+ let mut stack_to_swap = stacks.last().cloned().expect("at least one pane");
let mut cursor = self.pane.take().unwrap().cursor();
loop {
if cursor.is_leaf() {
- std::mem::swap(&mut pane_to_swap, cursor.leaf_mut().unwrap());
+ std::mem::swap(&mut stack_to_swap, cursor.leaf_mut().unwrap());
}
match cursor.preorder_next() {
@@ -992,7 +1287,9 @@ impl TabInner {
Err(c) => {
self.pane.replace(c.tree());
let size = self.size;
- apply_sizes_from_splits(self.pane.as_mut().unwrap(), &size);
+ if let Err(err) = apply_sizes_from_splits(self.pane.as_mut().unwrap(), &size) {
+ log::error!("failed to resize panes after rotation: {err:#}");
+ }
break;
}
}
@@ -1049,21 +1346,22 @@ impl TabInner {
}
}
- let pane = Arc::clone(cursor.leaf_mut().unwrap());
- let dims = parent_size.unwrap_or_else(|| root_size);
+ if let Some(pane) = cursor.leaf_mut().unwrap().active_pane() {
+ let dims = parent_size.unwrap_or_else(|| root_size);
- panes.push(PositionedPane {
- index,
- is_active: index == active_idx,
- is_zoomed: zoomed_id == Some(pane.pane_id()),
- left,
- top,
- width: dims.cols as _,
- height: dims.rows as _,
- pixel_width: dims.pixel_width as _,
- pixel_height: dims.pixel_height as _,
- pane,
- });
+ panes.push(PositionedPane {
+ index,
+ is_active: index == active_idx,
+ is_zoomed: zoomed_id == Some(pane.pane_id()),
+ left,
+ top,
+ width: dims.cols as _,
+ height: dims.rows as _,
+ pixel_width: dims.pixel_width as _,
+ pixel_height: dims.pixel_height as _,
+ pane,
+ });
+ }
}
match cursor.preorder_next() {
@@ -1144,7 +1442,9 @@ impl TabInner {
if let Some(zoomed) = &self.zoomed {
self.size = size;
- zoomed.resize(size).ok();
+ if let Err(err) = zoomed.resize(size) {
+ log::error!("failed to resize zoomed pane: {err:#}");
+ }
} else {
let dims = cell_dimensions(&size);
let (min_x, min_y) = compute_min_size(self.pane.as_mut().unwrap());
@@ -1176,7 +1476,9 @@ impl TabInner {
self.size = size;
// And then resize the individual panes to match
- apply_sizes_from_splits(self.pane.as_mut().unwrap(), &size);
+ if let Err(err) = apply_sizes_from_splits(self.pane.as_mut().unwrap(), &size) {
+ log::error!("failed to resize panes after split adjustment: {err:#}");
+ }
}
Mux::try_get().map(|mux| mux.notify(MuxNotification::TabResized(self.id)));
@@ -1223,7 +1525,8 @@ impl TabInner {
fn compute_size(node: &mut Tree) -> Option<TerminalSize> {
match node {
Tree::Empty => None,
- Tree::Leaf(pane) => {
+ Tree::Leaf(stack) => {
+ let pane = stack.active_pane()?;
let dims = pane.get_dimensions();
let size = TerminalSize {
cols: dims.cols,
@@ -1359,7 +1662,11 @@ impl TabInner {
if cursor.is_leaf() {
// Apply our size to the tty
- cursor.leaf_mut().map(|pane| pane.resize(pane_size));
+ if let Some(stack) = cursor.leaf_mut() {
+ if let Err(err) = stack.resize(pane_size) {
+ log::error!("failed to resize pane stack: {err:#}");
+ }
+ }
} else {
self.apply_pane_size(pane_size, &mut cursor);
}
@@ -1607,6 +1914,7 @@ impl TabInner {
{
let mut dead_panes = vec![];
let zoomed_pane = self.zoomed.as_ref().map(|p| p.pane_id());
+ let prior = self.get_active_pane();
{
let root_size = self.size;
@@ -1629,17 +1937,28 @@ impl TabInner {
};
if cursor.is_leaf() {
- let pane = Arc::clone(cursor.leaf_mut().unwrap());
- if f(pane_index, &pane) {
- removed_indices.push(pane_index);
- if Some(pane.pane_id()) == zoomed_pane {
+ let (removed, stack_became_empty) =
+ cursor
+ .leaf_mut()
+ .unwrap()
+ .remove_matching(pane_index, &f, zoomed_pane);
+ if !removed.is_empty() {
+ if removed
+ .iter()
+ .any(|pane| Some(pane.pane_id()) == zoomed_pane)
+ {
// If we removed the zoomed pane, un-zoom our state!
self.zoomed.take();
}
+ dead_panes.extend(removed);
+ }
+
+ if stack_became_empty {
+ removed_indices.push(pane_index);
let parent;
match cursor.unsplit_leaf() {
Ok((c, dead, p)) => {
- dead_panes.push(dead);
+ dead_panes.extend(dead.panes);
parent = p.unwrap();
cursor = c;
}
@@ -1647,7 +1966,6 @@ impl TabInner {
// We might be the root, for example
if c.is_top() && c.is_leaf() {
self.pane.replace(Tree::Empty);
- dead_panes.push(pane);
} else {
self.pane.replace(c.tree());
}
@@ -1665,14 +1983,20 @@ impl TabInner {
dpi: cell_dims.dpi,
};
- if let Some(unsplit) = cursor.leaf_mut() {
- unsplit.resize(size).ok();
+ if let Some(stack) = cursor.leaf_mut() {
+ if let Err(err) = stack.resize(size) {
+ log::error!("failed to resize pane stack after removal: {err:#}");
+ }
} else {
self.apply_pane_size(size, &mut cursor);
}
} else if !dead_panes.is_empty() {
// Apply our revised size to the tty
- pane.resize(pane_size).ok();
+ if let Some(stack) = cursor.leaf_mut() {
+ if let Err(err) = stack.resize(pane_size) {
+ log::error!("failed to resize pane stack after removal: {err:#}");
+ }
+ }
}
pane_index += 1;
@@ -1696,6 +2020,10 @@ impl TabInner {
self.active = active_idx.saturating_sub(removed_indices.len());
}
+ if !dead_panes.is_empty() {
+ self.advise_focus_change(prior);
+ }
+
if !dead_panes.is_empty() && kill {
let to_kill: Vec<_> = dead_panes.iter().map(|p| p.pane_id()).collect();
promise::spawn::spawn_into_main_thread(async move {
@@ -1710,9 +2038,9 @@ impl TabInner {
}
fn can_close_without_prompting(&mut self, reason: CloseReason) -> bool {
- let panes = self.iter_panes_ignoring_zoom();
- for pos in &panes {
- if !pos.pane.can_close_without_prompting(reason) {
+ let panes = self.iter_all_panes();
+ for pane in &panes {
+ if !pane.can_close_without_prompting(reason) {
return false;
}
}
@@ -1722,10 +2050,10 @@ impl TabInner {
fn is_dead(&mut self) -> bool {
// Make sure we account for all panes, so that we don't
// kill the whole tab if the zoomed pane is dead!
- let panes = self.iter_panes_ignoring_zoom();
+ let panes = self.iter_all_panes();
let mut dead_count = 0;
- for pos in &panes {
- if pos.pane.is_dead() {
+ for pane in &panes {
+ if pane.is_dead() {
dead_count += 1;
}
}
@@ -1761,17 +2089,55 @@ impl TabInner {
self.toggle_zoom();
}
- if let Some(item) = self
- .iter_panes_ignoring_zoom()
- .iter()
- .find(|p| p.pane.pane_id() == pane.pane_id())
- {
- self.active = item.index;
- self.recency.tag(item.index);
+ if let Some(pane_index) = self.activate_pane_in_stack_impl(pane.pane_id()) {
+ self.active = pane_index;
+ self.recency.tag(pane_index);
self.advise_focus_change(prior);
}
}
+ fn activate_pane_in_stack(&mut self, pane_id: PaneId) -> anyhow::Result<usize> {
+ if self.zoomed.is_some() {
+ anyhow::bail!("cannot switch pane tab while zoomed");
+ }
+
+ let prior = self.get_active_pane();
+ let pane_index = self
+ .activate_pane_in_stack_impl(pane_id)
+ .ok_or_else(|| anyhow::anyhow!("pane {} not found in tab", pane_id))?;
+ self.active = pane_index;
+ self.recency.tag(pane_index);
+ self.advise_focus_change(prior);
+ Mux::try_get().map(|mux| mux.notify(MuxNotification::TabResized(self.id)));
+
+ Ok(pane_index)
+ }
+
+ fn activate_pane_in_stack_impl(&mut self, pane_id: PaneId) -> Option<usize> {
+ let mut cursor = self.pane.take().unwrap().cursor();
+ let mut pane_index = 0;
+ let mut found = None;
+
+ loop {
+ if cursor.is_leaf() {
+ if cursor.leaf_mut().unwrap().set_active_pane(pane_id) {
+ found = Some(pane_index);
+ }
+ pane_index += 1;
+ }
+
+ match cursor.preorder_next() {
+ Ok(c) if found.is_none() => cursor = c,
+ Ok(c) | Err(c) => {
+ self.pane.replace(c.tree());
+ break;
+ }
+ }
+ }
+
+ found
+ }
+
fn advise_focus_change(&mut self, prior: Option<Arc<dyn Pane>>) {
let mux = Mux::get();
let current = self.get_active_pane();
@@ -1801,8 +2167,68 @@ impl TabInner {
self.advise_focus_change(prior);
}
+ fn add_pane_to_stack(
+ &mut self,
+ base_pane_id: PaneId,
+ pane: Arc<dyn Pane>,
+ ) -> anyhow::Result<usize> {
+ if self.zoomed.is_some() {
+ anyhow::bail!("cannot create pane tab while zoomed");
+ }
+
+ let prior = self.get_active_pane();
+ let mut cursor = self.pane.take().unwrap().cursor();
+ let mut pane_index = 0;
+ let mut found = false;
+
+ loop {
+ if cursor.is_leaf() {
+ let stack = cursor.leaf_mut().unwrap();
+ if stack.contains_pane(base_pane_id) {
+ if let Some(base) = stack.active_pane() {
+ let dims = base.get_dimensions();
+ pane.resize(TerminalSize {
+ rows: dims.viewport_rows,
+ cols: dims.cols,
+ pixel_height: dims.pixel_height,
+ pixel_width: dims.pixel_width,
+ dpi: dims.dpi,
+ })?;
+ }
+ stack.push_and_activate(Arc::clone(&pane));
+ found = true;
+ }
+ if !found {
+ pane_index += 1;
+ }
+ }
+
+ match cursor.preorder_next() {
+ Ok(c) if !found => cursor = c,
+ Ok(c) | Err(c) => {
+ self.pane.replace(c.tree());
+ break;
+ }
+ }
+ }
+
+ if !found {
+ anyhow::bail!("pane {} not found in tab", base_pane_id);
+ }
+
+ self.active = pane_index;
+ self.recency.tag(pane_index);
+ self.advise_focus_change(prior);
+ Mux::try_get().map(|mux| mux.notify(MuxNotification::TabResized(self.id)));
+
+ Ok(pane_index)
+ }
+
fn assign_pane(&mut self, pane: &Arc<dyn Pane>) {
- match Tree::new().cursor().assign_top(Arc::clone(pane)) {
+ match Tree::new()
+ .cursor()
+ .assign_top(PaneStack::new(Arc::clone(pane)))
+ {
Ok(c) => self.pane = Some(c.tree()),
Err(_) => panic!("tried to assign root pane to non-empty tree"),
}
@@ -1814,7 +2240,8 @@ impl TabInner {
fn swap_active_with_index(&mut self, pane_index: usize, keep_focus: bool) -> Option<()> {
let active_idx = self.get_active_idx();
- let mut pane = self.get_active_pane()?;
+ let prior = self.get_active_pane()?;
+ let mut stack = self.iter_stacks().into_iter().nth(active_idx)?;
log::trace!(
"swap_active_with_index: pane_index {} active {}",
pane_index,
@@ -1834,7 +2261,7 @@ impl TabInner {
}
};
- std::mem::swap(&mut pane, cursor.leaf_mut().unwrap());
+ std::mem::swap(&mut stack, cursor.leaf_mut().unwrap());
// re-position to the root
cursor = cursor.tree().cursor();
@@ -1849,19 +2276,21 @@ impl TabInner {
}
};
- std::mem::swap(&mut pane, cursor.leaf_mut().unwrap());
+ std::mem::swap(&mut stack, cursor.leaf_mut().unwrap());
self.pane.replace(cursor.tree());
// Advise the panes of their new sizes
let size = self.size;
- apply_sizes_from_splits(self.pane.as_mut().unwrap(), &size);
+ if let Err(err) = apply_sizes_from_splits(self.pane.as_mut().unwrap(), &size) {
+ log::error!("failed to resize panes after moving active pane: {err:#}");
+ }
}
// And update focus
if keep_focus {
self.set_active_idx(pane_index);
} else {
- self.advise_focus_change(Some(pane));
+ self.advise_focus_change(Some(prior));
}
None
}
@@ -2014,10 +2443,11 @@ impl TabInner {
let mut cursor = self.pane.take().unwrap().cursor();
if request.top_level && !cursor.is_leaf() {
+ let new_stack = PaneStack::new(Arc::clone(&pane));
let result = if request.target_is_second {
- cursor.split_node_and_insert_right(Arc::clone(&pane))
+ cursor.split_node_and_insert_right(new_stack)
} else {
- cursor.split_node_and_insert_left(Arc::clone(&pane))
+ cursor.split_node_and_insert_left(new_stack)
};
cursor = match result {
Ok(c) => {
@@ -2049,20 +2479,21 @@ impl TabInner {
}
};
- let existing_pane = Arc::clone(cursor.leaf_mut().unwrap());
+ let existing_stack = cursor.leaf_mut().unwrap().clone();
+ let new_stack = PaneStack::new(pane);
- let (pane1, pane2) = if request.target_is_second {
- (existing_pane, pane)
+ let (stack1, stack2) = if request.target_is_second {
+ (existing_stack, new_stack)
} else {
- (pane, existing_pane)
+ (new_stack, existing_stack)
};
- pane1.resize(split_info.first)?;
- pane2.resize(split_info.second.clone())?;
+ stack1.resize(split_info.first)?;
+ stack2.resize(split_info.second)?;
- *cursor.leaf_mut().unwrap() = pane1;
+ *cursor.leaf_mut().unwrap() = stack1;
- match cursor.split_leaf_and_insert_right(pane2) {
+ match cursor.split_leaf_and_insert_right(stack2) {
Ok(c) => cursor = c,
Err(c) => {
self.pane.replace(c.tree());
@@ -2108,10 +2539,11 @@ pub enum PaneNode {
node: SplitDirectionAndSize,
},
Leaf(PaneEntry),
+ Stack(PaneStackEntry),
}
impl PaneNode {
- pub fn into_tree(self) -> bintree::Tree<PaneEntry, SplitDirectionAndSize> {
+ pub fn into_tree(self) -> bintree::Tree<PaneStackEntry, SplitDirectionAndSize> {
match self {
PaneNode::Empty => bintree::Tree::Empty,
PaneNode::Split { left, right, node } => bintree::Tree::Node {
@@ -2119,7 +2551,11 @@ impl PaneNode {
right: Box::new((*right).into_tree()),
data: Some(node),
},
- PaneNode::Leaf(e) => bintree::Tree::Leaf(e),
+ PaneNode::Leaf(e) => bintree::Tree::Leaf(PaneStackEntry {
+ active: 0,
+ panes: vec![e],
+ }),
+ PaneNode::Stack(stack) => bintree::Tree::Leaf(stack),
}
}
@@ -2128,6 +2564,11 @@ impl PaneNode {
PaneNode::Empty => None,
PaneNode::Split { node, .. } => Some(node.size()),
PaneNode::Leaf(entry) => Some(entry.size),
+ PaneNode::Stack(stack) => stack
+ .panes
+ .get(stack.active)
+ .or_else(|| stack.panes.first())
+ .map(|entry| entry.size),
}
}
@@ -2139,10 +2580,23 @@ impl PaneNode {
None => right.window_and_tab_ids(),
},
PaneNode::Leaf(entry) => Some((entry.window_id, entry.tab_id)),
+ PaneNode::Stack(stack) => stack
+ .panes
+ .get(stack.active)
+ .or_else(|| stack.panes.first())
+ .map(|entry| (entry.window_id, entry.tab_id)),
}
}
}
+/// This type is used directly by the codec, take care to bump
+/// the codec version if you change this
+#[derive(Deserialize, Serialize, PartialEq, Debug, Clone)]
+pub struct PaneStackEntry {
+ pub active: usize,
+ pub panes: Vec<PaneEntry>,
+}
+
/// This type is used directly by the codec, take care to bump
/// the codec version if you change this
#[derive(Deserialize, Serialize, PartialEq, Debug, Clone)]
@@ -2227,7 +2681,7 @@ mod test {
}
fn get_cursor_position(&self) -> StableCursorPosition {
- unimplemented!();
+ StableCursorPosition::default()
}
fn get_current_seqno(&self) -> SequenceNo {
@@ -2267,11 +2721,22 @@ mod test {
}
fn get_dimensions(&self) -> RenderableDimensions {
- unimplemented!();
+ let size = *self.size.lock();
+ RenderableDimensions {
+ cols: size.cols,
+ viewport_rows: size.rows,
+ scrollback_rows: size.rows,
+ physical_top: 0,
+ scrollback_top: 0,
+ dpi: size.dpi,
+ pixel_width: size.pixel_width,
+ pixel_height: size.pixel_height,
+ reverse_video: false,
+ }
}
fn get_title(&self) -> String {
- unimplemented!()
+ format!("pane {}", self.id)
}
fn send_paste(&self, _text: &str) -> anyhow::Result<()> {
unimplemented!()
@@ -2279,7 +2744,7 @@ mod test {
fn reader(&self) -> anyhow::Result<Option<Box<dyn std::io::Read + Send>>> {
Ok(None)
}
- fn writer(&self) -> MappedMutexGuard<dyn std::io::Write> {
+ fn writer(&self) -> MappedMutexGuard<'_, dyn std::io::Write> {
unimplemented!()
}
fn resize(&self, size: TerminalSize) -> anyhow::Result<()> {
@@ -2318,13 +2783,7 @@ mod test {
#[test]
fn tab_splitting() {
- let size = TerminalSize {
- rows: 24,
- cols: 80,
- pixel_width: 800,
- pixel_height: 600,
- dpi: 96,
- };
+ let size = test_size();
let tab = Tab::new(&size);
tab.assign_pane(&FakePane::new(1, size));
@@ -2517,6 +2976,142 @@ mod test {
assert_eq!(600, panes[2].pixel_height);
}
+ fn test_size() -> TerminalSize {
+ TerminalSize {
+ rows: 24,
+ cols: 80,
+ pixel_width: 800,
+ pixel_height: 600,
+ dpi: 96,
+ }
+ }
+
+ struct MuxTestGuard;
+
+ impl Drop for MuxTestGuard {
+ fn drop(&mut self) {
+ Mux::shutdown();
+ }
+ }
+
+ fn install_mux() -> MuxTestGuard {
+ Mux::set_mux(&Arc::new(Mux::new(None)));
+ MuxTestGuard
+ }
+
+ #[test]
+ fn pane_stack_add_switch_and_remove() {
+ let _mux = install_mux();
+ let size = test_size();
+ let tab = Tab::new(&size);
+ let pane_1 = FakePane::new(100, size);
+ let pane_2 = FakePane::new(101, size);
+
+ tab.assign_pane(&pane_1);
+ assert_eq!(tab.add_pane_to_stack(100, Arc::clone(&pane_2)).unwrap(), 0);
+ assert_eq!(tab.count_panes(), Some(2));
+ assert_eq!(tab.pane_index_for_pane(100), Some(0));
+ assert_eq!(tab.pane_index_for_pane(101), Some(0));
+
+ let panes = tab.iter_panes();
+ assert_eq!(panes.len(), 1);
+ assert_eq!(panes[0].pane.pane_id(), 101);
+ assert!(panes[0].is_active);
+
+ let tabs = tab.pane_stack_tabs(100);
+ assert_eq!(tabs.len(), 2);
+ assert_eq!(tabs[0].pane_id, 100);
+ assert!(!tabs[0].is_active);
+ assert_eq!(tabs[1].pane_id, 101);
+ assert!(tabs[1].is_active);
+
+ tab.activate_pane_in_stack(100).unwrap();
+ assert_eq!(tab.get_active_pane().unwrap().pane_id(), 100);
+
+ let removed = tab.remove_pane(101).unwrap();
+ assert_eq!(removed.pane_id(), 101);
+ assert_eq!(tab.count_panes(), Some(1));
+ assert_eq!(tab.get_active_pane().unwrap().pane_id(), 100);
+
+ let pane_3 = FakePane::new(102, size);
+ tab.add_pane_to_stack(100, Arc::clone(&pane_3)).unwrap();
+ assert_eq!(tab.get_active_pane().unwrap().pane_id(), 102);
+
+ let removed_active = tab.remove_pane(102).unwrap();
+ assert_eq!(removed_active.pane_id(), 102);
+ assert_eq!(tab.count_panes(), Some(1));
+ assert_eq!(tab.get_active_pane().unwrap().pane_id(), 100);
+
+ tab.set_zoomed(true);
+ assert!(tab
+ .add_pane_to_stack(100, FakePane::new(103, size))
+ .is_err());
+ assert!(tab.activate_pane_in_stack(100).is_err());
+ }
+
+ fn pane_entry(pane_id: PaneId, size: TerminalSize, is_active_pane: bool) -> PaneEntry {
+ PaneEntry {
+ window_id: 1,
+ tab_id: 1,
+ pane_id,
+ title: format!("pane {pane_id}"),
+ size,
+ working_dir: None,
+ is_active_pane,
+ is_zoomed_pane: false,
+ workspace: "default".to_string(),
+ cursor_pos: StableCursorPosition::default(),
+ physical_top: 0,
+ top_row: 0,
+ left_col: 0,
+ tty_name: None,
+ }
+ }
+
+ #[test]
+ fn sync_with_pane_tree_preserves_stack_order_and_active_pane() {
+ let size = test_size();
+ let tab = Tab::new(&size);
+ let root = PaneNode::Split {
+ left: Box::new(PaneNode::Stack(PaneStackEntry {
+ active: 1,
+ panes: vec![pane_entry(200, size, false), pane_entry(201, size, true)],
+ })),
+ right: Box::new(PaneNode::Leaf(pane_entry(202, size, false))),
+ node: SplitDirectionAndSize {
+ direction: SplitDirection::Horizontal,
+ first: size,
+ second: size,
+ },
+ };
+
+ tab.sync_with_pane_tree(size, root, |entry| FakePane::new(entry.pane_id, entry.size));
+
+ let all_panes: Vec<_> = tab
+ .iter_all_panes()
+ .iter()
+ .map(|pane| pane.pane_id())
+ .collect();
+ assert_eq!(all_panes, vec![200, 201, 202]);
+ assert_eq!(tab.pane_index_for_pane(200), Some(0));
+ assert_eq!(tab.pane_index_for_pane(201), Some(0));
+ assert_eq!(tab.pane_index_for_pane(202), Some(1));
+
+ let panes = tab.iter_panes();
+ assert_eq!(panes.len(), 2);
+ assert_eq!(panes[0].pane.pane_id(), 201);
+ assert!(panes[0].is_active);
+ assert_eq!(panes[1].pane.pane_id(), 202);
+ assert!(!panes[1].is_active);
+
+ let tabs = tab.pane_stack_tabs(200);
+ assert_eq!(tabs.len(), 2);
+ assert_eq!(tabs[0].pane_id, 200);
+ assert!(!tabs[0].is_active);
+ assert_eq!(tabs[1].pane_id, 201);
+ assert!(tabs[1].is_active);
+ }
+
fn is_send_and_sync<T: Send + Sync>() -> bool {
true
}
diff --git a/mux/src/tmux_commands.rs b/mux/src/tmux_commands.rs
index 537b1891..37d9cba8 100644
--- a/mux/src/tmux_commands.rs
+++ b/mux/src/tmux_commands.rs
@@ -243,12 +243,8 @@ impl TmuxDomainState {
None => anyhow::bail!("Invalid tab id {}", tab_id),
};
- let pane_index = match tab
- .iter_panes_ignoring_zoom()
- .iter()
- .find(|p| p.pane.pane_id() == pane_id)
- {
- Some(p) => p.index,
+ let pane_index = match tab.pane_index_for_pane(pane_id) {
+ Some(index) => index,
None => anyhow::bail!("invalid pane id {}", pane_id),
};
@@ -475,12 +471,8 @@ impl TmuxDomainState {
None => anyhow::bail!("cannot find the local pane for {}", p.pane_id),
};
- split_pane_index = match tab
- .iter_panes_ignoring_zoom()
- .iter()
- .find(|x| x.pane.pane_id() == local_pane_id)
- {
- Some(x) => x.index,
+ split_pane_index = match tab.pane_index_for_pane(local_pane_id) {
+ Some(index) => index,
None => {
log::info!("invalid pane id {local_pane_id}");
continue;
diff --git a/nix/flake.nix b/nix/flake.nix
index 0dfbb39c..f4c03b9e 100644
--- a/nix/flake.nix
+++ b/nix/flake.nix
@@ -143,8 +143,8 @@
''
+ lib.optionalString stdenv.isDarwin /* bash */ ''
mkdir -p "$out/Applications"
- OUT_APP="$out/Applications/WezTerm.app"
- cp -r assets/macos/WezTerm.app "$OUT_APP"
+ OUT_APP="$out/Applications/ThinkTerm.app"
+ cp -r assets/macos/ThinkTerm.app "$OUT_APP"
rm $OUT_APP/*.dylib
cp -r assets/shell-integration/* "$OUT_APP"
# macOS will only recognize our application bundle
diff --git a/wezterm-client/src/domain.rs b/wezterm-client/src/domain.rs
index b4a824bd..75709263 100644
--- a/wezterm-client/src/domain.rs
+++ b/wezterm-client/src/domain.rs
@@ -48,8 +48,8 @@ impl ClientInner {
.retain(
|remote_tab_id, local_tab_id| match mux.get_tab(*local_tab_id) {
Some(tab) => {
- for pos in tab.iter_panes_ignoring_zoom() {
- if pos.pane.domain_id() == self.local_domain_id {
+ for pane in tab.iter_all_panes() {
+ if pane.domain_id() == self.local_domain_id {
return true;
}
}
@@ -72,8 +72,8 @@ impl ClientInner {
|_remote_window_id, local_window_id| match mux.get_window(*local_window_id) {
Some(w) => {
for tab in w.iter() {
- for pos in tab.iter_panes_ignoring_zoom() {
- if pos.pane.domain_id() == self.local_domain_id {
+ for pane in tab.iter_all_panes() {
+ if pane.domain_id() == self.local_domain_id {
return true;
}
}
diff --git a/wezterm-font/src/lib.rs b/wezterm-font/src/lib.rs
index 153482f9..a1bd4c88 100644
--- a/wezterm-font/src/lib.rs
+++ b/wezterm-font/src/lib.rs
@@ -557,20 +557,46 @@ impl FontConfigInner {
}
fn compute_title_font(&self, config: &ConfigHandle, make_bold: bool) -> (TextStyle, f64) {
- fn bold(family: &str) -> FontAttributes {
+ fn weighted(family: &str, weight: FontWeight) -> FontAttributes {
FontAttributes {
family: family.to_string(),
- weight: FontWeight::BOLD,
+ weight,
..Default::default()
}
}
- let mut fonts = vec![if make_bold {
- bold("Roboto")
+ let mut fonts = vec![if cfg!(target_os = "macos") {
+ weighted(
+ ".AppleSystemUIFont",
+ if make_bold {
+ FontWeight::MEDIUM
+ } else {
+ FontWeight::REGULAR
+ },
+ )
+ } else if make_bold {
+ weighted("Roboto", FontWeight::BOLD)
} else {
FontAttributes::new("Roboto")
}];
+ if cfg!(target_os = "macos") {
+ let mut fallback = weighted(
+ "Helvetica Neue",
+ if make_bold {
+ FontWeight::MEDIUM
+ } else {
+ FontWeight::REGULAR
+ },
+ );
+ fallback.is_fallback = true;
+ fonts.push(fallback);
+
+ let mut fallback = weighted(".Lucida Grande UI", FontWeight::MEDIUM);
+ fallback.is_fallback = true;
+ fonts.push(fallback);
+ }
+
// Fallback to their main font selection, so that we can pick up
// any fallback fonts they might have configured in the main
// config and so that they don't have to replicate that list for
@@ -949,12 +975,19 @@ impl FontConfigInner {
pub fn change_scaling(&self, font_scale: f64, dpi: usize) -> (f64, usize) {
let prior_font = *self.font_scale.borrow();
let prior_dpi = *self.dpi.borrow();
+ let dpi_changed = prior_dpi != dpi;
*self.dpi.borrow_mut() = dpi;
*self.font_scale.borrow_mut() = font_scale;
self.fonts.borrow_mut().clear();
self.metrics.borrow_mut().take();
- self.title_font.borrow_mut().take();
+
+ if dpi_changed {
+ self.title_font.borrow_mut().take();
+ self.pane_select_font.borrow_mut().take();
+ self.char_select_font.borrow_mut().take();
+ self.command_palette_font.borrow_mut().take();
+ }
(prior_font, prior_dpi)
}
diff --git a/wezterm-gui-subcommands/src/lib.rs b/wezterm-gui-subcommands/src/lib.rs
index da42ac66..5e809223 100644
--- a/wezterm-gui-subcommands/src/lib.rs
+++ b/wezterm-gui-subcommands/src/lib.rs
@@ -4,7 +4,7 @@ use config::{GuiPosition, SshParameters};
use std::ffi::OsString;
use std::path::PathBuf;
-pub const DEFAULT_WINDOW_CLASS: &str = "org.wezfurlong.wezterm";
+pub const DEFAULT_WINDOW_CLASS: &str = "com.roversx.thinkterm";
/// Helper for parsing config overrides
pub fn name_equals_value(arg: &str) -> Result<(String, String), String> {
@@ -62,7 +62,7 @@ pub struct StartCommand {
pub _cmd: bool,
/// Override the default windowing system class.
- /// The default is "org.wezfurlong.wezterm".
+ /// The default is "com.roversx.thinkterm".
/// Under X11 and Windows this changes the window class.
/// Under Wayland this changes the app_id.
/// This changes the class for all windows spawned by this
@@ -143,7 +143,7 @@ pub struct SshCommand {
pub verbose: bool,
/// Override the default windowing system class.
- /// The default is "org.wezfurlong.wezterm".
+ /// The default is "com.roversx.thinkterm".
/// Under X11 and Windows this changes the window class.
/// Under Wayland this changes the app_id.
/// This changes the class for all windows spawned by this
@@ -175,7 +175,7 @@ pub struct SerialCommand {
pub baud: Option<usize>,
/// Override the default windowing system class.
- /// The default is "org.wezfurlong.wezterm".
+ /// The default is "com.roversx.thinkterm".
/// Under X11 and Windows this changes the window class.
/// Under Wayland this changes the app_id.
/// This changes the class for all windows spawned by this
@@ -213,7 +213,7 @@ pub struct ConnectCommand {
pub new_tab: bool,
/// Override the default windowing system class.
- /// The default is "org.wezfurlong.wezterm".
+ /// The default is "com.roversx.thinkterm".
/// Under X11 and Windows this changes the window class.
/// Under Wayland this changes the app_id.
/// This changes the class for all windows spawned by this
diff --git a/wezterm-gui/Cargo.toml b/wezterm-gui/Cargo.toml
index a9f6cdf8..91e01839 100644
--- a/wezterm-gui/Cargo.toml
+++ b/wezterm-gui/Cargo.toml
@@ -74,6 +74,7 @@ rangeset.workspace = true
ratelim.workspace = true
rayon.workspace = true
regex.workspace = true
+resvg.workspace = true
serde = {workspace=true, features = ["rc", "derive"]}
serde_json.workspace = true
shlex.workspace = true
diff --git a/wezterm-gui/build.rs b/wezterm-gui/build.rs
index 6ffb3c08..1376ca06 100644
--- a/wezterm-gui/build.rs
+++ b/wezterm-gui/build.rs
@@ -165,14 +165,17 @@ END
let src_plist = repo_dir
.join("assets")
.join("macos")
- .join("WezTerm.app")
+ .join("ThinkTerm.app")
.join("Contents")
.join("Info.plist");
let build_target_dir = std::env::var("CARGO_TARGET_DIR")
.and_then(|s| Ok(std::path::PathBuf::from(s)))
.unwrap_or(repo_dir.join("target").join(profile));
let dest_plist = build_target_dir.join("Info.plist");
- println!("cargo:rerun-if-changed=assets/macos/WezTerm.app/Contents/Info.plist");
+ let src_icon = repo_dir.join("assets").join("icon").join("ThinkTerm.icns");
+ let dest_icon = build_target_dir.join("ThinkTerm.icns");
+ println!("cargo:rerun-if-changed=assets/macos/ThinkTerm.app/Contents/Info.plist");
+ println!("cargo:rerun-if-changed=assets/icon/ThinkTerm.icns");
std::fs::copy(&src_plist, &dest_plist)
.context(format!(
@@ -181,5 +184,13 @@ END
dest_plist.display()
))
.unwrap();
+
+ std::fs::copy(&src_icon, &dest_icon)
+ .context(format!(
+ "copy {} -> {}",
+ src_icon.display(),
+ dest_icon.display()
+ ))
+ .unwrap();
}
}
diff --git a/wezterm-gui/src/commands.rs b/wezterm-gui/src/commands.rs
index 581597cd..9fe1d35a 100644
--- a/wezterm-gui/src/commands.rs
+++ b/wezterm-gui/src/commands.rs
@@ -385,6 +385,8 @@ impl CommandDef {
let mut candidates_for_removal = vec![];
#[allow(unexpected_cfgs)] // <https://github.com/SSheldon/rust-objc/issues/125>
let wezterm_perform_key_assignment_sel = sel!(weztermPerformKeyAssignment:);
+ #[allow(unexpected_cfgs)] // <https://github.com/SSheldon/rust-objc/issues/125>
+ let thinkterm_about_sel = sel!(thinktermOrderFrontStandardAboutPanel:);
/// Mark menu items as candidates for removal
fn mark_candidates(menu: &Menu, candidates: &mut Vec<MenuItem>, action: SEL) {
@@ -420,7 +422,7 @@ impl CommandDef {
commands.retain(|cmd| !cmd.menubar.is_empty());
// Prefer to put the menus in this order
- let mut order: Vec<&'static str> = vec!["WezTerm", "Shell", "Edit", "View", "Window"];
+ let mut order: Vec<&'static str> = vec!["ThinkTerm", "Shell", "Edit", "View", "Window"];
// Add any other menus on the end
for cmd in &commands {
if !order.contains(&cmd.menubar[0]) {
@@ -440,21 +442,13 @@ impl CommandDef {
// macOS will insert stuff at the top and bottom, so we add
// a separator to tidy things up a bit
menu.add_item(&MenuItem::new_separator());
- } else if cmd.menubar[0] == "WezTerm" {
+ } else if cmd.menubar[0] == "ThinkTerm" {
menu.assign_as_app_menu();
- let about_item = MenuItem::new_with(
- &format!("WezTerm {}", config::wezterm_version()),
- Some(wezterm_perform_key_assignment_sel),
- "",
- );
- about_item.set_tool_tip("Click to copy version number");
- about_item.set_represented_item(RepresentedItem::KeyAssignment(
- KeyAssignment::CopyTextTo {
- text: config::wezterm_version().to_string(),
- destination: ClipboardCopyDestination::ClipboardAndPrimarySelection,
- },
- ));
+ let about_item =
+ MenuItem::new_with("About ThinkTerm", Some(thinkterm_about_sel), "");
+ about_item.set_target_application_delegate();
+ about_item.set_system_symbol_image("info.circle");
menu.add_item(&about_item);
menu.add_item(&MenuItem::new_separator());
@@ -745,9 +739,17 @@ pub fn derive_command_from_key_assignment(action: &KeyAssignment) -> Option<Comm
.into(),
keys: vec![(Modifiers::SUPER, "h".into())],
args: &[],
- menubar: &["WezTerm"],
+ menubar: &["ThinkTerm"],
icon: None,
},
+ OpenSettings => CommandDef {
+ brief: "Settings...".into(),
+ doc: "Opens the ThinkTerm settings UI".into(),
+ keys: vec![(Modifiers::SUPER, ",".into())],
+ args: &[ArgType::ActiveWindow],
+ menubar: &["ThinkTerm"],
+ icon: Some("cod_settings_gear"),
+ },
SpawnWindow => CommandDef {
brief: "New Window".into(),
doc: "Launches the default program into a new window".into(),
@@ -822,6 +824,22 @@ pub fn derive_command_from_key_assignment(action: &KeyAssignment) -> Option<Comm
menubar: &[],
icon: None,
},
+ PromptRenameTab => CommandDef {
+ brief: "Rename Tab".into(),
+ doc: "Prompts for a new title for the current tab".into(),
+ keys: vec![],
+ args: &[ArgType::ActiveTab],
+ menubar: &[],
+ icon: Some("md_edit"),
+ },
+ PromptRenamePaneTab(_) => CommandDef {
+ brief: "Rename Pane Tab".into(),
+ doc: "Prompts for a new title for the pane-local tab".into(),
+ keys: vec![],
+ args: &[ArgType::ActivePane],
+ menubar: &[],
+ icon: Some("md_edit"),
+ },
QuickSelect => CommandDef {
brief: "Enter QuickSelect mode".into(),
doc: "Activates the quick selection UI for the current pane".into(),
@@ -942,6 +960,14 @@ pub fn derive_command_from_key_assignment(action: &KeyAssignment) -> Option<Comm
menubar: &["View", "Font Size"],
icon: Some("md_format_size"),
},
+ SpawnTabToRight(_) => CommandDef {
+ brief: "New Terminal Tab to Right".into(),
+ doc: "Create a new tab immediately to the right of the current tab".into(),
+ keys: vec![],
+ args: &[ArgType::ActiveWindow],
+ menubar: &[],
+ icon: Some("md_tab_plus"),
+ },
SpawnTab(SpawnTabDomain::CurrentPaneDomain) => CommandDef {
brief: "New Tab".into(),
doc: "Create a new tab in the same domain as the current pane".into(),
@@ -1268,15 +1294,15 @@ pub fn derive_command_from_key_assignment(action: &KeyAssignment) -> Option<Comm
doc: "Reloads the configuration file".into(),
keys: vec![(Modifiers::SUPER, "r".into())],
args: &[],
- menubar: &["WezTerm"],
+ menubar: &["ThinkTerm"],
icon: Some("md_reload"),
},
QuitApplication => CommandDef {
- brief: "Quit WezTerm".into(),
- doc: "Quits WezTerm".into(),
+ brief: "Quit ThinkTerm".into(),
+ doc: "Quits ThinkTerm".into(),
keys: vec![(Modifiers::SUPER, "q".into())],
args: &[],
- menubar: &["WezTerm"],
+ menubar: &["ThinkTerm"],
icon: Some("oct_stop"),
},
MoveTabRelative(-1) => CommandDef {
@@ -2019,8 +2045,9 @@ pub fn derive_command_from_key_assignment(action: &KeyAssignment) -> Option<Comm
fn compute_default_actions() -> Vec<KeyAssignment> {
// These are ordered by their position within the various menus
return vec![
- // ----------------- WezTerm
+ // ----------------- ThinkTerm
ReloadConfiguration,
+ OpenSettings,
#[cfg(target_os = "macos")]
HideApplication,
#[cfg(target_os = "macos")]
diff --git a/wezterm-gui/src/glyphcache.rs b/wezterm-gui/src/glyphcache.rs
index f8674940..7538462e 100644
--- a/wezterm-gui/src/glyphcache.rs
+++ b/wezterm-gui/src/glyphcache.rs
@@ -2,6 +2,7 @@ use super::utilsprites::RenderMetrics;
use crate::customglyph::*;
use crate::renderstate::RenderContext;
use crate::termwindow::render::paint::AllowImage;
+use crate::termwindow::ui::icons::SvgIcon;
use ::window::bitmaps::atlas::{Atlas, OutOfTextureSpace, Sprite};
use ::window::bitmaps::{BitmapImage, Image, ImageTexture, Texture2d};
use ::window::color::SrgbaPixel;
@@ -71,6 +72,12 @@ pub struct SizedBlockKey {
pub size: CellMetricKey,
}
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct SizedSvgIconKey {
+ pub icon: SvgIcon,
+ pub size: u16,
+}
+
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct GlyphKey {
pub font_idx: usize,
@@ -565,6 +572,7 @@ pub struct GlyphCache {
frame_cache: HashMap<[u8; 32], Sprite>,
line_glyphs: HashMap<LineKey, Sprite>,
pub block_glyphs: HashMap<SizedBlockKey, Sprite>,
+ pub svg_icons: HashMap<SizedSvgIconKey, Sprite>,
pub cursor_glyphs: HashMap<(Option<CursorShape>, u8), Sprite>,
pub color: HashMap<(RgbColor, NotNan<f32>), Sprite>,
min_frame_duration: Duration,
@@ -588,6 +596,7 @@ impl GlyphCache {
atlas,
line_glyphs: HashMap::new(),
block_glyphs: HashMap::new(),
+ svg_icons: HashMap::new(),
cursor_glyphs: HashMap::new(),
color: HashMap::new(),
min_frame_duration: Duration::from_millis(1000 / fonts.config().max_fps as u64),
@@ -617,6 +626,7 @@ impl GlyphCache {
atlas,
line_glyphs: HashMap::new(),
block_glyphs: HashMap::new(),
+ svg_icons: HashMap::new(),
cursor_glyphs: HashMap::new(),
color: HashMap::new(),
min_frame_duration: Duration::from_millis(1000 / fonts.config().max_fps as u64),
@@ -1134,6 +1144,23 @@ impl GlyphCache {
Ok(sprite)
}
+ pub fn cached_svg_icon(&mut self, icon: SvgIcon, size: usize) -> anyhow::Result<Sprite> {
+ let size = size.max(1).min(u16::MAX as usize);
+ let key = SizedSvgIconKey {
+ icon,
+ size: size as u16,
+ };
+
+ if let Some(sprite) = self.svg_icons.get(&key) {
+ return Ok(sprite.clone());
+ }
+
+ let image = icon.rasterize(size)?;
+ let sprite = self.atlas.allocate(&image)?;
+ self.svg_icons.insert(key, sprite.clone());
+ Ok(sprite)
+ }
+
pub fn cached_block(
&mut self,
block: BlockKey,
diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rs
index a669a1e7..ef90a6c5 100644
--- a/wezterm-gui/src/main.rs
+++ b/wezterm-gui/src/main.rs
@@ -48,6 +48,7 @@ mod resize_increment_calculator;
mod scripting;
mod scrollbar;
mod selection;
+mod settings_window;
mod shapecache;
mod spawn;
mod stats;
@@ -67,7 +68,7 @@ pub use termwindow::{set_window_class, set_window_position, TermWindow, ICON_DAT
#[derive(Debug, Parser)]
#[command(
- about = "Wez's Terminal Emulator\nhttp://github.com/wezterm/wezterm",
+ about = "ThinkTerm - a workspace-first terminal\nhttps://github.com/RoversX/thinkterm",
version = config::wezterm_version()
)]
struct Opt {
@@ -578,10 +579,12 @@ impl Publish {
let mut cursor = tabroot.into_tree().cursor();
loop {
- if let Some(entry) = cursor.leaf_mut() {
- if entry.pane_id == pane_id {
- window_id.replace(entry.window_id);
- break 'outer;
+ if let Some(stack) = cursor.leaf_mut() {
+ for entry in &stack.panes {
+ if entry.pane_id == pane_id {
+ window_id.replace(entry.window_id);
+ break 'outer;
+ }
}
}
match cursor.preorder_next() {
diff --git a/wezterm-gui/src/overlay/prompt.rs b/wezterm-gui/src/overlay/prompt.rs
index 4c2449b8..ba42e2cf 100644
--- a/wezterm-gui/src/overlay/prompt.rs
+++ b/wezterm-gui/src/overlay/prompt.rs
@@ -48,7 +48,7 @@ impl LineEditorHost for PromptHost {
}
pub fn show_line_prompt_overlay(
- mut term: TermWizTerminal,
+ term: TermWizTerminal,
args: PromptInputLine,
window: GuiWin,
pane: MuxPane,
@@ -60,16 +60,12 @@ pub fn show_line_prompt_overlay(
),
};
- term.no_grab_mouse_in_raw_mode();
- let mut text = args.description.replace("\r\n", "\n").replace("\n", "\r\n");
- text.push_str("\r\n");
- term.render(&[Change::Text(text)])?;
-
- let mut host = PromptHost::new();
- let mut editor = LineEditor::new(&mut term);
- editor.set_prompt(&args.prompt);
- let line =
- editor.read_line_with_optional_initial_value(&mut host, args.initial_value.as_deref())?;
+ let line = read_line_prompt_overlay(
+ term,
+ &args.description,
+ &args.prompt,
+ args.initial_value.as_deref(),
+ )?;
promise::spawn::spawn_into_main_thread(async move {
trampoline(name, window, pane, line);
@@ -80,6 +76,23 @@ pub fn show_line_prompt_overlay(
Ok(())
}
+pub fn read_line_prompt_overlay(
+ mut term: TermWizTerminal,
+ description: &str,
+ prompt: &str,
+ initial_value: Option<&str>,
+) -> anyhow::Result<Option<String>> {
+ term.no_grab_mouse_in_raw_mode();
+ let mut text = description.replace("\r\n", "\n").replace("\n", "\r\n");
+ text.push_str("\r\n");
+ term.render(&[Change::Text(text)])?;
+
+ let mut host = PromptHost::new();
+ let mut editor = LineEditor::new(&mut term);
+ editor.set_prompt(prompt);
+ Ok(editor.read_line_with_optional_initial_value(&mut host, initial_value)?)
+}
+
fn trampoline(name: String, window: GuiWin, pane: MuxPane, line: Option<String>) {
promise::spawn::spawn(async move {
config::with_lua_config_on_main_thread(move |lua| do_event(lua, name, window, pane, line))
diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rs
new file mode 100644
index 00000000..913132fa
--- /dev/null
+++ b/wezterm-gui/src/settings_window.rs
@@ -0,0 +1,1743 @@
+use crate::colorease::ColorEaseUniform;
+use crate::customglyph::{BlockKey, Poly};
+use crate::quad::{QuadTrait, TripleLayerQuadAllocator, TripleLayerQuadAllocatorTrait};
+use crate::renderstate::{RenderContext, RenderState};
+use crate::termwindow::render::corners::{
+ BOTTOM_LEFT_ROUNDED_CORNER, BOTTOM_RIGHT_ROUNDED_CORNER, TOP_LEFT_ROUNDED_CORNER,
+ TOP_RIGHT_ROUNDED_CORNER,
+};
+use crate::uniforms::UniformBuilder;
+use crate::utilsprites::RenderMetrics;
+use anyhow::Context;
+use config::{configuration, Dimension, GeometryOrigin};
+use std::cell::RefCell;
+use std::path::PathBuf;
+use std::rc::Rc;
+use wezterm_bidi::Direction;
+use wezterm_font::{FontConfiguration, LoadedFont};
+use window::bitmaps::atlas::OutOfTextureSpace;
+use window::color::LinearRgba;
+use window::glium;
+use window::glium::texture::SrgbTexture2d;
+use window::glium::uniforms::{
+ MagnifySamplerFilter, MinifySamplerFilter, Sampler, SamplerWrapFunction,
+};
+use window::glium::{BlendingFunction, LinearBlendingFactor, Surface};
+use window::{
+ Appearance, Connection, ConnectionOps, Dimensions, MouseButtons, MouseCursor, MouseEvent,
+ MouseEventKind, MousePress, RequestedWindowGeometry, Window, WindowEvent, WindowOps,
+};
+
+const DEFAULT_WIDTH: usize = 1180;
+const DEFAULT_HEIGHT: usize = 760;
+const SIDEBAR_WIDTH: f32 = 286.0;
+const CONTROL_HEIGHT: f32 = 42.0;
+const CONTROL_RADIUS: f32 = 8.0;
+const NAV_ROW_RADIUS: f32 = 7.0;
+const NAV_ROW_HEIGHT: f32 = 40.0;
+const NAV_ROW_STEP: f32 = 44.0;
+
+thread_local! {
+ static SETTINGS_WINDOW: RefCell<Option<Rc<RefCell<SettingsWindow>>>> = RefCell::new(None);
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum SettingsSection {
+ General,
+ Appearance,
+ Terminal,
+ Workspaces,
+ Keymap,
+ WezTermSync,
+ Developer,
+}
+
+const SECTIONS: &[SettingsSection] = &[
+ SettingsSection::General,
+ SettingsSection::Appearance,
+ SettingsSection::Terminal,
+ SettingsSection::Workspaces,
+ SettingsSection::Keymap,
+ SettingsSection::WezTermSync,
+ SettingsSection::Developer,
+];
+
+impl SettingsSection {
+ fn label(self) -> &'static str {
+ match self {
+ Self::General => "General",
+ Self::Appearance => "Appearance",
+ Self::Terminal => "Terminal",
+ Self::Workspaces => "Workspaces",
+ Self::Keymap => "Keymap",
+ Self::WezTermSync => "WezTerm Sync",
+ Self::Developer => "Developer",
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum SettingsAction {
+ Select(SettingsSection),
+ OpenWezTermConfig,
+ PrepareWezTermSync,
+}
+
+#[derive(Debug, Clone)]
+struct HitTarget {
+ rect: window::RectF,
+ action: SettingsAction,
+}
+
+struct StyleToken<'a> {
+ name: &'a str,
+ value: &'a str,
+ swatch: Option<LinearRgba>,
+}
+
+#[derive(Clone, Copy)]
+struct SettingsPalette {
+ window_bg: LinearRgba,
+ sidebar_bg: LinearRgba,
+ separator: LinearRgba,
+ search_bg: LinearRgba,
+ search_border: LinearRgba,
+ nav_hover_bg: LinearRgba,
+ nav_pressed_bg: LinearRgba,
+ nav_selected_bg: LinearRgba,
+ control_bg: LinearRgba,
+ control_hover_bg: LinearRgba,
+ control_pressed_bg: LinearRgba,
+ control_border: LinearRgba,
+ title: LinearRgba,
+ text: LinearRgba,
+ secondary_text: LinearRgba,
+ muted_text: LinearRgba,
+ selected_text: LinearRgba,
+ rule: LinearRgba,
+}
+
+pub fn show() {
+ let already_open = SETTINGS_WINDOW.with(|slot| {
+ if let Some(settings) = slot.borrow().as_ref() {
+ if let Some(window) = settings.borrow().window.as_ref() {
+ window.show();
+ window.focus();
+ return true;
+ }
+ }
+ false
+ });
+
+ if already_open {
+ return;
+ }
+
+ promise::spawn::spawn(async {
+ if let Err(err) = SettingsWindow::open().await {
+ log::error!("failed to open settings window: {err:#}");
+ }
+ })
+ .detach();
+}
+
+struct SettingsWindow {
+ window: Option<Window>,
+ dimensions: Dimensions,
+ fonts: Rc<FontConfiguration>,
+ ui_font: Rc<LoadedFont>,
+ title_font: Rc<LoadedFont>,
+ metrics: RenderMetrics,
+ render_state: Option<RenderState>,
+ appearance: Appearance,
+ selected: SettingsSection,
+ hit_targets: Vec<HitTarget>,
+ hovered_action: Option<SettingsAction>,
+ pressed_action: Option<SettingsAction>,
+ status: String,
+}
+
+impl SettingsWindow {
+ async fn open() -> anyhow::Result<()> {
+ let config = configuration();
+ let dpi = window::default_dpi() as usize;
+ let fonts = Rc::new(FontConfiguration::new(Some(config.clone()), dpi)?);
+ let title_font = fonts.title_font()?;
+ let ui_font = Rc::clone(&title_font);
+ let metrics = RenderMetrics::with_font_metrics(&ui_font.metrics());
+ let appearance = Connection::get()
+ .map(|conn| conn.get_appearance())
+ .unwrap_or(Appearance::Dark);
+
+ let settings = Rc::new(RefCell::new(Self {
+ window: None,
+ dimensions: Dimensions {
+ pixel_width: DEFAULT_WIDTH,
+ pixel_height: DEFAULT_HEIGHT,
+ dpi,
+ },
+ fonts: Rc::clone(&fonts),
+ ui_font,
+ title_font,
+ metrics,
+ render_state: None,
+ appearance,
+ selected: SettingsSection::Appearance,
+ hit_targets: Vec::new(),
+ hovered_action: None,
+ pressed_action: None,
+ status: Self::initial_status(),
+ }));
+
+ let event_settings = Rc::clone(&settings);
+ let geometry = RequestedWindowGeometry {
+ width: Dimension::Pixels(DEFAULT_WIDTH as f32),
+ height: Dimension::Pixels(DEFAULT_HEIGHT as f32),
+ x: None,
+ y: None,
+ origin: GeometryOrigin::default(),
+ };
+
+ let window = Window::new_window(
+ "thinkterm-settings",
+ "ThinkTerm Settings",
+ geometry,
+ Some(&config),
+ Rc::clone(&fonts),
+ move |event, window| {
+ if let Err(err) = event_settings.borrow_mut().dispatch(event, window) {
+ log::error!("settings window event failed: {err:#}");
+ }
+ },
+ )
+ .await?;
+
+ window.set_title("ThinkTerm Settings");
+ let gl = window.enable_opengl().await?;
+ settings
+ .borrow_mut()
+ .created(RenderContext::Glium(Rc::clone(&gl)))?;
+ settings.borrow_mut().window.replace(window.clone());
+
+ SETTINGS_WINDOW.with(|slot| slot.replace(Some(settings)));
+
+ window.show();
+ window.invalidate();
+
+ Ok(())
+ }
+
+ fn created(&mut self, context: RenderContext) -> anyhow::Result<()> {
+ self.render_state
+ .replace(RenderState::new(context, &self.fonts, &self.metrics, 256)?);
+ Ok(())
+ }
+
+ fn dispatch(&mut self, event: WindowEvent, window: &Window) -> anyhow::Result<bool> {
+ match event {
+ WindowEvent::CloseRequested => {
+ window.close();
+ Ok(true)
+ }
+ WindowEvent::Destroyed => {
+ SETTINGS_WINDOW.with(|slot| {
+ slot.borrow_mut().take();
+ });
+ Ok(true)
+ }
+ WindowEvent::Resized { dimensions, .. } => {
+ self.dimensions = dimensions;
+ window.invalidate();
+ Ok(true)
+ }
+ WindowEvent::NeedRepaint => Ok(self.do_paint(window)),
+ WindowEvent::MouseEvent(event) => {
+ self.mouse_event(event, window);
+ Ok(true)
+ }
+ WindowEvent::MouseLeave => {
+ self.hovered_action = None;
+ self.pressed_action = None;
+ window.set_cursor(Some(MouseCursor::Arrow));
+ window.invalidate();
+ Ok(true)
+ }
+ WindowEvent::AppearanceChanged(appearance) => {
+ self.appearance = appearance;
+ window.invalidate();
+ Ok(true)
+ }
+ _ => Ok(true),
+ }
+ }
+
+ fn mouse_event(&mut self, event: MouseEvent, window: &Window) {
+ let x = event.coords.x as f32;
+ let y = event.coords.y as f32;
+ let action = self.action_at(x, y);
+
+ match event.kind {
+ MouseEventKind::Move => {
+ if self.hovered_action != action {
+ self.hovered_action = action;
+ window.set_cursor(Some(if action.is_some() {
+ MouseCursor::Hand
+ } else {
+ MouseCursor::Arrow
+ }));
+ window.invalidate();
+ }
+ }
+ MouseEventKind::Press(MousePress::Left) => {
+ self.hovered_action = action;
+ self.pressed_action = action;
+ if action.is_some() {
+ window.invalidate();
+ }
+ }
+ MouseEventKind::Release(MousePress::Left) => {
+ let pressed = self.pressed_action.take();
+ self.hovered_action = action;
+ if pressed.is_some() && pressed == action {
+ self.perform_action(action.unwrap());
+ }
+ window.invalidate();
+ }
+ _ if event.mouse_buttons == MouseButtons::NONE => {
+ if self.pressed_action.take().is_some() {
+ window.invalidate();
+ }
+ }
+ _ => {}
+ }
+ }
+
+ fn action_at(&self, x: f32, y: f32) -> Option<SettingsAction> {
+ self.hit_targets
+ .iter()
+ .find(|target| target.rect.contains(euclid::point2(x, y)))
+ .map(|target| target.action)
+ }
+
+ fn palette(&self) -> SettingsPalette {
+ match self.appearance {
+ Appearance::Light | Appearance::LightHighContrast => SettingsPalette {
+ window_bg: rgb(242, 242, 247),
+ sidebar_bg: rgb(246, 246, 248),
+ separator: rgba(60, 60, 67, 0.18),
+ search_bg: rgba(255, 255, 255, 0.92),
+ search_border: rgba(60, 60, 67, 0.20),
+ nav_hover_bg: rgba(60, 60, 67, 0.08),
+ nav_pressed_bg: rgba(60, 60, 67, 0.14),
+ nav_selected_bg: rgba(0, 122, 255, 0.88),
+ control_bg: rgba(255, 255, 255, 0.90),
+ control_hover_bg: rgba(249, 249, 251, 0.96),
+ control_pressed_bg: rgba(232, 242, 255, 0.98),
+ control_border: rgba(60, 60, 67, 0.20),
+ title: rgb(28, 28, 30),
+ text: rgb(28, 28, 30),
+ secondary_text: rgb(72, 72, 74),
+ muted_text: rgb(142, 142, 147),
+ selected_text: rgb(255, 255, 255),
+ rule: rgba(60, 60, 67, 0.16),
+ },
+ Appearance::Dark | Appearance::DarkHighContrast => SettingsPalette {
+ window_bg: rgb(28, 28, 30),
+ sidebar_bg: rgb(36, 36, 38),
+ separator: rgba(84, 84, 88, 0.55),
+ search_bg: rgba(58, 58, 60, 0.72),
+ search_border: rgba(99, 99, 102, 0.48),
+ nav_hover_bg: rgba(99, 99, 102, 0.26),
+ nav_pressed_bg: rgba(99, 99, 102, 0.36),
+ nav_selected_bg: rgba(10, 132, 255, 0.86),
+ control_bg: rgba(58, 58, 60, 0.70),
+ control_hover_bg: rgba(72, 72, 74, 0.76),
+ control_pressed_bg: rgba(64, 82, 112, 0.88),
+ control_border: rgba(99, 99, 102, 0.46),
+ title: rgb(242, 242, 247),
+ text: rgb(242, 242, 247),
+ secondary_text: rgb(199, 199, 204),
+ muted_text: rgb(142, 142, 147),
+ selected_text: rgb(255, 255, 255),
+ rule: rgba(84, 84, 88, 0.46),
+ },
+ }
+ }
+
+ fn perform_action(&mut self, action: SettingsAction) {
+ match action {
+ SettingsAction::Select(section) => {
+ self.selected = section;
+ }
+ SettingsAction::OpenWezTermConfig => {
+ if let Some(path) = Self::wezterm_config_source() {
+ self.status = format!("Opening {}", path.display());
+ Self::open_path(path);
+ } else {
+ self.status = "No wezterm.lua was found yet".to_string();
+ }
+ }
+ SettingsAction::PrepareWezTermSync => {
+ self.status = match Self::wezterm_config_source() {
+ Some(path) => format!(
+ "Ready to sync from {}. Import backend is intentionally pending.",
+ path.display()
+ ),
+ None => "Create or choose a WezTerm config before syncing".to_string(),
+ };
+ }
+ }
+ }
+
+ fn do_paint(&mut self, window: &Window) -> bool {
+ let gl = match self.render_state.as_ref().map(|state| &state.context) {
+ Some(RenderContext::Glium(gl)) => Rc::clone(gl),
+ _ => return false,
+ };
+
+ if gl.is_context_lost() {
+ log::error!("settings window opengl context was lost");
+ window.close();
+ return false;
+ }
+
+ for _ in 0..3 {
+ match self.paint_pass() {
+ Ok(()) => match self.render_state.as_mut().unwrap().allocated_more_quads() {
+ Ok(true) => continue,
+ Ok(false) => break,
+ Err(err) => {
+ log::error!("settings window quad allocation failed: {err:#}");
+ break;
+ }
+ },
+ Err(err) => {
+ if let Some(&OutOfTextureSpace {
+ size: Some(size),
+ current_size,
+ }) = err.root_cause().downcast_ref::<OutOfTextureSpace>()
+ {
+ let size = size.max(current_size);
+ if let Err(err) = self
+ .render_state
+ .as_mut()
+ .unwrap()
+ .recreate_texture_atlas(&self.fonts, &self.metrics, Some(size))
+ {
+ log::error!("settings window texture atlas resize failed: {err:#}");
+ break;
+ }
+ continue;
+ }
+ log::error!("settings window paint failed: {err:#}");
+ break;
+ }
+ }
+ }
+
+ let mut frame = glium::Frame::new(
+ gl,
+ (
+ self.dimensions.pixel_width as u32,
+ self.dimensions.pixel_height as u32,
+ ),
+ );
+ let result = self.call_draw_glium(&mut frame);
+ result.and_then(|_| window.finish_frame(frame)).is_ok()
+ }
+
+ fn paint_pass(&mut self) -> anyhow::Result<()> {
+ if let Some(render_state) = self.render_state.as_ref() {
+ for layer in render_state.layers.borrow().iter() {
+ layer.clear_quad_allocation();
+ }
+ }
+
+ self.hit_targets.clear();
+ let layer = self
+ .render_state
+ .as_ref()
+ .context("settings render state not initialized")?
+ .layer_for_zindex(0)?;
+ let mut layers = layer.quad_allocator();
+
+ self.paint_background(&mut layers)?;
+ self.paint_sidebar(&mut layers)?;
+ self.paint_content(&mut layers)?;
+ self.paint_status(&mut layers)?;
+
+ Ok(())
+ }
+
+ fn paint_background(&self, layers: &mut TripleLayerQuadAllocator<'_>) -> anyhow::Result<()> {
+ let palette = self.palette();
+ let width = self.dimensions.pixel_width as f32;
+ let height = self.dimensions.pixel_height as f32;
+ self.draw_rect(layers, 0, 0.0, 0.0, width, height, palette.window_bg)?;
+ self.draw_rect(
+ layers,
+ 0,
+ 0.0,
+ 0.0,
+ SIDEBAR_WIDTH,
+ height,
+ palette.sidebar_bg,
+ )?;
+ self.draw_rect(
+ layers,
+ 0,
+ SIDEBAR_WIDTH,
+ 0.0,
+ 1.0,
+ height,
+ palette.separator,
+ )?;
+ Ok(())
+ }
+
+ fn paint_sidebar(&mut self, layers: &mut TripleLayerQuadAllocator<'_>) -> anyhow::Result<()> {
+ let palette = self.palette();
+ let ui_font = Rc::clone(&self.ui_font);
+ let title_font = Rc::clone(&self.title_font);
+
+ self.draw_text(
+ layers,
+ &title_font,
+ 28.0,
+ 32.0,
+ "ThinkTerm Settings",
+ palette.title,
+ SIDEBAR_WIDTH - 56.0,
+ )?;
+
+ self.draw_rounded_frame(
+ layers,
+ 0,
+ 22.0,
+ 78.0,
+ SIDEBAR_WIDTH - 44.0,
+ 42.0,
+ palette.search_bg,
+ palette.search_border,
+ CONTROL_RADIUS,
+ )?;
+ self.draw_text(
+ layers,
+ &ui_font,
+ 40.0,
+ self.control_text_y(78.0, CONTROL_HEIGHT),
+ "Search settings...",
+ palette.muted_text,
+ SIDEBAR_WIDTH - 72.0,
+ )?;
+
+ let mut y = 148.0;
+ for &section in SECTIONS {
+ let action = SettingsAction::Select(section);
+ let selected = section == self.selected;
+ let hovered = self.hovered_action == Some(action);
+ let pressed = self.pressed_action == Some(action);
+ let row_y = y - 6.0;
+ let row_x = 18.0;
+ let row_width = SIDEBAR_WIDTH - 36.0;
+ let row_bg = if selected {
+ Some(palette.nav_selected_bg)
+ } else if pressed {
+ Some(palette.nav_pressed_bg)
+ } else if hovered {
+ Some(palette.nav_hover_bg)
+ } else {
+ None
+ };
+ if let Some(row_bg) = row_bg {
+ self.draw_rounded_rect(
+ layers,
+ 0,
+ row_x,
+ row_y,
+ row_width,
+ NAV_ROW_HEIGHT,
+ row_bg,
+ NAV_ROW_RADIUS,
+ )?;
+ }
+
+ self.hit_targets.push(HitTarget {
+ rect: euclid::rect(row_x, row_y, row_width, NAV_ROW_HEIGHT),
+ action,
+ });
+ self.draw_text(
+ layers,
+ &ui_font,
+ row_x + 16.0,
+ self.control_text_y(row_y, NAV_ROW_HEIGHT),
+ section.label(),
+ if selected {
+ palette.selected_text
+ } else {
+ palette.secondary_text
+ },
+ row_width - 32.0,
+ )?;
+ y += NAV_ROW_STEP;
+ }
+
+ Ok(())
+ }
+
+ fn paint_content(&mut self, layers: &mut TripleLayerQuadAllocator<'_>) -> anyhow::Result<()> {
+ let palette = self.palette();
+ let ui_font = Rc::clone(&self.ui_font);
+ let title_font = Rc::clone(&self.title_font);
+ let x = SIDEBAR_WIDTH + 46.0;
+ let max_width = self.dimensions.pixel_width as f32 - x - 50.0;
+
+ self.draw_text(
+ layers,
+ &title_font,
+ x,
+ 54.0,
+ self.selected.label(),
+ palette.title,
+ max_width,
+ )?;
+ let edit_button_width = 260.0_f32.min((max_width * 0.48).max(210.0));
+ self.draw_button(
+ layers,
+ x + max_width - edit_button_width,
+ 34.0,
+ edit_button_width,
+ "Open wezterm.lua",
+ SettingsAction::OpenWezTermConfig,
+ )?;
+
+ match self.selected {
+ SettingsSection::Appearance => self.paint_appearance(layers, x, max_width)?,
+ SettingsSection::WezTermSync => self.paint_wezterm_sync(layers, x, max_width)?,
+ SettingsSection::General => self.paint_placeholder(
+ layers,
+ &ui_font,
+ x,
+ "Startup behavior, default shell, launch directory, and update policy.",
+ max_width,
+ )?,
+ SettingsSection::Terminal => self.paint_placeholder(
+ layers,
+ &ui_font,
+ x,
+ "Terminal font, cursor, selection, bell, scrollback, and pane defaults.",
+ max_width,
+ )?,
+ SettingsSection::Workspaces => self.paint_placeholder(
+ layers,
+ &ui_font,
+ x,
+ "Workspace list, default workspace, sidebar behavior, and saved layouts.",
+ max_width,
+ )?,
+ SettingsSection::Keymap => self.paint_placeholder(
+ layers,
+ &ui_font,
+ x,
+ "Keyboard shortcuts and command palette actions.",
+ max_width,
+ )?,
+ SettingsSection::Developer => self.paint_developer(layers, x, max_width)?,
+ }
+
+ Ok(())
+ }
+
+ fn paint_appearance(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ x: f32,
+ max_width: f32,
+ ) -> anyhow::Result<()> {
+ let palette = self.palette();
+ let ui_font = Rc::clone(&self.ui_font);
+
+ self.draw_text(
+ layers,
+ &ui_font,
+ x,
+ 112.0,
+ "Theme",
+ palette.muted_text,
+ max_width,
+ )?;
+ self.draw_rect(layers, 0, x, 142.0, max_width, 1.0, palette.rule)?;
+
+ let mut y = 186.0;
+ self.paint_setting_row(
+ layers,
+ x,
+ y,
+ max_width,
+ "Theme Mode",
+ "Follow macOS appearance and choose light/dark schemes automatically.",
+ "System",
+ )?;
+ y += 102.0;
+ self.paint_setting_row(
+ layers,
+ x,
+ y,
+ max_width,
+ "Light Theme",
+ "Theme used when the system is in light appearance.",
+ "Apple System Colors Light",
+ )?;
+ y += 102.0;
+ self.paint_setting_row(
+ layers,
+ x,
+ y,
+ max_width,
+ "Dark Theme",
+ "Theme used when the system is in dark appearance.",
+ "Apple System Colors",
+ )?;
+ y += 102.0;
+ self.paint_setting_row(
+ layers,
+ x,
+ y,
+ max_width,
+ "Interface Font",
+ "Settings and sidebar use the macOS system UI font, separate from terminal text.",
+ "System UI",
+ )?;
+
+ Ok(())
+ }
+
+ fn paint_developer(
+ &self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ x: f32,
+ max_width: f32,
+ ) -> anyhow::Result<()> {
+ let palette = self.palette();
+ let ui_font = Rc::clone(&self.ui_font);
+
+ self.draw_text(
+ layers,
+ &ui_font,
+ x,
+ 112.0,
+ "Live settings UI components. The left side is rendered with the same primitives as the real window.",
+ palette.secondary_text,
+ max_width,
+ )?;
+ self.draw_rect(layers, 0, x, 146.0, max_width, 1.0, palette.rule)?;
+
+ let preview_width = (max_width * 0.58).min(560.0);
+ let notes_x = x + preview_width + 34.0;
+ let notes_width = (max_width - preview_width - 34.0).max(240.0);
+
+ self.draw_text(
+ layers,
+ &ui_font,
+ x,
+ 184.0,
+ "Component Preview",
+ palette.title,
+ preview_width,
+ )?;
+ self.draw_rect(layers, 0, x, 214.0, preview_width, 1.0, palette.rule)?;
+ self.paint_preview_search(layers, x, 238.0, preview_width)?;
+
+ self.draw_text(
+ layers,
+ &ui_font,
+ x,
+ 322.0,
+ "Sidebar Rows",
+ palette.title,
+ preview_width,
+ )?;
+ self.paint_preview_sidebar_row(layers, x, 356.0, preview_width, "General", false)?;
+ self.paint_preview_sidebar_row(layers, x, 402.0, preview_width, "Appearance", true)?;
+
+ self.draw_text(
+ layers,
+ &ui_font,
+ x,
+ 468.0,
+ "Buttons and Controls",
+ palette.title,
+ preview_width,
+ )?;
+ self.paint_preview_button(layers, x, 502.0, 176.0, "Normal Button", false)?;
+ self.paint_preview_button(layers, x + 194.0, 502.0, 162.0, "Accent Button", true)?;
+ self.paint_preview_control(layers, x, 554.0, 220.0, "System")?;
+
+ self.draw_text(
+ layers,
+ &ui_font,
+ x,
+ 590.0,
+ "Setting Row",
+ palette.title,
+ preview_width,
+ )?;
+ self.paint_setting_row(
+ layers,
+ x,
+ 626.0,
+ preview_width,
+ "Theme Mode",
+ "Follow macOS appearance.",
+ "System",
+ )?;
+
+ let component_tokens = [
+ StyleToken {
+ name: "search.field",
+ value: "h42 bg+top border",
+ swatch: Some(palette.search_bg),
+ },
+ StyleToken {
+ name: "nav.active.row",
+ value: "h40 system selection",
+ swatch: Some(palette.nav_selected_bg),
+ },
+ StyleToken {
+ name: "button.normal",
+ value: "h42 rounded hover",
+ swatch: Some(palette.control_bg),
+ },
+ StyleToken {
+ name: "button.accent",
+ value: "h42 active bg",
+ swatch: Some(palette.control_pressed_bg),
+ },
+ StyleToken {
+ name: "control.select",
+ value: "h42 rounded select",
+ swatch: Some(palette.control_bg),
+ },
+ StyleToken {
+ name: "setting.row",
+ value: "rule + label/value",
+ swatch: Some(palette.rule),
+ },
+ ];
+
+ let layout_tokens = [
+ StyleToken {
+ name: "window",
+ value: "1180 x 760",
+ swatch: None,
+ },
+ StyleToken {
+ name: "sidebar",
+ value: "286 px",
+ swatch: None,
+ },
+ StyleToken {
+ name: "content",
+ value: "46 gap / 50 margin",
+ swatch: None,
+ },
+ StyleToken {
+ name: "rows",
+ value: "nav40/44 setting102",
+ swatch: None,
+ },
+ ];
+
+ let cell_size = format!(
+ "{} x {} px",
+ self.metrics.cell_size.width, self.metrics.cell_size.height
+ );
+ let dpi = format!("{} dpi", self.dimensions.dpi);
+ let type_tokens = [
+ StyleToken {
+ name: "ui.font",
+ value: "macOS title font",
+ swatch: None,
+ },
+ StyleToken {
+ name: "title.font",
+ value: "window title font",
+ swatch: None,
+ },
+ StyleToken {
+ name: "cell size",
+ value: &cell_size,
+ swatch: None,
+ },
+ StyleToken {
+ name: "window dpi",
+ value: &dpi,
+ swatch: None,
+ },
+ ];
+
+ self.paint_style_group(
+ layers,
+ notes_x,
+ 184.0,
+ notes_width,
+ "Component Styles",
+ &component_tokens,
+ )?;
+ self.paint_style_group(
+ layers,
+ notes_x,
+ 410.0,
+ notes_width,
+ "Typography",
+ &type_tokens,
+ )?;
+ self.paint_style_group(
+ layers,
+ notes_x,
+ 552.0,
+ notes_width,
+ "Layout",
+ &layout_tokens,
+ )?;
+
+ Ok(())
+ }
+
+ fn paint_preview_search(
+ &self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ x: f32,
+ y: f32,
+ width: f32,
+ ) -> anyhow::Result<()> {
+ let palette = self.palette();
+ let ui_font = Rc::clone(&self.ui_font);
+ self.draw_text(layers, &ui_font, x, y, "Search Field", palette.title, width)?;
+ self.draw_rounded_frame(
+ layers,
+ 0,
+ x,
+ y + 28.0,
+ width.min(360.0),
+ CONTROL_HEIGHT,
+ palette.search_bg,
+ palette.search_border,
+ CONTROL_RADIUS,
+ )?;
+ self.draw_text(
+ layers,
+ &ui_font,
+ x + 18.0,
+ self.control_text_y(y + 28.0, CONTROL_HEIGHT),
+ "Search settings...",
+ palette.muted_text,
+ width.min(360.0) - 36.0,
+ )?;
+ Ok(())
+ }
+
+ fn paint_preview_sidebar_row(
+ &self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ x: f32,
+ y: f32,
+ width: f32,
+ label: &str,
+ selected: bool,
+ ) -> anyhow::Result<()> {
+ let palette = self.palette();
+ let ui_font = Rc::clone(&self.ui_font);
+ let row_width = width.min(360.0);
+ if selected {
+ self.draw_rounded_rect(
+ layers,
+ 0,
+ x,
+ y,
+ row_width,
+ 36.0,
+ palette.nav_selected_bg,
+ NAV_ROW_RADIUS,
+ )?;
+ } else {
+ self.draw_rounded_rect(
+ layers,
+ 0,
+ x,
+ y,
+ row_width,
+ 36.0,
+ palette.nav_hover_bg,
+ NAV_ROW_RADIUS,
+ )?;
+ }
+ self.draw_text(
+ layers,
+ &ui_font,
+ x + 16.0,
+ self.control_text_y(y, 36.0),
+ label,
+ if selected {
+ palette.selected_text
+ } else {
+ palette.secondary_text
+ },
+ row_width - 32.0,
+ )?;
+ Ok(())
+ }
+
+ fn paint_preview_button(
+ &self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ x: f32,
+ y: f32,
+ width: f32,
+ label: &str,
+ accent: bool,
+ ) -> anyhow::Result<()> {
+ let palette = self.palette();
+ let bg = if accent {
+ palette.nav_selected_bg
+ } else {
+ palette.control_bg
+ };
+ self.draw_rounded_frame(
+ layers,
+ 0,
+ x,
+ y,
+ width,
+ CONTROL_HEIGHT,
+ bg,
+ palette.control_border,
+ CONTROL_RADIUS,
+ )?;
+ self.draw_text(
+ layers,
+ &Rc::clone(&self.ui_font),
+ x + 14.0,
+ self.control_text_y(y, CONTROL_HEIGHT),
+ label,
+ if accent {
+ palette.selected_text
+ } else {
+ palette.text
+ },
+ width - 28.0,
+ )?;
+ Ok(())
+ }
+
+ fn paint_preview_control(
+ &self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ x: f32,
+ y: f32,
+ width: f32,
+ value: &str,
+ ) -> anyhow::Result<()> {
+ let palette = self.palette();
+ self.draw_rounded_frame(
+ layers,
+ 0,
+ x,
+ y,
+ width,
+ CONTROL_HEIGHT,
+ palette.control_bg,
+ palette.control_border,
+ CONTROL_RADIUS,
+ )?;
+ self.draw_text(
+ layers,
+ &Rc::clone(&self.ui_font),
+ x + 14.0,
+ self.control_text_y(y, CONTROL_HEIGHT),
+ value,
+ palette.text,
+ width - 42.0,
+ )?;
+ self.draw_text(
+ layers,
+ &Rc::clone(&self.ui_font),
+ x + width - 28.0,
+ self.control_text_y(y, CONTROL_HEIGHT),
+ "v",
+ palette.muted_text,
+ 14.0,
+ )?;
+ Ok(())
+ }
+
+ fn paint_style_group(
+ &self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ x: f32,
+ y: f32,
+ width: f32,
+ title: &str,
+ tokens: &[StyleToken<'_>],
+ ) -> anyhow::Result<()> {
+ let palette = self.palette();
+ self.draw_text(
+ layers,
+ &Rc::clone(&self.ui_font),
+ x,
+ y,
+ title,
+ palette.title,
+ width,
+ )?;
+ self.draw_rect(layers, 0, x, y + 28.0, width, 1.0, palette.rule)?;
+
+ let mut row_y = y + 52.0;
+ for token in tokens {
+ self.paint_style_token(
+ layers,
+ x,
+ row_y,
+ width,
+ token.name,
+ token.value,
+ token.swatch,
+ )?;
+ row_y += 26.0;
+ }
+
+ Ok(())
+ }
+
+ fn paint_style_token(
+ &self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ x: f32,
+ y: f32,
+ width: f32,
+ name: &str,
+ value: &str,
+ swatch: Option<LinearRgba>,
+ ) -> anyhow::Result<()> {
+ let palette = self.palette();
+ let name_x = if let Some(color) = swatch {
+ self.draw_rect(layers, 0, x, y + 3.0, 14.0, 14.0, color)?;
+ self.draw_rect(layers, 0, x, y + 3.0, 14.0, 1.0, rgba(255, 255, 255, 0.18))?;
+ x + 22.0
+ } else {
+ x
+ };
+ let value_x = x + width * 0.48;
+ self.draw_text(
+ layers,
+ &Rc::clone(&self.ui_font),
+ name_x,
+ y,
+ name,
+ palette.secondary_text,
+ (value_x - name_x - 12.0).max(80.0),
+ )?;
+ self.draw_text(
+ layers,
+ &Rc::clone(&self.ui_font),
+ value_x,
+ y,
+ value,
+ palette.text,
+ (x + width - value_x).max(80.0),
+ )?;
+ Ok(())
+ }
+
+ fn paint_wezterm_sync(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ x: f32,
+ max_width: f32,
+ ) -> anyhow::Result<()> {
+ let palette = self.palette();
+ let ui_font = Rc::clone(&self.ui_font);
+ let source = Self::wezterm_config_source()
+ .map(|path| path.display().to_string())
+ .unwrap_or_else(|| "No wezterm.lua found".to_string());
+
+ self.draw_text(
+ layers,
+ &ui_font,
+ x,
+ 112.0,
+ "Import and mirror existing WezTerm configuration without overwriting it first.",
+ palette.secondary_text,
+ max_width,
+ )?;
+ self.paint_setting_row(
+ layers,
+ x,
+ 166.0,
+ max_width,
+ "Detected Source",
+ &source,
+ "Read only",
+ )?;
+ self.paint_setting_row(
+ layers,
+ x,
+ 268.0,
+ max_width,
+ "ThinkTerm Target",
+ "Not connected yet",
+ "Pending",
+ )?;
+ self.draw_button(
+ layers,
+ x,
+ 390.0,
+ 240.0,
+ "Open WezTerm Config",
+ SettingsAction::OpenWezTermConfig,
+ )?;
+ self.draw_button(
+ layers,
+ x + 256.0,
+ 390.0,
+ 176.0,
+ "Prepare Sync",
+ SettingsAction::PrepareWezTermSync,
+ )?;
+
+ Ok(())
+ }
+
+ fn paint_placeholder(
+ &self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ font: &Rc<LoadedFont>,
+ x: f32,
+ body: &str,
+ max_width: f32,
+ ) -> anyhow::Result<()> {
+ let palette = self.palette();
+ self.draw_text(
+ layers,
+ font,
+ x,
+ 118.0,
+ body,
+ palette.secondary_text,
+ max_width,
+ )?;
+ self.draw_rect(layers, 0, x, 166.0, max_width, 1.0, palette.rule)?;
+ Ok(())
+ }
+
+ fn paint_setting_row(
+ &self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ x: f32,
+ y: f32,
+ width: f32,
+ label: &str,
+ description: &str,
+ value: &str,
+ ) -> anyhow::Result<()> {
+ let palette = self.palette();
+ let ui_font = Rc::clone(&self.ui_font);
+ self.draw_rect(layers, 0, x, y - 24.0, width, 1.0, palette.rule)?;
+ self.draw_text(
+ layers,
+ &ui_font,
+ x + 22.0,
+ y,
+ label,
+ palette.text,
+ width * 0.58,
+ )?;
+ self.draw_text(
+ layers,
+ &ui_font,
+ x + 22.0,
+ y + 30.0,
+ description,
+ palette.secondary_text,
+ width * 0.62,
+ )?;
+ let control_width = 220.0_f32.min(width * 0.34);
+ let control_x = x + width - control_width - 28.0;
+ let control_y = y + 2.0;
+ self.draw_rounded_frame(
+ layers,
+ 0,
+ control_x,
+ control_y,
+ control_width,
+ CONTROL_HEIGHT,
+ palette.control_bg,
+ palette.control_border,
+ CONTROL_RADIUS,
+ )?;
+ self.draw_text(
+ layers,
+ &ui_font,
+ control_x + 14.0,
+ self.control_text_y(control_y, CONTROL_HEIGHT),
+ value,
+ palette.text,
+ control_width - 26.0,
+ )?;
+ Ok(())
+ }
+
+ fn paint_status(&self, layers: &mut TripleLayerQuadAllocator<'_>) -> anyhow::Result<()> {
+ let palette = self.palette();
+ let ui_font = Rc::clone(&self.ui_font);
+ let y = self.dimensions.pixel_height as f32 - 42.0;
+ self.draw_rect(
+ layers,
+ 0,
+ 22.0,
+ y - 18.0,
+ SIDEBAR_WIDTH - 44.0,
+ 1.0,
+ palette.separator,
+ )?;
+ self.draw_text(
+ layers,
+ &ui_font,
+ 28.0,
+ y,
+ "Cmd+, Settings",
+ palette.muted_text,
+ SIDEBAR_WIDTH - 56.0,
+ )?;
+ self.draw_text(
+ layers,
+ &ui_font,
+ SIDEBAR_WIDTH + 46.0,
+ y,
+ &self.status,
+ palette.muted_text,
+ self.dimensions.pixel_width as f32 - SIDEBAR_WIDTH - 96.0,
+ )?;
+ Ok(())
+ }
+
+ fn draw_button(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ x: f32,
+ y: f32,
+ width: f32,
+ label: &str,
+ action: SettingsAction,
+ ) -> anyhow::Result<()> {
+ self.hit_targets.push(HitTarget {
+ rect: euclid::rect(x, y, width, CONTROL_HEIGHT),
+ action,
+ });
+
+ let palette = self.palette();
+ let is_hovered = self.hovered_action == Some(action);
+ let is_pressed = self.pressed_action == Some(action);
+ let background = if is_pressed {
+ palette.control_pressed_bg
+ } else if is_hovered {
+ palette.control_hover_bg
+ } else {
+ palette.control_bg
+ };
+ let border = if is_pressed {
+ palette.nav_selected_bg
+ } else if is_hovered {
+ palette.separator
+ } else {
+ palette.control_border
+ };
+ self.draw_rounded_frame(
+ layers,
+ 0,
+ x,
+ y,
+ width,
+ CONTROL_HEIGHT,
+ background,
+ border,
+ CONTROL_RADIUS,
+ )?;
+ self.draw_text(
+ layers,
+ &Rc::clone(&self.ui_font),
+ x + 14.0,
+ self.control_text_y(y, CONTROL_HEIGHT),
+ label,
+ palette.text,
+ width - 28.0,
+ )?;
+ Ok(())
+ }
+
+ fn control_text_y(&self, y: f32, height: f32) -> f32 {
+ let cell_height = self.metrics.cell_size.height as f32;
+ y + ((height - cell_height) / 2.0).max(0.0)
+ }
+
+ fn draw_rounded_frame(
+ &self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ layer_num: usize,
+ x: f32,
+ y: f32,
+ width: f32,
+ height: f32,
+ fill: LinearRgba,
+ border: LinearRgba,
+ radius: f32,
+ ) -> anyhow::Result<()> {
+ self.draw_rounded_rect(layers, layer_num, x, y, width, height, border, radius)?;
+ self.draw_rounded_rect(
+ layers,
+ layer_num,
+ x + 1.0,
+ y + 1.0,
+ width - 2.0,
+ height - 2.0,
+ fill,
+ (radius - 1.0).max(0.0),
+ )?;
+ Ok(())
+ }
+
+ fn draw_rounded_rect(
+ &self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ layer_num: usize,
+ x: f32,
+ y: f32,
+ width: f32,
+ height: f32,
+ color: LinearRgba,
+ radius: f32,
+ ) -> anyhow::Result<()> {
+ if width <= 0.0 || height <= 0.0 {
+ return Ok(());
+ }
+
+ let radius = radius.min(width / 2.0).min(height / 2.0).round().max(0.0);
+ if radius <= 0.0 {
+ return self.draw_rect(layers, layer_num, x, y, width, height, color);
+ }
+
+ let corner_size = euclid::size2(radius, radius);
+ self.draw_corner(
+ layers,
+ layer_num,
+ x,
+ y,
+ TOP_LEFT_ROUNDED_CORNER,
+ corner_size,
+ color,
+ )?;
+ self.draw_corner(
+ layers,
+ layer_num,
+ x + width - radius,
+ y,
+ TOP_RIGHT_ROUNDED_CORNER,
+ corner_size,
+ color,
+ )?;
+ self.draw_corner(
+ layers,
+ layer_num,
+ x,
+ y + height - radius,
+ BOTTOM_LEFT_ROUNDED_CORNER,
+ corner_size,
+ color,
+ )?;
+ self.draw_corner(
+ layers,
+ layer_num,
+ x + width - radius,
+ y + height - radius,
+ BOTTOM_RIGHT_ROUNDED_CORNER,
+ corner_size,
+ color,
+ )?;
+
+ self.draw_rect(
+ layers,
+ layer_num,
+ x + radius,
+ y,
+ width - radius * 2.0,
+ height,
+ color,
+ )?;
+ self.draw_rect(
+ layers,
+ layer_num,
+ x,
+ y + radius,
+ radius,
+ height - radius * 2.0,
+ color,
+ )?;
+ self.draw_rect(
+ layers,
+ layer_num,
+ x + width - radius,
+ y + radius,
+ radius,
+ height - radius * 2.0,
+ color,
+ )?;
+
+ Ok(())
+ }
+
+ fn draw_corner(
+ &self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ layer_num: usize,
+ x: f32,
+ y: f32,
+ polys: &'static [Poly],
+ size: euclid::Size2D<f32, window::PixelUnit>,
+ color: LinearRgba,
+ ) -> anyhow::Result<()> {
+ let render_state = self.render_state.as_ref().unwrap();
+ let sprite = render_state
+ .glyph_cache
+ .borrow_mut()
+ .cached_block(
+ BlockKey::PolyWithCustomMetrics {
+ polys,
+ underline_height: self.metrics.underline_height,
+ cell_size: euclid::size2(size.width as isize, size.height as isize),
+ },
+ &self.metrics,
+ )?
+ .texture_coords();
+
+ let mut quad = layers.allocate(layer_num)?;
+ let left_offset = self.dimensions.pixel_width as f32 / 2.0;
+ let top_offset = self.dimensions.pixel_height as f32 / 2.0;
+ quad.set_position(
+ x - left_offset,
+ y - top_offset,
+ x + size.width - left_offset,
+ y + size.height - top_offset,
+ );
+ quad.set_texture(sprite);
+ quad.set_fg_color(color);
+ quad.set_alt_color_and_mix_value(color, 0.0);
+ quad.set_hsv(None);
+ quad.set_has_color(false);
+ quad.set_grayscale();
+ Ok(())
+ }
+
+ fn draw_rect(
+ &self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ layer_num: usize,
+ x: f32,
+ y: f32,
+ width: f32,
+ height: f32,
+ color: LinearRgba,
+ ) -> anyhow::Result<()> {
+ if width <= 0.0 || height <= 0.0 {
+ return Ok(());
+ }
+
+ let render_state = self.render_state.as_ref().unwrap();
+ let mut quad = layers.allocate(layer_num)?;
+ let left_offset = self.dimensions.pixel_width as f32 / 2.0;
+ let top_offset = self.dimensions.pixel_height as f32 / 2.0;
+ quad.set_position(
+ x - left_offset,
+ y - top_offset,
+ x + width - left_offset,
+ y + height - top_offset,
+ );
+ quad.set_texture(render_state.util_sprites.filled_box.texture_coords());
+ quad.set_is_background();
+ quad.set_fg_color(color);
+ quad.set_hsv(None);
+ Ok(())
+ }
+
+ fn draw_text(
+ &self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ font: &Rc<LoadedFont>,
+ x: f32,
+ y: f32,
+ text: &str,
+ color: LinearRgba,
+ max_width: f32,
+ ) -> anyhow::Result<()> {
+ if text.is_empty() || max_width <= 0.0 {
+ return Ok(());
+ }
+
+ let infos = font.blocking_shape(text, None, Direction::LeftToRight, None, None)?;
+ let render_state = self.render_state.as_ref().unwrap();
+ let mut glyph_cache = render_state.glyph_cache.borrow_mut();
+ let style = font.style();
+ let mut pos_x = x;
+ let baseline = self.metrics.cell_size.height as f32 + self.metrics.descender.get() as f32;
+ let left_offset = self.dimensions.pixel_width as f32 / 2.0;
+ let top_offset = self.dimensions.pixel_height as f32 / 2.0;
+ let right_edge = x + max_width;
+
+ for info in infos {
+ let glyph = glyph_cache.cached_glyph(&info, style, false, font, &self.metrics, 1)?;
+ if let Some(texture) = glyph.texture.as_ref() {
+ let glyph_x = pos_x + (glyph.x_offset + glyph.bearing_x).get() as f32;
+ let glyph_y = y - (glyph.y_offset + glyph.bearing_y).get() as f32 + baseline;
+ let width = texture.coords.size.width as f32 * glyph.scale as f32;
+ let height = texture.coords.size.height as f32 * glyph.scale as f32;
+
+ if glyph_x + width > right_edge {
+ break;
+ }
+
+ let mut quad = layers.allocate(1)?;
+ quad.set_position(
+ glyph_x - left_offset,
+ glyph_y - top_offset,
+ glyph_x + width - left_offset,
+ glyph_y + height - top_offset,
+ );
+ quad.set_texture(texture.texture_coords());
+ quad.set_has_color(glyph.has_color);
+ quad.set_fg_color(color);
+ quad.set_hsv(None);
+ }
+ pos_x += glyph.x_advance.get() as f32;
+ if pos_x > right_edge {
+ break;
+ }
+ }
+
+ Ok(())
+ }
+
+ fn call_draw_glium(&mut self, frame: &mut glium::Frame) -> anyhow::Result<()> {
+ let render_state = self.render_state.as_ref().unwrap();
+ let tex = render_state.glyph_cache.borrow().atlas.texture();
+ let tex = tex.downcast_ref::<SrgbTexture2d>().unwrap();
+
+ frame.clear_color(0.0, 0.0, 0.0, 1.0);
+
+ let projection = euclid::Transform3D::<f32, f32, f32>::ortho(
+ -(self.dimensions.pixel_width as f32) / 2.0,
+ self.dimensions.pixel_width as f32 / 2.0,
+ self.dimensions.pixel_height as f32 / 2.0,
+ -(self.dimensions.pixel_height as f32) / 2.0,
+ -1.0,
+ 1.0,
+ )
+ .to_arrays_transposed();
+
+ let alpha_blending = glium::DrawParameters {
+ blend: glium::Blend {
+ color: BlendingFunction::Addition {
+ source: LinearBlendingFactor::SourceAlpha,
+ destination: LinearBlendingFactor::OneMinusSourceAlpha,
+ },
+ alpha: BlendingFunction::Addition {
+ source: LinearBlendingFactor::One,
+ destination: LinearBlendingFactor::OneMinusSourceAlpha,
+ },
+ constant_value: (0.0, 0.0, 0.0, 0.0),
+ },
+ ..Default::default()
+ };
+
+ let atlas_nearest_sampler = Sampler::new(&*tex)
+ .wrap_function(SamplerWrapFunction::Clamp)
+ .magnify_filter(MagnifySamplerFilter::Nearest)
+ .minify_filter(MinifySamplerFilter::Nearest);
+
+ let atlas_linear_sampler = Sampler::new(&*tex)
+ .wrap_function(SamplerWrapFunction::Clamp)
+ .magnify_filter(MagnifySamplerFilter::Linear)
+ .minify_filter(MinifySamplerFilter::Linear);
+
+ let foreground_text_hsb = (1.0_f32, 1.0_f32, 1.0_f32);
+ let milliseconds = 0_u32;
+ let ease = ColorEaseUniform {
+ in_function: [0.0, 0.0, 1.0, 1.0],
+ out_function: [0.0, 0.0, 1.0, 1.0],
+ in_duration_ms: 0,
+ out_duration_ms: 0,
+ };
+ let subpixel_aa = false;
+
+ for layer in render_state.layers.borrow().iter() {
+ for idx in 0..3 {
+ let vb = &layer.vb.borrow()[idx];
+ let (vertex_count, index_count) = vb.vertex_index_count();
+ if vertex_count > 0 {
+ let vertices = vb.current_vb_mut();
+ let mut uniforms = UniformBuilder::default();
+
+ uniforms.add("projection", &projection);
+ uniforms.add("atlas_nearest_sampler", &atlas_nearest_sampler);
+ uniforms.add("atlas_linear_sampler", &atlas_linear_sampler);
+ uniforms.add("foreground_text_hsb", &foreground_text_hsb);
+ uniforms.add("subpixel_aa", &subpixel_aa);
+ uniforms.add("milliseconds", &milliseconds);
+ uniforms.add_struct("cursor_blink", &ease);
+ uniforms.add_struct("blink", &ease);
+ uniforms.add_struct("rapid_blink", &ease);
+
+ frame.draw(
+ vertices.glium().slice(0..vertex_count).unwrap(),
+ vb.indices.glium().slice(0..index_count).unwrap(),
+ render_state.glyph_prog.as_ref().unwrap(),
+ &uniforms,
+ &alpha_blending,
+ )?;
+ }
+
+ vb.next_index();
+ }
+ }
+
+ Ok(())
+ }
+
+ fn initial_status() -> String {
+ match Self::wezterm_config_source() {
+ Some(path) => format!("Found WezTerm config at {}", path.display()),
+ None => "No existing WezTerm config was found yet".to_string(),
+ }
+ }
+
+ fn wezterm_config_source() -> Option<PathBuf> {
+ let mut candidates = vec![config::HOME_DIR.join(".wezterm.lua")];
+ for dir in config::CONFIG_DIRS.iter() {
+ candidates.push(dir.join("wezterm.lua"));
+ }
+ candidates.into_iter().find(|path| path.exists())
+ }
+
+ fn open_path(path: PathBuf) {
+ match url::Url::from_file_path(&path) {
+ Ok(url) => wezterm_open_url::open_url(url.as_str()),
+ Err(_) => log::error!("Unable to convert {} into a file URL", path.display()),
+ }
+ }
+}
+
+fn rgb(r: u8, g: u8, b: u8) -> LinearRgba {
+ rgba(r, g, b, 1.0)
+}
+
+fn rgba(r: u8, g: u8, b: u8, a: f32) -> LinearRgba {
+ LinearRgba::with_components(r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, a)
+}
diff --git a/wezterm-gui/src/shapecache.rs b/wezterm-gui/src/shapecache.rs
index e01ea4d7..da0834a3 100644
--- a/wezterm-gui/src/shapecache.rs
+++ b/wezterm-gui/src/shapecache.rs
@@ -7,6 +7,7 @@ use wezterm_font::units::*;
#[derive(PartialEq, Eq, Hash, Clone, Debug)]
pub struct ShapeCacheKey {
+ pub font_identity: u64,
pub style: TextStyle,
pub text: String,
}
@@ -60,6 +61,7 @@ impl ShapedInfo {
/// <https://github.com/sunshowers/borrow-complex-key-example/blob/master/src/lib.rs>
#[derive(Copy, Debug, Clone, PartialEq, Eq, Hash)]
pub struct BorrowedShapeCacheKey<'a> {
+ pub font_identity: u64,
pub style: &'a TextStyle,
pub text: &'a str,
}
@@ -67,6 +69,7 @@ pub struct BorrowedShapeCacheKey<'a> {
impl<'a> BorrowedShapeCacheKey<'a> {
pub fn to_owned(&self) -> ShapeCacheKey {
ShapeCacheKey {
+ font_identity: self.font_identity,
style: self.style.clone(),
text: self.text.to_owned(),
}
@@ -80,6 +83,7 @@ pub trait ShapeCacheKeyTrait: std::fmt::Debug {
impl ShapeCacheKeyTrait for ShapeCacheKey {
fn key<'k>(&'k self) -> BorrowedShapeCacheKey<'k> {
BorrowedShapeCacheKey {
+ font_identity: self.font_identity,
style: &self.style,
text: &self.text,
}
diff --git a/wezterm-gui/src/spawn.rs b/wezterm-gui/src/spawn.rs
index 28b9db9a..2d72d876 100644
--- a/wezterm-gui/src/spawn.rs
+++ b/wezterm-gui/src/spawn.rs
@@ -14,6 +14,7 @@ use wezterm_term::TerminalSize;
pub enum SpawnWhere {
NewWindow,
NewTab,
+ NewTabAt(usize),
SplitPane(SplitRequest),
}
@@ -123,7 +124,7 @@ pub async fn spawn_command_internal(
}
}
_ => {
- let (_tab, pane, window_id) = mux
+ let (tab, pane, window_id) = mux
.spawn_tab_or_window(
match spawn_where {
SpawnWhere::NewWindow => None,
@@ -145,6 +146,17 @@ pub async fn spawn_command_internal(
// the new window being created.
if Some(window_id) == src_window_id {
pane.set_config(term_config);
+
+ if let SpawnWhere::NewTabAt(insert_idx) = spawn_where {
+ if let Some(mut window) = mux.get_window_mut(window_id) {
+ if let Some(tab_idx) = window.idx_by_id(tab.tab_id()) {
+ let tab_inst = window.remove_by_idx(tab_idx);
+ let insert_idx = insert_idx.min(window.len());
+ window.insert(insert_idx, &tab_inst);
+ window.set_active_without_saving(insert_idx);
+ }
+ }
+ }
}
}
};
diff --git a/wezterm-gui/src/tabbar.rs b/wezterm-gui/src/tabbar.rs
index d8097520..dbf6e378 100644
--- a/wezterm-gui/src/tabbar.rs
+++ b/wezterm-gui/src/tabbar.rs
@@ -1,3 +1,4 @@
+use crate::termwindow::ui::terminal_title_for_display;
use crate::termwindow::{PaneInformation, TabInformation, UIItem, UIItemType};
use config::{ConfigHandle, TabBarColors};
use finl_unicode::grapheme_clusters::Graphemes;
@@ -12,6 +13,8 @@ use termwiz_funcs::{format_as_escapes, FormatColor, FormatItem};
use wezterm_term::{Line, Progress};
use window::{IntegratedTitleButton, IntegratedTitleButtonAlignment, IntegratedTitleButtonStyle};
+const TERMINAL_TAB_ICON: &str = "\u{f120} ";
+
#[derive(Clone, Debug, PartialEq)]
pub struct TabBarState {
line: Line,
@@ -148,13 +151,13 @@ fn compute_tab_title(
if let Some(pane) = &tab.active_pane {
let mut title = if tab.tab_title.is_empty() {
- pane.title.clone()
+ terminal_title_for_display(&pane.title).to_string()
} else {
tab.tab_title.clone()
};
let classic_spacing = if config.use_fancy_tab_bar { "" } else { " " };
- if config.show_tab_index_in_tab_bar {
+ if config.show_tab_index_in_tab_bar && !config.use_fancy_tab_bar {
let index = format!(
"{classic_spacing}{}: ",
tab.tab_index
@@ -189,6 +192,11 @@ fn compute_tab_title(
}
}
+ if !config.use_fancy_tab_bar {
+ len += unicode_column_width(TERMINAL_TAB_ICON, None);
+ items.push(FormatItem::Text(TERMINAL_TAB_ICON.to_string()));
+ }
+
// We have a preferred soft minimum on tab width to make it
// easier to click on tab titles, but we'll still go below
// this if there are too many tabs to fit the window at
@@ -218,6 +226,50 @@ fn is_tab_hover(mouse_x: Option<usize>, x: usize, tab_title_len: usize) -> bool
.unwrap_or(false);
}
+fn visible_tab_range_from_scroll(
+ tab_titles: &[TitleText],
+ scroll_offset: usize,
+ tab_width_max: usize,
+ available_cells: usize,
+) -> std::ops::Range<usize> {
+ if tab_titles.is_empty() {
+ return 0..0;
+ }
+
+ let widths: Vec<usize> = tab_titles
+ .iter()
+ .map(|title| title.len.min(tab_width_max).max(1))
+ .collect();
+ let total_width: usize = widths.iter().sum::<usize>() + tab_titles.len().saturating_sub(1);
+ if total_width <= available_cells {
+ return 0..tab_titles.len();
+ }
+
+ let mut start = scroll_offset.min(tab_titles.len().saturating_sub(1));
+ let mut end = start;
+ let mut used = 0usize;
+
+ while end < widths.len() {
+ let width = widths[end] + usize::from(used > 0);
+ if used > 0 && used.saturating_add(width) > available_cells {
+ break;
+ }
+ used += width;
+ end += 1;
+ }
+
+ while start > 0 && end == widths.len() {
+ let width = widths[start - 1] + usize::from(used > 0);
+ if used.saturating_add(width) > available_cells {
+ break;
+ }
+ used += width;
+ start -= 1;
+ }
+
+ start..end.max(start + 1).min(tab_titles.len())
+}
+
impl TabBarState {
pub fn default() -> Self {
Self {
@@ -337,6 +389,7 @@ impl TabBarState {
pane_info: &[PaneInformation],
colors: Option<&TabBarColors>,
config: &ConfigHandle,
+ tab_scroll_offset: f32,
left_status: &str,
right_status: &str,
) -> Self {
@@ -397,19 +450,28 @@ impl TabBarState {
} else {
vec![]
};
- let titles_len: usize = tab_titles.iter().map(|s| s.len).sum();
let number_of_tabs = tab_titles.len();
+ let show_new_tab_button = false;
- let available_cells =
- title_width.saturating_sub(number_of_tabs.saturating_sub(1) + new_tab.len());
- let tab_width_max = if config.use_fancy_tab_bar || available_cells >= titles_len {
- // We can render each title with its full width
- usize::max_value()
+ let available_cells = title_width.saturating_sub(
+ number_of_tabs.saturating_sub(1)
+ + if show_new_tab_button {
+ new_tab.len()
+ } else {
+ 0
+ },
+ );
+ let tab_width_max = config.tab_max_width;
+ let visible_tab_range = if config.use_fancy_tab_bar {
+ 0..tab_titles.len()
} else {
- // We need to clamp the length to balance them out
- available_cells / number_of_tabs
- }
- .min(config.tab_max_width);
+ visible_tab_range_from_scroll(
+ &tab_titles,
+ tab_scroll_offset.max(0.0).floor() as usize,
+ tab_width_max,
+ available_cells,
+ )
+ };
let mut line = Line::with_width(0, SEQ_ZERO);
@@ -453,7 +515,11 @@ impl TabBarState {
}
for (tab_idx, tab_title) in tab_titles.iter().enumerate() {
- let tab_title_len = tab_title.len.min(tab_width_max);
+ if !visible_tab_range.contains(&tab_idx) {
+ continue;
+ }
+
+ let tab_title_len = tab_title.len.min(tab_width_max).min(available_cells.max(1));
let active = tab_idx == active_tab_no;
let hover = !active && is_tab_hover(mouse_x, x, tab_title_len);
@@ -507,7 +573,7 @@ impl TabBarState {
}
// New tab button
- if config.show_new_tab_button_in_tab_bar {
+ if config.show_new_tab_button_in_tab_bar && show_new_tab_button {
let hover = is_tab_hover(mouse_x, x, new_tab_hover.len());
let new_tab_button = if hover { &new_tab_hover } else { &new_tab };
@@ -606,12 +672,18 @@ impl TabBarState {
Self { line, items }
}
- pub fn compute_ui_items(&self, y: usize, cell_height: usize, cell_width: usize) -> Vec<UIItem> {
+ pub fn compute_ui_items(
+ &self,
+ y: usize,
+ cell_height: usize,
+ cell_width: usize,
+ x_offset: usize,
+ ) -> Vec<UIItem> {
let mut items = vec![];
for entry in self.items.iter() {
items.push(UIItem {
- x: entry.x * cell_width,
+ x: x_offset + entry.x * cell_width,
width: entry.width * cell_width,
y,
height: cell_height,
diff --git a/wezterm-gui/src/termwindow/box_model.rs b/wezterm-gui/src/termwindow/box_model.rs
index feba448f..27a5fde1 100644
--- a/wezterm-gui/src/termwindow/box_model.rs
+++ b/wezterm-gui/src/termwindow/box_model.rs
@@ -3,6 +3,7 @@ use crate::color::LinearRgba;
use crate::customglyph::{BlockKey, Poly};
use crate::glyphcache::CachedGlyph;
use crate::quad::{QuadImpl, QuadTrait, TripleLayerQuadAllocator, TripleLayerQuadAllocatorTrait};
+use crate::termwindow::ui::icons::SvgIcon;
use crate::termwindow::{
ColorEase, MouseCapture, RenderState, TermWindowNotif, UIItem, UIItemType,
};
@@ -394,6 +395,7 @@ pub enum ElementContent {
Text(String),
Children(Vec<Element>),
Poly { line_width: isize, poly: SizedPoly },
+ Icon { icon: SvgIcon, size: Dimension },
}
pub struct LayoutContext<'a> {
@@ -441,6 +443,7 @@ impl ComputedElement {
}
ComputedElementContent::Text(_) => {}
ComputedElementContent::Poly { .. } => {}
+ ComputedElementContent::Icon { .. } => {}
}
}
@@ -469,6 +472,7 @@ impl ComputedElement {
}
}
ComputedElementContent::Poly { .. } => {}
+ ComputedElementContent::Icon { .. } => {}
}
}
}
@@ -481,6 +485,10 @@ pub enum ComputedElementContent {
line_width: isize,
poly: PixelSizedPoly,
},
+ Icon {
+ icon: SvgIcon,
+ size: f32,
+ },
}
#[derive(Debug, Clone)]
@@ -820,6 +828,26 @@ impl super::TermWindow {
},
})
}
+ ElementContent::Icon { icon, size } => {
+ let size = size.evaluate_as_pixels(context.height).max(1.0);
+ let content_rect = euclid::rect(0., 0., size.max(min_width), size.max(min_height));
+ let rects = element.compute_rects(context, content_rect);
+
+ Ok(ComputedElement {
+ item_type: element.item_type.clone(),
+ zindex: element.zindex + context.zindex,
+ baseline,
+ border,
+ border_corners,
+ colors: element.colors.clone(),
+ hover_colors: element.hover_colors.clone(),
+ bounds: rects.bounds,
+ border_rect: rects.border_rect,
+ padding: rects.padding,
+ content_rect: rects.content_rect,
+ content: ComputedElementContent::Icon { icon: *icon, size },
+ })
+ }
}
}
@@ -940,6 +968,26 @@ impl super::TermWindow {
self.resolve_text(colors, inherited_colors).apply(&mut quad);
}
}
+ ComputedElementContent::Icon { icon, size } => {
+ let size = (*size).round().max(1.0) as usize;
+ let sprite = gl_state
+ .glyph_cache
+ .borrow_mut()
+ .cached_svg_icon(*icon, size)?
+ .texture_coords();
+ let mut quad = layers.allocate(2)?;
+ let icon_size = size as f32;
+ quad.set_position(
+ element.content_rect.min_x() + left,
+ element.content_rect.min_y() + top,
+ element.content_rect.min_x() + left + icon_size,
+ element.content_rect.min_y() + top + icon_size,
+ );
+ self.resolve_text(colors, inherited_colors).apply(&mut quad);
+ quad.set_texture(sprite);
+ quad.set_hsv(None);
+ quad.set_grayscale();
+ }
}
Ok(())
diff --git a/wezterm-gui/src/termwindow/keyevent.rs b/wezterm-gui/src/termwindow/keyevent.rs
index 93fd60b9..d51c9d33 100644
--- a/wezterm-gui/src/termwindow/keyevent.rs
+++ b/wezterm-gui/src/termwindow/keyevent.rs
@@ -1,6 +1,7 @@
use crate::termwindow::InputMap;
use ::window::{
- DeadKeyStatus, KeyCode, KeyEvent, KeyboardLedStatus, Modifiers, RawKeyEvent, WindowOps,
+ Clipboard, DeadKeyStatus, KeyCode, KeyEvent, KeyboardLedStatus, Modifiers, RawKeyEvent,
+ WindowOps,
};
use anyhow::Context;
use config::keyassignment::{KeyAssignment, KeyTableEntry};
@@ -188,6 +189,170 @@ enum OnlyKeyBindings {
}
impl super::TermWindow {
+ fn paste_text_into_inline_tab_rename(&mut self, text: &str) {
+ if let Some(rename) = self.inline_tab_rename.as_mut() {
+ rename.insert(text);
+ self.update_title_impl();
+ if let Some(window) = self.window.as_ref() {
+ window.invalidate();
+ }
+ }
+ }
+
+ fn handle_inline_tab_rename_key(
+ &mut self,
+ window_key: &KeyEvent,
+ context: &dyn WindowOps,
+ ) -> bool {
+ if self.inline_tab_rename.is_none() {
+ return false;
+ }
+
+ if !window_key.key_is_down {
+ return true;
+ }
+
+ let mut shortcut_mods = window_key.modifiers;
+ shortcut_mods.remove(Modifiers::SHIFT | Modifiers::LEFT_SHIFT | Modifiers::RIGHT_SHIFT);
+ let super_only = shortcut_mods == Modifiers::SUPER;
+ if super_only {
+ match &window_key.key {
+ KeyCode::Char('a') | KeyCode::Char('A') => {
+ if let Some(rename) = self.inline_tab_rename.as_mut() {
+ rename.select_all();
+ self.update_title_impl();
+ context.invalidate();
+ }
+ return true;
+ }
+ KeyCode::Char('c') | KeyCode::Char('C') => {
+ if let Some(rename) = self.inline_tab_rename.as_ref() {
+ let text = rename
+ .selected_text()
+ .unwrap_or_else(|| rename.text.clone());
+ context.set_clipboard(Clipboard::Clipboard, text);
+ }
+ return true;
+ }
+ KeyCode::Char('x') | KeyCode::Char('X') => {
+ if let Some(rename) = self.inline_tab_rename.as_mut() {
+ let text = rename
+ .selected_text()
+ .unwrap_or_else(|| rename.text.clone());
+ context.set_clipboard(Clipboard::Clipboard, text);
+ if rename.has_selection() {
+ rename.delete_selection();
+ } else {
+ rename.text.clear();
+ rename.cursor = 0;
+ }
+ self.update_title_impl();
+ context.invalidate();
+ }
+ return true;
+ }
+ KeyCode::Char('v') | KeyCode::Char('V') => {
+ if let Some(window) = self.window.as_ref().cloned() {
+ let future = window.get_clipboard(Clipboard::Clipboard);
+ promise::spawn::spawn(async move {
+ if let Ok(text) = future.await {
+ window.notify(crate::termwindow::TermWindowNotif::Apply(Box::new(
+ move |term_window| {
+ term_window.paste_text_into_inline_tab_rename(&text);
+ },
+ )));
+ }
+ })
+ .detach();
+ }
+ return true;
+ }
+ _ => {}
+ }
+ }
+
+ let text_mod_blockers = Modifiers::ALT
+ | Modifiers::CTRL
+ | Modifiers::SUPER
+ | Modifiers::LEADER
+ | Modifiers::LEFT_ALT
+ | Modifiers::RIGHT_ALT
+ | Modifiers::LEFT_CTRL
+ | Modifiers::RIGHT_CTRL;
+
+ let mut dirty = false;
+ match &window_key.key {
+ KeyCode::Char('\r') => {
+ self.finish_inline_tab_rename(true);
+ context.invalidate();
+ return true;
+ }
+ KeyCode::Char('\u{1b}') => {
+ self.finish_inline_tab_rename(false);
+ context.invalidate();
+ return true;
+ }
+ KeyCode::Char('\u{8}') => {
+ if let Some(rename) = self.inline_tab_rename.as_mut() {
+ rename.backspace();
+ dirty = true;
+ }
+ }
+ KeyCode::Char('\u{7f}') => {
+ if let Some(rename) = self.inline_tab_rename.as_mut() {
+ rename.delete();
+ dirty = true;
+ }
+ }
+ KeyCode::LeftArrow => {
+ if let Some(rename) = self.inline_tab_rename.as_mut() {
+ rename.move_left();
+ dirty = true;
+ }
+ }
+ KeyCode::RightArrow => {
+ if let Some(rename) = self.inline_tab_rename.as_mut() {
+ rename.move_right();
+ dirty = true;
+ }
+ }
+ KeyCode::Home => {
+ if let Some(rename) = self.inline_tab_rename.as_mut() {
+ rename.cursor = 0;
+ dirty = true;
+ }
+ }
+ KeyCode::End => {
+ if let Some(rename) = self.inline_tab_rename.as_mut() {
+ rename.cursor = rename.text.chars().count();
+ dirty = true;
+ }
+ }
+ KeyCode::Char(c)
+ if !window_key.modifiers.intersects(text_mod_blockers) && !c.is_control() =>
+ {
+ if let Some(rename) = self.inline_tab_rename.as_mut() {
+ rename.insert(&c.to_string());
+ dirty = true;
+ }
+ }
+ KeyCode::Composed(text) if !window_key.modifiers.intersects(text_mod_blockers) => {
+ if let Some(rename) = self.inline_tab_rename.as_mut() {
+ rename.insert(text);
+ dirty = true;
+ }
+ }
+ _ => {}
+ }
+
+ if dirty {
+ self.update_title_impl();
+ context.invalidate();
+ }
+
+ true
+ }
+
fn encode_win32_input(&self, pane: &Arc<dyn Pane>, key: &KeyEvent) -> Option<String> {
if !self.config.allow_win32_input_mode
|| pane.get_keyboard_encoding() != KeyboardEncoding::Win32
@@ -597,6 +762,10 @@ impl super::TermWindow {
}
pub fn key_event_impl(&mut self, window_key: KeyEvent, context: &dyn WindowOps) {
+ if self.handle_inline_tab_rename_key(&window_key, context) {
+ return;
+ }
+
let pane = match self.get_active_pane_or_overlay() {
Some(pane) => pane,
None => return,
@@ -768,7 +937,7 @@ impl super::TermWindow {
WK::Char('\u{1b}') => KC::Escape,
WK::RawCode(_) => return Key::None,
WK::Physical(phys) => {
- return self.win_key_code_to_termwiz_key_code(&phys.to_key_code())
+ return self.win_key_code_to_termwiz_key_code(&phys.to_key_code());
}
WK::Char(c) => KC::Char(*c),
diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs
index 350cb8fb..bb557923 100644
--- a/wezterm-gui/src/termwindow/mod.rs
+++ b/wezterm-gui/src/termwindow/mod.rs
@@ -27,6 +27,7 @@ use crate::termwindow::render::{
};
use crate::termwindow::webgpu::WebGpuState;
use ::wezterm_term::input::{ClickPosition, MouseButton as TMB};
+use ::window::color::LinearRgba;
use ::window::*;
use anyhow::{anyhow, ensure, Context};
use config::keyassignment::{
@@ -36,7 +37,8 @@ use config::keyassignment::{
use config::window::WindowLevel;
use config::{
configuration, AudibleBell, ConfigHandle, Dimension, DimensionContext, FrontEndSelection,
- GeometryOrigin, GuiPosition, TermConfig, WindowCloseConfirmation,
+ GeometryOrigin, GuiPosition, RgbaColor, TabBarColor, TabBarColors, TermConfig,
+ WindowCloseConfirmation,
};
use lfucache::*;
use mlua::{FromLua, LuaSerdeExt, UserData, UserDataFields};
@@ -56,6 +58,7 @@ use smol::Timer;
use std::cell::{RefCell, RefMut};
use std::collections::{HashMap, LinkedList};
use std::ops::Add;
+use std::path::PathBuf;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
@@ -64,7 +67,7 @@ use termwiz::hyperlink::Hyperlink;
use termwiz::surface::SequenceNo;
use wezterm_dynamic::Value;
use wezterm_font::FontConfiguration;
-use wezterm_term::color::ColorPalette;
+use wezterm_term::color::{ColorAttribute, ColorPalette};
use wezterm_term::input::LastMouseClick;
use wezterm_term::{Alert, Progress, StableRowIndex, TerminalConfiguration, TerminalSize};
@@ -82,7 +85,49 @@ pub mod render;
pub mod resize;
mod selection;
pub mod spawn;
+pub mod ui;
pub mod webgpu;
+
+pub(crate) fn theme_aligned_tab_bar_colors_from_palette(palette: &ColorPalette) -> TabBarColors {
+ fn rgba(color: LinearRgba) -> RgbaColor {
+ color.to_srgb().into()
+ }
+
+ let background = palette.resolve_bg(ColorAttribute::Default).to_linear();
+ let foreground = palette.foreground.to_linear();
+ let muted = foreground.mul_alpha(0.68);
+
+ TabBarColors {
+ background: Some(rgba(background)),
+ active_tab: Some(TabBarColor {
+ bg_color: rgba(background),
+ fg_color: palette.foreground.into(),
+ ..TabBarColor::default()
+ }),
+ inactive_tab: Some(TabBarColor {
+ bg_color: rgba(background),
+ fg_color: rgba(muted),
+ ..TabBarColor::default()
+ }),
+ inactive_tab_hover: Some(TabBarColor {
+ bg_color: rgba(background),
+ fg_color: palette.foreground.into(),
+ ..TabBarColor::default()
+ }),
+ new_tab: Some(TabBarColor {
+ bg_color: rgba(background),
+ fg_color: rgba(muted),
+ ..TabBarColor::default()
+ }),
+ new_tab_hover: Some(TabBarColor {
+ bg_color: rgba(background),
+ fg_color: palette.foreground.into(),
+ ..TabBarColor::default()
+ }),
+ inactive_tab_edge: Some(rgba(background)),
+ inactive_tab_edge_hover: Some(rgba(background)),
+ }
+}
use crate::spawn::SpawnWhere;
use prevcursor::PrevCursorPos;
@@ -93,7 +138,7 @@ lazy_static::lazy_static! {
static ref POSITION: Mutex<Option<GuiPosition>> = Mutex::new(None);
}
-pub const ICON_DATA: &'static [u8] = include_bytes!("../../../assets/icon/terminal.png");
+pub const ICON_DATA: &'static [u8] = include_bytes!("../../../assets/icon/ThinkTerm.png");
pub fn set_window_position(pos: GuiPosition) {
POSITION.lock().unwrap().replace(pos);
@@ -155,12 +200,185 @@ pub enum TermWindowNotif {
pub enum UIItemType {
TabBar(TabBarItem),
CloseTab(usize),
+ PaneNav {
+ pane_id: PaneId,
+ pane_index: usize,
+ action: PaneNavAction,
+ },
+ WorkspaceSidebar(String),
+ WorkspaceSidebarBackground,
+ WorkspaceSidebarResize,
AboveScrollThumb,
ScrollThumb,
BelowScrollThumb,
Split(PositionedSplit),
}
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum PaneNavAction {
+ Background,
+ Activate(PaneId),
+ Close(PaneId),
+ NewTab,
+ SplitRight,
+ SplitDown,
+}
+
+#[derive(Clone, Debug)]
+enum InlineTabRenameTarget {
+ WindowTab(TabId),
+ PaneTab(PaneId),
+}
+
+#[derive(Clone, Debug)]
+struct InlineTabRename {
+ target: InlineTabRenameTarget,
+ text: String,
+ cursor: usize,
+ selection_anchor: Option<usize>,
+}
+
+impl InlineTabRename {
+ fn new(target: InlineTabRenameTarget, text: String) -> Self {
+ let cursor = text.chars().count();
+ Self {
+ target,
+ text,
+ cursor,
+ selection_anchor: Some(0),
+ }
+ }
+
+ fn display_text(&self) -> String {
+ if self.has_selection() {
+ return if self.text.is_empty() {
+ "|".to_string()
+ } else {
+ self.text.clone()
+ };
+ }
+
+ let mut text = String::new();
+ let mut inserted_cursor = false;
+ for (idx, ch) in self.text.chars().enumerate() {
+ if idx == self.cursor {
+ text.push('|');
+ inserted_cursor = true;
+ }
+ text.push(ch);
+ }
+ if !inserted_cursor {
+ text.push('|');
+ }
+ text
+ }
+
+ fn len(&self) -> usize {
+ self.text.chars().count()
+ }
+
+ fn byte_idx(&self, char_idx: usize) -> usize {
+ self.text
+ .char_indices()
+ .nth(char_idx)
+ .map(|(idx, _)| idx)
+ .unwrap_or_else(|| self.text.len())
+ }
+
+ fn selection_range(&self) -> Option<(usize, usize)> {
+ let anchor = self.selection_anchor?;
+ if anchor == self.cursor {
+ None
+ } else if anchor < self.cursor {
+ Some((anchor, self.cursor))
+ } else {
+ Some((self.cursor, anchor))
+ }
+ }
+
+ fn has_selection(&self) -> bool {
+ self.selection_range().is_some()
+ }
+
+ fn selected_text(&self) -> Option<String> {
+ let (start, end) = self.selection_range()?;
+ Some(
+ self.text
+ .chars()
+ .skip(start)
+ .take(end.saturating_sub(start))
+ .collect(),
+ )
+ }
+
+ fn select_all(&mut self) {
+ self.selection_anchor = Some(0);
+ self.cursor = self.len();
+ }
+
+ fn clear_selection(&mut self) {
+ self.selection_anchor = None;
+ }
+
+ fn delete_selection(&mut self) -> bool {
+ let Some((start, end)) = self.selection_range() else {
+ return false;
+ };
+ let start_byte = self.byte_idx(start);
+ let end_byte = self.byte_idx(end);
+ self.text.replace_range(start_byte..end_byte, "");
+ self.cursor = start;
+ self.clear_selection();
+ true
+ }
+
+ fn insert(&mut self, text: &str) {
+ self.delete_selection();
+ for ch in text.chars() {
+ if matches!(ch, '\r' | '\n') {
+ continue;
+ }
+ let byte_idx = self.byte_idx(self.cursor);
+ self.text.insert(byte_idx, ch);
+ self.cursor += 1;
+ }
+ }
+
+ fn backspace(&mut self) {
+ if self.delete_selection() {
+ return;
+ }
+ if self.cursor == 0 {
+ return;
+ }
+ let remove_idx = self.cursor - 1;
+ let byte_idx = self.byte_idx(remove_idx);
+ self.text.remove(byte_idx);
+ self.cursor = remove_idx;
+ }
+
+ fn delete(&mut self) {
+ if self.delete_selection() {
+ return;
+ }
+ let byte_idx = self.byte_idx(self.cursor);
+ if byte_idx == self.text.len() {
+ return;
+ }
+ self.text.remove(byte_idx);
+ }
+
+ fn move_left(&mut self) {
+ self.cursor = self.cursor.saturating_sub(1);
+ self.clear_selection();
+ }
+
+ fn move_right(&mut self) {
+ self.cursor = self.cursor.saturating_add(1).min(self.len());
+ self.clear_selection();
+ }
+}
+
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UIItem {
pub x: usize,
@@ -204,6 +422,20 @@ pub struct PaneState {
bell_start: Option<Instant>,
pub mouse_terminal_coords: Option<(ClickPosition, StableRowIndex)>,
+ pub font_scale: Option<f64>,
+}
+
+#[derive(Clone)]
+pub struct PaneFontEntry {
+ pub fonts: Rc<FontConfiguration>,
+ pub render_metrics: RenderMetrics,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct PaneFontKey {
+ font_scale_bits: u64,
+ dpi: usize,
+ config_generation: usize,
}
/// Data used when synchronously formatting pane and window titles
@@ -391,6 +623,12 @@ pub struct TermWindow {
show_scroll_bar: bool,
tab_bar: TabBarState,
fancy_tab_bar: Option<box_model::ComputedElement>,
+ tab_bar_scroll_offset: f32,
+ tab_bar_scroll_target: f32,
+ pane_nav_tab_scroll_offsets: HashMap<PaneId, f32>,
+ pane_nav_tab_scroll_targets: HashMap<PaneId, f32>,
+ inline_tab_rename: Option<InlineTabRename>,
+ pane_tab_title_overrides: HashMap<PaneId, String>,
pub right_status: String,
pub left_status: String,
last_ui_item: Option<UIItem>,
@@ -405,6 +643,7 @@ pub struct TermWindow {
tab_state: RefCell<HashMap<TabId, TabState>>,
pane_state: RefCell<HashMap<PaneId, PaneState>>,
+ pane_font_cache: RefCell<HashMap<PaneFontKey, PaneFontEntry>>,
semantic_zones: HashMap<PaneId, SemanticZoneCache>,
window_background: Vec<LoadedBackgroundLayer>,
@@ -440,6 +679,8 @@ pub struct TermWindow {
ui_items: Vec<UIItem>,
dragging: Option<(UIItem, MouseEvent)>,
+ workspace_sidebar_width: usize,
+ workspace_sidebar_collapsed: bool,
modal: RefCell<Option<Rc<dyn Modal>>>,
@@ -641,6 +882,7 @@ impl TermWindow {
pixel_cell: render_metrics.cell_size.width as f32,
};
let padding_left = config.window_padding.left.evaluate_as_pixels(h_context) as usize;
+ let workspace_sidebar_width = ui::workspace_sidebar_width_for_metrics(&render_metrics);
let padding_right = resize::effective_right_padding(&config, h_context) as usize;
let v_context = DimensionContext {
dpi: dpi as f32,
@@ -651,7 +893,10 @@ impl TermWindow {
let padding_bottom = config.window_padding.bottom.evaluate_as_pixels(v_context) as usize;
let mut dimensions = Dimensions {
- pixel_width: (terminal_size.pixel_width + padding_left + padding_right) as usize,
+ pixel_width: (terminal_size.pixel_width
+ + workspace_sidebar_width
+ + padding_left
+ + padding_right) as usize,
pixel_height: ((terminal_size.rows * render_metrics.cell_size.height as usize)
+ padding_top
+ padding_bottom) as usize
@@ -712,6 +957,12 @@ impl TermWindow {
show_scroll_bar: config.enable_scroll_bar,
tab_bar: TabBarState::default(),
fancy_tab_bar: None,
+ tab_bar_scroll_offset: 0.0,
+ tab_bar_scroll_target: 0.0,
+ pane_nav_tab_scroll_offsets: HashMap::new(),
+ pane_nav_tab_scroll_targets: HashMap::new(),
+ inline_tab_rename: None,
+ pane_tab_title_overrides: HashMap::new(),
right_status: String::new(),
left_status: String::new(),
last_mouse_coords: (0, -1),
@@ -722,6 +973,7 @@ impl TermWindow {
last_scroll_info: RenderableDimensions::default(),
tab_state: RefCell::new(HashMap::new()),
pane_state: RefCell::new(HashMap::new()),
+ pane_font_cache: RefCell::new(HashMap::new()),
current_mouse_buttons: vec![],
current_mouse_capture: None,
last_mouse_click: None,
@@ -783,6 +1035,8 @@ impl TermWindow {
semantic_zones: HashMap::new(),
ui_items: vec![],
dragging: None,
+ workspace_sidebar_width,
+ workspace_sidebar_collapsed: false,
last_ui_item: None,
is_click_to_focus_window: false,
key_table_state: KeyTableState::default(),
@@ -830,6 +1084,7 @@ impl TermWindow {
},
)
.await?;
+ window.set_titlebar_sidebar_button_visible(true);
tw.borrow_mut().window.replace(window.clone());
Self::apply_icon(&window)?;
@@ -946,6 +1201,13 @@ impl TermWindow {
self.mouse_event_impl(event, window);
Ok(true)
}
+ WindowEvent::ToggleWorkspaceSidebar => {
+ self.toggle_workspace_sidebar();
+ let dimensions = self.dimensions;
+ self.apply_dimensions(&dimensions, None, window);
+ window.invalidate();
+ Ok(true)
+ }
WindowEvent::MouseLeave => {
self.mouse_leave_impl(window);
Ok(true)
@@ -1394,6 +1656,17 @@ impl TermWindow {
}
fn apply_icon(window: &Window) -> anyhow::Result<()> {
+ #[cfg(target_os = "macos")]
+ if let Some(path) = Self::macos_application_icon_path() {
+ match ::window::set_application_icon_from_file(&path) {
+ Ok(()) => return Ok(()),
+ Err(err) => log::warn!(
+ "failed to load macOS application icon from {}: {err:#}",
+ path.display()
+ ),
+ }
+ }
+
let image = image::load_from_memory(ICON_DATA)?.into_rgba8();
let (width, height) = image.dimensions();
window.set_icon(Image::with_rgba32(
@@ -1405,6 +1678,23 @@ impl TermWindow {
Ok(())
}
+ #[cfg(target_os = "macos")]
+ fn macos_application_icon_path() -> Option<PathBuf> {
+ let exe = std::env::current_exe().ok()?;
+ let exe_dir = exe.parent()?;
+ let mut candidates = vec![exe_dir.join("ThinkTerm.icns")];
+
+ if let Some(contents_dir) = exe_dir.parent() {
+ candidates.push(contents_dir.join("Resources").join("ThinkTerm.icns"));
+ }
+
+ if let Some(repo_dir) = PathBuf::from(env!("CARGO_MANIFEST_DIR")).parent() {
+ candidates.push(repo_dir.join("assets").join("icon").join("ThinkTerm.icns"));
+ }
+
+ candidates.into_iter().find(|path| path.exists())
+ }
+
fn schedule_status_update(&self) {
if let Some(window) = self.window.as_ref() {
window.notify(TermWindowNotif::EmitStatusUpdate);
@@ -1788,6 +2078,7 @@ impl TermWindow {
self.line_to_ele_shape_cache
.borrow_mut()
.update_config(&config);
+ self.pane_font_cache.borrow_mut().clear();
self.fancy_tab_bar.take();
self.invalidate_fancy_tab_bar();
self.invalidate_modal();
@@ -1958,6 +2249,11 @@ impl TermWindow {
self.update_title_impl();
}
+ fn theme_aligned_tab_bar_colors(&mut self) -> TabBarColors {
+ let palette = self.palette().clone();
+ theme_aligned_tab_bar_colors_from_palette(&palette)
+ }
+
fn update_title_impl(&mut self) {
let mux = Mux::get();
let window = match mux.get_window(self.mux_window_id) {
@@ -1979,26 +2275,47 @@ impl TermWindow {
};
let tab_bar_height = self.tab_bar_pixel_height().unwrap_or(0.);
+ let tab_bar_x = self.tab_bar_left_edge();
+ let tab_bar_width = self.dimensions.pixel_width.saturating_sub(tab_bar_x).max(1);
let hovering_in_tab_bar = match &self.current_mouse_event {
Some(event) => {
let mouse_y = event.coords.y as f32;
- mouse_y >= tab_bar_y as f32 && mouse_y < tab_bar_y as f32 + tab_bar_height
+ let mouse_x = event.coords.x.max(0) as usize;
+ mouse_x >= tab_bar_x
+ && mouse_y >= tab_bar_y as f32
+ && mouse_y < tab_bar_y as f32 + tab_bar_height
}
None => false,
};
+ let has_explicit_tab_colors = self.config.resolved_palette.tab_bar.is_some();
+ let themed_tab_bar_colors = if has_explicit_tab_colors {
+ None
+ } else {
+ Some(self.theme_aligned_tab_bar_colors())
+ };
+ let tab_bar_colors = if has_explicit_tab_colors {
+ self.config.resolved_palette.tab_bar.as_ref()
+ } else {
+ themed_tab_bar_colors.as_ref()
+ };
+
let new_tab_bar = TabBarState::new(
- self.dimensions.pixel_width / self.render_metrics.cell_size.width as usize,
+ (tab_bar_width / self.render_metrics.cell_size.width as usize).max(1),
if hovering_in_tab_bar {
- Some(self.last_mouse_coords.0)
+ self.current_mouse_event.as_ref().map(|event| {
+ event.coords.x.saturating_sub(tab_bar_x as isize).max(0) as usize
+ / self.render_metrics.cell_size.width as usize
+ })
} else {
None
},
&tabs,
&panes,
- self.config.resolved_palette.tab_bar.as_ref(),
+ tab_bar_colors,
&self.config,
+ self.tab_bar_scroll_offset,
&self.left_status,
&self.right_status,
);
@@ -2324,6 +2641,113 @@ impl TermWindow {
promise::spawn::spawn(future).detach();
}
+ fn prompt_rename_current_tab(&mut self) {
+ let mux = Mux::get();
+ let tab = match mux.get_active_tab_for_window(self.mux_window_id) {
+ Some(tab) => tab,
+ None => return,
+ };
+
+ let tab_id = tab.tab_id();
+ let mut initial_title = tab.get_title();
+ if initial_title.is_empty() {
+ initial_title = tab
+ .get_active_pane()
+ .map(|pane| pane.get_title())
+ .unwrap_or_default();
+ }
+
+ self.inline_tab_rename = Some(InlineTabRename::new(
+ InlineTabRenameTarget::WindowTab(tab_id),
+ initial_title,
+ ));
+ self.update_title_impl();
+ }
+
+ fn prompt_rename_pane_tab(&mut self, pane_id: PaneId) {
+ let initial_title = self
+ .pane_tab_title_overrides
+ .get(&pane_id)
+ .cloned()
+ .or_else(|| {
+ Mux::get()
+ .get_pane(pane_id)
+ .map(|pane| ui::terminal_title_for_display(&pane.get_title()).to_string())
+ })
+ .unwrap_or_default();
+
+ self.inline_tab_rename = Some(InlineTabRename::new(
+ InlineTabRenameTarget::PaneTab(pane_id),
+ initial_title,
+ ));
+ self.update_title_impl();
+ }
+
+ fn finish_inline_tab_rename(&mut self, commit: bool) {
+ let rename = match self.inline_tab_rename.take() {
+ Some(rename) => rename,
+ None => return,
+ };
+
+ if commit {
+ let title = rename.text.trim().to_string();
+ match rename.target {
+ InlineTabRenameTarget::WindowTab(tab_id) => {
+ if let Some(tab) = Mux::get().get_tab(tab_id) {
+ tab.set_title(&title);
+ }
+ }
+ InlineTabRenameTarget::PaneTab(pane_id) => {
+ if title.is_empty() {
+ self.pane_tab_title_overrides.remove(&pane_id);
+ } else {
+ self.pane_tab_title_overrides.insert(pane_id, title);
+ }
+ }
+ }
+ }
+
+ self.update_title_impl();
+ }
+
+ fn inline_window_tab_rename_title(&self, tab_id: TabId) -> Option<String> {
+ self.inline_tab_rename
+ .as_ref()
+ .filter(|rename| matches!(rename.target, InlineTabRenameTarget::WindowTab(id) if id == tab_id))
+ .map(|rename| rename.display_text())
+ }
+
+ fn inline_window_tab_rename_tab_id(&self) -> Option<TabId> {
+ self.inline_tab_rename
+ .as_ref()
+ .and_then(|rename| match rename.target {
+ InlineTabRenameTarget::WindowTab(tab_id) => Some(tab_id),
+ InlineTabRenameTarget::PaneTab(_) => None,
+ })
+ }
+
+ pub fn pane_nav_tab_title(&self, pane_id: PaneId, title: &str) -> String {
+ if let Some(title) = self
+ .inline_tab_rename
+ .as_ref()
+ .filter(|rename| matches!(rename.target, InlineTabRenameTarget::PaneTab(id) if id == pane_id))
+ .map(|rename| rename.display_text())
+ {
+ return title;
+ }
+
+ self.pane_tab_title_overrides
+ .get(&pane_id)
+ .cloned()
+ .unwrap_or_else(|| ui::terminal_title_for_display(title).to_string())
+ }
+
+ pub fn is_renaming_pane_nav_tab(&self, pane_id: PaneId) -> bool {
+ self.inline_tab_rename.as_ref().is_some_and(
+ |rename| matches!(rename.target, InlineTabRenameTarget::PaneTab(id) if id == pane_id),
+ )
+ }
+
fn show_confirmation(&mut self, args: &Confirmation) {
let mux = Mux::get();
let tab = match mux.get_active_tab_for_window(self.mux_window_id) {
@@ -2640,6 +3064,9 @@ impl TermWindow {
SpawnTab(spawn_where) => {
self.spawn_tab(spawn_where);
}
+ SpawnTabToRight(spawn_where) => {
+ self.spawn_tab_to_right(spawn_where);
+ }
SpawnWindow => {
self.spawn_command(&SpawnCommand::default(), SpawnWhere::NewWindow);
}
@@ -2776,6 +3203,8 @@ impl TermWindow {
ScrollToTop => self.scroll_to_top(pane),
ScrollToBottom => self.scroll_to_bottom(pane),
ShowTabNavigator => self.show_tab_navigator(),
+ PromptRenameTab => self.prompt_rename_current_tab(),
+ PromptRenamePaneTab(pane_id) => self.prompt_rename_pane_tab(*pane_id),
ShowDebugOverlay => self.show_debug_overlay(),
ShowLauncher => self.show_launcher(),
ShowLauncherArgs(args) => {
@@ -3155,6 +3584,9 @@ impl TermWindow {
OpenUri(link) => {
wezterm_open_url::open_url(link);
}
+ OpenSettings => {
+ crate::settings_window::show();
+ }
ActivateCommandPalette => {
let modal = crate::termwindow::palette::CommandPalette::new(self);
self.set_modal(Rc::new(modal));
@@ -3221,6 +3653,12 @@ impl TermWindow {
None => return,
};
+ self.close_pane(pane, confirm);
+ }
+
+ fn close_pane(&mut self, pane: Arc<dyn Pane>, confirm: bool) {
+ let mux_window_id = self.mux_window_id;
+ let mux = Mux::get();
let pane_id = pane.pane_id();
if confirm && !pane.can_close_without_prompting(CloseReason::Pane) {
let window = self.window.clone().unwrap();
@@ -3291,6 +3729,46 @@ impl TermWindow {
})
}
+ pub fn pane_font_scale(&self, pane_id: PaneId) -> f64 {
+ self.pane_state
+ .borrow()
+ .get(&pane_id)
+ .and_then(|state| state.font_scale)
+ .unwrap_or_else(|| self.fonts.get_font_scale())
+ }
+
+ pub fn pane_font_resources(
+ &self,
+ font_scale: f64,
+ ) -> anyhow::Result<(Rc<FontConfiguration>, RenderMetrics)> {
+ let key = PaneFontKey {
+ font_scale_bits: font_scale.to_bits(),
+ dpi: self.dimensions.dpi,
+ config_generation: self.config.generation(),
+ };
+
+ if let Some(entry) = self.pane_font_cache.borrow().get(&key) {
+ return Ok((Rc::clone(&entry.fonts), entry.render_metrics));
+ }
+
+ let fonts = Rc::new(FontConfiguration::new(
+ Some(self.config.clone()),
+ self.dimensions.dpi,
+ )?);
+ fonts.change_scaling(font_scale, self.dimensions.dpi);
+ let render_metrics = RenderMetrics::new(&fonts)?;
+
+ self.pane_font_cache.borrow_mut().insert(
+ key,
+ PaneFontEntry {
+ fonts: Rc::clone(&fonts),
+ render_metrics,
+ },
+ );
+
+ Ok((fonts, render_metrics))
+ }
+
pub fn tab_state(&self, tab_id: TabId) -> RefMut<'_, TabState> {
RefMut::map(self.tab_state.borrow_mut(), |state| {
state.entry(tab_id).or_insert_with(TabState::default)
@@ -3467,17 +3945,21 @@ impl TermWindow {
.enumerate()
.map(|(idx, tab)| {
let panes = self.get_pos_panes_for_tab(tab);
+ let tab_id = tab.tab_id();
+ let tab_title = self
+ .inline_window_tab_rename_title(tab_id)
+ .unwrap_or_else(|| tab.get_title());
TabInformation {
tab_index: idx,
- tab_id: tab.tab_id(),
+ tab_id,
is_active: tab_index == idx,
is_last_active: window
.get_last_active_idx()
.map(|last_active| last_active == idx)
.unwrap_or(false),
window_id: self.mux_window_id,
- tab_title: tab.get_title(),
+ tab_title,
active_pane: panes
.iter()
.find(|p| p.is_active)
diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rs
index 07bc58e2..c86ec710 100644
--- a/wezterm-gui/src/termwindow/mouseevent.rs
+++ b/wezterm-gui/src/termwindow/mouseevent.rs
@@ -1,6 +1,10 @@
+use crate::frontend::front_end;
use crate::tabbar::TabBarItem;
+use crate::termwindow::ui::pane_nav_bar_height_for_metrics;
+use crate::termwindow::ui::tokens::{PANE_NAV_BUTTON_GAP, PANE_NAV_INSET, PANE_NAV_TAB_MAX_WIDTH};
use crate::termwindow::{
- GuiWin, MouseCapture, PositionedSplit, ScrollHit, TermWindowNotif, UIItem, UIItemType, TMB,
+ GuiWin, MouseCapture, PaneNavAction, PositionedSplit, ScrollHit, TermWindowNotif, UIItem,
+ UIItemType, TMB,
};
use ::window::{
ContextMenuItem, MouseButtons as WMB, MouseCursor, MouseEvent, MouseEventKind as WMEK,
@@ -12,7 +16,7 @@ use config::keyassignment::{
};
use config::MouseEventAltScreen;
use mux::pane::{Pane, WithPaneLines};
-use mux::tab::SplitDirection;
+use mux::tab::{PositionedPane, SplitDirection};
use mux::Mux;
use mux_lua::MuxPane;
use std::convert::TryInto;
@@ -27,6 +31,221 @@ use wezterm_term::input::{MouseButton, MouseEventKind as TMEK};
use wezterm_term::{ClickPosition, LastMouseClick, StableRowIndex};
impl super::TermWindow {
+ fn tab_scroll_pixels(amount: i16) -> f32 {
+ let steps = amount.unsigned_abs().max(1) as f32;
+ let delta = (steps * 56.0).min(280.0);
+ if amount < 0 {
+ delta
+ } else {
+ -delta
+ }
+ }
+
+ pub(super) fn window_tab_width_pixels(&self) -> f32 {
+ let cell_width = self.render_metrics.cell_size.width.max(1) as f32;
+ (self.config.tab_max_width as f32 * cell_width)
+ .max(cell_width * 15.0)
+ .max(176.0)
+ .ceil()
+ }
+
+ pub(super) fn window_tab_left_padding_pixels(&self) -> f32 {
+ if self.workspace_sidebar_width() > 0 {
+ return 0.0;
+ }
+
+ let cell_width = self.render_metrics.cell_size.width.max(1) as f32;
+ if self
+ .config
+ .window_decorations
+ .contains(WindowDecorations::INTEGRATED_BUTTONS)
+ && (self.config.integrated_title_button_alignment
+ == window::IntegratedTitleButtonAlignment::Left
+ || self.config.integrated_title_button_style
+ == window::IntegratedTitleButtonStyle::MacOsNative)
+ {
+ if self.config.integrated_title_button_style
+ == window::IntegratedTitleButtonStyle::MacOsNative
+ {
+ if self.window_state.contains(WindowState::FULL_SCREEN) {
+ cell_width * 0.5
+ } else {
+ 70.0
+ }
+ } else {
+ 0.0
+ }
+ } else {
+ cell_width * 0.5
+ }
+ }
+
+ pub(super) fn window_tab_viewport_width(&self) -> f32 {
+ let border = self.get_os_border();
+ let left_padding = self.window_tab_left_padding_pixels();
+
+ self.dimensions
+ .pixel_width
+ .saturating_sub(self.tab_bar_left_edge())
+ .saturating_sub(border.right.get() as usize)
+ .saturating_sub(left_padding.max(0.0) as usize)
+ .max(1) as f32
+ }
+
+ pub(super) fn max_window_tab_scroll_offset(&self) -> f32 {
+ let mux = Mux::get();
+ let Some(window) = mux.get_window(self.mux_window_id) else {
+ return 0.0;
+ };
+ let tab_count = window.len();
+ if tab_count <= 1 {
+ return 0.0;
+ }
+
+ let tab_width = self.window_tab_width_pixels();
+ let total_width = tab_count as f32 * tab_width;
+ let available_width = self.window_tab_viewport_width();
+
+ (total_width - available_width).max(0.0)
+ }
+
+ fn scroll_window_tab_bar(&mut self, amount: i16, context: &dyn WindowOps) {
+ let max_offset = self.max_window_tab_scroll_offset();
+ let offset =
+ (self.tab_bar_scroll_target + Self::tab_scroll_pixels(amount)).clamp(0.0, max_offset);
+ if (offset - self.tab_bar_scroll_target).abs() > f32::EPSILON
+ || (offset - self.tab_bar_scroll_offset).abs() > f32::EPSILON
+ {
+ self.tab_bar_scroll_target = offset;
+ self.tab_bar_scroll_offset = offset;
+ self.invalidate_fancy_tab_bar();
+ context.invalidate();
+ }
+ }
+
+ fn max_pane_nav_tab_scroll_offset(&self, pane_id: mux::pane::PaneId) -> f32 {
+ let Some(tab) = Mux::get().get_active_tab_for_window(self.mux_window_id) else {
+ return 0.0;
+ };
+
+ let tab_count = Mux::get().pane_stack_tabs(pane_id).len();
+ if tab_count <= 1 {
+ return 0.0;
+ }
+
+ let cell_width = self.render_metrics.cell_size.width as f32;
+ let pane_width = tab
+ .iter_panes_ignoring_zoom()
+ .into_iter()
+ .find(|pos| pos.pane.pane_id() == pane_id)
+ .map(|pos| pos.width as f32 * cell_width)
+ .unwrap_or(0.0);
+ if pane_width <= 0.0 {
+ return 0.0;
+ }
+
+ let nav_height = pane_nav_bar_height_for_metrics(self.render_metrics);
+ let icon_size = nav_height.saturating_sub(PANE_NAV_INSET * 2).clamp(20, 24);
+ let button_size = (icon_size + 10)
+ .min(nav_height.saturating_sub(4))
+ .max(icon_size);
+ let controls_width = (button_size + PANE_NAV_BUTTON_GAP)
+ .saturating_mul(2)
+ .saturating_add(PANE_NAV_INSET * 2);
+ let viewport_width = (pane_width as usize).saturating_sub(controls_width).max(1) as f32;
+ let tab_width = PANE_NAV_TAB_MAX_WIDTH as f32;
+ let total_width = tab_count as f32 * tab_width
+ + tab_count.saturating_sub(1) as f32 * PANE_NAV_BUTTON_GAP as f32;
+
+ (total_width - viewport_width).max(0.0)
+ }
+
+ fn scroll_pane_nav_tabs(
+ &mut self,
+ pane_id: mux::pane::PaneId,
+ amount: i16,
+ context: &dyn WindowOps,
+ ) {
+ let current = self
+ .pane_nav_tab_scroll_targets
+ .get(&pane_id)
+ .copied()
+ .or_else(|| self.pane_nav_tab_scroll_offsets.get(&pane_id).copied())
+ .unwrap_or(0.0);
+ let max_offset = self.max_pane_nav_tab_scroll_offset(pane_id);
+ let offset = (current + Self::tab_scroll_pixels(amount)).clamp(0.0, max_offset.max(0.0));
+ if (offset - current).abs() > f32::EPSILON
+ || self
+ .pane_nav_tab_scroll_offsets
+ .get(&pane_id)
+ .is_some_and(|current| (offset - current).abs() > f32::EPSILON)
+ {
+ self.pane_nav_tab_scroll_targets.insert(pane_id, offset);
+ self.pane_nav_tab_scroll_offsets.insert(pane_id, offset);
+ context.invalidate();
+ }
+ }
+
+ fn wheel_amount(event: &MouseEvent) -> Option<i16> {
+ match event.kind {
+ WMEK::VertWheel(amount) | WMEK::HorzWheel(amount) => Some(amount),
+ _ => None,
+ }
+ }
+
+ fn mouse_wheel_tab_surfaces(&mut self, event: &MouseEvent, context: &dyn WindowOps) -> bool {
+ let Some(amount) = Self::wheel_amount(event) else {
+ return false;
+ };
+
+ if self.show_tab_bar {
+ let border = self.get_os_border();
+ let tab_bar_height = self.tab_bar_pixel_height().unwrap_or(0.);
+ let tab_bar_y = if self.config.tab_bar_at_bottom {
+ self.dimensions.pixel_height as f32 - tab_bar_height - border.bottom.get() as f32
+ } else {
+ border.top.get() as f32
+ };
+ let y = event.coords.y as f32;
+ if event.coords.x >= self.tab_bar_left_edge() as isize
+ && y >= tab_bar_y
+ && y < tab_bar_y + tab_bar_height
+ {
+ self.scroll_window_tab_bar(amount, context);
+ return true;
+ }
+ }
+
+ let Some(tab) = Mux::get().get_active_tab_for_window(self.mux_window_id) else {
+ return false;
+ };
+
+ let border = self.get_os_border();
+ let top_bar_height = if self.show_tab_bar && !self.config.tab_bar_at_bottom {
+ self.tab_bar_pixel_height().unwrap_or(0.)
+ } else {
+ 0.0
+ };
+ let (padding_left, _) = self.padding_left_top();
+ let nav_height = pane_nav_bar_height_for_metrics(self.render_metrics) as f32;
+ let cell_width = self.render_metrics.cell_size.width as f32;
+ let cell_height = self.render_metrics.cell_size.height as f32;
+ let x = event.coords.x as f32;
+ let y = event.coords.y as f32;
+
+ for pos in tab.iter_panes_ignoring_zoom() {
+ let pane_x = padding_left + border.left.get() as f32 + pos.left as f32 * cell_width;
+ let pane_y = top_bar_height + border.top.get() as f32 + pos.top as f32 * cell_height;
+ let pane_width = pos.width as f32 * cell_width;
+ if x >= pane_x && x < pane_x + pane_width && y >= pane_y && y < pane_y + nav_height {
+ self.scroll_pane_nav_tabs(pos.pane.pane_id(), amount, context);
+ return true;
+ }
+ }
+
+ false
+ }
+
fn resolve_ui_item(&self, event: &MouseEvent) -> Option<UIItem> {
let x = event.coords.x;
let y = event.coords.y;
@@ -43,6 +262,10 @@ impl super::TermWindow {
self.update_title_post_status();
}
UIItemType::CloseTab(_)
+ | UIItemType::PaneNav { .. }
+ | UIItemType::WorkspaceSidebar(_)
+ | UIItemType::WorkspaceSidebarBackground
+ | UIItemType::WorkspaceSidebarResize
| UIItemType::AboveScrollThumb
| UIItemType::BelowScrollThumb
| UIItemType::ScrollThumb
@@ -54,6 +277,10 @@ impl super::TermWindow {
match item.item_type {
UIItemType::TabBar(_) => {}
UIItemType::CloseTab(_)
+ | UIItemType::PaneNav { .. }
+ | UIItemType::WorkspaceSidebar(_)
+ | UIItemType::WorkspaceSidebarBackground
+ | UIItemType::WorkspaceSidebarResize
| UIItemType::AboveScrollThumb
| UIItemType::BelowScrollThumb
| UIItemType::ScrollThumb
@@ -61,6 +288,68 @@ impl super::TermWindow {
}
}
+ fn click_position_for_pane(
+ &self,
+ event: &MouseEvent,
+ pane: &Arc<dyn Pane>,
+ pos: &PositionedPane,
+ ) -> ClickPosition {
+ let border = self.get_os_border();
+ let first_line_offset = if self.show_tab_bar && !self.config.tab_bar_at_bottom {
+ self.tab_bar_pixel_height().unwrap_or(0.) as isize
+ } else {
+ 0
+ } + border.top.get() as isize;
+ let (padding_left, padding_top) = self.padding_left_top();
+
+ let global_cell_size = self.render_metrics.cell_size;
+ let pane_font_scale = self.pane_font_scale(pos.pane.pane_id());
+ let pane_cell_size = if pane_font_scale.to_bits() == self.fonts.get_font_scale().to_bits() {
+ global_cell_size
+ } else {
+ self.pane_font_resources(pane_font_scale)
+ .map(|(_, metrics)| metrics.cell_size)
+ .unwrap_or(global_cell_size)
+ };
+
+ let pane_left = (padding_left + border.left.get() as f32) as isize
+ + (pos.left as isize * global_cell_size.width);
+ let pane_top =
+ padding_top as isize + first_line_offset + (pos.top as isize * global_cell_size.height);
+ let pane_nav_height = pane_nav_bar_height_for_metrics(self.render_metrics) as isize;
+
+ let local_x = event.coords.x.sub(pane_left);
+ let local_y = event.coords.y.sub(pane_top + pane_nav_height);
+
+ let x = (local_x.max(0) as f32) / pane_cell_size.width.max(1) as f32;
+ let column = if !pane.is_mouse_grabbed() {
+ x.round()
+ } else {
+ x
+ }
+ .trunc() as usize;
+
+ let row = (local_y.max(0) / pane_cell_size.height.max(1)) as i64;
+
+ let x_pixel_offset = if column > 0 {
+ local_x.max(0) % pane_cell_size.width.max(1)
+ } else {
+ local_x
+ };
+ let y_pixel_offset = if row > 0 {
+ local_y.max(0) % pane_cell_size.height.max(1)
+ } else {
+ local_y
+ };
+
+ ClickPosition {
+ column,
+ row,
+ x_pixel_offset,
+ y_pixel_offset,
+ }
+ }
+
pub fn mouse_event_impl(&mut self, event: MouseEvent, context: &dyn WindowOps) {
log::trace!("{:?}", event);
let pane = match self.get_active_pane_or_overlay() {
@@ -70,6 +359,10 @@ impl super::TermWindow {
self.current_mouse_event.replace(event.clone());
+ if self.mouse_wheel_tab_surfaces(&event, context) {
+ return;
+ }
+
let border = self.get_os_border();
let first_line_offset = if self.show_tab_bar && !self.config.tab_bar_at_bottom {
@@ -351,12 +644,32 @@ impl super::TermWindow {
UIItemType::ScrollThumb => {
self.drag_scroll_thumb(item, start_event, event, context);
}
+ UIItemType::WorkspaceSidebarResize => {
+ self.drag_workspace_sidebar_resize(item, start_event, event, context);
+ }
+ UIItemType::PaneNav { .. } => {}
_ => {
log::error!("drag not implemented for {:?}", item);
}
}
}
+ fn drag_workspace_sidebar_resize(
+ &mut self,
+ item: UIItem,
+ start_event: MouseEvent,
+ event: MouseEvent,
+ context: &dyn WindowOps,
+ ) {
+ let left_edge = self.get_os_border().left.get() as isize;
+ let width = event.coords.x.saturating_sub(left_edge).max(0) as usize;
+ self.expand_workspace_sidebar();
+ self.set_workspace_sidebar_width(width);
+ self.reflow_workspace_sidebar(context);
+ context.set_cursor(Some(MouseCursor::SizeLeftRight));
+ self.dragging.replace((item, start_event));
+ }
+
fn mouse_event_ui_item(
&mut self,
item: UIItem,
@@ -385,7 +698,186 @@ impl super::TermWindow {
UIItemType::CloseTab(idx) => {
self.mouse_event_close_tab(idx, event, context);
}
+ UIItemType::PaneNav {
+ pane_id,
+ pane_index,
+ action,
+ } => {
+ self.mouse_event_pane_nav(pane_id, pane_index, action, event, context);
+ }
+ UIItemType::WorkspaceSidebar(workspace) => {
+ self.mouse_event_workspace_sidebar(workspace, event, context);
+ }
+ UIItemType::WorkspaceSidebarBackground => {
+ context.set_cursor(Some(MouseCursor::Arrow));
+ }
+ UIItemType::WorkspaceSidebarResize => {
+ self.mouse_event_workspace_sidebar_resize(item, event, context);
+ }
+ }
+ }
+
+ fn reflow_workspace_sidebar(&mut self, context: &dyn WindowOps) {
+ if let Some(window) = self.window.as_ref().cloned() {
+ let dimensions = self.dimensions;
+ self.apply_dimensions(&dimensions, None, &window);
}
+ context.invalidate();
+ }
+
+ pub fn mouse_event_workspace_sidebar_resize(
+ &mut self,
+ item: UIItem,
+ event: MouseEvent,
+ context: &dyn WindowOps,
+ ) {
+ context.set_cursor(Some(MouseCursor::SizeLeftRight));
+ if event.kind == WMEK::Press(MousePress::Left) {
+ self.dragging.replace((item, event));
+ }
+ }
+
+ pub fn mouse_event_workspace_sidebar(
+ &mut self,
+ workspace: String,
+ event: MouseEvent,
+ context: &dyn WindowOps,
+ ) {
+ if let WMEK::Press(MousePress::Left) = event.kind {
+ if Mux::get().active_workspace() != workspace {
+ front_end().switch_workspace(&workspace);
+ }
+ context.invalidate();
+ }
+ context.set_cursor(Some(MouseCursor::Arrow));
+ }
+
+ fn pane_nav_tab_context_menu_items(&self, pane_id: mux::pane::PaneId) -> Vec<ContextMenuItem> {
+ vec![ContextMenuItem::item_with_icon(
+ "Rename Tab...",
+ "pencil",
+ KeyAssignment::PromptRenamePaneTab(pane_id),
+ )]
+ }
+
+ pub fn mouse_event_pane_nav(
+ &mut self,
+ pane_id: mux::pane::PaneId,
+ pane_index: usize,
+ action: PaneNavAction,
+ event: MouseEvent,
+ context: &dyn WindowOps,
+ ) {
+ context.set_cursor(Some(MouseCursor::Arrow));
+
+ match event.kind {
+ WMEK::VertWheel(amount) | WMEK::HorzWheel(amount) => {
+ self.scroll_pane_nav_tabs(pane_id, amount, context);
+ return;
+ }
+ _ => {}
+ }
+
+ if event.kind == WMEK::Press(MousePress::Right) {
+ if let PaneNavAction::Activate(target_pane_id) = action {
+ context.show_context_menu(
+ event.coords,
+ self.pane_nav_tab_context_menu_items(target_pane_id),
+ );
+ }
+ return;
+ }
+
+ if event.kind != WMEK::Press(MousePress::Left) {
+ return;
+ }
+
+ let mux = Mux::get();
+ if let Some(tab) = mux.get_active_tab_for_window(self.mux_window_id) {
+ tab.set_active_idx(pane_index);
+ }
+
+ match action {
+ PaneNavAction::Background => {
+ if self.last_mouse_click.as_ref().map(|c| c.streak) == Some(2) {
+ self.spawn_pane_nav_tab(pane_id, pane_index);
+ }
+ }
+ PaneNavAction::Activate(target_pane_id) => {
+ if target_pane_id != pane_id {
+ if let Err(err) = mux.activate_pane_in_stack(target_pane_id) {
+ log::error!("pane nav activate failed: {err:#}");
+ }
+ }
+ }
+ PaneNavAction::Close(target_pane_id) => {
+ if let Some(pane) = mux.get_pane(target_pane_id) {
+ self.close_pane(pane, true);
+ }
+ }
+ PaneNavAction::NewTab => self.spawn_pane_nav_tab(pane_id, pane_index),
+ PaneNavAction::SplitRight | PaneNavAction::SplitDown => {
+ let pane = match mux.get_pane(pane_id) {
+ Some(pane) => pane,
+ None => return,
+ };
+ let direction = match action {
+ PaneNavAction::SplitRight => PaneDirection::Right,
+ PaneNavAction::SplitDown => PaneDirection::Down,
+ _ => unreachable!(),
+ };
+ let assignment = KeyAssignment::SplitPane(SplitPane {
+ direction,
+ size: SplitSize::Percent(50),
+ command: SpawnCommand::default(),
+ top_level: false,
+ });
+ if let Err(err) = self.perform_key_assignment(&pane, &assignment) {
+ log::error!("pane nav action failed: {err:#}");
+ }
+ }
+ }
+
+ context.invalidate();
+ }
+
+ fn spawn_pane_nav_tab(&mut self, pane_id: mux::pane::PaneId, pane_index: usize) {
+ let mux = Mux::get();
+ let tab = match mux.get_active_tab_for_window(self.mux_window_id) {
+ Some(tab) => tab,
+ None => return,
+ };
+ let panes = tab.iter_panes_ignoring_zoom();
+ let pos = panes
+ .iter()
+ .find(|pos| pos.pane.pane_id() == pane_id)
+ .or_else(|| panes.get(pane_index))
+ .cloned();
+ let pos = match pos {
+ Some(pos) => pos,
+ None => return,
+ };
+ let size = self.terminal_size_for_positioned_pane(&pos, self.render_metrics);
+ let window = GuiWin::new(self);
+
+ promise::spawn::spawn(async move {
+ if let Err(err) = Mux::get()
+ .spawn_pane_in_stack(pane_id, SpawnTabDomain::CurrentPaneDomain, None, None, size)
+ .await
+ {
+ log::error!("pane nav new terminal failed: {err:#}");
+ return;
+ }
+ window
+ .window
+ .notify(TermWindowNotif::Apply(Box::new(move |term_window| {
+ term_window.update_title();
+ if let Some(window) = term_window.window.as_ref() {
+ window.invalidate();
+ }
+ })));
+ })
+ .detach();
}
pub fn mouse_event_close_tab(
@@ -456,6 +948,130 @@ impl super::TermWindow {
.detach();
}
+ fn spawn_window_tab_from_active_pane(&mut self) {
+ let pane = match self.get_active_pane_or_overlay() {
+ Some(pane) => pane,
+ None => return,
+ };
+ let assignment = KeyAssignment::SpawnTab(SpawnTabDomain::CurrentPaneDomain);
+ if let Err(err) = self.perform_key_assignment(&pane, &assignment) {
+ log::error!("tab bar double-click new tab failed: {err:#}");
+ }
+ }
+
+ fn tab_context_action(tab_idx: usize, action: KeyAssignment) -> KeyAssignment {
+ KeyAssignment::Multiple(vec![KeyAssignment::ActivateTab(tab_idx as isize), action])
+ }
+
+ fn close_tabs_to_left_action(tab_idx: usize) -> Option<KeyAssignment> {
+ if tab_idx == 0 {
+ return None;
+ }
+
+ let mut actions = Vec::with_capacity(tab_idx * 2);
+ for _ in 0..tab_idx {
+ actions.push(KeyAssignment::ActivateTab(0));
+ actions.push(KeyAssignment::CloseCurrentTab { confirm: false });
+ }
+ Some(KeyAssignment::Multiple(actions))
+ }
+
+ fn close_tabs_to_right_action(tab_idx: usize, tab_count: usize) -> Option<KeyAssignment> {
+ if tab_idx + 1 >= tab_count {
+ return None;
+ }
+
+ let mut actions = Vec::with_capacity((tab_count - tab_idx - 1) * 2);
+ for _ in tab_idx + 1..tab_count {
+ actions.push(KeyAssignment::ActivateTab((tab_idx + 1) as isize));
+ actions.push(KeyAssignment::CloseCurrentTab { confirm: false });
+ }
+ Some(KeyAssignment::Multiple(actions))
+ }
+
+ fn close_other_tabs_action(tab_idx: usize, tab_count: usize) -> Option<KeyAssignment> {
+ if tab_count <= 1 {
+ return None;
+ }
+
+ let mut actions = vec![];
+ if let Some(KeyAssignment::Multiple(mut right)) =
+ Self::close_tabs_to_right_action(tab_idx, tab_count)
+ {
+ actions.append(&mut right);
+ }
+ if let Some(KeyAssignment::Multiple(mut left)) = Self::close_tabs_to_left_action(tab_idx) {
+ actions.append(&mut left);
+ }
+ Some(KeyAssignment::Multiple(actions))
+ }
+
+ fn tab_context_menu_items(&self, tab_idx: usize) -> Vec<ContextMenuItem> {
+ let tab_count = Mux::get()
+ .get_window(self.mux_window_id)
+ .map(|window| window.len())
+ .unwrap_or(0);
+ if tab_count == 0 || tab_idx >= tab_count {
+ return vec![];
+ }
+
+ let mut items = vec![ContextMenuItem::item_with_icon(
+ "Rename Tab...",
+ "pencil",
+ Self::tab_context_action(tab_idx, KeyAssignment::PromptRenameTab),
+ )];
+
+ let mut close_items = vec![];
+ if let Some(action) = Self::close_tabs_to_left_action(tab_idx) {
+ close_items.push(ContextMenuItem::item("Close Tabs to Left", action));
+ }
+ if let Some(action) = Self::close_tabs_to_right_action(tab_idx, tab_count) {
+ close_items.push(ContextMenuItem::item("Close Tabs to Right", action));
+ }
+ if let Some(action) = Self::close_other_tabs_action(tab_idx, tab_count) {
+ close_items.push(ContextMenuItem::item("Close Other Tabs", action));
+ }
+ if !close_items.is_empty() {
+ items.push(ContextMenuItem::Separator);
+ items.append(&mut close_items);
+ }
+
+ let mut move_items = vec![];
+ if tab_idx > 0 {
+ move_items.push(ContextMenuItem::item(
+ "Move Tab Left",
+ Self::tab_context_action(tab_idx, KeyAssignment::MoveTab(tab_idx - 1)),
+ ));
+ }
+ if tab_idx + 1 < tab_count {
+ move_items.push(ContextMenuItem::item(
+ "Move Tab Right",
+ Self::tab_context_action(tab_idx, KeyAssignment::MoveTab(tab_idx + 1)),
+ ));
+ }
+ if !move_items.is_empty() {
+ items.push(ContextMenuItem::Separator);
+ items.append(&mut move_items);
+ }
+
+ items.push(ContextMenuItem::Separator);
+ items.push(ContextMenuItem::item_with_icon(
+ "New Terminal Tab to Right",
+ "plus.square",
+ Self::tab_context_action(
+ tab_idx,
+ KeyAssignment::SpawnTabToRight(SpawnTabDomain::CurrentPaneDomain),
+ ),
+ ));
+ items.push(ContextMenuItem::Separator);
+ items.push(ContextMenuItem::item(
+ "Zoom Pane",
+ Self::tab_context_action(tab_idx, KeyAssignment::TogglePaneZoomState),
+ ));
+
+ items
+ }
+
pub fn mouse_event_tab_bar(
&mut self,
item: TabBarItem,
@@ -471,6 +1087,13 @@ impl super::TermWindow {
self.do_new_tab_button_click(MousePress::Left);
}
TabBarItem::None | TabBarItem::LeftStatus | TabBarItem::RightStatus => {
+ if self.last_mouse_click.as_ref().map(|c| c.streak) == Some(2) {
+ self.window_drag_position.take();
+ self.spawn_window_tab_from_active_pane();
+ context.invalidate();
+ return;
+ }
+
let maximized = self
.window_state
.intersects(WindowState::MAXIMIZED | WindowState::FULL_SCREEN);
@@ -526,8 +1149,8 @@ impl super::TermWindow {
| TabBarItem::WindowButton(_) => {}
},
WMEK::Press(MousePress::Right) => match item {
- TabBarItem::Tab { .. } => {
- self.show_tab_navigator();
+ TabBarItem::Tab { tab_idx, .. } => {
+ context.show_context_menu(event.coords, self.tab_context_menu_items(tab_idx));
}
TabBarItem::NewTabButton { .. } => {
self.do_new_tab_button_click(MousePress::Right);
@@ -555,11 +1178,8 @@ impl super::TermWindow {
| TabBarItem::Tab { .. }
| TabBarItem::NewTabButton { .. } => {}
},
- WMEK::VertWheel(n) => {
- if self.config.mouse_wheel_scrolls_tabs {
- self.activate_tab_relative(if n < 1 { 1 } else { -1 }, true)
- .ok();
- }
+ WMEK::VertWheel(amount) | WMEK::HorzWheel(amount) => {
+ self.scroll_window_tab_bar(amount, context);
}
_ => {}
}
@@ -741,22 +1361,18 @@ impl super::TermWindow {
}
}
}
- column = column.saturating_sub(pos.left);
- row = row.saturating_sub(pos.top as i64);
+ let position = self.click_position_for_pane(&event, &pane, &pos);
+ column = position.column;
+ row = position.row;
+ x_pixel_offset = position.x_pixel_offset;
+ y_pixel_offset = position.y_pixel_offset;
break;
} else if is_already_captured && pane.pane_id() == pos.pane.pane_id() {
- column = column.saturating_sub(pos.left);
- row = row.saturating_sub(pos.top as i64).max(0);
-
- if position.column < pos.left {
- x_pixel_offset -= self.render_metrics.cell_size.width
- * (pos.left as isize - position.column as isize);
- }
- if position.row < pos.top as i64 {
- y_pixel_offset -= self.render_metrics.cell_size.height
- * (pos.top as isize - position.row as isize);
- }
-
+ let position = self.click_position_for_pane(&event, &pane, &pos);
+ column = position.column;
+ row = position.row;
+ x_pixel_offset = position.x_pixel_offset;
+ y_pixel_offset = position.y_pixel_offset;
break;
}
}
diff --git a/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs b/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs
index ebf39368..4123062a 100644
--- a/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs
+++ b/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs
@@ -1,532 +1,595 @@
-use crate::customglyph::*;
+use crate::customglyph::BlockKey;
+use crate::quad::{QuadTrait, TripleLayerQuadAllocator, TripleLayerQuadAllocatorTrait};
use crate::tabbar::{TabBarItem, TabEntry};
-use crate::termwindow::box_model::*;
-use crate::termwindow::render::corners::*;
-
-use crate::termwindow::render::window_buttons::window_button_element;
-use crate::termwindow::{UIItem, UIItemType};
+use crate::termwindow::ui::icons::SvgIcon;
+use crate::termwindow::{TermWindowNotif, UIItem, UIItemType};
use crate::utilsprites::RenderMetrics;
-use config::{Dimension, DimensionContext, TabBarColors};
+use anyhow::Context;
+use finl_unicode::grapheme_clusters::Graphemes;
use std::rc::Rc;
+use termwiz::cell::grapheme_column_width;
+use wezterm_bidi::Direction;
use wezterm_font::LoadedFont;
+use wezterm_term::Line;
use wezterm_term::color::{ColorAttribute, ColorPalette};
-use window::{IntegratedTitleButtonAlignment, IntegratedTitleButtonStyle};
-
-const X_BUTTON: &[Poly] = &[
- Poly {
- path: &[
- PolyCommand::MoveTo(BlockCoord::One, BlockCoord::Zero),
- PolyCommand::LineTo(BlockCoord::Zero, BlockCoord::One),
- ],
- intensity: BlockAlpha::Full,
- style: PolyStyle::Outline,
- },
- Poly {
- path: &[
- PolyCommand::MoveTo(BlockCoord::Zero, BlockCoord::Zero),
- PolyCommand::LineTo(BlockCoord::One, BlockCoord::One),
- ],
- intensity: BlockAlpha::Full,
- style: PolyStyle::Outline,
- },
-];
-
-const PLUS_BUTTON: &[Poly] = &[
- Poly {
- path: &[
- PolyCommand::MoveTo(BlockCoord::Frac(1, 2), BlockCoord::Zero),
- PolyCommand::LineTo(BlockCoord::Frac(1, 2), BlockCoord::One),
- ],
- intensity: BlockAlpha::Full,
- style: PolyStyle::Outline,
- },
- Poly {
- path: &[
- PolyCommand::MoveTo(BlockCoord::Zero, BlockCoord::Frac(1, 2)),
- PolyCommand::LineTo(BlockCoord::One, BlockCoord::Frac(1, 2)),
- ],
- intensity: BlockAlpha::Full,
- style: PolyStyle::Outline,
- },
-];
+use window::WindowOps;
+use window::color::LinearRgba;
+
+const WINDOW_TAB_INSET: usize = 8;
+const WINDOW_TAB_ICON_GAP: usize = 8;
+const WINDOW_TAB_BUTTON_GAP: usize = 6;
+const WINDOW_TAB_MIN_TEXT_COLS: usize = 3;
impl crate::TermWindow {
pub fn invalidate_fancy_tab_bar(&mut self) {
self.fancy_tab_bar.take();
}
- pub fn build_fancy_tab_bar(&self, palette: &ColorPalette) -> anyhow::Result<ComputedElement> {
- let tab_bar_height = self.tab_bar_pixel_height()?;
+ pub fn paint_fancy_tab_bar(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator,
+ ) -> anyhow::Result<Vec<UIItem>> {
+ let palette = self.palette().clone();
+ let row_height = self.tab_bar_pixel_height()?.ceil() as usize;
+ if row_height == 0 {
+ return Ok(vec![]);
+ }
+
let font = self.fonts.title_font()?;
let metrics = RenderMetrics::with_font_metrics(&font.metrics());
- let items = self.tab_bar.items();
- let colors = self
- .config
- .colors
- .as_ref()
- .and_then(|c| c.tab_bar.as_ref())
- .cloned()
- .unwrap_or_else(TabBarColors::default);
-
- let mut left_status = vec![];
- let mut left_eles = vec![];
- let mut right_eles = vec![];
- let bar_colors = ElementColors {
- border: BorderColor::default(),
- bg: if self.focused.is_some() {
- self.config.window_frame.active_titlebar_bg
- } else {
- self.config.window_frame.inactive_titlebar_bg
- }
- .to_linear()
- .into(),
- text: if self.focused.is_some() {
- self.config.window_frame.active_titlebar_fg
- } else {
- self.config.window_frame.inactive_titlebar_fg
- }
+ let icon_size = fancy_tab_icon_size(&metrics, row_height as f32) as usize;
+ let button_size = (icon_size + 10)
+ .min(row_height.saturating_sub(6))
+ .max(icon_size);
+ let tab_width = self.window_tab_width_pixels().ceil() as usize;
+
+ let background = palette
+ .resolve_bg(ColorAttribute::Default)
.to_linear()
- .into(),
- };
+ .mul_alpha(self.config.window_background_opacity);
+ let foreground = palette.foreground.to_linear();
+ let muted_fg = foreground.mul_alpha(0.66);
+ let divider = foreground.mul_alpha(0.14);
+ let active_edge = foreground.mul_alpha(0.20);
+ let accent = palette.selection_bg.to_linear();
- let item_to_elem = |item: &TabEntry| -> Element {
- let element = Element::with_line(&font, &item.title, palette);
-
- let bg_color = item
- .title
- .get_cell(0)
- .and_then(|c| match c.attrs().background() {
- ColorAttribute::Default => None,
- col => Some(palette.resolve_bg(col)),
- });
- let fg_color = item
- .title
- .get_cell(0)
- .and_then(|c| match c.attrs().foreground() {
- ColorAttribute::Default => None,
- col => Some(palette.resolve_fg(col)),
- });
-
- let new_tab = colors.new_tab();
- let new_tab_hover = colors.new_tab_hover();
- let active_tab = colors.active_tab();
-
- match item.item {
- TabBarItem::RightStatus | TabBarItem::LeftStatus | TabBarItem::None => element
- .item_type(UIItemType::TabBar(TabBarItem::None))
- .line_height(Some(1.75))
- .margin(BoxDimension {
- left: Dimension::Cells(0.),
- right: Dimension::Cells(0.),
- top: Dimension::Cells(0.0),
- bottom: Dimension::Cells(0.),
- })
- .padding(BoxDimension {
- left: Dimension::Cells(0.5),
- right: Dimension::Cells(0.),
- top: Dimension::Cells(0.),
- bottom: Dimension::Cells(0.),
- })
- .border(BoxDimension::new(Dimension::Pixels(0.)))
- .colors(bar_colors.clone()),
- TabBarItem::NewTabButton => Element::new(
- &font,
- ElementContent::Poly {
- line_width: metrics.underline_height.max(2),
- poly: SizedPoly {
- poly: PLUS_BUTTON,
- width: Dimension::Pixels(metrics.cell_size.height as f32 / 2.),
- height: Dimension::Pixels(metrics.cell_size.height as f32 / 2.),
- },
- },
- )
- .vertical_align(VerticalAlign::Middle)
- .item_type(UIItemType::TabBar(item.item.clone()))
- .margin(BoxDimension {
- left: Dimension::Cells(0.5),
- right: Dimension::Cells(0.),
- top: Dimension::Cells(0.2),
- bottom: Dimension::Cells(0.),
- })
- .padding(BoxDimension {
- left: Dimension::Cells(0.5),
- right: Dimension::Cells(0.5),
- top: Dimension::Cells(0.2),
- bottom: Dimension::Cells(0.25),
- })
- .border(BoxDimension::new(Dimension::Pixels(1.)))
- .colors(ElementColors {
- border: BorderColor::default(),
- bg: new_tab.bg_color.to_linear().into(),
- text: new_tab.fg_color.to_linear().into(),
- })
- .hover_colors(Some(ElementColors {
- border: BorderColor::default(),
- bg: new_tab_hover.bg_color.to_linear().into(),
- text: new_tab_hover.fg_color.to_linear().into(),
- })),
- TabBarItem::Tab { active, .. } if active => element
- .vertical_align(VerticalAlign::Bottom)
- .item_type(UIItemType::TabBar(item.item.clone()))
- .margin(BoxDimension {
- left: Dimension::Cells(0.),
- right: Dimension::Cells(0.),
- top: Dimension::Cells(0.2),
- bottom: Dimension::Cells(0.),
- })
- .padding(BoxDimension {
- left: Dimension::Cells(0.5),
- right: Dimension::Cells(0.5),
- top: Dimension::Cells(0.2),
- bottom: Dimension::Cells(0.25),
- })
- .border(BoxDimension::new(Dimension::Pixels(1.)))
- .border_corners(Some(Corners {
- top_left: SizedPoly {
- width: Dimension::Cells(0.5),
- height: Dimension::Cells(0.5),
- poly: TOP_LEFT_ROUNDED_CORNER,
- },
- top_right: SizedPoly {
- width: Dimension::Cells(0.5),
- height: Dimension::Cells(0.5),
- poly: TOP_RIGHT_ROUNDED_CORNER,
- },
- bottom_left: SizedPoly::none(),
- bottom_right: SizedPoly::none(),
- }))
- .colors(ElementColors {
- border: BorderColor::new(
- bg_color
- .unwrap_or_else(|| active_tab.bg_color.into())
- .to_linear(),
- ),
- bg: bg_color
- .unwrap_or_else(|| active_tab.bg_color.into())
- .to_linear()
- .into(),
- text: fg_color
- .unwrap_or_else(|| active_tab.fg_color.into())
- .to_linear()
- .into(),
- }),
- TabBarItem::Tab { .. } => element
- .vertical_align(VerticalAlign::Bottom)
- .item_type(UIItemType::TabBar(item.item.clone()))
- .margin(BoxDimension {
- left: Dimension::Cells(0.),
- right: Dimension::Cells(0.),
- top: Dimension::Cells(0.2),
- bottom: Dimension::Cells(0.),
- })
- .padding(BoxDimension {
- left: Dimension::Cells(0.5),
- right: Dimension::Cells(0.5),
- top: Dimension::Cells(0.2),
- bottom: Dimension::Cells(0.25),
- })
- .border(BoxDimension::new(Dimension::Pixels(1.)))
- .border_corners(Some(Corners {
- top_left: SizedPoly {
- width: Dimension::Cells(0.5),
- height: Dimension::Cells(0.5),
- poly: TOP_LEFT_ROUNDED_CORNER,
- },
- top_right: SizedPoly {
- width: Dimension::Cells(0.5),
- height: Dimension::Cells(0.5),
- poly: TOP_RIGHT_ROUNDED_CORNER,
- },
- bottom_left: SizedPoly {
- width: Dimension::Cells(0.),
- height: Dimension::Cells(0.33),
- poly: &[],
- },
- bottom_right: SizedPoly {
- width: Dimension::Cells(0.),
- height: Dimension::Cells(0.33),
- poly: &[],
- },
- }))
- .colors({
- let inactive_tab = colors.inactive_tab();
- let bg = bg_color
- .unwrap_or_else(|| inactive_tab.bg_color.into())
- .to_linear();
- let edge = colors.inactive_tab_edge().to_linear();
- ElementColors {
- border: BorderColor {
- left: bg,
- right: edge,
- top: bg,
- bottom: bg,
- },
- bg: bg.into(),
- text: fg_color
- .unwrap_or_else(|| inactive_tab.fg_color.into())
- .to_linear()
- .into(),
- }
- })
- .hover_colors({
- let inactive_tab_hover = colors.inactive_tab_hover();
- Some(ElementColors {
- border: BorderColor::new(
- bg_color
- .unwrap_or_else(|| inactive_tab_hover.bg_color.into())
- .to_linear(),
- ),
- bg: bg_color
- .unwrap_or_else(|| inactive_tab_hover.bg_color.into())
- .to_linear()
- .into(),
- text: fg_color
- .unwrap_or_else(|| inactive_tab_hover.fg_color.into())
- .to_linear()
- .into(),
- })
- }),
- TabBarItem::WindowButton(button) => window_button_element(
- button,
- self.window_state.contains(window::WindowState::MAXIMIZED),
- &font,
- &metrics,
- &self.config,
- ),
- }
+ let border = self.get_os_border();
+ let row_x = self.tab_bar_left_edge();
+ let row_y = if self.config.tab_bar_at_bottom {
+ self.dimensions
+ .pixel_height
+ .saturating_sub(row_height + border.bottom.get() as usize)
+ } else {
+ border.top.get() as usize
};
+ let row_width = self
+ .dimensions
+ .pixel_width
+ .saturating_sub(row_x + border.right.get() as usize)
+ .max(1);
+ let row_right = row_x + row_width;
+ let viewport_left = (row_x as f32 + self.window_tab_left_padding_pixels()).ceil() as usize;
+ let viewport_right = row_right;
+ let viewport_width = viewport_right.saturating_sub(viewport_left);
- let num_tabs: f32 = items
- .iter()
- .map(|item| match item.item {
- TabBarItem::NewTabButton | TabBarItem::Tab { .. } => 1.,
- _ => 0.,
- })
- .sum();
- let max_tab_width = ((self.dimensions.pixel_width as f32 / num_tabs)
- - (1.5 * metrics.cell_size.width as f32))
- .max(0.);
-
- // Reserve space for the native titlebar buttons
- if self
- .config
- .window_decorations
- .contains(::window::WindowDecorations::INTEGRATED_BUTTONS)
- && self.config.integrated_title_button_style == IntegratedTitleButtonStyle::MacOsNative
- && !self.window_state.contains(window::WindowState::FULL_SCREEN)
- {
- left_status.push(
- Element::new(&font, ElementContent::Text("".to_string())).margin(BoxDimension {
- left: Dimension::Cells(4.0), // FIXME: determine exact width of macos ... buttons
- right: Dimension::Cells(0.),
- top: Dimension::Cells(0.),
- bottom: Dimension::Cells(0.),
- }),
- );
+ self.filled_rectangle(
+ layers,
+ 0,
+ euclid::rect(
+ row_x as f32,
+ row_y as f32,
+ row_width as f32,
+ row_height as f32,
+ ),
+ background,
+ )
+ .context("fancy tab bar background")?;
+ self.filled_rectangle(
+ layers,
+ 1,
+ euclid::rect(
+ row_x as f32,
+ (row_y + row_height.saturating_sub(1)) as f32,
+ row_width as f32,
+ 1.0,
+ ),
+ divider,
+ )
+ .context("fancy tab bar divider")?;
+
+ let mut ui_items = vec![UIItem {
+ x: row_x,
+ y: row_y,
+ width: row_width,
+ height: row_height,
+ item_type: UIItemType::TabBar(TabBarItem::None),
+ }];
+
+ if viewport_width == 0 || tab_width == 0 {
+ return Ok(ui_items);
}
- for item in items {
- match item.item {
- TabBarItem::LeftStatus => left_status.push(item_to_elem(item)),
- TabBarItem::None | TabBarItem::RightStatus => right_eles.push(item_to_elem(item)),
- TabBarItem::WindowButton(_) => {
- if self.config.integrated_title_button_alignment
- == IntegratedTitleButtonAlignment::Left
- {
- left_eles.push(item_to_elem(item))
- } else {
- right_eles.push(item_to_elem(item))
- }
- }
- TabBarItem::Tab { tab_idx, active } => {
- let mut elem = item_to_elem(item);
- elem.max_width = Some(Dimension::Pixels(max_tab_width));
- elem.content = match elem.content {
- ElementContent::Text(_) => unreachable!(),
- ElementContent::Poly { .. } => unreachable!(),
- ElementContent::Children(mut kids) => {
- if self.config.show_close_tab_button_in_tabs {
- kids.push(make_x_button(&font, &metrics, &colors, tab_idx, active));
- }
- ElementContent::Children(kids)
- }
- };
- left_eles.push(elem);
- }
- _ => left_eles.push(item_to_elem(item)),
+ let max_scroll = self.max_window_tab_scroll_offset();
+ let scroll_offset = self.tab_bar_scroll_offset.clamp(0.0, max_scroll.max(0.0));
+ let inline_rename_tab_idx = self.inline_window_tab_rename_tab_id().and_then(|tab_id| {
+ mux::Mux::get()
+ .get_window(self.mux_window_id)
+ .and_then(|window| window.idx_by_id(tab_id))
+ });
+
+ let mut tab_sequence_idx = 0usize;
+ for item in self.tab_bar.items() {
+ let TabBarItem::Tab { tab_idx, active } = item.item else {
+ continue;
+ };
+
+ let virtual_left = tab_sequence_idx as f32 * tab_width as f32 - scroll_offset;
+ tab_sequence_idx += 1;
+
+ let tab_left = viewport_left as f32 + virtual_left;
+ let tab_right = tab_left + tab_width as f32;
+ if tab_right <= viewport_left as f32 || tab_left >= viewport_right as f32 {
+ continue;
}
- }
- let mut children = vec![];
+ let visible_left = tab_left.max(viewport_left as f32);
+ let visible_right = tab_right.min(viewport_right as f32);
+ let visible_width = (visible_right - visible_left).max(0.0);
+ if visible_width <= 1.0 {
+ continue;
+ }
- if !left_status.is_empty() {
- children.push(
- Element::new(&font, ElementContent::Children(left_status))
- .colors(bar_colors.clone()),
- );
+ self.paint_window_tab(
+ layers,
+ &mut ui_items,
+ item,
+ tab_idx,
+ active,
+ inline_rename_tab_idx == Some(tab_idx),
+ tab_left,
+ visible_left,
+ visible_width,
+ viewport_left,
+ viewport_right,
+ row_y,
+ row_height,
+ tab_width,
+ button_size,
+ icon_size,
+ &font,
+ metrics,
+ &palette,
+ background,
+ if active { foreground } else { muted_fg },
+ active_edge,
+ accent,
+ )?;
}
- let window_buttons_at_left = self
- .config
- .window_decorations
- .contains(window::WindowDecorations::INTEGRATED_BUTTONS)
- && (self.config.integrated_title_button_alignment
- == IntegratedTitleButtonAlignment::Left
- || self.config.integrated_title_button_style
- == IntegratedTitleButtonStyle::MacOsNative);
-
- let left_padding = if window_buttons_at_left {
- if self.config.integrated_title_button_style == IntegratedTitleButtonStyle::MacOsNative
- {
- if !self.window_state.contains(window::WindowState::FULL_SCREEN) {
- Dimension::Pixels(70.0)
- } else {
- Dimension::Cells(0.5)
- }
- } else {
- Dimension::Pixels(0.0)
- }
+ self.paint_fancy_tab_bar_overflow(
+ layers,
+ row_y,
+ row_height,
+ viewport_left,
+ viewport_width,
+ scroll_offset,
+ max_scroll,
+ background,
+ divider,
+ )?;
+
+ Ok(ui_items)
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ fn paint_window_tab(
+ &self,
+ layers: &mut TripleLayerQuadAllocator,
+ ui_items: &mut Vec<UIItem>,
+ item: &TabEntry,
+ tab_idx: usize,
+ active: bool,
+ is_renaming: bool,
+ tab_left: f32,
+ visible_left: f32,
+ visible_width: f32,
+ viewport_left: usize,
+ viewport_right: usize,
+ row_y: usize,
+ row_height: usize,
+ tab_width: usize,
+ button_size: usize,
+ icon_size: usize,
+ font: &Rc<LoadedFont>,
+ metrics: RenderMetrics,
+ palette: &ColorPalette,
+ background: LinearRgba,
+ foreground: LinearRgba,
+ active_edge: LinearRgba,
+ accent: LinearRgba,
+ ) -> anyhow::Result<()> {
+ self.filled_rectangle(
+ layers,
+ 1,
+ euclid::rect(visible_left, row_y as f32, visible_width, row_height as f32),
+ background,
+ )
+ .context("window tab background")?;
+
+ if active {
+ self.filled_rectangle(
+ layers,
+ 1,
+ euclid::rect(visible_left, row_y as f32, 1.0, row_height as f32),
+ active_edge,
+ )
+ .context("window tab active left edge")?;
+ self.filled_rectangle(
+ layers,
+ 1,
+ euclid::rect(
+ (visible_left + visible_width - 1.0).max(visible_left),
+ row_y as f32,
+ 1.0,
+ row_height as f32,
+ ),
+ active_edge,
+ )
+ .context("window tab active right edge")?;
+ self.filled_rectangle(
+ layers,
+ 1,
+ euclid::rect(
+ visible_left,
+ row_y as f32 + row_height.saturating_sub(3) as f32,
+ visible_width,
+ 3.0,
+ ),
+ accent,
+ )
+ .context("window tab active indicator")?;
} else {
- Dimension::Cells(0.5)
- };
+ self.filled_rectangle(
+ layers,
+ 1,
+ euclid::rect(
+ (visible_left + visible_width - 1.0).max(visible_left),
+ row_y as f32 + 7.0,
+ 1.0,
+ row_height.saturating_sub(14) as f32,
+ ),
+ active_edge.mul_alpha(0.55),
+ )
+ .context("window tab separator")?;
+ }
- children.push(
- Element::new(&font, ElementContent::Children(left_eles))
- .vertical_align(VerticalAlign::Bottom)
- .colors(bar_colors.clone())
- .padding(BoxDimension {
- left: left_padding,
- right: Dimension::Cells(0.),
- top: Dimension::Cells(0.),
- bottom: Dimension::Cells(0.),
- })
- .zindex(1),
- );
- children.push(
- Element::new(&font, ElementContent::Children(right_eles))
- .colors(bar_colors.clone())
- .float(Float::Right),
- );
+ ui_items.push(UIItem {
+ x: visible_left.max(0.0) as usize,
+ y: row_y,
+ width: visible_width.max(0.0) as usize,
+ height: row_height,
+ item_type: UIItemType::TabBar(TabBarItem::Tab { tab_idx, active }),
+ });
- let content = ElementContent::Children(children);
+ let tab_left = tab_left.max(0.0) as usize;
+ let icon_x = tab_left + WINDOW_TAB_INSET;
+ let icon_y = row_y + (row_height.saturating_sub(icon_size) / 2);
+ if icon_x >= viewport_left && icon_x.saturating_add(icon_size) <= viewport_right {
+ self.paint_fancy_tab_icon(
+ layers,
+ SvgIcon::SquareTerminal,
+ icon_x,
+ icon_y,
+ icon_size,
+ foreground,
+ )?;
+ }
+
+ let close_x = tab_left
+ .saturating_add(tab_width)
+ .saturating_sub(button_size + WINDOW_TAB_BUTTON_GAP);
+ let show_close = self.config.show_close_tab_button_in_tabs && !is_renaming;
+ if show_close
+ && close_x >= viewport_left
+ && close_x.saturating_add(button_size) <= viewport_right
+ {
+ ui_items.push(UIItem {
+ x: close_x,
+ y: row_y + (row_height.saturating_sub(button_size) / 2),
+ width: button_size,
+ height: button_size,
+ item_type: UIItemType::CloseTab(tab_idx),
+ });
+ self.paint_fancy_tab_icon(
+ layers,
+ SvgIcon::X,
+ close_x + (button_size.saturating_sub(icon_size) / 2),
+ icon_y,
+ icon_size,
+ foreground.mul_alpha(0.82),
+ )?;
+ }
- let tabs = Element::new(&font, content)
- .display(DisplayType::Block)
- .item_type(UIItemType::TabBar(TabBarItem::None))
- .min_width(Some(Dimension::Pixels(self.dimensions.pixel_width as f32)))
- .min_height(Some(Dimension::Pixels(tab_bar_height)))
- .vertical_align(VerticalAlign::Bottom)
- .colors(bar_colors);
+ let text_x = icon_x + icon_size + WINDOW_TAB_ICON_GAP;
+ let text_right = if show_close {
+ close_x.saturating_sub(WINDOW_TAB_ICON_GAP)
+ } else {
+ tab_left
+ .saturating_add(tab_width)
+ .saturating_sub(WINDOW_TAB_INSET)
+ }
+ .min(viewport_right);
+ let text_width = text_right.saturating_sub(text_x);
+ let text_y = row_y + (row_height.saturating_sub(metrics.cell_size.height as usize) / 2);
+ if text_x >= viewport_left && text_x < viewport_right {
+ let text_fg = if is_renaming {
+ self.filled_rectangle(
+ layers,
+ 1,
+ euclid::rect(
+ text_x.saturating_sub(3) as f32,
+ text_y as f32,
+ text_width.saturating_add(6) as f32,
+ metrics.cell_size.height as f32,
+ ),
+ palette.selection_bg.to_linear(),
+ )
+ .context("window tab rename selection")?;
+ palette.selection_fg.to_linear()
+ } else {
+ foreground
+ };
+ self.paint_fancy_tab_text(
+ layers,
+ font,
+ &item.title,
+ text_x,
+ text_y,
+ text_width,
+ text_fg,
+ )?;
+ }
+ Ok(())
+ }
- let border = self.get_os_border();
+ #[allow(clippy::too_many_arguments)]
+ fn paint_fancy_tab_bar_overflow(
+ &self,
+ layers: &mut TripleLayerQuadAllocator,
+ row_y: usize,
+ row_height: usize,
+ viewport_left: usize,
+ viewport_width: usize,
+ scroll_offset: f32,
+ max_scroll: f32,
+ background: LinearRgba,
+ divider: LinearRgba,
+ ) -> anyhow::Result<()> {
+ let fade_width = 22usize.min(viewport_width / 3);
+ if fade_width <= 1 {
+ return Ok(());
+ }
- let mut computed = self.compute_element(
- &LayoutContext {
- height: DimensionContext {
- dpi: self.dimensions.dpi as f32,
- pixel_max: self.dimensions.pixel_height as f32,
- pixel_cell: metrics.cell_size.height as f32,
- },
- width: DimensionContext {
- dpi: self.dimensions.dpi as f32,
- pixel_max: self.dimensions.pixel_width as f32,
- pixel_cell: metrics.cell_size.width as f32,
- },
- bounds: euclid::rect(
- border.left.get() as f32,
- 0.,
- self.dimensions.pixel_width as f32 - (border.left + border.right).get() as f32,
- tab_bar_height,
+ if scroll_offset > 0.0 {
+ self.filled_rectangle(
+ layers,
+ 1,
+ euclid::rect(
+ viewport_left as f32,
+ row_y as f32,
+ fade_width as f32,
+ row_height as f32,
),
- metrics: &metrics,
- gl_state: self.render_state.as_ref().unwrap(),
- zindex: 10,
- },
- &tabs,
- )?;
+ background.mul_alpha(0.94),
+ )
+ .context("window tab left overflow shade")?;
+ self.filled_rectangle(
+ layers,
+ 1,
+ euclid::rect(
+ (viewport_left + fade_width.saturating_sub(2)) as f32,
+ row_y as f32,
+ 2.0,
+ row_height as f32,
+ ),
+ divider,
+ )
+ .context("window tab left overflow edge")?;
+ }
- computed.translate(euclid::vec2(
- 0.,
- if self.config.tab_bar_at_bottom {
- self.dimensions.pixel_height as f32
- - (computed.bounds.height() + border.bottom.get() as f32)
- } else {
- border.top.get() as f32
- },
- ));
+ if scroll_offset < max_scroll {
+ let x = viewport_left + viewport_width.saturating_sub(fade_width);
+ self.filled_rectangle(
+ layers,
+ 1,
+ euclid::rect(x as f32, row_y as f32, fade_width as f32, row_height as f32),
+ background.mul_alpha(0.94),
+ )
+ .context("window tab right overflow shade")?;
+ self.filled_rectangle(
+ layers,
+ 1,
+ euclid::rect(x as f32, row_y as f32, 2.0, row_height as f32),
+ divider,
+ )
+ .context("window tab right overflow edge")?;
+ }
- Ok(computed)
+ Ok(())
}
- pub fn paint_fancy_tab_bar(&self) -> anyhow::Result<Vec<UIItem>> {
- let computed = self.fancy_tab_bar.as_ref().ok_or_else(|| {
- anyhow::anyhow!("paint_fancy_tab_bar called but fancy_tab_bar is None")
- })?;
- let ui_items = computed.ui_items();
+ #[allow(clippy::too_many_arguments)]
+ fn paint_fancy_tab_text(
+ &self,
+ layers: &mut TripleLayerQuadAllocator,
+ font: &Rc<LoadedFont>,
+ title: &Line,
+ x: usize,
+ y: usize,
+ width: usize,
+ foreground: LinearRgba,
+ ) -> anyhow::Result<()> {
+ let metrics = RenderMetrics::with_font_metrics(&font.metrics());
+ let cell_width = (metrics.cell_size.width as usize).max(1);
+ let min_width = WINDOW_TAB_MIN_TEXT_COLS * cell_width;
+ if width < min_width {
+ return Ok(());
+ }
+ let mut text = String::new();
+ for cell in title.visible_cells() {
+ text.push_str(cell.str());
+ }
+ self.paint_ui_title_text(layers, font, &metrics, &text, x, y, width, foreground)
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ pub(super) fn paint_ui_title_text(
+ &self,
+ layers: &mut TripleLayerQuadAllocator,
+ font: &Rc<LoadedFont>,
+ metrics: &RenderMetrics,
+ text: &str,
+ x: usize,
+ y: usize,
+ width: usize,
+ foreground: LinearRgba,
+ ) -> anyhow::Result<()> {
+ if text.is_empty() || width == 0 {
+ return Ok(());
+ }
+
+ let Some(window) = self.window.as_ref().cloned() else {
+ return Ok(());
+ };
let gl_state = self.render_state.as_ref().unwrap();
- self.render_element(&computed, gl_state, None)?;
+ let infos = font.shape(
+ text,
+ move || window.notify(TermWindowNotif::InvalidateShapeCache),
+ BlockKey::filter_out_synthetic,
+ None,
+ Direction::LeftToRight,
+ None,
+ None,
+ )?;
+ let mut glyph_cache = gl_state.glyph_cache.borrow_mut();
+ let left_offset = self.dimensions.pixel_width as f32 / -2.0;
+ let top_offset = self.dimensions.pixel_height as f32 / -2.0;
+ let baseline = metrics.cell_size.height as f32 + metrics.descender.get() as f32;
+ let max_x = x as f32 + width as f32;
+ let mut x_pos = x as f32;
+ let y = y as f32;
+ let style = font.style();
- Ok(ui_items)
+ for info in infos {
+ let cell_start = &text[info.cluster as usize..];
+ let mut iter = Graphemes::new(cell_start).peekable();
+ let Some(grapheme) = iter.next() else {
+ continue;
+ };
+
+ if let Some(key) = BlockKey::from_str(grapheme) {
+ let advance = metrics.cell_size.width as f32;
+ if x_pos + advance > max_x {
+ break;
+ }
+ let sprite = glyph_cache.cached_block(key, metrics)?;
+ let mut quad = layers.allocate(2)?;
+ quad.set_position(
+ x_pos + left_offset,
+ y + top_offset,
+ x_pos + left_offset + advance,
+ y + top_offset + metrics.cell_size.height as f32,
+ );
+ quad.set_texture(sprite.texture_coords());
+ quad.set_fg_color(foreground);
+ quad.set_alt_color_and_mix_value(foreground, 0.0);
+ quad.set_hsv(None);
+ x_pos += advance;
+ continue;
+ }
+
+ let next_grapheme = iter.peek().copied();
+ let followed_by_space = next_grapheme == Some(" ");
+ let num_cells = grapheme_column_width(grapheme, None).max(1) as u8;
+ let glyph = glyph_cache.cached_glyph(
+ &info,
+ &style,
+ followed_by_space,
+ font,
+ metrics,
+ num_cells,
+ )?;
+ let advance = glyph.x_advance.get() as f32;
+ if x_pos + advance > max_x {
+ break;
+ }
+
+ if let Some(texture) = glyph.texture.as_ref() {
+ let glyph_x = x_pos + (glyph.x_offset + glyph.bearing_x).get() as f32;
+ let glyph_y = y - (glyph.y_offset + glyph.bearing_y).get() as f32 + baseline;
+ let glyph_width = texture.coords.size.width as f32 * glyph.scale as f32;
+ let glyph_height = texture.coords.size.height as f32 * glyph.scale as f32;
+ if glyph_x + glyph_width > max_x {
+ break;
+ }
+ let mut quad = layers.allocate(2)?;
+ quad.set_position(
+ glyph_x + left_offset,
+ glyph_y + top_offset,
+ glyph_x + left_offset + glyph_width,
+ glyph_y + top_offset + glyph_height,
+ );
+ quad.set_texture(texture.texture_coords());
+ quad.set_fg_color(foreground);
+ quad.set_alt_color_and_mix_value(foreground, 0.0);
+ quad.set_has_color(glyph.has_color);
+ quad.set_hsv(None);
+ }
+
+ x_pos += advance;
+ }
+
+ Ok(())
+ }
+
+ fn paint_fancy_tab_icon(
+ &self,
+ layers: &mut TripleLayerQuadAllocator,
+ icon: SvgIcon,
+ x: usize,
+ y: usize,
+ size: usize,
+ color: LinearRgba,
+ ) -> anyhow::Result<()> {
+ let left_offset = self.dimensions.pixel_width as f32 / 2.0;
+ let top_offset = self.dimensions.pixel_height as f32 / 2.0;
+ let gl_state = self.render_state.as_ref().unwrap();
+ let sprite = gl_state
+ .glyph_cache
+ .borrow_mut()
+ .cached_svg_icon(icon, size)?
+ .texture_coords();
+
+ let mut quad = layers.allocate(2)?;
+ quad.set_position(
+ x as f32 - left_offset,
+ y as f32 - top_offset,
+ x as f32 + size as f32 - left_offset,
+ y as f32 + size as f32 - top_offset,
+ );
+ quad.set_texture(sprite);
+ quad.set_fg_color(color);
+ quad.set_alt_color_and_mix_value(color, 0.0);
+ quad.set_hsv(None);
+ quad.set_grayscale();
+
+ Ok(())
}
}
-fn make_x_button(
- font: &Rc<LoadedFont>,
- metrics: &RenderMetrics,
- colors: &TabBarColors,
- tab_idx: usize,
- active: bool,
-) -> Element {
- Element::new(
- &font,
- ElementContent::Poly {
- line_width: metrics.underline_height.max(2),
- poly: SizedPoly {
- poly: X_BUTTON,
- width: Dimension::Pixels(metrics.cell_size.height as f32 / 2.),
- height: Dimension::Pixels(metrics.cell_size.height as f32 / 2.),
- },
- },
- )
- // Ensure that we draw our background over the
- // top of the rest of the tab contents
- .zindex(1)
- .vertical_align(VerticalAlign::Middle)
- .float(Float::Right)
- .item_type(UIItemType::CloseTab(tab_idx))
- .hover_colors({
- let inactive_tab_hover = colors.inactive_tab_hover();
- let active_tab = colors.active_tab();
-
- Some(ElementColors {
- border: BorderColor::default(),
- bg: (if active {
- inactive_tab_hover.bg_color
- } else {
- active_tab.bg_color
- })
- .to_linear()
- .into(),
- text: (if active {
- inactive_tab_hover.fg_color
- } else {
- active_tab.fg_color
- })
- .to_linear()
- .into(),
- })
- })
- .padding(BoxDimension {
- left: Dimension::Cells(0.25),
- right: Dimension::Cells(0.25),
- top: Dimension::Cells(0.25),
- bottom: Dimension::Cells(0.25),
- })
- .margin(BoxDimension {
- left: Dimension::Cells(0.5),
- right: Dimension::Cells(0.),
- top: Dimension::Cells(0.),
- bottom: Dimension::Cells(0.),
- })
+fn fancy_tab_icon_size(metrics: &RenderMetrics, tab_bar_height: f32) -> f32 {
+ let from_bar = (tab_bar_height - 14.0).max(1.0);
+ let from_font = metrics.cell_size.height as f32 * 0.95;
+ from_bar.min(from_font).clamp(18.0, 24.0).floor()
}
diff --git a/wezterm-gui/src/termwindow/render/mod.rs b/wezterm-gui/src/termwindow/render/mod.rs
index dccdd632..4fe09887 100644
--- a/wezterm-gui/src/termwindow/render/mod.rs
+++ b/wezterm-gui/src/termwindow/render/mod.rs
@@ -29,7 +29,7 @@ use termwiz::hyperlink::Hyperlink;
use termwiz::surface::{CursorShape, CursorVisibility, SequenceNo};
use wezterm_font::shaper::PresentationWidth;
use wezterm_font::units::{IntPixelLength, PixelLength};
-use wezterm_font::{ClearShapeCache, GlyphInfo, LoadedFont};
+use wezterm_font::{ClearShapeCache, FontConfiguration, GlyphInfo, LoadedFont};
use wezterm_term::color::{ColorAttribute, ColorPalette};
use wezterm_term::{CellAttributes, Line, StableRowIndex};
use window::color::LinearRgba;
@@ -62,6 +62,7 @@ pub struct LineQuadCacheKey {
pub composing: Option<String>,
pub selection: Range<usize>,
pub shape_hash: [u8; 16],
+ pub font_identity: u64,
pub top_pixel_y: NotNan<f32>,
pub left_pixel_x: NotNan<f32>,
pub phys_line_idx: usize,
@@ -90,6 +91,11 @@ pub struct LineToElementParams<'a> {
pub window_is_transparent: bool,
pub reverse_video: bool,
pub shape_key: &'a Option<LineToEleShapeCacheKey>,
+ pub font: Option<&'a Rc<LoadedFont>>,
+ pub style: Option<&'a TextStyle>,
+ pub font_config: Option<&'a Rc<FontConfiguration>>,
+ pub render_metrics: RenderMetrics,
+ pub font_identity: u64,
}
#[derive(Debug, Hash, PartialEq, Eq, Clone)]
@@ -97,6 +103,7 @@ pub struct LineToEleShapeCacheKey {
pub shape_hash: [u8; 16],
pub composing: Option<(usize, String)>,
pub shape_generation: usize,
+ pub font_identity: u64,
}
pub struct LineToElementShapeItem {
@@ -166,6 +173,8 @@ pub struct RenderScreenLineParams<'a> {
pub use_pixel_positioning: bool,
pub render_metrics: RenderMetrics,
+ pub font_config: Option<Rc<FontConfiguration>>,
+ pub font_identity: u64,
pub shape_key: Option<LineToEleShapeCacheKey>,
pub password_input: bool,
}
@@ -354,7 +363,8 @@ impl crate::TermWindow {
.config
.window_padding
.left
- .evaluate_as_pixels(h_context);
+ .evaluate_as_pixels(h_context)
+ + self.workspace_sidebar_width() as f32;
let padding_right = self.config.window_padding.right;
let padding_top = self.config.window_padding.top.evaluate_as_pixels(v_context);
let padding_bottom = self
@@ -399,13 +409,23 @@ impl crate::TermWindow {
style: &TextStyle,
attrs: &CellAttributes,
font: Option<&Rc<LoadedFont>>,
+ font_config: Option<&Rc<FontConfiguration>>,
gl_state: &RenderState,
metrics: &RenderMetrics,
+ font_identity: u64,
) -> anyhow::Result<Rc<CachedGlyph>> {
let fa_lock = "\u{f023}";
let line = Line::from_text(fa_lock, attrs, 0, None);
let cluster = line.cluster(None);
- let shape_info = self.cached_cluster_shape(style, &cluster[0], gl_state, font, metrics)?;
+ let shape_info = self.cached_cluster_shape(
+ style,
+ &cluster[0],
+ gl_state,
+ font,
+ font_config,
+ metrics,
+ font_identity,
+ )?;
Ok(Rc::clone(&shape_info[0].glyph))
}
@@ -784,10 +804,13 @@ impl crate::TermWindow {
cluster: &CellCluster,
gl_state: &RenderState,
font: Option<&Rc<LoadedFont>>,
+ font_config: Option<&Rc<FontConfiguration>>,
metrics: &RenderMetrics,
+ font_identity: u64,
) -> anyhow::Result<Rc<Vec<ShapedInfo>>> {
let shape_resolve_start = Instant::now();
let key = BorrowedShapeCacheKey {
+ font_identity,
style,
text: &cluster.text,
};
@@ -797,7 +820,7 @@ impl crate::TermWindow {
None => {
let font = match font {
Some(f) => Rc::clone(f),
- None => self.fonts.resolve_font(style)?,
+ None => font_config.unwrap_or(&self.fonts).resolve_font(style)?,
};
let window = self.window.as_ref().unwrap().clone();
diff --git a/wezterm-gui/src/termwindow/render/paint.rs b/wezterm-gui/src/termwindow/render/paint.rs
index 5218d2d7..7bd9516f 100644
--- a/wezterm-gui/src/termwindow/render/paint.rs
+++ b/wezterm-gui/src/termwindow/render/paint.rs
@@ -14,6 +14,43 @@ pub enum AllowImage {
}
impl crate::TermWindow {
+ fn damp_scroll_value(current: f32, target: f32) -> (f32, bool) {
+ let delta = target - current;
+ if delta.abs() <= 0.75 {
+ (target, false)
+ } else {
+ (current + delta * 0.38, true)
+ }
+ }
+
+ fn advance_tab_scroll_animation(&mut self, now: Instant) {
+ let mut animating = false;
+ let (next_window_scroll, window_animating) =
+ Self::damp_scroll_value(self.tab_bar_scroll_offset, self.tab_bar_scroll_target);
+ if (next_window_scroll - self.tab_bar_scroll_offset).abs() > f32::EPSILON {
+ self.tab_bar_scroll_offset = next_window_scroll;
+ self.invalidate_fancy_tab_bar();
+ }
+ animating |= window_animating;
+
+ for (pane_id, target) in self.pane_nav_tab_scroll_targets.clone() {
+ let current = self
+ .pane_nav_tab_scroll_offsets
+ .get(&pane_id)
+ .copied()
+ .unwrap_or(0.0);
+ let (next, pane_animating) = Self::damp_scroll_value(current, target);
+ if (next - current).abs() > f32::EPSILON {
+ self.pane_nav_tab_scroll_offsets.insert(pane_id, next);
+ }
+ animating |= pane_animating;
+ }
+
+ if animating {
+ self.update_next_frame_time(Some(now + Duration::from_millis(16)));
+ }
+ }
+
pub fn paint_impl(&mut self, frame: &mut RenderFrame) {
self.num_frames += 1;
// If nothing on screen needs animating, then we can avoid
@@ -23,6 +60,7 @@ impl crate::TermWindow {
self.allow_images = AllowImage::Yes;
let start = Instant::now();
+ self.advance_tab_scroll_animation(start);
{
let diff = start.duration_since(self.last_fps_check_time);
@@ -169,6 +207,7 @@ impl crate::TermWindow {
// Clear out UI item positions; we'll rebuild these as we render
self.ui_items.clear();
+ self.sync_pane_font_sizes();
let panes = self.get_panes_to_render();
let focused = self.focused.is_some();
let window_is_transparent =
@@ -265,6 +304,9 @@ impl crate::TermWindow {
}
}
+ self.paint_workspace_sidebar(&mut layers)
+ .context("paint_workspace_sidebar")?;
+
if self.show_tab_bar {
self.paint_tab_bar(&mut layers).context("paint_tab_bar")?;
}
diff --git a/wezterm-gui/src/termwindow/render/pane.rs b/wezterm-gui/src/termwindow/render/pane.rs
index da273cc6..93b815ff 100644
--- a/wezterm-gui/src/termwindow/render/pane.rs
+++ b/wezterm-gui/src/termwindow/render/pane.rs
@@ -1,11 +1,20 @@
-use crate::quad::{HeapQuadAllocator, QuadTrait, TripleLayerQuadAllocator};
+use crate::quad::{
+ HeapQuadAllocator, QuadTrait, TripleLayerQuadAllocator, TripleLayerQuadAllocatorTrait,
+};
use crate::selection::SelectionRange;
use crate::termwindow::box_model::*;
use crate::termwindow::render::{
same_hyperlink, CursorProperties, LineQuadCacheKey, LineQuadCacheValue, LineToEleShapeCacheKey,
RenderScreenLineParams,
};
-use crate::termwindow::{ScrollHit, UIItem, UIItemType};
+use crate::termwindow::ui::icons::SvgIcon;
+use crate::termwindow::ui::pane_nav_bar_height_for_metrics;
+use crate::termwindow::ui::tokens::{
+ PANE_NAV_BUTTON_GAP, PANE_NAV_ICON_GAP, PANE_NAV_INSET, PANE_NAV_TAB_MAX_WIDTH,
+ PANE_NAV_TAB_MIN_WIDTH, PANE_NAV_TAB_RADIUS,
+};
+use crate::termwindow::{PaneNavAction, ScrollHit, UIItem, UIItemType};
+use crate::utilsprites::RenderMetrics;
use ::window::bitmaps::TextureRect;
use ::window::DeadKeyStatus;
use anyhow::Context;
@@ -13,14 +22,450 @@ use config::VisualBellTarget;
use mux::pane::{PaneId, WithPaneLines};
use mux::renderable::{RenderableDimensions, StableCursorPosition};
use mux::tab::PositionedPane;
+use mux::Mux;
use ordered_float::NotNan;
+use std::rc::Rc;
use std::time::Instant;
use wezterm_dynamic::Value;
+use wezterm_font::{FontConfiguration, LoadedFont};
use wezterm_term::color::{ColorAttribute, ColorPalette};
use wezterm_term::{Line, StableRowIndex};
use window::color::LinearRgba;
impl crate::TermWindow {
+ fn pane_nav_bar_height(&self, pos: &PositionedPane) -> usize {
+ pane_nav_bar_height_for_metrics(self.render_metrics).min(
+ pos.pixel_height
+ .saturating_sub(self.render_metrics.cell_size.height.max(1) as usize),
+ )
+ }
+
+ fn pane_content_origin(&self, pos: &PositionedPane) -> anyhow::Result<(f32, f32)> {
+ let tab_bar_height = if self.show_tab_bar {
+ self.tab_bar_pixel_height()
+ .context("tab_bar_pixel_height")?
+ } else {
+ 0.
+ };
+ let top_bar_height = if self.config.tab_bar_at_bottom {
+ 0.0
+ } else {
+ tab_bar_height
+ };
+ let border = self.get_os_border();
+ let (padding_left, _) = self.padding_left_top();
+ Ok((
+ padding_left
+ + border.left.get() as f32
+ + (pos.left as f32 * self.render_metrics.cell_size.width as f32),
+ top_bar_height
+ + border.top.get() as f32
+ + (pos.top as f32 * self.render_metrics.cell_size.height as f32),
+ ))
+ }
+
+ fn paint_pane_nav_bar(
+ &mut self,
+ pos: &PositionedPane,
+ layers: &mut TripleLayerQuadAllocator,
+ palette: &ColorPalette,
+ ) -> anyhow::Result<usize> {
+ let nav_height = self.pane_nav_bar_height(pos);
+ if nav_height == 0 {
+ return Ok(0);
+ }
+
+ let (pane_x, pane_y) = self.pane_content_origin(pos)?;
+ let pane_width = pos.width as f32 * self.render_metrics.cell_size.width as f32;
+ if pane_width <= 0.0 {
+ return Ok(0);
+ }
+
+ let background = palette
+ .resolve_bg(ColorAttribute::Default)
+ .to_linear()
+ .mul_alpha(self.config.window_background_opacity);
+ let foreground = palette.foreground.to_linear();
+ let nav_bg = background;
+ let divider = foreground.mul_alpha(0.08);
+ let muted_fg = foreground.mul_alpha(0.66);
+ let tab_bg = background;
+ let tab_fg = if pos.is_active { foreground } else { muted_fg };
+
+ self.filled_rectangle(
+ layers,
+ 1,
+ euclid::rect(pane_x, pane_y, pane_width, nav_height as f32),
+ nav_bg,
+ )
+ .context("pane nav background")?;
+ self.filled_rectangle(
+ layers,
+ 1,
+ euclid::rect(
+ pane_x,
+ pane_y + nav_height.saturating_sub(1) as f32,
+ pane_width,
+ 1.0,
+ ),
+ divider,
+ )
+ .context("pane nav divider")?;
+ self.ui_items.push(UIItem {
+ x: pane_x.max(0.0) as usize,
+ y: pane_y.max(0.0) as usize,
+ width: pane_width.max(0.0) as usize,
+ height: nav_height,
+ item_type: UIItemType::PaneNav {
+ pane_id: pos.pane.pane_id(),
+ pane_index: pos.index,
+ action: PaneNavAction::Background,
+ },
+ });
+
+ let icon_size = nav_height.saturating_sub(PANE_NAV_INSET * 2).clamp(20, 24);
+ let button_size = (icon_size + 10)
+ .min(nav_height.saturating_sub(4))
+ .max(icon_size);
+ let button_y = pane_y as usize + (nav_height.saturating_sub(button_size) / 2);
+ let mut button_x = (pane_x + pane_width) as usize;
+ for (icon, action) in [
+ (SvgIcon::SplitVertical, PaneNavAction::SplitDown),
+ (SvgIcon::SplitHorizontal, PaneNavAction::SplitRight),
+ ] {
+ button_x = button_x.saturating_sub(button_size + PANE_NAV_BUTTON_GAP);
+ self.paint_pane_nav_icon_button(
+ layers,
+ icon,
+ button_x,
+ button_y,
+ button_size,
+ icon_size,
+ muted_fg,
+ pos,
+ action,
+ )?;
+ }
+
+ let tabs = Mux::get().pane_stack_tabs(pos.pane.pane_id());
+ let tab_start = pane_x as usize + PANE_NAV_INSET;
+ let tab_width = PANE_NAV_TAB_MAX_WIDTH.max(PANE_NAV_TAB_MIN_WIDTH);
+ let tab_step = tab_width + PANE_NAV_BUTTON_GAP;
+ let total_tab_width = tabs.len().saturating_mul(tab_width).saturating_add(
+ tabs.len()
+ .saturating_sub(1)
+ .saturating_mul(PANE_NAV_BUTTON_GAP),
+ );
+ let max_tab_right = button_x.saturating_sub(PANE_NAV_INSET);
+ let viewport_width = max_tab_right.saturating_sub(tab_start);
+ let max_scroll = total_tab_width.saturating_sub(viewport_width) as f32;
+ let scroll_offset = self
+ .pane_nav_tab_scroll_offsets
+ .get(&pos.pane.pane_id())
+ .copied()
+ .unwrap_or(0.0)
+ .clamp(0.0, max_scroll.max(0.0));
+ let tab_height = button_size;
+ let tab_y = button_y;
+ for (idx, tab) in tabs.into_iter().enumerate() {
+ if tab_width <= icon_size + PANE_NAV_ICON_GAP + button_size || viewport_width == 0 {
+ break;
+ }
+
+ let virtual_x = idx.saturating_mul(tab_step) as f32;
+ let tab_left = tab_start as f32 + virtual_x - scroll_offset;
+ let tab_right = tab_left + tab_width as f32;
+ if tab_right <= tab_start as f32 || tab_left >= max_tab_right as f32 {
+ continue;
+ }
+
+ let visible_left = tab_left.max(tab_start as f32);
+ let visible_right = tab_right.min(max_tab_right as f32);
+ let visible_width = (visible_right - visible_left).max(0.0);
+ if visible_width <= 1.0 {
+ continue;
+ }
+
+ let visible_active_tab = tab.is_active && pos.is_active;
+ let is_renaming_tab = self.is_renaming_pane_nav_tab(tab.pane_id);
+ let this_tab_bg = tab_bg;
+ let this_tab_fg = if visible_active_tab { tab_fg } else { muted_fg };
+ let active_edge = foreground.mul_alpha(0.20);
+ self.fill_rounded_rectangle(
+ layers,
+ 1,
+ euclid::rect(visible_left, tab_y as f32, visible_width, tab_height as f32),
+ this_tab_bg,
+ PANE_NAV_TAB_RADIUS,
+ )
+ .context("pane nav tab")?;
+ if visible_active_tab {
+ self.filled_rectangle(
+ layers,
+ 1,
+ euclid::rect(
+ visible_left,
+ tab_y as f32 + (tab_height as f32 - 3.0).max(0.0),
+ visible_width,
+ 3.0,
+ ),
+ palette.selection_bg.to_linear(),
+ )
+ .context("pane nav active tab accent")?;
+ self.filled_rectangle(
+ layers,
+ 1,
+ euclid::rect(visible_left, tab_y as f32, 1.0, tab_height as f32),
+ active_edge,
+ )
+ .context("pane nav active tab left edge")?;
+ self.filled_rectangle(
+ layers,
+ 1,
+ euclid::rect(
+ (visible_left + visible_width - 1.0).max(visible_left),
+ tab_y as f32,
+ 1.0,
+ tab_height as f32,
+ ),
+ active_edge,
+ )
+ .context("pane nav active tab right edge")?;
+ }
+ self.ui_items.push(UIItem {
+ x: visible_left.max(0.0) as usize,
+ y: tab_y,
+ width: visible_width.max(0.0) as usize,
+ height: tab_height,
+ item_type: UIItemType::PaneNav {
+ pane_id: pos.pane.pane_id(),
+ pane_index: pos.index,
+ action: PaneNavAction::Activate(tab.pane_id),
+ },
+ });
+
+ let draw_tab_x = tab_left.max(0.0) as usize;
+ let title_icon_x = draw_tab_x + PANE_NAV_INSET;
+ let title_icon_y = tab_y + ((tab_height.saturating_sub(icon_size)) / 2);
+ if title_icon_x >= tab_start && title_icon_x.saturating_add(icon_size) <= max_tab_right
+ {
+ self.paint_pane_nav_icon(
+ layers,
+ SvgIcon::SquareTerminal,
+ title_icon_x,
+ title_icon_y,
+ icon_size,
+ this_tab_fg,
+ )?;
+ }
+
+ let close_x = draw_tab_x + tab_width - button_size;
+ if !is_renaming_tab {
+ if close_x >= tab_start && close_x.saturating_add(button_size) <= max_tab_right {
+ self.ui_items.push(UIItem {
+ x: close_x,
+ y: tab_y,
+ width: button_size,
+ height: button_size,
+ item_type: UIItemType::PaneNav {
+ pane_id: pos.pane.pane_id(),
+ pane_index: pos.index,
+ action: PaneNavAction::Close(tab.pane_id),
+ },
+ });
+ self.paint_pane_nav_icon(
+ layers,
+ SvgIcon::X,
+ close_x + ((button_size.saturating_sub(icon_size)) / 2),
+ title_icon_y,
+ icon_size,
+ muted_fg,
+ )?;
+ }
+ }
+
+ let ui_font = self.fonts.title_font().context("pane nav title font")?;
+ let ui_metrics = RenderMetrics::with_font_metrics(&ui_font.metrics());
+ let text_x = title_icon_x + icon_size + PANE_NAV_ICON_GAP;
+ let text_right = if is_renaming_tab {
+ draw_tab_x + tab_width - PANE_NAV_INSET
+ } else {
+ close_x
+ };
+ let text_width = text_right
+ .min(max_tab_right)
+ .saturating_sub(text_x + PANE_NAV_ICON_GAP);
+ let text_y =
+ tab_y + ((tab_height.saturating_sub(ui_metrics.cell_size.height as usize)) / 2);
+ let title = self.pane_nav_tab_title(tab.pane_id, &tab.title);
+ if text_x >= tab_start && text_x < max_tab_right && text_width > 0 {
+ let text_fg = if is_renaming_tab {
+ self.fill_rounded_rectangle(
+ layers,
+ 1,
+ euclid::rect(
+ text_x.saturating_sub(3) as f32,
+ text_y as f32,
+ text_width.saturating_add(6) as f32,
+ ui_metrics.cell_size.height as f32,
+ ),
+ palette.selection_bg.to_linear(),
+ 4.0,
+ )
+ .context("pane nav rename selection")?;
+ palette.selection_fg.to_linear()
+ } else {
+ this_tab_fg
+ };
+ self.paint_pane_nav_text(
+ layers, &ui_font, ui_metrics, &title, text_x, text_y, text_width, text_fg,
+ )?;
+ }
+ }
+
+ let fade_width = 18.0_f32.min(viewport_width as f32 / 3.0);
+ if fade_width > 1.0 && scroll_offset > 0.0 {
+ self.filled_rectangle(
+ layers,
+ 1,
+ euclid::rect(tab_start as f32, pane_y, fade_width, nav_height as f32),
+ nav_bg.mul_alpha(0.94),
+ )
+ .context("pane nav left overflow shade")?;
+ self.filled_rectangle(
+ layers,
+ 1,
+ euclid::rect(
+ tab_start as f32 + fade_width - 2.0,
+ pane_y,
+ 2.0,
+ nav_height as f32,
+ ),
+ divider,
+ )
+ .context("pane nav left overflow edge")?;
+ }
+ if fade_width > 1.0 && scroll_offset < max_scroll {
+ self.filled_rectangle(
+ layers,
+ 1,
+ euclid::rect(
+ max_tab_right as f32 - fade_width,
+ pane_y,
+ fade_width,
+ nav_height as f32,
+ ),
+ nav_bg.mul_alpha(0.94),
+ )
+ .context("pane nav right overflow shade")?;
+ self.filled_rectangle(
+ layers,
+ 1,
+ euclid::rect(
+ max_tab_right as f32 - fade_width,
+ pane_y,
+ 2.0,
+ nav_height as f32,
+ ),
+ divider,
+ )
+ .context("pane nav right overflow edge")?;
+ }
+
+ Ok(nav_height)
+ }
+
+ fn paint_pane_nav_icon_button(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator,
+ icon: SvgIcon,
+ x: usize,
+ y: usize,
+ button_size: usize,
+ icon_size: usize,
+ color: LinearRgba,
+ pos: &PositionedPane,
+ action: PaneNavAction,
+ ) -> anyhow::Result<()> {
+ self.ui_items.push(UIItem {
+ x,
+ y,
+ width: button_size,
+ height: button_size,
+ item_type: UIItemType::PaneNav {
+ pane_id: pos.pane.pane_id(),
+ pane_index: pos.index,
+ action,
+ },
+ });
+
+ self.paint_pane_nav_icon(
+ layers,
+ icon,
+ x + ((button_size.saturating_sub(icon_size)) / 2),
+ y + ((button_size.saturating_sub(icon_size)) / 2),
+ icon_size,
+ color,
+ )
+ }
+
+ fn paint_pane_nav_text(
+ &self,
+ layers: &mut TripleLayerQuadAllocator,
+ font: &Rc<LoadedFont>,
+ metrics: RenderMetrics,
+ text: &str,
+ x: usize,
+ y: usize,
+ width: usize,
+ foreground: LinearRgba,
+ ) -> anyhow::Result<()> {
+ if width == 0 {
+ return Ok(());
+ }
+
+ let cell_width = (metrics.cell_size.width as usize).max(1);
+ if width < cell_width {
+ return Ok(());
+ }
+
+ self.paint_ui_title_text(layers, font, &metrics, text, x, y, width, foreground)
+ }
+
+ fn paint_pane_nav_icon(
+ &self,
+ layers: &mut TripleLayerQuadAllocator,
+ icon: SvgIcon,
+ x: usize,
+ y: usize,
+ size: usize,
+ color: LinearRgba,
+ ) -> anyhow::Result<()> {
+ let left_offset = self.dimensions.pixel_width as f32 / 2.0;
+ let top_offset = self.dimensions.pixel_height as f32 / 2.0;
+ let gl_state = self.render_state.as_ref().unwrap();
+ let sprite = gl_state
+ .glyph_cache
+ .borrow_mut()
+ .cached_svg_icon(icon, size)?
+ .texture_coords();
+
+ let mut quad = layers.allocate(2)?;
+ quad.set_position(
+ x as f32 - left_offset,
+ y as f32 - top_offset,
+ x as f32 + size as f32 - left_offset,
+ y as f32 + size as f32 - top_offset,
+ );
+ quad.set_texture(sprite);
+ quad.set_fg_color(color);
+ quad.set_alt_color_and_mix_value(color, 0.0);
+ quad.set_hsv(None);
+ quad.set_grayscale();
+
+ Ok(())
+ }
+
fn paint_pane_box_model(&mut self, pos: &PositionedPane) -> anyhow::Result<()> {
let computed = self.build_pane(pos)?;
let mut ui_items = computed.ui_items();
@@ -85,6 +530,16 @@ impl crate::TermWindow {
let pane_id = pos.pane.pane_id();
let current_viewport = self.get_viewport(pane_id);
let dims = pos.pane.get_dimensions();
+ let global_render_metrics = self.render_metrics;
+ let pane_font_scale = self.pane_font_scale(pane_id);
+ let (pane_font_config, pane_render_metrics) =
+ if pane_font_scale.to_bits() == self.fonts.get_font_scale().to_bits() {
+ (None, global_render_metrics)
+ } else {
+ let (fonts, metrics) = self.pane_font_resources(pane_font_scale)?;
+ (Some(fonts), metrics)
+ };
+ let render_dims = dims;
let gl_state = self.render_state.as_ref().unwrap();
@@ -221,6 +676,10 @@ impl crate::TermWindow {
}
}
+ let pane_nav_height = self
+ .paint_pane_nav_bar(pos, layers, &palette)
+ .context("paint_pane_nav_bar")?;
+
// TODO: we only have a single scrollbar in a single position.
// We only update it for the active pane, but we should probably
// do a per-pane scrollbar. That will require more extensive
@@ -304,8 +763,11 @@ impl crate::TermWindow {
{
let stable_range = match current_viewport {
- Some(top) => top..top + dims.viewport_rows as StableRowIndex,
- None => dims.physical_top..dims.physical_top + dims.viewport_rows as StableRowIndex,
+ Some(top) => top..top + render_dims.viewport_rows as StableRowIndex,
+ None => {
+ dims.physical_top
+ ..dims.physical_top + render_dims.viewport_rows as StableRowIndex
+ }
};
pos.pane
@@ -318,6 +780,9 @@ impl crate::TermWindow {
dims: RenderableDimensions,
top_pixel_y: f32,
left_pixel_x: f32,
+ render_metrics: RenderMetrics,
+ font_config: Option<Rc<FontConfiguration>>,
+ font_identity: u64,
pos: &'a PositionedPane,
pane_id: PaneId,
cursor: &'a StableCursorPosition,
@@ -339,15 +804,21 @@ impl crate::TermWindow {
let left_pixel_x = padding_left
+ border.left.get() as f32
- + (pos.left as f32 * self.render_metrics.cell_size.width as f32);
+ + (pos.left as f32 * global_render_metrics.cell_size.width as f32);
+ let pane_top_pixel_y = top_pixel_y
+ + (pos.top as f32 * global_render_metrics.cell_size.height as f32)
+ + pane_nav_height as f32;
let mut render = LineRender {
term_window: self,
selrange,
rectangular,
- dims,
- top_pixel_y,
+ dims: render_dims,
+ top_pixel_y: pane_top_pixel_y,
left_pixel_x,
+ render_metrics: pane_render_metrics,
+ font_config: pane_font_config,
+ font_identity: pane_font_scale.to_bits(),
pos,
pane_id,
cursor: &cursor,
@@ -430,13 +901,13 @@ impl crate::TermWindow {
config_generation: self.term_window.config.generation(),
shape_generation: self.term_window.shape_generation,
quad_generation: self.term_window.quad_generation,
+ font_identity: self.font_identity,
composing: composing.clone(),
selection: selrange.clone(),
cursor,
shape_hash,
top_pixel_y: NotNan::new(self.top_pixel_y).unwrap()
- + (line_idx + self.pos.top) as f32
- * self.term_window.render_metrics.cell_size.height as f32,
+ + line_idx as f32 * self.render_metrics.cell_size.height as f32,
left_pixel_x: NotNan::new(self.left_pixel_x).unwrap(),
phys_line_idx: line_idx,
reverse_video: self.dims.reverse_video,
@@ -473,6 +944,7 @@ impl crate::TermWindow {
let shape_key = LineToEleShapeCacheKey {
shape_hash,
shape_generation: quad_key.shape_generation,
+ font_identity: self.font_identity,
composing: if self.cursor.y == stable_row && self.pos.is_active {
if let DeadKeyStatus::Composing(composing) =
&self.term_window.dead_key_status
@@ -493,7 +965,7 @@ impl crate::TermWindow {
top_pixel_y: *quad_key.top_pixel_y,
left_pixel_x: self.left_pixel_x,
pixel_width: self.dims.cols as f32
- * self.term_window.render_metrics.cell_size.width as f32,
+ * self.render_metrics.cell_size.width as f32,
stable_line_idx: Some(stable_row),
line: &line,
selection: selrange.clone(),
@@ -520,7 +992,9 @@ impl crate::TermWindow {
.term_window
.config
.experimental_pixel_positioning,
- render_metrics: self.term_window.render_metrics,
+ render_metrics: self.render_metrics,
+ font_config: self.font_config.clone(),
+ font_identity: self.font_identity,
shape_key: Some(shape_key),
password_input,
},
diff --git a/wezterm-gui/src/termwindow/render/screen_line.rs b/wezterm-gui/src/termwindow/render/screen_line.rs
index ccc320ea..3bf75aa8 100644
--- a/wezterm-gui/src/termwindow/render/screen_line.rs
+++ b/wezterm-gui/src/termwindow/render/screen_line.rs
@@ -148,6 +148,11 @@ impl crate::TermWindow {
window_is_transparent: params.window_is_transparent,
reverse_video: params.dims.reverse_video,
shape_key: &params.shape_key,
+ font: params.font.as_ref(),
+ style: params.style,
+ font_config: params.font_config.as_ref(),
+ render_metrics: params.render_metrics,
+ font_identity: params.font_identity,
};
let (shaped, invalidate_on_hover) = self.build_line_element_shape(params)?;
@@ -372,8 +377,10 @@ impl crate::TermWindow {
&TextStyle::default(),
&attrs,
params.font.as_ref(),
+ params.font_config.as_ref(),
gl_state,
&params.render_metrics,
+ params.font_identity,
)
.context("resolve_lock_glyph")?;
@@ -750,7 +757,12 @@ impl crate::TermWindow {
if !matches!(last_style.as_ref(), Some(ClusterStyleCache{attrs,..}) if *attrs == &cluster.attrs)
{
let attrs = &cluster.attrs;
- let style = self.fonts.match_style(params.config, attrs);
+ let style = params.style.unwrap_or_else(|| {
+ params
+ .font_config
+ .unwrap_or(&self.fonts)
+ .match_style(params.config, attrs)
+ });
let hyperlink = attrs.hyperlink();
let is_highlited_hyperlink =
same_hyperlink(hyperlink, self.current_highlight.as_ref());
@@ -766,7 +778,7 @@ impl crate::TermWindow {
attrs.strikethrough(),
attrs.underline(),
attrs.overline(),
- &self.render_metrics,
+ &params.render_metrics,
)?
.texture_coords();
let bg_is_default = attrs.background() == ColorAttribute::Default;
@@ -859,8 +871,10 @@ impl crate::TermWindow {
style_params.style,
&cluster,
&gl_state,
- None,
- &self.render_metrics,
+ params.font,
+ params.font_config,
+ &params.render_metrics,
+ params.font_identity,
)?;
let pixel_width = glyph_info
.iter()
diff --git a/wezterm-gui/src/termwindow/render/tab_bar.rs b/wezterm-gui/src/termwindow/render/tab_bar.rs
index 95c24d79..cccfbf40 100644
--- a/wezterm-gui/src/termwindow/render/tab_bar.rs
+++ b/wezterm-gui/src/termwindow/render/tab_bar.rs
@@ -1,5 +1,6 @@
use crate::quad::TripleLayerQuadAllocator;
use crate::termwindow::render::RenderScreenLineParams;
+use crate::termwindow::theme_aligned_tab_bar_colors_from_palette;
use crate::utilsprites::RenderMetrics;
use config::ConfigHandle;
use mux::renderable::RenderableDimensions;
@@ -9,13 +10,8 @@ use window::color::LinearRgba;
impl crate::TermWindow {
pub fn paint_tab_bar(&mut self, layers: &mut TripleLayerQuadAllocator) -> anyhow::Result<()> {
if self.config.use_fancy_tab_bar {
- if self.fancy_tab_bar.is_none() {
- let palette = self.palette().clone();
- let tab_bar = self.build_fancy_tab_bar(&palette)?;
- self.fancy_tab_bar.replace(tab_bar);
- }
-
- self.ui_items.append(&mut self.paint_fancy_tab_bar()?);
+ let mut tab_bar_items = self.paint_fancy_tab_bar(layers)?;
+ self.ui_items.append(&mut tab_bar_items);
return Ok(());
}
@@ -29,12 +25,15 @@ impl crate::TermWindow {
} else {
border.top.get() as f32
};
+ let tab_bar_x = self.tab_bar_left_edge();
+ let tab_bar_width = self.dimensions.pixel_width.saturating_sub(tab_bar_x).max(1);
// Register the tab bar location
self.ui_items.append(&mut self.tab_bar.compute_ui_items(
tab_bar_y as usize,
self.render_metrics.cell_size.height as usize,
self.render_metrics.cell_size.width as usize,
+ tab_bar_x,
));
let window_is_transparent =
@@ -42,6 +41,28 @@ impl crate::TermWindow {
let gl_state = self.render_state.as_ref().unwrap();
let white_space = gl_state.util_sprites.white_space.texture_coords();
let filled_box = gl_state.util_sprites.filled_box.texture_coords();
+ let tab_bar_colors = self
+ .config
+ .resolved_palette
+ .tab_bar
+ .as_ref()
+ .cloned()
+ .unwrap_or_else(|| theme_aligned_tab_bar_colors_from_palette(&palette));
+ let tab_bar_bg = tab_bar_colors
+ .background()
+ .to_linear()
+ .mul_alpha(self.config.window_background_opacity);
+ self.filled_rectangle(
+ layers,
+ 0,
+ euclid::rect(
+ tab_bar_x as f32,
+ tab_bar_y,
+ tab_bar_width as f32,
+ tab_bar_height,
+ ),
+ tab_bar_bg,
+ )?;
let default_bg = palette
.resolve_bg(ColorAttribute::Default)
.to_linear()
@@ -54,23 +75,22 @@ impl crate::TermWindow {
self.render_screen_line(
RenderScreenLineParams {
top_pixel_y: tab_bar_y,
- left_pixel_x: 0.,
- pixel_width: self.dimensions.pixel_width as f32,
+ left_pixel_x: tab_bar_x as f32,
+ pixel_width: tab_bar_width as f32,
stable_line_idx: None,
line: self.tab_bar.line(),
selection: 0..0,
cursor: &Default::default(),
palette: &palette,
dims: &RenderableDimensions {
- cols: self.dimensions.pixel_width
- / self.render_metrics.cell_size.width as usize,
+ cols: (tab_bar_width / self.render_metrics.cell_size.width as usize).max(1),
physical_top: 0,
scrollback_rows: 0,
scrollback_top: 0,
viewport_rows: 1,
dpi: self.terminal_size.dpi,
pixel_height: self.render_metrics.cell_size.height as usize,
- pixel_width: self.terminal_size.pixel_width,
+ pixel_width: tab_bar_width,
reverse_video: false,
},
config: &self.config,
@@ -91,6 +111,8 @@ impl crate::TermWindow {
font: None,
use_pixel_positioning: self.config.experimental_pixel_positioning,
render_metrics: self.render_metrics,
+ font_config: None,
+ font_identity: self.fonts.get_font_scale().to_bits(),
shape_key: None,
password_input: false,
},
@@ -107,7 +129,7 @@ impl crate::TermWindow {
) -> anyhow::Result<f32> {
if config.use_fancy_tab_bar {
let font = fontconfig.title_font()?;
- Ok((font.metrics().cell_height.get() as f32 * 1.75).ceil())
+ Ok((font.metrics().cell_height.get() as f32 * 2.05).ceil())
} else {
Ok(render_metrics.cell_size.height as f32)
}
diff --git a/wezterm-gui/src/termwindow/render/window_buttons.rs b/wezterm-gui/src/termwindow/render/window_buttons.rs
index d8bf6078..18fe3cd3 100644
--- a/wezterm-gui/src/termwindow/render/window_buttons.rs
+++ b/wezterm-gui/src/termwindow/render/window_buttons.rs
@@ -1,3 +1,5 @@
+#![allow(dead_code)]
+
use crate::customglyph::*;
use crate::termwindow::box_model::*;
use crate::termwindow::render::corners::*;
diff --git a/wezterm-gui/src/termwindow/resize.rs b/wezterm-gui/src/termwindow/resize.rs
index 74a45034..782a96ec 100644
--- a/wezterm-gui/src/termwindow/resize.rs
+++ b/wezterm-gui/src/termwindow/resize.rs
@@ -1,7 +1,9 @@
use crate::resize_increment_calculator::ResizeIncrementCalculator;
+use crate::termwindow::ui::pane_nav_bar_height_for_metrics;
use crate::utilsprites::RenderMetrics;
use ::window::{Dimensions, ResizeIncrement, Window, WindowOps, WindowState};
use config::{ConfigHandle, DimensionContext};
+use mux::tab::PositionedPane;
use mux::Mux;
use std::rc::Rc;
use wezterm_font::FontConfiguration;
@@ -20,6 +22,67 @@ pub enum ScaleChange {
}
impl super::TermWindow {
+ pub(crate) fn terminal_size_for_positioned_pane(
+ &self,
+ pos: &PositionedPane,
+ render_metrics: RenderMetrics,
+ ) -> TerminalSize {
+ let cell_width = render_metrics.cell_size.width.max(1) as usize;
+ let cell_height = render_metrics.cell_size.height.max(1) as usize;
+ let pane_nav_height = pane_nav_bar_height_for_metrics(render_metrics)
+ .min(pos.pixel_height.saturating_sub(cell_height));
+ let pixel_width = pos.pixel_width.max(cell_width);
+ let pixel_height = pos
+ .pixel_height
+ .saturating_sub(pane_nav_height)
+ .max(cell_height);
+ let cols = (pixel_width / cell_width).max(1);
+ let rows = (pixel_height / cell_height).max(1);
+
+ TerminalSize {
+ rows,
+ cols,
+ pixel_width: cols * cell_width,
+ pixel_height: rows * cell_height,
+ dpi: self.dimensions.dpi as u32,
+ }
+ }
+
+ fn sync_positioned_pane_font_size(&self, pos: &PositionedPane) -> anyhow::Result<()> {
+ let pane_id = pos.pane.pane_id();
+ let font_scale = self.pane_font_scale(pane_id);
+ let render_metrics = if font_scale.to_bits() == self.fonts.get_font_scale().to_bits() {
+ self.render_metrics
+ } else {
+ self.pane_font_resources(font_scale)?.1
+ };
+ let target_size = self.terminal_size_for_positioned_pane(pos, render_metrics);
+ let dims = pos.pane.get_dimensions();
+
+ if dims.cols != target_size.cols
+ || dims.viewport_rows != target_size.rows
+ || dims.pixel_width != target_size.pixel_width
+ || dims.pixel_height != target_size.pixel_height
+ || dims.dpi != target_size.dpi
+ {
+ pos.pane.resize(target_size)?;
+ }
+
+ Ok(())
+ }
+
+ pub fn sync_pane_font_sizes(&self) {
+ for pos in self.get_panes_to_render() {
+ if let Err(err) = self.sync_positioned_pane_font_size(&pos) {
+ log::error!(
+ "failed to sync font-scaled pane size for pane {}: {:#}",
+ pos.pane.pane_id(),
+ err
+ );
+ }
+ }
+ }
+
pub fn resize(
&mut self,
dimensions: Dimensions,
@@ -195,7 +258,8 @@ impl super::TermWindow {
pixel_max: size.pixel_height as f32,
pixel_cell: self.render_metrics.cell_size.height as f32,
};
- let padding_left = config.window_padding.left.evaluate_as_pixels(h_context) as usize;
+ let padding_left = config.window_padding.left.evaluate_as_pixels(h_context) as usize
+ + self.workspace_sidebar_width();
let padding_top = config.window_padding.top.evaluate_as_pixels(v_context) as usize;
let padding_bottom =
config.window_padding.bottom.evaluate_as_pixels(v_context) as usize;
@@ -241,7 +305,8 @@ impl super::TermWindow {
pixel_max: self.terminal_size.pixel_height as f32,
pixel_cell: self.render_metrics.cell_size.height as f32,
};
- let padding_left = config.window_padding.left.evaluate_as_pixels(h_context) as usize;
+ let padding_left = config.window_padding.left.evaluate_as_pixels(h_context) as usize
+ + self.workspace_sidebar_width();
let padding_top = config.window_padding.top.evaluate_as_pixels(v_context) as usize;
let padding_bottom =
config.window_padding.bottom.evaluate_as_pixels(v_context) as usize;
@@ -298,6 +363,7 @@ impl super::TermWindow {
tab.resize(size);
}
};
+ self.sync_pane_font_sizes();
self.resize_overlays();
self.invalidate_fancy_tab_bar();
self.update_title();
@@ -454,22 +520,84 @@ impl super::TermWindow {
}
}
+ fn adjust_active_pane_font_scale(&mut self, font_scale: f64) {
+ let pane_id = match self.get_active_pane_no_overlay() {
+ Some(pane) => pane.pane_id(),
+ None => {
+ if let Some(window) = self.window.as_ref().map(|w| w.clone()) {
+ self.adjust_font_scale(font_scale, &window);
+ }
+ return;
+ }
+ };
+
+ let font_size = self.config.font_size * font_scale;
+ let theoretical_height = font_size * self.dimensions.dpi as f64 / 72.0;
+
+ if theoretical_height < 2.0 {
+ log::warn!(
+ "refusing to go to an unreasonably small pane font scale {:?}
+ font_scale={} would yield font_height {}",
+ self.dimensions,
+ font_scale,
+ theoretical_height
+ );
+ return;
+ }
+
+ let global_scale = self.fonts.get_font_scale();
+ {
+ let mut state = self.pane_state(pane_id);
+ state.font_scale = if font_scale.to_bits() == global_scale.to_bits() {
+ None
+ } else {
+ Some(font_scale)
+ };
+ }
+
+ self.sync_pane_font_sizes();
+ self.quad_generation += 1;
+ self.shape_generation += 1;
+ self.shape_cache.borrow_mut().clear();
+ self.line_to_ele_shape_cache.borrow_mut().clear();
+ self.invalidate_fancy_tab_bar();
+ self.invalidate_modal();
+
+ if let Some(window) = self.window.as_ref() {
+ window.invalidate();
+ }
+ }
+
pub fn decrease_font_size(&mut self) {
- self.pending_scale_changes
- .push_back(ScaleChange::Relative(1.0 / 1.1));
- self.apply_pending_scale_changes();
+ if let Some(pane) = self.get_active_pane_no_overlay() {
+ let font_scale = self.pane_font_scale(pane.pane_id());
+ self.adjust_active_pane_font_scale(font_scale * (1.0 / 1.1));
+ } else {
+ self.pending_scale_changes
+ .push_back(ScaleChange::Relative(1.0 / 1.1));
+ self.apply_pending_scale_changes();
+ }
}
pub fn increase_font_size(&mut self) {
- self.pending_scale_changes
- .push_back(ScaleChange::Relative(1.1));
- self.apply_pending_scale_changes();
+ if let Some(pane) = self.get_active_pane_no_overlay() {
+ let font_scale = self.pane_font_scale(pane.pane_id());
+ self.adjust_active_pane_font_scale(font_scale * 1.1);
+ } else {
+ self.pending_scale_changes
+ .push_back(ScaleChange::Relative(1.1));
+ self.apply_pending_scale_changes();
+ }
}
pub fn reset_font_size(&mut self) {
- self.pending_scale_changes
- .push_back(ScaleChange::Absolute(1.0));
- self.apply_pending_scale_changes();
+ if self.get_active_pane_no_overlay().is_some() {
+ self.adjust_active_pane_font_scale(self.fonts.get_font_scale());
+ } else {
+ self.pending_scale_changes
+ .push_back(ScaleChange::Absolute(1.0));
+ self.apply_pending_scale_changes();
+ }
}
pub fn set_window_size(&mut self, size: TerminalSize, window: &Window) -> anyhow::Result<()> {
diff --git a/wezterm-gui/src/termwindow/spawn.rs b/wezterm-gui/src/termwindow/spawn.rs
index 1395afc3..ed4a7d0f 100644
--- a/wezterm-gui/src/termwindow/spawn.rs
+++ b/wezterm-gui/src/termwindow/spawn.rs
@@ -33,4 +33,19 @@ impl super::TermWindow {
SpawnWhere::NewTab,
);
}
+
+ pub fn spawn_tab_to_right(&mut self, domain: &SpawnTabDomain) {
+ let insert_idx = mux::Mux::get()
+ .get_window(self.mux_window_id)
+ .map(|window| window.get_active_idx().saturating_add(1))
+ .unwrap_or(0);
+
+ self.spawn_command(
+ &SpawnCommand {
+ domain: domain.clone(),
+ ..Default::default()
+ },
+ SpawnWhere::NewTabAt(insert_idx),
+ );
+ }
}
diff --git a/wezterm-gui/src/termwindow/ui/icons.rs b/wezterm-gui/src/termwindow/ui/icons.rs
new file mode 100644
index 00000000..9ffa3583
--- /dev/null
+++ b/wezterm-gui/src/termwindow/ui/icons.rs
@@ -0,0 +1,96 @@
+use anyhow::{Context, Result};
+use window::Image;
+
+#[allow(dead_code)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum SvgIcon {
+ ExternalLink,
+ FolderOpen,
+ Globe,
+ PanelRightClose,
+ PanelRightOpen,
+ Plus,
+ SquareTerminal,
+ SplitHorizontal,
+ SplitVertical,
+ Terminal,
+ X,
+}
+
+impl SvgIcon {
+ pub fn bytes(self) -> &'static [u8] {
+ match self {
+ Self::ExternalLink => {
+ include_bytes!("../../../../third_party/lucide/icons/external-link.svg")
+ }
+ Self::FolderOpen => {
+ include_bytes!("../../../../third_party/lucide/icons/folder-open.svg")
+ }
+ Self::Globe => include_bytes!("../../../../third_party/lucide/icons/globe.svg"),
+ Self::PanelRightClose => {
+ include_bytes!("../../../../third_party/lucide/icons/panel-right-close.svg")
+ }
+ Self::PanelRightOpen => {
+ include_bytes!("../../../../third_party/lucide/icons/panel-right-open.svg")
+ }
+ Self::Plus => include_bytes!("../../../../third_party/lucide/icons/plus.svg"),
+ Self::SquareTerminal => {
+ include_bytes!("../../../../third_party/lucide/icons/square-terminal.svg")
+ }
+ Self::SplitHorizontal => {
+ include_bytes!("../../../../third_party/lucide/icons/square-split-horizontal.svg")
+ }
+ Self::SplitVertical => {
+ include_bytes!("../../../../third_party/lucide/icons/square-split-vertical.svg")
+ }
+ Self::Terminal => include_bytes!("../../../../third_party/lucide/icons/terminal.svg"),
+ Self::X => include_bytes!("../../../../third_party/lucide/icons/x.svg"),
+ }
+ }
+
+ pub fn rasterize(self, size: usize) -> Result<Image> {
+ let size = size.max(1);
+ let svg = std::str::from_utf8(self.bytes()).context("SVG asset is not UTF-8")?;
+ let svg = svg.replace("currentColor", "#ffffff");
+ let tree = resvg::usvg::Tree::from_data(svg.as_bytes(), &resvg::usvg::Options::default())
+ .context("parsing SVG icon")?;
+ let svg_size = tree.size();
+ let scale = (size as f32 / svg_size.width()).min(size as f32 / svg_size.height());
+ let translate_x = (size as f32 - svg_size.width() * scale) / 2.0;
+ let translate_y = (size as f32 - svg_size.height() * scale) / 2.0;
+ let transform = resvg::tiny_skia::Transform::from_translate(translate_x, translate_y)
+ .pre_scale(scale, scale);
+
+ let mut pixmap = resvg::tiny_skia::Pixmap::new(size as u32, size as u32)
+ .with_context(|| format!("allocating {size}px SVG icon pixmap"))?;
+ resvg::render(&tree, transform, &mut pixmap.as_mut());
+
+ Ok(Image::from_raw(size, size, pixmap.take()))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::SvgIcon;
+
+ #[test]
+ fn svg_icons_rasterize() {
+ for icon in [
+ SvgIcon::ExternalLink,
+ SvgIcon::FolderOpen,
+ SvgIcon::Globe,
+ SvgIcon::PanelRightClose,
+ SvgIcon::PanelRightOpen,
+ SvgIcon::Plus,
+ SvgIcon::SquareTerminal,
+ SvgIcon::SplitHorizontal,
+ SvgIcon::SplitVertical,
+ SvgIcon::Terminal,
+ SvgIcon::X,
+ ] {
+ let data: Vec<u8> = icon.rasterize(24).unwrap().into();
+ assert_eq!(data.len(), 24 * 24 * 4);
+ assert!(data.iter().any(|value| *value != 0));
+ }
+ }
+}
diff --git a/wezterm-gui/src/termwindow/ui/mod.rs b/wezterm-gui/src/termwindow/ui/mod.rs
new file mode 100644
index 00000000..ce697336
--- /dev/null
+++ b/wezterm-gui/src/termwindow/ui/mod.rs
@@ -0,0 +1,38 @@
+pub mod icons;
+pub mod sidebar;
+pub mod tokens;
+
+use crate::utilsprites::RenderMetrics;
+
+pub use sidebar::workspace_sidebar_width_for_metrics;
+
+pub fn pane_nav_bar_height_for_metrics(render_metrics: RenderMetrics) -> usize {
+ (render_metrics.cell_size.height as usize + tokens::PANE_NAV_EXTRA_HEIGHT)
+ .clamp(tokens::PANE_NAV_MIN_HEIGHT, tokens::PANE_NAV_MAX_HEIGHT)
+}
+
+pub fn terminal_title_for_display(title: &str) -> &str {
+ let title = title.trim();
+ if title.is_empty() || is_default_shell_title(title) {
+ "Terminal"
+ } else {
+ title
+ }
+}
+
+fn is_default_shell_title(title: &str) -> bool {
+ let title = title.rsplit(['/', '\\']).next().unwrap_or(title);
+ matches!(
+ title.to_ascii_lowercase().as_str(),
+ "zsh"
+ | "bash"
+ | "sh"
+ | "fish"
+ | "nu"
+ | "nushell"
+ | "elvish"
+ | "xonsh"
+ | "pwsh"
+ | "powershell"
+ )
+}
diff --git a/wezterm-gui/src/termwindow/ui/sidebar.rs b/wezterm-gui/src/termwindow/ui/sidebar.rs
new file mode 100644
index 00000000..ba1b4198
--- /dev/null
+++ b/wezterm-gui/src/termwindow/ui/sidebar.rs
@@ -0,0 +1,451 @@
+use crate::quad::{QuadTrait, TripleLayerQuadAllocator, TripleLayerQuadAllocatorTrait};
+use crate::termwindow::render::corners::{
+ BOTTOM_LEFT_ROUNDED_CORNER, BOTTOM_RIGHT_ROUNDED_CORNER, TOP_LEFT_ROUNDED_CORNER,
+ TOP_RIGHT_ROUNDED_CORNER,
+};
+use crate::termwindow::render::RenderScreenLineParams;
+use crate::termwindow::ui::icons::SvgIcon;
+use crate::termwindow::ui::tokens::{
+ mix, SIDEBAR_ICON_GAP, SIDEBAR_INSET, SIDEBAR_MAX_WIDTH, SIDEBAR_MIN_WIDTH,
+ SIDEBAR_RESIZE_HANDLE_WIDTH, SIDEBAR_ROW_RADIUS, SIDEBAR_WIDTH_CELLS,
+};
+use crate::termwindow::{UIItem, UIItemType};
+use crate::utilsprites::RenderMetrics;
+use anyhow::Context;
+use mux::renderable::RenderableDimensions;
+use mux::Mux;
+use std::rc::Rc;
+use wezterm_font::LoadedFont;
+use wezterm_term::color::{ColorAttribute, ColorPalette};
+use wezterm_term::{CellAttributes, Line};
+use window::color::LinearRgba;
+use window::RectF;
+
+#[derive(Debug, Clone, Copy)]
+pub struct WorkspaceSidebarRect {
+ pub x: usize,
+ pub y: usize,
+ pub width: usize,
+ pub height: usize,
+}
+
+pub fn workspace_sidebar_width_for_metrics(render_metrics: &RenderMetrics) -> usize {
+ (render_metrics.cell_size.width as usize * SIDEBAR_WIDTH_CELLS).max(SIDEBAR_MIN_WIDTH)
+}
+
+impl crate::TermWindow {
+ pub fn workspace_sidebar_width(&self) -> usize {
+ if self.workspace_sidebar_collapsed {
+ 0
+ } else {
+ self.workspace_sidebar_width
+ .clamp(SIDEBAR_MIN_WIDTH, self.workspace_sidebar_max_width())
+ }
+ }
+
+ pub fn workspace_sidebar_max_width(&self) -> usize {
+ SIDEBAR_MAX_WIDTH.min((self.dimensions.pixel_width / 2).max(SIDEBAR_MIN_WIDTH))
+ }
+
+ pub fn set_workspace_sidebar_width(&mut self, width: usize) {
+ self.workspace_sidebar_width =
+ width.clamp(SIDEBAR_MIN_WIDTH, self.workspace_sidebar_max_width());
+ }
+
+ pub fn toggle_workspace_sidebar(&mut self) {
+ self.workspace_sidebar_collapsed = !self.workspace_sidebar_collapsed;
+ }
+
+ pub fn expand_workspace_sidebar(&mut self) {
+ self.workspace_sidebar_collapsed = false;
+ }
+
+ pub fn tab_bar_left_edge(&self) -> usize {
+ let border = self.get_os_border();
+ border.left.get() as usize + self.workspace_sidebar_width()
+ }
+
+ pub fn workspace_sidebar_rect(&self) -> Option<WorkspaceSidebarRect> {
+ let border = self.get_os_border();
+ let bottom_tab_bar_height = if self.config.tab_bar_at_bottom && self.show_tab_bar {
+ self.tab_bar_pixel_height().unwrap_or(0.0).ceil() as usize
+ } else {
+ 0
+ };
+
+ let x = border.left.get() as usize;
+ let y = border.top.get() as usize;
+ let width = self.workspace_sidebar_width().min(
+ self.dimensions
+ .pixel_width
+ .saturating_sub((border.left + border.right).get() as usize),
+ );
+ let height = self
+ .dimensions
+ .pixel_height
+ .saturating_sub(y + border.bottom.get() as usize + bottom_tab_bar_height);
+
+ if width == 0 || height == 0 {
+ return None;
+ }
+
+ Some(WorkspaceSidebarRect {
+ x,
+ y,
+ width,
+ height,
+ })
+ }
+
+ pub fn paint_workspace_sidebar(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator,
+ ) -> anyhow::Result<()> {
+ let rect = match self.workspace_sidebar_rect() {
+ Some(rect) => rect,
+ None => return Ok(()),
+ };
+
+ let palette = self.palette().clone();
+ let background = palette
+ .resolve_bg(ColorAttribute::Default)
+ .to_linear()
+ .mul_alpha(self.config.window_background_opacity);
+ let black = LinearRgba::with_components(0.0, 0.0, 0.0, background.3);
+ let foreground = palette.foreground.to_linear();
+ let sidebar_bg = mix(background, black, 0.12);
+ let divider = foreground.mul_alpha(0.14);
+ let selected_bg = palette.selection_bg.to_linear().mul_alpha(0.55);
+ let active_fg = palette
+ .selection_fg
+ .to_linear()
+ .when_fully_transparent(foreground);
+ let muted_fg = foreground.mul_alpha(0.62);
+ let ui_font = self.fonts.title_font().context("sidebar ui font")?;
+ let ui_metrics = RenderMetrics::with_font_metrics(&ui_font.metrics());
+ let ui_cell_height = ui_metrics.cell_size.height as usize;
+ let icon_size = (ui_cell_height + 12).clamp(30, 36);
+
+ self.filled_rectangle(
+ layers,
+ 0,
+ euclid::rect(
+ rect.x as f32,
+ rect.y as f32,
+ rect.width as f32,
+ rect.height as f32,
+ ),
+ sidebar_bg,
+ )
+ .context("sidebar background")?;
+ self.filled_rectangle(
+ layers,
+ 1,
+ euclid::rect(
+ (rect.x + rect.width.saturating_sub(1)) as f32,
+ rect.y as f32,
+ 1.0,
+ rect.height as f32,
+ ),
+ divider,
+ )
+ .context("sidebar divider")?;
+
+ self.ui_items.push(UIItem {
+ x: rect.x,
+ y: rect.y,
+ width: rect.width,
+ height: rect.height,
+ item_type: UIItemType::WorkspaceSidebarBackground,
+ });
+
+ let item_height = (ui_cell_height.max(icon_size) + SIDEBAR_INSET * 2).max(56);
+ let item_x = rect.x + SIDEBAR_INSET;
+ let item_width = rect.width.saturating_sub(SIDEBAR_INSET * 2 + 1);
+ let row_icon_x = item_x + SIDEBAR_INSET;
+ let row_text_x = row_icon_x + icon_size + SIDEBAR_ICON_GAP;
+ let row_text_width = item_x
+ .saturating_add(item_width)
+ .saturating_sub(row_text_x + SIDEBAR_INSET);
+ self.ui_items.push(UIItem {
+ x: rect
+ .x
+ .saturating_add(rect.width)
+ .saturating_sub(SIDEBAR_RESIZE_HANDLE_WIDTH / 2),
+ y: rect.y,
+ width: SIDEBAR_RESIZE_HANDLE_WIDTH,
+ height: rect.height,
+ item_type: UIItemType::WorkspaceSidebarResize,
+ });
+
+ if self.workspace_sidebar_collapsed {
+ return Ok(());
+ }
+
+ let mux = Mux::get();
+ let active_workspace = mux.active_workspace();
+ let mut workspaces = mux.iter_workspaces();
+ if !workspaces.iter().any(|name| name == &active_workspace) {
+ workspaces.insert(0, active_workspace.clone());
+ }
+
+ let mut y = rect.y + SIDEBAR_INSET;
+ for workspace in workspaces {
+ if y + item_height > rect.y + rect.height {
+ break;
+ }
+
+ let is_active = workspace == active_workspace;
+ if is_active {
+ self.fill_rounded_rectangle(
+ layers,
+ 0,
+ euclid::rect(
+ item_x as f32,
+ y as f32,
+ item_width as f32,
+ item_height as f32,
+ ),
+ selected_bg,
+ SIDEBAR_ROW_RADIUS,
+ )
+ .context("sidebar selected workspace")?;
+ }
+
+ self.ui_items.push(UIItem {
+ x: item_x,
+ y,
+ width: item_width,
+ height: item_height,
+ item_type: UIItemType::WorkspaceSidebar(workspace.clone()),
+ });
+
+ let icon_y = y + ((item_height.saturating_sub(icon_size)) / 2);
+ let text_y = y + ((item_height.saturating_sub(ui_cell_height)) / 2);
+ self.paint_sidebar_icon(
+ layers,
+ SvgIcon::FolderOpen,
+ row_icon_x,
+ icon_y,
+ icon_size,
+ if is_active { active_fg } else { muted_fg },
+ )?;
+ self.paint_sidebar_text(
+ layers,
+ &palette,
+ &ui_font,
+ ui_metrics,
+ &workspace,
+ row_text_x,
+ text_y,
+ row_text_width,
+ if is_active { active_fg } else { foreground },
+ )?;
+
+ y += item_height + (SIDEBAR_INSET / 2);
+ }
+
+ Ok(())
+ }
+
+ pub(crate) fn fill_rounded_rectangle(
+ &self,
+ layers: &mut TripleLayerQuadAllocator,
+ layer_num: usize,
+ rect: RectF,
+ color: LinearRgba,
+ radius: f32,
+ ) -> anyhow::Result<()> {
+ let radius = radius.min(rect.width() / 2.0).min(rect.height() / 2.0);
+ if radius <= 0.0 {
+ self.filled_rectangle(layers, layer_num, rect, color)?;
+ return Ok(());
+ }
+
+ let corner_size = euclid::size2(radius, radius);
+ self.poly_quad(
+ layers,
+ layer_num,
+ euclid::point2(rect.min_x(), rect.min_y()),
+ TOP_LEFT_ROUNDED_CORNER,
+ 0,
+ corner_size,
+ color,
+ )?
+ .set_grayscale();
+ self.poly_quad(
+ layers,
+ layer_num,
+ euclid::point2(rect.max_x() - radius, rect.min_y()),
+ TOP_RIGHT_ROUNDED_CORNER,
+ 0,
+ corner_size,
+ color,
+ )?
+ .set_grayscale();
+ self.poly_quad(
+ layers,
+ layer_num,
+ euclid::point2(rect.min_x(), rect.max_y() - radius),
+ BOTTOM_LEFT_ROUNDED_CORNER,
+ 0,
+ corner_size,
+ color,
+ )?
+ .set_grayscale();
+ self.poly_quad(
+ layers,
+ layer_num,
+ euclid::point2(rect.max_x() - radius, rect.max_y() - radius),
+ BOTTOM_RIGHT_ROUNDED_CORNER,
+ 0,
+ corner_size,
+ color,
+ )?
+ .set_grayscale();
+
+ self.filled_rectangle(
+ layers,
+ layer_num,
+ euclid::rect(
+ rect.min_x() + radius,
+ rect.min_y(),
+ rect.width() - radius * 2.0,
+ rect.height(),
+ ),
+ color,
+ )?;
+ self.filled_rectangle(
+ layers,
+ layer_num,
+ euclid::rect(
+ rect.min_x(),
+ rect.min_y() + radius,
+ radius,
+ rect.height() - radius * 2.0,
+ ),
+ color,
+ )?;
+ self.filled_rectangle(
+ layers,
+ layer_num,
+ euclid::rect(
+ rect.max_x() - radius,
+ rect.min_y() + radius,
+ radius,
+ rect.height() - radius * 2.0,
+ ),
+ color,
+ )?;
+
+ Ok(())
+ }
+
+ fn paint_sidebar_text(
+ &self,
+ layers: &mut TripleLayerQuadAllocator,
+ palette: &ColorPalette,
+ font: &Rc<LoadedFont>,
+ metrics: RenderMetrics,
+ text: &str,
+ x: usize,
+ y: usize,
+ width: usize,
+ foreground: LinearRgba,
+ ) -> anyhow::Result<()> {
+ if width == 0 {
+ return Ok(());
+ }
+
+ let gl_state = self.render_state.as_ref().unwrap();
+ let white_space = gl_state.util_sprites.white_space.texture_coords();
+ let filled_box = gl_state.util_sprites.filled_box.texture_coords();
+ let cell_width = metrics.cell_size.width as usize;
+ let cell_height = metrics.cell_size.height as usize;
+ let attrs = CellAttributes::blank();
+ let line = Line::from_text(text, &attrs, 0, None);
+
+ self.render_screen_line(
+ RenderScreenLineParams {
+ top_pixel_y: y as f32,
+ left_pixel_x: x as f32,
+ pixel_width: width as f32,
+ stable_line_idx: None,
+ line: &line,
+ selection: 0..0,
+ cursor: &Default::default(),
+ palette,
+ dims: &RenderableDimensions {
+ cols: (width / cell_width).max(1),
+ physical_top: 0,
+ scrollback_rows: 0,
+ scrollback_top: 0,
+ viewport_rows: 1,
+ dpi: self.terminal_size.dpi,
+ pixel_height: cell_height,
+ pixel_width: width,
+ reverse_video: false,
+ },
+ config: &self.config,
+ cursor_border_color: LinearRgba::default(),
+ foreground,
+ pane: None,
+ is_active: true,
+ selection_fg: LinearRgba::default(),
+ selection_bg: LinearRgba::default(),
+ cursor_fg: LinearRgba::default(),
+ cursor_bg: LinearRgba::default(),
+ cursor_is_default_color: true,
+ white_space,
+ filled_box,
+ window_is_transparent: true,
+ default_bg: LinearRgba::TRANSPARENT,
+ style: Some(font.style()),
+ font: Some(Rc::clone(font)),
+ use_pixel_positioning: true,
+ render_metrics: metrics,
+ font_config: None,
+ font_identity: font.id() as u64,
+ shape_key: None,
+ password_input: false,
+ },
+ layers,
+ )?;
+
+ Ok(())
+ }
+
+ fn paint_sidebar_icon(
+ &self,
+ layers: &mut TripleLayerQuadAllocator,
+ icon: SvgIcon,
+ x: usize,
+ y: usize,
+ size: usize,
+ color: LinearRgba,
+ ) -> anyhow::Result<()> {
+ let left_offset = self.dimensions.pixel_width as f32 / 2.0;
+ let top_offset = self.dimensions.pixel_height as f32 / 2.0;
+ let gl_state = self.render_state.as_ref().unwrap();
+ let sprite = gl_state
+ .glyph_cache
+ .borrow_mut()
+ .cached_svg_icon(icon, size)?
+ .texture_coords();
+
+ let mut quad = layers.allocate(1)?;
+ quad.set_position(
+ x as f32 - left_offset,
+ y as f32 - top_offset,
+ x as f32 + size as f32 - left_offset,
+ y as f32 + size as f32 - top_offset,
+ );
+ quad.set_texture(sprite);
+ quad.set_fg_color(color);
+ quad.set_alt_color_and_mix_value(color, 0.0);
+ quad.set_hsv(None);
+ quad.set_grayscale();
+
+ Ok(())
+ }
+}
diff --git a/wezterm-gui/src/termwindow/ui/tokens.rs b/wezterm-gui/src/termwindow/ui/tokens.rs
new file mode 100644
index 00000000..0e0dcee9
--- /dev/null
+++ b/wezterm-gui/src/termwindow/ui/tokens.rs
@@ -0,0 +1,30 @@
+use window::color::LinearRgba;
+
+pub const SIDEBAR_WIDTH_CELLS: usize = 26;
+pub const SIDEBAR_MIN_WIDTH: usize = 224;
+pub const SIDEBAR_MAX_WIDTH: usize = 520;
+pub const SIDEBAR_INSET: usize = 10;
+pub const SIDEBAR_ICON_GAP: usize = 10;
+pub const SIDEBAR_ROW_RADIUS: f32 = 6.0;
+pub const SIDEBAR_RESIZE_HANDLE_WIDTH: usize = 8;
+
+pub const PANE_NAV_INSET: usize = 6;
+pub const PANE_NAV_ICON_GAP: usize = 8;
+pub const PANE_NAV_BUTTON_GAP: usize = 4;
+pub const PANE_NAV_EXTRA_HEIGHT: usize = 12;
+pub const PANE_NAV_MIN_HEIGHT: usize = 42;
+pub const PANE_NAV_MAX_HEIGHT: usize = 48;
+pub const PANE_NAV_TAB_MIN_WIDTH: usize = 180;
+pub const PANE_NAV_TAB_MAX_WIDTH: usize = 220;
+pub const PANE_NAV_TAB_RADIUS: f32 = 5.0;
+
+pub fn mix(a: LinearRgba, b: LinearRgba, amount: f32) -> LinearRgba {
+ let amount = amount.clamp(0.0, 1.0);
+ let inverse = 1.0 - amount;
+ LinearRgba::with_components(
+ a.0 * inverse + b.0 * amount,
+ a.1 * inverse + b.1 * amount,
+ a.2 * inverse + b.2 * amount,
+ a.3 * inverse + b.3 * amount,
+ )
+}
diff --git a/wezterm/src/cli/activate_tab.rs b/wezterm/src/cli/activate_tab.rs
index 7cb32b34..1c4694fa 100644
--- a/wezterm/src/cli/activate_tab.rs
+++ b/wezterm/src/cli/activate_tab.rs
@@ -57,17 +57,19 @@ impl ActivateTab {
let mut cursor = tabroot.into_tree().cursor();
loop {
- if let Some(entry) = cursor.leaf_mut() {
- pane_id_to_tab_id.insert(entry.pane_id, entry.tab_id);
- if entry.is_active_pane {
- tab_id_to_active_pane_id.insert(entry.tab_id, entry.pane_id);
- }
- window_by_tab_id.insert(entry.tab_id, entry.window_id);
- let win = tabs_by_window
- .entry(entry.window_id)
- .or_insert_with(Vec::new);
- if win.last().copied() != Some(entry.tab_id) {
- win.push(entry.tab_id);
+ if let Some(stack) = cursor.leaf_mut() {
+ for entry in &stack.panes {
+ pane_id_to_tab_id.insert(entry.pane_id, entry.tab_id);
+ if entry.is_active_pane {
+ tab_id_to_active_pane_id.insert(entry.tab_id, entry.pane_id);
+ }
+ window_by_tab_id.insert(entry.tab_id, entry.window_id);
+ let win = tabs_by_window
+ .entry(entry.window_id)
+ .or_insert_with(Vec::new);
+ if win.last().copied() != Some(entry.tab_id) {
+ win.push(entry.tab_id);
+ }
}
}
match cursor.preorder_next() {
diff --git a/wezterm/src/cli/list.rs b/wezterm/src/cli/list.rs
index 35ab4fc2..4438c442 100644
--- a/wezterm/src/cli/list.rs
+++ b/wezterm/src/cli/list.rs
@@ -24,17 +24,19 @@ impl ListCommand {
let mut cursor = tabroot.into_tree().cursor();
loop {
- if let Some(entry) = cursor.leaf_mut() {
- let window_title = panes
- .window_titles
- .get(&entry.window_id)
- .map(|s| s.as_str())
- .unwrap_or("");
- output_items.push(CliListResultItem::from(
- entry.clone(),
- tab_title,
- window_title,
- ));
+ if let Some(stack) = cursor.leaf_mut() {
+ for entry in &stack.panes {
+ let window_title = panes
+ .window_titles
+ .get(&entry.window_id)
+ .map(|s| s.as_str())
+ .unwrap_or("");
+ output_items.push(CliListResultItem::from(
+ entry.clone(),
+ tab_title,
+ window_title,
+ ));
+ }
}
match cursor.preorder_next() {
Ok(c) => cursor = c,
diff --git a/wezterm/src/cli/move_pane_to_new_tab.rs b/wezterm/src/cli/move_pane_to_new_tab.rs
index 61ae5da6..a862ae0b 100644
--- a/wezterm/src/cli/move_pane_to_new_tab.rs
+++ b/wezterm/src/cli/move_pane_to_new_tab.rs
@@ -44,10 +44,12 @@ impl MovePaneToNewTab {
let mut cursor = tabroot.into_tree().cursor();
loop {
- if let Some(entry) = cursor.leaf_mut() {
- if entry.pane_id == pane_id {
- window_id.replace(entry.window_id);
- break 'outer_move;
+ if let Some(stack) = cursor.leaf_mut() {
+ for entry in &stack.panes {
+ if entry.pane_id == pane_id {
+ window_id.replace(entry.window_id);
+ break 'outer_move;
+ }
}
}
match cursor.preorder_next() {
diff --git a/wezterm/src/cli/rename_workspace.rs b/wezterm/src/cli/rename_workspace.rs
index 03c3018f..d0d0e866 100644
--- a/wezterm/src/cli/rename_workspace.rs
+++ b/wezterm/src/cli/rename_workspace.rs
@@ -32,8 +32,10 @@ impl RenameWorkspace {
let mut cursor = tabroot.into_tree().cursor();
loop {
- if let Some(entry) = cursor.leaf_mut() {
- pane_id_to_workspace.insert(entry.pane_id, entry.workspace.to_string());
+ if let Some(stack) = cursor.leaf_mut() {
+ for entry in &stack.panes {
+ pane_id_to_workspace.insert(entry.pane_id, entry.workspace.to_string());
+ }
}
match cursor.preorder_next() {
Ok(c) => cursor = c,
diff --git a/wezterm/src/cli/set_tab_title.rs b/wezterm/src/cli/set_tab_title.rs
index 6cf23122..ab6af051 100644
--- a/wezterm/src/cli/set_tab_title.rs
+++ b/wezterm/src/cli/set_tab_title.rs
@@ -31,8 +31,10 @@ impl SetTabTitle {
let mut cursor = tabroot.into_tree().cursor();
loop {
- if let Some(entry) = cursor.leaf_mut() {
- pane_id_to_tab_id.insert(entry.pane_id, entry.tab_id);
+ if let Some(stack) = cursor.leaf_mut() {
+ for entry in &stack.panes {
+ pane_id_to_tab_id.insert(entry.pane_id, entry.tab_id);
+ }
}
match cursor.preorder_next() {
Ok(c) => cursor = c,
diff --git a/wezterm/src/cli/set_window_title.rs b/wezterm/src/cli/set_window_title.rs
index 089c87a2..f76ccb02 100644
--- a/wezterm/src/cli/set_window_title.rs
+++ b/wezterm/src/cli/set_window_title.rs
@@ -32,8 +32,10 @@ impl SetWindowTitle {
let mut cursor = tabroot.into_tree().cursor();
loop {
- if let Some(entry) = cursor.leaf_mut() {
- pane_id_to_window_id.insert(entry.pane_id, entry.window_id);
+ if let Some(stack) = cursor.leaf_mut() {
+ for entry in &stack.panes {
+ pane_id_to_window_id.insert(entry.pane_id, entry.window_id);
+ }
}
match cursor.preorder_next() {
Ok(c) => cursor = c,
diff --git a/wezterm/src/cli/spawn_command.rs b/wezterm/src/cli/spawn_command.rs
index 0e6e490c..7c8b6c03 100644
--- a/wezterm/src/cli/spawn_command.rs
+++ b/wezterm/src/cli/spawn_command.rs
@@ -66,10 +66,12 @@ impl SpawnCommand {
let mut cursor = tabroot.into_tree().cursor();
loop {
- if let Some(entry) = cursor.leaf_mut() {
- if entry.pane_id == pane_id {
- window_id.replace(entry.window_id);
- break 'outer;
+ if let Some(stack) = cursor.leaf_mut() {
+ for entry in &stack.panes {
+ if entry.pane_id == pane_id {
+ window_id.replace(entry.window_id);
+ break 'outer;
+ }
}
}
match cursor.preorder_next() {
diff --git a/wezterm/src/cli/zoom_pane.rs b/wezterm/src/cli/zoom_pane.rs
index e8b8f755..152f9431 100644
--- a/wezterm/src/cli/zoom_pane.rs
+++ b/wezterm/src/cli/zoom_pane.rs
@@ -40,10 +40,12 @@ impl ZoomPane {
let mut cursor = tabroot.into_tree().cursor();
loop {
- if let Some(entry) = cursor.leaf_mut() {
- pane_id_to_tab_id.insert(entry.pane_id, entry.tab_id);
- if entry.is_active_pane && entry.is_zoomed_pane {
- tab_id_to_active_zoomed_pane_id.insert(entry.tab_id, entry.pane_id);
+ if let Some(stack) = cursor.leaf_mut() {
+ for entry in &stack.panes {
+ pane_id_to_tab_id.insert(entry.pane_id, entry.tab_id);
+ if entry.is_active_pane && entry.is_zoomed_pane {
+ tab_id_to_active_zoomed_pane_id.insert(entry.tab_id, entry.pane_id);
+ }
}
}
match cursor.preorder_next() {
diff --git a/wezterm/src/main.rs b/wezterm/src/main.rs
index 0661d803..ff00baa5 100644
--- a/wezterm/src/main.rs
+++ b/wezterm/src/main.rs
@@ -23,7 +23,7 @@ mod cli;
#[derive(Debug, Parser)]
#[command(
- about = "Wez's Terminal Emulator\nhttp://github.com/wezterm/wezterm",
+ about = "ThinkTerm - a workspace-first terminal\nhttps://github.com/RoversX/thinkterm",
version = wezterm_version()
)]
pub struct Opt {
diff --git a/window/Cargo.toml b/window/Cargo.toml
index e4723aa4..3f178ec1 100644
--- a/window/Cargo.toml
+++ b/window/Cargo.toml
@@ -93,6 +93,7 @@ cgl.workspace = true
cocoa.workspace = true
core-foundation.workspace = true
core-graphics.workspace = true
+foreign-types.workspace = true
objc.workspace = true
objc2-core-graphics.workspace = true
plist.workspace = true
diff --git a/window/src/lib.rs b/window/src/lib.rs
index 2b1f7cb2..5bc77f35 100644
--- a/window/src/lib.rs
+++ b/window/src/lib.rs
@@ -230,6 +230,8 @@ pub enum WindowEvent {
AppearanceChanged(Appearance),
+ ToggleWorkspaceSidebar,
+
Notification(Box<dyn Any + Send + Sync>),
// Called when the files are being dragged into the window
@@ -362,6 +364,9 @@ pub trait WindowOps {
/// and/or in the task manager/task switcher
fn set_icon(&self, _image: Image) {}
+ /// Shows or hides ThinkTerm's terminal workspace sidebar button.
+ fn set_titlebar_sidebar_button_visible(&self, _visible: bool) {}
+
fn maximize(&self) {}
fn restore(&self) {}
fn focus(&self) {}
diff --git a/window/src/os/macos/app.rs b/window/src/os/macos/app.rs
index 3f8dbb71..148ecfaf 100644
--- a/window/src/os/macos/app.rs
+++ b/window/src/os/macos/app.rs
@@ -3,18 +3,27 @@ use crate::macos::menu::RepresentedItem;
use crate::macos::{nsstring, nsstring_to_str};
use crate::menu::{Menu, MenuItem};
use crate::{ApplicationEvent, Connection};
-use cocoa::appkit::NSApplicationTerminateReply;
-use cocoa::base::id;
-use cocoa::foundation::NSInteger;
+use cocoa::appkit::{NSApp, NSApplicationTerminateReply, NSImage, NSImageNameApplicationIcon};
+use cocoa::base::{id, nil};
+use cocoa::foundation::{NSDictionary, NSInteger, NSUInteger};
use config::keyassignment::KeyAssignment;
use config::WindowCloseConfirmation;
use objc::declare::ClassDecl;
use objc::rc::StrongPtr;
use objc::runtime::{Class, Object, Sel, BOOL, NO, YES};
use objc::*;
+use std::path::{Path, PathBuf};
const CLS_NAME: &str = "WezTermAppDelegate";
+#[link(name = "AppKit", kind = "framework")]
+extern "C" {
+ static NSAboutPanelOptionApplicationName: id;
+ static NSAboutPanelOptionApplicationIcon: id;
+ static NSAboutPanelOptionApplicationVersion: id;
+ static NSAboutPanelOptionVersion: id;
+}
+
extern "C" fn application_should_terminate(
_self: &mut Object,
_sel: Sel,
@@ -60,6 +69,40 @@ fn terminate_now() -> u64 {
NSApplicationTerminateReply::NSTerminateNow as u64
}
+fn thinkterm_icon_path() -> Option<PathBuf> {
+ let exe = std::env::current_exe().ok()?;
+ let exe_dir = exe.parent()?;
+ let mut candidates = vec![exe_dir.join("ThinkTerm.icns")];
+
+ if let Some(contents_dir) = exe_dir.parent() {
+ candidates.push(contents_dir.join("Resources").join("ThinkTerm.icns"));
+ }
+
+ if let Some(repo_dir) = PathBuf::from(env!("CARGO_MANIFEST_DIR")).parent() {
+ candidates.push(repo_dir.join("assets").join("icon").join("ThinkTerm.icns"));
+ }
+
+ candidates.into_iter().find(|path| path.exists())
+}
+
+fn load_thinkterm_icon(path: &Path) -> Option<StrongPtr> {
+ let path_string = path.to_string_lossy();
+
+ unsafe {
+ let ns_image = cocoa::appkit::NSImage::initWithContentsOfFile_(
+ NSImage::alloc(nil),
+ *nsstring(path_string.as_ref()),
+ );
+ if ns_image == nil {
+ None
+ } else {
+ let ns_image = StrongPtr::new(ns_image);
+ let _: BOOL = msg_send![*ns_image, setName:NSImageNameApplicationIcon];
+ Some(ns_image)
+ }
+ }
+}
+
extern "C" fn application_will_finish_launching(
_self: &mut Object,
_sel: Sel,
@@ -112,6 +155,46 @@ extern "C" fn wezterm_perform_key_assignment(
}
}
+extern "C" fn thinkterm_order_front_standard_about_panel(
+ _self: &mut Object,
+ _sel: Sel,
+ _sender: *mut Object,
+) {
+ unsafe {
+ let app = NSApp();
+ let app_name = nsstring("ThinkTerm");
+ let empty_app_version = nsstring("");
+ let empty_build_version = nsstring("");
+ let loaded_icon = thinkterm_icon_path().and_then(|path| load_thinkterm_icon(&path));
+
+ let mut keys = vec![
+ NSAboutPanelOptionApplicationName,
+ NSAboutPanelOptionApplicationVersion,
+ NSAboutPanelOptionVersion,
+ ];
+ let mut objects = vec![*app_name, *empty_app_version, *empty_build_version];
+
+ let app_icon = if let Some(icon) = loaded_icon.as_ref() {
+ **icon
+ } else {
+ msg_send![app, applicationIconImage]
+ };
+ if app_icon != nil {
+ let () = msg_send![app, setApplicationIconImage: app_icon];
+ keys.push(NSAboutPanelOptionApplicationIcon);
+ objects.push(app_icon);
+ }
+
+ let options = NSDictionary::dictionaryWithObjects_forKeys_count_(
+ nil,
+ objects.as_ptr(),
+ keys.as_ptr(),
+ objects.len() as NSUInteger,
+ );
+ let () = msg_send![app, orderFrontStandardAboutPanelWithOptions: options];
+ }
+}
+
extern "C" fn application_open_file(
this: &mut Object,
_sel: Sel,
@@ -175,6 +258,11 @@ fn get_class() -> &'static Class {
sel!(weztermPerformKeyAssignment:),
wezterm_perform_key_assignment as extern "C" fn(&mut Object, Sel, *mut Object),
);
+ cls.add_method(
+ sel!(thinktermOrderFrontStandardAboutPanel:),
+ thinkterm_order_front_standard_about_panel
+ as extern "C" fn(&mut Object, Sel, *mut Object),
+ );
cls.add_method(
sel!(applicationOpenUntitledFile:),
application_open_untitled_file
diff --git a/window/src/os/macos/menu.rs b/window/src/os/macos/menu.rs
index 1671e9c6..fa9e0725 100644
--- a/window/src/os/macos/menu.rs
+++ b/window/src/os/macos/menu.rs
@@ -266,6 +266,19 @@ impl MenuItem {
}
}
+ pub fn set_target_application(&self) {
+ unsafe {
+ self.item.setTarget_(NSApp());
+ }
+ }
+
+ pub fn set_target_application_delegate(&self) {
+ unsafe {
+ let delegate: id = msg_send![NSApp(), delegate];
+ self.item.setTarget_(delegate);
+ }
+ }
+
pub fn set_system_symbol_image(&self, symbol_name: &str) {
unsafe {
let ns_image_cls = class!(NSImage);
diff --git a/window/src/os/macos/window.rs b/window/src/os/macos/window.rs
index 49a67ca6..407f5fbe 100644
--- a/window/src/os/macos/window.rs
+++ b/window/src/os/macos/window.rs
@@ -2,14 +2,15 @@
#![allow(clippy::let_unit_value)]
use super::keycodes::*;
-use super::{nsstring, nsstring_to_str};
+use super::{nsstring, nsstring_to_str, BitmapRef};
+use crate::bitmaps::BitmapImage;
use crate::clipboard::Clipboard as ClipboardContext;
use crate::connection::ConnectionOps;
use crate::os::macos::menu::{Menu, MenuItem, RepresentedItem};
use crate::parameters::{Border, Parameters, TitleBar};
use crate::{
- Clipboard, Connection, ContextMenuItem, DeadKeyStatus, Dimensions, Handled, KeyCode, KeyEvent,
- Modifiers, MouseButtons, MouseCursor, MouseEvent, MouseEventKind, MousePress, Point,
+ Clipboard, Connection, ContextMenuItem, DeadKeyStatus, Dimensions, Handled, Image, KeyCode,
+ KeyEvent, Modifiers, MouseButtons, MouseCursor, MouseEvent, MouseEventKind, MousePress, Point,
RawKeyEvent, Rect, RequestedWindowGeometry, ResizeIncrement, ResolvedGeometry, ScreenPoint,
Size, ULength, WindowDecorations, WindowEvent, WindowEventSender, WindowOps, WindowState,
};
@@ -18,8 +19,9 @@ use async_trait::async_trait;
use cocoa::appkit::{
self, CGFloat, NSApplication, NSApplicationActivateIgnoringOtherApps,
NSApplicationPresentationOptions, NSBackingStoreBuffered, NSEvent, NSEventModifierFlags,
- NSOpenGLContext, NSOpenGLPixelFormat, NSPasteboard, NSRunningApplication, NSScreen, NSView,
- NSViewHeightSizable, NSViewWidthSizable, NSWindow, NSWindowStyleMask,
+ NSImage, NSImageNameApplicationIcon, NSOpenGLContext, NSOpenGLPixelFormat, NSPasteboard,
+ NSRunningApplication, NSScreen, NSView, NSViewHeightSizable, NSViewWidthSizable, NSWindow,
+ NSWindowStyleMask,
};
use cocoa::base::*;
use cocoa::foundation::{
@@ -33,6 +35,7 @@ use core_foundation::bundle::{CFBundleGetBundleWithIdentifier, CFBundleGetFuncti
use core_foundation::data::{CFData, CFDataGetBytePtr, CFDataRef};
use core_foundation::string::{CFString, CFStringRef, UniChar};
use core_foundation::{declare_TCFType, impl_TCFType};
+use foreign_types::ForeignType;
use objc::declare::ClassDecl;
use objc::rc::{StrongPtr, WeakPtr};
use objc::runtime::{Class, Object, Protocol, Sel};
@@ -45,7 +48,7 @@ use raw_window_handle::{
use std::any::Any;
use std::cell::RefCell;
use std::ffi::{c_void, CStr};
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
use std::ptr::NonNull;
use std::rc::Rc;
use std::str::FromStr;
@@ -57,6 +60,29 @@ use wezterm_input_types::{is_ascii_control, IntegratedTitleButtonStyle, Keyboard
const NSViewLayerContentsPlacementTopLeft: NSInteger = 11;
#[allow(non_upper_case_globals)]
const NSViewLayerContentsRedrawDuringViewResize: NSInteger = 2;
+const THINKTERM_TITLEBAR_SIDEBAR_BUTTON_FALLBACK_X: f64 = 96.0;
+const THINKTERM_TITLEBAR_SIDEBAR_BUTTON_FULLSCREEN_X: f64 = 22.0;
+const THINKTERM_TITLEBAR_SIDEBAR_BUTTON_GAP: f64 = 8.0;
+const THINKTERM_TITLEBAR_SIDEBAR_BUTTON_SIZE: f64 = 30.0;
+const THINKTERM_TITLEBAR_SIDEBAR_BUTTON_TAG: NSInteger = 0x7474_7362;
+
+pub fn set_application_icon_from_file(path: &Path) -> anyhow::Result<()> {
+ let path_string = path.to_string_lossy();
+
+ unsafe {
+ let ns_image = NSImage::alloc(nil).initWithContentsOfFile_(*nsstring(path_string.as_ref()));
+ if ns_image == nil {
+ bail!("failed to load application icon from {}", path.display());
+ }
+
+ let ns_image = StrongPtr::new(ns_image);
+ let _: BOOL = msg_send![*ns_image, setName:NSImageNameApplicationIcon];
+ let app = NSApplication::sharedApplication(nil);
+ app.setApplicationIconImage_(*ns_image);
+ }
+
+ Ok(())
+}
#[link(name = "CoreGraphics", kind = "framework")]
extern "C" {
@@ -374,6 +400,7 @@ pub(crate) struct WindowInner {
view: StrongPtr,
window: StrongPtr,
config: ConfigHandle,
+ titlebar_sidebar_button_visible: bool,
}
fn function_key_to_keycode(function_key: char) -> KeyCode {
@@ -634,6 +661,7 @@ impl Window {
window,
view,
config: config.clone(),
+ titlebar_sidebar_button_visible: false,
}));
inner.borrow_mut().window.replace(weak_window);
conn.windows
@@ -791,6 +819,34 @@ impl WindowOps for Window {
});
}
+ fn set_icon(&self, image: Image) {
+ let (width, height) = image.image_dimensions();
+ let bitmap = BitmapRef::with_image(&image);
+
+ unsafe {
+ let size = NSSize::new(width as CGFloat, height as CGFloat);
+ let ns_image: id = msg_send![
+ NSImage::alloc(nil),
+ initWithCGImage: bitmap.as_ptr()
+ size: size
+ ];
+
+ if ns_image != nil {
+ let ns_image = StrongPtr::new(ns_image);
+ let _: BOOL = msg_send![*ns_image, setName:NSImageNameApplicationIcon];
+ let app = NSApplication::sharedApplication(nil);
+ app.setApplicationIconImage_(*ns_image);
+ }
+ }
+ }
+
+ fn set_titlebar_sidebar_button_visible(&self, visible: bool) {
+ Connection::with_window_inner(self.id, move |inner| {
+ inner.set_titlebar_sidebar_button_visible(visible);
+ Ok(())
+ });
+ }
+
fn set_window_level(&self, level: WindowLevel) {
Connection::with_window_inner(self.id, move |inner| {
inner.set_window_level(level);
@@ -997,6 +1053,20 @@ impl WindowInner {
self.config.window_decorations,
self.config.integrated_title_button_style,
);
+ self.update_titlebar_sidebar_button();
+ }
+ }
+
+ fn set_titlebar_sidebar_button_visible(&mut self, visible: bool) {
+ self.titlebar_sidebar_button_visible = visible;
+ self.update_titlebar_sidebar_button();
+ }
+
+ fn update_titlebar_sidebar_button(&mut self) {
+ if self.titlebar_sidebar_button_visible {
+ install_thinkterm_titlebar_sidebar_button(&self.window, *self.view);
+ } else {
+ remove_thinkterm_titlebar_sidebar_button(&self.window);
}
}
@@ -1188,6 +1258,7 @@ impl WindowInner {
);
self.update_titlebar_background();
+ self.update_titlebar_sidebar_button();
self.window.makeKeyAndOrderFront_(nil)
}
@@ -1449,11 +1520,7 @@ fn apply_decorations_to_window(
let _: () = msg_send![button, setHidden: hidden];
}
- window.setTitleVisibility_(if decorations.contains(WindowDecorations::TITLE) {
- appkit::NSWindowTitleVisibility::NSWindowTitleVisible
- } else {
- appkit::NSWindowTitleVisibility::NSWindowTitleHidden
- });
+ window.setTitleVisibility_(appkit::NSWindowTitleVisibility::NSWindowTitleHidden);
if decorations.contains(WindowDecorations::INTEGRATED_BUTTONS)
|| decorations.contains(WindowDecorations::MACOS_USE_BACKGROUND_COLOR_AS_TITLEBAR_COLOR)
@@ -1465,6 +1532,161 @@ fn apply_decorations_to_window(
}
}
+fn install_thinkterm_titlebar_sidebar_button(window: &StrongPtr, target: id) {
+ unsafe {
+ let Some(titlebar_view_container) = get_titlebar_view_container(window) else {
+ return;
+ };
+ let titlebar_view_container = titlebar_view_container.load();
+ if titlebar_view_container.is_null() {
+ return;
+ }
+ let titlebar_view_container_id = *titlebar_view_container;
+ if let Some(button) = thinkterm_titlebar_sidebar_button(&titlebar_view_container) {
+ position_thinkterm_titlebar_sidebar_button(window, titlebar_view_container_id, button);
+ return;
+ }
+
+ let button: id = msg_send![
+ class!(NSButton),
+ buttonWithTitle: *nsstring("")
+ target: target
+ action: sel!(thinktermToggleWorkspaceSidebar:)
+ ];
+ if button.is_null() {
+ return;
+ }
+
+ position_thinkterm_titlebar_sidebar_button(window, titlebar_view_container_id, button);
+ let () = msg_send![button, setBordered: NO];
+ let () = msg_send![button, setBezelStyle: 0isize];
+ let () = msg_send![button, setImagePosition: 1isize];
+ let () = msg_send![button, setTag: THINKTERM_TITLEBAR_SIDEBAR_BUTTON_TAG];
+
+ let image_class = class!(NSImage);
+ let supports_symbol_images: BOOL = msg_send![
+ image_class,
+ respondsToSelector: sel!(imageWithSystemSymbolName:accessibilityDescription:)
+ ];
+ if supports_symbol_images == YES {
+ let image: id = msg_send![
+ image_class,
+ imageWithSystemSymbolName: *nsstring("sidebar.left")
+ accessibilityDescription: *nsstring("Toggle sidebar")
+ ];
+ if !image.is_null() {
+ let () = msg_send![button, setImage: image];
+ } else {
+ let () = msg_send![button, setTitle: *nsstring("▣")];
+ }
+ } else {
+ let () = msg_send![button, setTitle: *nsstring("▣")];
+ }
+
+ let () = msg_send![titlebar_view_container_id, addSubview: button];
+ }
+}
+
+fn position_thinkterm_titlebar_sidebar_button(
+ window: &StrongPtr,
+ titlebar_view_container_id: id,
+ button: id,
+) {
+ unsafe {
+ let titlebar_frame = NSView::frame(titlebar_view_container_id);
+ let zoom_button = window.standardWindowButton_(appkit::NSWindowButton::NSWindowZoomButton);
+ let is_fullscreen =
+ NSWindow::styleMask(**window).contains(NSWindowStyleMask::NSFullScreenWindowMask);
+ let zoom_button_hidden = if zoom_button.is_null() {
+ false
+ } else {
+ let hidden: BOOL = msg_send![zoom_button, isHidden];
+ hidden == YES
+ };
+ let x = if zoom_button.is_null() {
+ if is_fullscreen {
+ THINKTERM_TITLEBAR_SIDEBAR_BUTTON_FULLSCREEN_X
+ } else {
+ THINKTERM_TITLEBAR_SIDEBAR_BUTTON_FALLBACK_X
+ }
+ } else {
+ let zoom_frame = NSView::frame(zoom_button);
+ if zoom_button_hidden && zoom_frame.size.width <= 0.0 {
+ THINKTERM_TITLEBAR_SIDEBAR_BUTTON_FULLSCREEN_X
+ } else {
+ zoom_frame.origin.x + zoom_frame.size.width + THINKTERM_TITLEBAR_SIDEBAR_BUTTON_GAP
+ }
+ };
+ let y =
+ ((titlebar_frame.size.height - THINKTERM_TITLEBAR_SIDEBAR_BUTTON_SIZE) / 2.0).max(0.0);
+ let frame = NSRect::new(
+ NSPoint::new(x, y),
+ NSSize::new(
+ THINKTERM_TITLEBAR_SIDEBAR_BUTTON_SIZE,
+ THINKTERM_TITLEBAR_SIDEBAR_BUTTON_SIZE,
+ ),
+ );
+ let () = msg_send![button, setFrame: frame];
+ }
+}
+
+fn reposition_thinkterm_titlebar_sidebar_button_if_present(window: &StrongPtr) {
+ let Some(titlebar_view_container) = get_titlebar_view_container(window) else {
+ return;
+ };
+ let titlebar_view_container = titlebar_view_container.load();
+ if titlebar_view_container.is_null() {
+ return;
+ }
+
+ let Some(button) = thinkterm_titlebar_sidebar_button(&titlebar_view_container) else {
+ return;
+ };
+
+ position_thinkterm_titlebar_sidebar_button(window, *titlebar_view_container, button);
+}
+
+fn remove_thinkterm_titlebar_sidebar_button(window: &StrongPtr) {
+ unsafe {
+ let Some(titlebar_view_container) = get_titlebar_view_container(window) else {
+ return;
+ };
+ let titlebar_view_container = titlebar_view_container.load();
+ if titlebar_view_container.is_null() {
+ return;
+ }
+
+ let Some(button) = thinkterm_titlebar_sidebar_button(&titlebar_view_container) else {
+ return;
+ };
+ let () = msg_send![button, removeFromSuperview];
+ }
+}
+
+fn thinkterm_titlebar_sidebar_button(titlebar_view_container: &StrongPtr) -> Option<id> {
+ unsafe {
+ let Some(subviews) = get_view_subviews(titlebar_view_container) else {
+ return None;
+ };
+ let subviews = subviews.load();
+ let count = subviews.count();
+
+ for i in 0..count {
+ let subview: id = subviews.objectAtIndex(i);
+ if subview.is_null() {
+ continue;
+ }
+
+ let tag: NSInteger = msg_send![subview, tag];
+ if tag == THINKTERM_TITLEBAR_SIDEBAR_BUTTON_TAG {
+ return Some(subview);
+ }
+ }
+
+ None
+ }
+}
+
fn decoration_to_mask(
decorations: WindowDecorations,
integrated_title_button_style: IntegratedTitleButtonStyle,
@@ -2355,6 +2577,15 @@ impl WindowView {
}
}
+ extern "C" fn thinkterm_toggle_workspace_sidebar(this: &mut Object, _sel: Sel, _sender: id) {
+ if let Some(this) = Self::get_this(this) {
+ this.inner
+ .borrow_mut()
+ .events
+ .dispatch(WindowEvent::ToggleWorkspaceSidebar);
+ }
+ }
+
extern "C" fn window_will_close(this: &mut Object, _sel: Sel, _id: id) {
if let Some(this) = Self::get_this(this) {
// Advise the window of its impending death
@@ -3025,6 +3256,9 @@ impl WindowView {
(_, true) => WindowState::MAXIMIZED,
_ => WindowState::default(),
};
+ if let Some(window) = inner.window.as_ref() {
+ reposition_thinkterm_titlebar_sidebar_button_if_present(&window.load());
+ }
let dpi = inner
.window
@@ -3254,6 +3488,10 @@ impl WindowView {
Self::wezterm_perform_key_assignment
as extern "C" fn(&mut Object, Sel, *mut Object),
);
+ cls.add_method(
+ sel!(thinktermToggleWorkspaceSidebar:),
+ Self::thinkterm_toggle_workspace_sidebar as extern "C" fn(&mut Object, Sel, id),
+ );
cls.add_method(
sel!(windowWillClose:),