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.

many update

RoversX93806511f87e
diff --git a/Cargo.lock b/Cargo.lock
index 99632057..6e2e708a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -7474,6 +7474,7 @@ dependencies = [
"async-task",
"async-trait",
"bitflags 1.3.2",
+ "block2",
"bytes",
"cgl",
"clipboard-win",
diff --git a/config/src/keyassignment.rs b/config/src/keyassignment.rs
index 13723305..86afd627 100644
--- a/config/src/keyassignment.rs
+++ b/config/src/keyassignment.rs
@@ -575,6 +575,11 @@ pub enum KeyAssignment {
ShowTabNavigator,
PromptRenameTab,
PromptRenamePaneTab(usize),
+ PromptRenameProjectSession(String),
+ ToggleProjectSessionPinned(String),
+ ArchiveProjectSession(String),
+ DeleteProjectSession(String),
+ MarkProjectSessionUnread(String),
ShowDebugOverlay,
HideApplication,
QuitApplication,
diff --git a/mux/src/lib.rs b/mux/src/lib.rs
index b0ed3d3c..f27d9a8a 100644
--- a/mux/src/lib.rs
+++ b/mux/src/lib.rs
@@ -559,7 +559,7 @@ impl Mux {
.get_tab(tab_id)
.ok_or_else(|| anyhow::anyhow!("tab {tab_id} not found"))?;
- tab.set_active_pane(&pane);
+ tab.set_active_pane_silent(&pane);
Ok(())
}
@@ -1092,6 +1092,11 @@ impl Mux {
.unwrap_or_default()
}
+ pub fn pane_stack_id(&self, pane_id: PaneId) -> Option<crate::tab::PaneStackId> {
+ let (_domain_id, _window_id, tab_id) = self.resolve_pane_id(pane_id)?;
+ self.get_tab(tab_id)?.pane_stack_id(pane_id)
+ }
+
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)
diff --git a/mux/src/tab.rs b/mux/src/tab.rs
index 88f5725a..ed9e2d55 100644
--- a/mux/src/tab.rs
+++ b/mux/src/tab.rs
@@ -196,6 +196,8 @@ pub struct Tab {
#[derive(Clone)]
pub struct PositionedPane {
+ /// Stable identifier for the pane stack that owns this pane.
+ pub pane_stack_id: PaneStackId,
/// The topological pane index that can be used to reference this pane
pub index: usize,
/// true if this is the active pane at the time the position was computed
@@ -221,6 +223,7 @@ pub struct PositionedPane {
impl std::fmt::Debug for PositionedPane {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::result::Result<(), std::fmt::Error> {
fmt.debug_struct("PositionedPane")
+ .field("pane_stack_id", &self.pane_stack_id)
.field("index", &self.index)
.field("is_active", &self.is_active)
.field("left", &self.left)
@@ -771,6 +774,10 @@ impl Tab {
self.inner.lock().pane_stack_tabs(pane_id)
}
+ pub fn pane_stack_id(&self, pane_id: PaneId) -> Option<PaneStackId> {
+ self.inner.lock().pane_stack_id(pane_id)
+ }
+
pub fn pane_index_for_pane(&self, pane_id: PaneId) -> Option<usize> {
self.inner.lock().pane_index_for_pane(pane_id)
}
@@ -896,6 +903,10 @@ impl Tab {
self.inner.lock().set_active_pane(pane)
}
+ pub fn set_active_pane_silent(&self, pane: &Arc<dyn Pane>) {
+ self.inner.lock().set_active_pane_silent(pane)
+ }
+
pub fn set_active_idx(&self, pane_index: usize) {
self.inner.lock().set_active_idx(pane_index)
}
@@ -991,7 +1002,7 @@ impl TabInner {
let mut index = 0;
loop {
if let Some(stack) = cursor.leaf_mut() {
- if stack.set_active_pane(active.pane_id()) {
+ if stack.contains_pane(active.pane_id()) {
// Found it
self.active = index;
self.recency.tag(index);
@@ -1190,6 +1201,30 @@ impl TabInner {
tabs
}
+ fn pane_stack_id(&mut self, pane_id: PaneId) -> Option<PaneStackId> {
+ let mut pane_stack_id = None;
+ 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) {
+ pane_stack_id = Some(stack.id());
+ }
+ }
+
+ match cursor.preorder_next() {
+ Ok(c) if pane_stack_id.is_none() => cursor = c,
+ Ok(c) | Err(c) => {
+ self.pane.replace(c.tree());
+ break;
+ }
+ }
+ }
+
+ pane_stack_id
+ }
+
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;
@@ -1304,6 +1339,7 @@ impl TabInner {
if let Some(zoomed) = self.zoomed.as_ref() {
let size = self.size;
panes.push(PositionedPane {
+ pane_stack_id: zoomed.pane_id(),
index: 0,
is_active: true,
is_zoomed: true,
@@ -1348,8 +1384,10 @@ impl TabInner {
if let Some(pane) = cursor.leaf_mut().unwrap().active_pane() {
let dims = parent_size.unwrap_or_else(|| root_size);
+ let pane_stack_id = cursor.leaf_mut().unwrap().id();
panes.push(PositionedPane {
+ pane_stack_id,
index,
is_active: index == active_idx,
is_zoomed: zoomed_id == Some(pane.pane_id()),
@@ -2076,6 +2114,14 @@ impl TabInner {
}
fn set_active_pane(&mut self, pane: &Arc<dyn Pane>) {
+ self.set_active_pane_impl(pane, true);
+ }
+
+ fn set_active_pane_silent(&mut self, pane: &Arc<dyn Pane>) {
+ self.set_active_pane_impl(pane, false);
+ }
+
+ fn set_active_pane_impl(&mut self, pane: &Arc<dyn Pane>, notify_focus: bool) {
let prior = self.get_active_pane();
if is_pane(pane, &prior.as_ref()) {
@@ -2092,7 +2138,7 @@ impl TabInner {
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);
+ self.advise_focus_change_impl(prior, notify_focus);
}
}
@@ -2139,17 +2185,25 @@ impl TabInner {
}
fn advise_focus_change(&mut self, prior: Option<Arc<dyn Pane>>) {
+ self.advise_focus_change_impl(prior, true);
+ }
+
+ fn advise_focus_change_impl(&mut self, prior: Option<Arc<dyn Pane>>, notify_focus: bool) {
let mux = Mux::get();
let current = self.get_active_pane();
match (prior, current) {
(Some(prior), Some(current)) if prior.pane_id() != current.pane_id() => {
prior.focus_changed(false);
current.focus_changed(true);
- mux.notify(MuxNotification::PaneFocused(current.pane_id()));
+ if notify_focus {
+ mux.notify(MuxNotification::PaneFocused(current.pane_id()));
+ }
}
(None, Some(current)) => {
current.focus_changed(true);
- mux.notify(MuxNotification::PaneFocused(current.pane_id()));
+ if notify_focus {
+ mux.notify(MuxNotification::PaneFocused(current.pane_id()));
+ }
}
(Some(prior), None) => {
prior.focus_changed(false);
@@ -3112,6 +3166,30 @@ mod test {
assert!(tabs[1].is_active);
}
+ #[test]
+ fn sync_with_pane_tree_does_not_overwrite_stack_active_tab() {
+ let size = test_size();
+ let tab = Tab::new(&size);
+ let root = PaneNode::Stack(PaneStackEntry {
+ active: 1,
+ panes: vec![pane_entry(200, size, true), pane_entry(201, size, false)],
+ });
+
+ tab.sync_with_pane_tree(size, root, |entry| FakePane::new(entry.pane_id, entry.size));
+
+ let panes = tab.iter_panes();
+ assert_eq!(panes.len(), 1);
+ assert_eq!(panes[0].pane.pane_id(), 201);
+ assert!(panes[0].is_active);
+
+ let tabs = tab.pane_stack_tabs(201);
+ 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/wezterm-font/src/lib.rs b/wezterm-font/src/lib.rs
index a1bd4c88..f2d5fde7 100644
--- a/wezterm-font/src/lib.rs
+++ b/wezterm-font/src/lib.rs
@@ -607,7 +607,7 @@ impl FontConfigInner {
fonts.push(font);
}
- let font_size = if cfg!(windows) { 10. } else { 12. };
+ let font_size = if cfg!(windows) { 11. } else { 14. };
(
TextStyle {
diff --git a/wezterm-gui/src/commands.rs b/wezterm-gui/src/commands.rs
index 9fe1d35a..2614c793 100644
--- a/wezterm-gui/src/commands.rs
+++ b/wezterm-gui/src/commands.rs
@@ -840,6 +840,46 @@ pub fn derive_command_from_key_assignment(action: &KeyAssignment) -> Option<Comm
menubar: &[],
icon: Some("md_edit"),
},
+ PromptRenameProjectSession(_) => CommandDef {
+ brief: "Rename Session".into(),
+ doc: "Prompts for a new name for the ThinkTerm session".into(),
+ keys: vec![],
+ args: &[ArgType::ActiveWindow],
+ menubar: &[],
+ icon: Some("md_edit"),
+ },
+ ToggleProjectSessionPinned(_) => CommandDef {
+ brief: "Pin Session".into(),
+ doc: "Toggles the pinned state for the ThinkTerm session".into(),
+ keys: vec![],
+ args: &[ArgType::ActiveWindow],
+ menubar: &[],
+ icon: None,
+ },
+ ArchiveProjectSession(_) => CommandDef {
+ brief: "Archive Session".into(),
+ doc: "Archives the ThinkTerm session".into(),
+ keys: vec![],
+ args: &[ArgType::ActiveWindow],
+ menubar: &[],
+ icon: None,
+ },
+ DeleteProjectSession(_) => CommandDef {
+ brief: "Delete Session".into(),
+ doc: "Deletes the ThinkTerm session from the session store".into(),
+ keys: vec![],
+ args: &[ArgType::ActiveWindow],
+ menubar: &[],
+ icon: None,
+ },
+ MarkProjectSessionUnread(_) => CommandDef {
+ brief: "Mark Session as Unread".into(),
+ doc: "Marks the ThinkTerm session as unread".into(),
+ keys: vec![],
+ args: &[ArgType::ActiveWindow],
+ menubar: &[],
+ icon: None,
+ },
QuickSelect => CommandDef {
brief: "Enter QuickSelect mode".into(),
doc: "Activates the quick selection UI for the current pane".into(),
diff --git a/wezterm-gui/src/frontend.rs b/wezterm-gui/src/frontend.rs
index 4fc2285b..0f85e27a 100644
--- a/wezterm-gui/src/frontend.rs
+++ b/wezterm-gui/src/frontend.rs
@@ -80,6 +80,12 @@ impl GuiFrontEnd {
MuxNotification::PaneFocused(pane_id) => {
promise::spawn::spawn_into_main_thread(async move {
let mux = Mux::get();
+ if mux.get_pane(pane_id).is_none() {
+ log::debug!(
+ "Ignoring stale PaneFocused notification for missing pane {pane_id}"
+ );
+ return;
+ }
if let Err(err) = mux.focus_pane_and_containing_tab(pane_id) {
log::error!("Error reconciling PaneFocused notification: {err:#}");
}
diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rs
index ef90a6c5..e3535523 100644
--- a/wezterm-gui/src/main.rs
+++ b/wezterm-gui/src/main.rs
@@ -42,6 +42,7 @@ mod frontend;
mod glyphcache;
mod inputmap;
mod overlay;
+mod project_sessions;
mod quad;
mod renderstate;
mod resize_increment_calculator;
diff --git a/wezterm-gui/src/project_sessions.rs b/wezterm-gui/src/project_sessions.rs
new file mode 100644
index 00000000..45d8ea55
--- /dev/null
+++ b/wezterm-gui/src/project_sessions.rs
@@ -0,0 +1,1298 @@
+use anyhow::{ensure, Context, Result};
+use chrono::Utc;
+use config::keyassignment::SpawnTabDomain;
+use futures::future::LocalBoxFuture;
+use mux::domain::SplitSource;
+use mux::pane::PaneId;
+use mux::tab::{PaneEntry, PaneNode, PaneStackEntry, SplitDirection, SplitRequest, SplitSize};
+use mux::window::WindowId as MuxWindowId;
+use mux::Mux;
+use parking_lot::Mutex;
+use serde::{Deserialize, Serialize};
+use std::collections::HashMap;
+use std::fs;
+use std::io::Write;
+use std::path::{Path, PathBuf};
+use std::sync::Arc;
+use wezterm_term::TerminalConfiguration;
+use wezterm_term::TerminalSize;
+
+pub type ProjectId = String;
+pub type SessionId = String;
+
+#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
+pub struct SessionStore {
+ pub active_project_id: Option<ProjectId>,
+ pub projects: Vec<Project>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct Project {
+ pub id: ProjectId,
+ pub name: String,
+ pub path: PathBuf,
+ pub sessions: Vec<Session>,
+ pub active_session_id: Option<SessionId>,
+ #[serde(default)]
+ pub sessions_collapsed: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct Session {
+ pub id: SessionId,
+ pub name: String,
+ pub project_id: ProjectId,
+ pub layout: Option<SessionLayoutSnapshot>,
+ pub materialized_workspace_name: Option<String>,
+ pub last_active_at: i64,
+ #[serde(default)]
+ pub is_pinned: bool,
+ #[serde(default)]
+ pub is_unread: bool,
+ #[serde(default)]
+ pub archived: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct SessionLayoutSnapshot {
+ pub active_tab: usize,
+ pub tabs: Vec<serde_json::Value>,
+ #[serde(default)]
+ pub terminal_specs: Vec<TerminalSpecEntry>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct TerminalSpecEntry {
+ pub pane_id: PaneId,
+ pub spec: TerminalSpawnSpec,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct TerminalSpawnSpec {
+ pub cwd: Option<String>,
+ pub domain: Option<String>,
+ pub title: String,
+}
+
+#[derive(Debug, Clone)]
+pub struct ProjectSessionView {
+ pub projects: Vec<ProjectView>,
+}
+
+#[derive(Debug, Clone)]
+pub struct ProjectView {
+ pub id: ProjectId,
+ pub name: String,
+ pub is_active: bool,
+ pub sessions_collapsed: bool,
+ pub sessions: Vec<SessionView>,
+}
+
+#[derive(Debug, Clone)]
+pub struct SessionView {
+ pub id: SessionId,
+ pub name: String,
+ pub is_active: bool,
+ pub is_materialized: bool,
+ pub is_pinned: bool,
+ pub is_unread: bool,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ActivationPlan {
+ pub session_id: SessionId,
+ pub workspace_name: String,
+ pub project_path: PathBuf,
+ pub needs_materialize: bool,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct DeletedSession {
+ pub was_active: bool,
+ pub next_session_id: Option<SessionId>,
+ pub materialized_workspace_name: Option<String>,
+}
+
+lazy_static::lazy_static! {
+ static ref SESSION_STORE: Mutex<SessionStore> =
+ Mutex::new(load_session_store().unwrap_or_else(|err| {
+ log::warn!("failed to load ThinkTerm session store: {err:#}");
+ SessionStore::default()
+ }));
+}
+
+pub fn session_store_path() -> PathBuf {
+ config::DATA_DIR.join("thinkterm").join("sessions.json")
+}
+
+fn legacy_session_store_path() -> PathBuf {
+ config::CACHE_DIR.join("thinkterm").join("sessions.json")
+}
+
+pub fn load_session_store() -> Result<SessionStore> {
+ let path = session_store_path();
+ if path.exists() {
+ return load_session_store_from_path(&path);
+ }
+
+ let legacy_path = legacy_session_store_path();
+ if legacy_path.exists() {
+ let store = load_session_store_from_path(&legacy_path)?;
+ if let Err(err) = save_session_store_to_path(&path, &store) {
+ log::warn!(
+ "failed to migrate ThinkTerm session store from {} to {}: {err:#}",
+ legacy_path.display(),
+ path.display()
+ );
+ }
+ return Ok(store);
+ }
+
+ Ok(SessionStore::default())
+}
+
+pub fn load_session_store_from_path(path: &Path) -> Result<SessionStore> {
+ if !path.exists() {
+ return Ok(SessionStore::default());
+ }
+ let file = fs::File::open(path).with_context(|| format!("open {}", path.display()))?;
+ serde_json::from_reader(file).with_context(|| format!("parse {}", path.display()))
+}
+
+pub fn save_session_store(store: &SessionStore) -> Result<()> {
+ save_session_store_to_path(&session_store_path(), store)
+}
+
+pub fn save_session_store_to_path(path: &Path, store: &SessionStore) -> Result<()> {
+ if let Some(parent) = path.parent() {
+ fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
+ let mut file = tempfile::NamedTempFile::new_in(parent)
+ .with_context(|| format!("create temporary session store in {}", parent.display()))?;
+ serde_json::to_writer_pretty(&mut file, store)
+ .with_context(|| format!("write {}", path.display()))?;
+ file.flush()
+ .with_context(|| format!("flush {}", path.display()))?;
+ file.as_file()
+ .sync_all()
+ .with_context(|| format!("sync {}", path.display()))?;
+ file.persist(path)
+ .with_context(|| format!("replace {}", path.display()))?;
+ return Ok(());
+ }
+
+ let mut file = fs::File::create(path).with_context(|| format!("create {}", path.display()))?;
+ serde_json::to_writer_pretty(&mut file, store)
+ .with_context(|| format!("write {}", path.display()))?;
+ file.flush()
+ .with_context(|| format!("flush {}", path.display()))?;
+ file.sync_all()
+ .with_context(|| format!("sync {}", path.display()))
+}
+
+pub fn current_project_from_cwd() -> Project {
+ let path = std::env::current_dir().unwrap_or_else(|_| config::HOME_DIR.to_path_buf());
+ let name = path
+ .file_name()
+ .and_then(|name| name.to_str())
+ .filter(|name| !name.is_empty())
+ .unwrap_or("Home")
+ .to_string();
+ let id = project_id_for_path(&path);
+ Project {
+ id,
+ name,
+ path,
+ sessions: vec![],
+ active_session_id: None,
+ sessions_collapsed: false,
+ }
+}
+
+pub fn view_for_current_project(
+ active_workspace: &str,
+ live_workspaces: &[String],
+) -> ProjectSessionView {
+ let mut store = SESSION_STORE.lock();
+ let (project_id, mut changed) =
+ if let Some(project_id) = store.project_id_for_workspace(active_workspace) {
+ if store.active_project_id.as_deref() != Some(&project_id) {
+ store.active_project_id = Some(project_id.clone());
+ (project_id, true)
+ } else {
+ (project_id, false)
+ }
+ } else {
+ store.ensure_current_project(active_workspace)
+ };
+ changed |= store.sync_active_workspace(&project_id, active_workspace);
+ let view = store.view_for_project(&project_id, live_workspaces);
+ if changed {
+ persist_locked(&store);
+ }
+ view
+}
+
+pub fn create_session(project_id: &str, name: Option<String>) -> SessionId {
+ let mut store = SESSION_STORE.lock();
+ let session_id = store.create_session(project_id, name);
+ persist_locked(&store);
+ session_id
+}
+
+pub fn create_project_from_path(path: &str) -> Result<SessionId> {
+ let path = normalize_project_path(path)?;
+ let mut store = SESSION_STORE.lock();
+ let session_id = store.create_project_from_path(path);
+ persist_locked(&store);
+ Ok(session_id)
+}
+
+pub fn active_session_for_project(project_id: &str) -> Option<SessionId> {
+ let mut store = SESSION_STORE.lock();
+ let session_id = store.active_session_for_project(project_id);
+ if session_id.is_some() {
+ persist_locked(&store);
+ }
+ session_id
+}
+
+pub fn activate_session_record(
+ session_id: &str,
+ live_workspaces: &[String],
+) -> Option<ActivationPlan> {
+ let mut store = SESSION_STORE.lock();
+ let plan = store.activate_session_record(session_id, live_workspaces);
+ persist_locked(&store);
+ plan
+}
+
+pub fn snapshot_workspace_layout(workspace: &str, window_id: MuxWindowId) {
+ let Some(snapshot) = snapshot_window_layout(window_id) else {
+ return;
+ };
+
+ let mut store = SESSION_STORE.lock();
+ store.snapshot_workspace_layout(workspace, snapshot);
+ persist_locked(&store);
+}
+
+pub fn snapshot_active_session_layout(window_id: MuxWindowId) {
+ let workspace = Mux::get().active_workspace();
+ snapshot_workspace_layout(&workspace, window_id);
+}
+
+pub async fn materialize_session(
+ workspace_name: String,
+ layout: Option<SessionLayoutSnapshot>,
+ initial_cwd: Option<String>,
+ size: TerminalSize,
+ src_window_id: Option<MuxWindowId>,
+ term_config: Arc<dyn TerminalConfiguration>,
+) -> Result<()> {
+ let mux = Mux::get();
+ if !mux.iter_windows_in_workspace(&workspace_name).is_empty() {
+ return Ok(());
+ }
+
+ let layout = layout.and_then(|layout| {
+ if layout.tabs.is_empty() {
+ None
+ } else {
+ Some(layout)
+ }
+ });
+ if let Some(layout) = layout {
+ materialize_layout(mux, workspace_name, layout, initial_cwd, size, term_config).await
+ } else {
+ let (_tab, pane, _window_id) = mux
+ .spawn_tab_or_window(
+ None,
+ SpawnTabDomain::DefaultDomain,
+ None,
+ initial_cwd,
+ size,
+ None,
+ workspace_name,
+ None,
+ )
+ .await
+ .context("spawn default session window")?;
+ pane.set_config(term_config);
+ let _ = src_window_id;
+ Ok(())
+ }
+}
+
+pub fn session_layout(session_id: &str) -> Option<SessionLayoutSnapshot> {
+ let store = SESSION_STORE.lock();
+ store
+ .projects
+ .iter()
+ .flat_map(|project| project.sessions.iter())
+ .find(|session| session.id == session_id)
+ .and_then(|session| session.layout.clone())
+}
+
+pub fn session_name(session_id: &str) -> Option<String> {
+ let store = SESSION_STORE.lock();
+ store
+ .projects
+ .iter()
+ .flat_map(|project| project.sessions.iter())
+ .find(|session| session.id == session_id)
+ .map(|session| session.name.clone())
+}
+
+pub fn rename_session(session_id: &str, name: String) -> bool {
+ let mut store = SESSION_STORE.lock();
+ let changed = store.rename_session(session_id, name);
+ if changed {
+ persist_locked(&store);
+ }
+ changed
+}
+
+pub fn toggle_session_pinned(session_id: &str) -> bool {
+ let mut store = SESSION_STORE.lock();
+ let changed = store.toggle_session_pinned(session_id);
+ if changed {
+ persist_locked(&store);
+ }
+ changed
+}
+
+pub fn mark_session_unread(session_id: &str) -> bool {
+ let mut store = SESSION_STORE.lock();
+ let changed = store.mark_session_unread(session_id);
+ if changed {
+ persist_locked(&store);
+ }
+ changed
+}
+
+pub fn archive_session(session_id: &str) -> bool {
+ let mut store = SESSION_STORE.lock();
+ let changed = store.archive_session(session_id);
+ if changed {
+ persist_locked(&store);
+ }
+ changed
+}
+
+pub fn delete_session(session_id: &str) -> Option<DeletedSession> {
+ let mut store = SESSION_STORE.lock();
+ let deleted = store.delete_session(session_id);
+ if deleted.is_some() {
+ persist_locked(&store);
+ }
+ deleted
+}
+
+pub fn toggle_project_sessions_collapsed(project_id: &str) -> bool {
+ let mut store = SESSION_STORE.lock();
+ let changed = store.toggle_project_sessions_collapsed(project_id);
+ if changed {
+ persist_locked(&store);
+ }
+ changed
+}
+
+fn session_views_for_project(
+ project: &Project,
+ active_project_id: Option<&str>,
+ live_workspaces: &[String],
+) -> Vec<SessionView> {
+ let project_is_active = active_project_id == Some(project.id.as_str());
+ project
+ .sessions
+ .iter()
+ .filter(|session| !session.archived)
+ .map(|session| {
+ let is_materialized = session
+ .materialized_workspace_name
+ .as_ref()
+ .map(|workspace| live_workspaces.iter().any(|live| live == workspace))
+ .unwrap_or(false);
+ SessionView {
+ id: session.id.clone(),
+ name: session.name.clone(),
+ is_active: project_is_active
+ && project.active_session_id.as_deref() == Some(&session.id),
+ is_materialized,
+ is_pinned: session.is_pinned,
+ is_unread: session.is_unread,
+ }
+ })
+ .collect()
+}
+
+impl SessionStore {
+ fn ensure_current_project(&mut self, active_workspace: &str) -> (ProjectId, bool) {
+ let current = current_project_from_cwd();
+ let (project_id, mut changed) =
+ if let Some(project) = self.projects.iter().find(|p| p.path == current.path) {
+ (project.id.clone(), false)
+ } else {
+ let mut project = current;
+ let session = Session::new(
+ project.id.clone(),
+ "main".to_string(),
+ Some(active_workspace.to_string()),
+ );
+ project.active_session_id = Some(session.id.clone());
+ project.sessions.push(session);
+ let project_id = project.id.clone();
+ self.projects.push(project);
+ (project_id, true)
+ };
+ if self.active_project_id.as_deref() != Some(&project_id) {
+ self.active_project_id = Some(project_id.clone());
+ changed = true;
+ }
+ (project_id, changed)
+ }
+
+ fn view_for_project(&self, project_id: &str, live_workspaces: &[String]) -> ProjectSessionView {
+ let active_project_id = self.active_project_id.as_deref().unwrap_or(project_id);
+ let projects = self
+ .projects
+ .iter()
+ .map(|project| ProjectView {
+ id: project.id.clone(),
+ name: project.name.clone(),
+ is_active: project.id == active_project_id,
+ sessions_collapsed: project.sessions_collapsed,
+ sessions: session_views_for_project(
+ project,
+ Some(active_project_id),
+ live_workspaces,
+ ),
+ })
+ .collect();
+ ProjectSessionView { projects }
+ }
+
+ fn sync_active_workspace(&mut self, project_id: &str, active_workspace: &str) -> bool {
+ let Some(project) = self.projects.iter_mut().find(|p| p.id == project_id) else {
+ return false;
+ };
+ if let Some(session) = project.sessions.iter().find(|session| {
+ session.materialized_workspace_name.as_deref() == Some(active_workspace)
+ }) {
+ if project.active_session_id.as_deref() != Some(&session.id) {
+ project.active_session_id = Some(session.id.clone());
+ return true;
+ }
+ return false;
+ }
+
+ let active_id = project
+ .active_session_id
+ .clone()
+ .or_else(|| project.sessions.first().map(|session| session.id.clone()));
+ if let Some(active_id) = active_id {
+ if let Some(session) = project
+ .sessions
+ .iter_mut()
+ .find(|session| session.id == active_id)
+ {
+ let mut changed = false;
+ if session.materialized_workspace_name.as_deref() != Some(active_workspace) {
+ session.materialized_workspace_name = Some(active_workspace.to_string());
+ changed = true;
+ }
+ if project.active_session_id.as_deref() != Some(&session.id) {
+ project.active_session_id = Some(session.id.clone());
+ changed = true;
+ }
+ return changed;
+ }
+ }
+ false
+ }
+
+ fn create_session(&mut self, project_id: &str, name: Option<String>) -> SessionId {
+ let project = self
+ .projects
+ .iter_mut()
+ .find(|project| project.id == project_id)
+ .expect("project_id should exist before creating session");
+ let name = name.unwrap_or_else(|| format!("Session {}", project.sessions.len() + 1));
+ let session = Session::new(project.id.clone(), name, None);
+ let id = session.id.clone();
+ project.sessions.push(session);
+ id
+ }
+
+ fn create_project_from_path(&mut self, path: PathBuf) -> SessionId {
+ let project_id = project_id_for_path(&path);
+ if self.projects.iter().any(|project| project.path == path) {
+ return self
+ .active_session_for_project(&project_id)
+ .expect("existing project should have an active session");
+ }
+
+ let name = path
+ .file_name()
+ .and_then(|name| name.to_str())
+ .filter(|name| !name.is_empty())
+ .unwrap_or("Project")
+ .to_string();
+ let mut project = Project {
+ id: project_id.clone(),
+ name,
+ path,
+ sessions: vec![],
+ active_session_id: None,
+ sessions_collapsed: false,
+ };
+ let session = Session::new(project_id.clone(), "main".to_string(), None);
+ let session_id = session.id.clone();
+ project.active_session_id = Some(session_id.clone());
+ project.sessions.push(session);
+ self.active_project_id = Some(project_id);
+ self.projects.push(project);
+ session_id
+ }
+
+ fn project_id_for_workspace(&self, workspace: &str) -> Option<ProjectId> {
+ self.projects.iter().find_map(|project| {
+ project
+ .sessions
+ .iter()
+ .any(|session| {
+ session.materialized_workspace_name.as_deref() == Some(workspace)
+ || workspace_name_for_session(&project.id, &session.id) == workspace
+ })
+ .then(|| project.id.clone())
+ })
+ }
+
+ fn active_session_for_project(&mut self, project_id: &str) -> Option<SessionId> {
+ let project = self
+ .projects
+ .iter_mut()
+ .find(|project| project.id == project_id)?;
+ if project.active_session_id.as_ref().is_some_and(|active_id| {
+ project
+ .sessions
+ .iter()
+ .any(|session| !session.archived && &session.id == active_id)
+ }) {
+ self.active_project_id = Some(project.id.clone());
+ return project.active_session_id.clone();
+ }
+
+ let session_id = project
+ .sessions
+ .iter()
+ .find(|session| !session.archived)
+ .map(|session| session.id.clone())
+ .unwrap_or_else(|| {
+ let session = Session::new(project.id.clone(), "main".to_string(), None);
+ let session_id = session.id.clone();
+ project.sessions.push(session);
+ session_id
+ });
+ project.active_session_id = Some(session_id.clone());
+ self.active_project_id = Some(project.id.clone());
+ Some(session_id)
+ }
+
+ fn activate_session_record(
+ &mut self,
+ session_id: &str,
+ live_workspaces: &[String],
+ ) -> Option<ActivationPlan> {
+ let project = self.projects.iter_mut().find(|project| {
+ project
+ .sessions
+ .iter()
+ .any(|session| session.id == session_id)
+ })?;
+ let project_id = project.id.clone();
+ let session = project
+ .sessions
+ .iter_mut()
+ .find(|session| session.id == session_id)?;
+ let workspace_name = session
+ .materialized_workspace_name
+ .clone()
+ .unwrap_or_else(|| workspace_name_for_session(&project_id, &session.id));
+ let needs_materialize = !live_workspaces.iter().any(|live| live == &workspace_name);
+ session.materialized_workspace_name = Some(workspace_name.clone());
+ session.last_active_at = now_ts();
+ session.is_unread = false;
+ project.active_session_id = Some(session.id.clone());
+ self.active_project_id = Some(project.id.clone());
+ Some(ActivationPlan {
+ session_id: session.id.clone(),
+ workspace_name,
+ project_path: project.path.clone(),
+ needs_materialize,
+ })
+ }
+
+ fn snapshot_workspace_layout(&mut self, workspace: &str, snapshot: SessionLayoutSnapshot) {
+ for project in &mut self.projects {
+ for session in &mut project.sessions {
+ if session.materialized_workspace_name.as_deref() == Some(workspace) {
+ session.layout = Some(snapshot);
+ session.last_active_at = now_ts();
+ return;
+ }
+ }
+ }
+ }
+
+ fn rename_session(&mut self, session_id: &str, name: String) -> bool {
+ let name = name.trim();
+ if name.is_empty() {
+ return false;
+ }
+
+ for project in &mut self.projects {
+ if let Some(session) = project
+ .sessions
+ .iter_mut()
+ .find(|session| session.id == session_id)
+ {
+ if session.name == name {
+ return false;
+ }
+ session.name = name.to_string();
+ session.last_active_at = now_ts();
+ return true;
+ }
+ }
+ false
+ }
+
+ fn toggle_session_pinned(&mut self, session_id: &str) -> bool {
+ for project in &mut self.projects {
+ if let Some(session) = project
+ .sessions
+ .iter_mut()
+ .find(|session| session.id == session_id)
+ {
+ session.is_pinned = !session.is_pinned;
+ session.last_active_at = now_ts();
+ return true;
+ }
+ }
+ false
+ }
+
+ fn mark_session_unread(&mut self, session_id: &str) -> bool {
+ for project in &mut self.projects {
+ if let Some(session) = project
+ .sessions
+ .iter_mut()
+ .find(|session| session.id == session_id)
+ {
+ if session.is_unread {
+ return false;
+ }
+ session.is_unread = true;
+ return true;
+ }
+ }
+ false
+ }
+
+ fn archive_session(&mut self, session_id: &str) -> bool {
+ for project in &mut self.projects {
+ if project.active_session_id.as_deref() == Some(session_id) {
+ return false;
+ }
+ if let Some(session) = project
+ .sessions
+ .iter_mut()
+ .find(|session| session.id == session_id)
+ {
+ if session.archived {
+ return false;
+ }
+ session.archived = true;
+ session.last_active_at = now_ts();
+ return true;
+ }
+ }
+ false
+ }
+
+ fn delete_session(&mut self, session_id: &str) -> Option<DeletedSession> {
+ for project in &mut self.projects {
+ let Some(index) = project
+ .sessions
+ .iter()
+ .position(|session| session.id == session_id)
+ else {
+ continue;
+ };
+ if project.sessions.len() <= 1 {
+ return None;
+ }
+
+ let removed = project.sessions.remove(index);
+ let was_active = project.active_session_id.as_deref() == Some(session_id);
+ let next_session_id = if was_active {
+ let next_index = index.saturating_sub(1).min(project.sessions.len() - 1);
+ let next_id = project.sessions[next_index].id.clone();
+ project.active_session_id = Some(next_id.clone());
+ Some(next_id)
+ } else {
+ None
+ };
+
+ return Some(DeletedSession {
+ was_active,
+ next_session_id,
+ materialized_workspace_name: removed.materialized_workspace_name,
+ });
+ }
+ None
+ }
+
+ fn toggle_project_sessions_collapsed(&mut self, project_id: &str) -> bool {
+ let Some(project) = self
+ .projects
+ .iter_mut()
+ .find(|project| project.id == project_id)
+ else {
+ return false;
+ };
+ project.sessions_collapsed = !project.sessions_collapsed;
+ true
+ }
+}
+
+impl Session {
+ fn new(project_id: ProjectId, name: String, workspace: Option<String>) -> Self {
+ Self {
+ id: new_id("session"),
+ name,
+ project_id,
+ layout: None,
+ materialized_workspace_name: workspace,
+ last_active_at: now_ts(),
+ is_pinned: false,
+ is_unread: false,
+ archived: false,
+ }
+ }
+}
+
+fn persist_locked(store: &SessionStore) {
+ if let Err(err) = save_session_store(store) {
+ log::warn!("failed to save ThinkTerm session store: {err:#}");
+ }
+}
+
+fn snapshot_window_layout(window_id: MuxWindowId) -> Option<SessionLayoutSnapshot> {
+ let mux = Mux::get();
+ let window = mux.get_window(window_id)?;
+ let active_tab = window.get_active_idx();
+ let mut terminal_specs = vec![];
+ let tabs = window
+ .iter()
+ .filter_map(|tab| {
+ let tree = tab.codec_pane_tree();
+ collect_terminal_specs(&mux, &tree, &mut terminal_specs);
+ serde_json::to_value(tree).ok()
+ })
+ .collect::<Vec<_>>();
+ Some(SessionLayoutSnapshot {
+ active_tab,
+ tabs,
+ terminal_specs,
+ })
+}
+
+async fn materialize_layout(
+ mux: Arc<Mux>,
+ workspace_name: String,
+ layout: SessionLayoutSnapshot,
+ initial_cwd: Option<String>,
+ size: TerminalSize,
+ term_config: Arc<dyn TerminalConfiguration>,
+) -> Result<()> {
+ let terminal_specs = layout
+ .terminal_specs
+ .iter()
+ .map(|entry| (entry.pane_id, entry.spec.clone()))
+ .collect::<HashMap<_, _>>();
+ let mut window_id = None;
+ let mut spawned_tabs = 0usize;
+ for tab_value in &layout.tabs {
+ let node: PaneNode =
+ serde_json::from_value(tab_value.clone()).context("decode session tab layout")?;
+ let first_entry = first_pane_entry(&node);
+ let cwd = first_entry
+ .and_then(|entry| working_dir_for_entry(entry, &terminal_specs))
+ .or_else(|| initial_cwd.clone());
+ let domain = first_entry
+ .map(|entry| spawn_domain_for_entry(&mux, entry, &terminal_specs, true))
+ .unwrap_or(SpawnTabDomain::DefaultDomain);
+ let (_tab, pane, win_id) = mux
+ .spawn_tab_or_window(
+ window_id,
+ domain,
+ None,
+ cwd,
+ node.root_size().unwrap_or(size),
+ None,
+ workspace_name.clone(),
+ None,
+ )
+ .await
+ .context("spawn session tab")?;
+ pane.set_config(Arc::clone(&term_config));
+ window_id = Some(win_id);
+ restore_node(
+ Arc::clone(&mux),
+ pane.pane_id(),
+ &node,
+ &terminal_specs,
+ Arc::clone(&term_config),
+ )
+ .await?;
+ spawned_tabs += 1;
+ }
+
+ if let Some(win_id) = window_id {
+ if let Some(mut window) = mux.get_window_mut(win_id) {
+ if spawned_tabs > 0 {
+ window.set_active_without_saving(layout.active_tab.min(spawned_tabs - 1));
+ }
+ }
+ }
+
+ Ok(())
+}
+
+fn restore_node<'a>(
+ mux: Arc<Mux>,
+ base_pane_id: PaneId,
+ node: &'a PaneNode,
+ terminal_specs: &'a HashMap<PaneId, TerminalSpawnSpec>,
+ term_config: Arc<dyn TerminalConfiguration>,
+) -> LocalBoxFuture<'a, Result<()>> {
+ Box::pin(async move {
+ match node {
+ PaneNode::Empty | PaneNode::Leaf(_) => {}
+ PaneNode::Stack(stack) => {
+ restore_stack(mux, base_pane_id, stack, terminal_specs, term_config).await?;
+ }
+ PaneNode::Split { left, right, node } => {
+ let right_entry = first_pane_entry(right);
+ let request = SplitRequest {
+ direction: node.direction,
+ target_is_second: true,
+ top_level: false,
+ size: SplitSize::Percent(split_second_percent(
+ node.direction,
+ node.first,
+ node.second,
+ )),
+ };
+ let (right_pane, _size) = mux
+ .split_pane(
+ base_pane_id,
+ request,
+ SplitSource::Spawn {
+ command: None,
+ command_dir: right_entry
+ .and_then(|entry| working_dir_for_entry(entry, terminal_specs)),
+ },
+ right_entry
+ .map(|entry| spawn_domain_for_entry(&mux, entry, terminal_specs, false))
+ .unwrap_or(SpawnTabDomain::CurrentPaneDomain),
+ )
+ .await
+ .context("restore split pane")?;
+ right_pane.set_config(Arc::clone(&term_config));
+ restore_node(
+ Arc::clone(&mux),
+ base_pane_id,
+ left,
+ terminal_specs,
+ Arc::clone(&term_config),
+ )
+ .await?;
+ restore_node(
+ mux,
+ right_pane.pane_id(),
+ right,
+ terminal_specs,
+ term_config,
+ )
+ .await?;
+ }
+ }
+ Ok(())
+ })
+}
+
+async fn restore_stack(
+ mux: Arc<Mux>,
+ base_pane_id: PaneId,
+ stack: &PaneStackEntry,
+ terminal_specs: &HashMap<PaneId, TerminalSpawnSpec>,
+ term_config: Arc<dyn TerminalConfiguration>,
+) -> Result<()> {
+ let mut pane_ids = vec![base_pane_id];
+ for entry in stack.panes.iter().skip(1) {
+ let pane = mux
+ .spawn_pane_in_stack(
+ base_pane_id,
+ spawn_domain_for_entry(&mux, entry, terminal_specs, false),
+ None,
+ working_dir_for_entry(entry, terminal_specs),
+ entry.size,
+ )
+ .await
+ .context("restore pane-local tab")?;
+ pane.set_config(Arc::clone(&term_config));
+ pane_ids.push(pane.pane_id());
+ }
+
+ if let Some(pane_id) = pane_ids.get(stack.active).copied() {
+ let _ = mux.activate_pane_in_stack(pane_id);
+ }
+ Ok(())
+}
+
+fn split_second_percent(
+ direction: SplitDirection,
+ first: TerminalSize,
+ second: TerminalSize,
+) -> u8 {
+ let (first, second) = match direction {
+ SplitDirection::Horizontal => (first.cols, second.cols),
+ SplitDirection::Vertical => (first.rows, second.rows),
+ };
+ let total = first.saturating_add(second).max(1);
+ ((second.saturating_mul(100) / total).clamp(5, 95)) as u8
+}
+
+fn working_dir_from_entry(entry: &PaneEntry) -> Option<String> {
+ entry
+ .working_dir
+ .as_ref()
+ .and_then(|url| url.url.to_file_path().ok())
+ .and_then(|path| path.to_str().map(|path| path.to_string()))
+}
+
+fn collect_terminal_specs(mux: &Mux, node: &PaneNode, terminal_specs: &mut Vec<TerminalSpecEntry>) {
+ match node {
+ PaneNode::Empty => {}
+ PaneNode::Leaf(entry) => collect_terminal_spec(mux, entry, terminal_specs),
+ PaneNode::Stack(stack) => {
+ for entry in &stack.panes {
+ collect_terminal_spec(mux, entry, terminal_specs);
+ }
+ }
+ PaneNode::Split { left, right, .. } => {
+ collect_terminal_specs(mux, left, terminal_specs);
+ collect_terminal_specs(mux, right, terminal_specs);
+ }
+ }
+}
+
+fn collect_terminal_spec(
+ mux: &Mux,
+ entry: &PaneEntry,
+ terminal_specs: &mut Vec<TerminalSpecEntry>,
+) {
+ let domain = mux
+ .get_pane(entry.pane_id)
+ .and_then(|pane| mux.get_domain(pane.domain_id()))
+ .map(|domain| domain.domain_name().to_string());
+ terminal_specs.push(TerminalSpecEntry {
+ pane_id: entry.pane_id,
+ spec: TerminalSpawnSpec {
+ cwd: working_dir_from_entry(entry),
+ domain,
+ title: entry.title.clone(),
+ },
+ });
+}
+
+fn first_pane_entry(node: &PaneNode) -> Option<&PaneEntry> {
+ match node {
+ PaneNode::Empty => None,
+ PaneNode::Leaf(entry) => Some(entry),
+ PaneNode::Stack(stack) => stack.panes.first(),
+ PaneNode::Split { left, .. } => first_pane_entry(left),
+ }
+}
+
+fn working_dir_for_entry(
+ entry: &PaneEntry,
+ terminal_specs: &HashMap<PaneId, TerminalSpawnSpec>,
+) -> Option<String> {
+ terminal_specs
+ .get(&entry.pane_id)
+ .and_then(|spec| spec.cwd.clone())
+ .or_else(|| working_dir_from_entry(entry))
+}
+
+fn spawn_domain_for_entry(
+ mux: &Mux,
+ entry: &PaneEntry,
+ terminal_specs: &HashMap<PaneId, TerminalSpawnSpec>,
+ default_if_missing: bool,
+) -> SpawnTabDomain {
+ terminal_specs
+ .get(&entry.pane_id)
+ .and_then(|spec| spec.domain.as_deref())
+ .filter(|domain| mux.get_domain_by_name(domain).is_some())
+ .map(|domain| SpawnTabDomain::DomainName(domain.to_string()))
+ .unwrap_or(if default_if_missing {
+ SpawnTabDomain::DefaultDomain
+ } else {
+ SpawnTabDomain::CurrentPaneDomain
+ })
+}
+
+fn project_id_for_path(path: &Path) -> ProjectId {
+ let mut hash = 0xcbf29ce484222325u64;
+ for byte in path.as_os_str().to_string_lossy().bytes() {
+ hash ^= byte as u64;
+ hash = hash.wrapping_mul(0x100000001b3);
+ }
+ format!("project-{hash:x}")
+}
+
+fn normalize_project_path(path: &str) -> Result<PathBuf> {
+ let trimmed = path.trim();
+ ensure!(!trimmed.is_empty(), "project path is empty");
+
+ let expanded = if trimmed == "~" {
+ config::HOME_DIR.to_path_buf()
+ } else if let Some(rest) = trimmed.strip_prefix("~/") {
+ config::HOME_DIR.join(rest)
+ } else {
+ let path = PathBuf::from(trimmed);
+ if path.is_absolute() {
+ path
+ } else {
+ std::env::current_dir()
+ .unwrap_or_else(|_| config::HOME_DIR.to_path_buf())
+ .join(path)
+ }
+ };
+
+ let canonical =
+ fs::canonicalize(&expanded).with_context(|| format!("open {}", expanded.display()))?;
+ ensure!(
+ canonical.is_dir(),
+ "project path is not a directory: {}",
+ canonical.display()
+ );
+ Ok(canonical)
+}
+
+fn workspace_name_for_session(project_id: &str, session_id: &str) -> String {
+ format!("thinkterm:{project_id}:{session_id}")
+}
+
+fn new_id(prefix: &str) -> String {
+ format!(
+ "{prefix}-{}-{:08x}",
+ Utc::now().timestamp_millis(),
+ fastrand::u32(..)
+ )
+}
+
+fn now_ts() -> i64 {
+ Utc::now().timestamp()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use tempfile::tempdir;
+
+ #[test]
+ fn session_store_round_trip() {
+ let dir = tempdir().unwrap();
+ let path = dir.path().join("sessions.json");
+ let mut store = SessionStore::default();
+ let project = Project {
+ id: "project-1".to_string(),
+ name: "thinkterm".to_string(),
+ path: PathBuf::from("/tmp/thinkterm"),
+ sessions: vec![Session::new(
+ "project-1".to_string(),
+ "main".to_string(),
+ None,
+ )],
+ active_session_id: None,
+ sessions_collapsed: false,
+ };
+ store.active_project_id = Some(project.id.clone());
+ store.projects.push(project);
+ save_session_store_to_path(&path, &store).unwrap();
+ let loaded = load_session_store_from_path(&path).unwrap();
+ assert_eq!(loaded.projects[0].path, PathBuf::from("/tmp/thinkterm"));
+ assert_eq!(loaded.projects[0].sessions[0].name, "main");
+ }
+
+ #[test]
+ fn inactive_session_activation_materializes_once() {
+ let mut store = SessionStore::default();
+ let project = Project {
+ id: "project-1".to_string(),
+ name: "thinkterm".to_string(),
+ path: PathBuf::from("/tmp/thinkterm"),
+ sessions: vec![Session::new(
+ "project-1".to_string(),
+ "main".to_string(),
+ None,
+ )],
+ active_session_id: None,
+ sessions_collapsed: false,
+ };
+ let session_id = project.sessions[0].id.clone();
+ store.projects.push(project);
+
+ let plan = store.activate_session_record(&session_id, &[]).unwrap();
+ assert!(plan.needs_materialize);
+ let plan = store
+ .activate_session_record(&session_id, &[plan.workspace_name.clone()])
+ .unwrap();
+ assert!(!plan.needs_materialize);
+ }
+
+ #[test]
+ fn created_project_gets_own_workspace_and_cwd() {
+ let dir = tempdir().unwrap();
+ let mut store = SessionStore::default();
+
+ let session_id = store.create_project_from_path(dir.path().to_path_buf());
+ let project_id = store.active_project_id.clone().unwrap();
+ let workspace_name = workspace_name_for_session(&project_id, &session_id);
+
+ assert_eq!(
+ store.project_id_for_workspace(&workspace_name),
+ Some(project_id.clone())
+ );
+
+ let plan = store.activate_session_record(&session_id, &[]).unwrap();
+ assert!(plan.needs_materialize);
+ assert_eq!(plan.project_path, dir.path());
+ assert_eq!(plan.workspace_name, workspace_name);
+ }
+
+ #[test]
+ fn snapshot_layout_attaches_to_materialized_session() {
+ let mut store = SessionStore::default();
+ let mut session = Session::new(
+ "project-1".to_string(),
+ "main".to_string(),
+ Some("ws".to_string()),
+ );
+ let session_id = session.id.clone();
+ let project = Project {
+ id: "project-1".to_string(),
+ name: "thinkterm".to_string(),
+ path: PathBuf::from("/tmp/thinkterm"),
+ sessions: vec![session.clone()],
+ active_session_id: Some(session_id),
+ sessions_collapsed: false,
+ };
+ store.projects.push(project);
+ store.snapshot_workspace_layout(
+ "ws",
+ SessionLayoutSnapshot {
+ active_tab: 0,
+ tabs: vec![serde_json::json!({"kind": "test"})],
+ terminal_specs: vec![],
+ },
+ );
+ session = store.projects[0].sessions[0].clone();
+ assert_eq!(session.layout.unwrap().tabs.len(), 1);
+ }
+
+ #[test]
+ fn view_marks_only_global_active_project_session_active() {
+ let mut store = SessionStore::default();
+ let first = Session::new("project-1".to_string(), "main".to_string(), None);
+ let second = Session::new("project-2".to_string(), "current".to_string(), None);
+ let first_id = first.id.clone();
+ let second_id = second.id.clone();
+ store.projects.push(Project {
+ id: "project-1".to_string(),
+ name: "thinkterm".to_string(),
+ path: PathBuf::from("/tmp/thinkterm"),
+ sessions: vec![first],
+ active_session_id: Some(first_id),
+ sessions_collapsed: false,
+ });
+ store.projects.push(Project {
+ id: "project-2".to_string(),
+ name: "agent_dock".to_string(),
+ path: PathBuf::from("/tmp/agent_dock"),
+ sessions: vec![second],
+ active_session_id: Some(second_id),
+ sessions_collapsed: false,
+ });
+ store.active_project_id = Some("project-2".to_string());
+
+ let view = store.view_for_project("project-2", &[]);
+ assert!(!view.projects[0].is_active);
+ assert!(!view.projects[0].sessions[0].is_active);
+ assert!(view.projects[1].is_active);
+ assert!(view.projects[1].sessions[0].is_active);
+ }
+
+ #[test]
+ fn session_menu_metadata_actions_update_store() {
+ let mut store = SessionStore::default();
+ let mut first = Session::new("project-1".to_string(), "main".to_string(), None);
+ let second = Session::new("project-1".to_string(), "Session 2".to_string(), None);
+ let third = Session::new("project-1".to_string(), "Session 3".to_string(), None);
+ let first_id = first.id.clone();
+ let second_id = second.id.clone();
+ let third_id = third.id.clone();
+ first.is_unread = true;
+ store.projects.push(Project {
+ id: "project-1".to_string(),
+ name: "thinkterm".to_string(),
+ path: PathBuf::from("/tmp/thinkterm"),
+ sessions: vec![first, second, third],
+ active_session_id: Some(first_id.clone()),
+ sessions_collapsed: false,
+ });
+
+ assert!(store.rename_session(&second_id, "Review".to_string()));
+ assert!(store.toggle_session_pinned(&second_id));
+ assert!(store.mark_session_unread(&second_id));
+ assert!(store.archive_session(&second_id));
+ assert!(!store.archive_session(&first_id));
+ assert_eq!(
+ store
+ .delete_session(&third_id)
+ .unwrap()
+ .materialized_workspace_name,
+ None
+ );
+
+ let project = &store.projects[0];
+ let archived = project
+ .sessions
+ .iter()
+ .find(|session| session.id == second_id)
+ .unwrap();
+ assert_eq!(archived.name, "Review");
+ assert!(archived.is_pinned);
+ assert!(archived.is_unread);
+ assert!(archived.archived);
+
+ let view = store.view_for_project("project-1", &[]);
+ assert_eq!(view.projects[0].sessions.len(), 1);
+ assert_eq!(view.projects[0].sessions[0].id, first_id);
+ }
+}
diff --git a/wezterm-gui/src/tabbar.rs b/wezterm-gui/src/tabbar.rs
index dbf6e378..22d1e859 100644
--- a/wezterm-gui/src/tabbar.rs
+++ b/wezterm-gui/src/tabbar.rs
@@ -151,7 +151,11 @@ fn compute_tab_title(
if let Some(pane) = &tab.active_pane {
let mut title = if tab.tab_title.is_empty() {
- terminal_title_for_display(&pane.title).to_string()
+ if config.use_fancy_tab_bar {
+ "Terminal".to_string()
+ } else {
+ terminal_title_for_display(&pane.title).to_string()
+ }
} else {
tab.tab_title.clone()
};
diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs
index bb557923..19cb3a61 100644
--- a/wezterm-gui/src/termwindow/mod.rs
+++ b/wezterm-gui/src/termwindow/mod.rs
@@ -47,8 +47,8 @@ use mux::pane::{
};
use mux::renderable::RenderableDimensions;
use mux::tab::{
- PositionedPane, PositionedSplit, SplitDirection, SplitRequest, SplitSize as MuxSplitSize, Tab,
- TabId,
+ PaneStackId, PositionedPane, PositionedSplit, SplitDirection, SplitRequest,
+ SplitSize as MuxSplitSize, Tab, TabId,
};
use mux::window::WindowId as MuxWindowId;
use mux::{Mux, MuxNotification};
@@ -188,6 +188,7 @@ pub enum TermWindowNotif {
},
MuxNotification(MuxNotification),
EmitStatusUpdate,
+ OpenProjectPath(PathBuf),
Apply(Box<dyn FnOnce(&mut TermWindow) + Send + Sync>),
SwitchToMuxWindow(MuxWindowId),
SetInnerSize {
@@ -205,7 +206,14 @@ pub enum UIItemType {
pane_index: usize,
action: PaneNavAction,
},
- WorkspaceSidebar(String),
+ ProjectNew,
+ ProjectToggleSessions(String),
+ Project(String),
+ ProjectSession(String),
+ ProjectSessionArchive(String),
+ ProjectSessionNew(String),
+ WorkspaceSidebarScrollTrack,
+ WorkspaceSidebarScrollThumb,
WorkspaceSidebarBackground,
WorkspaceSidebarResize,
AboveScrollThumb,
@@ -224,6 +232,12 @@ pub enum PaneNavAction {
SplitDown,
}
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum TabWheelSurface {
+ Window,
+ PaneStack(PaneStackId),
+}
+
#[derive(Clone, Debug)]
enum InlineTabRenameTarget {
WindowTab(TabId),
@@ -627,6 +641,8 @@ pub struct TermWindow {
tab_bar_scroll_target: f32,
pane_nav_tab_scroll_offsets: HashMap<PaneId, f32>,
pane_nav_tab_scroll_targets: HashMap<PaneId, f32>,
+ tab_wheel_surface_lock: Option<(TabWheelSurface, Instant)>,
+ tab_wheel_direction_lock: Option<(TabWheelSurface, i16, Instant)>,
inline_tab_rename: Option<InlineTabRename>,
pane_tab_title_overrides: HashMap<PaneId, String>,
pub right_status: String,
@@ -681,6 +697,8 @@ pub struct TermWindow {
dragging: Option<(UIItem, MouseEvent)>,
workspace_sidebar_width: usize,
workspace_sidebar_collapsed: bool,
+ workspace_sidebar_scroll_offset: f32,
+ workspace_sidebar_scrollbar_visible_until: Option<Instant>,
modal: RefCell<Option<Rc<dyn Modal>>>,
@@ -961,6 +979,8 @@ impl TermWindow {
tab_bar_scroll_target: 0.0,
pane_nav_tab_scroll_offsets: HashMap::new(),
pane_nav_tab_scroll_targets: HashMap::new(),
+ tab_wheel_surface_lock: None,
+ tab_wheel_direction_lock: None,
inline_tab_rename: None,
pane_tab_title_overrides: HashMap::new(),
right_status: String::new(),
@@ -1037,6 +1057,8 @@ impl TermWindow {
dragging: None,
workspace_sidebar_width,
workspace_sidebar_collapsed: false,
+ workspace_sidebar_scroll_offset: 0.0,
+ workspace_sidebar_scrollbar_visible_until: None,
last_ui_item: None,
is_click_to_focus_window: false,
key_table_state: KeyTableState::default(),
@@ -1581,6 +1603,13 @@ impl TermWindow {
TermWindowNotif::EmitStatusUpdate => {
self.emit_status_event();
}
+ TermWindowNotif::OpenProjectPath(path) => {
+ let path = path.to_string_lossy();
+ match crate::project_sessions::create_project_from_path(path.as_ref()) {
+ Ok(session_id) => self.activate_project_session(session_id, window),
+ Err(err) => log::error!("failed to create ThinkTerm project: {err:#}"),
+ }
+ }
TermWindowNotif::GetSelectionForPane { pane_id, tx } => {
let mux = Mux::get();
let pane = mux
@@ -2683,6 +2712,44 @@ impl TermWindow {
self.update_title_impl();
}
+ fn prompt_rename_project_session(&mut self, session_id: String) {
+ let mux = Mux::get();
+ let tab = match mux.get_active_tab_for_window(self.mux_window_id) {
+ Some(tab) => tab,
+ None => return,
+ };
+
+ let initial_title = crate::project_sessions::session_name(&session_id).unwrap_or_default();
+ let description = "Rename Session".to_string();
+ let prompt = "Name: ".to_string();
+
+ let (overlay, future) = start_overlay(self, &tab, move |_tab_id, term| {
+ let line = crate::overlay::prompt::read_line_prompt_overlay(
+ term,
+ &description,
+ &prompt,
+ Some(&initial_title),
+ )?;
+ if let Some(line) = line {
+ crate::project_sessions::rename_session(&session_id, line);
+ }
+ Ok(())
+ });
+ self.assign_overlay(tab.tab_id(), overlay);
+ promise::spawn::spawn(future).detach();
+ }
+
+ pub(crate) fn prompt_create_project(&mut self, context: &dyn WindowOps) {
+ let Some(window) = self.window.as_ref().cloned() else {
+ return;
+ };
+ context.pick_folder_async(Box::new(move |path| {
+ if let Some(path) = path {
+ window.notify(TermWindowNotif::OpenProjectPath(path));
+ }
+ }));
+ }
+
fn finish_inline_tab_rename(&mut self, commit: bool) {
let rename = match self.inline_tab_rename.take() {
Some(rename) => rename,
@@ -3205,6 +3272,46 @@ impl TermWindow {
ShowTabNavigator => self.show_tab_navigator(),
PromptRenameTab => self.prompt_rename_current_tab(),
PromptRenamePaneTab(pane_id) => self.prompt_rename_pane_tab(*pane_id),
+ PromptRenameProjectSession(session_id) => {
+ self.prompt_rename_project_session(session_id.clone())
+ }
+ ToggleProjectSessionPinned(session_id) => {
+ crate::project_sessions::toggle_session_pinned(session_id);
+ if let Some(window) = window.as_ref() {
+ window.invalidate();
+ }
+ }
+ ArchiveProjectSession(session_id) => {
+ crate::project_sessions::archive_session(session_id);
+ if let Some(window) = window.as_ref() {
+ window.invalidate();
+ }
+ }
+ DeleteProjectSession(session_id) => {
+ if let Some(deleted) = crate::project_sessions::delete_session(session_id) {
+ if deleted.was_active {
+ if let (Some(next_session_id), Some(window)) =
+ (deleted.next_session_id, window.as_ref())
+ {
+ self.activate_project_session(next_session_id, window);
+ }
+ } else if let Some(workspace) = deleted.materialized_workspace_name {
+ let mux = Mux::get();
+ for window_id in mux.iter_windows_in_workspace(&workspace) {
+ mux.kill_window(window_id);
+ }
+ }
+ if let Some(window) = window.as_ref() {
+ window.invalidate();
+ }
+ }
+ }
+ MarkProjectSessionUnread(session_id) => {
+ crate::project_sessions::mark_session_unread(session_id);
+ if let Some(window) = window.as_ref() {
+ window.invalidate();
+ }
+ }
ShowDebugOverlay => self.show_debug_overlay(),
ShowLauncher => self.show_launcher(),
ShowLauncherArgs(args) => {
@@ -3987,6 +4094,7 @@ impl TermWindow {
{
let size = tab.get_size();
vec![PositionedPane {
+ pane_stack_id: pane.pane_id(),
index: 0,
is_active: true,
is_zoomed: false,
diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rs
index c86ec710..3876006c 100644
--- a/wezterm-gui/src/termwindow/mouseevent.rs
+++ b/wezterm-gui/src/termwindow/mouseevent.rs
@@ -1,10 +1,13 @@
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::ui::tokens::{
+ PANE_NAV_BUTTON_GAP, PANE_NAV_INSET, PANE_NAV_TAB_GAP, TAB_ROW_START_PADDING,
+ TAB_VERTICAL_PADDING, WINDOW_TAB_ACTION_RESERVED_WIDTH, WINDOW_TAB_GAP,
+};
use crate::termwindow::{
- GuiWin, MouseCapture, PaneNavAction, PositionedSplit, ScrollHit, TermWindowNotif, UIItem,
- UIItemType, TMB,
+ GuiWin, MouseCapture, PaneNavAction, PositionedSplit, ScrollHit, TabWheelSurface,
+ TermWindowNotif, UIItem, UIItemType, TMB,
};
use ::window::{
ContextMenuItem, MouseButtons as WMB, MouseCursor, MouseEvent, MouseEventKind as WMEK,
@@ -14,7 +17,7 @@ use config::keyassignment::{
ClipboardPasteSource, KeyAssignment, MouseEventTrigger, PaneDirection, SpawnCommand,
SpawnTabDomain, SplitPane, SplitSize,
};
-use config::MouseEventAltScreen;
+use config::{MouseEventAltScreen, TermConfig};
use mux::pane::{Pane, WithPaneLines};
use mux::tab::{PositionedPane, SplitDirection};
use mux::Mux;
@@ -23,13 +26,16 @@ use std::convert::TryInto;
use std::ops::Sub;
use std::rc::Rc;
use std::sync::Arc;
-use std::time::Duration;
+use std::time::{Duration, Instant};
use termwiz::hyperlink::Hyperlink;
use termwiz::surface::Line;
use wezterm_dynamic::ToDynamic;
use wezterm_term::input::{MouseButton, MouseEventKind as TMEK};
use wezterm_term::{ClickPosition, LastMouseClick, StableRowIndex};
+const TAB_WHEEL_SURFACE_LOCK_MS: u64 = 700;
+const TAB_WHEEL_DIRECTION_LOCK_MS: u64 = 140;
+
impl super::TermWindow {
fn tab_scroll_pixels(amount: i16) -> f32 {
let steps = amount.unsigned_abs().max(1) as f32;
@@ -41,6 +47,16 @@ impl super::TermWindow {
}
}
+ fn sidebar_scroll_pixels(amount: i16) -> f32 {
+ let steps = amount.unsigned_abs().max(1) as f32;
+ let delta = (steps * 6.0).min(42.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)
@@ -80,6 +96,14 @@ impl super::TermWindow {
}
}
+ pub(super) fn pane_nav_tab_left_inset(&self, pane_left: usize) -> usize {
+ if pane_left == 0 && self.workspace_sidebar_width() > 0 {
+ TAB_ROW_START_PADDING
+ } else {
+ PANE_NAV_INSET
+ }
+ }
+
pub(super) fn window_tab_viewport_width(&self) -> f32 {
let border = self.get_os_border();
let left_padding = self.window_tab_left_padding_pixels();
@@ -89,6 +113,11 @@ impl super::TermWindow {
.saturating_sub(self.tab_bar_left_edge())
.saturating_sub(border.right.get() as usize)
.saturating_sub(left_padding.max(0.0) as usize)
+ .saturating_sub(if self.config.use_fancy_tab_bar {
+ TAB_ROW_START_PADDING + WINDOW_TAB_ACTION_RESERVED_WIDTH
+ } else {
+ 0
+ })
.max(1) as f32
}
@@ -103,7 +132,13 @@ impl super::TermWindow {
}
let tab_width = self.window_tab_width_pixels();
- let total_width = tab_count as f32 * tab_width;
+ let tab_gap = if self.config.use_fancy_tab_bar {
+ WINDOW_TAB_GAP as f32
+ } else {
+ 0.0
+ };
+ let total_width =
+ tab_count as f32 * tab_width + tab_count.saturating_sub(1) as f32 * tab_gap;
let available_width = self.window_tab_viewport_width();
(total_width - available_width).max(0.0)
@@ -123,101 +158,202 @@ impl super::TermWindow {
}
}
- fn max_pane_nav_tab_scroll_offset(&self, pane_id: mux::pane::PaneId) -> f32 {
+ fn max_pane_nav_tab_scroll_offset_for_stack(&self, stack_id: mux::tab::PaneStackId) -> 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();
+ let Some(pos) = tab
+ .iter_panes_ignoring_zoom()
+ .into_iter()
+ .find(|pos| pos.pane_stack_id == stack_id)
+ else {
+ return 0.0;
+ };
+
+ let tab_count = Mux::get().pane_stack_tabs(pos.pane.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);
+ let content_width = pos.width as f32 * cell_width;
+ let pane_width = if pos.left == 0 && self.workspace_sidebar_width() > 0 {
+ content_width
+ + (self.padding_left_top().0 - self.workspace_sidebar_width() as f32).max(0.0)
+ } else {
+ content_width
+ };
+ let pane_left = pos.left;
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))
+ let button_size = nav_height
+ .saturating_sub(TAB_VERTICAL_PADDING * 2)
.max(icon_size);
let controls_width = (button_size + PANE_NAV_BUTTON_GAP)
.saturating_mul(2)
- .saturating_add(PANE_NAV_INSET * 2);
+ .saturating_add(PANE_NAV_INSET)
+ .saturating_add(self.pane_nav_tab_left_inset(pane_left));
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 tab_width = self.window_tab_width_pixels();
let total_width = tab_count as f32 * tab_width
- + tab_count.saturating_sub(1) as f32 * PANE_NAV_BUTTON_GAP as f32;
+ + tab_count.saturating_sub(1) as f32 * PANE_NAV_TAB_GAP as f32;
(total_width - viewport_width).max(0.0)
}
- fn scroll_pane_nav_tabs(
+ fn set_tab_wheel_surface_lock(&mut self, surface: TabWheelSurface) {
+ self.tab_wheel_surface_lock = Some((
+ surface,
+ std::time::Instant::now() + std::time::Duration::from_millis(TAB_WHEEL_SURFACE_LOCK_MS),
+ ));
+ }
+
+ fn locked_tab_wheel_surface(&self) -> Option<TabWheelSurface> {
+ let (surface, until) = self.tab_wheel_surface_lock?;
+ (until > Instant::now()).then_some(surface)
+ }
+
+ fn should_ignore_tab_wheel_amount(&mut self, surface: TabWheelSurface, amount: i16) -> bool {
+ let sign = amount.signum();
+ if sign == 0 {
+ return true;
+ }
+
+ let now = Instant::now();
+ if let Some((locked_surface, locked_sign, until)) = self.tab_wheel_direction_lock {
+ if locked_surface == surface
+ && until > now
+ && locked_sign != sign
+ && amount.unsigned_abs() <= 1
+ {
+ return true;
+ }
+ }
+
+ self.tab_wheel_direction_lock = Some((
+ surface,
+ sign,
+ now + Duration::from_millis(TAB_WHEEL_DIRECTION_LOCK_MS),
+ ));
+ false
+ }
+
+ pub(crate) fn tab_wheel_scroll_active(&self) -> bool {
+ self.locked_tab_wheel_surface().is_some()
+ || self
+ .pane_nav_tab_scroll_targets
+ .iter()
+ .any(|(stack_id, target)| {
+ let current = self
+ .pane_nav_tab_scroll_offsets
+ .get(stack_id)
+ .copied()
+ .unwrap_or(0.0);
+ (current - target).abs() > 0.75
+ })
+ }
+
+ fn scroll_pane_nav_stack_tabs(
&mut self,
- pane_id: mux::pane::PaneId,
+ stack_key: mux::tab::PaneStackId,
amount: i16,
context: &dyn WindowOps,
) {
- let current = self
- .pane_nav_tab_scroll_targets
- .get(&pane_id)
+ let max_offset = self.max_pane_nav_tab_scroll_offset_for_stack(stack_key);
+ let stored_offset = self
+ .pane_nav_tab_scroll_offsets
+ .get(&stack_key)
.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)
+ let current_offset = stored_offset.clamp(0.0, max_offset.max(0.0));
+ let needs_offset_clamp = (current_offset - stored_offset).abs() > f32::EPSILON;
+ let stored_target = self
+ .pane_nav_tab_scroll_targets
+ .get(&stack_key)
+ .copied()
+ .unwrap_or(current_offset);
+ let current_target = stored_target.clamp(0.0, max_offset.max(0.0));
+ let needs_target_clamp = (current_target - stored_target).abs() > f32::EPSILON;
+ let offset =
+ (current_target + Self::tab_scroll_pixels(amount)).clamp(0.0, max_offset.max(0.0));
+ if (offset - current_target).abs() > f32::EPSILON
+ || needs_offset_clamp
+ || needs_target_clamp
{
- self.pane_nav_tab_scroll_targets.insert(pane_id, offset);
- self.pane_nav_tab_scroll_offsets.insert(pane_id, offset);
+ self.pane_nav_tab_scroll_targets.insert(stack_key, offset);
+ if needs_offset_clamp || !self.pane_nav_tab_scroll_offsets.contains_key(&stack_key) {
+ self.pane_nav_tab_scroll_offsets
+ .insert(stack_key, current_offset);
+ }
+ self.update_next_frame_time(Some(Instant::now() + Duration::from_millis(16)));
+ context.invalidate();
+ }
+ }
+
+ fn scroll_pane_nav_tabs(
+ &mut self,
+ pane_id: mux::pane::PaneId,
+ amount: i16,
+ context: &dyn WindowOps,
+ ) {
+ if let Some(stack_key) = Mux::get().pane_stack_id(pane_id) {
+ self.scroll_tab_wheel_surface(TabWheelSurface::PaneStack(stack_key), amount, context);
+ }
+ }
+
+ fn lock_pane_nav_tab_wheel_surface(
+ &mut self,
+ pane_id: mux::pane::PaneId,
+ ) -> Option<mux::tab::PaneStackId> {
+ let stack_key = Mux::get().pane_stack_id(pane_id)?;
+ self.set_tab_wheel_surface_lock(TabWheelSurface::PaneStack(stack_key));
+ Some(stack_key)
+ }
+
+ fn scroll_tab_wheel_surface(
+ &mut self,
+ surface: TabWheelSurface,
+ amount: i16,
+ context: &dyn WindowOps,
+ ) {
+ if self.should_ignore_tab_wheel_amount(surface, amount) {
context.invalidate();
+ return;
+ }
+
+ match surface {
+ TabWheelSurface::Window => self.scroll_window_tab_bar(amount, context),
+ TabWheelSurface::PaneStack(stack_id) => {
+ self.scroll_pane_nav_stack_tabs(stack_id, amount, context)
+ }
}
}
fn wheel_amount(event: &MouseEvent) -> Option<i16> {
match event.kind {
- WMEK::VertWheel(amount) | WMEK::HorzWheel(amount) => Some(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;
- }
+ fn tab_wheel_surface_at_event(&self, event: &MouseEvent) -> Option<TabWheelSurface> {
+ if let Some(UIItem {
+ item_type: UIItemType::PaneNav { pane_id, .. },
+ ..
+ }) = self.resolve_ui_item(event)
+ {
+ return Mux::get()
+ .pane_stack_id(pane_id)
+ .map(TabWheelSurface::PaneStack);
}
let Some(tab) = Mux::get().get_active_tab_for_window(self.mux_window_id) else {
- return false;
+ return None;
};
let border = self.get_os_border();
@@ -234,16 +370,119 @@ impl super::TermWindow {
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 content_pane_x =
+ padding_left + border.left.get() as f32 + pos.left as f32 * cell_width;
+ let pane_x = if pos.left == 0 && self.workspace_sidebar_width() > 0 {
+ self.tab_bar_left_edge() as f32
+ } else {
+ content_pane_x
+ };
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;
+ let pane_width = (content_pane_x + pos.width as f32 * cell_width - pane_x).max(1.0);
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;
+ return Some(TabWheelSurface::PaneStack(pos.pane_stack_id));
}
}
- false
+ if self.show_tab_bar {
+ 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
+ };
+ if event.coords.x >= self.tab_bar_left_edge() as isize
+ && y >= tab_bar_y
+ && y < tab_bar_y + tab_bar_height
+ {
+ return Some(TabWheelSurface::Window);
+ }
+ }
+
+ None
+ }
+
+ fn vertical_wheel_tab_surface_passthrough(&self, event: &MouseEvent, item: &UIItem) -> bool {
+ if !matches!(event.kind, WMEK::VertWheel(_)) {
+ return false;
+ }
+
+ matches!(
+ item.item_type,
+ UIItemType::PaneNav { .. } | UIItemType::TabBar(_)
+ )
+ }
+
+ fn mouse_wheel_tab_surfaces(&mut self, event: &MouseEvent, context: &dyn WindowOps) -> bool {
+ if !matches!(event.kind, WMEK::VertWheel(_) | WMEK::HorzWheel(_)) {
+ return false;
+ }
+
+ let hovered_surface = self.tab_wheel_surface_at_event(event);
+
+ if let Some(amount) = Self::wheel_amount(event) {
+ match hovered_surface {
+ Some(surface) => {
+ self.set_tab_wheel_surface_lock(surface);
+ self.scroll_tab_wheel_surface(surface, amount, context);
+ true
+ }
+ None => {
+ self.tab_wheel_surface_lock = None;
+ false
+ }
+ }
+ } else {
+ false
+ }
+ }
+
+ fn mouse_wheel_workspace_sidebar(
+ &mut self,
+ event: &MouseEvent,
+ context: &dyn WindowOps,
+ ) -> bool {
+ let Some(rect) = self.workspace_sidebar_rect() else {
+ return false;
+ };
+
+ let x = event.coords.x;
+ let y = event.coords.y;
+ if x < rect.x as isize
+ || x >= rect.x.saturating_add(rect.width) as isize
+ || y < rect.y as isize
+ || y >= rect.y.saturating_add(rect.height) as isize
+ {
+ return false;
+ }
+
+ let amount = match event.kind {
+ WMEK::VertWheel(amount) => amount,
+ // Trackpads often emit a little horizontal inertia while the user is
+ // vertically scrolling. Consume it inside the sidebar so it doesn't
+ // leak to tab or terminal wheel handlers at the scroll bounds.
+ WMEK::HorzWheel(_) => return true,
+ _ => return false,
+ };
+ if amount == 0 {
+ return true;
+ }
+
+ let max_offset = self.workspace_sidebar_scroll_max();
+ if max_offset <= 0.0 {
+ return true;
+ }
+
+ self.show_workspace_sidebar_scrollbar();
+ let offset = (self.workspace_sidebar_scroll_offset + Self::sidebar_scroll_pixels(amount))
+ .clamp(0.0, max_offset);
+ if (offset - self.workspace_sidebar_scroll_offset).abs() > f32::EPSILON {
+ self.workspace_sidebar_scroll_offset = offset;
+ context.invalidate();
+ } else {
+ context.invalidate();
+ }
+ true
}
fn resolve_ui_item(&self, event: &MouseEvent) -> Option<UIItem> {
@@ -263,7 +502,14 @@ impl super::TermWindow {
}
UIItemType::CloseTab(_)
| UIItemType::PaneNav { .. }
- | UIItemType::WorkspaceSidebar(_)
+ | UIItemType::ProjectNew
+ | UIItemType::ProjectToggleSessions(_)
+ | UIItemType::Project(_)
+ | UIItemType::ProjectSession(_)
+ | UIItemType::ProjectSessionArchive(_)
+ | UIItemType::ProjectSessionNew(_)
+ | UIItemType::WorkspaceSidebarScrollTrack
+ | UIItemType::WorkspaceSidebarScrollThumb
| UIItemType::WorkspaceSidebarBackground
| UIItemType::WorkspaceSidebarResize
| UIItemType::AboveScrollThumb
@@ -278,7 +524,14 @@ impl super::TermWindow {
UIItemType::TabBar(_) => {}
UIItemType::CloseTab(_)
| UIItemType::PaneNav { .. }
- | UIItemType::WorkspaceSidebar(_)
+ | UIItemType::ProjectNew
+ | UIItemType::ProjectToggleSessions(_)
+ | UIItemType::Project(_)
+ | UIItemType::ProjectSession(_)
+ | UIItemType::ProjectSessionArchive(_)
+ | UIItemType::ProjectSessionNew(_)
+ | UIItemType::WorkspaceSidebarScrollTrack
+ | UIItemType::WorkspaceSidebarScrollThumb
| UIItemType::WorkspaceSidebarBackground
| UIItemType::WorkspaceSidebarResize
| UIItemType::AboveScrollThumb
@@ -359,6 +612,10 @@ impl super::TermWindow {
self.current_mouse_event.replace(event.clone());
+ if self.mouse_wheel_workspace_sidebar(&event, context) {
+ return;
+ }
+
if self.mouse_wheel_tab_surfaces(&event, context) {
return;
}
@@ -486,7 +743,9 @@ impl super::TermWindow {
let prior_ui_item = self.last_ui_item.clone();
let ui_item = if matches!(self.current_mouse_capture, None | Some(MouseCapture::UI)) {
- let ui_item = self.resolve_ui_item(&event);
+ let ui_item = self
+ .resolve_ui_item(&event)
+ .filter(|item| !self.vertical_wheel_tab_surface_passthrough(&event, item));
match (self.last_ui_item.take(), &ui_item) {
(Some(prior), Some(item)) => {
@@ -628,6 +887,40 @@ impl super::TermWindow {
self.dragging.replace((item, start_event));
}
+ fn set_workspace_sidebar_scroll_from_thumb_top(
+ &mut self,
+ thumb_top: f32,
+ context: &dyn WindowOps,
+ ) {
+ let Some(scroll) = self.workspace_sidebar_scroll_geometry() else {
+ return;
+ };
+ let travel = (scroll.track_height as f32 - scroll.thumb_height).max(1.0);
+ let relative_top = (thumb_top - scroll.track_y as f32).clamp(0.0, travel);
+ let offset = (relative_top / travel * scroll.max_scroll).clamp(0.0, scroll.max_scroll);
+ self.show_workspace_sidebar_scrollbar();
+ if (offset - self.workspace_sidebar_scroll_offset).abs() > f32::EPSILON {
+ self.workspace_sidebar_scroll_offset = offset;
+ context.invalidate();
+ } else {
+ context.invalidate();
+ }
+ }
+
+ fn drag_workspace_sidebar_scroll_thumb(
+ &mut self,
+ item: UIItem,
+ start_event: MouseEvent,
+ event: MouseEvent,
+ context: &dyn WindowOps,
+ ) {
+ let from_top = start_event.coords.y.saturating_sub(item.y as isize) as f32;
+ let thumb_top = event.coords.y as f32 - from_top;
+ self.set_workspace_sidebar_scroll_from_thumb_top(thumb_top, context);
+ context.set_cursor(Some(MouseCursor::Hand));
+ self.dragging.replace((item, start_event));
+ }
+
fn drag_ui_item(
&mut self,
item: UIItem,
@@ -647,6 +940,9 @@ impl super::TermWindow {
UIItemType::WorkspaceSidebarResize => {
self.drag_workspace_sidebar_resize(item, start_event, event, context);
}
+ UIItemType::WorkspaceSidebarScrollThumb => {
+ self.drag_workspace_sidebar_scroll_thumb(item, start_event, event, context);
+ }
UIItemType::PaneNav { .. } => {}
_ => {
log::error!("drag not implemented for {:?}", item);
@@ -705,12 +1001,33 @@ impl super::TermWindow {
} => {
self.mouse_event_pane_nav(pane_id, pane_index, action, event, context);
}
- UIItemType::WorkspaceSidebar(workspace) => {
- self.mouse_event_workspace_sidebar(workspace, event, context);
+ UIItemType::ProjectNew => {
+ self.mouse_event_project_new(event, context);
+ }
+ UIItemType::ProjectToggleSessions(project_id) => {
+ self.mouse_event_project_toggle_sessions(project_id, event, context);
+ }
+ UIItemType::Project(project_id) => {
+ self.mouse_event_project(project_id, event, context);
+ }
+ UIItemType::ProjectSession(session_id) => {
+ self.mouse_event_project_session(session_id, event, context);
+ }
+ UIItemType::ProjectSessionArchive(session_id) => {
+ self.mouse_event_project_session_archive(session_id, event, context);
+ }
+ UIItemType::ProjectSessionNew(project_id) => {
+ self.mouse_event_project_session_new(project_id, event, context);
}
UIItemType::WorkspaceSidebarBackground => {
context.set_cursor(Some(MouseCursor::Arrow));
}
+ UIItemType::WorkspaceSidebarScrollTrack => {
+ self.mouse_event_workspace_sidebar_scroll_track(item, event, context);
+ }
+ UIItemType::WorkspaceSidebarScrollThumb => {
+ self.mouse_event_workspace_sidebar_scroll_thumb(item, event, context);
+ }
UIItemType::WorkspaceSidebarResize => {
self.mouse_event_workspace_sidebar_resize(item, event, context);
}
@@ -737,21 +1054,203 @@ impl super::TermWindow {
}
}
- pub fn mouse_event_workspace_sidebar(
+ pub fn mouse_event_workspace_sidebar_scroll_thumb(
+ &mut self,
+ item: UIItem,
+ event: MouseEvent,
+ context: &dyn WindowOps,
+ ) {
+ context.set_cursor(Some(MouseCursor::Hand));
+ self.show_workspace_sidebar_scrollbar();
+ if event.kind == WMEK::Press(MousePress::Left) {
+ self.dragging.replace((item, event));
+ context.invalidate();
+ }
+ }
+
+ pub fn mouse_event_workspace_sidebar_scroll_track(
+ &mut self,
+ _item: UIItem,
+ event: MouseEvent,
+ context: &dyn WindowOps,
+ ) {
+ context.set_cursor(Some(MouseCursor::Hand));
+ self.show_workspace_sidebar_scrollbar();
+ if event.kind == WMEK::Press(MousePress::Left) {
+ if let Some(scroll) = self.workspace_sidebar_scroll_geometry() {
+ let thumb_top = event.coords.y as f32 - scroll.thumb_height / 2.0;
+ self.set_workspace_sidebar_scroll_from_thumb_top(thumb_top, context);
+ }
+ context.invalidate();
+ }
+ }
+
+ pub fn mouse_event_project_session_new(
&mut self,
- workspace: String,
+ project_id: 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);
+ let session_id = crate::project_sessions::create_session(&project_id, None);
+ self.activate_project_session(session_id, context);
+ }
+ context.set_cursor(Some(MouseCursor::Arrow));
+ }
+
+ pub fn mouse_event_project_new(&mut self, event: MouseEvent, context: &dyn WindowOps) {
+ if let WMEK::Press(MousePress::Left) = event.kind {
+ self.prompt_create_project(context);
+ }
+ context.set_cursor(Some(MouseCursor::Arrow));
+ }
+
+ pub fn mouse_event_project(
+ &mut self,
+ project_id: String,
+ event: MouseEvent,
+ context: &dyn WindowOps,
+ ) {
+ if let WMEK::Press(MousePress::Left) = event.kind {
+ if let Some(session_id) =
+ crate::project_sessions::active_session_for_project(&project_id)
+ {
+ self.activate_project_session(session_id, context);
+ } else {
+ context.invalidate();
}
+ }
+ context.set_cursor(Some(MouseCursor::Arrow));
+ }
+
+ pub fn mouse_event_project_toggle_sessions(
+ &mut self,
+ project_id: String,
+ event: MouseEvent,
+ context: &dyn WindowOps,
+ ) {
+ if let WMEK::Press(MousePress::Left) = event.kind {
+ crate::project_sessions::toggle_project_sessions_collapsed(&project_id);
context.invalidate();
}
context.set_cursor(Some(MouseCursor::Arrow));
}
+ pub fn mouse_event_project_session(
+ &mut self,
+ session_id: String,
+ event: MouseEvent,
+ context: &dyn WindowOps,
+ ) {
+ match event.kind {
+ WMEK::Press(MousePress::Left) => {
+ self.activate_project_session(session_id, context);
+ }
+ WMEK::Press(MousePress::Right) => {
+ context.show_context_menu(
+ event.coords,
+ self.project_session_context_menu_items(&session_id),
+ );
+ }
+ _ => {}
+ }
+ context.set_cursor(Some(MouseCursor::Arrow));
+ }
+
+ pub fn mouse_event_project_session_archive(
+ &mut self,
+ session_id: String,
+ event: MouseEvent,
+ context: &dyn WindowOps,
+ ) {
+ if let WMEK::Press(MousePress::Left) = event.kind {
+ if crate::project_sessions::archive_session(&session_id) {
+ context.invalidate();
+ }
+ }
+ context.set_cursor(Some(MouseCursor::Arrow));
+ }
+
+ fn project_session_context_menu_items(&self, session_id: &str) -> Vec<ContextMenuItem> {
+ let session_id = session_id.to_string();
+ vec![
+ ContextMenuItem::item(
+ "Pin Session",
+ KeyAssignment::ToggleProjectSessionPinned(session_id.clone()),
+ ),
+ ContextMenuItem::item_with_icon(
+ "Rename Session...",
+ "pencil",
+ KeyAssignment::PromptRenameProjectSession(session_id.clone()),
+ ),
+ ContextMenuItem::item(
+ "Archive Session",
+ KeyAssignment::ArchiveProjectSession(session_id.clone()),
+ ),
+ ContextMenuItem::item(
+ "Delete Session",
+ KeyAssignment::DeleteProjectSession(session_id.clone()),
+ ),
+ ContextMenuItem::item(
+ "Mark as Unread",
+ KeyAssignment::MarkProjectSessionUnread(session_id),
+ ),
+ ]
+ }
+
+ pub(crate) fn activate_project_session(&mut self, session_id: String, context: &dyn WindowOps) {
+ crate::project_sessions::snapshot_active_session_layout(self.mux_window_id);
+
+ let mux = Mux::get();
+ let live_workspaces = mux.iter_workspaces();
+ let Some(plan) =
+ crate::project_sessions::activate_session_record(&session_id, &live_workspaces)
+ else {
+ context.invalidate();
+ return;
+ };
+
+ if !plan.needs_materialize {
+ if mux.active_workspace() != plan.workspace_name {
+ front_end().switch_workspace(&plan.workspace_name);
+ }
+ context.invalidate();
+ return;
+ }
+
+ let workspace_name = plan.workspace_name.clone();
+ let initial_cwd = plan.project_path.to_str().map(|path| path.to_string());
+ let layout = crate::project_sessions::session_layout(&plan.session_id);
+ let dpi = self.dimensions.dpi as u32;
+ let size = self.config.initial_size(
+ dpi,
+ crate::cell_pixel_dims(&self.config, self.dimensions.dpi as f64).ok(),
+ );
+ let term_config: Arc<dyn wezterm_term::TerminalConfiguration> =
+ Arc::new(TermConfig::with_config(self.config.clone()));
+ let switcher = crate::frontend::WorkspaceSwitcher::new(&workspace_name);
+ mux.set_active_workspace(&workspace_name);
+
+ promise::spawn::spawn(async move {
+ if let Err(err) = crate::project_sessions::materialize_session(
+ workspace_name,
+ layout,
+ initial_cwd,
+ size,
+ None,
+ term_config,
+ )
+ .await
+ {
+ log::error!("failed to materialize ThinkTerm session: {err:#}");
+ }
+ switcher.do_switch();
+ })
+ .detach();
+
+ context.invalidate();
+ }
+
fn pane_nav_tab_context_menu_items(&self, pane_id: mux::pane::PaneId) -> Vec<ContextMenuItem> {
vec![ContextMenuItem::item_with_icon(
"Rename Tab...",
@@ -771,10 +1270,15 @@ impl super::TermWindow {
context.set_cursor(Some(MouseCursor::Arrow));
match event.kind {
- WMEK::VertWheel(amount) | WMEK::HorzWheel(amount) => {
+ WMEK::HorzWheel(amount) => {
+ self.lock_pane_nav_tab_wheel_surface(pane_id);
self.scroll_pane_nav_tabs(pane_id, amount, context);
return;
}
+ WMEK::VertWheel(_) => {
+ self.lock_pane_nav_tab_wheel_surface(pane_id);
+ return;
+ }
_ => {}
}
@@ -793,21 +1297,19 @@ impl super::TermWindow {
}
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 let Some(tab) = mux.get_active_tab_for_window(self.mux_window_id) {
+ tab.set_active_idx(pane_index);
+ }
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:#}");
- }
+ if let Err(err) = mux.activate_pane_in_stack(target_pane_id) {
+ log::error!("pane nav activate failed: {err:#}");
}
}
PaneNavAction::Close(target_pane_id) => {
@@ -815,8 +1317,16 @@ impl super::TermWindow {
self.close_pane(pane, true);
}
}
- PaneNavAction::NewTab => self.spawn_pane_nav_tab(pane_id, pane_index),
+ PaneNavAction::NewTab => {
+ if let Some(tab) = mux.get_active_tab_for_window(self.mux_window_id) {
+ tab.set_active_idx(pane_index);
+ }
+ self.spawn_pane_nav_tab(pane_id, pane_index);
+ }
PaneNavAction::SplitRight | PaneNavAction::SplitDown => {
+ if let Some(tab) = mux.get_active_tab_for_window(self.mux_window_id) {
+ tab.set_active_idx(pane_index);
+ }
let pane = match mux.get_pane(pane_id) {
Some(pane) => pane,
None => return,
@@ -1178,9 +1688,10 @@ impl super::TermWindow {
| TabBarItem::Tab { .. }
| TabBarItem::NewTabButton { .. } => {}
},
- WMEK::VertWheel(amount) | WMEK::HorzWheel(amount) => {
+ WMEK::HorzWheel(amount) => {
self.scroll_window_tab_bar(amount, context);
}
+ WMEK::VertWheel(_) => {}
_ => {}
}
context.set_cursor(Some(MouseCursor::Arrow));
@@ -1343,14 +1854,9 @@ impl super::TermWindow {
is_click_to_focus_pane = true;
}
WMEK::Move => {
- if self.config.pane_focus_follows_mouse {
- let mux = Mux::get();
- mux.get_active_tab_for_window(self.mux_window_id)
- .map(|tab| tab.set_active_idx(pos.index));
-
- pane = Arc::clone(&pos.pane);
- context.invalidate();
- }
+ // ThinkTerm keeps pane focus explicit. The upstream
+ // focus-follows-mouse behavior makes split panes
+ // appear to switch while scrolling pane-local tabs.
}
WMEK::Release(_) | WMEK::HorzWheel(_) => {}
WMEK::VertWheel(_) => {
diff --git a/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs b/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs
index 4123062a..935e3c91 100644
--- a/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs
+++ b/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs
@@ -2,6 +2,11 @@ use crate::customglyph::BlockKey;
use crate::quad::{QuadTrait, TripleLayerQuadAllocator, TripleLayerQuadAllocatorTrait};
use crate::tabbar::{TabBarItem, TabEntry};
use crate::termwindow::ui::icons::SvgIcon;
+use crate::termwindow::ui::tokens::{
+ active_capsule_bg, capsule_border, CAPSULE_BORDER_WIDTH, TAB_CLOSE_HOVER_INSET,
+ TAB_CLOSE_HOVER_RADIUS, TAB_CLOSE_RIGHT_GAP, TAB_ROW_START_PADDING, TAB_VERTICAL_PADDING,
+ WINDOW_TAB_ACTION_RESERVED_WIDTH, WINDOW_TAB_GAP, WINDOW_TAB_RADIUS,
+};
use crate::termwindow::{TermWindowNotif, UIItem, UIItemType};
use crate::utilsprites::RenderMetrics;
use anyhow::Context;
@@ -10,14 +15,13 @@ 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::WindowOps;
+use wezterm_term::Line;
use window::color::LinearRgba;
+use window::WindowOps;
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 {
@@ -38,8 +42,8 @@ impl crate::TermWindow {
let font = self.fonts.title_font()?;
let metrics = RenderMetrics::with_font_metrics(&font.metrics());
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))
+ let button_size = row_height
+ .saturating_sub(TAB_VERTICAL_PADDING * 2)
.max(icon_size);
let tab_width = self.window_tab_width_pixels().ceil() as usize;
@@ -49,9 +53,6 @@ impl crate::TermWindow {
.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 border = self.get_os_border();
let row_x = self.tab_bar_left_edge();
@@ -68,8 +69,9 @@ impl crate::TermWindow {
.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_left = (row_x as f32 + self.window_tab_left_padding_pixels()).ceil() as usize
+ + TAB_ROW_START_PADDING;
+ let viewport_right = row_right.saturating_sub(WINDOW_TAB_ACTION_RESERVED_WIDTH);
let viewport_width = viewport_right.saturating_sub(viewport_left);
self.filled_rectangle(
@@ -84,19 +86,6 @@ impl crate::TermWindow {
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,
@@ -117,13 +106,14 @@ impl crate::TermWindow {
.and_then(|window| window.idx_by_id(tab_id))
});
+ let tab_step = tab_width + WINDOW_TAB_GAP;
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;
+ let virtual_left = tab_sequence_idx as f32 * tab_step as f32 - scroll_offset;
tab_sequence_idx += 1;
let tab_left = viewport_left as f32 + virtual_left;
@@ -161,21 +151,19 @@ impl crate::TermWindow {
&palette,
background,
if active { foreground } else { muted_fg },
- active_edge,
- accent,
)?;
}
- self.paint_fancy_tab_bar_overflow(
+ self.paint_window_tab_new_button(
layers,
+ &mut ui_items,
+ row_right,
row_y,
row_height,
- viewport_left,
- viewport_width,
- scroll_offset,
- max_scroll,
- background,
- divider,
+ button_size,
+ icon_size,
+ foreground,
+ muted_fg,
)?;
Ok(ui_items)
@@ -205,8 +193,6 @@ impl crate::TermWindow {
palette: &ColorPalette,
background: LinearRgba,
foreground: LinearRgba,
- active_edge: LinearRgba,
- accent: LinearRgba,
) -> anyhow::Result<()> {
self.filled_rectangle(
layers,
@@ -216,52 +202,37 @@ impl crate::TermWindow {
)
.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")?;
+ let hover_x = visible_left.max(0.0) as usize;
+ let hover_width = visible_width.max(0.0) as usize;
+ let is_hovered = self.is_pointer_over_ui_rect(hover_x, row_y, hover_width, row_height);
+ let surface_foreground = palette.foreground.to_linear();
+ let tab_surface_color = if active {
+ active_capsule_bg(background.3)
+ } else if is_hovered && !is_renaming {
+ surface_foreground.mul_alpha(0.055)
} else {
- 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")?;
- }
+ surface_foreground.mul_alpha(0.025)
+ };
+ let tab_surface_y = row_y + (row_height.saturating_sub(button_size) / 2);
+ self.fill_rounded_rectangle_with_border(
+ layers,
+ 1,
+ euclid::rect(
+ visible_left,
+ tab_surface_y as f32,
+ visible_width,
+ button_size as f32,
+ ),
+ tab_surface_color,
+ if active {
+ capsule_border(surface_foreground, true)
+ } else {
+ LinearRgba::TRANSPARENT
+ },
+ WINDOW_TAB_RADIUS,
+ CAPSULE_BORDER_WIDTH,
+ )
+ .context("window tab surface")?;
ui_items.push(UIItem {
x: visible_left.max(0.0) as usize,
@@ -287,31 +258,64 @@ impl crate::TermWindow {
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;
+ .saturating_sub(button_size + TAB_CLOSE_RIGHT_GAP);
+ let close_y = row_y + (row_height.saturating_sub(button_size) / 2);
+ let close_slot_reserved = self.config.show_close_tab_button_in_tabs && !is_renaming;
+ let show_close = close_slot_reserved && (active || is_hovered);
if show_close
&& close_x >= viewport_left
&& close_x.saturating_add(button_size) <= viewport_right
{
+ let close_hovered =
+ self.is_pointer_over_ui_rect(close_x, close_y, button_size, button_size);
+ if close_hovered {
+ let hover_alpha =
+ if self.is_pointer_pressing_ui_rect(close_x, close_y, button_size, button_size)
+ {
+ 0.20
+ } else {
+ 0.12
+ };
+ let hover_inset = TAB_CLOSE_HOVER_INSET.min(button_size / 2);
+ let hover_size = button_size.saturating_sub(hover_inset * 2);
+ self.fill_rounded_rectangle(
+ layers,
+ 1,
+ euclid::rect(
+ (close_x + hover_inset) as f32,
+ (close_y + hover_inset) as f32,
+ hover_size as f32,
+ hover_size as f32,
+ ),
+ foreground.mul_alpha(hover_alpha),
+ TAB_CLOSE_HOVER_RADIUS,
+ )
+ .context("window tab close hover")?;
+ }
ui_items.push(UIItem {
x: close_x,
- y: row_y + (row_height.saturating_sub(button_size) / 2),
+ y: close_y,
width: button_size,
height: button_size,
item_type: UIItemType::CloseTab(tab_idx),
});
+ let close_fg = if close_hovered {
+ foreground
+ } else {
+ foreground.mul_alpha(0.82)
+ };
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),
+ close_fg,
)?;
}
let text_x = icon_x + icon_size + WINDOW_TAB_ICON_GAP;
- let text_right = if show_close {
+ let text_right = if close_slot_reserved {
close_x.saturating_sub(WINDOW_TAB_ICON_GAP)
} else {
tab_left
@@ -353,69 +357,59 @@ impl crate::TermWindow {
}
#[allow(clippy::too_many_arguments)]
- fn paint_fancy_tab_bar_overflow(
+ fn paint_window_tab_new_button(
&self,
layers: &mut TripleLayerQuadAllocator,
+ ui_items: &mut Vec<UIItem>,
+ row_right: usize,
row_y: usize,
row_height: usize,
- viewport_left: usize,
- viewport_width: usize,
- scroll_offset: f32,
- max_scroll: f32,
- background: LinearRgba,
- divider: LinearRgba,
+ button_size: usize,
+ icon_size: usize,
+ foreground: LinearRgba,
+ muted_fg: LinearRgba,
) -> anyhow::Result<()> {
- let fade_width = 22usize.min(viewport_width / 3);
- if fade_width <= 1 {
- return Ok(());
- }
-
- 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,
- ),
- background.mul_alpha(0.94),
- )
- .context("window tab left overflow shade")?;
- self.filled_rectangle(
+ let button_x = row_right.saturating_sub(WINDOW_TAB_INSET + button_size);
+ let button_y = row_y + (row_height.saturating_sub(button_size) / 2);
+ let hovered = self.is_pointer_over_ui_rect(button_x, button_y, button_size, button_size);
+ if hovered {
+ let hover_alpha =
+ if self.is_pointer_pressing_ui_rect(button_x, button_y, button_size, button_size) {
+ 0.20
+ } else {
+ 0.12
+ };
+ self.fill_rounded_rectangle(
layers,
1,
euclid::rect(
- (viewport_left + fade_width.saturating_sub(2)) as f32,
- row_y as f32,
- 2.0,
- row_height as f32,
+ button_x as f32,
+ button_y as f32,
+ button_size as f32,
+ button_size as f32,
),
- divider,
+ foreground.mul_alpha(hover_alpha),
+ 5.0,
)
- .context("window tab left overflow edge")?;
+ .context("window tab new button hover")?;
}
- 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")?;
- }
+ ui_items.push(UIItem {
+ x: button_x,
+ y: button_y,
+ width: button_size,
+ height: button_size,
+ item_type: UIItemType::TabBar(TabBarItem::NewTabButton),
+ });
- Ok(())
+ self.paint_fancy_tab_icon(
+ layers,
+ SvgIcon::Plus,
+ button_x + (button_size.saturating_sub(icon_size) / 2),
+ button_y + (button_size.saturating_sub(icon_size) / 2),
+ icon_size,
+ if hovered { foreground } else { muted_fg },
+ )
}
#[allow(clippy::too_many_arguments)]
@@ -444,7 +438,7 @@ impl crate::TermWindow {
}
#[allow(clippy::too_many_arguments)]
- pub(super) fn paint_ui_title_text(
+ pub(crate) fn paint_ui_title_text(
&self,
layers: &mut TripleLayerQuadAllocator,
font: &Rc<LoadedFont>,
diff --git a/wezterm-gui/src/termwindow/render/mod.rs b/wezterm-gui/src/termwindow/render/mod.rs
index 4fe09887..40d37381 100644
--- a/wezterm-gui/src/termwindow/render/mod.rs
+++ b/wezterm-gui/src/termwindow/render/mod.rs
@@ -7,7 +7,9 @@ use crate::quad::{
};
use crate::shapecache::*;
use crate::termwindow::render::paint::AllowImage;
-use crate::termwindow::{BorrowedShapeCacheKey, RenderState, ShapedInfo, TermWindowNotif};
+use crate::termwindow::{
+ BorrowedShapeCacheKey, MouseCapture, RenderState, ShapedInfo, TermWindowNotif,
+};
use crate::utilsprites::RenderMetrics;
use ::window::bitmaps::{TextureCoord, TextureRect, TextureSize};
use ::window::{DeadKeyStatus, PointF, RectF, SizeF, WindowOps};
@@ -295,6 +297,40 @@ impl crate::TermWindow {
Ok(quad)
}
+ pub(crate) fn is_pointer_over_ui_rect(
+ &self,
+ x: usize,
+ y: usize,
+ width: usize,
+ height: usize,
+ ) -> bool {
+ if width == 0 || height == 0 {
+ return false;
+ }
+ if !matches!(self.current_mouse_capture, None | Some(MouseCapture::UI)) {
+ return false;
+ }
+ let Some(event) = &self.current_mouse_event else {
+ return false;
+ };
+ let mouse_x = event.coords.x;
+ let mouse_y = event.coords.y;
+ mouse_x >= x as isize
+ && mouse_x < x.saturating_add(width) as isize
+ && mouse_y >= y as isize
+ && mouse_y < y.saturating_add(height) as isize
+ }
+
+ pub(crate) fn is_pointer_pressing_ui_rect(
+ &self,
+ x: usize,
+ y: usize,
+ width: usize,
+ height: usize,
+ ) -> bool {
+ self.is_pointer_over_ui_rect(x, y, width, height) && !self.current_mouse_buttons.is_empty()
+ }
+
pub fn poly_quad<'a>(
&self,
layers: &'a mut TripleLayerQuadAllocator,
diff --git a/wezterm-gui/src/termwindow/render/pane.rs b/wezterm-gui/src/termwindow/render/pane.rs
index 93b815ff..30012cc7 100644
--- a/wezterm-gui/src/termwindow/render/pane.rs
+++ b/wezterm-gui/src/termwindow/render/pane.rs
@@ -10,8 +10,9 @@ use crate::termwindow::render::{
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,
+ active_capsule_bg, capsule_border, CAPSULE_BORDER_WIDTH, PANE_NAV_BUTTON_GAP,
+ PANE_NAV_ICON_GAP, PANE_NAV_INSET, PANE_NAV_TAB_GAP, PANE_NAV_TAB_RADIUS,
+ TAB_CLOSE_HOVER_INSET, TAB_CLOSE_HOVER_RADIUS, TAB_CLOSE_RIGHT_GAP, TAB_VERTICAL_PADDING,
};
use crate::termwindow::{PaneNavAction, ScrollHit, UIItem, UIItemType};
use crate::utilsprites::RenderMetrics;
@@ -31,6 +32,7 @@ use wezterm_font::{FontConfiguration, LoadedFont};
use wezterm_term::color::{ColorAttribute, ColorPalette};
use wezterm_term::{Line, StableRowIndex};
use window::color::LinearRgba;
+use window::MouseEventKind as WMEK;
impl crate::TermWindow {
fn pane_nav_bar_height(&self, pos: &PositionedPane) -> usize {
@@ -75,42 +77,27 @@ impl crate::TermWindow {
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 {
+ let (content_pane_x, pane_y) = self.pane_content_origin(pos)?;
+ let content_pane_width = pos.width as f32 * self.render_metrics.cell_size.width as f32;
+ if content_pane_width <= 0.0 {
return Ok(0);
}
+ let content_pane_right = content_pane_x + content_pane_width;
+ let pane_x = if pos.left == 0 && self.workspace_sidebar_width() > 0 {
+ self.tab_bar_left_edge() as f32
+ } else {
+ content_pane_x
+ };
+ let pane_width = (content_pane_right - pane_x).max(1.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,
@@ -124,8 +111,8 @@ impl crate::TermWindow {
});
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))
+ let button_size = nav_height
+ .saturating_sub(TAB_VERTICAL_PADDING * 2)
.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;
@@ -142,29 +129,35 @@ impl crate::TermWindow {
button_size,
icon_size,
muted_fg,
+ foreground,
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 tab_start = pane_x as usize + self.pane_nav_tab_left_inset(pos.left);
+ let tab_width = self.window_tab_width_pixels().ceil() as usize;
+ let tab_step = tab_width + PANE_NAV_TAB_GAP;
let total_tab_width = tabs.len().saturating_mul(tab_width).saturating_add(
tabs.len()
.saturating_sub(1)
- .saturating_mul(PANE_NAV_BUTTON_GAP),
+ .saturating_mul(PANE_NAV_TAB_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())
+ .get(&pos.pane_stack_id)
.copied()
.unwrap_or(0.0)
.clamp(0.0, max_scroll.max(0.0));
+ let suppress_hover = self
+ .current_mouse_event
+ .as_ref()
+ .is_some_and(|event| matches!(event.kind, WMEK::VertWheel(_) | WMEK::HorzWheel(_)))
+ || self.tab_wheel_scroll_active();
let tab_height = button_size;
let tab_y = button_y;
for (idx, tab) in tabs.into_iter().enumerate() {
@@ -186,52 +179,35 @@ impl crate::TermWindow {
continue;
}
- let visible_active_tab = tab.is_active && pos.is_active;
+ let selected_tab = tab.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(
+ let this_tab_fg = if selected_tab { tab_fg } else { muted_fg };
+ let hover_x = visible_left.max(0.0) as usize;
+ let hover_width = visible_width.max(0.0) as usize;
+ let is_hovered = !suppress_hover
+ && self.is_pointer_over_ui_rect(hover_x, tab_y, hover_width, tab_height);
+ let tab_surface_color = if selected_tab {
+ active_capsule_bg(background.3)
+ } else if is_hovered && !is_renaming_tab {
+ foreground.mul_alpha(0.055)
+ } else {
+ foreground.mul_alpha(0.025)
+ };
+ let tab_border_color = if selected_tab {
+ capsule_border(foreground, true)
+ } else {
+ LinearRgba::TRANSPARENT
+ };
+ self.fill_rounded_rectangle_with_border(
layers,
1,
euclid::rect(visible_left, tab_y as f32, visible_width, tab_height as f32),
- this_tab_bg,
+ tab_surface_color,
+ tab_border_color,
PANE_NAV_TAB_RADIUS,
+ CAPSULE_BORDER_WIDTH,
)
- .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")?;
- }
+ .context("pane nav tab surface")?;
self.ui_items.push(UIItem {
x: visible_left.max(0.0) as usize,
y: tab_y,
@@ -259,9 +235,42 @@ impl crate::TermWindow {
)?;
}
- let close_x = draw_tab_x + tab_width - button_size;
- if !is_renaming_tab {
+ let close_x = draw_tab_x
+ .saturating_add(tab_width)
+ .saturating_sub(button_size + TAB_CLOSE_RIGHT_GAP);
+ let close_slot_reserved = !is_renaming_tab;
+ let show_close = close_slot_reserved && (selected_tab || is_hovered);
+ if show_close {
if close_x >= tab_start && close_x.saturating_add(button_size) <= max_tab_right {
+ let close_hovered =
+ self.is_pointer_over_ui_rect(close_x, tab_y, button_size, button_size);
+ if close_hovered {
+ let hover_alpha = if self.is_pointer_pressing_ui_rect(
+ close_x,
+ tab_y,
+ button_size,
+ button_size,
+ ) {
+ 0.20
+ } else {
+ 0.12
+ };
+ let hover_inset = TAB_CLOSE_HOVER_INSET.min(button_size / 2);
+ let hover_size = button_size.saturating_sub(hover_inset * 2);
+ self.fill_rounded_rectangle(
+ layers,
+ 1,
+ euclid::rect(
+ (close_x + hover_inset) as f32,
+ (tab_y + hover_inset) as f32,
+ hover_size as f32,
+ hover_size as f32,
+ ),
+ foreground.mul_alpha(hover_alpha),
+ TAB_CLOSE_HOVER_RADIUS,
+ )
+ .context("pane nav close hover")?;
+ }
self.ui_items.push(UIItem {
x: close_x,
y: tab_y,
@@ -279,7 +288,7 @@ impl crate::TermWindow {
close_x + ((button_size.saturating_sub(icon_size)) / 2),
title_icon_y,
icon_size,
- muted_fg,
+ if close_hovered { foreground } else { muted_fg },
)?;
}
}
@@ -287,10 +296,10 @@ impl crate::TermWindow {
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 {
+ let text_right = if close_slot_reserved {
close_x
+ } else {
+ draw_tab_x + tab_width - PANE_NAV_INSET
};
let text_width = text_right
.min(max_tab_right)
@@ -323,55 +332,6 @@ impl crate::TermWindow {
}
}
- 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)
}
@@ -384,6 +344,7 @@ impl crate::TermWindow {
button_size: usize,
icon_size: usize,
color: LinearRgba,
+ hover_color: LinearRgba,
pos: &PositionedPane,
action: PaneNavAction,
) -> anyhow::Result<()> {
@@ -399,13 +360,30 @@ impl crate::TermWindow {
},
});
+ let hovered = self.is_pointer_over_ui_rect(x, y, button_size, button_size);
+ if hovered {
+ let hover_alpha = if self.is_pointer_pressing_ui_rect(x, y, button_size, button_size) {
+ 0.20
+ } else {
+ 0.12
+ };
+ self.fill_rounded_rectangle(
+ layers,
+ 1,
+ euclid::rect(x as f32, y as f32, button_size as f32, button_size as f32),
+ color.mul_alpha(hover_alpha),
+ 5.0,
+ )
+ .context("pane nav button hover")?;
+ }
+
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,
+ if hovered { hover_color } else { color },
)
}
diff --git a/wezterm-gui/src/termwindow/render/tab_bar.rs b/wezterm-gui/src/termwindow/render/tab_bar.rs
index cccfbf40..f66a71da 100644
--- a/wezterm-gui/src/termwindow/render/tab_bar.rs
+++ b/wezterm-gui/src/termwindow/render/tab_bar.rs
@@ -1,6 +1,7 @@
use crate::quad::TripleLayerQuadAllocator;
use crate::termwindow::render::RenderScreenLineParams;
use crate::termwindow::theme_aligned_tab_bar_colors_from_palette;
+use crate::termwindow::ui::pane_nav_bar_height_for_metrics;
use crate::utilsprites::RenderMetrics;
use config::ConfigHandle;
use mux::renderable::RenderableDimensions;
@@ -124,12 +125,11 @@ impl crate::TermWindow {
pub fn tab_bar_pixel_height_impl(
config: &ConfigHandle,
- fontconfig: &wezterm_font::FontConfiguration,
+ _fontconfig: &wezterm_font::FontConfiguration,
render_metrics: &RenderMetrics,
) -> anyhow::Result<f32> {
if config.use_fancy_tab_bar {
- let font = fontconfig.title_font()?;
- Ok((font.metrics().cell_height.get() as f32 * 2.05).ceil())
+ Ok(pane_nav_bar_height_for_metrics(*render_metrics) as f32)
} else {
Ok(render_metrics.cell_size.height as f32)
}
diff --git a/wezterm-gui/src/termwindow/ui/icons.rs b/wezterm-gui/src/termwindow/ui/icons.rs
index 9ffa3583..b03b0ad8 100644
--- a/wezterm-gui/src/termwindow/ui/icons.rs
+++ b/wezterm-gui/src/termwindow/ui/icons.rs
@@ -4,8 +4,12 @@ use window::Image;
#[allow(dead_code)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SvgIcon {
+ Archive,
+ ChevronDown,
+ ChevronRight,
ExternalLink,
FolderOpen,
+ FolderPlus,
Globe,
PanelRightClose,
PanelRightOpen,
@@ -14,18 +18,29 @@ pub enum SvgIcon {
SplitHorizontal,
SplitVertical,
Terminal,
+ Trash2,
X,
}
impl SvgIcon {
pub fn bytes(self) -> &'static [u8] {
match self {
+ Self::Archive => include_bytes!("../../../../third_party/lucide/icons/archive.svg"),
+ Self::ChevronDown => {
+ include_bytes!("../../../../third_party/lucide/icons/chevron-down.svg")
+ }
+ Self::ChevronRight => {
+ include_bytes!("../../../../third_party/lucide/icons/chevron-right.svg")
+ }
Self::ExternalLink => {
include_bytes!("../../../../third_party/lucide/icons/external-link.svg")
}
Self::FolderOpen => {
include_bytes!("../../../../third_party/lucide/icons/folder-open.svg")
}
+ Self::FolderPlus => {
+ include_bytes!("../../../../third_party/lucide/icons/folder-plus.svg")
+ }
Self::Globe => include_bytes!("../../../../third_party/lucide/icons/globe.svg"),
Self::PanelRightClose => {
include_bytes!("../../../../third_party/lucide/icons/panel-right-close.svg")
@@ -44,6 +59,7 @@ impl SvgIcon {
include_bytes!("../../../../third_party/lucide/icons/square-split-vertical.svg")
}
Self::Terminal => include_bytes!("../../../../third_party/lucide/icons/terminal.svg"),
+ Self::Trash2 => include_bytes!("../../../../third_party/lucide/icons/trash-2.svg"),
Self::X => include_bytes!("../../../../third_party/lucide/icons/x.svg"),
}
}
@@ -76,8 +92,12 @@ mod tests {
#[test]
fn svg_icons_rasterize() {
for icon in [
+ SvgIcon::Archive,
SvgIcon::ExternalLink,
+ SvgIcon::ChevronDown,
+ SvgIcon::ChevronRight,
SvgIcon::FolderOpen,
+ SvgIcon::FolderPlus,
SvgIcon::Globe,
SvgIcon::PanelRightClose,
SvgIcon::PanelRightOpen,
@@ -86,6 +106,7 @@ mod tests {
SvgIcon::SplitHorizontal,
SvgIcon::SplitVertical,
SvgIcon::Terminal,
+ SvgIcon::Trash2,
SvgIcon::X,
] {
let data: Vec<u8> = icon.rasterize(24).unwrap().into();
diff --git a/wezterm-gui/src/termwindow/ui/sidebar.rs b/wezterm-gui/src/termwindow/ui/sidebar.rs
index ba1b4198..d278910f 100644
--- a/wezterm-gui/src/termwindow/ui/sidebar.rs
+++ b/wezterm-gui/src/termwindow/ui/sidebar.rs
@@ -1,25 +1,26 @@
+use crate::project_sessions;
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,
+ active_capsule_bg, capsule_border, CAPSULE_BORDER_WIDTH, SIDEBAR_ICON_GAP, SIDEBAR_INSET,
+ SIDEBAR_MAX_WIDTH, SIDEBAR_MIN_WIDTH, SIDEBAR_RESIZE_HANDLE_WIDTH, SIDEBAR_ROW_GAP,
+ 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 wezterm_term::color::ColorAttribute;
use window::color::LinearRgba;
-use window::RectF;
+use window::{MouseEventKind as WMEK, RectF};
+
+const SIDEBAR_SCROLLBAR_VISIBLE_MS: u64 = 900;
#[derive(Debug, Clone, Copy)]
pub struct WorkspaceSidebarRect {
@@ -29,6 +30,17 @@ pub struct WorkspaceSidebarRect {
pub height: usize,
}
+#[derive(Debug, Clone, Copy)]
+pub struct WorkspaceSidebarScrollGeometry {
+ pub track_x: usize,
+ pub track_y: usize,
+ pub track_width: usize,
+ pub track_height: usize,
+ pub thumb_y: f32,
+ pub thumb_height: f32,
+ pub max_scroll: f32,
+}
+
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)
}
@@ -97,6 +109,122 @@ impl crate::TermWindow {
})
}
+ fn workspace_sidebar_list_height(
+ view: &project_sessions::ProjectSessionView,
+ row_height: usize,
+ row_gap: usize,
+ ) -> usize {
+ let mut height = 0usize;
+ for project in &view.projects {
+ height = height.saturating_add(row_height + row_gap);
+ if !project.sessions_collapsed {
+ height = height
+ .saturating_add(project.sessions.len().saturating_mul(row_height + row_gap));
+ }
+ }
+ height.saturating_sub(row_gap)
+ }
+
+ pub fn workspace_sidebar_scroll_max(&self) -> f32 {
+ let Some(rect) = self.workspace_sidebar_rect() else {
+ return 0.0;
+ };
+ if self.workspace_sidebar_collapsed {
+ return 0.0;
+ }
+
+ let ui_cell_height = self
+ .fonts
+ .title_font()
+ .map(|font| {
+ RenderMetrics::with_font_metrics(&font.metrics())
+ .cell_size
+ .height as usize
+ })
+ .unwrap_or(self.render_metrics.cell_size.height as usize);
+ let icon_size = (ui_cell_height + 12).clamp(30, 36);
+ let panel_margin = 0usize;
+ let panel_y = rect.y + panel_margin;
+ let panel_height = rect.height.saturating_sub(panel_margin * 2).max(1);
+ let content_bottom = panel_y + panel_height.saturating_sub(SIDEBAR_INSET);
+ let list_top = panel_y + SIDEBAR_INSET + ui_cell_height + SIDEBAR_INSET;
+ let viewport_height = content_bottom.saturating_sub(list_top);
+ if viewport_height == 0 {
+ return 0.0;
+ }
+
+ let mux = Mux::get();
+ let active_workspace = mux.active_workspace();
+ let workspaces = mux.iter_workspaces();
+ let view = project_sessions::view_for_current_project(&active_workspace, &workspaces);
+ let row_height = (ui_cell_height.max(icon_size) + SIDEBAR_INSET).max(52);
+ let row_gap = SIDEBAR_ROW_GAP;
+ let total_height = Self::workspace_sidebar_list_height(&view, row_height, row_gap);
+ total_height.saturating_sub(viewport_height) as f32
+ }
+
+ pub fn workspace_sidebar_scroll_geometry(&self) -> Option<WorkspaceSidebarScrollGeometry> {
+ let rect = self.workspace_sidebar_rect()?;
+ if self.workspace_sidebar_collapsed {
+ return None;
+ }
+
+ let ui_cell_height = self
+ .fonts
+ .title_font()
+ .map(|font| {
+ RenderMetrics::with_font_metrics(&font.metrics())
+ .cell_size
+ .height as usize
+ })
+ .unwrap_or(self.render_metrics.cell_size.height as usize);
+ let icon_size = (ui_cell_height + 12).clamp(30, 36);
+ let panel_margin = 0usize;
+ let panel_x = rect.x + panel_margin;
+ let panel_y = rect.y + panel_margin;
+ let panel_width = rect.width.saturating_sub(panel_margin * 2).max(1);
+ let panel_height = rect.height.saturating_sub(panel_margin * 2).max(1);
+ let content_bottom = panel_y + panel_height.saturating_sub(SIDEBAR_INSET);
+ let list_top = panel_y + SIDEBAR_INSET + ui_cell_height + SIDEBAR_INSET;
+ let viewport_height = content_bottom.saturating_sub(list_top);
+ if viewport_height == 0 {
+ return None;
+ }
+
+ let mux = Mux::get();
+ let active_workspace = mux.active_workspace();
+ let workspaces = mux.iter_workspaces();
+ let view = project_sessions::view_for_current_project(&active_workspace, &workspaces);
+ let row_height = (ui_cell_height.max(icon_size) + SIDEBAR_INSET).max(52);
+ let row_gap = SIDEBAR_ROW_GAP;
+ let total_height = Self::workspace_sidebar_list_height(&view, row_height, row_gap);
+ let max_scroll = total_height.saturating_sub(viewport_height) as f32;
+ if max_scroll <= 0.0 || total_height == 0 {
+ return None;
+ }
+
+ let track_width = 4usize;
+ let track_height = viewport_height.max(1);
+ let thumb_height = ((viewport_height as f32 / total_height as f32) * track_height as f32)
+ .clamp(28.0, track_height as f32);
+ let travel = (track_height as f32 - thumb_height).max(1.0);
+ let scroll_offset = self.workspace_sidebar_scroll_offset.clamp(0.0, max_scroll);
+ let thumb_y = list_top as f32 + (scroll_offset / max_scroll) * travel;
+ let track_x = panel_x
+ .saturating_add(panel_width)
+ .saturating_sub(SIDEBAR_INSET / 2 + track_width);
+
+ Some(WorkspaceSidebarScrollGeometry {
+ track_x,
+ track_y: list_top,
+ track_width,
+ track_height,
+ thumb_y,
+ thumb_height,
+ max_scroll,
+ })
+ }
+
pub fn paint_workspace_sidebar(
&mut self,
layers: &mut TripleLayerQuadAllocator,
@@ -111,11 +239,10 @@ impl crate::TermWindow {
.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 sidebar_bg = background;
+ let selected_bg = active_capsule_bg(background.3);
+ let selected_border = capsule_border(foreground, true);
let active_fg = palette
.selection_fg
.to_linear()
@@ -125,32 +252,34 @@ impl crate::TermWindow {
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);
-
+ let panel_margin = 0usize;
+ let panel_x = rect.x + panel_margin;
+ let panel_y = rect.y + panel_margin;
+ let panel_width = rect.width.saturating_sub(panel_margin * 2).max(1);
+ let panel_height = rect.height.saturating_sub(panel_margin * 2).max(1);
+ let content_bottom = panel_y + panel_height.saturating_sub(SIDEBAR_INSET);
+
+ if rect.y > 0 {
+ self.filled_rectangle(
+ layers,
+ 0,
+ euclid::rect(rect.x as f32, 0.0, rect.width as f32, rect.y as f32),
+ sidebar_bg,
+ )
+ .context("sidebar header background")?;
+ }
self.filled_rectangle(
layers,
0,
euclid::rect(
- rect.x as f32,
- rect.y as f32,
- rect.width as f32,
- rect.height as f32,
+ panel_x as f32,
+ panel_y as f32,
+ panel_width as f32,
+ panel_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,
@@ -159,14 +288,9 @@ impl crate::TermWindow {
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);
+ let session_row_height = (ui_cell_height.max(icon_size) + SIDEBAR_INSET).max(52);
+ let item_x = panel_x + SIDEBAR_INSET;
+ let item_width = panel_width.saturating_sub(SIDEBAR_INSET * 2 + 1);
self.ui_items.push(UIItem {
x: rect
.x
@@ -184,70 +308,533 @@ impl crate::TermWindow {
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 workspaces = mux.iter_workspaces();
+ let view = project_sessions::view_for_current_project(&active_workspace, &workspaces);
+
+ let header_icon_size = icon_size.min(32);
+ let button_size = (header_icon_size + 8).clamp(32, 40);
+ let mut y = panel_y + SIDEBAR_INSET;
+ let section_button_size = button_size.min(34);
+ let section_button_x = item_x
+ .saturating_add(item_width)
+ .saturating_sub(section_button_size + SIDEBAR_INSET);
+ let section_button_y = y.saturating_sub(6);
+ self.paint_sidebar_text(
+ layers,
+ &ui_font,
+ ui_metrics,
+ "Workspaces",
+ item_x + SIDEBAR_INSET,
+ y,
+ section_button_x.saturating_sub(item_x + SIDEBAR_INSET * 2),
+ muted_fg,
+ )?;
+ self.fill_rounded_rectangle(
+ layers,
+ 1,
+ euclid::rect(
+ section_button_x as f32,
+ section_button_y as f32,
+ section_button_size as f32,
+ section_button_size as f32,
+ ),
+ foreground.mul_alpha(0.08),
+ SIDEBAR_ROW_RADIUS,
+ )
+ .context("sidebar new project button")?;
+ self.ui_items.push(UIItem {
+ x: section_button_x,
+ y: section_button_y,
+ width: section_button_size,
+ height: section_button_size,
+ item_type: UIItemType::ProjectNew,
+ });
+ let section_icon_size = header_icon_size.min(section_button_size.saturating_sub(10));
+ self.paint_sidebar_icon(
+ layers,
+ SvgIcon::FolderPlus,
+ section_button_x + ((section_button_size.saturating_sub(section_icon_size)) / 2),
+ section_button_y + ((section_button_size.saturating_sub(section_icon_size)) / 2),
+ section_icon_size,
+ foreground,
+ )?;
+ y += ui_cell_height + SIDEBAR_INSET;
+ let list_top = y;
+ let row_gap = SIDEBAR_ROW_GAP;
+ let max_scroll = {
+ let viewport_height = content_bottom.saturating_sub(list_top);
+ let total_height =
+ Self::workspace_sidebar_list_height(&view, session_row_height, row_gap);
+ total_height.saturating_sub(viewport_height) as f32
+ };
+ self.workspace_sidebar_scroll_offset =
+ self.workspace_sidebar_scroll_offset.clamp(0.0, max_scroll);
+ let scroll_offset = self.workspace_sidebar_scroll_offset;
+ let list_top_f = list_top as f32;
+ let content_bottom_f = content_bottom as f32;
+ let suppress_hover = self
+ .current_mouse_event
+ .as_ref()
+ .is_some_and(|event| matches!(event.kind, WMEK::VertWheel(_) | WMEK::HorzWheel(_)));
+ let mut virtual_y = 0usize;
+
+ for project in &view.projects {
+ let row_top = list_top_f + virtual_y as f32 - scroll_offset;
+ let row_bottom = row_top + session_row_height as f32;
+ let row_is_visible = row_bottom > list_top_f && row_top < content_bottom_f;
+ let y = row_top.floor().max(0.0) as usize;
+ let hit_y = row_top.max(list_top_f).floor().max(0.0) as usize;
+ let hit_bottom = row_bottom.min(content_bottom_f).ceil().max(hit_y as f32) as usize;
+ let hit_height = hit_bottom.saturating_sub(hit_y).max(1);
+
+ let disclosure_size = icon_size.min(22);
+ let disclosure_x = item_x + SIDEBAR_INSET;
+ let project_icon_x = disclosure_x + disclosure_size + 4;
+ let project_text_x = project_icon_x + icon_size + SIDEBAR_ICON_GAP;
+ let project_action_size =
+ section_button_size.min(session_row_height.saturating_sub(12));
+ let project_action_x = item_x
+ .saturating_add(item_width)
+ .saturating_sub(project_action_size + SIDEBAR_INSET);
+ let project_text_right = if project.is_active {
+ project_action_x
+ } else {
+ item_x
+ .saturating_add(item_width)
+ .saturating_sub(SIDEBAR_INSET)
+ };
+
+ if row_is_visible {
+ self.ui_items.push(UIItem {
+ x: item_x,
+ y: hit_y,
+ width: item_width,
+ height: hit_height,
+ item_type: UIItemType::Project(project.id.clone()),
+ });
+ }
- let mut y = rect.y + SIDEBAR_INSET;
- for workspace in workspaces {
- if y + item_height > rect.y + rect.height {
- break;
+ let icon_y = y + ((session_row_height.saturating_sub(icon_size)) / 2);
+ let disclosure_y = y + ((session_row_height.saturating_sub(disclosure_size)) / 2);
+ let text_y = y + ((session_row_height.saturating_sub(ui_cell_height)) / 2);
+ if row_is_visible {
+ self.ui_items.push(UIItem {
+ x: disclosure_x,
+ y: disclosure_y,
+ width: disclosure_size,
+ height: disclosure_size,
+ item_type: UIItemType::ProjectToggleSessions(project.id.clone()),
+ });
+ self.paint_sidebar_icon(
+ layers,
+ if project.sessions_collapsed {
+ SvgIcon::ChevronRight
+ } else {
+ SvgIcon::ChevronDown
+ },
+ disclosure_x,
+ disclosure_y,
+ disclosure_size,
+ muted_fg,
+ )?;
+ self.paint_sidebar_icon(
+ layers,
+ SvgIcon::FolderOpen,
+ project_icon_x,
+ icon_y,
+ icon_size,
+ muted_fg,
+ )?;
+ self.paint_sidebar_text(
+ layers,
+ &ui_font,
+ ui_metrics,
+ &project.name,
+ project_text_x,
+ text_y,
+ project_text_right.saturating_sub(project_text_x + SIDEBAR_INSET),
+ muted_fg,
+ )?;
}
- let is_active = workspace == active_workspace;
- if is_active {
+ if row_is_visible && project.is_active {
self.fill_rounded_rectangle(
layers,
- 0,
+ 1,
euclid::rect(
- item_x as f32,
- y as f32,
- item_width as f32,
- item_height as f32,
+ project_action_x as f32,
+ (y + ((session_row_height.saturating_sub(project_action_size)) / 2)) as f32,
+ project_action_size as f32,
+ project_action_size as f32,
),
- selected_bg,
+ foreground.mul_alpha(0.08),
SIDEBAR_ROW_RADIUS,
)
- .context("sidebar selected workspace")?;
+ .context("sidebar new session button")?;
+ self.ui_items.push(UIItem {
+ x: project_action_x,
+ y: y + ((session_row_height.saturating_sub(project_action_size)) / 2),
+ width: project_action_size,
+ height: project_action_size,
+ item_type: UIItemType::ProjectSessionNew(project.id.clone()),
+ });
+ let action_icon_size = header_icon_size.min(project_action_size.saturating_sub(10));
+ self.paint_sidebar_icon(
+ layers,
+ SvgIcon::Plus,
+ project_action_x + ((project_action_size.saturating_sub(action_icon_size)) / 2),
+ y + ((session_row_height.saturating_sub(project_action_size)) / 2)
+ + ((project_action_size.saturating_sub(action_icon_size)) / 2),
+ action_icon_size,
+ foreground,
+ )?;
}
- self.ui_items.push(UIItem {
- x: item_x,
- y,
- width: item_width,
- height: item_height,
- item_type: UIItemType::WorkspaceSidebar(workspace.clone()),
- });
+ virtual_y += session_row_height + row_gap;
+
+ if !project.sessions_collapsed {
+ let session_x = item_x + SIDEBAR_INSET * 3;
+ let session_width = item_width.saturating_sub(SIDEBAR_INSET * 3);
+ let session_icon_x = project_icon_x + SIDEBAR_INSET;
+ let session_text_x = session_icon_x + icon_size + SIDEBAR_ICON_GAP;
+ let guide_x = disclosure_x + disclosure_size / 2;
+ let guide_top =
+ (list_top_f + virtual_y as f32 - scroll_offset).max(list_top_f) as usize;
+ let session_start_virtual_y = virtual_y;
+ let mut guide_bottom = guide_top;
+
+ for session in &project.sessions {
+ let row_top = list_top_f + virtual_y as f32 - scroll_offset;
+ let row_bottom = row_top + session_row_height as f32;
+ let row_is_visible = row_bottom > list_top_f && row_top < content_bottom_f;
+ let y = row_top.floor().max(0.0) as usize;
+ let hit_y = row_top.max(list_top_f).floor().max(0.0) as usize;
+ let hit_bottom =
+ row_bottom.min(content_bottom_f).ceil().max(hit_y as f32) as usize;
+ let hit_height = hit_bottom.saturating_sub(hit_y).max(1);
+ guide_bottom = y.saturating_add(session_row_height);
+
+ if row_is_visible && session.is_active {
+ self.fill_rounded_rectangle_with_border(
+ layers,
+ 0,
+ euclid::rect(
+ session_x as f32,
+ y as f32,
+ session_width as f32,
+ session_row_height as f32,
+ ),
+ selected_bg,
+ selected_border,
+ SIDEBAR_ROW_RADIUS + 2.0,
+ CAPSULE_BORDER_WIDTH,
+ )
+ .context("sidebar selected session")?;
+ }
+
+ let icon_y = y + ((session_row_height.saturating_sub(icon_size)) / 2);
+ let text_y = y + ((session_row_height.saturating_sub(ui_cell_height)) / 2);
+ let status_size = 8usize;
+ let status_x = session_x
+ .saturating_add(session_width)
+ .saturating_sub(SIDEBAR_INSET + status_size);
+ let status_y = y + ((session_row_height.saturating_sub(status_size)) / 2);
+ if row_is_visible {
+ self.ui_items.push(UIItem {
+ x: session_x,
+ y: hit_y,
+ width: session_width,
+ height: hit_height,
+ item_type: UIItemType::ProjectSession(session.id.clone()),
+ });
+ let is_hovered = !suppress_hover
+ && self.is_pointer_over_ui_rect(
+ session_x,
+ y,
+ session_width,
+ session_row_height,
+ );
+ let action_size = section_button_size
+ .min(session_row_height.saturating_sub(12))
+ .max(24);
+ let action_x = session_x
+ .saturating_add(session_width)
+ .saturating_sub(SIDEBAR_INSET + action_size);
+ let action_y = y + ((session_row_height.saturating_sub(action_size)) / 2);
+ let text_right = if is_hovered { action_x } else { status_x };
+ let text_width = text_right.saturating_sub(session_text_x + SIDEBAR_INSET);
+ if is_hovered && !session.is_active {
+ self.fill_rounded_rectangle(
+ layers,
+ 0,
+ euclid::rect(
+ session_x as f32,
+ y as f32,
+ session_width as f32,
+ session_row_height as f32,
+ ),
+ foreground.mul_alpha(0.06),
+ SIDEBAR_ROW_RADIUS + 2.0,
+ )
+ .context("sidebar hovered session")?;
+ }
+ self.paint_sidebar_icon(
+ layers,
+ SvgIcon::SquareTerminal,
+ session_icon_x,
+ icon_y,
+ icon_size,
+ if session.is_active {
+ active_fg
+ } else {
+ muted_fg
+ },
+ )?;
+ self.paint_sidebar_text(
+ layers,
+ &ui_font,
+ ui_metrics,
+ &session.name,
+ session_text_x,
+ text_y,
+ text_width,
+ if session.is_active {
+ active_fg
+ } else {
+ foreground
+ },
+ )?;
+ if is_hovered {
+ let delete_hovered = self.is_pointer_over_ui_rect(
+ action_x,
+ action_y,
+ action_size,
+ action_size,
+ );
+ self.fill_rounded_rectangle(
+ layers,
+ 1,
+ euclid::rect(
+ action_x as f32,
+ action_y as f32,
+ action_size as f32,
+ action_size as f32,
+ ),
+ foreground.mul_alpha(if delete_hovered { 0.14 } else { 0.08 }),
+ SIDEBAR_ROW_RADIUS,
+ )
+ .context("sidebar delete session button")?;
+ self.ui_items.push(UIItem {
+ x: action_x,
+ y: action_y,
+ width: action_size,
+ height: action_size,
+ item_type: UIItemType::ProjectSessionArchive(session.id.clone()),
+ });
+ let action_icon_size =
+ header_icon_size.min(action_size.saturating_sub(10));
+ self.paint_sidebar_icon(
+ layers,
+ SvgIcon::Archive,
+ action_x + ((action_size.saturating_sub(action_icon_size)) / 2),
+ action_y + ((action_size.saturating_sub(action_icon_size)) / 2),
+ action_icon_size,
+ if delete_hovered { foreground } else { muted_fg },
+ )?;
+ } else {
+ self.fill_rounded_rectangle(
+ layers,
+ 1,
+ euclid::rect(
+ status_x as f32,
+ status_y as f32,
+ status_size as f32,
+ status_size as f32,
+ ),
+ if session.is_unread {
+ palette
+ .selection_bg
+ .to_linear()
+ .when_fully_transparent(foreground)
+ } else if session.is_pinned {
+ foreground.mul_alpha(0.68)
+ } else if session.is_materialized {
+ foreground.mul_alpha(0.45)
+ } else {
+ foreground.mul_alpha(0.16)
+ },
+ status_size as f32 / 2.0,
+ )
+ .context("sidebar session status")?;
+ }
+ }
+
+ virtual_y += session_row_height + row_gap;
+ }
+
+ if virtual_y > session_start_virtual_y && guide_bottom > guide_top {
+ self.filled_rectangle(
+ layers,
+ 0,
+ euclid::rect(
+ guide_x as f32,
+ guide_top as f32,
+ 1.0,
+ guide_bottom
+ .min(content_bottom)
+ .saturating_sub(guide_top + row_gap)
+ as f32,
+ ),
+ foreground.mul_alpha(0.16),
+ )
+ .context("sidebar session guide")?;
+ }
+ }
+ }
- 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(
+ let header_mask_height = list_top.saturating_sub(panel_y);
+ if header_mask_height > 0 {
+ self.filled_rectangle(
layers,
- SvgIcon::FolderOpen,
- row_icon_x,
- icon_y,
- icon_size,
- if is_active { active_fg } else { muted_fg },
- )?;
+ 2,
+ euclid::rect(
+ panel_x as f32,
+ panel_y as f32,
+ panel_width as f32,
+ header_mask_height as f32,
+ ),
+ sidebar_bg,
+ )
+ .context("sidebar header scroll mask")?;
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 },
+ "Workspaces",
+ item_x + SIDEBAR_INSET,
+ panel_y + SIDEBAR_INSET,
+ section_button_x.saturating_sub(item_x + SIDEBAR_INSET * 2),
+ muted_fg,
)?;
+ self.fill_rounded_rectangle(
+ layers,
+ 2,
+ euclid::rect(
+ section_button_x as f32,
+ section_button_y as f32,
+ section_button_size as f32,
+ section_button_size as f32,
+ ),
+ foreground.mul_alpha(0.08),
+ SIDEBAR_ROW_RADIUS,
+ )
+ .context("sidebar new project button repaint")?;
+ self.paint_sidebar_icon(
+ layers,
+ SvgIcon::FolderPlus,
+ section_button_x + ((section_button_size.saturating_sub(section_icon_size)) / 2),
+ section_button_y + ((section_button_size.saturating_sub(section_icon_size)) / 2),
+ section_icon_size,
+ foreground,
+ )?;
+ }
+
+ let bottom_mask_height = panel_y
+ .saturating_add(panel_height)
+ .saturating_sub(content_bottom);
+ if bottom_mask_height > 0 {
+ self.filled_rectangle(
+ layers,
+ 2,
+ euclid::rect(
+ panel_x as f32,
+ content_bottom as f32,
+ panel_width as f32,
+ bottom_mask_height as f32,
+ ),
+ sidebar_bg,
+ )
+ .context("sidebar bottom scroll mask")?;
+ }
- y += item_height + (SIDEBAR_INSET / 2);
+ if self.workspace_sidebar_scrollbar_visible() {
+ self.update_next_frame_time(self.workspace_sidebar_scrollbar_visible_until);
+ }
+
+ if self.workspace_sidebar_scrollbar_visible() {
+ let Some(scroll) = self.workspace_sidebar_scroll_geometry() else {
+ return Ok(());
+ };
+
+ let track_radius = scroll.track_width as f32 / 2.0;
+ self.fill_rounded_rectangle(
+ layers,
+ 2,
+ euclid::rect(
+ scroll.track_x as f32,
+ scroll.track_y as f32,
+ scroll.track_width as f32,
+ scroll.track_height as f32,
+ ),
+ foreground.mul_alpha(0.06),
+ track_radius,
+ )
+ .context("sidebar scroll track")?;
+
+ self.fill_rounded_rectangle(
+ layers,
+ 2,
+ euclid::rect(
+ scroll.track_x as f32,
+ scroll.thumb_y,
+ scroll.track_width as f32,
+ scroll.thumb_height,
+ ),
+ foreground.mul_alpha(0.34),
+ track_radius,
+ )
+ .context("sidebar scroll thumb")?;
+
+ let hit_slop = 6usize;
+ self.ui_items.push(UIItem {
+ x: scroll.track_x.saturating_sub(hit_slop),
+ y: scroll.track_y,
+ width: scroll.track_width + hit_slop * 2,
+ height: scroll.track_height,
+ item_type: UIItemType::WorkspaceSidebarScrollTrack,
+ });
+ self.ui_items.push(UIItem {
+ x: scroll.track_x.saturating_sub(hit_slop),
+ y: scroll.thumb_y.round().max(0.0) as usize,
+ width: scroll.track_width + hit_slop * 2,
+ height: scroll.thumb_height.round().max(1.0) as usize,
+ item_type: UIItemType::WorkspaceSidebarScrollThumb,
+ });
}
Ok(())
}
+ pub(crate) fn show_workspace_sidebar_scrollbar(&mut self) {
+ self.workspace_sidebar_scrollbar_visible_until = Some(
+ std::time::Instant::now()
+ + std::time::Duration::from_millis(SIDEBAR_SCROLLBAR_VISIBLE_MS),
+ );
+ }
+
+ fn workspace_sidebar_scrollbar_visible(&self) -> bool {
+ let actively_dragging = self.dragging.as_ref().is_some_and(|(item, _)| {
+ matches!(
+ item.item_type,
+ UIItemType::WorkspaceSidebarScrollTrack | UIItemType::WorkspaceSidebarScrollThumb
+ )
+ });
+ actively_dragging
+ || self
+ .workspace_sidebar_scrollbar_visible_until
+ .is_some_and(|until| until > std::time::Instant::now())
+ }
+
pub(crate) fn fill_rounded_rectangle(
&self,
layers: &mut TripleLayerQuadAllocator,
@@ -341,10 +928,42 @@ impl crate::TermWindow {
Ok(())
}
+ pub(crate) fn fill_rounded_rectangle_with_border(
+ &self,
+ layers: &mut TripleLayerQuadAllocator,
+ layer_num: usize,
+ rect: RectF,
+ fill: LinearRgba,
+ border: LinearRgba,
+ radius: f32,
+ border_width: f32,
+ ) -> anyhow::Result<()> {
+ let border_width = border_width
+ .max(0.0)
+ .min(rect.width() / 2.0)
+ .min(rect.height() / 2.0);
+ if border_width <= 0.0 {
+ return self.fill_rounded_rectangle(layers, layer_num, rect, fill, radius);
+ }
+
+ self.fill_rounded_rectangle(layers, layer_num, rect, border, radius)?;
+ self.fill_rounded_rectangle(
+ layers,
+ layer_num,
+ euclid::rect(
+ rect.min_x() + border_width,
+ rect.min_y() + border_width,
+ (rect.width() - border_width * 2.0).max(0.0),
+ (rect.height() - border_width * 2.0).max(0.0),
+ ),
+ fill,
+ (radius - border_width).max(0.0),
+ )
+ }
+
fn paint_sidebar_text(
&self,
layers: &mut TripleLayerQuadAllocator,
- palette: &ColorPalette,
font: &Rc<LoadedFont>,
metrics: RenderMetrics,
text: &str,
@@ -353,66 +972,11 @@ impl crate::TermWindow {
width: usize,
foreground: LinearRgba,
) -> anyhow::Result<()> {
- if width == 0 {
+ if text.is_empty() || 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(())
+ self.paint_ui_title_text(layers, font, &metrics, text, x, y, width, foreground)
}
fn paint_sidebar_icon(
@@ -433,7 +997,7 @@ impl crate::TermWindow {
.cached_svg_icon(icon, size)?
.texture_coords();
- let mut quad = layers.allocate(1)?;
+ let mut quad = layers.allocate(2)?;
quad.set_position(
x as f32 - left_offset,
y as f32 - top_offset,
diff --git a/wezterm-gui/src/termwindow/ui/tokens.rs b/wezterm-gui/src/termwindow/ui/tokens.rs
index 0e0dcee9..5ee89dce 100644
--- a/wezterm-gui/src/termwindow/ui/tokens.rs
+++ b/wezterm-gui/src/termwindow/ui/tokens.rs
@@ -5,26 +5,40 @@ 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_ROW_GAP: usize = 10;
+pub const SIDEBAR_ROW_RADIUS: f32 = 10.0;
pub const SIDEBAR_RESIZE_HANDLE_WIDTH: usize = 8;
-pub const PANE_NAV_INSET: usize = 6;
+pub const TAB_ROW_START_PADDING: usize = 16;
+pub const WINDOW_TAB_ACTION_RESERVED_WIDTH: usize = 48;
+pub const WINDOW_TAB_GAP: usize = 18;
+pub const WINDOW_TAB_RADIUS: f32 = 12.0;
+pub const TAB_CLOSE_HOVER_INSET: usize = 5;
+pub const TAB_CLOSE_HOVER_RADIUS: f32 = 999.0;
+pub const TAB_CLOSE_RIGHT_GAP: usize = 6;
+pub const TAB_VERTICAL_PADDING: usize = 8;
+
+pub const PANE_NAV_INSET: usize = 10;
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 const PANE_NAV_TAB_GAP: usize = 18;
+pub const PANE_NAV_EXTRA_HEIGHT: usize = 32;
+pub const PANE_NAV_MIN_HEIGHT: usize = 62;
+pub const PANE_NAV_MAX_HEIGHT: usize = 72;
+pub const PANE_NAV_TAB_RADIUS: f32 = 12.0;
+
+pub const ACTIVE_CAPSULE_CHANNEL: f32 = 8.0 / 255.0;
+pub const CAPSULE_BORDER_WIDTH: f32 = 1.0;
-pub fn mix(a: LinearRgba, b: LinearRgba, amount: f32) -> LinearRgba {
- let amount = amount.clamp(0.0, 1.0);
- let inverse = 1.0 - amount;
+pub fn active_capsule_bg(alpha: f32) -> LinearRgba {
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,
+ ACTIVE_CAPSULE_CHANNEL,
+ ACTIVE_CAPSULE_CHANNEL,
+ ACTIVE_CAPSULE_CHANNEL,
+ alpha.clamp(0.0, 1.0),
)
}
+
+pub fn capsule_border(foreground: LinearRgba, active: bool) -> LinearRgba {
+ foreground.mul_alpha(if active { 0.24 } else { 0.10 })
+}
diff --git a/window/Cargo.toml b/window/Cargo.toml
index 3f178ec1..8de6bbf3 100644
--- a/window/Cargo.toml
+++ b/window/Cargo.toml
@@ -90,6 +90,7 @@ wayland-egl = {workspace=true, optional=true}
[target.'cfg(target_os="macos")'.dependencies]
cgl.workspace = true
+block2.workspace = true
cocoa.workspace = true
core-foundation.workspace = true
core-graphics.workspace = true
diff --git a/window/src/lib.rs b/window/src/lib.rs
index 5bc77f35..86513333 100644
--- a/window/src/lib.rs
+++ b/window/src/lib.rs
@@ -310,6 +310,11 @@ pub trait WindowOps {
/// Show a native context menu at the specified client-area pixel coordinate.
fn show_context_menu(&self, _coords: Point, _items: Vec<ContextMenuItem>) {}
+ /// Show a native folder picker and invoke the callback with the selected directory.
+ fn pick_folder_async(&self, callback: Box<dyn FnOnce(Option<PathBuf>) + 'static>) {
+ callback(None);
+ }
+
/// Invalidate the window so that the entire client area will
/// be repainted shortly
fn invalidate(&self);
diff --git a/window/src/os/macos/window.rs b/window/src/os/macos/window.rs
index 407f5fbe..ab9485ee 100644
--- a/window/src/os/macos/window.rs
+++ b/window/src/os/macos/window.rs
@@ -16,6 +16,7 @@ use crate::{
};
use anyhow::{anyhow, bail, ensure};
use async_trait::async_trait;
+use block2::RcBlock;
use cocoa::appkit::{
self, CGFloat, NSApplication, NSApplicationActivateIgnoringOtherApps,
NSApplicationPresentationOptions, NSBackingStoreBuffered, NSEvent, NSEventModifierFlags,
@@ -52,6 +53,7 @@ use std::path::{Path, PathBuf};
use std::ptr::NonNull;
use std::rc::Rc;
use std::str::FromStr;
+use std::sync::{Arc, Mutex};
use std::time::Instant;
use wezterm_font::FontConfiguration;
use wezterm_input_types::{is_ascii_control, IntegratedTitleButtonStyle, KeyboardLedStatus};
@@ -752,11 +754,13 @@ impl WindowOps for Window {
{
Connection::with_window_inner(self.id, move |inner| {
if let Some(window_view) = WindowView::get_this(unsafe { &**inner.view }) {
- window_view
- .inner
- .borrow_mut()
- .events
- .dispatch(WindowEvent::Notification(Box::new(t)));
+ if let Ok(mut inner) = window_view.inner.try_borrow_mut() {
+ inner
+ .events
+ .dispatch(WindowEvent::Notification(Box::new(t)));
+ } else {
+ log::trace!("skipping notification while window is busy");
+ }
}
Ok(())
});
@@ -804,6 +808,52 @@ impl WindowOps for Window {
});
}
+ fn pick_folder_async(&self, callback: Box<dyn FnOnce(Option<PathBuf>) + 'static>) {
+ unsafe {
+ let _pool = NSAutoreleasePool::new(nil);
+ let panel: id = msg_send![class!(NSOpenPanel), openPanel];
+ let panel = StrongPtr::retain(panel);
+ let () = msg_send![*panel, setCanChooseFiles: NO];
+ let () = msg_send![*panel, setCanChooseDirectories: YES];
+ let () = msg_send![*panel, setAllowsMultipleSelection: NO];
+ let () = msg_send![*panel, setCanCreateDirectories: YES];
+ let () = msg_send![*panel, setResolvesAliases: YES];
+ let title = nsstring("Open Project");
+ let prompt = nsstring("Open");
+ let () = msg_send![*panel, setTitle: *title];
+ let () = msg_send![*panel, setPrompt: *prompt];
+
+ const NS_MODAL_RESPONSE_OK: NSInteger = 1;
+ let callback = Arc::new(Mutex::new(Some(callback)));
+ let callback_for_block = callback.clone();
+ let panel_for_block = panel.clone();
+ let block = RcBlock::new(move |result: NSInteger| {
+ let selected_path = if result != NS_MODAL_RESPONSE_OK {
+ None
+ } else {
+ let url: id = msg_send![*panel_for_block, URL];
+ if url == nil {
+ None
+ } else {
+ let path: id = msg_send![url, path];
+ if path == nil {
+ None
+ } else {
+ Some(PathBuf::from(nsstring_to_str(path)))
+ }
+ }
+ };
+
+ if let Ok(mut callback) = callback_for_block.lock() {
+ if let Some(callback) = callback.take() {
+ callback(selected_path);
+ }
+ }
+ });
+ let () = msg_send![*panel, beginWithCompletionHandler: &*block];
+ }
+ }
+
fn invalidate(&self) {
Connection::with_window_inner(self.id, |inner| {
inner.invalidate();
@@ -1677,6 +1727,11 @@ fn thinkterm_titlebar_sidebar_button(titlebar_view_container: &StrongPtr) -> Opt
continue;
}
+ let responds_to_tag: BOOL = msg_send![subview, respondsToSelector: sel!(tag)];
+ if responds_to_tag != YES {
+ continue;
+ }
+
let tag: NSInteger = msg_send![subview, tag];
if tag == THINKTERM_TITLEBAR_SIDEBAR_BUTTON_TAG {
return Some(subview);
@@ -2493,7 +2548,10 @@ impl WindowView {
let native_full_screen;
{
- let inner = self.inner.borrow();
+ let Ok(inner) = self.inner.try_borrow() else {
+ log::trace!("skipping application presentation update while window is busy");
+ return;
+ };
native_full_screen = inner.config.native_macos_fullscreen_mode;
is_simple_full_screen = inner.fullscreen.is_some();
}
@@ -2521,20 +2579,22 @@ impl WindowView {
extern "C" fn did_become_key(this: &mut Object, _sel: Sel, _id: id) {
if let Some(this) = Self::get_this(this) {
- this.inner
- .borrow_mut()
- .events
- .dispatch(WindowEvent::FocusChanged(true));
+ if let Ok(mut inner) = this.inner.try_borrow_mut() {
+ inner.events.dispatch(WindowEvent::FocusChanged(true));
+ } else {
+ log::trace!("skipping focus gained notification while window is busy");
+ }
this.update_application_presentation(true);
}
}
extern "C" fn did_resign_key(this: &mut Object, _sel: Sel, _id: id) {
if let Some(this) = Self::get_this(this) {
- this.inner
- .borrow_mut()
- .events
- .dispatch(WindowEvent::FocusChanged(false));
+ if let Ok(mut inner) = this.inner.try_borrow_mut() {
+ inner.events.dispatch(WindowEvent::FocusChanged(false));
+ } else {
+ log::trace!("skipping focus lost notification while window is busy");
+ }
this.update_application_presentation(true);
}
}
@@ -3337,7 +3397,10 @@ impl WindowView {
extern "C" fn draw_rect(view: &mut Object, sel: Sel, _dirty_rect: NSRect) {
if let Some(this) = Self::get_this(view) {
- let mut inner = this.inner.borrow_mut();
+ let Ok(mut inner) = this.inner.try_borrow_mut() else {
+ log::trace!("skipping draw while window is busy");
+ return;
+ };
if inner.screen_changed {
// If the screen resolution changed (which can also
@@ -3365,12 +3428,15 @@ impl WindowView {
.await;
Connection::with_window_inner(window_id, move |inner| {
if let Some(window_view) = WindowView::get_this(unsafe { &**inner.view }) {
- let mut state = window_view.inner.borrow_mut();
- state.paint_throttled = false;
- if state.invalidated {
- unsafe {
- let () = msg_send![*inner.view, setNeedsDisplay: YES];
+ if let Ok(mut state) = window_view.inner.try_borrow_mut() {
+ state.paint_throttled = false;
+ if state.invalidated {
+ unsafe {
+ let () = msg_send![*inner.view, setNeedsDisplay: YES];
+ }
}
+ } else {
+ log::trace!("skipping paint throttle update while window is busy");
}
}
Ok(())