neovide 0.17.4

Neovide: No Nonsense Neovim Gui
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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
pub mod feature;
mod switcher;
mod tab_navigation;

use std::cell::RefCell;
use std::collections::VecDeque;
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::Arc;

use glamour::Point2;
use objc2::rc::Retained;
use objc2_app_kit::NSWindow;
use objc2_foundation::NSArray;
use winit::dpi::LogicalSize;
use winit::event::WindowEvent;
use winit::platform::macos;
use winit::platform::macos::WindowExtMacOS;
use winit::window::Window;
use winit::window::WindowId;

use self::feature::MacosWindowFeature;
use self::feature::TouchpadStage;
use self::feature::scrollbar::ScrollbarLayoutInput;
use self::switcher::EditorSwitcherRow;
use self::switcher::close_editor_switcher_if_open;
use self::switcher::editor_switcher_key_event_matches;
use self::switcher::show_editor_switcher_panel;
use self::tab_navigation::TabNavigationAction;
use self::tab_navigation::TabNavigationHotkeys;
use super::Route;
use super::RouteWindow;
use super::ShortcutHandling;
use super::WindowPadding;
use super::WindowSettingsChanged;
use super::WinitWindowWrapper;
use crate::CmdLineSettings;
use crate::bridge::NeovimHandler;
use crate::bridge::OpenArgs;
use crate::error_msg;
use crate::renderer::Renderer;
use crate::renderer::rendered_window::BASE_GRID_ID;
use crate::renderer::rendered_window::NO_MULTIGRID_GRID_ID;
use crate::settings::Settings;
use crate::units::GridPos;
use crate::units::Pixel;
use crate::units::PixelPos;
use crate::units::PixelRect;
use crate::units::PixelSize;
use crate::window::ForceClickKind;
use crate::window::MacShortcutCommand;
use crate::window::application::platform::hide_application;
use crate::window::macos::appkit::get_ns_window;
use crate::window::macos::system_tabs::system_tab_bar_enabled;
use crate::window::settings::platform::OptionAsMeta;

/// Host geometry captured before a new AppKit tab joins its chosen window.
///
/// The route asks its chosen host for this snapshot only when system tabs
/// are requested for a full or transparent frame outside native fullscreen.
/// It passes both sizes to the new window before AppKit can resize the host
/// while adding that window to the tab group and attaching its tab bar.
///
/// `outer` is the host frame size in AppKit points. For an inline tab, the
/// feature applies it to the new window before attachment and preserves its
/// frame top edge, so the new tab starts at the same size as its host window.
///
/// `content_height` comes from `contentRectForFrameRect`. For a full frame,
/// AppKit can enlarge the content area when the tab toolbar appears, so the
/// host height remains pending until the actual `NSTabBar` attaches to the
/// new window. The tab owner then restores every group member to that host
/// height and clears the target, leaving later tab switches and resizes alone.
///
/// Transparent frames use `outer` but do not restore `content_height` because
/// their grid inset depends on the live tab bar geometry. A new fullscreen
/// window receives no snapshot, and simple fullscreen ignores one if present.
#[derive(Clone, Copy)]
pub struct HostTabSize {
    pub outer: LogicalSize<f64>,
    pub content_height: f64,
}

/// The chosen AppKit host for a new system tab, held across window creation.
///
/// `MacosWindowFeature::host_tab_for_new_window` captures the host before winit
/// creates the new window. The retained `NSWindow` keeps its identity available
/// while the new feature tries to attach only its own window to that tab group.
///
/// The route discards this host when the new window will start fullscreen. For
/// full or transparent frames outside system fullscreen, `size` holds the host
/// geometry. A system fullscreen host still supplies its window without a size.
pub struct HostTab {
    pub window: Retained<NSWindow>,
    pub size: Option<HostTabSize>,
}

/// Neovide windows share a tabbing identifier, even after detachment. Match
/// the NSWindow in the captured member list to find its actual tab group.
fn tab_group_contains_window(members: &NSArray<NSWindow>, window: &NSWindow) -> bool {
    members.iter().any(|member| std::ptr::eq::<NSWindow>(&*member, window))
}

impl HostTabSize {
    fn from_ns_window(window: &NSWindow) -> Self {
        let frame = window.frame();
        let content = window.contentRectForFrameRect(frame);
        Self {
            outer: LogicalSize::new(frame.size.width, frame.size.height),
            content_height: content.size.height,
        }
    }
}

