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
117            badge_state,
118
119            copy_mode: crate::copy_mode::CopyModeState::new(),
120
121            file_transfer_state: crate::app::file_transfers::FileTransferState::default(),
122
123            update_state: UpdateState::default(),
124
125            trigger_state: TriggerState::default(),
126
127            notification_click_state: super::NotificationClickState::default(),
128
129            pending_snap_size: None,
130
131            last_workflow_context: std::sync::Arc::new(std::sync::Mutex::new(None)),
132        }
133    }
134
135    /// Format window title with optional window number
136    /// This should be used everywhere a title is set to ensure consistency
137    pub(crate) fn format_title(&self, base_title: &str) -> String {
138        if self.config.load().placement.show_window_number {
139            format!("{} [{}]", base_title, self.window_index)
140        } else {
141            base_title.to_string()
142        }
143    }
144
145    /// Extract a substring based on character columns to avoid UTF-8 slicing panics
146    pub(crate) fn extract_columns(line: &str, start_col: usize, end_col: Option<usize>) -> String {
147        let mut extracted = String::new();
148        let end_bound = end_col.unwrap_or(usize::MAX);
149
150        if start_col > end_bound {
151            return extracted;
152        }
153
154        for (idx, ch) in line.chars().enumerate() {
155            if idx > end_bound {
156                break;
157            }
158
159            if idx >= start_col {
160                extracted.push(ch);
161            }
162        }
163
164        extracted
165    }
166
167    /// Initialize the window asynchronously
168    ///
169    /// `skip_default_tab` - When `true`, skips creating the default shell tab.
170    /// Used by the "Move Tab to New Window" path to initialize a fully functional
171    /// window that starts with an empty `TabManager`, ready to receive a transferred
172    /// tab via `insert_tab_at`. All normal callers pass `false`.
173    ///
174    /// `first_tab_cwd` - Optional working directory for the first tab.
175    /// Used by arrangement restore to set the CWD before the shell spawns.
176    pub(crate) async fn initialize_async(
177        &mut self,
178        window: Window,
179        skip_default_tab: bool,
180        first_tab_cwd: Option<String>,
181    ) -> Result<()> {
182        use crate::app::window_state::renderer_init::RendererInitParams;
183
184        // Enable IME (Input Method Editor) to receive all character events including Space
185        window.set_ime_allowed(true);
186        log::debug!("IME enabled for character input");
187
188        // Detect system theme at startup and apply if auto_dark_mode is enabled
189        {
190            let cfg = self.config.load();
191            if cfg.theme_colors.auto_dark_mode {
192                let is_dark = window
193                    .theme()
194                    .is_none_or(|t| t == winit::window::Theme::Dark);
195                drop(cfg); // release guard before mutation via rcu
196                self.config.rcu(|old| {
197                    let mut new = (**old).clone();
198                    if new.apply_system_theme(is_dark) {
199                        Arc::new(new)
200                    } else {
201                        Arc::clone(old)
202                    }
203                });
204                let cfg = self.config.load();
205                log::info!(
206                    "Auto dark mode: detected {} system theme, using theme: {}",
207                    if is_dark { "dark" } else { "light" },
208                    cfg.theme_colors.theme
209                );
210            }
211        }
212
213        // Detect system theme at startup and apply tab style if tab_style is Automatic
214        {
215            let is_dark = window
216                .theme()
217                .is_none_or(|t| t == winit::window::Theme::Dark);
218            let should_apply = {
219                let mut probe = (**self.config.load()).clone();
220                probe.apply_system_tab_style(is_dark)
221            };
222            if should_apply {
223                self.config.rcu(|old| {
224                    let mut new = (**old).clone();
225                    if new.apply_system_tab_style(is_dark) {
226                        Arc::new(new)
227                    } else {
228                        Arc::clone(old)
229                    }
230                });
231                let cfg = self.config.load();
232                log::info!(
233                    "Auto tab style: detected {} system theme, applying {} tab style",
234                    if is_dark { "dark" } else { "light" },
235                    if is_dark {
236                        cfg.tabs.dark_tab_style.display_name()
237                    } else {
238                        cfg.tabs.light_tab_style.display_name()
239                    }
240                );
241            }
242        }
243
244        let window = Arc::new(window);
245
246        // Initialize egui context and state (no memory to preserve on first init)
247        self.init_egui(&window, false);
248
249        // Create renderer using DRY init params
250        let cfg = self.config.load();
251        let theme = cfg.load_theme();
252        // Get shader metadata from cache for full 3-tier resolution
253        let metadata = cfg
254            .shader
255            .custom_shader
256            .as_ref()
257            .and_then(|name| self.shader_state.shader_metadata_cache.get(name).cloned());
258        // Get cursor shader metadata from cache for full 3-tier resolution
259        let cursor_metadata = cfg.shader.cursor_shader.as_ref().and_then(|name| {
260            self.shader_state
261                .cursor_shader_metadata_cache
262                .get(name)
263                .cloned()
264        });
265        let params = RendererInitParams::from_config(
266            &cfg,
267            &theme,
268            metadata.as_ref(),
269            cursor_metadata.as_ref(),
270        );
271        drop(cfg); // release guard before moving to macOS section
272
273        let mut renderer = params.create_renderer(Arc::clone(&window)).await?;
274        self.collect_startup_shader_errors(&mut renderer);
275
276        // macOS: Configure CAMetalLayer (transparency + performance)
277        // This MUST be done AFTER creating the wgpu surface/renderer
278        // so that the CAMetalLayer has been created by wgpu
279        #[cfg(target_os = "macos")]
280        {
281            if let Err(e) = crate::macos_metal::configure_metal_layer_for_performance(&window) {
282                log::warn!("Failed to configure Metal layer: {}", e);
283                log::warn!(
284                    "Continuing anyway - may experience reduced FPS or missing transparency on macOS"
285                );
286            }
287            // Set initial layer opacity to match config (content only, frame unaffected)
288            if let Err(e) = crate::macos_metal::set_layer_opacity(&window, 1.0) {
289                log::warn!("Failed to set initial Metal layer opacity: {}", e);
290            }
291            // Apply initial blur settings if enabled
292            {
293                let cfg = self.config.load();
294                if cfg.window.blur_enabled
295                    && cfg.window.window_opacity < 1.0
296                    && let Err(e) =
297                        crate::macos_blur::set_window_blur(&window, cfg.window.blur_radius)
298                {
299                    log::warn!("Failed to set initial window blur: {}", e);
300                }
301            }
302        }
303
304        // Apply cursor shader configuration
305        self.apply_cursor_shader_config(&mut renderer, &params);
306
307        // Set tab bar offsets BEFORE creating the first tab
308        // This ensures the terminal is sized correctly from the start
309        // Use 1 as tab count since we're about to create the first tab
310        let (initial_tab_bar_height, initial_tab_bar_width, tab_bar_mode, tab_bar_position) = {
311            let cfg = self.config.load();
312            (
313                self.tab_bar_ui.get_height(1, &cfg),
314                self.tab_bar_ui.get_width(1, &cfg),
315                cfg.tabs.tab_bar_mode,
316                cfg.tabs.tab_bar_position,
317            )
318        };
319        let (initial_cols, initial_rows) = renderer.grid_size();
320        log::info!(
321            "Tab bar init: mode={:?}, position={:?}, height={:.1}, width={:.1}, initial_grid={}x{}, content_offset_y_before={:.1}",
322            tab_bar_mode,
323            tab_bar_position,
324            initial_tab_bar_height,
325            initial_tab_bar_width,
326            initial_cols,
327            initial_rows,
328            renderer.content_offset_y()
329        );
330        self.apply_tab_bar_offsets(&mut renderer, initial_tab_bar_height, initial_tab_bar_width);
331
332        // Get the renderer's grid size BEFORE storing it (and before creating tabs)
333        // This ensures the shell starts with correct dimensions that account for tab bar
334        let (renderer_cols, renderer_rows) = renderer.grid_size();
335        let cell_width = renderer.cell_width();
336        let cell_height = renderer.cell_height();
337
338        self.window = Some(Arc::clone(&window));
339        self.renderer = Some(renderer);
340
341        // Initialize shader watcher if hot reload is enabled
342        self.init_shader_watcher();
343
344        // Initialize config file watcher for automatic reload
345        self.init_config_watcher();
346
347        // Initialize config-update file watcher (MCP server writes here)
348        self.init_config_update_watcher();
349
350        // Initialize screenshot-request watcher (MCP server screenshot tool writes here)
351        self.init_screenshot_request_watcher();
352
353        // Initialize shader-diagnostics-request watcher (MCP server diagnostics tool writes here)
354        self.init_shader_diagnostics_request_watcher();
355
356        // Sync status bar monitor state based on config
357        {
358            let cfg = self.config.load();
359            self.status_bar_ui.sync_monitor_state(&cfg);
360        }
361
362        // Create the first tab with the correct grid size from the renderer
363        // This ensures the shell is spawned with dimensions that account for tab bar.
364        // Skipped when `skip_default_tab` is true (e.g. "Move Tab to New Window" path).
365        if !skip_default_tab {
366            log::info!(
367                "Creating first tab with grid size {}x{} (accounting for tab bar)",
368                renderer_cols,
369                renderer_rows
370            );
371            let (max_fps, inactive_tab_fps) = {
372                let cfg = self.config.load();
373                (cfg.rendering.max_fps, cfg.power.inactive_tab_fps)
374            };
375            let tab_id = self.tab_manager.new_tab_with_cwd(
376                &self.config.load(),
377                Arc::clone(&self.runtime),
378                first_tab_cwd,
379                Some((renderer_cols, renderer_rows)), // Pass correct grid size
380            )?;
381
382            // Set cell dimensions on the terminal (for TIOCGWINSZ pixel size reporting)
383            if let Some(tab) = self.tab_manager.get_tab_mut(tab_id) {
384                let width_px = (renderer_cols as f32 * cell_width) as usize;
385                let height_px = (renderer_rows as f32 * cell_height) as usize;
386
387                if let Ok(mut term) = tab.terminal.try_write() {
388                    term.set_cell_dimensions(cell_width as u32, cell_height as u32);
389                    // Send resize to ensure PTY has correct pixel dimensions
390                    if let Err(e) =
391                        term.resize_with_pixels(renderer_cols, renderer_rows, width_px, height_px)
392                    {
393                        crate::debug_error!("TERMINAL", "resize_with_pixels failed (init): {e}");
394                    }
395                    log::info!(
396                        "Initial terminal dimensions: {}x{} ({}x{} px)",
397                        renderer_cols,
398                        renderer_rows,
399                        width_px,
400                        height_px
401                    );
402                }
403
404                // Start refresh task for the first tab
405                tab.start_refresh_task(
406                    Arc::clone(&self.runtime),
407                    Arc::clone(&window),
408                    max_fps,
409                    inactive_tab_fps,
410                );
411            }
412        }
413
414        // Auto-connect agent if panel is open on startup and auto-launch is enabled
415        if self.overlay_ui.ai_inspector.open {
416            self.try_auto_connect_agent();
417        }
418
419        // Check if we should prompt user to install integrations (shaders and/or shell integration)
420        {
421            let cfg = self.config.load();
422            if cfg.should_prompt_integrations(crate::VERSION) {
423                drop(cfg);
424                log::info!("Integrations not installed - showing welcome dialog");
425                self.overlay_ui.integrations_ui.show_dialog();
426                self.focus_state.needs_redraw = true;
427                window.request_redraw();
428            }
429        }
430
431        Ok(())
432    }
433}