Skip to main content

par_term/app/window_state/
impl_init.rs

1//! Constructor and async initialization for `WindowState`.
2
3use super::impl_agent::merge_custom_ai_inspector_agents;
4use super::{
5    EguiState, FocusState, OverlayState, RenderLoopState, TriggerState, UpdateState, WatcherState,
6    WindowState,
7};
8use crate::badge::BadgeState;
9use crate::config::Config;
10use crate::smart_selection::SmartSelectionCache;
11use crate::status_bar::StatusBarUI;
12use crate::tab::TabManager;
13use crate::tab_bar_ui::TabBarUI;
14use anyhow::Result;
15use arc_swap::ArcSwap;
16use par_term_acp::discover_agents;
17use par_term_input::InputHandler;
18use par_term_keybindings::{KeyCombo, KeybindingRegistry};
19use std::sync::Arc;
20use tokio::runtime::Runtime;
21use winit::window::Window;
22
23impl WindowState {
24    pub(crate) fn parse_custom_action_prefix_combo(prefix_key: &str) -> Option<KeyCombo> {
25        let trimmed = prefix_key.trim();
26        if trimmed.is_empty() {
27            return None;
28        }
29
30        match par_term_keybindings::parser::parse_key_combo(trimmed) {
31            Ok(combo) => Some(combo),
32            Err(error) => {
33                log::warn!(
34                    "Invalid custom action prefix key '{}': {}",
35                    prefix_key,
36                    error
37                );
38                None
39            }
40        }
41    }
42
43    /// Create a new window state with the given configuration
44    pub fn new(config: Config, runtime: Arc<Runtime>) -> Self {
45        let keybinding_registry = KeybindingRegistry::from_config(&config.keybindings);
46        let custom_action_prefix_combo =
47            Self::parse_custom_action_prefix_combo(&config.custom_action_prefix_key);
48        let shaders_dir = Config::shaders_dir();
49        let tmux_prefix_key = crate::tmux::PrefixKey::parse(&config.tmux.tmux_prefix_key);
50
51        let mut input_handler = InputHandler::new();
52        // Initialize Option/Alt key modes from config
53        input_handler.update_option_key_modes(
54            config.input.left_option_key_mode,
55            config.input.right_option_key_mode,
56        );
57
58        // Create badge state and overlay UI before wrapping config in ArcSwap
59        let badge_state = BadgeState::new(&config);
60        let overlay_ui = crate::app::window_state::overlay_ui_state::OverlayUiState::new(&config);
61
62        // Discover available ACP agents
63        let config_dir = Config::config_dir();
64        let discovered_agents = discover_agents(&config_dir);
65        let available_agents = merge_custom_ai_inspector_agents(
66            discovered_agents,
67            &config.ai_inspector.ai_inspector_custom_agents,
68        );
69
70        Self {
71            config: ArcSwap::from(Arc::new(config)),
72            window: None,
73            renderer: None,
74            input_handler,
75            runtime,
76
77            tab_manager: TabManager::new(),
78            tab_bar_ui: TabBarUI::new(),
79            status_bar_ui: StatusBarUI::new(),
80
81            debug: crate::app::window_state::debug_state::DebugState::new(),
82            frame: crate::app::window_state::frame_state::FrameState::new(),
83
84            cursor_anim: crate::app::window_state::cursor_anim_state::CursorAnimState::default(),
85            is_fullscreen: false,
86            egui: EguiState::default(),
87            shader_state: crate::app::window_state::shader_state::ShaderState::new(shaders_dir),
88            overlay_ui,
89            agent_state: super::agent_state::AgentState::new(available_agents),
90            is_recording: false,
91            is_shutting_down: false,
92            window_index: 1, // Will be set by WindowManager when window is created
93
94            focus_state: FocusState::default(),
95
96            render_loop: RenderLoopState::default(),
97
98            watcher_state: WatcherState::default(),
99
100            clipboard_image_click_guard: None,
101
102            last_osc52_clipboard: None,
103
104            overlay_state: OverlayState::default(),
105
106            keybinding_registry,
107            custom_action_prefix_combo,
108            custom_action_prefix_state: crate::tmux::PrefixState::default(),
109
110            smart_selection_cache: SmartSelectionCache::new(),
111
112            tmux_state: super::TmuxState::new(tmux_prefix_key),
113
114            broadcast_input: false,
115            pane_transfer_state: Default::default(),
116            pane_hint_select: Default::default(),
117
118            badge_state,
119
120            copy_mode: crate::copy_mode::CopyModeState::new(),
121
122            file_transfer_state: crate::app::file_transfers::FileTransferState::default(),
123
124            update_state: UpdateState::default(),
125
126            trigger_state: TriggerState::default(),
127
128            agent_commands: crate::agent_commands_store::AgentCommandStore::new(),
129
130            notification_click_state: super::NotificationClickState::default(),
131
132            pending_snap_size: None,
133
134            last_workflow_context: std::sync::Arc::new(std::sync::Mutex::new(None)),
135        }
136    }
137
138    /// Format window title with optional window number
139    /// This should be used everywhere a title is set to ensure consistency
140    pub(crate) fn format_title(&self, base_title: &str) -> String {
141        if self.config.load().placement.show_window_number {
142            format!("{} [{}]", base_title, self.window_index)
143        } else {
144            base_title.to_string()
145        }
146    }
147
148    /// Extract a substring based on character columns to avoid UTF-8 slicing panics
149    pub(crate) fn extract_columns(line: &str, start_col: usize, end_col: Option<usize>) -> String {
150        let mut extracted = String::new();
151        let end_bound = end_col.unwrap_or(usize::MAX);
152
153        if start_col > end_bound {
154            return extracted;
155        }
156
157        for (idx, ch) in line.chars().enumerate() {
158            if idx > end_bound {
159                break;
160            }
161
162            if idx >= start_col {
163                extracted.push(ch);
164            }
165        }
166
167        extracted
168    }
169
170    /// Initialize the window asynchronously
171    ///
172    /// `skip_default_tab` - When `true`, skips creating the default shell tab.
173    /// Used by the "Move Tab to New Window" path to initialize a fully functional
174    /// window that starts with an empty `TabManager`, ready to receive a transferred
175    /// tab via `insert_tab_at`. All normal callers pass `false`.
176    ///
177    /// `first_tab_cwd` - Optional working directory for the first tab.
178    /// Used by arrangement restore to set the CWD before the shell spawns.
179    pub(crate) async fn initialize_async(
180        &mut self,
181        window: Window,
182        skip_default_tab: bool,
183        first_tab_cwd: Option<String>,
184    ) -> Result<()> {
185        use crate::app::window_state::renderer_init::RendererInitParams;
186
187        // Enable IME (Input Method Editor) to receive all character events including Space
188        window.set_ime_allowed(true);
189        log::debug!("IME enabled for character input");
190
191        // Detect system theme at startup and apply if auto_dark_mode is enabled
192        {
193            let cfg = self.config.load();
194            if cfg.theme_colors.auto_dark_mode {
195                let is_dark = window
196                    .theme()
197                    .is_none_or(|t| t == winit::window::Theme::Dark);
198                drop(cfg); // release guard before mutation via rcu
199                self.config.rcu(|old| {
200                    let mut new = (**old).clone();
201                    if new.apply_system_theme(is_dark) {
202                        Arc::new(new)
203                    } else {
204                        Arc::clone(old)
205                    }
206                });
207                let cfg = self.config.load();
208                log::info!(
209                    "Auto dark mode: detected {} system theme, using theme: {}",
210                    if is_dark { "dark" } else { "light" },
211                    cfg.theme_colors.theme
212                );
213            }
214        }
215
216        // Detect system theme at startup and apply tab style if tab_style is Automatic
217        {
218            let is_dark = window
219                .theme()
220                .is_none_or(|t| t == winit::window::Theme::Dark);
221            let should_apply = {
222                let mut probe = (**self.config.load()).clone();
223                probe.apply_system_tab_style(is_dark)
224            };
225            if should_apply {
226                self.config.rcu(|old| {
227                    let mut new = (**old).clone();
228                    if new.apply_system_tab_style(is_dark) {
229                        Arc::new(new)
230                    } else {
231                        Arc::clone(old)
232                    }
233                });
234                let cfg = self.config.load();
235                log::info!(
236                    "Auto tab style: detected {} system theme, applying {} tab style",
237                    if is_dark { "dark" } else { "light" },
238                    if is_dark {
239                        cfg.tabs.dark_tab_style.display_name()
240                    } else {
241                        cfg.tabs.light_tab_style.display_name()
242                    }
243                );
244            }
245        }
246
247        let window = Arc::new(window);
248
249        // Initialize egui context and state (no memory to preserve on first init)
250        self.init_egui(&window, false);
251
252        // Create renderer using DRY init params
253        let cfg = self.config.load();
254        let theme = cfg.load_theme();
255        // Get shader metadata from cache for full 3-tier resolution
256        let metadata = cfg
257            .shader
258            .custom_shader
259            .as_ref()
260            .and_then(|name| self.shader_state.shader_metadata_cache.get(name).cloned());
261        // Get cursor shader metadata from cache for full 3-tier resolution
262        let cursor_metadata = cfg.shader.cursor_shader.as_ref().and_then(|name| {
263            self.shader_state
264                .cursor_shader_metadata_cache
265                .get(name)
266                .cloned()
267        });
268        let params = RendererInitParams::from_config(
269            &cfg,
270            &theme,
271            metadata.as_ref(),
272            cursor_metadata.as_ref(),
273        );
274        drop(cfg); // release guard before moving to macOS section
275
276        let mut renderer = params.create_renderer(Arc::clone(&window)).await?;
277        self.collect_startup_shader_errors(&mut renderer);
278
279        // macOS: Configure CAMetalLayer (transparency + performance)
280        // This MUST be done AFTER creating the wgpu surface/renderer
281        // so that the CAMetalLayer has been created by wgpu
282        #[cfg(target_os = "macos")]
283        {
284            if let Err(e) = crate::macos_metal::configure_metal_layer_for_performance(&window) {
285                log::warn!("Failed to configure Metal layer: {}", e);
286                log::warn!(
287                    "Continuing anyway - may experience reduced FPS or missing transparency on macOS"
288                );
289            }
290            // Set initial layer opacity to match config (content only, frame unaffected)
291            if let Err(e) = crate::macos_metal::set_layer_opacity(&window, 1.0) {
292                log::warn!("Failed to set initial Metal layer opacity: {}", e);
293            }
294            // Apply initial blur settings if enabled
295            {
296                let cfg = self.config.load();
297                if cfg.window.blur_enabled
298                    && cfg.window.window_opacity < 1.0
299                    && let Err(e) =
300                        crate::macos_blur::set_window_blur(&window, cfg.window.blur_radius)
301                {
302                    log::warn!("Failed to set initial window blur: {}", e);
303                }
304                // macOS 27 draws the titlebar from the NSWindow background color
305                // when the window is non-opaque; winit's transparent(true) set it
306                // to clear at creation. Restore a real background color unless
307                // per-pixel translucency is active.
308                let translucent = cfg.window.window_opacity < 1.0
309                    || (cfg.background.background_image_enabled
310                        && cfg.background.background_image_opacity < 1.0);
311                if let Err(e) =
312                    crate::macos_metal::set_window_background_for_translucency(&window, translucent)
313                {
314                    log::warn!("Failed to set initial window background: {}", e);
315                }
316            }
317        }
318
319        // Apply cursor shader configuration
320        self.apply_cursor_shader_config(&mut renderer, &params);
321
322        // Set tab bar offsets BEFORE creating the first tab
323        // This ensures the terminal is sized correctly from the start
324        // Use 1 as tab count since we're about to create the first tab
325        let (initial_tab_bar_height, initial_tab_bar_width, tab_bar_mode, tab_bar_position) = {
326            let cfg = self.config.load();
327            (
328                self.tab_bar_ui.get_height(1, &cfg),
329                self.tab_bar_ui.get_width(1, &cfg),
330                cfg.tabs.tab_bar_mode,
331                cfg.tabs.tab_bar_position,
332            )
333        };
334        let (initial_cols, initial_rows) = renderer.grid_size();
335        log::info!(
336            "Tab bar init: mode={:?}, position={:?}, height={:.1}, width={:.1}, initial_grid={}x{}, content_offset_y_before={:.1}",
337            tab_bar_mode,
338            tab_bar_position,
339            initial_tab_bar_height,
340            initial_tab_bar_width,
341            initial_cols,
342            initial_rows,
343            renderer.content_offset_y()
344        );
345        self.apply_tab_bar_offsets(&mut renderer, initial_tab_bar_height, initial_tab_bar_width);
346
347        // Get the renderer's grid size BEFORE storing it (and before creating tabs)
348        // This ensures the shell starts with correct dimensions that account for tab bar
349        let (renderer_cols, renderer_rows) = renderer.grid_size();
350        let cell_width = renderer.cell_width();
351        let cell_height = renderer.cell_height();
352
353        self.window = Some(Arc::clone(&window));
354        self.renderer = Some(renderer);
355
356        // Initialize shader watcher if hot reload is enabled
357        self.init_shader_watcher();
358
359        // Initialize config file watcher for automatic reload
360        self.init_config_watcher();
361
362        // Initialize config-update file watcher (MCP server writes here)
363        self.init_config_update_watcher();
364
365        // Initialize screenshot-request watcher (MCP server screenshot tool writes here)
366        self.init_screenshot_request_watcher();
367
368        // Initialize shader-diagnostics-request watcher (MCP server diagnostics tool writes here)
369        self.init_shader_diagnostics_request_watcher();
370
371        // Sync status bar monitor state based on config
372        {
373            let cfg = self.config.load();
374            self.status_bar_ui.sync_monitor_state(&cfg);
375        }
376
377        // Create the first tab with the correct grid size from the renderer
378        // This ensures the shell is spawned with dimensions that account for tab bar.
379        // Skipped when `skip_default_tab` is true (e.g. "Move Tab to New Window" path).
380        if !skip_default_tab {
381            log::info!(
382                "Creating first tab with grid size {}x{} (accounting for tab bar)",
383                renderer_cols,
384                renderer_rows
385            );
386            let (max_fps, inactive_tab_fps) = {
387                let cfg = self.config.load();
388                (cfg.rendering.max_fps, cfg.power.inactive_tab_fps)
389            };
390            let tab_id = self.tab_manager.new_tab_with_cwd(
391                &self.config.load(),
392                Arc::clone(&self.runtime),
393                first_tab_cwd,
394                Some((renderer_cols, renderer_rows)), // Pass correct grid size
395            )?;
396
397            // Set cell dimensions on the terminal (for TIOCGWINSZ pixel size reporting)
398            if let Some(tab) = self.tab_manager.get_tab_mut(tab_id) {
399                let width_px = (renderer_cols as f32 * cell_width) as usize;
400                let height_px = (renderer_rows as f32 * cell_height) as usize;
401
402                if let Ok(mut term) = tab.terminal.try_write() {
403                    term.set_cell_dimensions(cell_width as u32, cell_height as u32);
404                    // Send resize to ensure PTY has correct pixel dimensions
405                    if let Err(e) =
406                        term.resize_with_pixels(renderer_cols, renderer_rows, width_px, height_px)
407                    {
408                        crate::debug_error!("TERMINAL", "resize_with_pixels failed (init): {e}");
409                    }
410                    log::info!(
411                        "Initial terminal dimensions: {}x{} ({}x{} px)",
412                        renderer_cols,
413                        renderer_rows,
414                        width_px,
415                        height_px
416                    );
417                }
418
419                // Start refresh task for the first tab
420                tab.start_refresh_task(
421                    Arc::clone(&self.runtime),
422                    Arc::clone(&window),
423                    max_fps,
424                    inactive_tab_fps,
425                );
426            }
427        }
428
429        // Auto-connect agent if panel is open on startup and auto-launch is enabled
430        if self.overlay_ui.ai_inspector.open {
431            self.try_auto_connect_agent();
432        }
433
434        // Check if we should prompt user to install integrations (shaders and/or shell integration)
435        {
436            let cfg = self.config.load();
437            if cfg.should_prompt_integrations(crate::VERSION) {
438                drop(cfg);
439                log::info!("Integrations not installed - showing welcome dialog");
440                self.overlay_ui.integrations_ui.show_dialog();
441                self.focus_state.needs_redraw = true;
442                window.request_redraw();
443            }
444        }
445
446        Ok(())
447    }
448}