pub fn create_window_feature(
    window: &Rc<Window>,
    settings: Arc<Settings>,
    handler: NeovimHandler,
    renderer: &Rc<RefCell<Box<Renderer>>>,
    creating_initial_window: bool,
    host_tab: Option<HostTab>,
) -> MacosWindowFeature {
    let mut feat = MacosWindowFeature::from_winit_window(window, settings, handler, host_tab);
    feat.apply_scrollbar_snapshot(&renderer.borrow());
    if creating_initial_window {
        feat.activate_and_focus();
    }
    feat
}

pub struct WindowNavigationState {
    pub window_mru: VecDeque<WindowId>,
    pub focus_return_target: Option<WindowId>,
    ignore_next_focus_gain: bool,
    tab_navigation_hotkeys: TabNavigationHotkeys,
}

impl WindowNavigationState {
    pub fn new(settings: &Settings) -> Self {
        Self {
            window_mru: VecDeque::new(),
            focus_return_target: None,
            ignore_next_focus_gain: false,
            tab_navigation_hotkeys: TabNavigationHotkeys::new(settings),
        }
    }
}

impl WinitWindowWrapper {
    pub fn handle_platform_window_settings_changed(
        &mut self,
        window_ids: &[WindowId],
        changed_setting: WindowSettingsChanged,
    ) {
        match changed_setting {
            WindowSettingsChanged::InputMacosOptionKeyIsMeta(option) => {
                for window_id in window_ids {
                    self.set_macos_option_as_meta(*window_id, option);
                }
            }
            WindowSettingsChanged::InputMacosAltIsMeta(true) => {
                error_msg!(concat!(
                    "neovide_input_macos_alt_is_meta has now been removed. ",
                    "Use neovide_input_macos_option_key_is_meta instead. ",
                    "Please check https://neovide.dev/configuration.html#macos-option-key-is-meta for more information.",
                ));
            }
            WindowSettingsChanged::MacosSimpleFullscreen(fullscreen) => {
                for window_id in window_ids {
                    self.set_simple_fullscreen(*window_id, fullscreen);
                }
            }
            WindowSettingsChanged::SystemScrollbar(_) => {
                for window_id in window_ids {
                    if let Some(route) = self.routes.get(window_id) {
                        let renderer = route.window.renderer.borrow();
                        route.window.with_macos_feature_mut(|feature| {
                            feature.apply_scrollbar_snapshot(&renderer);
                        });
                    }
                }
            }
            WindowSettingsChanged::Opacity(_) | WindowSettingsChanged::NormalOpacity(_) => {
                for window_id in window_ids {
                    if let Some(route) = self.routes.get(window_id) {
                        let renderer = route.window.renderer.borrow();
                        route.window.with_macos_feature_mut(|feature| {
                            feature.refresh_scrollbar_colors(&renderer);
                        });
                    }
                }
            }
            _ => {}
        }

        for window_id in window_ids {
            if let Some(feature) = self.macos_feature_for_window(*window_id) {
                feature.borrow_mut().handle_settings_changed(changed_setting.clone());
            }
        }
    }

    pub fn handle_touchpad_pressure_command(
        &mut self,
        window_id: WindowId,
        col: i64,
        row: i64,
        entity: String,
        guifont: String,
        kind: ForceClickKind,
    ) {
        let Some(feature) = self.macos_feature_for_window(window_id) else {
            log::warn!("Touchpad pressure received before macOS feature initialization");
            return;
        };

        let titlebar_height = feature.borrow().system_titlebar_height as f32;
        let window_padding = self.calculate_window_padding(window_id);
        let pixel_position = self.grid_to_pixel_position(window_id, col, row);
        let Some(grid_scale_height) = self.routes.get(&window_id).map(|route| {
            let renderer = route.window.renderer.borrow();
            renderer.grid_renderer.grid_scale.height()
        }) else {
            return;
        };
        let point = self.apply_padding_to_position(pixel_position, window_padding, titlebar_height);

        feature.borrow_mut().handle_force_click_target(
            &entity,
            kind,
            point,
            guifont,
            grid_scale_height,
        );
    }

