par-term 0.30.10

Cross-platform GPU-accelerated terminal emulator with inline graphics support (Sixel, iTerm2, Kitty)
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
//! Native menu support for par-term
//!
//! This module provides cross-platform native menu support using the `muda` crate.
//! - macOS: Global application menu bar (see [`macos`])
//! - Linux: Per-window GTK-based menu bar (see [`linux`])
//! - Windows: Per-window Win32 menu bar

mod actions;

/// macOS-specific menu building and NSApp initialization.
#[cfg(target_os = "macos")]
pub(super) mod macos;

/// Linux-specific menu initialization (GTK/X11/Wayland).
#[cfg(any(
    target_os = "linux",
    target_os = "dragonfly",
    target_os = "freebsd",
    target_os = "netbsd",
    target_os = "openbsd"
))]
pub(super) mod linux;

pub use actions::MenuAction;

use crate::profile::Profile;
use anyhow::Result;
use muda::{
    Menu, MenuEvent, MenuId, MenuItem, PredefinedMenuItem, Submenu,
    accelerator::{Accelerator, Code, Modifiers},
};
use std::collections::HashMap;
use std::sync::Arc;
use winit::window::Window;

/// Manages the native menu system
pub struct MenuManager {
    /// The root menu
    menu: Menu,
    /// Mapping from menu item IDs to actions
    action_map: HashMap<MenuId, MenuAction>,
    /// Profiles submenu for dynamic profile items
    profiles_submenu: Submenu,
    /// Track profile menu items for cleanup
    profile_menu_items: Vec<MenuItem>,
}

