paneru 0.4.4

A sliding, tiling window manager for MacOS.
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
use std::sync::mpsc::Receiver;
use std::time::{Duration, Instant};

use bevy::MinimalPlugins;
use bevy::app::App as BevyApp;
use bevy::app::{PostUpdate, PreUpdate, Startup};
use bevy::ecs::hierarchy::ChildOf;
use bevy::ecs::lifecycle::RemovedComponents;
use bevy::ecs::message::Messages;
use bevy::ecs::query::{Added, Changed, With};
use bevy::ecs::resource::Resource;
use bevy::ecs::schedule::common_conditions::{not, resource_exists};
use bevy::ecs::system::{Commands, EntityCommands, Query, Res, SystemId};
use bevy::prelude::Event as BevyEvent;
use bevy::tasks::Task;
use bevy::time::Timer;
use bevy::time::common_conditions::on_timer;
use bevy::time::{Time, Virtual};
use bevy::{
    app::Update,
    ecs::{component::Component, entity::Entity, schedule::IntoScheduleConfigs},
};
use derive_more::{Deref, DerefMut};
use tracing::{Level, instrument};

use crate::commands::register_commands;
use crate::config::{CONFIGURATION_FILE, Config, WindowParams};
use crate::ecs::layout::LayoutStrip;
use crate::ecs::state::PaneruState;
use crate::errors::Result;
use crate::events::{Event, EventSender};
use crate::manager::{
    Application, Origin, ProcessApi, Size, Window, WindowManager, WindowManagerApi, WindowManagerOS,
};
use crate::menubar::MenuBarManager;
use crate::overlay::{FlashMessageManager, OverlayManager};
use crate::platform::{Modifiers, PlatformCallbacks, WinID, WorkspaceId};

pub mod display;
pub mod focus;
pub mod layout;
pub mod mouse;
pub mod params;
pub(crate) mod restore;
pub mod scroll;
pub mod state;
mod systems;
mod triggers;
pub mod workspace;

/// Registers the Bevy systems for the `WindowManager`.
/// This function adds various systems to the `Update` schedule, including event dispatchers,
/// process/application/window lifecycle management, animation, and periodic watchers.
///
/// # Arguments
///
/// * `app` - The Bevy application to register the systems with.
#[allow(clippy::too_many_lines)]
pub fn register_systems(app: &mut bevy::app::App) {
    const LOW_POWER_MODE_CHECK_SEC: u64 = 60;

    let not_swiping = |scrolling: Query<&Scrolling, With<ActiveWorkspaceMarker>>| {
        scrolling
            .iter()
            .next()
            .is_none_or(|marker| !marker.is_user_swiping)
    };
    let dimming_enabled = |config: Option<Res<Config>>| {
        config
            .is_some_and(|config| config.has_dim_inactive_color() || config.border_active_window())
    };
    // The overlay must refresh not just when the active strip's layout changes,
    // but also whenever focus moves — including focus *loss* (e.g. switching to
    // an empty virtual workspace), which otherwise leaves a stale outline.
    // Position changes on the focused window also dirty the overlay so that
    // dragging a floating window moves the highlight with it.
    let overlay_dirty =
        |strip_changed: Query<(), (With<ActiveWorkspaceMarker>, Changed<LayoutStrip>)>,
         focus_gained: Query<(), Added<FocusedMarker>>,
         mut focus_lost: RemovedComponents<FocusedMarker>,
         focused_moved: Query<(), (With<FocusedMarker>, Changed<Position>)>| {
            !strip_changed.is_empty()
                || !focus_gained.is_empty()
                || focus_lost.read().next().is_some()
                || !focused_moved.is_empty()
        };
    let native_tabs_enabled =
        |config: Option<Res<Config>>| config.is_none_or(|config| config.native_tabs_enabled());

    app.add_systems(
        Startup,
        (systems::gather_displays, systems::gather_initial_processes).chain(),
    );
    app.add_systems(
        PreUpdate,
        (systems::window_creation_event, systems::pump_events),
    );
    app.add_systems(
        Update,
        (
            (
                triggers::apply_window_defaults,
                systems::detect_tabbed_windows.run_if(native_tabs_enabled),
                triggers::apply_window_positions,
            )
                .chain(),
            (
                systems::add_existing_process,
                systems::add_existing_application,
                systems::finish_setup,
            )
                .chain()
                .run_if(resource_exists::<Initializing>),
            systems::add_launched_process,
            systems::add_launched_application,
            systems::fresh_marker_cleanup,
            systems::timeout_ticker,
            systems::retry_front_switch,
            systems::update_low_power_state
                .run_if(resource_exists::<LowPowerMode>)
                .run_if(on_timer(Duration::from_secs(LOW_POWER_MODE_CHECK_SEC))),
            (
                systems::window_resized_update_frame,
                systems::window_moved_update_frame,
            )
                .chain()
                .run_if(not_swiping),
            systems::cleanup_on_exit,
            restore::tick_restore_grace,
            state::periodic_state_save.run_if(on_timer(Duration::from_secs(300))),
            state::cleanup_on_exit,
        ),
    );
    app.add_systems(
        PostUpdate,
        (
            (
                systems::animate_entities,
                systems::commit_window_position.run_if(not(resource_exists::<Initializing>)),
                systems::verify_window_position.run_if(not(resource_exists::<Initializing>)),
            )
                .chain(),
            (
                systems::animate_resize_entities,
                systems::commit_window_size.run_if(not(resource_exists::<Initializing>)),
            )
                .chain(),
            (
                systems::update_overlays
                    .after(systems::animate_entities)
                    .after(systems::animate_resize_entities)
                    .run_if(dimming_enabled)
                    .run_if(overlay_dirty),
                systems::update_flash_messages,
            )
                .chain(),
            crate::menubar::update_menu_bar,
        ),
    );
}

