par-term 0.38.0

Cross-platform GPU-accelerated terminal emulator with inline graphics support (Sixel, iTerm2, Kitty)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
//! Window creation, destruction, and monitor positioning.
//!
//! This module handles the core lifecycle of terminal windows: creating new
//! windows with proper configuration, applying monitor-based positioning, and
//! closing windows cleanly.
//!
//! Session save/restore and arranged-window creation live in the sibling
//! `window_session` module.
//!
//! CLI timer handling (check_cli_timers, send_command_to_shell, take_screenshot)
//! lives in the sibling `cli_timer` module.

use std::sync::Arc;
use std::time::Instant;

use winit::event_loop::ActiveEventLoop;

use crate::app::window_state::WindowState;
use crate::config::Config;
use crate::menu::MenuManager;

use super::WindowManager;
use super::update_checker::update_available_version;

impl WindowManager {
    /// Create a new window with a fresh terminal session
    pub fn create_window(&mut self, event_loop: &ActiveEventLoop) {
        use crate::config::WindowType;
        use crate::font_metrics::window_size_from_config;
        use winit::window::Window;

        // Reload config from disk to pick up any changes made by other windows
        if let Ok(fresh_config) = Config::load() {
            self.config.store(Arc::new(fresh_config));
        }

        // Re-apply CLI shader override (fresh config load above would wipe it)
        if let Some(ref shader) = self.runtime_options.shader {
            self.config.rcu(|old| {
                let mut new = (**old).clone();
                new.shader.custom_shader = Some(shader.clone());
                new.shader.custom_shader_enabled = true;
                new.background.background_image_enabled = false;
                Arc::new(new)
            });
        }

        // Calculate window size from cols/rows BEFORE window creation.
        let (width, height) =
            window_size_from_config(&self.config.load(), 1.0).unwrap_or((800, 600));

        // Build window title, optionally including window number
        let window_number = self.windows.len() + 1;
        let title = if self.config.load().placement.show_window_number {
            format!("{} [{}]", self.config.load().window_title, window_number)
        } else {
            self.config.load().window_title.clone()
        };

        let mut window_attrs = Window::default_attributes()
            .with_title(&title)
            .with_inner_size(winit::dpi::LogicalSize::new(width, height))
            .with_decorations(self.config.load().window.window_decorations);

        // Lock window size if requested (prevent resize)
        if self.config.load().placement.lock_window_size {
            window_attrs = window_attrs.with_resizable(false);
            log::info!("Window size locked (resizing disabled)");
        }

        // Start in fullscreen if window_type is Fullscreen
        if self.config.load().placement.window_type == WindowType::Fullscreen {
            window_attrs =
                window_attrs.with_fullscreen(Some(winit::window::Fullscreen::Borderless(None)));
            log::info!("Window starting in fullscreen mode");
        }

        // Load and set the application icon
        let icon_bytes = include_bytes!("../../../assets/icon.png");
        if let Ok(icon_image) = image::load_from_memory(icon_bytes) {
            let rgba = icon_image.to_rgba8();
            let (width, height) = rgba.dimensions();
            if let Ok(icon) = winit::window::Icon::from_rgba(rgba.into_raw(), width, height) {
                window_attrs = window_attrs.with_window_icon(Some(icon));
                log::info!("Window icon set ({}x{})", width, height);
            } else {
                log::warn!("Failed to create window icon from RGBA data");
            }
        } else {
            log::warn!("Failed to load embedded icon image");
        }

        // Set window always-on-top if requested
        if self.config.load().window.window_always_on_top {
            window_attrs = window_attrs.with_window_level(winit::window::WindowLevel::AlwaysOnTop);
            log::info!("Window always-on-top enabled");
        }

        // Always enable window transparency support for runtime opacity changes
        window_attrs = window_attrs.with_transparent(true);
        log::info!(
            "Window transparency enabled (opacity: {})",
            self.config.load().window.window_opacity
        );

        // macOS: accept the first mouse click so that clicking the tab bar or
        // any other UI element while the window is in the background both brings
        // the window into focus AND delivers the click to the application.
        // Without this, macOS silently eats the activation click and the user
        // must click a second time to interact.  The existing focus-click
        // suppression path (`focus_click_pending`) still guards the terminal
        // area against forwarding clicks to PTY mouse-tracking apps.
        #[cfg(target_os = "macos")]
        {
            use winit::platform::macos::WindowAttributesExtMacOS as _;
            window_attrs = window_attrs.with_accepts_first_mouse(true);
        }

        match event_loop.create_window(window_attrs) {
            Ok(window) => {
                let window_id = window.id();

                // Initialize menu BEFORE the blocking GPU init so that macOS
                // menu accelerators (Cmd+, for Settings, Cmd+Q for Quit) are
                // registered immediately. Without this, there is a multi-second
                // window during GPU setup where winit's default menu is active
                // and unhandled key combos can cause the app to exit via
                // [NSApp terminate:].
                if self.menu.is_none() {
                    match MenuManager::new() {
                        Ok(menu) => {
                            if let Err(e) = menu.init_global() {
                                log::warn!("Failed to initialize global menu: {}", e);
                            }
                            self.menu = Some(menu);
                        }
                        Err(e) => {
                            log::warn!("Failed to create menu: {}", e);
                        }
                    }
                }

                let mut window_state =
                    WindowState::new((**self.config.load()).clone(), Arc::clone(&self.runtime));
                // Set window index for title formatting (window_number calculated earlier)
                window_state.window_index = window_number;

                // Initialize async components using the shared runtime
                // (GPU setup — this blocks for 2-3 seconds)
                let runtime = Arc::clone(&self.runtime);
                if let Err(e) = runtime.block_on(window_state.initialize_async(window, false, None))
                {
                    log::error!("Failed to initialize window: {}", e);
                    return;
                }

                // Attach menu to the window (platform-specific: per-window on Windows/Linux)
                if let Some(menu) = &self.menu
                    && let Some(win) = &window_state.window
                    && let Err(e) = menu.init_for_window(win)
                {
                    log::warn!("Failed to initialize menu for window: {}", e);
                }

                // Apply target monitor and edge positioning after window creation
                if let Some(win) = &window_state.window {
                    self.apply_window_positioning(win, event_loop);
                }

                // Handle tmux auto-attach on first window only
                if self.windows.is_empty()
                    && window_state.config.load().tmux.tmux_enabled
                    && window_state.config.load().tmux.tmux_auto_attach
                {
                    let session_name = window_state
                        .config
                        .load()
                        .tmux
                        .tmux_auto_attach_session
                        .clone();

                    // Use gateway mode: writes tmux commands to existing PTY
                    if let Some(ref name) = session_name {
                        if !name.is_empty() {
                            log::info!(
                                "tmux auto-attach: attempting to attach to session '{}' via gateway",
                                name
                            );
                            match window_state.attach_tmux_gateway(name) {
                                Ok(()) => {
                                    log::info!(
                                        "tmux auto-attach: gateway initiated for session '{}'",
                                        name
                                    );
                                }
                                Err(e) => {
                                    log::warn!(
                                        "tmux auto-attach: failed to attach to '{}': {} - continuing without tmux",
                                        name,
                                        e
                                    );
                                    // Continue without tmux - don't fail startup
                                }
                            }
                        } else {
                            // Empty string means create new session
                            log::info!(
                                "tmux auto-attach: no session specified, creating new session via gateway"
                            );
                            if let Err(e) = window_state.initiate_tmux_gateway(None) {
                                log::warn!(
                                    "tmux auto-attach: failed to create new session: {} - continuing without tmux",
                                    e
                                );
                            }
                        }
                    } else {
                        // None means create new session
                        log::info!(
                            "tmux auto-attach: no session specified, creating new session via gateway"
                        );
                        if let Err(e) = window_state.initiate_tmux_gateway(None) {
                            log::warn!(
                                "tmux auto-attach: failed to create new session: {} - continuing without tmux",
                                e
                            );
                        }
                    }
                }

                self.windows.insert(window_id, window_state);
                self.pending_window_count += 1;

                // Sync existing update state to new window's status bar and dialog
                let update_version = self
                    .last_update_result
                    .as_ref()
                    .and_then(update_available_version);
                let update_result_clone = self.last_update_result.clone();
                let install_type = self.detect_installation_type();
                if let Some(ws) = self.windows.get_mut(&window_id) {
                    ws.status_bar_ui.update_available_version = update_version;
                    ws.update_state.last_result = update_result_clone;
                    ws.update_state.installation_type = install_type;
                }

                // Set start time on first window creation (for CLI timers)
                if self.start_time.is_none() {
                    self.start_time = Some(Instant::now());
                }

                log::info!(
                    "Created new window {:?} (total: {})",
                    window_id,
                    self.windows.len()
                );
            }
            Err(e) => {
                log::error!("Failed to create window: {}", e);
            }
        }
    }