    pub fn handle_highlight_matching_pair_command(
        &self,
        window_id: WindowId,
        grid: u64,
        row: u64,
        column: u64,
        text: Option<String>,
    ) {
        let target_grid = if grid == NO_MULTIGRID_GRID_ID { BASE_GRID_ID } else { grid };
        let Some(route) = self.routes.get(&window_id) else {
            return;
        };

        let rect = {
            let renderer = route.window.renderer.borrow();
            let grid_scale = renderer.grid_renderer.grid_scale;
            let cell_size = PixelSize::new(grid_scale.width(), grid_scale.height());
            let grid_pos = GridPos::new(column as f32, row as f32);
            renderer.rendered_windows.get(&target_grid).map(|window| {
                let mut adjusted_grid = grid_pos + window.grid_current_position.to_vector();
                adjusted_grid.y -= window.scroll_animation.position;
                let origin = adjusted_grid * grid_scale;
                PixelRect::from_origin_and_size(origin, cell_size)
            })
        };

        if let (Some(rect), Some(feature)) = (rect, self.macos_feature_for_window(window_id)) {
            feature.borrow_mut().show_find_indicator_for_rect(rect, text.as_deref());
        }
    }

    pub fn handle_platform_shortcuts(
        &mut self,
        window_id: WindowId,
        event: &WindowEvent,
    ) -> ShortcutHandling {
        if let WindowEvent::KeyboardInput { event: key_event, is_synthetic: false, .. } = event {
            let modifiers = self.keyboard_manager.current_modifiers();
            if editor_switcher_key_event_matches(key_event, &modifiers) {
                self.show_editor_switcher();
                return ShortcutHandling { overlay_consumed: true, ..Default::default() };
            }
        }

        if system_tab_bar_enabled()
            && let WindowEvent::KeyboardInput { event: key_event, .. } = event
        {
            let modifiers = self.keyboard_manager.current_modifiers();
            if let Some(action) =
                self.window_navigation.tab_navigation_hotkeys.action_for(key_event, &modifiers)
                && let Some(route) = self.routes.get(&window_id)
                && let Some(feature) = &route.window.macos_feature
            {
                let feature_ref = feature.borrow();
                if feature_ref.can_navigate_tabs() {
                    match action {
                        TabNavigationAction::Next => feature_ref.select_next_tab(),
                        TabNavigationAction::Previous => feature_ref.select_previous_tab(),
                    }
                    return ShortcutHandling { keyboard_consumed: true, ..Default::default() };
                }
            }
        }

        ShortcutHandling::default()
    }

    pub fn handle_mac_shortcut(&mut self, command: MacShortcutCommand) {
        match command {
            MacShortcutCommand::TogglePinnedWindow => self.toggle_pinned_window(),
            MacShortcutCommand::ShowEditorSwitcher => self.show_editor_switcher(),
        }
    }

    pub fn record_window_usage(&mut self, window_id: WindowId) {
        self.window_navigation.window_mru.retain(|id| *id != window_id);
        self.window_navigation.window_mru.push_front(window_id);
    }

    fn cleanup_window_mru(&mut self) {
        self.window_navigation.window_mru.retain(|id| self.routes.contains_key(id));
    }

    pub fn handle_focus_gain_for_shortcuts(&mut self, window_id: WindowId) {
        if self.window_navigation.ignore_next_focus_gain {
            self.window_navigation.ignore_next_focus_gain = false;
        } else {
            self.record_window_usage(window_id);
        }
    }

    fn pinned_candidate(&mut self) -> Option<WindowId> {
        self.cleanup_window_mru();
        if let Some(id) = self.window_navigation.window_mru.front().copied() {
            Some(id)
        } else {
            self.routes.keys().next().copied()
        }
    }

    fn editor_switcher_rows(&mut self) -> Vec<EditorSwitcherRow> {
        let focused_route = self.get_focused_route();
        self.cleanup_window_mru();

        let mut ordered_windows: Vec<WindowId> =
            self.window_navigation.window_mru.iter().copied().collect();
        for window_id in self.routes.keys().copied() {
            if !ordered_windows.contains(&window_id) {
                ordered_windows.push(window_id);
            }
        }

        ordered_windows
            .into_iter()
            .filter_map(|window_id| {
                let route = self.routes.get(&window_id)?;
                let title = if route.window.title.is_empty() {
                    "Untitled".to_string()
                } else {
                    route.window.title.clone()
                };

                let subtitle = Self::editor_switcher_subtitle(route);

                Some(EditorSwitcherRow {
                    window_id,
                    title,
                    subtitle,
                    modified: route.window.document.modified,
                    is_current: focused_route == Some(window_id),
                })
            })
            .collect()
    }