/// Registers all the event triggers for the window manager.
pub fn register_triggers(app: &mut bevy::app::App) {
    app.add_systems(
        Update,
        (
            triggers::front_switched_trigger,
            triggers::window_focused_trigger,
            triggers::mission_control_trigger,
            triggers::application_event_trigger,
            triggers::dispatch_application_messages,
            triggers::window_destroyed_trigger,
            triggers::refresh_configuration_trigger,
            triggers::theme_change_trigger,
            triggers::window_resize_verifier,
        ),
    );
    app.add_observer(triggers::window_unmanaged_trigger)
        .add_observer(triggers::window_managed_trigger)
        .add_observer(triggers::window_minimized_trigger)
        .add_observer(triggers::spawn_window_trigger)
        .add_observer(triggers::send_message_trigger)
        .add_observer(triggers::window_removal_trigger)
        .add_observer(triggers::cleanup_timeout_trigger)
        .add_observer(restore::restore_window_state);
}

/// Marker component for the currently focused window.
#[derive(Component)]
pub struct FocusedMarker;

#[derive(Component)]
pub struct ActiveWorkspaceMarker;

#[derive(Component)]
pub struct SelectedVirtualMarker;

#[derive(Component)]
pub struct FlashMessage(pub String);

/// Marker component for the currently active display.
#[derive(Component)]
pub struct ActiveDisplayMarker;

/// Marker component signifying a freshly created process, application, or window.
#[derive(Component)]
pub struct FreshMarker;

/// Marker component used to gather existing processes and windows during initialization.
#[derive(Component)]
pub struct ExistingMarker;

/// Component representing a request to reposition a window.
#[derive(Component, Debug, Deref, DerefMut)]
pub struct RepositionMarker(pub Origin);

/// Component representing a request to resize a window.
#[derive(Component, Debug, Deref, DerefMut)]
pub struct ResizeMarker(pub Size);

/// Marker component indicating that windows around the marked entity need to be reshuffled.
#[derive(Component)]
pub struct ReshuffleAroundMarker;

/// Marker component requesting that the strip scroll *minimally* to keep the
/// entity's NEW layout position inside the viewport. Unlike
/// [`ReshuffleAroundMarker`], this does not anchor the entity to its old visual
/// position — if the new layout slot is already on-screen, the strip is left
/// alone and the entity is free to slide there. Only when the new slot would
/// fall off the edge does the strip scroll just enough to expose it.
#[derive(Component)]
pub struct EnsureVisibleMarker;

#[derive(Component, Debug)]
pub struct Scrolling {
    pub velocity: f64,
    pub position: f64,
    /// When true, the user's fingers are on the trackpad.
    pub is_user_swiping: bool,
    /// Last time a physical swipe event was received.
    pub last_event: Instant,
}

impl Default for Scrolling {
    fn default() -> Self {
        Self {
            velocity: 0.0,
            position: 0.0,
            is_user_swiping: false,
            last_event: Instant::now(),
        }
    }
}