    /// Create a window that will immediately receive a tab transferred via
    /// `move_tab`. Unlike [`Self::create_window`], this helper:
    ///
    /// - uses the caller-supplied `size` and `outer_position` instead of the
    ///   config default, so the new window matches the source window's geometry
    /// - calls `initialize_async(..., skip_default_tab = true, None)` so the new
    ///   window starts with an empty `TabManager`
    /// - skips tmux auto-attach and "first-window-only" side effects (menu init
    ///   is still performed once globally via `self.menu.is_none()`)
    ///
    /// Returns the new `WindowId`, or `None` on failure.
    pub(crate) fn create_window_for_moved_tab(
        &mut self,
        event_loop: &winit::event_loop::ActiveEventLoop,
        size: winit::dpi::PhysicalSize<u32>,
        outer_position: winit::dpi::PhysicalPosition<i32>,
    ) -> Option<winit::window::WindowId> {
        use winit::window::Window;

        // Reload config from disk so the new window picks up latest settings.
        if let Ok(fresh_config) = Config::load() {
            self.config.store(Arc::new(fresh_config));
        }

        // Re-apply CLI shader override (fresh config load would wipe it).
        if let Some(ref shader) = self.runtime_options.shader {
            self.config.rcu(|old| {
                let mut new = (**old).clone();
                new.shader.custom_shader = Some(shader.clone());
                new.shader.custom_shader_enabled = true;
                new.background.background_image_enabled = false;
                Arc::new(new)
            });
        }

        let window_number = self.windows.len() + 1;
        let title = if self.config.load().placement.show_window_number {
            format!("{} [{}]", self.config.load().window_title, window_number)
        } else {
            self.config.load().window_title.clone()
        };

        let mut window_attrs = Window::default_attributes()
            .with_title(&title)
            .with_inner_size(size)
            .with_decorations(self.config.load().window.window_decorations)
            .with_transparent(true);

        if self.config.load().placement.lock_window_size {
            window_attrs = window_attrs.with_resizable(false);
        }

        // Icon
        let icon_bytes = include_bytes!("../../../assets/icon.png");
        if let Ok(icon_image) = image::load_from_memory(icon_bytes) {
            let rgba = icon_image.to_rgba8();
            let (w, h) = rgba.dimensions();
            if let Ok(icon) = winit::window::Icon::from_rgba(rgba.into_raw(), w, h) {
                window_attrs = window_attrs.with_window_icon(Some(icon));
            }
        }

        if self.config.load().window.window_always_on_top {
            window_attrs = window_attrs.with_window_level(winit::window::WindowLevel::AlwaysOnTop);
        }

        #[cfg(target_os = "macos")]
        {
            use winit::platform::macos::WindowAttributesExtMacOS as _;
            window_attrs = window_attrs.with_accepts_first_mouse(true);
        }

        let window = match event_loop.create_window(window_attrs) {
            Ok(w) => w,
            Err(e) => {
                crate::debug_error!(
                    "TAB",
                    "create_window_for_moved_tab: winit create_window failed: {}",
                    e
                );
                return None;
            }
        };
        let window_id = window.id();

        // Menu init (idempotent — only runs once globally).
        if self.menu.is_none() {
            match MenuManager::new() {
                Ok(menu) => {
                    if let Err(e) = menu.init_global() {
                        log::warn!("Failed to initialize global menu: {}", e);
                    }
                    self.menu = Some(menu);
                }
                Err(e) => log::warn!("Failed to create menu: {}", e),
            }
        }

        let mut window_state =
            WindowState::new((**self.config.load()).clone(), Arc::clone(&self.runtime));
        window_state.window_index = window_number;

        let runtime = Arc::clone(&self.runtime);
        if let Err(e) = runtime.block_on(window_state.initialize_async(window, true, None)) {
            crate::debug_error!(
                "TAB",
                "create_window_for_moved_tab: initialize_async failed: {}",
                e
            );
            return None;
        }

        // Attach menu per-window (platform-specific).
        if let Some(menu) = &self.menu
            && let Some(win) = &window_state.window
            && let Err(e) = menu.init_for_window(win)
        {
            log::warn!("Failed to initialize menu for moved-tab window: {}", e);
        }

        // Apply the requested outer position. Clamp is the caller's responsibility.
        if let Some(win) = &window_state.window {
            win.set_outer_position(outer_position);
        }

        self.windows.insert(window_id, window_state);
        self.pending_window_count += 1;

        crate::debug_info!(
            "TAB",
            "Created new window {:?} for moved tab at {:?} size {:?}",
            window_id,
            outer_position,
            size
        );

        Some(window_id)
    }