    fn editor_switcher_subtitle(route: &Route) -> String {
        if !route.window.document.path.is_empty() {
            route.window.document.path.clone()
        } else if let Some(cwd) = &route.cwd {
            cwd.to_string_lossy().into_owned()
        } else {
            String::new()
        }
    }

    fn capture_focus_target(&mut self, pinned_id: WindowId) {
        let current = self.get_focused_route();
        if current != Some(pinned_id) {
            self.window_navigation.focus_return_target = current;
        } else {
            self.window_navigation.focus_return_target = None;
        }
    }

    fn restore_focus_target(&mut self) -> bool {
        let Some(target_id) = self.window_navigation.focus_return_target.take() else {
            return false;
        };

        let Some(window) =
            self.routes.get(&target_id).map(|route| route.window.winit_window.clone())
        else {
            return false;
        };

        if let Some(feature) = self.macos_feature_for_window(target_id) {
            feature.borrow().activate_application();
        }

        window.focus_window();

        true
    }

    fn toggle_pinned_window(&mut self) {
        let Some(window_id) = self.pinned_candidate() else {
            return;
        };

        let Some(route) = self.routes.get(&window_id) else {
            return;
        };

        let window = route.window.winit_window.clone();
        let macos_feature = self.macos_feature_for_window(window_id);
        let is_active = {
            if let Some(feature) = &macos_feature {
                feature.borrow().is_key_window()
            } else {
                window.has_focus()
            }
        };

        self.window_navigation.ignore_next_focus_gain = true;

        if is_active {
            let uses_native_tabs = system_tab_bar_enabled()
                && self.settings.get::<CmdLineSettings>().system_native_tabs;

            if uses_native_tabs {
                hide_application();
                return;
            }

            if !self.restore_focus_target() {
                hide_application();
            }
        } else {
            if let Some(feature) = &macos_feature {
                feature.borrow().activate_application();
            }
            self.capture_focus_target(window_id);
            window.focus_window();
            self.record_window_usage(window_id);
        }
    }

    fn show_editor_switcher(&mut self) {
        if self.routes.is_empty() {
            return;
        }

        if close_editor_switcher_if_open() {
            return;
        }

        let rows = self.editor_switcher_rows();
        let icon = self.settings.get::<CmdLineSettings>().icon;
        show_editor_switcher_panel(rows, icon.as_ref());
    }
}

#[derive(Default)]
pub struct RouteLaunchConfig {
    neovim_bin: Option<String>,
    neovim_args: Option<Vec<String>>,
}

#[derive(Default)]
pub struct DocumentState {
    pub path: String,
    pub modified: bool,
}

impl RouteLaunchConfig {
    fn from_open_args(args: &OpenArgs) -> Self {
        Self { neovim_bin: args.neovim_bin.clone(), neovim_args: args.neovim_args.clone() }
    }

    fn from_cmdline(cmdline: CmdLineSettings) -> Self {
        Self {
            neovim_bin: cmdline.neovim_bin,
            neovim_args: (!cmdline.neovim_args.is_empty()).then_some(cmdline.neovim_args),
        }
    }
}

impl RouteWindow {
    pub fn handle_touchpad_pressure(&self, stage: i64) {
        if let Some(feature) = &self.macos_feature {
            match TouchpadStage::from_stage(stage) {
                TouchpadStage::Soft | TouchpadStage::Click => {
                    feature.borrow_mut().set_definition_is_active(false)
                }
                TouchpadStage::ForceClick => feature.borrow_mut().handle_touchpad_force_click(),
            }
        }
    }

    pub fn with_macos_feature<R>(&self, read: impl FnOnce(&MacosWindowFeature) -> R) -> Option<R> {
        let feature = self.macos_feature.as_ref()?;

        Some(read(feature.borrow().as_ref()))
    }

    pub fn with_macos_feature_mut<R>(
        &self,
        update: impl FnOnce(&mut MacosWindowFeature) -> R,
    ) -> Option<R> {
        let feature = self.macos_feature.as_ref()?;

        Some(update(feature.borrow_mut().as_mut()))
    }
}

impl WinitWindowWrapper {
    pub fn route_launch_config_for_window_creation(
        &self,
        args: Option<&OpenArgs>,
        creating_initial_window: bool,
    ) -> RouteLaunchConfig {
        if let Some(args) = args {
            return RouteLaunchConfig::from_open_args(args);
        }

        if !creating_initial_window {
            return RouteLaunchConfig::default();
        }

        RouteLaunchConfig::from_cmdline(self.settings.get::<CmdLineSettings>())
    }