#[derive(Component, Clone, Debug, Default, Deref, DerefMut)]
pub struct LayoutPosition(pub Origin);

#[derive(Component, Clone, Debug, Deref, DerefMut)]
pub struct Position(pub Origin);

#[derive(Component, Clone, Debug, Deref, DerefMut)]
pub struct Bounds(pub Size);

#[derive(Component, Clone, Debug, Deref, DerefMut)]
pub struct WidthRatio(pub f64);

/// Marks a window entity that is currently on a native macOS fullscreen space.
/// The window has been removed from its tiled position in the strip.
/// `order` gives the sequence in which windows went fullscreen (0, 1, 2, …)
/// so they can be navigated left-to-right in that order after the tiled strip.
#[derive(Clone, Component, Debug)]
pub struct NativeFullscreenMarker {
    pub layout_strip: Entity,
    pub workspace_id: WorkspaceId,
    pub index: usize,
}

#[derive(Component)]
pub struct FullWidthMarker {
    pub width_ratio: f64,
}

/// Enum component indicating the unmanaged state of a window.
#[derive(Component, Debug)]
pub enum Unmanaged {
    /// The window is floating and not part of the tiling layout.
    Floating,
    /// The window is minimized.
    Minimized,
    /// The window is hidden.
    Hidden,
}

#[derive(Clone, Component, Copy, Debug)]
pub struct PreviousManagedStrip {
    pub workspace_id: WorkspaceId,
    pub virtual_index: u32,
    pub index: usize,
}

/// Wrapper component for a `ProcessApi` trait object, enabling dynamic dispatch for process-related operations within Bevy.
#[derive(Component, Deref, DerefMut)]
pub struct BProcess(pub Box<dyn ProcessApi>);

/// Component to manage a timeout, often used for delaying actions or retries.
#[derive(Component)]
pub struct Timeout {
    /// The Bevy timer instance.
    pub timer: Timer,
    /// An optional system to execute on timeout.
    pub system_id: Option<SystemId>,
}

impl Timeout {
    /// Creates a new `Timeout` with a specified duration and an optional message.
    /// The timer is set to run once.
    ///
    /// # Arguments
    ///
    /// * `duration` - The `Duration` for the timeout.
    /// * `message` - An `Option<String>` containing a message to associate with the timeout.
    ///
    /// # Returns
    ///
    /// A new `Timeout` instance.
    pub fn new(duration: Duration, message: Option<String>, commands: &mut Commands) -> Self {
        let timer = Timer::from_seconds(duration.as_secs_f32(), bevy::time::TimerMode::Once);
        if let Some(message) = message {
            let callback = move || {
                tracing::debug!("{message}");
            };
            let system_id = Some(commands.register_system(callback));

            Self { timer, system_id }
        } else {
            Self {
                timer,
                system_id: None,
            }
        }
    }

    /// Creates an action timeout, which oneshots a provided system id.
    pub fn callback(duration: Duration, system_id: SystemId, commands: &mut Commands) {
        let timer = Timer::from_seconds(duration.as_secs_f32(), bevy::time::TimerMode::Once);
        commands.spawn(Self {
            timer,
            system_id: Some(system_id),
        });
    }
}

/// Component used as a retry mechanism for stray focus events that arrive before the target window is fully created.
#[derive(Component)]
pub struct StrayFocusEvent(pub WinID);

/// Component used as a retry mechanism when `focused_window_id()` fails during
/// an `ApplicationFrontSwitched` event (e.g. transient `kAXErrorCannotComplete`).
#[derive(Component)]
pub struct RetryFrontSwitch(pub Entity);

#[derive(Component)]
pub struct BruteforceWindows(Task<Vec<Window>>);

#[derive(Component, Debug)]
pub enum DockPosition {
    Bottom(i32),
    Left(i32),
    Right(i32),
    Hidden,
}

#[derive(Component)]
pub struct RefreshWindowSizes(pub Instant);

impl Default for RefreshWindowSizes {
    fn default() -> Self {
        Self(Instant::now())
    }
}

impl RefreshWindowSizes {
    pub fn ready(&self) -> bool {
        const REFRESH_WINDOW_SIZE_DELAY_SEC: u64 = 5;
        self.0.elapsed() > Duration::from_secs(REFRESH_WINDOW_SIZE_DELAY_SEC)
    }
}

#[derive(Component)]
pub struct VerifyWindowPosition {
    remaining: u8,
}