    /// Compute the outer position for a newly-spawned "move to new window" window.
    ///
    /// Starts from the source window's outer position + (30, 30) and clamps so the
    /// full rect of the new window stays inside the source's monitor. If clamping
    /// would require moving back across the source, returns the source's exact
    /// outer position (new window stacks directly on top of the source).
    pub(crate) fn compute_moved_tab_outer_position(
        event_loop: &winit::event_loop::ActiveEventLoop,
        source_outer_pos: winit::dpi::PhysicalPosition<i32>,
        new_window_size: winit::dpi::PhysicalSize<u32>,
    ) -> winit::dpi::PhysicalPosition<i32> {
        const OFFSET: i32 = 30;
        let desired = winit::dpi::PhysicalPosition::new(
            source_outer_pos.x + OFFSET,
            source_outer_pos.y + OFFSET,
        );

        let monitors: Vec<_> = event_loop.available_monitors().collect();
        let source_monitor = monitors
            .iter()
            .find(|m| {
                let mp = m.position();
                let ms = m.size();
                source_outer_pos.x >= mp.x
                    && source_outer_pos.y >= mp.y
                    && source_outer_pos.x < mp.x + ms.width as i32
                    && source_outer_pos.y < mp.y + ms.height as i32
            })
            .or_else(|| monitors.first());

        let Some(monitor) = source_monitor else {
            return desired;
        };

        let mp = monitor.position();
        let ms = monitor.size();
        let max_x = mp.x + ms.width as i32 - new_window_size.width as i32;
        let max_y = mp.y + ms.height as i32 - new_window_size.height as i32;

        let clamped_x = desired.x.min(max_x).max(mp.x);
        let clamped_y = desired.y.min(max_y).max(mp.y);

        // If clamping pushed us back above the source (source is huge relative to
        // the monitor), stack on top of the source instead.
        if clamped_x <= source_outer_pos.x && clamped_y <= source_outer_pos.y {
            source_outer_pos
        } else {
            winit::dpi::PhysicalPosition::new(clamped_x, clamped_y)
        }
    }