impl MenuManager {
    /// Create a new menu manager with the default menu structure
    pub fn new() -> Result<Self> {
        let menu = Menu::new();
        let mut action_map = HashMap::new();

        // Platform-specific modifier keys
        // macOS: Cmd (META) is safe — it's separate from Ctrl used by terminal control codes
        // Windows/Linux: Use Ctrl+Shift to avoid conflicts with terminal control codes
        // (Ctrl+C=SIGINT, Ctrl+D=EOF, Ctrl+W=delete-word, Ctrl+V=literal-next, etc.)
        #[cfg(target_os = "macos")]
        let cmd_or_ctrl = Modifiers::META;
        #[cfg(not(target_os = "macos"))]
        let cmd_or_ctrl = Modifiers::CONTROL | Modifiers::SHIFT;

        // For items that already include Shift (same on all platforms)
        #[cfg(target_os = "macos")]
        let cmd_or_ctrl_shift = Modifiers::META | Modifiers::SHIFT;
        #[cfg(not(target_os = "macos"))]
        let cmd_or_ctrl_shift = Modifiers::CONTROL | Modifiers::SHIFT;

        // Tab number switching: Cmd+N (macOS) / Alt+N (Windows/Linux)
        #[cfg(target_os = "macos")]
        let tab_switch_mod = Modifiers::META;
        #[cfg(not(target_os = "macos"))]
        let tab_switch_mod = Modifiers::ALT;

        // macOS: Application menu (must be first submenu — becomes the macOS app menu)
        #[cfg(target_os = "macos")]
        macos::build_app_menu(&menu, &mut action_map)?;

        // File menu
        let file_menu = Submenu::new("File", true);

        let new_window = MenuItem::with_id(
            "new_window",
            "New Window",
            true,
            Some(Accelerator::new(Some(cmd_or_ctrl), Code::KeyN)),
        );
        action_map.insert(new_window.id().clone(), MenuAction::NewWindow);
        file_menu.append(&new_window)?;

        let close_window = MenuItem::with_id(
            "close_window",
            "Close", // Smart close: closes tab if multiple, window if single
            true,
            Some(Accelerator::new(Some(cmd_or_ctrl), Code::KeyW)),
        );
        action_map.insert(close_window.id().clone(), MenuAction::CloseWindow);
        file_menu.append(&close_window)?;

        file_menu.append(&PredefinedMenuItem::separator())?;

        // On macOS, Quit is in the app menu (handled automatically)
        // On Windows/Linux, add Quit to File menu
        #[cfg(not(target_os = "macos"))]
        {
            let quit = MenuItem::with_id(
                "quit",
                "Quit",
                true,
                Some(Accelerator::new(Some(cmd_or_ctrl), Code::KeyQ)),
            );
            action_map.insert(quit.id().clone(), MenuAction::Quit);
            file_menu.append(&quit)?;
        }

        menu.append(&file_menu)?;

        // Tab menu
        let tab_menu = Submenu::new("Tab", true);

        let new_tab = MenuItem::with_id(
            "new_tab",
            "New Tab",
            true,
            Some(Accelerator::new(Some(cmd_or_ctrl), Code::KeyT)),
        );
        action_map.insert(new_tab.id().clone(), MenuAction::NewTab);
        tab_menu.append(&new_tab)?;

        let close_tab = MenuItem::with_id(
            "close_tab",
            "Close Tab",
            true,
            None, // Same as Close in File menu (smart close)
        );
        action_map.insert(close_tab.id().clone(), MenuAction::CloseTab);
        tab_menu.append(&close_tab)?;

        tab_menu.append(&PredefinedMenuItem::separator())?;

        let next_tab = MenuItem::with_id(
            "next_tab",
            "Next Tab",
            true,
            Some(Accelerator::new(
                Some(cmd_or_ctrl_shift),
                Code::BracketRight,
            )),
        );
        action_map.insert(next_tab.id().clone(), MenuAction::NextTab);
        tab_menu.append(&next_tab)?;

        let prev_tab = MenuItem::with_id(
            "prev_tab",
            "Previous Tab",
            true,
            Some(Accelerator::new(Some(cmd_or_ctrl_shift), Code::BracketLeft)),
        );
        action_map.insert(prev_tab.id().clone(), MenuAction::PreviousTab);
        tab_menu.append(&prev_tab)?;

        tab_menu.append(&PredefinedMenuItem::separator())?;

        // Tab 1-9 shortcuts: Cmd+N (macOS) / Alt+N (Windows/Linux)
        for i in 1..=9 {
            let code = match i {
                1 => Code::Digit1,
                2 => Code::Digit2,
                3 => Code::Digit3,
                4 => Code::Digit4,
                5 => Code::Digit5,
                6 => Code::Digit6,
                7 => Code::Digit7,
                8 => Code::Digit8,
                9 => Code::Digit9,
                _ => unreachable!(),
            };
            let tab_item = MenuItem::with_id(
                format!("tab_{}", i),
                format!("Tab {}", i),
                true,
                Some(Accelerator::new(Some(tab_switch_mod), code)),
            );
            action_map.insert(tab_item.id().clone(), MenuAction::SwitchToTab(i));
            tab_menu.append(&tab_item)?;
        }

        menu.append(&tab_menu)?;

        // Profiles menu
        let profiles_menu = Submenu::new("Profiles", true);

        let manage_profiles = MenuItem::with_id(
            "manage_profiles",
            "Manage Profiles...",
            true,
            Some(Accelerator::new(Some(cmd_or_ctrl_shift), Code::KeyP)),
        );
        action_map.insert(manage_profiles.id().clone(), MenuAction::ManageProfiles);
        profiles_menu.append(&manage_profiles)?;

        let toggle_drawer = MenuItem::with_id(
            "toggle_profile_drawer",
            "Toggle Profile Drawer",
            true,
            None, // Same shortcut as manage for now, or use different
        );
        action_map.insert(toggle_drawer.id().clone(), MenuAction::ToggleProfileDrawer);
        profiles_menu.append(&toggle_drawer)?;

        profiles_menu.append(&PredefinedMenuItem::separator())?;

        // Dynamic profile menu items will be added via update_profiles()

        menu.append(&profiles_menu)?;

        // Store reference to profiles submenu for dynamic updates
        let profiles_submenu = profiles_menu;

        // Edit menu
        let edit_menu = Submenu::new("Edit", true);

        // Copy/Paste/Select All: Cmd+C/V/A (macOS) / Ctrl+Shift+C/V/A (other)
        let copy = MenuItem::with_id(
            "copy",
            "Copy",
            true,
            Some(Accelerator::new(Some(cmd_or_ctrl), Code::KeyC)),
        );
        action_map.insert(copy.id().clone(), MenuAction::Copy);
        edit_menu.append(&copy)?;

        let paste = MenuItem::with_id(
            "paste",
            "Paste",
            true,
            Some(Accelerator::new(Some(cmd_or_ctrl), Code::KeyV)),
        );
        action_map.insert(paste.id().clone(), MenuAction::Paste);
        edit_menu.append(&paste)?;

        let select_all = MenuItem::with_id(
            "select_all",
            "Select All",
            true,
            Some(Accelerator::new(Some(cmd_or_ctrl), Code::KeyA)),
        );
        action_map.insert(select_all.id().clone(), MenuAction::SelectAll);
        edit_menu.append(&select_all)?;

        edit_menu.append(&PredefinedMenuItem::separator())?;

        let clear_scrollback = MenuItem::with_id(
            "clear_scrollback",
            "Clear Scrollback",
            true,
            Some(Accelerator::new(Some(cmd_or_ctrl_shift), Code::KeyK)),
        );
        action_map.insert(clear_scrollback.id().clone(), MenuAction::ClearScrollback);
        edit_menu.append(&clear_scrollback)?;

        let clipboard_history = MenuItem::with_id(
            "clipboard_history",
            "Clipboard History",
            true,
            Some(Accelerator::new(Some(cmd_or_ctrl_shift), Code::KeyH)),
        );
        action_map.insert(clipboard_history.id().clone(), MenuAction::ClipboardHistory);
        edit_menu.append(&clipboard_history)?;

        // Windows/Linux: Add Preferences to Edit menu (standard location on these platforms)
        #[cfg(not(target_os = "macos"))]
        {
            edit_menu.append(&PredefinedMenuItem::separator())?;

            let preferences = MenuItem::with_id(
                "preferences",
                "Preferences...",
                true,
                Some(Accelerator::new(
                    Some(Modifiers::CONTROL | Modifiers::SHIFT),
                    Code::Comma,
                )),
            );
            action_map.insert(preferences.id().clone(), MenuAction::OpenSettings);
            edit_menu.append(&preferences)?;
        }

        menu.append(&edit_menu)?;

        // View menu
        let view_menu = Submenu::new("View", true);

        let toggle_fullscreen = MenuItem::with_id(
            "toggle_fullscreen",
            "Toggle Fullscreen",
            true,
            Some(Accelerator::new(None, Code::F11)),
        );
        action_map.insert(toggle_fullscreen.id().clone(), MenuAction::ToggleFullscreen);
        view_menu.append(&toggle_fullscreen)?;

        let maximize_vertically = MenuItem::with_id(
            "maximize_vertically",
            "Maximize Vertically",
            true,
            Some(Accelerator::new(Some(Modifiers::SHIFT), Code::F11)),
        );
        action_map.insert(
            maximize_vertically.id().clone(),
            MenuAction::MaximizeVertically,
        );
        view_menu.append(&maximize_vertically)?;

        view_menu.append(&PredefinedMenuItem::separator())?;

        let increase_font = MenuItem::with_id(
            "increase_font",
            "Increase Font Size",
            true,
            Some(Accelerator::new(Some(cmd_or_ctrl), Code::Equal)),
        );
        action_map.insert(increase_font.id().clone(), MenuAction::IncreaseFontSize);
        view_menu.append(&increase_font)?;

        let decrease_font = MenuItem::with_id(
            "decrease_font",
            "Decrease Font Size",
            true,
            Some(Accelerator::new(Some(cmd_or_ctrl), Code::Minus)),
        );
        action_map.insert(decrease_font.id().clone(), MenuAction::DecreaseFontSize);
        view_menu.append(&decrease_font)?;

        let reset_font = MenuItem::with_id(
            "reset_font",
            "Reset Font Size",
            true,
            Some(Accelerator::new(Some(cmd_or_ctrl), Code::Digit0)),
        );
        action_map.insert(reset_font.id().clone(), MenuAction::ResetFontSize);
        view_menu.append(&reset_font)?;

        view_menu.append(&PredefinedMenuItem::separator())?;

        let fps_overlay = MenuItem::with_id(
            "fps_overlay",
            "FPS Overlay",
            true,
            Some(Accelerator::new(None, Code::F3)),
        );
        action_map.insert(fps_overlay.id().clone(), MenuAction::ToggleFpsOverlay);
        view_menu.append(&fps_overlay)?;

        let settings = MenuItem::with_id(
            "settings",
            "Settings...",
            true,
            Some(Accelerator::new(None, Code::F12)),
        );
        action_map.insert(settings.id().clone(), MenuAction::OpenSettings);
        view_menu.append(&settings)?;

        view_menu.append(&PredefinedMenuItem::separator())?;

        let save_arrangement =
            MenuItem::with_id("save_arrangement", "Save Window Arrangement...", true, None);
        action_map.insert(save_arrangement.id().clone(), MenuAction::SaveArrangement);
        view_menu.append(&save_arrangement)?;

        menu.append(&view_menu)?;

        // Shell menu
        let shell_menu = Submenu::new("Shell", true);

        let install_remote_integration = MenuItem::with_id(
            "install_remote_shell_integration",
            "Install Shell Integration on Remote Host...",
            true,
            None,
        );
        action_map.insert(
            install_remote_integration.id().clone(),
            MenuAction::InstallShellIntegrationRemote,
        );
        shell_menu.append(&install_remote_integration)?;

        menu.append(&shell_menu)?;

        // Window menu (primarily for macOS)
        #[cfg(target_os = "macos")]
        macos::build_window_menu(&menu, &mut action_map)?;

        // Help menu
        let help_menu = Submenu::new("Help", true);

        let keyboard_shortcuts = MenuItem::with_id(
            "keyboard_shortcuts",
            "Keyboard Shortcuts",
            true,
            Some(Accelerator::new(None, Code::F1)),
        );
        action_map.insert(keyboard_shortcuts.id().clone(), MenuAction::ShowHelp);
        help_menu.append(&keyboard_shortcuts)?;

        help_menu.append(&PredefinedMenuItem::separator())?;

        let about = MenuItem::with_id("about", "About par-term", true, None);
        action_map.insert(about.id().clone(), MenuAction::About);
        help_menu.append(&about)?;

        menu.append(&help_menu)?;

        Ok(Self {
            menu,
            action_map,
            profiles_submenu,
            profile_menu_items: Vec::new(),
        })
    }