impl Default for VerifyWindowPosition {
    fn default() -> Self {
        Self { remaining: 3 }
    }
}

impl VerifyWindowPosition {
    pub fn tick(&mut self) -> bool {
        self.remaining = self.remaining.saturating_sub(1);
        self.remaining == 0
    }
}

#[derive(Deref, DerefMut, Resource)]
pub struct LowPowerMode(pub bool);

#[derive(Resource)]
pub struct SystemTheme {
    pub is_dark: bool,
}

/// Resource to control whether window reshuffling should be skipped.
#[derive(Resource)]
pub struct SkipReshuffle(pub bool);

/// Component marking a deferred reshuffle while the mouse button is held down.
/// Spawned with a `Timeout` so it auto-despawns if the mouse-up event is lost.
#[derive(Component)]
pub struct MouseHeldMarker(pub Entity);

/// Resource indicating whether Mission Control is currently active.
#[derive(Resource)]
pub struct MissionControlActive(pub bool);

/// Resource holding the `WinID` of a window that should gain focus when focus-follows-mouse is enabled.
#[derive(Resource)]
pub struct FocusFollowsMouse(pub Option<WinID>);

#[derive(Resource)]
pub struct Initializing;

/// Bevy event trigger for spawning new windows.
#[derive(BevyEvent)]
pub struct SpawnWindowTrigger(pub Vec<Window>);

#[derive(BevyEvent)]
pub struct ReadDisplayProperties(pub Entity);

#[derive(BevyEvent)]
pub struct SendMessageTrigger(pub Event);

#[derive(BevyEvent)]
pub struct RestoreWindowState;

pub trait SpawnCommandsExt {
    fn reposition_entity(&mut self, entity: Entity, origin: Origin);

    fn resize_entity(&mut self, entity: Entity, size: Size);

    fn reshuffle_around(&mut self, entity: Entity);

    fn ensure_visible(&mut self, entity: Entity);

    fn focus_entity(&mut self, entity: Entity, raise: bool);

    fn flash_message(&mut self, message: String, duration: f32);

    // Spawns a layout strip in a single place, to properly insert all components.
    fn spawn_layout_strip(
        &mut self,
        layout_strip: LayoutStrip,
        origin: Origin,
        display_entity: Entity,
        active: bool,
    ) -> EntityCommands<'_>;
}

impl SpawnCommandsExt for Commands<'_, '_> {
    #[instrument(level = Level::TRACE, skip(self))]
    fn reposition_entity(&mut self, entity: Entity, origin: Origin) {
        if let Ok(mut entity_commands) = self.get_entity(entity) {
            entity_commands.try_insert(RepositionMarker(origin));
        }
    }

    #[instrument(level = Level::TRACE, skip(self))]
    fn resize_entity(&mut self, entity: Entity, size: Size) {
        if size.x <= 0 || size.y <= 0 {
            return;
        }
        if let Ok(mut entity_commands) = self.get_entity(entity) {
            entity_commands.try_insert(ResizeMarker(size));
        }
    }

    #[instrument(level = Level::TRACE, skip(self))]
    fn reshuffle_around(&mut self, entity: Entity) {
        if let Ok(mut entity_commands) = self.get_entity(entity) {
            entity_commands.try_insert(ReshuffleAroundMarker);
        }
    }

    #[instrument(level = Level::TRACE, skip(self))]
    fn ensure_visible(&mut self, entity: Entity) {
        if let Ok(mut entity_commands) = self.get_entity(entity) {
            entity_commands.try_insert(EnsureVisibleMarker);
        }
    }

    #[instrument(level = Level::TRACE, skip(self))]
    fn focus_entity(&mut self, entity: Entity, raise: bool) {
        if let Ok(mut entity_commands) = self.get_entity(entity) {
            entity_commands.try_insert(FocusedMarker);
            self.trigger(focus::FocusWindow { entity, raise });
        }
    }

    #[instrument(level = Level::TRACE, skip(self))]
    fn flash_message(&mut self, message: String, duration: f32) {
        let timeout = Timeout::new(Duration::from_secs_f32(duration), None, self);
        self.spawn((timeout, FlashMessage(message)));
    }

