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.

Add onboarding flow and multi window support

RoversX3350cb572e54
diff --git a/wezterm-gui/src/frontend.rs b/wezterm-gui/src/frontend.rs
index ac901652..20ebf66b 100644
--- a/wezterm-gui/src/frontend.rs
+++ b/wezterm-gui/src/frontend.rs
@@ -1,10 +1,9 @@
use crate::scripting::guiwin::GuiWin;
use crate::spawn::SpawnWhere;
-use crate::termwindow::TermWindowNotif;
use crate::TermWindow;
use ::window::*;
-use anyhow::{Context, Error};
-use config::keyassignment::{KeyAssignment, SpawnCommand};
+use anyhow::{anyhow, Context, Error};
+use config::keyassignment::{KeyAssignment, SpawnCommand, SpawnTabDomain};
use config::{ConfigSubscription, NotificationHandling};
use mux::client::ClientId;
use mux::window::WindowId as MuxWindowId;
@@ -19,7 +18,12 @@ use wezterm_toast_notification::*;
pub struct GuiFrontEnd {
connection: Rc<Connection>,
- switching_workspaces: RefCell<bool>,
+ // Depth counter: > 0 means at least one window is mid-switch (materializing
+ // a workspace it is about to adopt). While non-zero the additive reconcile
+ // is suppressed so it can't spawn a duplicate window for the mux window
+ // being adopted. A counter (rather than a bool) lets concurrent switches /
+ // Dock "New Window" clicks nest without one clobbering another's guard.
+ switching_workspaces: RefCell<usize>,
spawned_mux_window: RefCell<HashSet<MuxWindowId>>,
known_windows: RefCell<BTreeMap<Window, MuxWindowId>>,
client_id: Arc<ClientId>,
@@ -43,7 +47,7 @@ impl GuiFrontEnd {
let front_end = Rc::new(GuiFrontEnd {
connection,
- switching_workspaces: RefCell::new(false),
+ switching_workspaces: RefCell::new(0),
spawned_mux_window: RefCell::new(HashSet::new()),
known_windows: RefCell::new(BTreeMap::new()),
client_id: client_id.clone(),
@@ -66,9 +70,20 @@ impl GuiFrontEnd {
.detach();
}
}
+ MuxNotification::WindowCreated(window_id) => {
+ promise::spawn::spawn_into_main_thread(async move {
+ let fe = crate::frontend::front_end();
+ if fe.spawned_mux_window.borrow().contains(&window_id) {
+ return;
+ }
+ if !fe.is_switching_workspace() {
+ fe.reconcile_workspace();
+ }
+ })
+ .detach();
+ }
MuxNotification::WindowWorkspaceChanged(_)
| MuxNotification::ActiveWorkspaceChanged(_)
- | MuxNotification::WindowCreated(_)
| MuxNotification::WindowRemoved(_) => {
promise::spawn::spawn_into_main_thread(async move {
let fe = crate::frontend::front_end();
@@ -310,7 +325,7 @@ impl GuiFrontEnd {
Connection::get().unwrap().terminate_message_loop();
}
KeyAssignment::SpawnWindow => {
- spawn_command(&SpawnCommand::default(), SpawnWhere::NewWindow);
+ front_end().spawn_space_window();
}
KeyAssignment::SpawnTab(spawn_where) => {
spawn_command(
@@ -357,70 +372,55 @@ impl GuiFrontEnd {
pub fn reconcile_workspace(&self) -> Future<()> {
let mut promise = Promise::new();
let mux = Mux::get();
- let workspace = mux.active_workspace_for_client(&self.client_id);
-
- if mux.is_workspace_empty(&workspace) {
- // We don't want to silently kill off things that might
- // be running in other workspaces, so let's pick one
- // and activate it
- if self.is_switching_workspace() {
- promise.ok(());
- return promise.get_future().unwrap();
- }
- for workspace in mux.iter_workspaces() {
- if !mux.is_workspace_empty(&workspace) {
- mux.set_active_workspace_for_client(&self.client_id, &workspace);
- log::debug!("using {} instead, as it is not empty", workspace);
- break;
- }
- }
- }
- let workspace = mux.active_workspace_for_client(&self.client_id);
- log::debug!("workspace is {}, fixup windows", workspace);
-
- let mut mux_windows = mux.iter_windows_in_workspace(&workspace);
-
- // First, repurpose existing windows.
- // Note that both iter_windows_in_workspace and self.known_windows have a
- // deterministic iteration order, so switching back and forth should result
- // in a consistent mux <-> gui window mapping.
+ // Each GUI window is pinned to its own mux window (its Space). We do
+ // NOT force every window onto a single active workspace any more, since
+ // ThinkTerm intentionally lets multiple windows live in different
+ // Spaces (workspaces) at the same time. Reconcile is therefore additive
+ // and only does two non-destructive things:
+ // 1. Close GUI windows whose mux window has gone away (e.g. the last
+ // pane in that window exited and the mux killed the window).
+ // 2. Create GUI windows for mux windows in the active workspace that
+ // don't have a GUI window yet (startup's first window, and the
+ // native SpawnWindow path that adds a mux window to the current
+ // workspace). Windows pinned to live mux windows in *other*
+ // workspaces are never touched.
+
+ // 1. Drop GUI windows whose mux window no longer exists.
let known_windows = std::mem::take(&mut *self.known_windows.borrow_mut());
let mut windows = BTreeMap::new();
- let mut unused = BTreeMap::new();
-
for (window, window_id) in known_windows.into_iter() {
- if let Some(idx) = mux_windows.iter().position(|&id| id == window_id) {
- // it already points to the desired mux window
+ if mux.get_window(window_id).is_some() {
windows.insert(window, window_id);
- mux_windows.remove(idx);
} else {
- unused.insert(window, window_id);
- }
- }
-
- let mut mux_windows = mux_windows.into_iter();
-
- for (window, old_id) in unused.into_iter() {
- if let Some(mux_window_id) = mux_windows.next() {
- window.notify(TermWindowNotif::SwitchToMuxWindow(mux_window_id));
- windows.insert(window, mux_window_id);
- } else {
- // We have more windows than are in the new workspace;
- // we no longer need this one!
window.close();
- front_end().spawned_mux_window.borrow_mut().remove(&old_id);
+ self.spawned_mux_window.borrow_mut().remove(&window_id);
}
}
-
- log::trace!("reconcile: windows -> {:?}", windows);
*self.known_windows.borrow_mut() = windows;
- let future = promise.get_future().unwrap();
+ // 2. Spawn GUI windows for active-workspace mux windows that lack one.
+ let workspace = mux.active_workspace_for_client(&self.client_id);
+ let mux_windows = mux.iter_windows_in_workspace(&workspace);
+ log::debug!(
+ "reconcile: active_ws={} mux_in_active={:?} known={:?} spawned={:?}",
+ workspace,
+ mux_windows,
+ self.known_windows
+ .borrow()
+ .values()
+ .copied()
+ .collect::<Vec<_>>(),
+ self.spawned_mux_window
+ .borrow()
+ .iter()
+ .copied()
+ .collect::<Vec<_>>(),
+ );
- // then spawn any new windows that are needed
+ let future = promise.get_future().unwrap();
promise::spawn::spawn(async move {
- while let Some(mux_window_id) = mux_windows.next() {
+ for mux_window_id in mux_windows {
if front_end().has_mux_window(mux_window_id)
|| front_end()
.spawned_mux_window
@@ -444,13 +444,109 @@ impl GuiFrontEnd {
.remove(&mux_window_id);
}
}
- *front_end().switching_workspaces.borrow_mut() = false;
+ // Note: reconcile does not touch the switch-depth counter; only the
+ // paired switch operations (which increment on entry) decrement it.
promise.ok(());
})
.detach();
future
}
+ fn spawn_space_window(&self) {
+ // Each Dock "New Window" gets its own Space and its own GUI window, and
+ // must work regardless of whatever else is in flight. We claim a
+ // distinct (unoccupied) Space synchronously so rapid repeated clicks
+ // each land on a different Space, then suppress reconcile only while we
+ // materialize + create this window.
+ let space_owner_id = crate::workspace_threads::next_space_owner_id();
+ let active_space_id = crate::workspace_threads::claim_space_for_new_window(space_owner_id);
+ self.set_switching_workspaces(true);
+
+ promise::spawn::spawn(async move {
+ let result = async {
+ let (mux_window_id, created_mux_window) =
+ Self::materialize_space_window_for_app(&active_space_id).await?;
+ front_end()
+ .spawned_mux_window
+ .borrow_mut()
+ .insert(mux_window_id);
+ if let Err(err) = TermWindow::new_window_with_claimed_space(
+ mux_window_id,
+ space_owner_id,
+ active_space_id.clone(),
+ )
+ .await
+ {
+ if created_mux_window {
+ Mux::get().kill_window(mux_window_id);
+ }
+ return Err(err);
+ }
+ Ok(())
+ }
+ .await;
+
+ if let Err(err) = result {
+ crate::workspace_threads::release_window_space(space_owner_id);
+ log::error!("failed to create ThinkTerm Space window: {err:#}");
+ }
+ front_end().set_switching_workspaces(false);
+ })
+ .detach();
+ }
+
+ async fn materialize_space_window_for_app(
+ space_id: &str,
+ ) -> anyhow::Result<(MuxWindowId, bool)> {
+ let mux = Mux::get();
+ let thread_id = crate::workspace_threads::ensure_active_thread_for_space(space_id)
+ .ok_or_else(|| anyhow!("failed to ensure active thread for Space {space_id}"))?;
+ let live_workspaces = mux.iter_workspaces();
+ let plan = crate::workspace_threads::activate_thread_record(&thread_id, &live_workspaces)
+ .ok_or_else(|| {
+ anyhow!("failed to activate thread {thread_id} for Space {space_id}")
+ })?;
+ let created_mux_window = plan.needs_materialize;
+
+ if plan.needs_materialize {
+ let config = config::configuration();
+ let dpi = config.dpi.unwrap_or_else(|| ::window::default_dpi());
+ let size = config.initial_size(dpi as u32, crate::cell_pixel_dims(&config, dpi).ok());
+ let term_config: Arc<dyn wezterm_term::TerminalConfiguration> =
+ Arc::new(config::TermConfig::with_config(config.clone()));
+ let layout = crate::workspace_threads::thread_layout(&plan.thread_id);
+ let remote_spec = crate::ssh_hosts::host_spec(
+ crate::workspace_threads::remote_host_id_for_project_id(&plan.project_id),
+ );
+ let (initial_cwd, default_domain) = if let Some(spec) = remote_spec.as_ref() {
+ let domain_name = crate::ssh_hosts::ensure_ssh_domain_registered(spec)?;
+ (None, SpawnTabDomain::DomainName(domain_name))
+ } else {
+ (
+ plan.project_path.to_str().map(|path| path.to_string()),
+ SpawnTabDomain::DefaultDomain,
+ )
+ };
+
+ crate::workspace_threads::materialize_thread(
+ plan.workspace_name.clone(),
+ layout,
+ initial_cwd,
+ size,
+ None,
+ term_config,
+ default_domain,
+ )
+ .await?;
+ }
+
+ mux.iter_windows_in_workspace(&plan.workspace_name)
+ .into_iter()
+ .next()
+ .map(|window_id| (window_id, created_mux_window))
+ .ok_or_else(|| anyhow!("Space workspace {} has no mux window", plan.workspace_name))
+ }
+
pub fn has_mux_window(&self, mux_window_id: MuxWindowId) -> bool {
for &mux_id in self.known_windows.borrow().values() {
if mux_id == mux_window_id {
@@ -463,11 +559,15 @@ impl GuiFrontEnd {
pub fn switch_workspace(&self, workspace: &str) {
let mux = Mux::get();
mux.set_active_workspace_for_client(&self.client_id, workspace);
- *self.switching_workspaces.borrow_mut() = false;
+ self.set_switching_workspaces(false);
self.reconcile_workspace();
}
pub fn record_known_window(&self, window: Window, mux_window_id: MuxWindowId) {
+ // Mark this mux window as having a GUI window so the additive reconcile
+ // never re-creates a window for it (e.g. after the user closes it while
+ // its mux window keeps running in the background).
+ self.spawned_mux_window.borrow_mut().insert(mux_window_id);
self.known_windows
.borrow_mut()
.insert(window, mux_window_id);
@@ -483,6 +583,24 @@ impl GuiFrontEnd {
}
}
+ /// Re-point an existing GUI window at a different mux window. Used when a
+ /// window switches the Space it is showing in place, so that
+ /// `known_windows` stays accurate without relying on reconcile to rebuild
+ /// the whole mux <-> gui mapping.
+ pub fn rebind_known_window(&self, window: &Window, mux_window_id: MuxWindowId) {
+ self.known_windows
+ .borrow_mut()
+ .insert(window.clone(), mux_window_id);
+ // Mark the adopted mux window as spawned so reconcile won't create a
+ // duplicate for it. We deliberately do NOT un-mark the window's
+ // *previous* mux window: after an in-window Space switch it keeps
+ // running in the background, and must stay protected so the additive
+ // reconcile never resurrects it as a stray "different" window (e.g.
+ // after another window is closed). A mux window only leaves the set
+ // when it actually dies (cleanup in `reconcile_workspace`).
+ self.spawned_mux_window.borrow_mut().insert(mux_window_id);
+ }
+
pub fn invalidate_all_windows(&self) {
for window in self.known_windows.borrow().keys() {
window.invalidate();
@@ -490,7 +608,20 @@ impl GuiFrontEnd {
}
pub fn is_switching_workspace(&self) -> bool {
- *self.switching_workspaces.borrow()
+ *self.switching_workspaces.borrow() > 0
+ }
+
+ /// Enter (true) or leave (false) a workspace-switch critical section,
+ /// during which the additive reconcile is suppressed so it doesn't spawn a
+ /// duplicate window for the mux window being adopted. Calls must be paired;
+ /// the underlying depth counter lets concurrent switches nest safely.
+ pub fn set_switching_workspaces(&self, value: bool) {
+ let mut depth = self.switching_workspaces.borrow_mut();
+ if value {
+ *depth += 1;
+ } else {
+ *depth = depth.saturating_sub(1);
+ }
}
pub fn gui_window_for_mux_window(&self, mux_window_id: MuxWindowId) -> Option<GuiWin> {
@@ -527,15 +658,11 @@ pub struct WorkspaceSwitcher {
impl WorkspaceSwitcher {
pub fn new(new_name: &str) -> Self {
- *front_end().switching_workspaces.borrow_mut() = true;
+ front_end().set_switching_workspaces(true);
Self {
new_name: new_name.to_string(),
}
}
-
- pub fn do_switch(self) {
- // Drop is invoked, which will complete the switch
- }
}
impl Drop for WorkspaceSwitcher {
diff --git a/wezterm-gui/src/native_settings.rs b/wezterm-gui/src/native_settings.rs
index c65feec7..995daac1 100644
--- a/wezterm-gui/src/native_settings.rs
+++ b/wezterm-gui/src/native_settings.rs
@@ -11,8 +11,9 @@ pub(crate) const DEFAULT_SETTINGS_FONT_WEIGHT: u16 = 600;
pub(crate) const DEFAULT_SIDEBAR_FONT_SIZE: f64 = 15.0;
pub(crate) const DEFAULT_TAB_FONT_SIZE: f64 = 14.0;
pub(crate) const DEFAULT_PANE_HEADER_FONT_SIZE: f64 = 14.0;
+pub(crate) const ONBOARDING_VERSION: u32 = 1;
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum NativeThemeMode {
System,
@@ -52,7 +53,7 @@ impl NativeThemeMode {
}
}
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum NativeAppIcon {
Default,
@@ -81,7 +82,7 @@ impl NativeAppIcon {
}
}
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum NativeRendererBackend {
OpenGL,
@@ -104,6 +105,32 @@ impl NativeRendererBackend {
}
}
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
+#[serde(rename_all = "lowercase")]
+pub(crate) enum NativeLanguagePreference {
+ System,
+ English,
+ Chinese,
+ Japanese,
+}
+
+impl Default for NativeLanguagePreference {
+ fn default() -> Self {
+ Self::System
+ }
+}
+
+impl NativeLanguagePreference {
+ pub(crate) fn label(self) -> &'static str {
+ match self {
+ Self::System => "Follow System",
+ Self::English => "English",
+ Self::Chinese => "中文",
+ Self::Japanese => "日本語",
+ }
+ }
+}
+
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default)]
pub(crate) struct NativeAppearanceSettings {
@@ -135,6 +162,24 @@ pub(crate) struct NativeDeveloperSettings {
pub(crate) developer_mode: bool,
}
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(default)]
+pub(crate) struct NativeOnboardingSettings {
+ pub(crate) seen_version: u32,
+ pub(crate) language: NativeLanguagePreference,
+ pub(crate) show_left_sidebar_by_default: bool,
+}
+
+impl Default for NativeOnboardingSettings {
+ fn default() -> Self {
+ Self {
+ seen_version: 0,
+ language: NativeLanguagePreference::System,
+ show_left_sidebar_by_default: true,
+ }
+ }
+}
+
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default)]
pub(crate) struct NativeCompatibilitySettings {
@@ -167,6 +212,7 @@ pub(crate) struct ThinkTermNativeSettings {
pub(crate) terminal: NativeTerminalSettings,
pub(crate) chrome: NativeChromeSettings,
pub(crate) developer: NativeDeveloperSettings,
+ pub(crate) onboarding: NativeOnboardingSettings,
pub(crate) compatibility: NativeCompatibilitySettings,
pub(crate) window: NativeWindowSettings,
}
@@ -179,6 +225,7 @@ impl Default for ThinkTermNativeSettings {
terminal: NativeTerminalSettings::default(),
chrome: NativeChromeSettings::default(),
developer: NativeDeveloperSettings::default(),
+ onboarding: NativeOnboardingSettings::default(),
compatibility: NativeCompatibilitySettings::default(),
window: NativeWindowSettings::default(),
}
@@ -226,6 +273,10 @@ pub(crate) fn load() -> ThinkTermNativeSettings {
settings_cache().lock().clone()
}
+pub(crate) fn should_show_onboarding(settings: &ThinkTermNativeSettings) -> bool {
+ settings.onboarding.seen_version < ONBOARDING_VERSION
+}
+
pub(crate) fn reload_from_disk() -> ThinkTermNativeSettings {
let settings = load_from_disk();
*settings_cache().lock() = settings.clone();
@@ -340,6 +391,10 @@ pub(crate) fn save_workspace_sidebar_width(width: usize) -> anyhow::Result<()> {
save(&settings)
}
+pub(crate) fn mark_onboarding_seen(settings: &mut ThinkTermNativeSettings) {
+ settings.onboarding.seen_version = ONBOARDING_VERSION;
+}
+
pub(crate) fn tab_font_size() -> f64 {
load()
.chrome
@@ -365,3 +420,33 @@ pub(crate) fn main_window_renderer(
.main_renderer
.unwrap_or_else(|| NativeRendererBackend::from_front_end(config_front_end))
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn onboarding_is_required_before_current_version() {
+ let mut settings = ThinkTermNativeSettings::default();
+ settings.onboarding.seen_version = 0;
+
+ assert!(should_show_onboarding(&settings));
+ }
+
+ #[test]
+ fn onboarding_is_not_required_after_current_version_is_seen() {
+ let mut settings = ThinkTermNativeSettings::default();
+ settings.onboarding.seen_version = ONBOARDING_VERSION;
+
+ assert!(!should_show_onboarding(&settings));
+ }
+
+ #[test]
+ fn mark_onboarding_seen_stores_current_version() {
+ let mut settings = ThinkTermNativeSettings::default();
+
+ mark_onboarding_seen(&mut settings);
+
+ assert_eq!(settings.onboarding.seen_version, ONBOARDING_VERSION);
+ }
+}
diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rs
index 7816ad48..d36fec24 100644
--- a/wezterm-gui/src/settings_window.rs
+++ b/wezterm-gui/src/settings_window.rs
@@ -224,6 +224,7 @@ enum SettingsAction {
ToggleImportField(ImportFieldId),
ToggleMainWindowFrameRestore,
ToggleDeveloperMode,
+ ShowOnboardingNow,
ToggleMemoryMonitoring,
RefreshMemorySnapshot,
CopyMemorySnapshot,
@@ -2129,6 +2130,29 @@ impl SettingsWindow {
}
}
}
+ SettingsAction::ShowOnboardingNow => {
+ self.ui.open_dropdown = None;
+ let Some(front_end) = crate::frontend::try_front_end() else {
+ self.status = "No main ThinkTerm window is available.".to_string();
+ return;
+ };
+ let windows = front_end.gui_windows();
+ if windows.is_empty() {
+ self.status = "No main ThinkTerm window is open.".to_string();
+ } else {
+ let count = windows.len();
+ for gui_window in windows {
+ gui_window
+ .window
+ .notify(crate::termwindow::TermWindowNotif::Apply(Box::new(
+ |term_window| {
+ term_window.show_onboarding();
+ },
+ )));
+ }
+ self.status = format!("Onboarding opened in {count} main window(s).");
+ }
+ }
SettingsAction::ToggleMemoryMonitoring => {
self.ui.open_dropdown = None;
self.ui.memory_monitoring = !self.ui.memory_monitoring;
@@ -3048,8 +3072,8 @@ impl SettingsWindow {
let scroll = self.ui.content_scroll.offset;
let row_step = self.settings_row_step();
let section_y = CONTENT_SECTION_Y - scroll;
- let (card_y, first_row_y) = self.settings_card_geometry(section_y, 2);
- let card_height = self.settings_card_height(2);
+ let (card_y, first_row_y) = self.settings_card_geometry(section_y, 3);
+ let card_height = self.settings_card_height(3);
let button_y = card_y + card_height + self.settings_section_card_gap();
self.ui.content_scroll.set_extents(
self.content_bottom(),
@@ -3096,27 +3120,40 @@ impl SettingsWindow {
} else {
"Hidden"
},
+ false,
+ )?;
+ self.paint_setting_row(
+ layers,
+ row_x,
+ first_row_y + row_step * 2.0,
+ row_width,
+ "Onboarding",
+ "Open the setup wizard without changing the saved seen version.",
+ "Manual test entry",
true,
)?;
+ let developer_label = if self.developer_mode_enabled() {
+ "Disable Developer Mode"
+ } else {
+ "Enable Developer Mode"
+ };
+ let developer_width = self.button_width_for_label(developer_label, 300.0);
self.draw_button(
layers,
x,
button_y,
- self.button_width_for_label(
- if self.developer_mode_enabled() {
- "Disable Developer Mode"
- } else {
- "Enable Developer Mode"
- },
- 300.0,
- ),
- if self.developer_mode_enabled() {
- "Disable Developer Mode"
- } else {
- "Enable Developer Mode"
- },
+ developer_width,
+ developer_label,
SettingsAction::ToggleDeveloperMode,
)?;
+ self.draw_button(
+ layers,
+ x + developer_width + 14.0,
+ button_y,
+ self.button_width_for_label("Show Onboarding Now", 300.0),
+ "Show Onboarding Now",
+ SettingsAction::ShowOnboardingNow,
+ )?;
Ok(())
}
diff --git a/wezterm-gui/src/termwindow/content_view.rs b/wezterm-gui/src/termwindow/content_view.rs
index 76e9cdec..c7e1d6ad 100644
--- a/wezterm-gui/src/termwindow/content_view.rs
+++ b/wezterm-gui/src/termwindow/content_view.rs
@@ -7,7 +7,9 @@
use crate::quad::TripleLayerQuadAllocator;
use crate::termwindow::TermWindow;
use crate::ui::{DrawContext, UiPalette};
+use std::path::PathBuf;
use std::rc::Rc;
+use std::time::Instant;
use wezterm_font::LoadedFont;
use wezterm_term::{KeyCode, KeyModifiers};
use window::{MouseEventKind as WMEK, RectF};
@@ -34,6 +36,11 @@ pub(crate) trait ContentView {
false
}
+ /// Schedule a follow-up repaint for view-local animations.
+ fn next_frame_time(&self) -> Option<Instant> {
+ None
+ }
+
/// Paint the view into `area` (the terminal content rect). `cursor_on` is
/// the current blink phase for any focused caret.
fn paint(
@@ -43,6 +50,8 @@ pub(crate) trait ContentView {
area: RectF,
palette: UiPalette,
font: &Rc<LoadedFont>,
+ title_font: &Rc<LoadedFont>,
+ section_font: &Rc<LoadedFont>,
cursor_on: bool,
) -> anyhow::Result<()>;
@@ -55,6 +64,17 @@ pub(crate) trait ContentView {
ContentViewResponse::Redraw
}
+ /// Handle the synthetic tab close button / Escape-style close request.
+ fn on_close_requested(&mut self) -> ContentViewResponse {
+ ContentViewResponse::Close
+ }
+
+ /// Handle a folder selected by a native folder picker that was initiated by
+ /// this view.
+ fn on_folder_picked(&mut self, _path: PathBuf) -> ContentViewResponse {
+ ContentViewResponse::Ignored
+ }
+
/// Text to copy to the clipboard for ⌘C (e.g. the focused field), if any.
fn copy_text(&self) -> Option<String> {
None
diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs
index 9faba08e..662d8aed 100644
--- a/wezterm-gui/src/termwindow/mod.rs
+++ b/wezterm-gui/src/termwindow/mod.rs
@@ -88,6 +88,7 @@ pub mod content_view;
pub mod keyevent;
pub mod modal;
mod mouseevent;
+pub mod onboarding;
pub mod palette;
pub mod paneselect;
mod prevcursor;
@@ -896,6 +897,22 @@ impl TermWindow {
self.quad_generation += 1;
self.load_os_parameters();
+ if focused {
+ // Each window is pinned to its own Space (workspace). Keep the
+ // mux's single global "active workspace" pointed at whichever
+ // window is focused, so defaults like spawn-new-window land in the
+ // right place. Reconcile is additive, so this is non-destructive.
+ let mux = Mux::get();
+ let ws = mux
+ .get_window(self.mux_window_id)
+ .map(|w| w.get_workspace().to_string());
+ if let Some(ws) = ws {
+ if mux.active_workspace() != ws {
+ mux.set_active_workspace(&ws);
+ }
+ }
+ }
+
if self.focused.is_none() {
self.last_mouse_click = None;
self.current_mouse_buttons.clear();
@@ -951,6 +968,27 @@ impl TermWindow {
impl TermWindow {
pub async fn new_window(mux_window_id: MuxWindowId) -> anyhow::Result<()> {
+ Self::new_window_impl(mux_window_id, None, true).await
+ }
+
+ pub async fn new_window_with_claimed_space(
+ mux_window_id: MuxWindowId,
+ space_owner_id: u64,
+ active_space_id: String,
+ ) -> anyhow::Result<()> {
+ Self::new_window_impl(
+ mux_window_id,
+ Some((space_owner_id, active_space_id)),
+ false,
+ )
+ .await
+ }
+
+ async fn new_window_impl(
+ mux_window_id: MuxWindowId,
+ claimed_space: Option<(u64, String)>,
+ restore_saved_thread: bool,
+ ) -> anyhow::Result<()> {
let config = configuration();
let native_settings = crate::native_settings::load();
let main_renderer =
@@ -1051,9 +1089,12 @@ impl TermWindow {
let render_state = None;
let connection_name = Connection::get().unwrap().name();
- let space_owner_id = crate::workspace_threads::next_space_owner_id();
- let active_space_id =
- crate::workspace_threads::claim_initial_space_for_window(space_owner_id);
+ let (space_owner_id, active_space_id) = claimed_space.unwrap_or_else(|| {
+ let space_owner_id = crate::workspace_threads::next_space_owner_id();
+ let active_space_id =
+ crate::workspace_threads::claim_initial_space_for_window(space_owner_id);
+ (space_owner_id, active_space_id)
+ });
let workspace_layout_structure_fingerprint =
crate::workspace_threads::window_layout_structure_fingerprint(mux_window_id);
@@ -1179,7 +1220,7 @@ impl TermWindow {
active_space_id,
workspace_layout_structure_fingerprint,
workspace_sidebar_width,
- workspace_sidebar_collapsed: false,
+ workspace_sidebar_collapsed: !native_settings.onboarding.show_left_sidebar_by_default,
workspace_sidebar_scroll_offset: 0.0,
workspace_sidebar_scrollbar_visible_until: None,
last_ui_item: None,
@@ -1304,13 +1345,22 @@ impl TermWindow {
myself.apply_native_terminal_settings();
myself.apply_workspace_thread_font_scales();
myself.load_os_parameters();
- if let Some(thread_id) =
- crate::workspace_threads::thread_to_restore_for_space(&myself.active_space_id)
- {
- myself.activate_workspace_thread_for_new_window(thread_id, &window, mux_window_id);
+ if restore_saved_thread {
+ if let Some(thread_id) =
+ crate::workspace_threads::thread_to_restore_for_space(&myself.active_space_id)
+ {
+ myself.activate_workspace_thread_for_new_window(
+ thread_id,
+ &window,
+ mux_window_id,
+ );
+ } else {
+ myself.sync_current_workspace_thread();
+ }
} else {
myself.sync_current_workspace_thread();
}
+ myself.maybe_show_onboarding();
window.show();
myself.subscribe_to_pane_updates();
myself.emit_window_event("window-config-reloaded", None);
@@ -1796,24 +1846,7 @@ impl TermWindow {
func(self);
}
TermWindowNotif::SwitchToMuxWindow(mux_window_id) => {
- self.mux_window_id = mux_window_id;
- *self.mux_window_id_for_subscriptions.lock().unwrap() = mux_window_id;
-
- self.clear_all_overlays();
- self.current_highlight.take();
- self.apply_workspace_thread_font_scales();
- self.invalidate_fancy_tab_bar();
- self.invalidate_modal();
-
- let mux = Mux::get();
- if let Some(window) = mux.get_window(self.mux_window_id) {
- for tab in window.iter() {
- tab.resize(self.terminal_size);
- }
- };
- self.sync_current_workspace_thread();
- self.update_title();
- window.invalidate();
+ self.switch_to_mux_window(mux_window_id);
}
TermWindowNotif::SetInnerSize { width, height } => {
self.set_inner_size(window, width, height);
@@ -1828,6 +1861,63 @@ impl TermWindow {
window.set_inner_size(width, height);
}
+ /// Re-point THIS GUI window at a different mux window (the mux window of
+ /// the Space/workspace we want to display) without disturbing any other
+ /// window. This is the per-window primitive used both by the
+ /// `SwitchToMuxWindow` notification and by in-place Space/thread switches.
+ pub(crate) fn switch_to_mux_window(&mut self, mux_window_id: MuxWindowId) {
+ if self.mux_window_id == mux_window_id
+ && front_end()
+ .gui_window_for_mux_window(mux_window_id)
+ .is_some()
+ {
+ // Already showing it and the mapping is current; nothing to do.
+ return;
+ }
+
+ self.mux_window_id = mux_window_id;
+ *self.mux_window_id_for_subscriptions.lock().unwrap() = mux_window_id;
+
+ // Keep the frontend's window<->mux mapping accurate so that the
+ // additive reconcile does not try to spawn a duplicate window for the
+ // mux window we just adopted.
+ if let Some(window) = self.window.as_ref() {
+ front_end().rebind_known_window(window, mux_window_id);
+ }
+
+ self.clear_all_overlays();
+ self.current_highlight.take();
+ self.apply_workspace_thread_font_scales();
+ self.invalidate_fancy_tab_bar();
+ self.invalidate_modal();
+
+ let mux = Mux::get();
+ if let Some(window) = mux.get_window(self.mux_window_id) {
+ for tab in window.iter() {
+ tab.resize(self.terminal_size);
+ }
+ };
+ self.sync_current_workspace_thread();
+ self.update_title();
+ if let Some(window) = self.window.as_ref() {
+ window.invalidate();
+ }
+ }
+
+ /// Switch THIS window to display the (already-live) workspace `workspace`,
+ /// adopting its mux window in place, and make it the active workspace so
+ /// that spawn-new-window defaults stay correct. Returns false when the
+ /// workspace has no mux window to adopt.
+ pub(crate) fn adopt_workspace_in_this_window(&mut self, workspace: &str) -> bool {
+ let mux = Mux::get();
+ let Some(target) = mux.iter_windows_in_workspace(workspace).first().copied() else {
+ return false;
+ };
+ mux.set_active_workspace(workspace);
+ self.switch_to_mux_window(target);
+ true
+ }
+
/// Take care to remove our panes from the mux, otherwise
/// we can leave the mux with no windows but some panes
/// and it won't believe that we are empty.
@@ -2429,6 +2519,50 @@ impl TermWindow {
self.invalidate_window();
}
+ pub(crate) fn request_close_content_view(&mut self) {
+ let response = match self.content_view.as_mut() {
+ Some(view) => view.on_close_requested(),
+ None => crate::termwindow::content_view::ContentViewResponse::Ignored,
+ };
+ self.handle_content_response(response);
+ }
+
+ pub(crate) fn show_onboarding(&mut self) {
+ let space_name = crate::workspace_threads::active_space_name(&self.active_space_id)
+ .unwrap_or_else(|| self.active_space_id.clone());
+ self.open_content_view(Box::new(
+ crate::termwindow::onboarding::OnboardingView::new(
+ self.active_space_id.clone(),
+ space_name,
+ ),
+ ));
+ }
+
+ pub(crate) fn maybe_show_onboarding(&mut self) {
+ if crate::native_settings::should_show_onboarding(&crate::native_settings::load()) {
+ self.show_onboarding();
+ }
+ }
+
+ pub(crate) fn pick_content_view_folder(&mut self) {
+ let Some(window) = self.window.as_ref().cloned() else {
+ return;
+ };
+ let notify_window = window.clone();
+ window.pick_folder_async(Box::new(move |path| {
+ if let Some(path) = path {
+ notify_window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
+ let response = term_window
+ .content_view
+ .as_mut()
+ .map(|view| view.on_folder_picked(path))
+ .unwrap_or(crate::termwindow::content_view::ContentViewResponse::Ignored);
+ term_window.handle_content_response(response);
+ })));
+ }
+ }));
+ }
+
pub(crate) fn set_content_view_active(&mut self, active: bool) {
if self.content_view.is_some() {
self.content_view_active = active;
@@ -4035,8 +4169,8 @@ impl TermWindow {
new_idx
};
let new_idx = new_idx as usize % workspaces.len();
- if let Some(w) = workspaces.get(new_idx) {
- front_end().switch_workspace(w);
+ if let Some(w) = workspaces.get(new_idx).cloned() {
+ self.adopt_workspace_in_this_window(&w);
}
}
SwitchToWorkspace { name, spawn } => {
@@ -4046,14 +4180,18 @@ impl TermWindow {
.as_ref()
.map(|name| name.to_string())
.unwrap_or_else(|| mux.generate_workspace_name());
- let switcher = crate::frontend::WorkspaceSwitcher::new(&name);
- mux.set_active_workspace(&name);
if mux.iter_windows_in_workspace(&name).is_empty() {
+ // Materialize a window in the target workspace, then adopt
+ // it into THIS window in place.
+ front_end().set_switching_workspaces(true);
+ mux.set_active_workspace(&name);
let spawn = spawn.as_ref().map(|s| s.clone()).unwrap_or_default();
let size = self.terminal_size;
let term_config = Arc::new(TermConfig::with_config(self.config.clone()));
let src_window_id = self.mux_window_id;
+ let reconcile_window = self.window.clone();
+ let adopt_workspace = name.clone();
promise::spawn::spawn(async move {
if let Err(err) = crate::spawn::spawn_command_internal(
@@ -4067,12 +4205,17 @@ impl TermWindow {
{
log::error!("Failed to spawn: {:#}", err);
}
- switcher.do_switch();
+ crate::termwindow::mouseevent::adopt_workspace_into_window(
+ &reconcile_window,
+ &adopt_workspace,
+ );
+ front_end().set_switching_workspaces(false);
drop(activity);
})
.detach();
} else {
- switcher.do_switch();
+ self.adopt_workspace_in_this_window(&name);
+ drop(activity);
}
}
DetachDomain(domain) => {
diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rs
index d840b15b..a05cc9ee 100644
--- a/wezterm-gui/src/termwindow/mouseevent.rs
+++ b/wezterm-gui/src/termwindow/mouseevent.rs
@@ -1173,7 +1173,7 @@ impl super::TermWindow {
UIItemType::ContentViewClose => {
context.set_cursor(Some(MouseCursor::Hand));
if event.kind == WMEK::Press(MousePress::Left) {
- self.close_content_view();
+ self.request_close_content_view();
}
}
UIItemType::WorkspaceSidebarViewOptions => {
@@ -1653,9 +1653,7 @@ impl super::TermWindow {
};
if !plan.needs_materialize {
- if mux.active_workspace() != plan.workspace_name {
- front_end().switch_workspace(&plan.workspace_name);
- }
+ self.adopt_workspace_in_this_window(&plan.workspace_name);
context.invalidate();
return;
}
@@ -1693,10 +1691,14 @@ impl super::TermWindow {
);
let term_config: Arc<dyn wezterm_term::TerminalConfiguration> =
Arc::new(TermConfig::with_config(self.config.clone()));
- let switcher = crate::frontend::WorkspaceSwitcher::new(&workspace_name);
+ // Suppress the additive reconcile while we materialize the target
+ // workspace's mux window; we adopt it into THIS window afterwards so
+ // no duplicate window is spawned and no other window is disturbed.
+ front_end().set_switching_workspaces(true);
mux.set_active_workspace(&workspace_name);
let reconcile_window = self.window.clone();
+ let adopt_workspace = workspace_name.clone();
promise::spawn::spawn(async move {
let materialized = match crate::workspace_threads::materialize_thread(
workspace_name,
@@ -1715,7 +1717,8 @@ impl super::TermWindow {
false
}
};
- switcher.do_switch();
+ adopt_workspace_into_window(&reconcile_window, &adopt_workspace);
+ front_end().set_switching_workspaces(false);
if materialized {
cleanup_orphaned_mux_window(orphan_candidate_window_id);
}
@@ -1766,11 +1769,10 @@ impl super::TermWindow {
);
let mux = Mux::get();
- // Already live? Just switch to it rather than spawning a duplicate.
+ // Already live? Just switch this window to it rather than spawning a
+ // duplicate.
if !mux.iter_windows_in_workspace(&workspace_name).is_empty() {
- if mux.active_workspace() != workspace_name {
- front_end().switch_workspace(&workspace_name);
- }
+ self.adopt_workspace_in_this_window(&workspace_name);
invalidate(&window);
return;
}
@@ -1790,10 +1792,13 @@ impl super::TermWindow {
);
let term_config: Arc<dyn wezterm_term::TerminalConfiguration> =
Arc::new(TermConfig::with_config(self.config.clone()));
- let switcher = crate::frontend::WorkspaceSwitcher::new(&workspace_name);
+ // Suppress the additive reconcile while materializing; adopt the new
+ // mux window into THIS window afterwards (no duplicate, others intact).
+ front_end().set_switching_workspaces(true);
mux.set_active_workspace(&workspace_name);
let ws = workspace_name.clone();
+ let adopt_workspace = workspace_name.clone();
let detect_os = spec.detect_os;
let detect_domain = domain_name.clone();
let detect_project = project_id.clone();
@@ -1813,7 +1818,8 @@ impl super::TermWindow {
{
log::error!("failed to connect SSH session: {err:#}");
}
- switcher.do_switch();
+ adopt_workspace_into_window(&reconcile_window, &adopt_workspace);
+ front_end().set_switching_workspaces(false);
reconcile_workspace_layout_after_materialize(reconcile_window);
// Optional, user-controlled OS detection over the live session.
@@ -2913,6 +2919,23 @@ fn reconcile_workspace_layout_after_materialize(window: Option<::window::Window>
}
}
+/// After a target workspace has been materialized in a background task, adopt
+/// its mux window into `window` (the window that initiated the switch) in
+/// place, without disturbing any other window. Rebinding the frontend mapping
+/// immediately closes the race where the additive reconcile might otherwise
+/// spawn a duplicate window for the freshly materialized mux window.
+pub(crate) fn adopt_workspace_into_window(window: &Option<::window::Window>, workspace: &str) {
+ let mux = Mux::get();
+ let Some(target) = mux.iter_windows_in_workspace(workspace).first().copied() else {
+ return;
+ };
+ mux.set_active_workspace(workspace);
+ if let Some(window) = window.as_ref() {
+ front_end().rebind_known_window(window, target);
+ window.notify(TermWindowNotif::SwitchToMuxWindow(target));
+ }
+}
+
fn cleanup_orphaned_mux_window(window_id: Option<MuxWindowId>) {
let Some(window_id) = window_id else {
return;
diff --git a/wezterm-gui/src/termwindow/onboarding.rs b/wezterm-gui/src/termwindow/onboarding.rs
new file mode 100644
index 00000000..7bf3fad5
--- /dev/null
+++ b/wezterm-gui/src/termwindow/onboarding.rs
@@ -0,0 +1,2113 @@
+use crate::native_settings::{
+ mark_onboarding_seen, NativeLanguagePreference, NativeThemeMode, ThinkTermNativeSettings,
+};
+use crate::quad::TripleLayerQuadAllocator;
+use crate::termwindow::content_view::{ContentView, ContentViewResponse};
+use crate::termwindow::ui::icons::SvgIcon;
+use crate::termwindow::TermWindow;
+use crate::ui::{
+ draw_scrollbar, draw_toggle, rect, wheel_delta_pixels, ControlState, DrawContext,
+ InteractionState, ScrollState, UiContext, UiPalette, UiTokens, WidgetKind,
+};
+use std::path::{Path, PathBuf};
+use std::rc::Rc;
+use std::time::{Duration, Instant};
+use wezterm_font::LoadedFont;
+use wezterm_term::{KeyCode, KeyModifiers};
+use window::color::LinearRgba;
+use window::{MouseEventKind as WMEK, MousePress, RectF, WindowOps};
+
+const OUTER_PAD: f32 = 56.0;
+const CARD_RADIUS: f32 = 20.0;
+const ACTION_H: f32 = 66.0;
+const CONTENT_MAX_W: f32 = 1240.0;
+const HEADER_H: f32 = 160.0;
+const FOOTER_H: f32 = 150.0;
+const PROJECT_ROW_H: f32 = 118.0;
+const PROJECT_ROW_GAP: f32 = 10.0;
+const TRANSITION_MS: u64 = 280;
+const TRANSITION_IN_START_T: f32 = 0.52;
+const TRANSITION_OUT_END_T: f32 = 0.48;
+const TRANSITION_ENTER_SLIDE: f32 = 28.0;
+const TRANSITION_EXIT_SLIDE: f32 = 18.0;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Step {
+ Welcome,
+ ImportSources,
+ ReviewProjects,
+ Preferences,
+ Ready,
+}
+
+impl Step {
+ fn all() -> &'static [Step] {
+ &[
+ Self::Welcome,
+ Self::ImportSources,
+ Self::ReviewProjects,
+ Self::Preferences,
+ Self::Ready,
+ ]
+ }
+
+ fn index(self) -> usize {
+ Self::all()
+ .iter()
+ .position(|step| *step == self)
+ .unwrap_or(0)
+ }
+
+ fn title(self) -> &'static str {
+ match self {
+ Self::Welcome => "Welcome",
+ Self::ImportSources => "Import Sources",
+ Self::ReviewProjects => "Review Projects",
+ Self::Preferences => "Preferences",
+ Self::Ready => "Ready",
+ }
+ }
+
+ fn eyebrow(self) -> &'static str {
+ match self {
+ Self::Welcome => "Set up your native terminal workspace",
+ Self::ImportSources => "Choose where projects come from",
+ Self::ReviewProjects => "Confirm before importing",
+ Self::Preferences => "Tune the native workspace",
+ Self::Ready => "Start clean",
+ }
+ }
+
+ fn next(self) -> Self {
+ match self {
+ Self::Welcome => Self::ImportSources,
+ Self::ImportSources => Self::ReviewProjects,
+ Self::ReviewProjects => Self::Preferences,
+ Self::Preferences => Self::Ready,
+ Self::Ready => Self::Ready,
+ }
+ }
+
+ fn previous(self) -> Self {
+ match self {
+ Self::Welcome => Self::Welcome,
+ Self::ImportSources => Self::Welcome,
+ Self::ReviewProjects => Self::ImportSources,
+ Self::Preferences => Self::ReviewProjects,
+ Self::Ready => Self::Preferences,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+enum ImportProvider {
+ VsCode,
+ Cursor,
+ Antigravity,
+ Cmux,
+ Manual,
+}
+
+impl ImportProvider {
+ fn all() -> &'static [Self] {
+ &[
+ Self::VsCode,
+ Self::Cursor,
+ Self::Antigravity,
+ Self::Cmux,
+ Self::Manual,
+ ]
+ }
+
+ fn label(self) -> &'static str {
+ match self {
+ Self::VsCode => "VS Code",
+ Self::Cursor => "Cursor",
+ Self::Antigravity => "Antigravity",
+ Self::Cmux => "cmux",
+ Self::Manual => "Choose Folder Manually",
+ }
+ }
+
+ fn description(self) -> &'static str {
+ match self {
+ Self::VsCode => "Workspace scan is not available in v1.",
+ Self::Cursor => "Cursor project history import is coming soon.",
+ Self::Antigravity => "Local Antigravity scan is not yet supported.",
+ Self::Cmux => "cmux session discovery is not wired yet.",
+ Self::Manual => "Pick a folder and review it before import.",
+ }
+ }
+
+ fn icon(self) -> SvgIcon {
+ match self {
+ Self::VsCode | Self::Cursor => SvgIcon::SquareTerminal,
+ Self::Antigravity => SvgIcon::Layers,
+ Self::Cmux => SvgIcon::Terminal,
+ Self::Manual => SvgIcon::FolderPlus,
+ }
+ }
+
+ fn is_available(self) -> bool {
+ matches!(self, Self::Manual)
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+enum OnboardingAction {
+ Primary,
+ Back,
+ Skip,
+ Provider(ImportProvider),
+ ToggleProject(usize),
+ RemoveProject(usize),
+ Language(NativeLanguagePreference),
+ Appearance(NativeThemeMode),
+ ToggleSidebar,
+}
+
+#[derive(Debug, Clone, Copy)]
+struct StepTransition {
+ from: Step,
+ to: Step,
+ direction: f32,
+ started_at: Instant,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum ProjectSource {
+ Manual,
+}
+
+impl ProjectSource {
+ fn label(&self) -> &'static str {
+ match self {
+ Self::Manual => "Manual",
+ }
+ }
+}
+
+#[derive(Debug, Clone)]
+struct PendingProject {
+ name: String,
+ path: PathBuf,
+ source: ProjectSource,
+ selected: bool,
+}
+
+impl PendingProject {
+ fn from_path(path: PathBuf, source: ProjectSource) -> Self {
+ let name = project_name_for_path(&path);
+ Self {
+ name,
+ path,
+ source,
+ selected: true,
+ }
+ }
+}
+
+pub(crate) struct OnboardingView {
+ step: Step,
+ widgets: UiContext<OnboardingAction>,
+ interaction: InteractionState<OnboardingAction>,
+ review_scroll: ScrollState,
+ initial_space_id: String,
+ initial_space_name: String,
+ pending_projects: Vec<PendingProject>,
+ target_space_id: Option<String>,
+ imported_project_count: usize,
+ selected_language: NativeLanguagePreference,
+ selected_appearance: NativeThemeMode,
+ show_left_sidebar: bool,
+ status: Option<String>,
+ transition: Option<StepTransition>,
+}
+
+impl OnboardingView {
+ pub(crate) fn new(initial_space_id: String, initial_space_name: String) -> Self {
+ let settings = crate::native_settings::load();
+ Self {
+ step: Step::Welcome,
+ widgets: UiContext::default(),
+ interaction: InteractionState::default(),
+ review_scroll: ScrollState::new(),
+ initial_space_id,
+ initial_space_name,
+ pending_projects: Vec::new(),
+ target_space_id: None,
+ imported_project_count: 0,
+ selected_language: settings.onboarding.language,
+ selected_appearance: settings.appearance.theme_mode,
+ show_left_sidebar: settings.onboarding.show_left_sidebar_by_default,
+ status: None,
+ transition: None,
+ }
+ }
+
+ fn normalized_space_name(&self) -> String {
+ self.fallback_space_name()
+ }
+
+ fn fallback_space_name(&self) -> String {
+ let initial_name = self.initial_space_name.trim();
+ if !initial_name.is_empty() {
+ initial_name.to_string()
+ } else {
+ let initial_id = self.initial_space_id.trim();
+ if initial_id.is_empty() {
+ "Default".to_string()
+ } else {
+ initial_id.to_string()
+ }
+ }
+ }
+
+ fn selected_project_count(&self) -> usize {
+ self.pending_projects
+ .iter()
+ .filter(|project| project.selected)
+ .count()
+ }
+
+ fn start_step_transition(&mut self, next: Step, direction: f32) {
+ let from = self.step;
+ if from == next {
+ return;
+ }
+ self.step = next;
+ if next == Step::ReviewProjects {
+ self.review_scroll.reset();
+ }
+ self.interaction.pressed = None;
+ self.transition = Some(StepTransition {
+ from,
+ to: next,
+ direction,
+ started_at: Instant::now(),
+ });
+ }
+
+ fn target_space_id_for_choice(&self) -> String {
+ let initial_id = self.initial_space_id.trim();
+ if initial_id.is_empty() {
+ crate::workspace_threads::ensure_space_named(&self.normalized_space_name())
+ } else {
+ self.initial_space_id.clone()
+ }
+ }
+
+ fn primary_label(&self) -> &'static str {
+ match self.step {
+ Step::Welcome | Step::ImportSources | Step::Preferences => "Continue",
+ Step::ReviewProjects => {
+ if self.selected_project_count() == 0 {
+ "Continue Without Import"
+ } else {
+ "Import Selected"
+ }
+ }
+ Step::Ready => "Start ThinkTerm",
+ }
+ }
+
+ fn primary_enabled(&self) -> bool {
+ true
+ }
+
+ fn on_mouse_impl(&mut self, x: f32, y: f32, kind: WMEK) -> ContentViewResponse {
+ let hit = self.widgets.hit_test(x, y).map(|target| target.action);
+ match kind {
+ WMEK::VertWheel(amount) if self.step == Step::ReviewProjects => {
+ let old = self.review_scroll.offset;
+ self.review_scroll.scroll_by(wheel_delta_pixels(amount));
+ if (self.review_scroll.offset - old).abs() > 0.01 {
+ ContentViewResponse::Redraw
+ } else {
+ ContentViewResponse::Ignored
+ }
+ }
+ WMEK::Move => {
+ if self.interaction.hovered != hit {
+ self.interaction.hovered = hit;
+ ContentViewResponse::Redraw
+ } else {
+ ContentViewResponse::Ignored
+ }
+ }
+ WMEK::Press(MousePress::Left) => {
+ self.interaction.pressed = hit;
+ ContentViewResponse::Redraw
+ }
+ WMEK::Release(MousePress::Left) => {
+ let pressed = self.interaction.pressed.take();
+ if let (Some(a), Some(b)) = (hit, pressed) {
+ if a == b {
+ return self.apply(a);
+ }
+ }
+ ContentViewResponse::Redraw
+ }
+ _ => ContentViewResponse::Ignored,
+ }
+ }
+
+ fn apply(&mut self, action: OnboardingAction) -> ContentViewResponse {
+ self.status = None;
+ match action {
+ OnboardingAction::Primary => self.apply_primary(),
+ OnboardingAction::Back => {
+ self.start_step_transition(self.step.previous(), -1.0);
+ ContentViewResponse::Redraw
+ }
+ OnboardingAction::Skip => self.skip_response(),
+ OnboardingAction::Provider(provider) => {
+ if provider.is_available() {
+ ContentViewResponse::Run(Box::new(|tw: &mut TermWindow| {
+ tw.pick_content_view_folder();
+ }))
+ } else {
+ self.status = Some(format!("{} import is coming soon.", provider.label()));
+ ContentViewResponse::Redraw
+ }
+ }
+ OnboardingAction::ToggleProject(index) => {
+ if let Some(project) = self.pending_projects.get_mut(index) {
+ project.selected = !project.selected;
+ }
+ ContentViewResponse::Redraw
+ }
+ OnboardingAction::RemoveProject(index) => {
+ if index < self.pending_projects.len() {
+ self.pending_projects.remove(index);
+ }
+ ContentViewResponse::Redraw
+ }
+ OnboardingAction::Language(language) => {
+ self.selected_language = language;
+ ContentViewResponse::Redraw
+ }
+ OnboardingAction::Appearance(mode) => {
+ self.selected_appearance = mode;
+ ContentViewResponse::Redraw
+ }
+ OnboardingAction::ToggleSidebar => {
+ self.show_left_sidebar = !self.show_left_sidebar;
+ ContentViewResponse::Redraw
+ }
+ }
+ }
+
+ fn apply_primary(&mut self) -> ContentViewResponse {
+ if !self.primary_enabled() {
+ return ContentViewResponse::Redraw;
+ }
+ match self.step {
+ Step::Welcome | Step::ImportSources => {
+ self.start_step_transition(self.step.next(), 1.0);
+ ContentViewResponse::Redraw
+ }
+ Step::ReviewProjects => {
+ self.import_selected_projects();
+ self.start_step_transition(Step::Preferences, 1.0);
+ ContentViewResponse::Redraw
+ }
+ Step::Preferences => {
+ self.start_step_transition(Step::Ready, 1.0);
+ ContentViewResponse::Redraw
+ }
+ Step::Ready => self.finish_response(),
+ }
+ }
+
+ fn import_selected_projects(&mut self) {
+ let space_id = self
+ .target_space_id
+ .clone()
+ .unwrap_or_else(|| self.target_space_id_for_choice());
+ let mut imported = 0usize;
+ for project in self
+ .pending_projects
+ .iter()
+ .filter(|project| project.selected)
+ {
+ let path = project.path.to_string_lossy();
+ match crate::workspace_threads::create_project_from_path(&space_id, path.as_ref()) {
+ Ok(_) => imported += 1,
+ Err(err) => {
+ log::error!(
+ "failed to import onboarding project {}: {err:#}",
+ project.path.display()
+ );
+ }
+ }
+ }
+ self.target_space_id = Some(space_id);
+ self.imported_project_count = imported;
+ }
+
+ fn finish_response(&self) -> ContentViewResponse {
+ let prefs = OnboardingPrefs {
+ space_name: self.normalized_space_name(),
+ target_space_id: Some(
+ self.target_space_id
+ .clone()
+ .unwrap_or_else(|| self.target_space_id_for_choice()),
+ ),
+ imported_project_count: self.imported_project_count,
+ language: self.selected_language,
+ appearance: self.selected_appearance,
+ show_left_sidebar: self.show_left_sidebar,
+ };
+ ContentViewResponse::Run(Box::new(move |tw: &mut TermWindow| {
+ finish_onboarding(tw, prefs);
+ }))
+ }
+
+ fn skip_response(&self) -> ContentViewResponse {
+ ContentViewResponse::Run(Box::new(|tw: &mut TermWindow| {
+ let mut settings = crate::native_settings::load();
+ mark_onboarding_seen(&mut settings);
+ if let Err(err) = crate::native_settings::save(&settings) {
+ log::error!("failed to save onboarding skip state: {err:#}");
+ }
+ tw.close_content_view();
+ }))
+ }
+
+ fn on_key_impl(&mut self, key: KeyCode, mods: KeyModifiers) -> ContentViewResponse {
+ match (key, mods) {
+ (KeyCode::Escape, _) => self.skip_response(),
+ (KeyCode::Enter, _) => self.apply_primary(),
+ (KeyCode::Tab, KeyModifiers::NONE) => {
+ self.start_step_transition(self.step.next(), 1.0);
+ ContentViewResponse::Redraw
+ }
+ (KeyCode::Tab, KeyModifiers::SHIFT) => {
+ self.start_step_transition(self.step.previous(), -1.0);
+ ContentViewResponse::Redraw
+ }
+ _ => ContentViewResponse::Ignored,
+ }
+ }
+
+ fn on_paste_impl(&mut self, _text: &str) -> ContentViewResponse {
+ ContentViewResponse::Ignored
+ }
+
+ fn add_manual_project(&mut self, path: PathBuf) {
+ if self
+ .pending_projects
+ .iter()
+ .any(|project| project.path == path)
+ {
+ self.status = Some("That folder is already in the review list.".to_string());
+ } else {
+ self.pending_projects
+ .push(PendingProject::from_path(path, ProjectSource::Manual));
+ self.status = Some("Folder added. Review it before importing.".to_string());
+ }
+ self.start_step_transition(Step::ReviewProjects, 1.0);
+ self.review_scroll.reset();
+ }
+
+ fn line_h(ctx: &DrawContext) -> f32 {
+ (ctx.metrics.cell_size.height as f32 + 14.0).max(34.0)
+ }
+
+ fn compact_line_h(ctx: &DrawContext) -> f32 {
+ (ctx.metrics.cell_size.height as f32 + 8.0).max(28.0)
+ }
+
+ fn control_h(ctx: &DrawContext) -> f32 {
+ (ctx.metrics.cell_size.height as f32 + 30.0).max(60.0)
+ }
+
+ fn preference_choice_h(ctx: &DrawContext) -> f32 {
+ (Self::control_h(ctx) + 10.0).clamp(68.0, 80.0)
+ }
+
+ fn preference_group_height(ctx: &DrawContext, choice_count: usize) -> f32 {
+ let rows = choice_count.div_ceil(2).max(1) as f32;
+ Self::line_h(ctx) + 26.0 + rows * Self::preference_choice_h(ctx) + (rows - 1.0) * 18.0
+ }
+
+ fn action_h(ctx: &DrawContext) -> f32 {
+ Self::control_h(ctx).min(68.0).max(ACTION_H)
+ }
+
+ fn centered_text_y(ctx: &DrawContext, area: RectF) -> f32 {
+ let text_h = ctx.metrics.cell_size.height as f32;
+ area.origin.y + ((area.size.height - text_h) / 2.0).max(4.0)
+ }
+
+ fn transition_duration() -> Duration {
+ Duration::from_millis(TRANSITION_MS)
+ }
+
+ fn ease_in_out(t: f32) -> f32 {
+ let t = t.clamp(0.0, 1.0);
+ t * t * (3.0 - 2.0 * t)
+ }
+
+ fn ease_out_cubic(t: f32) -> f32 {
+ let t = t.clamp(0.0, 1.0);
+ 1.0 - (1.0 - t).powi(3)
+ }
+
+ fn faded_palette(mut palette: UiPalette, alpha: f32) -> UiPalette {
+ let alpha = alpha.clamp(0.0, 1.0);
+ palette.separator = palette.separator.mul_alpha(alpha);
+ palette.control_bg = palette.control_bg.mul_alpha(alpha);
+ palette.control_hover_bg = palette.control_hover_bg.mul_alpha(alpha);
+ palette.control_pressed_bg = palette.control_pressed_bg.mul_alpha(alpha);
+ palette.control_border = palette.control_border.mul_alpha(alpha);
+ palette.sidebar_button_bg = palette.sidebar_button_bg.mul_alpha(alpha);
+ palette.sidebar_button_hover_bg = palette.sidebar_button_hover_bg.mul_alpha(alpha);
+ palette.sidebar_row_hover_bg = palette.sidebar_row_hover_bg.mul_alpha(alpha);
+ palette.sidebar_row_active_bg = palette.sidebar_row_active_bg.mul_alpha(alpha);
+ palette.sidebar_row_active_border = palette.sidebar_row_active_border.mul_alpha(alpha);
+ palette.selected_bg = palette.selected_bg.mul_alpha(alpha);
+ palette.text = palette.text.mul_alpha(alpha);
+ palette.secondary_text = palette.secondary_text.mul_alpha(alpha);
+ palette.muted_text = palette.muted_text.mul_alpha(alpha);
+ palette.selected_text = palette.selected_text.mul_alpha(alpha);
+ palette.scrollbar_thumb = palette.scrollbar_thumb.mul_alpha(alpha);
+ palette
+ }
+
+ fn transition_t(&self) -> Option<f32> {
+ self.transition.map(|transition| {
+ let elapsed = transition.started_at.elapsed();
+ (elapsed.as_secs_f32() / Self::transition_duration().as_secs_f32()).clamp(0.0, 1.0)
+ })
+ }
+
+ fn paint_body_for_step(
+ &mut self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ step: Step,
+ body: RectF,
+ palette: UiPalette,
+ font: &Rc<LoadedFont>,
+ tokens: UiTokens,
+ section_font: &Rc<LoadedFont>,
+ ) -> anyhow::Result<()> {
+ match step {
+ Step::Welcome => self.paint_welcome(ctx, layers, body, palette, font)?,
+ Step::ImportSources => self.paint_import_sources(ctx, layers, body, palette, font)?,
+ Step::ReviewProjects => self.paint_review(ctx, layers, body, palette, font, tokens)?,
+ Step::Preferences => {
+ self.paint_preferences(ctx, layers, body, palette, font, section_font)?
+ }
+ Step::Ready => self.paint_ready(ctx, layers, body, palette, font)?,
+ }
+ Ok(())
+ }
+
+ fn paint_body_for_step_without_widgets(
+ &mut self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ step: Step,
+ body: RectF,
+ palette: UiPalette,
+ font: &Rc<LoadedFont>,
+ tokens: UiTokens,
+ section_font: &Rc<LoadedFont>,
+ ) -> anyhow::Result<()> {
+ let real_widgets = std::mem::take(&mut self.widgets);
+ let result =
+ self.paint_body_for_step(ctx, layers, step, body, palette, font, tokens, section_font);
+ self.widgets = real_widgets;
+ result
+ }
+
+ fn paint_body(
+ &mut self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ body: RectF,
+ palette: UiPalette,
+ font: &Rc<LoadedFont>,
+ tokens: UiTokens,
+ section_font: &Rc<LoadedFont>,
+ ) -> anyhow::Result<()> {
+ let Some(transition) = self.transition else {
+ return self.paint_body_for_step(
+ ctx,
+ layers,
+ self.step,
+ body,
+ palette,
+ font,
+ tokens,
+ section_font,
+ );
+ };
+
+ let raw_t = self.transition_t().unwrap_or(1.0);
+ if raw_t >= 1.0 {
+ self.transition = None;
+ return self.paint_body_for_step(
+ ctx,
+ layers,
+ self.step,
+ body,
+ palette,
+ font,
+ tokens,
+ section_font,
+ );
+ }
+
+ let direction = transition.direction;
+ if raw_t < TRANSITION_OUT_END_T {
+ let t = Self::ease_out_cubic(raw_t / TRANSITION_OUT_END_T);
+ let outgoing = rect(
+ body.origin.x - direction * TRANSITION_EXIT_SLIDE * t,
+ body.origin.y,
+ body.size.width,
+ body.size.height,
+ );
+ self.paint_body_for_step_without_widgets(
+ ctx,
+ layers,
+ transition.from,
+ outgoing,
+ Self::faded_palette(palette, 1.0 - t),
+ font,
+ tokens,
+ section_font,
+ )?;
+ }
+ if raw_t >= TRANSITION_IN_START_T {
+ let t = Self::ease_out_cubic(
+ (raw_t - TRANSITION_IN_START_T) / (1.0 - TRANSITION_IN_START_T),
+ );
+ let incoming = rect(
+ body.origin.x + direction * TRANSITION_ENTER_SLIDE * (1.0 - t),
+ body.origin.y,
+ body.size.width,
+ body.size.height,
+ );
+ self.paint_body_for_step(
+ ctx,
+ layers,
+ transition.to,
+ incoming,
+ Self::faded_palette(palette, t),
+ font,
+ tokens,
+ section_font,
+ )?;
+ }
+ Ok(())
+ }
+
+ fn paint_impl(
+ &mut self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ area: RectF,
+ palette: UiPalette,
+ font: &Rc<LoadedFont>,
+ title_font: &Rc<LoadedFont>,
+ section_font: &Rc<LoadedFont>,
+ _cursor_on: bool,
+ ) -> anyhow::Result<()> {
+ self.widgets.clear();
+ let tokens = UiTokens::default();
+ ctx.draw_rect(
+ layers,
+ 0,
+ area.origin.x,
+ area.origin.y,
+ area.size.width,
+ area.size.height,
+ palette.window_bg,
+ )?;
+
+ let shell = inset_rect(area, OUTER_PAD);
+ let content_w = shell.size.width.min(CONTENT_MAX_W).max(0.0);
+ let content_x = shell.origin.x + ((shell.size.width - content_w) / 2.0).max(0.0);
+ let content = rect(content_x, shell.origin.y, content_w, shell.size.height);
+
+ self.paint_header(ctx, layers, content, palette, font, title_font)?;
+ let body = rect(
+ content.origin.x,
+ content.origin.y + HEADER_H,
+ content.size.width,
+ (content.size.height - HEADER_H - FOOTER_H).max(0.0),
+ );
+ self.paint_body(ctx, layers, body, palette, font, tokens, section_font)?;
+ self.paint_status(ctx, layers, content, palette, font)?;
+ self.paint_footer(ctx, layers, content, palette, font)?;
+ Ok(())
+ }
+
+ fn paint_header(
+ &self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ content: RectF,
+ palette: UiPalette,
+ font: &Rc<LoadedFont>,
+ title_font: &Rc<LoadedFont>,
+ ) -> anyhow::Result<()> {
+ ctx.draw_text(
+ layers,
+ title_font,
+ content.origin.x,
+ content.origin.y + 6.0,
+ self.step.title(),
+ palette.text,
+ content.size.width,
+ )?;
+ self.draw_wrapped_text(
+ ctx,
+ layers,
+ font,
+ content.origin.x,
+ content.origin.y + 64.0,
+ content.size.width.min(900.0),
+ self.step.eyebrow(),
+ palette.muted_text,
+ 2,
+ )?;
+ ctx.draw_rect(
+ layers,
+ 0,
+ content.origin.x,
+ content.origin.y + HEADER_H - 24.0,
+ content.size.width,
+ 1.0,
+ palette.separator,
+ )
+ }
+
+ fn paint_welcome(
+ &mut self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ area: RectF,
+ palette: UiPalette,
+ font: &Rc<LoadedFont>,
+ ) -> anyhow::Result<()> {
+ self.draw_wrapped_text(
+ ctx,
+ layers,
+ font,
+ area.origin.x,
+ area.origin.y,
+ area.size.width.min(960.0),
+ "Open folders, review imports, and keep terminal sessions tied to the work they belong to.",
+ palette.secondary_text,
+ 2,
+ )?;
+ let line_h = Self::line_h(ctx);
+ let card_h = (line_h * 3.2 + 58.0).max(156.0);
+ let cards = [
+ (
+ SvgIcon::Layers,
+ "Workspaces",
+ "Keep related folders and sessions together.",
+ ),
+ (
+ SvgIcon::FolderOpen,
+ "Projects",
+ "Review each folder before ThinkTerm creates it.",
+ ),
+ (
+ SvgIcon::SquareTerminal,
+ "Sessions",
+ "Return to long-running terminal work quickly.",
+ ),
+ ];
+ let card_gap = 22.0;
+ let card_w = ((area.size.width - card_gap * 2.0) / 3.0).max(240.0);
+ let mut x = area.origin.x;
+ let y = area.origin.y + line_h * 2.0 + 46.0;
+ for (icon, title, description) in cards {
+ self.paint_info_card(
+ ctx,
+ layers,
+ rect(x, y, card_w, card_h),
+ palette,
+ font,
+ icon,
+ title,
+ description,
+ )?;
+ x += card_w + card_gap;
+ }
+ self.paint_info_card(
+ ctx,
+ layers,
+ rect(
+ area.origin.x,
+ y + card_h + 24.0,
+ area.size.width,
+ (line_h * 2.6 + 54.0).max(136.0),
+ ),
+ palette,
+ font,
+ SvgIcon::Info,
+ "Private by default",
+ "No project paths, terminal content, or local folders are collected. Manual imports stay local until you confirm.",
+ )?;
+ Ok(())
+ }
+
+ fn paint_import_sources(
+ &mut self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ area: RectF,
+ palette: UiPalette,
+ font: &Rc<LoadedFont>,
+ ) -> anyhow::Result<()> {
+ self.draw_wrapped_text(
+ ctx,
+ layers,
+ font,
+ area.origin.x,
+ area.origin.y,
+ area.size.width.min(960.0),
+ "Choose a source to scan. v1 imports manual folders only, and nothing is created until review.",
+ palette.secondary_text,
+ 2,
+ )?;
+ let line_h = Self::line_h(ctx);
+ let grid_w = area.size.width;
+ let gap = 20.0;
+ let card_w = ((grid_w - gap) / 2.0).max(280.0);
+ let card_h = (line_h * 3.0 + 64.0).max(164.0);
+ let start_y = area.origin.y + line_h * 2.0 + 42.0;
+ for (idx, provider) in ImportProvider::all().iter().enumerate() {
+ let is_manual = *provider == ImportProvider::Manual;
+ let row = idx / 2;
+ let col = idx % 2;
+ let x = area.origin.x + col as f32 * (card_w + gap);
+ let y = start_y + row as f32 * (card_h + gap);
+ self.paint_provider_card(
+ ctx,
+ layers,
+ rect(
+ if is_manual { area.origin.x } else { x },
+ y,
+ if is_manual { grid_w } else { card_w },
+ card_h,
+ ),
+ palette,
+ font,
+ *provider,
+ )?;
+ }
+ Ok(())
+ }
+
+ fn paint_review(
+ &mut self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ area: RectF,
+ palette: UiPalette,
+ font: &Rc<LoadedFont>,
+ tokens: UiTokens,
+ ) -> anyhow::Result<()> {
+ let count = self.pending_projects.len();
+ let selected = self.selected_project_count();
+ let summary = format!("{selected} of {count} projects selected");
+ let line_h = Self::line_h(ctx);
+ ctx.draw_text(
+ layers,
+ font,
+ area.origin.x,
+ area.origin.y,
+ &summary,
+ palette.secondary_text,
+ area.size.width,
+ )?;
+ let list = rect(
+ area.origin.x,
+ area.origin.y + line_h + 20.0,
+ area.size.width.min(820.0),
+ (area.size.height - line_h - 28.0).max(0.0),
+ );
+ if self.pending_projects.is_empty() {
+ self.paint_empty_state(ctx, layers, list, palette, font)?;
+ return Ok(());
+ }
+ let content_h = self.pending_projects.len() as f32 * PROJECT_ROW_H
+ + self.pending_projects.len().saturating_sub(1) as f32 * PROJECT_ROW_GAP;
+ self.review_scroll.set_extents(list.size.height, content_h);
+ let mut y = list.origin.y - self.review_scroll.offset;
+ let projects = self.pending_projects.clone();
+ for (idx, project) in projects.iter().enumerate() {
+ if y + PROJECT_ROW_H >= list.origin.y && y <= list.origin.y + list.size.height {
+ self.paint_project_row(
+ ctx,
+ layers,
+ rect(list.origin.x, y, list.size.width, PROJECT_ROW_H),
+ list,
+ palette,
+ font,
+ idx,
+ project,
+ )?;
+ }
+ y += PROJECT_ROW_H + PROJECT_ROW_GAP;
+ }
+ if self.review_scroll.has_overflow() {
+ draw_scrollbar(ctx, layers, palette, tokens, list, self.review_scroll)?;
+ }
+ Ok(())
+ }
+
+ fn paint_preferences(
+ &mut self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ area: RectF,
+ palette: UiPalette,
+ font: &Rc<LoadedFont>,
+ section_font: &Rc<LoadedFont>,
+ ) -> anyhow::Result<()> {
+ let group_w = area.size.width.min(1120.0);
+ let line_h = Self::line_h(ctx);
+ let language_h = Self::preference_group_height(ctx, 4);
+ self.paint_preference_group(
+ ctx,
+ layers,
+ rect(area.origin.x, area.origin.y, group_w, language_h),
+ palette,
+ font,
+ section_font,
+ "Language",
+ &[
+ (
+ NativeLanguagePreference::System.label(),
+ OnboardingAction::Language(NativeLanguagePreference::System),
+ self.selected_language == NativeLanguagePreference::System,
+ ),
+ (
+ NativeLanguagePreference::English.label(),
+ OnboardingAction::Language(NativeLanguagePreference::English),
+ self.selected_language == NativeLanguagePreference::English,
+ ),
+ (
+ NativeLanguagePreference::Chinese.label(),
+ OnboardingAction::Language(NativeLanguagePreference::Chinese),
+ self.selected_language == NativeLanguagePreference::Chinese,
+ ),
+ (
+ NativeLanguagePreference::Japanese.label(),
+ OnboardingAction::Language(NativeLanguagePreference::Japanese),
+ self.selected_language == NativeLanguagePreference::Japanese,
+ ),
+ ],
+ )?;
+ let appearance_y = area.origin.y + language_h + 54.0;
+ let appearance_h = Self::preference_group_height(ctx, 3);
+ self.paint_preference_group(
+ ctx,
+ layers,
+ rect(area.origin.x, appearance_y, group_w, appearance_h),
+ palette,
+ font,
+ section_font,
+ "Appearance",
+ &[
+ (
+ "Follow System",
+ OnboardingAction::Appearance(NativeThemeMode::System),
+ self.selected_appearance == NativeThemeMode::System,
+ ),
+ (
+ "Light",
+ OnboardingAction::Appearance(NativeThemeMode::Light),
+ self.selected_appearance == NativeThemeMode::Light,
+ ),
+ (
+ "Dark",
+ OnboardingAction::Appearance(NativeThemeMode::Dark),
+ self.selected_appearance == NativeThemeMode::Dark,
+ ),
+ ],
+ )?;
+ let toggle_y = appearance_y + appearance_h + 58.0;
+ let toggle_row = rect(area.origin.x, toggle_y, group_w, 124.0);
+ self.widgets.push(
+ toggle_row,
+ WidgetKind::Button,
+ OnboardingAction::ToggleSidebar,
+ );
+ let hovered = self.interaction.hovered == Some(OnboardingAction::ToggleSidebar);
+ let pressed = self.interaction.pressed == Some(OnboardingAction::ToggleSidebar);
+ let toggle_bg = if pressed {
+ palette.control_pressed_bg
+ } else if hovered {
+ palette.control_hover_bg
+ } else {
+ palette.control_bg
+ };
+ ctx.draw_rounded_frame(
+ layers,
+ 0,
+ toggle_row.origin.x,
+ toggle_row.origin.y,
+ toggle_row.size.width,
+ toggle_row.size.height,
+ toggle_bg,
+ palette.control_border,
+ CARD_RADIUS,
+ )?;
+ let toggle_rect = rect(
+ toggle_row.origin.x + 24.0,
+ toggle_row.origin.y + 47.0,
+ 54.0,
+ 30.0,
+ );
+ draw_toggle(
+ ctx,
+ layers,
+ &mut self.widgets,
+ palette,
+ toggle_rect,
+ self.show_left_sidebar,
+ OnboardingAction::ToggleSidebar,
+ )?;
+ ctx.draw_text(
+ layers,
+ section_font,
+ toggle_row.origin.x + 100.0,
+ toggle_row.origin.y + 26.0,
+ "Show left sidebar by default",
+ palette.text,
+ toggle_row.size.width - 124.0,
+ )?;
+ ctx.draw_text(
+ layers,
+ font,
+ toggle_row.origin.x + 100.0,
+ toggle_row.origin.y + 72.0,
+ "Applies to newly opened main windows and this setup finish.",
+ palette.muted_text,
+ toggle_row.size.width - 124.0,
+ )?;
+ Ok(())
+ }
+
+ fn paint_ready(
+ &mut self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ area: RectF,
+ palette: UiPalette,
+ font: &Rc<LoadedFont>,
+ ) -> anyhow::Result<()> {
+ let rows = [
+ ("Space", self.normalized_space_name()),
+ ("Projects imported", self.imported_project_count.to_string()),
+ (
+ "Sidebar",
+ if self.show_left_sidebar {
+ "Shown by default".to_string()
+ } else {
+ "Hidden by default".to_string()
+ },
+ ),
+ ("Language", self.selected_language.label().to_string()),
+ ("Appearance", self.selected_appearance.label().to_string()),
+ ];
+ let mut y = area.origin.y;
+ let row_h = (Self::line_h(ctx) + 34.0).max(64.0);
+ for (label, value) in rows {
+ self.paint_summary_row(
+ ctx,
+ layers,
+ rect(area.origin.x, y, area.size.width.min(760.0), row_h),
+ palette,
+ font,
+ label,
+ &value,
+ )?;
+ y += row_h + 12.0;
+ }
+ Ok(())
+ }
+
+ fn paint_footer(
+ &mut self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ content: RectF,
+ palette: UiPalette,
+ font: &Rc<LoadedFont>,
+ ) -> anyhow::Result<()> {
+ let footer_y = content.origin.y + content.size.height - FOOTER_H;
+ ctx.draw_rect(
+ layers,
+ 0,
+ content.origin.x,
+ footer_y,
+ content.size.width,
+ 1.0,
+ palette.separator,
+ )?;
+ self.paint_step_progress(
+ ctx,
+ layers,
+ rect(content.origin.x, footer_y + 18.0, content.size.width, 40.0),
+ palette,
+ font,
+ )?;
+
+ let action_h = Self::action_h(ctx);
+ let y = footer_y + 76.0;
+ let primary_w = if self.step == Step::ReviewProjects {
+ 330.0
+ } else if self.step == Step::Ready {
+ 290.0
+ } else {
+ 230.0
+ };
+ let primary = rect(
+ content.origin.x + content.size.width - primary_w,
+ y,
+ primary_w,
+ action_h,
+ );
+ self.paint_button(
+ ctx,
+ layers,
+ primary,
+ palette,
+ font,
+ self.primary_label(),
+ OnboardingAction::Primary,
+ true,
+ self.primary_enabled(),
+ )?;
+ if self.step != Step::Welcome {
+ self.paint_button(
+ ctx,
+ layers,
+ rect(primary.origin.x - 194.0, y, 170.0, action_h),
+ palette,
+ font,
+ "Back",
+ OnboardingAction::Back,
+ false,
+ true,
+ )?;
+ }
+ self.paint_button(
+ ctx,
+ layers,
+ rect(content.origin.x, y, 154.0, action_h),
+ palette,
+ font,
+ "Skip",
+ OnboardingAction::Skip,
+ false,
+ true,
+ )
+ }
+
+ fn paint_status(
+ &self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ content: RectF,
+ palette: UiPalette,
+ font: &Rc<LoadedFont>,
+ ) -> anyhow::Result<()> {
+ let Some(status) = &self.status else {
+ return Ok(());
+ };
+ ctx.draw_text(
+ layers,
+ font,
+ content.origin.x,
+ content.origin.y + content.size.height - FOOTER_H - Self::compact_line_h(ctx) - 16.0,
+ status,
+ palette.muted_text,
+ content.size.width,
+ )
+ }
+
+ fn paint_step_progress(
+ &self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ area: RectF,
+ palette: UiPalette,
+ font: &Rc<LoadedFont>,
+ ) -> anyhow::Result<()> {
+ let steps = Step::all();
+ let progress_index =
+ if let (Some(transition), Some(raw_t)) = (self.transition, self.transition_t()) {
+ let from = transition.from.index() as f32;
+ let to = transition.to.index() as f32;
+ from + (to - from) * Self::ease_in_out(raw_t)
+ } else {
+ self.step.index() as f32
+ };
+ let label = format!(
+ "Step {} of {} · {}",
+ self.step.index() + 1,
+ steps.len(),
+ self.step.title()
+ );
+ ctx.draw_text(
+ layers,
+ font,
+ area.origin.x,
+ Self::centered_text_y(ctx, area),
+ &label,
+ palette.secondary_text,
+ area.size.width * 0.42,
+ )?;
+
+ let track_w = (area.size.width * 0.46).min(520.0).max(280.0);
+ let track_x = area.origin.x + area.size.width - track_w;
+ let center_y = area.origin.y + area.size.height / 2.0;
+ let segment_w = track_w / steps.len().max(1) as f32;
+ let active_progress = palette.secondary_text.mul_alpha(0.78);
+ ctx.draw_rounded_rect(
+ layers,
+ 0,
+ track_x,
+ center_y - 2.0,
+ track_w,
+ 4.0,
+ palette.control_border.mul_alpha(0.55),
+ 2.0,
+ )?;
+ let fill_w = segment_w * (progress_index + 1.0);
+ ctx.draw_rounded_rect(
+ layers,
+ 1,
+ track_x,
+ center_y - 2.0,
+ fill_w.min(track_w),
+ 4.0,
+ active_progress,
+ 2.0,
+ )?;
+ for (idx, step) in steps.iter().enumerate() {
+ let active = *step == self.step;
+ let idx_f = idx as f32;
+ let complete = idx_f < progress_index.floor();
+ let active_strength = (1.0 - (idx_f - progress_index).abs()).clamp(0.0, 1.0);
+ let cx = track_x + segment_w * idx as f32 + segment_w / 2.0;
+ let size = 14.0 + 4.0 * active_strength;
+ let color = if complete || active || active_strength > 0.01 {
+ active_progress.mul_alpha((0.58 + active_strength * 0.42).clamp(0.0, 1.0))
+ } else {
+ palette.control_border
+ };
+ ctx.draw_rounded_rect(
+ layers,
+ 1,
+ cx - size / 2.0,
+ center_y - size / 2.0,
+ size,
+ size,
+ color,
+ size / 2.0,
+ )?;
+ }
+ Ok(())
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ fn paint_info_card(
+ &self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ card: RectF,
+ palette: UiPalette,
+ font: &Rc<LoadedFont>,
+ icon: SvgIcon,
+ title: &str,
+ description: &str,
+ ) -> anyhow::Result<()> {
+ ctx.draw_rounded_frame(
+ layers,
+ 0,
+ card.origin.x,
+ card.origin.y,
+ card.size.width,
+ card.size.height,
+ palette.control_bg,
+ palette.control_border,
+ CARD_RADIUS,
+ )?;
+ let line_h = Self::line_h(ctx);
+ let icon_y = card.origin.y + 24.0;
+ ctx.draw_svg_icon(
+ layers,
+ icon,
+ card.origin.x + 24.0,
+ icon_y,
+ 28.0,
+ palette.secondary_text,
+ )?;
+ ctx.draw_text(
+ layers,
+ font,
+ card.origin.x + 68.0,
+ card.origin.y + 22.0,
+ title,
+ palette.text,
+ card.size.width - 92.0,
+ )?;
+ self.draw_wrapped_text(
+ ctx,
+ layers,
+ font,
+ card.origin.x + 24.0,
+ card.origin.y + 26.0 + line_h,
+ card.size.width - 48.0,
+ description,
+ palette.secondary_text,
+ 2,
+ )
+ }
+
+ fn paint_provider_card(
+ &mut self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ card: RectF,
+ palette: UiPalette,
+ font: &Rc<LoadedFont>,
+ provider: ImportProvider,
+ ) -> anyhow::Result<()> {
+ self.widgets.push(
+ card,
+ WidgetKind::Button,
+ OnboardingAction::Provider(provider),
+ );
+ let hovered = self.interaction.hovered == Some(OnboardingAction::Provider(provider));
+ let pressed = self.interaction.pressed == Some(OnboardingAction::Provider(provider));
+ let available = provider.is_available();
+ let bg = if pressed {
+ palette.control_pressed_bg
+ } else if hovered {
+ palette.control_hover_bg
+ } else {
+ palette.control_bg
+ };
+ let border = if hovered {
+ palette.separator
+ } else {
+ palette.control_border
+ };
+ let line_h = Self::line_h(ctx);
+ ctx.draw_rounded_frame(
+ layers,
+ 0,
+ card.origin.x,
+ card.origin.y,
+ card.size.width,
+ card.size.height,
+ bg,
+ border,
+ CARD_RADIUS,
+ )?;
+ let icon_color = if available {
+ palette.secondary_text
+ } else {
+ palette.muted_text
+ };
+ ctx.draw_svg_icon(
+ layers,
+ provider.icon(),
+ card.origin.x + 18.0,
+ card.origin.y + 22.0,
+ 28.0,
+ icon_color,
+ )?;
+ ctx.draw_text(
+ layers,
+ font,
+ card.origin.x + 60.0,
+ card.origin.y + 16.0,
+ provider.label(),
+ palette.text,
+ card.size.width - 78.0,
+ )?;
+ self.draw_wrapped_text(
+ ctx,
+ layers,
+ font,
+ card.origin.x + 60.0,
+ card.origin.y + 16.0 + line_h,
+ card.size.width - 78.0,
+ provider.description(),
+ palette.muted_text,
+ 2,
+ )?;
+ let badge = if available {
+ "Available"
+ } else {
+ "Coming soon"
+ };
+ ctx.draw_text(
+ layers,
+ font,
+ card.origin.x + 60.0,
+ card.origin.y + card.size.height - line_h - 12.0,
+ badge,
+ if available {
+ palette.secondary_text
+ } else {
+ palette.muted_text
+ },
+ card.size.width - 78.0,
+ )
+ }
+
+ fn paint_project_row(
+ &mut self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ row: RectF,
+ clip: RectF,
+ palette: UiPalette,
+ font: &Rc<LoadedFont>,
+ index: usize,
+ project: &PendingProject,
+ ) -> anyhow::Result<()> {
+ let hit_y = row.origin.y.max(clip.origin.y);
+ let hit_h = (row.origin.y + row.size.height).min(clip.origin.y + clip.size.height) - hit_y;
+ if hit_h <= 0.0 {
+ return Ok(());
+ }
+ self.widgets.push(
+ rect(row.origin.x, hit_y, row.size.width, hit_h),
+ WidgetKind::SidebarRow,
+ OnboardingAction::ToggleProject(index),
+ );
+ let hovered = self.interaction.hovered == Some(OnboardingAction::ToggleProject(index));
+ let bg = if project.selected {
+ palette.sidebar_row_active_bg
+ } else if hovered {
+ palette.sidebar_row_hover_bg
+ } else {
+ palette.control_bg
+ };
+ ctx.draw_rounded_frame(
+ layers,
+ 0,
+ row.origin.x,
+ row.origin.y,
+ row.size.width,
+ row.size.height,
+ bg,
+ palette.control_border,
+ CARD_RADIUS,
+ )?;
+ let checkbox = rect(row.origin.x + 16.0, row.origin.y + 24.0, 28.0, 28.0);
+ ctx.draw_rounded_frame(
+ layers,
+ 1,
+ checkbox.origin.x,
+ checkbox.origin.y,
+ checkbox.size.width,
+ checkbox.size.height,
+ if project.selected {
+ palette.selected_bg
+ } else {
+ palette.control_bg
+ },
+ if project.selected {
+ palette.selected_bg
+ } else {
+ palette.control_border
+ },
+ 6.0,
+ )?;
+ if project.selected {
+ ctx.draw_svg_icon(
+ layers,
+ SvgIcon::CircleCheck,
+ checkbox.origin.x + 3.0,
+ checkbox.origin.y + 3.0,
+ 22.0,
+ palette.selected_text,
+ )?;
+ }
+ ctx.draw_text(
+ layers,
+ font,
+ row.origin.x + 62.0,
+ row.origin.y + 16.0,
+ &project.name,
+ palette.text,
+ row.size.width - 154.0,
+ )?;
+ let line_h = Self::line_h(ctx);
+ ctx.draw_text(
+ layers,
+ font,
+ row.origin.x + 62.0,
+ row.origin.y + 16.0 + line_h,
+ &project.path.display().to_string(),
+ palette.secondary_text,
+ row.size.width - 154.0,
+ )?;
+ ctx.draw_text(
+ layers,
+ font,
+ row.origin.x + row.size.width - 132.0,
+ row.origin.y + 16.0,
+ project.source.label(),
+ palette.muted_text,
+ 76.0,
+ )?;
+ let remove = rect(
+ row.origin.x + row.size.width - 46.0,
+ row.origin.y + 22.0,
+ 32.0,
+ 32.0,
+ );
+ self.widgets.push(
+ remove,
+ WidgetKind::Button,
+ OnboardingAction::RemoveProject(index),
+ );
+ let remove_hover = self.interaction.hovered == Some(OnboardingAction::RemoveProject(index));
+ if remove_hover {
+ ctx.draw_rounded_rect(
+ layers,
+ 1,
+ remove.origin.x,
+ remove.origin.y,
+ remove.size.width,
+ remove.size.height,
+ palette.control_hover_bg,
+ 8.0,
+ )?;
+ }
+ ctx.draw_svg_icon(
+ layers,
+ SvgIcon::X,
+ remove.origin.x + 8.0,
+ remove.origin.y + 8.0,
+ 16.0,
+ palette.muted_text,
+ )
+ }
+
+ fn paint_empty_state(
+ &mut self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ area: RectF,
+ palette: UiPalette,
+ font: &Rc<LoadedFont>,
+ ) -> anyhow::Result<()> {
+ let line_h = Self::line_h(ctx);
+ let card = rect(
+ area.origin.x,
+ area.origin.y,
+ area.size.width.min(720.0),
+ line_h * 3.4,
+ );
+ ctx.draw_rounded_frame(
+ layers,
+ 0,
+ card.origin.x,
+ card.origin.y,
+ card.size.width,
+ card.size.height,
+ palette.control_bg,
+ palette.control_border,
+ CARD_RADIUS,
+ )?;
+ ctx.draw_svg_icon(
+ layers,
+ SvgIcon::FolderOpen,
+ card.origin.x + 22.0,
+ card.origin.y + 26.0,
+ 34.0,
+ palette.muted_text,
+ )?;
+ ctx.draw_text(
+ layers,
+ font,
+ card.origin.x + 76.0,
+ card.origin.y + 24.0,
+ "No projects queued",
+ palette.text,
+ card.size.width - 98.0,
+ )?;
+ self.draw_wrapped_text(
+ ctx,
+ layers,
+ font,
+ card.origin.x + 76.0,
+ card.origin.y + 24.0 + line_h,
+ card.size.width - 98.0,
+ "Go back to choose a folder manually, continue with an empty workspace, or Skip setup.",
+ palette.secondary_text,
+ 2,
+ )
+ }
+
+ fn paint_preference_group(
+ &mut self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ area: RectF,
+ palette: UiPalette,
+ font: &Rc<LoadedFont>,
+ section_font: &Rc<LoadedFont>,
+ title: &str,
+ choices: &[(&str, OnboardingAction, bool)],
+ ) -> anyhow::Result<()> {
+ let line_h = Self::line_h(ctx);
+ ctx.draw_text(
+ layers,
+ section_font,
+ area.origin.x,
+ area.origin.y,
+ title,
+ palette.text,
+ area.size.width,
+ )?;
+ let columns = 2usize;
+ let gap = 18.0;
+ let control_h = Self::preference_choice_h(ctx);
+ let width = ((area.size.width - gap) / columns as f32).max(180.0);
+ let start_y = area.origin.y + line_h + 26.0;
+ for (idx, (label, action, selected)) in choices.iter().enumerate() {
+ let col = idx % columns;
+ let row = idx / columns;
+ let x = area.origin.x + col as f32 * (width + gap);
+ let y = start_y + row as f32 * (control_h + 18.0);
+ self.paint_choice_pill(
+ ctx,
+ layers,
+ rect(x, y, width, control_h),
+ palette,
+ font,
+ label,
+ *selected,
+ *action,
+ )?;
+ }
+ Ok(())
+ }
+
+ fn paint_choice_pill(
+ &mut self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ area: RectF,
+ palette: UiPalette,
+ font: &Rc<LoadedFont>,
+ label: &str,
+ selected: bool,
+ action: OnboardingAction,
+ ) -> anyhow::Result<()> {
+ self.widgets.push(area, WidgetKind::Button, action);
+ let hovered = self.interaction.hovered == Some(action);
+ let pressed = self.interaction.pressed == Some(action);
+ let bg = if selected {
+ palette.selected_bg.mul_alpha(0.22)
+ } else if pressed {
+ palette.control_pressed_bg
+ } else if hovered {
+ palette.control_hover_bg
+ } else {
+ palette.control_bg
+ };
+ let border = if selected {
+ palette.selected_bg
+ } else {
+ palette.control_border
+ };
+ ctx.draw_rounded_frame(
+ layers,
+ 0,
+ area.origin.x,
+ area.origin.y,
+ area.size.width,
+ area.size.height,
+ bg,
+ border,
+ CARD_RADIUS,
+ )?;
+ ctx.draw_text(
+ layers,
+ font,
+ area.origin.x + 22.0,
+ Self::centered_text_y(ctx, area),
+ label,
+ if selected {
+ palette.text
+ } else {
+ palette.secondary_text
+ },
+ area.size.width - 44.0,
+ )
+ }
+
+ fn paint_button(
+ &mut self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ area: RectF,
+ palette: UiPalette,
+ font: &Rc<LoadedFont>,
+ label: &str,
+ action: OnboardingAction,
+ primary: bool,
+ enabled: bool,
+ ) -> anyhow::Result<()> {
+ self.widgets.push(area, WidgetKind::Button, action);
+ let state = if !enabled {
+ ControlState::Disabled
+ } else if self.interaction.pressed == Some(action) {
+ ControlState::Pressed
+ } else if self.interaction.hovered == Some(action) {
+ ControlState::Hovered
+ } else {
+ ControlState::Normal
+ };
+ let (mut bg, mut border) = state.colors(palette);
+ let mut text = palette.text;
+ if primary && enabled {
+ bg = if state == ControlState::Pressed {
+ palette.selected_bg.mul_alpha(0.78)
+ } else {
+ palette.selected_bg
+ };
+ border = palette.selected_bg;
+ text = palette.selected_text;
+ } else if !enabled {
+ bg = bg.mul_alpha(0.50);
+ text = palette.muted_text;
+ }
+ ctx.draw_rounded_frame(
+ layers,
+ 0,
+ area.origin.x,
+ area.origin.y,
+ area.size.width,
+ area.size.height,
+ bg,
+ border,
+ CARD_RADIUS,
+ )?;
+ let text_w = ctx.measure_text_width(font, label);
+ let max_text_w = (area.size.width - 24.0).max(0.0);
+ let x = area.origin.x + ((area.size.width - text_w.min(max_text_w)) / 2.0).max(12.0);
+ ctx.draw_text(
+ layers,
+ font,
+ x,
+ Self::centered_text_y(ctx, area),
+ label,
+ text,
+ max_text_w,
+ )
+ }
+
+ fn paint_summary_row(
+ &self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ row: RectF,
+ palette: UiPalette,
+ font: &Rc<LoadedFont>,
+ label: &str,
+ value: &str,
+ ) -> anyhow::Result<()> {
+ ctx.draw_rounded_frame(
+ layers,
+ 0,
+ row.origin.x,
+ row.origin.y,
+ row.size.width,
+ row.size.height,
+ palette.control_bg,
+ palette.control_border,
+ CARD_RADIUS,
+ )?;
+ ctx.draw_text(
+ layers,
+ font,
+ row.origin.x + 18.0,
+ Self::centered_text_y(ctx, row),
+ label,
+ palette.secondary_text,
+ row.size.width * 0.42,
+ )?;
+ ctx.draw_text(
+ layers,
+ font,
+ row.origin.x + row.size.width * 0.45,
+ Self::centered_text_y(ctx, row),
+ value,
+ palette.text,
+ row.size.width * 0.52,
+ )
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ fn draw_wrapped_text(
+ &self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ font: &Rc<LoadedFont>,
+ x: f32,
+ mut y: f32,
+ width: f32,
+ text: &str,
+ color: LinearRgba,
+ max_lines: usize,
+ ) -> anyhow::Result<()> {
+ if max_lines == 0 || width <= 0.0 || text.is_empty() {
+ return Ok(());
+ }
+ let mut lines = Vec::new();
+ let mut current = String::new();
+ let mut consumed_words = 0usize;
+ let words = text.split_whitespace().collect::<Vec<_>>();
+ for word in &words {
+ let candidate = if current.is_empty() {
+ (*word).to_string()
+ } else {
+ format!("{current} {word}")
+ };
+ if current.is_empty() || ctx.measure_text_width(font, &candidate) <= width {
+ current = candidate;
+ consumed_words += 1;
+ } else {
+ lines.push(current);
+ current = (*word).to_string();
+ consumed_words += 1;
+ if lines.len() == max_lines {
+ break;
+ }
+ }
+ }
+ if !current.is_empty() && lines.len() < max_lines {
+ lines.push(current);
+ }
+ let truncated = consumed_words < words.len();
+ if truncated {
+ if let Some(last) = lines.last_mut() {
+ *last = ctx.text_with_ellipsis(font, last, width);
+ }
+ }
+ let line_h = Self::compact_line_h(ctx);
+ for line in lines.into_iter().take(max_lines) {
+ ctx.draw_text(layers, font, x, y, &line, color, width)?;
+ y += line_h;
+ }
+ Ok(())
+ }
+}
+
+#[derive(Debug, Clone)]
+struct OnboardingPrefs {
+ space_name: String,
+ target_space_id: Option<String>,
+ imported_project_count: usize,
+ language: NativeLanguagePreference,
+ appearance: NativeThemeMode,
+ show_left_sidebar: bool,
+}
+
+fn finish_onboarding(tw: &mut TermWindow, prefs: OnboardingPrefs) {
+ let mut settings = crate::native_settings::load();
+ apply_onboarding_preferences(&mut settings, &prefs);
+ if let Err(err) = crate::native_settings::save(&settings) {
+ log::error!("failed to save onboarding settings: {err:#}");
+ }
+ crate::native_settings::apply_to_app(&settings);
+ if let Some(front_end) = crate::frontend::try_front_end() {
+ front_end.invalidate_all_windows();
+ }
+
+ let space_id = prefs
+ .target_space_id
+ .clone()
+ .unwrap_or_else(|| crate::workspace_threads::ensure_space_named(&prefs.space_name));
+
+ if let Some(window) = tw.window.as_ref().cloned() {
+ if tw.active_space_id != space_id {
+ tw.switch_space(space_id, &window);
+ } else {
+ window.invalidate();
+ }
+ if tw.workspace_sidebar_collapsed == prefs.show_left_sidebar {
+ tw.workspace_sidebar_collapsed = !prefs.show_left_sidebar;
+ let dimensions = tw.dimensions;
+ tw.apply_dimensions(&dimensions, None, &window);
+ }
+ }
+ log::debug!(
+ "onboarding completed: imported_project_count={}",
+ prefs.imported_project_count
+ );
+ tw.close_content_view();
+}
+
+fn apply_onboarding_preferences(settings: &mut ThinkTermNativeSettings, prefs: &OnboardingPrefs) {
+ settings.appearance.theme_mode = prefs.appearance;
+ settings.onboarding.language = prefs.language;
+ settings.onboarding.show_left_sidebar_by_default = prefs.show_left_sidebar;
+ mark_onboarding_seen(settings);
+}
+
+fn project_name_for_path(path: &Path) -> String {
+ path.file_name()
+ .and_then(|name| name.to_str())
+ .filter(|name| !name.is_empty())
+ .unwrap_or("Project")
+ .to_string()
+}
+
+fn inset_rect(rect: RectF, amount: f32) -> RectF {
+ euclid::rect(
+ rect.origin.x + amount,
+ rect.origin.y + amount,
+ (rect.size.width - amount * 2.0).max(0.0),
+ (rect.size.height - amount * 2.0).max(0.0),
+ )
+}
+
+impl ContentView for OnboardingView {
+ fn title(&self) -> String {
+ "ThinkTerm Setup".to_string()
+ }
+
+ fn wants_cursor_blink(&self) -> bool {
+ false
+ }
+
+ fn next_frame_time(&self) -> Option<Instant> {
+ self.transition
+ .filter(|transition| transition.started_at.elapsed() < Self::transition_duration())
+ .map(|_| Instant::now() + Duration::from_millis(16))
+ }
+
+ fn paint(
+ &mut self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ area: RectF,
+ palette: UiPalette,
+ font: &Rc<LoadedFont>,
+ title_font: &Rc<LoadedFont>,
+ section_font: &Rc<LoadedFont>,
+ cursor_on: bool,
+ ) -> anyhow::Result<()> {
+ self.paint_impl(
+ ctx,
+ layers,
+ area,
+ palette,
+ font,
+ title_font,
+ section_font,
+ cursor_on,
+ )
+ }
+
+ fn on_mouse(&mut self, x: f32, y: f32, kind: WMEK) -> ContentViewResponse {
+ self.on_mouse_impl(x, y, kind)
+ }
+
+ fn on_key(&mut self, key: KeyCode, mods: KeyModifiers) -> ContentViewResponse {
+ self.on_key_impl(key, mods)
+ }
+
+ fn on_paste(&mut self, text: &str) -> ContentViewResponse {
+ self.on_paste_impl(text)
+ }
+
+ fn on_close_requested(&mut self) -> ContentViewResponse {
+ self.skip_response()
+ }
+
+ fn on_folder_picked(&mut self, path: PathBuf) -> ContentViewResponse {
+ self.add_manual_project(path);
+ ContentViewResponse::Redraw
+ }
+
+ fn copy_text(&self) -> Option<String> {
+ None
+ }
+
+ fn cut_text(&mut self) -> Option<String> {
+ None
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn manual_project_uses_folder_name_and_starts_selected() {
+ let project = PendingProject::from_path(
+ PathBuf::from("/tmp/thinkterm-onboarding-demo"),
+ ProjectSource::Manual,
+ );
+
+ assert_eq!(project.name, "thinkterm-onboarding-demo");
+ assert!(project.selected);
+ assert_eq!(project.source.label(), "Manual");
+ }
+
+ #[test]
+ fn selected_project_count_tracks_toggles() {
+ let mut view = OnboardingView::new("space-default".to_string(), "Default".to_string());
+ view.pending_projects.push(PendingProject::from_path(
+ PathBuf::from("/tmp/one"),
+ ProjectSource::Manual,
+ ));
+ view.pending_projects.push(PendingProject::from_path(
+ PathBuf::from("/tmp/two"),
+ ProjectSource::Manual,
+ ));
+
+ assert_eq!(view.selected_project_count(), 2);
+ view.pending_projects[1].selected = false;
+ assert_eq!(view.selected_project_count(), 1);
+ }
+
+ #[test]
+ fn flow_skips_space_step() {
+ assert_eq!(Step::all().len(), 5);
+ assert_eq!(Step::Welcome.next(), Step::ImportSources);
+ assert_eq!(Step::ImportSources.previous(), Step::Welcome);
+ }
+
+ #[test]
+ fn target_space_uses_initial_space() {
+ let view = OnboardingView::new("space-default".to_string(), "Default".to_string());
+ assert_eq!(view.normalized_space_name(), "Default");
+ assert_eq!(view.target_space_id_for_choice(), "space-default");
+ }
+
+ #[test]
+ fn unavailable_providers_are_not_reported_available() {
+ assert!(ImportProvider::Manual.is_available());
+ assert!(!ImportProvider::VsCode.is_available());
+ assert!(!ImportProvider::Cursor.is_available());
+ assert!(!ImportProvider::Antigravity.is_available());
+ assert!(!ImportProvider::Cmux.is_available());
+ }
+}
diff --git a/wezterm-gui/src/termwindow/render/paint.rs b/wezterm-gui/src/termwindow/render/paint.rs
index 8671883c..f602c381 100644
--- a/wezterm-gui/src/termwindow/render/paint.rs
+++ b/wezterm-gui/src/termwindow/render/paint.rs
@@ -195,6 +195,12 @@ impl crate::TermWindow {
let ui_font = self
.fonts
.command_palette_font_with_size_and_weight(font_size, font_weight)?;
+ let title_font = self
+ .fonts
+ .title_font_with_size_and_weight(font_size + 10.0, font_weight.max(760))?;
+ let section_font = self
+ .fonts
+ .title_font_with_size_and_weight(font_size + 2.0, font_weight.max(700))?;
let render_metrics =
crate::utilsprites::RenderMetrics::with_font_metrics(&ui_font.metrics());
let dimensions = self.dimensions;
@@ -245,9 +251,22 @@ impl crate::TermWindow {
let gl_state = self.render_state.as_ref().unwrap();
let ctx = DrawContext::new(gl_state, dimensions, &render_metrics);
- if let Some(view) = self.content_view.as_mut() {
- view.paint(&ctx, layers, area, palette, &ui_font, cursor_on)?;
- }
+ let next_frame = if let Some(view) = self.content_view.as_mut() {
+ view.paint(
+ &ctx,
+ layers,
+ area,
+ palette,
+ &ui_font,
+ &title_font,
+ &section_font,
+ cursor_on,
+ )?;
+ view.next_frame_time()
+ } else {
+ None
+ };
+ self.update_next_frame_time(next_frame);
Ok(())
}
diff --git a/wezterm-gui/src/termwindow/ssh_hosts_view.rs b/wezterm-gui/src/termwindow/ssh_hosts_view.rs
index 949ff31d..7e1a42b6 100644
--- a/wezterm-gui/src/termwindow/ssh_hosts_view.rs
+++ b/wezterm-gui/src/termwindow/ssh_hosts_view.rs
@@ -1394,6 +1394,8 @@ impl ContentView for SshHostsView {
area: RectF,
palette: UiPalette,
font: &Rc<LoadedFont>,
+ _title_font: &Rc<LoadedFont>,
+ _section_font: &Rc<LoadedFont>,
cursor_on: bool,
) -> anyhow::Result<()> {
self.paint_impl(ctx, layers, area, palette, font, cursor_on)
diff --git a/wezterm-gui/src/workspace_threads.rs b/wezterm-gui/src/workspace_threads.rs
index f26847c4..fc87dd3e 100644
--- a/wezterm-gui/src/workspace_threads.rs
+++ b/wezterm-gui/src/workspace_threads.rs
@@ -420,21 +420,7 @@ pub fn claim_initial_space_for_window(owner_id: u64) -> SpaceId {
let mut store = THREAD_STORE.lock();
let changed = store.normalize_after_load();
- let space_id = store
- .last_active_space_id
- .clone()
- .filter(|space_id| store.has_space(space_id) && !occupied.contains(space_id))
- .or_else(|| {
- store
- .spaces
- .iter()
- .find(|space| !occupied.contains(&space.id))
- .map(|space| space.id.clone())
- })
- .unwrap_or_else(|| {
- let name = next_space_name(&store.spaces);
- store.create_space_record(name)
- });
+ let space_id = store.claim_available_space_id(&occupied);
if store.last_active_space_id.as_deref() != Some(&space_id) {
store.last_active_space_id = Some(space_id.clone());
persist_locked(&store);
@@ -447,6 +433,10 @@ pub fn claim_initial_space_for_window(owner_id: u64) -> SpaceId {
space_id
}
+pub fn claim_space_for_new_window(owner_id: u64) -> SpaceId {
+ claim_initial_space_for_window(owner_id)
+}
+
pub fn release_window_space(owner_id: u64) {
WINDOW_SPACES.lock().remove(&owner_id);
}
@@ -516,6 +506,30 @@ pub fn create_space(name: Option<String>) -> SpaceId {
id
}
+pub fn ensure_space_named(name: &str) -> SpaceId {
+ let name = name.trim();
+ let name = if name.is_empty() { "Default" } else { name };
+ let mut store = THREAD_STORE.lock();
+ let mut changed = store.normalize_after_load();
+ let id = store
+ .spaces
+ .iter()
+ .find(|space| space.name.eq_ignore_ascii_case(name))
+ .map(|space| space.id.clone())
+ .unwrap_or_else(|| {
+ changed = true;
+ store.create_space_record(name.to_string())
+ });
+ if store.last_active_space_id.as_deref() != Some(&id) {
+ store.last_active_space_id = Some(id.clone());
+ changed = true;
+ }
+ if changed {
+ persist_locked(&store);
+ }
+ id
+}
+
pub fn rename_space(space_id: &str, name: String) -> bool {
let mut store = THREAD_STORE.lock();
let changed = store.rename_space(space_id, name);
@@ -596,7 +610,7 @@ pub fn ensure_active_thread_for_space(space_id: &str) -> Option<WorkspaceThreadI
.map(|project| project.id.clone())
})
.unwrap_or_else(|| {
- let mut project = current_project_from_cwd(space_id);
+ let mut project = default_project_for_space(space_id);
let session = WorkspaceThread::new(project.id.clone(), "main".to_string(), None);
let thread_id = session.id.clone();
project.active_thread_id = Some(thread_id);
@@ -632,19 +646,18 @@ pub fn workspace_has_thread_binding(workspace: &str) -> bool {
store.workspace_space_id(workspace).is_some()
}
-pub fn current_project_from_cwd(space_id: &str) -> 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();
+/// A brand-new / empty Space has no project yet. Give it a stable default
+/// project rooted at the user's home directory. Previously this used the
+/// process launch cwd (`std::env::current_dir()`), which is arbitrary — `/`
+/// when launched from Finder, or whatever directory the binary was started
+/// from — and made a new Space appear to "inherit" the previous window's path.
+pub fn default_project_for_space(space_id: &str) -> Project {
+ let path = config::HOME_DIR.clone();
let id = project_id_for_path(space_id, &path);
Project {
id,
space_id: space_id.to_string(),
- name,
+ name: "Home".to_string(),
path,
threads: vec![],
active_thread_id: None,
@@ -653,7 +666,7 @@ pub fn current_project_from_cwd(space_id: &str) -> Project {
}
fn current_project_for_workspace(space_id: &str, active_workspace: &str) -> Project {
- let mut project = current_project_from_cwd(space_id);
+ let mut project = default_project_for_space(space_id);
let session = WorkspaceThread::new_initial(
project.id.clone(),
"main".to_string(),
@@ -1192,6 +1205,25 @@ impl WorkspaceThreadStore {
id
}
+ fn claim_available_space_id(
+ &mut self,
+ occupied: &std::collections::HashSet<SpaceId>,
+ ) -> SpaceId {
+ self.last_active_space_id
+ .clone()
+ .filter(|space_id| self.has_space(space_id) && !occupied.contains(space_id))
+ .or_else(|| {
+ self.spaces
+ .iter()
+ .find(|space| !occupied.contains(&space.id))
+ .map(|space| space.id.clone())
+ })
+ .unwrap_or_else(|| {
+ let name = next_space_name(&self.spaces);
+ self.create_space_record(name)
+ })
+ }
+
fn rename_space(&mut self, space_id: &str, name: String) -> bool {
let name = name.trim();
if name.is_empty() {
@@ -1276,7 +1308,7 @@ impl WorkspaceThreadStore {
space_id: &str,
active_workspace: &str,
) -> (ProjectId, bool) {
- let current = current_project_from_cwd(space_id);
+ let current = default_project_for_space(space_id);
let (project_id, mut changed) = if let Some(project) = self
.projects
.iter()
@@ -2795,6 +2827,37 @@ mod tests {
assert!(!is_materializing_thread_layout(&workspace));
}
+ #[test]
+ fn claim_available_space_prefers_unoccupied_existing_space() {
+ let mut store = test_store();
+ let default_space = default_space_id();
+ let second_space = store.create_space_record("Second".to_string());
+ let third_space = store.create_space_record("Third".to_string());
+ store.last_active_space_id = Some(second_space.clone());
+ let occupied: std::collections::HashSet<SpaceId> =
+ vec![default_space, third_space].into_iter().collect();
+
+ let claimed = store.claim_available_space_id(&occupied);
+
+ assert_eq!(claimed, second_space);
+ assert_eq!(store.spaces.len(), 3);
+ }
+
+ #[test]
+ fn claim_available_space_creates_when_all_spaces_are_occupied() {
+ let mut store = test_store();
+ let default_space = default_space_id();
+ let second_space = store.create_space_record("Second".to_string());
+ let occupied: std::collections::HashSet<SpaceId> =
+ vec![default_space, second_space].into_iter().collect();
+
+ let claimed = store.claim_available_space_id(&occupied);
+
+ assert!(!occupied.contains(&claimed));
+ assert!(store.has_space(&claimed));
+ assert_eq!(store.spaces.len(), 3);
+ }
+
#[test]
fn empty_space_has_no_thread_to_restore() {
let mut store = test_store();