    /// Initialize the global menu system (macOS only).
    ///
    /// On macOS this attaches the menu to NSApp (the global application object),
    /// replacing winit's default menu. This should be called as early as possible
    /// — before any blocking GPU initialization — so that our custom accelerators
    /// (Cmd+, for Settings, Cmd+Q for graceful Quit) are active immediately.
    ///
    /// On other platforms this is a no-op; use [`init_for_window`] to attach
    /// per-window menu bars.
    pub fn init_global(&self) -> Result<()> {
        #[cfg(target_os = "macos")]
        {
            macos::init_for_nsapp(&self.menu)
        }
        #[cfg(not(target_os = "macos"))]
        {
            Ok(())
        }
    }

    /// Initialize the menu for a window
    ///
    /// On macOS, this initializes the global application menu (only needs to be called once).
    /// On Windows/Linux, this attaches a menu bar to the specific window.
    #[allow(unused_variables)] // window is only used on Windows/Linux
    pub fn init_for_window(&self, window: &Arc<Window>) -> Result<()> {
        #[cfg(target_os = "macos")]
        {
            macos::init_for_nsapp(&self.menu)
        }

        #[cfg(target_os = "windows")]
        {
            use winit::raw_window_handle::{HasWindowHandle, RawWindowHandle};
            if let Ok(handle) = window.window_handle()
                && let RawWindowHandle::Win32(win32_handle) = handle.as_raw()
            {
                // SAFETY: We have a valid Win32 window handle from winit
                unsafe {
                    self.menu.init_for_hwnd(win32_handle.hwnd.get() as _)?;
                }
                log::info!("Initialized Windows menu bar for window");
            }
            return Ok(());
        }

        #[cfg(any(
            target_os = "linux",
            target_os = "dragonfly",
            target_os = "freebsd",
            target_os = "netbsd",
            target_os = "openbsd"
        ))]
        {
            return linux::init_for_window(window);
        }

        #[cfg(not(any(
            target_os = "macos",
            target_os = "windows",
            target_os = "linux",
            target_os = "dragonfly",
            target_os = "freebsd",
            target_os = "netbsd",
            target_os = "openbsd"
        )))]
        {
            log::warn!("Menu bar not supported on this platform");
            Ok(())
        }
    }

    /// Poll for menu events and return any triggered actions
    pub fn poll_events(&self) -> impl Iterator<Item = MenuAction> + '_ {
        std::iter::from_fn(|| {
            // Use try_recv to get events without blocking
            match MenuEvent::receiver().try_recv() {
                Ok(event) => self.action_map.get(&event.id).copied(),
                Err(_) => None,
            }
        })
    }

    /// Update the profiles submenu with the current list of profiles
    ///
    /// This should be called whenever profiles are loaded or modified.
    pub fn update_profiles(&mut self, profiles: &[&Profile]) {
        // Remove existing profile menu items
        for item in self.profile_menu_items.drain(..) {
            // Remove from action_map
            self.action_map.remove(item.id());
            // Remove from submenu
            let _ = self.profiles_submenu.remove(&item);
        }

        // Add new profile menu items in order
        for profile in profiles {
            let menu_id = format!("profile_{}", profile.id);
            let label = profile.display_label();

            let item = MenuItem::with_id(menu_id, &label, true, None);

            // Map to OpenProfile action
            self.action_map
                .insert(item.id().clone(), MenuAction::OpenProfile(profile.id));

            // Add to submenu
            if let Err(e) = self.profiles_submenu.append(&item) {
                log::warn!("Failed to add profile menu item '{}': {}", label, e);
                continue;
            }

            // Track for later removal
            self.profile_menu_items.push(item);
        }

        log::info!("Updated profiles menu with {} items", profiles.len());
    }

    /// Update profiles from a ProfileManager (convenience method)
    pub fn update_profiles_from_manager(&mut self, manager: &crate::profile::ProfileManager) {
        let profiles: Vec<&Profile> = manager.profiles_ordered();
        self.update_profiles(&profiles);
    }
}