    pub fn set_macos_option_as_meta(&mut self, window_id: WindowId, option: OptionAsMeta) {
        let winit_option = match option {
            OptionAsMeta::OnlyLeft => macos::OptionAsAlt::OnlyLeft,
            OptionAsMeta::OnlyRight => macos::OptionAsAlt::OnlyRight,
            OptionAsMeta::Both => macos::OptionAsAlt::Both,
            OptionAsMeta::None => macos::OptionAsAlt::None,
        };

        let Some(route) = self.routes.get(&window_id) else {
            return;
        };
        let window = route.window.winit_window.clone();
        if winit_option != window.option_as_alt() {
            window.set_option_as_alt(winit_option);
        }
    }

    pub fn set_simple_fullscreen(&mut self, window_id: WindowId, fullscreen: bool) {
        let Some(route) = self.routes.get(&window_id) else {
            return;
        };

        let window = route.window.winit_window.clone();
        if fullscreen && window.fullscreen().is_some() {
            return;
        }

        let Some(feature) = &route.window.macos_feature else {
            window.set_simple_fullscreen(fullscreen);
            return;
        };

        if fullscreen {
            feature.borrow_mut().set_simple_fullscreen_mode(true);
            window.set_simple_fullscreen(true);
        } else {
            window.set_simple_fullscreen(false);
            feature.borrow_mut().set_simple_fullscreen_mode(false);
        }
    }

    pub fn apply_document_state(&self, window_id: WindowId) {
        let Some(route) = self.routes.get(&window_id) else {
            return;
        };

        let Some(feature) = self.macos_feature_for_window(window_id) else {
            return;
        };

        feature
            .borrow()
            .set_document_state(&route.window.document.path, route.window.document.modified);
    }

    pub fn sync_native_tabs_resize(&mut self, source_window_id: WindowId) {
        if !system_tab_bar_enabled() || !self.settings.get::<CmdLineSettings>().system_native_tabs {
            return;
        }

        if self.routes.len() <= 1 {
            return;
        }

        let Some(source_route) = self.routes.get(&source_window_id) else {
            return;
        };

        let source_window = get_ns_window(&source_route.window.winit_window);
        let Some(group) = source_window.tabGroup() else { return };
        let members = group.windows();
        if members.len() < 2 {
            return;
        }

        let shared_inner_size = source_route.window.winit_window.inner_size();
        let window_ids: Vec<WindowId> = self
            .routes
            .iter()
            .filter_map(|(id, route)| {
                let window = get_ns_window(&route.window.winit_window);
                tab_group_contains_window(&members, &window).then_some(*id)
            })
            .collect();

        // Only windows in the same AppKit group share a visual surface. A tab
        // detached into another group keeps its own grid size and padding.
        for window_id in window_ids {
            if let Some(route) = self.routes.get_mut(&window_id)
                && let Some(macos_feature) = &mut route.window.macos_feature
            {
                macos_feature.borrow_mut().handle_size_changed();
            }

            let window_padding = self.calculate_window_padding(window_id);
            if let Some(route) = self.routes.get_mut(&window_id) {
                route.state.saved_inner_size = shared_inner_size;
                route.state.window_padding = window_padding;
            }

            self.update_grid_size_from_window(window_id);
        }
    }

    pub fn grid_to_pixel_position(
        &mut self,
        window_id: WindowId,
        col: i64,
        row: i64,
    ) -> Point2<Pixel<f32>> {
        let grid_position = GridPos::new(col, row);
        let mut renderer = {
            let route = self.routes.get(&window_id).expect("window must exist");
            route.window.renderer.borrow_mut()
        };
        let root_region_offset = renderer.window_regions.first().map(|region| region.region.min);

        // Align the lookup point with the actual font baseline instead of a heuristic offset.
        let grid_scale = renderer.grid_renderer.grid_scale;
        let baseline_offset = renderer.grid_renderer.shaper.baseline_offset();
        drop(renderer);

        let mut position = grid_position * grid_scale;

        if let Some(offset) = root_region_offset {
            position.x += offset.x;
            position.y += offset.y;
        }

        position.y += baseline_offset;

        position
    }

    pub fn apply_padding_to_position(
        &self,
        position: Point2<Pixel<f32>>,
        padding: WindowPadding,
        titlebar_height: f32,
    ) -> Point2<Pixel<f32>> {
        let _ = (padding, titlebar_height);
        position
    }