    /// Apply window positioning based on config (target monitor and edge anchoring)
    pub(super) fn apply_window_positioning(
        &self,
        window: &std::sync::Arc<winit::window::Window>,
        event_loop: &ActiveEventLoop,
    ) {
        use crate::config::WindowType;

        // Get list of available monitors
        let monitors: Vec<_> = event_loop.available_monitors().collect();
        if monitors.is_empty() {
            log::warn!("No monitors available for window positioning");
            return;
        }

        // Select target monitor (default to primary/first)
        let monitor = if let Some(index) = self.config.load().placement.target_monitor {
            monitors
                .get(index)
                .cloned()
                .or_else(|| monitors.first().cloned())
        } else {
            event_loop
                .primary_monitor()
                .or_else(|| monitors.first().cloned())
        };

        let Some(monitor) = monitor else {
            log::warn!("Could not determine target monitor");
            return;
        };

        let monitor_pos = monitor.position();
        let monitor_size = monitor.size();
        let window_size = window.outer_size();

        // Apply edge positioning if configured
        match self.config.load().placement.window_type {
            WindowType::EdgeTop => {
                // Position at top of screen, spanning full width
                window.set_outer_position(winit::dpi::PhysicalPosition::new(
                    monitor_pos.x,
                    monitor_pos.y,
                ));
                let _ = window.request_inner_size(winit::dpi::PhysicalSize::new(
                    monitor_size.width,
                    window_size.height,
                ));
                log::info!("Window positioned at top edge of monitor");
            }
            WindowType::EdgeBottom => {
                // Position at bottom of screen, spanning full width
                let y = monitor_pos.y + monitor_size.height as i32 - window_size.height as i32;
                window.set_outer_position(winit::dpi::PhysicalPosition::new(monitor_pos.x, y));
                let _ = window.request_inner_size(winit::dpi::PhysicalSize::new(
                    monitor_size.width,
                    window_size.height,
                ));
                log::info!("Window positioned at bottom edge of monitor");
            }
            WindowType::EdgeLeft => {
                // Position at left of screen, spanning full height
                window.set_outer_position(winit::dpi::PhysicalPosition::new(
                    monitor_pos.x,
                    monitor_pos.y,
                ));
                let _ = window.request_inner_size(winit::dpi::PhysicalSize::new(
                    window_size.width,
                    monitor_size.height,
                ));
                log::info!("Window positioned at left edge of monitor");
            }
            WindowType::EdgeRight => {
                // Position at right of screen, spanning full height
                let x = monitor_pos.x + monitor_size.width as i32 - window_size.width as i32;
                window.set_outer_position(winit::dpi::PhysicalPosition::new(x, monitor_pos.y));
                let _ = window.request_inner_size(winit::dpi::PhysicalSize::new(
                    window_size.width,
                    monitor_size.height,
                ));
                log::info!("Window positioned at right edge of monitor");
            }
            WindowType::Normal | WindowType::Fullscreen => {
                // For normal/fullscreen, just position on target monitor if specified
                if self.config.load().placement.target_monitor.is_some() {
                    // Center window on target monitor
                    let x =
                        monitor_pos.x + (monitor_size.width as i32 - window_size.width as i32) / 2;
                    let y = monitor_pos.y
                        + (monitor_size.height as i32 - window_size.height as i32) / 2;
                    window.set_outer_position(winit::dpi::PhysicalPosition::new(x, y));
                    log::info!(
                        "Window centered on monitor {} at ({}, {})",
                        self.config.load().placement.target_monitor.unwrap_or(0),
                        x,
                        y
                    );
                }
            }
        }

        // Move window to target macOS Space if configured (macOS only, no-op on other platforms)
        if let Some(space) = self.config.load().placement.target_space
            && let Err(e) = crate::macos_space::move_window_to_space(window, space)
        {
            log::warn!("Failed to move window to Space {}: {}", space, e);
        }
    }
}