    #[instrument(level = Level::TRACE, skip(self))]
    fn spawn_layout_strip(
        &mut self,
        layout_strip: LayoutStrip,
        origin: Origin,
        display_entity: Entity,
        active: bool,
    ) -> EntityCommands<'_> {
        let mut spawned = self.spawn((layout_strip, Position(origin), ChildOf(display_entity)));
        if active {
            spawned.insert(ActiveWorkspaceMarker);
        } else {
            spawned.insert(SelectedVirtualMarker);
        }
        spawned
    }
}

pub fn setup_bevy_app(sender: EventSender, receiver: Receiver<Event>) -> Result<BevyApp> {
    let window_manager: Box<dyn WindowManagerApi> = Box::new(WindowManagerOS::new(sender.clone()));
    let watcher = window_manager.setup_config_watcher(CONFIGURATION_FILE.as_path())?;

    let mut app = BevyApp::new();

    app.add_plugins(MinimalPlugins)
        .init_resource::<Messages<Event>>()
        .insert_resource(Time::<Virtual>::from_max_delta(Duration::from_secs(10)))
        .insert_resource(WindowManager(window_manager))
        .insert_resource(SkipReshuffle(false))
        .insert_resource(SystemTheme {
            is_dark: crate::util::is_dark_mode(),
        })
        .insert_resource(MissionControlActive(false))
        .insert_resource(FocusFollowsMouse(None))
        .insert_resource(Initializing)
        .insert_non_send_resource(watcher)
        .add_plugins(mouse::MouseEventsPlugin)
        .add_plugins(scroll::ScrollEventsPlugin)
        .add_plugins(workspace::WorkspaceEventsPlugin)
        .add_plugins(layout::LayoutEventsPlugin)
        .add_plugins(focus::FocusEventsPlugin)
        .add_plugins(display::DisplayEventsPlugin)
        .add_plugins((register_triggers, register_systems, register_commands));

    let menu_events = sender.clone();
    let mut platform_callbacks = PlatformCallbacks::new(sender);
    platform_callbacks.setup_handlers()?;
    let mtm = platform_callbacks.main_thread_marker;
    let overlay_manager = OverlayManager::new(mtm);
    let flash_message_manager = FlashMessageManager::new(mtm);
    let menu_bar_manager = MenuBarManager::new(mtm, menu_events);
    app.insert_non_send_resource(platform_callbacks)
        .insert_non_send_resource(overlay_manager)
        .insert_non_send_resource(flash_message_manager)
        .insert_non_send_resource(menu_bar_manager)
        .insert_non_send_resource(receiver);

    if let Some(previous_state) =
        PaneruState::load_from_file(&PaneruState::default_state_file_path())
    {
        app.insert_resource(previous_state);
    }

    // Do not insert this in mocks.
    app.insert_resource(LowPowerMode(false));

    Ok(app)
}

struct WindowProperties {
    params: Vec<WindowParams>,
}

impl WindowProperties {
    pub fn new(app: &Application, window: &Window, config: &Config) -> Self {
        let bundle_id = app.bundle_id().unwrap_or_default();
        let title = window.title().unwrap_or_default();
        let params = config.find_window_properties(&title, &bundle_id);
        Self { params }
    }

    pub fn floating(&self) -> bool {
        self.params
            .iter()
            .find_map(|props| props.floating)
            .unwrap_or(false)
    }

    pub fn insertion(&self) -> Option<usize> {
        self.params.iter().find_map(|props| props.index)
    }

    pub fn dont_focus(&self) -> bool {
        self.params
            .iter()
            .find_map(|props| props.dont_focus)
            .unwrap_or(false)
    }

    pub fn border_radius(&self) -> Option<f64> {
        self.params.iter().find_map(|p| p.border_radius)
    }

    pub fn grid_ratios(&self) -> Option<(f64, f64, f64, f64)> {
        self.params.iter().find_map(WindowParams::grid_ratios)
    }

    pub fn passthrough_keys(&self) -> Vec<(u8, Modifiers)> {
        self.params
            .iter()
            .flat_map(|p| p.passthrough_keys().to_vec())
            .collect::<Vec<_>>()
    }

    pub fn width_ratio(&self) -> Option<f64> {
        self.params.iter().find_map(|props| props.width)
    }

    pub fn vertical_padding(&self) -> i32 {
        self.params
            .iter()
            .find_map(|props| props.vertical_padding)
            .unwrap_or(0)
    }

    pub fn horizontal_padding(&self) -> i32 {
        self.params
            .iter()
            .find_map(|props| props.horizontal_padding)
            .unwrap_or(0)
    }
}