    pub fn focused_route_launch_context(&self) -> Option<(Option<PathBuf>, OpenArgs)> {
        let focused_id = self.get_focused_route()?;
        let route = self.routes.get(&focused_id)?;
        Some((
            route.cwd.clone(),
            OpenArgs {
                files_to_open: vec![],
                tabs: false,
                neovim_bin: route.launch_config.neovim_bin.clone(),
                neovim_args: route.launch_config.neovim_args.clone(),
            },
        ))
    }

    pub fn activate_and_focus_window(&self, window_id: WindowId) -> bool {
        let Some(feature) = self.macos_feature_for_window(window_id) else {
            return false;
        };

        feature.borrow().activate_and_focus();
        true
    }

    /// Decide whether a new macOS window starts its own fullscreen transition.
    ///
    /// `try_create_window` reads the fullscreen setting for every new route. It
    /// calls this after winit creates the new window, but before applying that
    /// setting or passing any captured `HostTab` to the new macOS feature. The
    /// initial window and windows without system tabs keep the requested value.
    ///
    /// When the selected host is already in native fullscreen, the new system
    /// tab can join that group without starting another fullscreen transition.
    /// AppKit can raise `NSWindowStackController` assertions when the new tab
    /// window enters fullscreen during attachment to the existing tab group.
    ///
    /// Returning `false` skips the initial `set_fullscreen` call for this new
    /// window. It also keeps any captured `HostTab` available for the feature
    /// to try joining the existing fullscreen host group. The host remains in
    /// native fullscreen, and the shared fullscreen setting remains unchanged.
    pub fn fullscreen_for_new_window(
        &self,
        creating_initial_window: bool,
        fullscreen: bool,
    ) -> bool {
        if !self.should_handle_tabbed_fullscreen(creating_initial_window, fullscreen) {
            return fullscreen;
        }

        let opening_fullscreen_tab = self
            .get_focused_route()
            .and_then(|window_id| self.macos_feature_for_window(window_id))
            .is_some_and(|feature| feature.borrow().is_native_fullscreen_enabled());

        if opening_fullscreen_tab {
            log::info!("Skipping initial fullscreen for new tab window from fullscreen host");
            return false;
        }

        fullscreen
    }

    fn should_handle_tabbed_fullscreen(
        &self,
        creating_initial_window: bool,
        fullscreen: bool,
    ) -> bool {
        !creating_initial_window
            && fullscreen
            && system_tab_bar_enabled()
            && self.settings.get::<CmdLineSettings>().system_native_tabs
    }

    pub fn macos_feature_for_window(
        &self,
        window_id: WindowId,
    ) -> Option<Rc<RefCell<Box<MacosWindowFeature>>>> {
        self.routes.get(&window_id).and_then(|route| route.window.macos_feature.as_ref().cloned())
    }

    pub fn update_scrollbar_layout_from_window(&self, window_id: WindowId) {
        let Some(route) = self.routes.get(&window_id) else {
            return;
        };

        let window_padding = route.state.window_padding;

        let Some(macos_feature) = self.macos_feature_for_window(window_id) else {
            return;
        };

        let reserved_width = {
            let macos_feature = macos_feature.borrow();
            macos_feature.scrollbar_reserved_width_in_pixels()
        };

        if reserved_width == 0 {
            macos_feature.borrow_mut().set_scrollbar_layout(ScrollbarLayoutInput::default());
            return;
        }

        let content_size = self.content_pixel_size_from_window(window_id);

        // a resize request is not yet drawable state so we keep the track at the
        // committed root edge until neovim acknowledges the new grid size.
        let renderer = route.window.renderer.borrow();
        let grid_scale = renderer.grid_renderer.grid_scale;
        let root_grid_size = renderer
            .scrollbar_snapshot
            .as_ref()
            .and_then(|snapshot| snapshot.root_grid_size)
            .unwrap_or_else(|| renderer.get_grid_size().as_());
        let left_lane_enabled =
            macos_feature.borrow().scrollbar_left_reserved_width_in_pixels() > 0;

        macos_feature.borrow_mut().set_scrollbar_layout(ScrollbarLayoutInput {
            root_grid_size,
            grid_origin: PixelPos::new(
                f64::from(window_padding.left),
                f64::from(window_padding.top),
            ),
            content_size: window_padding.content_size(content_size).as_(),
            cell_size: PixelSize::new(
                f64::from(grid_scale.width()),
                f64::from(grid_scale.height()),
            ),
            left_lane_enabled,
        });
    }
}