leftwm-core 0.5.5

A window manager for Adventurers
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
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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
use super::{Manager, Window, WindowChange, WindowType, Workspace};
use crate::child_process::exec_shell;
use crate::config::{Config, InsertBehavior};
use crate::display_action::DisplayAction;
use crate::display_servers::DisplayServer;
use crate::layouts::{self, MAIN_AND_VERT_STACK};
use crate::models::{Handle, WindowHandle, WindowState, Xyhw};
use crate::state::State;
use crate::utils::helpers;
use std::env;
use std::str::FromStr;

impl<H: Handle, C: Config, SERVER: DisplayServer<H>> Manager<H, C, SERVER> {
    /// `window_created_handler` is called when the display server sends
    /// the event `DisplayEvent::WindowCreate(w, x, y)`.
    ///
    /// Returns true if changes need to be rendered.
    pub fn window_created_handler(&mut self, mut window: Window<H>, x: i32, y: i32) -> bool {
        // Don't add the window if the manager already knows about it.
        if self.state.windows.iter().any(|w| w.handle == window.handle) {
            return false;
        }

        // Setup any predefined hooks.
        self.config
            .setup_predefined_window(&mut self.state, &mut window);

        // TODO: this seems very janky.
        let mut is_first = false;
        let mut on_same_tag = true;
        // Random value
        let mut layout = MAIN_AND_VERT_STACK.to_string();
        let respect_dialog_position = self.config.respect_dialog_position();
        setup_window(
            &mut self.state,
            &mut window,
            (x, y),
            respect_dialog_position,
            &mut layout,
            &mut is_first,
            &mut on_same_tag,
        );
        self.config.load_window(&mut window);
        insert_window(&mut self.state, &mut window, &layout);

        let follow_mouse = self.state.focus_manager.focus_new_windows
            && self.state.focus_manager.behaviour.is_sloppy()
            && self.state.focus_manager.sloppy_mouse_follows_focus
            && window.is_managed()
            && on_same_tag
            && window.allows_mouse_warp();

        // Let the DS know we are managing this window.
        let act = DisplayAction::AddedWindow(window.handle, window.floating(), follow_mouse);
        self.state.actions.push_back(act);

        // Let the DS know the correct desktop to find this window.
        if window.tag.is_some() {
            let act = DisplayAction::SetWindowTag(window.handle, window.tag);
            self.state.actions.push_back(act);
        }

        // Tell the WM to reevaluate the stacking order, so the new window is put in the correct layer
        self.state.sort_windows();

        // if `single_window_border` is `false`, remove borders if there is a single visible window
        self.state.handle_single_border(self.config.border_width());

        // `is_first` and `on_same_tag` are set by `setup_window`
        // TODO: remove focus_new_windows variable from focus_manager,
        // TODO: use self.config.focus_new_windows() instead
        if (self.state.focus_manager.focus_new_windows || is_first) && on_same_tag {
            self.state.focus_window(&window.handle);
        }

        // run the `on_new_window_cmd` set in `config.ron`
        if let Some(cmd) = &self.config.on_new_window_cmd() {
            exec_shell(cmd, &mut self.children);
        }

        true
    }

    /// `window_destroyed_handler` is called when the display server sends
    /// the `DisplayEvent::WindowDestroy(handle)` event.
    ///
    /// Returns true if changes need to be rendered.
    pub fn window_destroyed_handler(&mut self, handle: &WindowHandle<H>) -> bool {
        // Get the previous focused window else find the next or previous window on the workspace.
        let new_handle = if let Some(Some(last_focused_window)) = self
            .state
            .focus_manager
            .window_history
            .iter()
            // Take the first window that is not the destroyed window.
            .find(|w| w != &&Some(*handle))
        {
            Some(*last_focused_window)
        } else {
            self.get_next_or_previous_handle(handle)
        };
        // If there is a parent we would want to focus it.
        let (transient, floating, visible) =
            match self.state.windows.iter().find(|w| &w.handle == handle) {
                Some(window) => (window.transient, window.floating(), window.visible()),
                None => return false,
            };
        self.state
            .focus_manager
            .tags_last_window
            .retain(|_, h| h != handle);
        self.state.windows.retain(|w| &w.handle != handle);

        self.state.handle_single_border(self.config.border_width());

        // Make sure the workspaces do not draw on the docks.
        update_workspace_avoid_list(&mut self.state);

        let focused = self.state.focus_manager.window_history.front();
        // Make sure focus is recalculated if we closed the currently focused window
        if focused == Some(&Some(*handle)) {
            if self.state.focus_manager.behaviour.is_sloppy()
                && self.state.focus_manager.sloppy_mouse_follows_focus
            {
                let act = DisplayAction::FocusWindowUnderCursor;
                self.state.actions.push_back(act);
                // Make sure we actually update the focus, as the currently
                // focused window will be removed from history.
                self.state.focus_manager.window_history.push_front(None);
            } else if let Some(parent) =
                find_transient_parent(&self.state.windows, transient).map(|p| p.handle)
            {
                self.state.focus_window(&parent);
            } else if let Some(handle) = new_handle {
                self.state.focus_window(&handle);
            } else {
                let act = DisplayAction::Unfocus(Some(*handle), floating);
                self.state.actions.push_back(act);
                self.state.focus_manager.window_history.push_front(None);
            }
        }

        // Remove destroyed window from history.
        self.state
            .focus_manager
            .window_history
            .retain(|w| w != &Some(*handle));

        // Only update windows if this window is visible.
        visible
    }

    /// `window_changed_handler` is called when the display server sends
    /// the `DisplayEvent::WindowChange(change)` event.
    ///
    /// Returns true if changes need to be rendered.
    pub fn window_changed_handler(&mut self, change: WindowChange<H>) -> bool {
        let mut changed = false;
        let mut fullscreen_changed = false;
        let mut above_changed = false;
        let mut transient_changed = false;
        let strut_changed = change.strut.is_some();
        let windows = self.state.windows.clone();
        let respect_dialog_position = self.config.respect_dialog_position();
        if let Some(window) = self
            .state
            .windows
            .iter_mut()
            .find(|w| w.handle == change.handle)
        {
            transient_changed = change
                .transient
                .as_ref()
                .is_some_and(|transient| transient != &window.transient);
            if let Some(states) = &change.states {
                fullscreen_changed =
                    states.contains(&WindowState::Fullscreen) != window.is_fullscreen();
                above_changed = states.contains(&WindowState::Above)
                    != window.states.contains(&WindowState::Above);
            }
            let container = if respect_dialog_position && window.r#type.is_dialog_like() {
                None
            } else {
                match find_transient_parent(&windows, window.transient) {
                    Some(parent) => Some(parent.exact_xyhw()),
                    None if window.r#type == WindowType::Dialog => self
                        .state
                        .workspaces
                        .iter()
                        .find(|ws| ws.tag == window.tag)
                        .map(|ws| ws.xyhw),
                    _ => None,
                }
            };

            changed = change.update(window, container);
            if window.r#type == WindowType::Dock {
                update_workspace_avoid_list(&mut self.state);
                // Don't let changes from docks re-render the worker. This will result in an
                // infinite loop. Just be patient a rerender will occur.
            }
        }
        if fullscreen_changed {
            // Update `dock` windows once, so they can recieve mouse click events again.
            // This is necessary, since we exclude them from the general update loop above.
            if let Some(windows) = self
                .state
                .windows
                .iter()
                .find(|w| w.r#type == WindowType::Dock)
            {
                self.display_server.update_windows(vec![windows]);
            }
        }

        if fullscreen_changed || above_changed || transient_changed {
            // Reorder windows.
            self.state.sort_windows();
        }
        if strut_changed {
            self.state.update_static();
        }
        changed
    }

    /// Find the next or previous window on the currently focused workspace.
    /// May return `None` if no other window is present.
    ///
    /// Returns true if changes need to be rendered.
    pub fn get_next_or_previous_handle(
        &mut self,
        handle: &WindowHandle<H>,
    ) -> Option<WindowHandle<H>> {
        let focused_workspace = self.state.focus_manager.workspace(&self.state.workspaces)?;
        let on_focused_workspace = |x: &Window<H>| -> bool { focused_workspace.is_managed(x) };
        let mut windows_on_workspace =
            helpers::vec_extract(&mut self.state.windows, on_focused_workspace);
        let is_handle = |x: &Window<H>| -> bool { &x.handle == handle };
        let new_handle = helpers::relative_find(&windows_on_workspace, is_handle, 1, false)
            .or_else(|| helpers::relative_find(&windows_on_workspace, is_handle, -1, false))
            .map(|w| w.handle);
        self.state.windows.append(&mut windows_on_workspace);
        new_handle
    }
}

// Private helper functions.

fn find_terminal<H: Handle>(state: &State<H>, pid: Option<u32>) -> Option<&Window<H>> {
    // Get $SHELL, e.g. /bin/zsh
    let shell_path = env::var("SHELL").ok()?;
    // Remove /bin/
    let shell = shell_path.split('/').next_back()?;
    // Try and find the shell that launched this app, if such a thing exists.
    let is_terminal = |pid: u32| -> Option<bool> {
        let parent = std::fs::read(format!("/proc/{pid}/comm")).ok()?;
        let parent_bytes = parent.split(|&c| c == b' ').next()?;
        let parent_str = std::str::from_utf8(parent_bytes).ok()?.strip_suffix('\n')?;
        Some(parent_str == shell)
    };

    let get_parent = |pid: u32| -> Option<u32> {
        let stat = std::fs::read(format!("/proc/{pid}/stat")).ok()?;
        let ppid_bytes = stat.split(|&c| c == b' ').nth(3)?;
        let ppid_str = std::str::from_utf8(ppid_bytes).ok()?;
        let ppid_u32 = u32::from_str(ppid_str).ok()?;
        Some(ppid_u32)
    };

    let pid = pid?;
    let shell_id = get_parent(pid)?;
    if is_terminal(shell_id)? {
        let terminal = get_parent(shell_id)?;
        return state.windows.iter().find(|w| w.pid == Some(terminal));
    }

    None
}

fn find_transient_parent<H: Handle>(
    windows: &[Window<H>],
    transient: Option<WindowHandle<H>>,
) -> Option<&Window<H>> {
    let mut transient = transient?;
    loop {
        transient = if let Some(found) = windows
            .iter()
            .find(|x| x.handle == transient)
            .and_then(|x| x.transient)
        {
            found
        } else {
            return windows.iter().find(|x| x.handle == transient);
        };
    }
}

fn insert_window<H: Handle>(state: &mut State<H>, window: &mut Window<H>, layout: &str) {
    let mut was_fullscreen = false;
    if window.r#type == WindowType::Normal {
        let for_active_workspace =
            |x: &Window<H>| -> bool { window.tag == x.tag && x.is_managed() };
        // Only minimize when the new window is type normal.
        if let Some(fsw) = state
            .windows
            .iter_mut()
            .find(|w| for_active_workspace(w) && w.is_fullscreen())
        {
            let act =
                DisplayAction::SetState(fsw.handle, !fsw.is_fullscreen(), WindowState::Fullscreen);
            state.actions.push_back(act);
            was_fullscreen = true;
        } else if let Some(fsw) = state
            .windows
            .iter_mut()
            .find(|w| for_active_workspace(w) && w.is_maximized())
            && !window.floating()
        {
            let act =
                DisplayAction::SetState(fsw.handle, !fsw.is_maximized(), WindowState::Maximized);
            state.actions.push_back(act);
        }

        // TODO: remove hard coded layout names.
        let monocle = layouts::MONOCLE;
        let main_and_deck = layouts::MAIN_AND_DECK;
        if layout == monocle || layout == main_and_deck {
            // Extract the current windows on the same workspace.
            let mut to_reorder = helpers::vec_extract(&mut state.windows, for_active_workspace);
            if layout == monocle || to_reorder.is_empty() {
                // When in monocle we want the new window to be fullscreen if the previous window was
                // fullscreen.
                if was_fullscreen {
                    let act = DisplayAction::SetState(
                        window.handle,
                        !window.is_fullscreen(),
                        WindowState::Fullscreen,
                    );
                    state.actions.push_back(act);
                }
                // Place the window above the other windows on the workspace.
                to_reorder.insert(0, window.clone());
            } else {
                // Place the window second within the other windows on the workspace.
                to_reorder.insert(1, window.clone());
            }
            state.windows.append(&mut to_reorder);
            return;
        }
    }

    // Keep dialog-like, floating, and scratchpad windows at the top.
    if window.r#type.is_dialog_like() || window.floating() || is_scratchpad(state, window) {
        state.windows.insert(0, window.clone());
        return;
    }

    let current_index = state
        .focus_manager
        .window(&state.windows)
        .and_then(|current| {
            state
                .windows
                .iter()
                .position(|w| w.handle == current.handle)
        })
        .unwrap_or(0);

    // Past special cases we just insert the window based on the configured insert behavior
    match state.insert_behavior {
        InsertBehavior::Top => state.windows.insert(0, window.clone()),
        InsertBehavior::Bottom => state.windows.push(window.clone()),
        InsertBehavior::AfterCurrent if current_index < state.windows.len() => {
            state.windows.insert(current_index + 1, window.clone());
        }
        InsertBehavior::AfterCurrent | InsertBehavior::BeforeCurrent => {
            state.windows.insert(current_index, window.clone());
        }
    }
}

fn is_scratchpad<H: Handle>(state: &State<H>, window: &Window<H>) -> bool {
    state
        .active_scratchpads
        .iter()
        .any(|(_, id)| id.iter().any(|id| window.pid == Some(*id)))
}

// Tries to position a window according to the requested sizes.
// When no size was requested, defaults to `ws.center_halfed()`
fn set_relative_floating<H: Handle>(window: &mut Window<H>, ws: &Workspace, outer: Xyhw) {
    window.set_floating(true);
    window.normal = ws.xyhw;
    let xyhw = window.requested.map_or_else(
        || ws.center_halfed(),
        |mut requested| {
            requested.center_relative(outer, window.border);
            if !ws.xyhw_avoided.contains_xyhw(&requested) {
                requested.center_relative(ws.xyhw_avoided, window.border);
            }
            requested
        },
    );
    window.set_floating_exact(xyhw);
}

// Dialog-like windows already carry the geometry selected by their client. Keep that geometry
// instead of replacing its position with LeftWM's centering policy.
fn set_requested_floating<H: Handle>(window: &mut Window<H>, ws: &Workspace) {
    window.set_floating(true);
    window.normal = ws.xyhw;
    let xyhw = window.requested.unwrap_or_else(|| ws.center_halfed());
    window.set_floating_exact(xyhw);
}

fn setup_window<H: Handle>(
    state: &mut State<H>,
    window: &mut Window<H>,
    xy: (i32, i32),
    respect_dialog_position: bool,
    layout: &mut String,
    is_first: &mut bool,
    on_same_tag: &mut bool,
) {
    // Identify the workspace in which to create the window.
    let ws = state
        .focus_manager
        .create_follows_cursor() // If the window must be created under the cursor...
        .then_some(
            // ...look for the workspace with the cursor.
            state
                .workspaces
                .iter()
                .find(|ws| ws.xyhw.contains_point(xy.0, xy.1)),
        )
        .flatten()
        .or(state.focus_manager.workspace(&state.workspaces)); // Else, use the workspace which has the focus.

    // If no workspace was found, put the window on tag 1.
    let Some(ws) = ws else {
        tracing::warn!("setup_window failed to identify workspace. Falling back to tag 1");
        window.tag = Some(1);
        if is_scratchpad(state, window)
            && let Some(scratchpad_tag) = state.tags.get_hidden_by_label("NSP")
        {
            window.tag(&scratchpad_tag.id);
            window.set_floating(true);
        }
        return;
    };

    // Setup basic variables.
    let for_active_workspace = |x: &Window<H>| -> bool { ws.tag == x.tag && x.is_managed() };
    *is_first = !state.windows.iter().any(for_active_workspace);
    // May have been set by a predefined tag.
    if window.tag.is_none() {
        window.tag =
            find_terminal(state, window.pid).map_or_else(|| ws.tag, |terminal| terminal.tag);
    }
    *on_same_tag = ws.tag == window.tag;
    layout.clone_from(&state.layout_manager.layout(ws.id, window.tag.unwrap()).name);

    // Setup a scratchpad window.
    if let Some((scratchpad_name, _)) = state
        .active_scratchpads
        .iter()
        .find(|(_, id)| id.iter().any(|id| Some(*id) == window.pid))
    {
        window.set_floating(true);
        if let Some(s) = state
            .scratchpads
            .iter()
            .find(|s| *scratchpad_name == s.name)
        {
            let new_float_exact = s.xyhw(&ws.xyhw);
            window.normal = ws.xyhw;
            window.set_floating_exact(new_float_exact);
            return;
        }
    }

    // Dialog-like clients are responsible for their own geometry. This must run before transient
    // handling, which intentionally centers normal child windows relative to their parent.
    if respect_dialog_position && window.r#type.is_dialog_like() {
        set_requested_floating(window, ws);
        return;
    }

    // Setup a child window.
    if let Some(parent) = find_transient_parent(&state.windows, window.transient) {
        // This is currently for vlc, this probably will need to be more general if another
        // case comes up where we don't want to move the window.
        if window.r#type != WindowType::Utility {
            set_relative_floating(window, ws, parent.exact_xyhw());
            return;
        }
    }

    // Setup window based on type.
    match window.r#type {
        WindowType::Normal => {
            window.apply_margin_multiplier(ws.margin_multiplier);
            if window.floating() {
                set_relative_floating(window, ws, ws.xyhw_avoided);
            }
        }
        WindowType::Dialog | WindowType::Splash => {
            set_relative_floating(window, ws, ws.xyhw_avoided);
        }
        _ => {}
    }
}

fn update_workspace_avoid_list<H: Handle>(state: &mut State<H>) {
    let mut avoid = vec![];
    state
        .windows
        .iter()
        .filter(|w| w.r#type == WindowType::Dock)
        .filter_map(|w| w.strut.map(|strut| (w.handle, strut)))
        .for_each(|(handle, to_avoid)| {
            tracing::trace!("AVOID STRUT:[{:?}] {:?}", handle, to_avoid);
            avoid.push(to_avoid);
        });
    for ws in &mut state.workspaces {
        let struts = avoid
            .clone()
            .into_iter()
            .filter(|s| {
                let (x, y) = s.center();
                ws.contains_point(x, y)
            })
            .collect();
        ws.avoid = struts;
        ws.update_avoided_areas();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Manager;
    use crate::layouts::MONOCLE;
    use crate::models::{FocusBehaviour, MockHandle, Screen, XyhwBuilder, XyhwChange};

    fn last_window_order(state: &State<MockHandle>) -> Vec<WindowHandle<MockHandle>> {
        state
            .actions
            .iter()
            .rev()
            .find_map(|action| match action {
                DisplayAction::SetWindowOrder(order) => Some(order.clone()),
                _ => None,
            })
            .expect("expected a window order action")
    }

    fn follows_mouse_on_creation(
        window: Window<MockHandle>,
        focus_new_windows: bool,
        focus_behaviour: FocusBehaviour,
        sloppy_mouse_follows_focus: bool,
    ) -> bool {
        let mut manager = Manager::new_test(vec!["1".to_owned()]);
        manager.screen_create_handler(Screen::default());
        manager.state.actions.clear();
        manager.state.focus_manager.focus_new_windows = focus_new_windows;
        manager.state.focus_manager.behaviour = focus_behaviour;
        manager.state.focus_manager.sloppy_mouse_follows_focus = sloppy_mouse_follows_focus;

        manager.window_created_handler(window, -1, -1);

        manager
            .state
            .actions
            .iter()
            .find_map(|action| match action {
                DisplayAction::AddedWindow(_, _, follow_mouse) => Some(*follow_mouse),
                _ => None,
            })
            .expect("expected an AddedWindow action")
    }

    #[test]
    fn new_window_mouse_warp_uses_type_default_and_window_override() {
        let cases = [
            (1, WindowType::Normal, None, true),
            (2, WindowType::Utility, None, false),
            (3, WindowType::Normal, Some(true), false),
            (4, WindowType::Utility, Some(false), true),
        ];

        for (handle, window_type, disable_mouse_grab, expected) in cases {
            let mut window = Window::new(WindowHandle(handle), None, None);
            window.r#type = window_type;
            window.set_disable_mouse_grab(disable_mouse_grab);

            assert_eq!(
                follows_mouse_on_creation(window, true, FocusBehaviour::Sloppy, true),
                expected,
                "unexpected follow_mouse for disable_mouse_grab={disable_mouse_grab:?}",
            );
        }
    }

    fn dialog_like_types() -> [WindowType; 10] {
        [
            WindowType::Dialog,
            WindowType::Splash,
            WindowType::Utility,
            WindowType::Menu,
            WindowType::DropdownMenu,
            WindowType::PopupMenu,
            WindowType::Tooltip,
            WindowType::Notification,
            WindowType::Combo,
            WindowType::Dnd,
        ]
    }

    #[test]
    fn dialog_like_windows_keep_their_requested_geometry_when_enabled() {
        let requested: Xyhw = XyhwBuilder {
            x: 120,
            y: 80,
            w: 240,
            h: 160,
            ..XyhwBuilder::default()
        }
        .into();

        for (handle, window_type) in dialog_like_types().into_iter().enumerate() {
            let mut manager = Manager::new_test(vec!["1".to_owned()]);
            manager.config.respect_dialog_position = true;
            manager.screen_create_handler(Screen::default());

            let handle = WindowHandle::<MockHandle>(handle as i32 + 1);
            let mut window = Window::new(handle, None, None);
            window.r#type = window_type;
            window.requested = Some(requested);
            manager.window_created_handler(window, -1, -1);

            let actual = manager
                .state
                .windows
                .iter()
                .find(|window| window.handle == handle)
                .expect("expected the dialog-like window")
                .exact_xyhw();
            assert_eq!(actual, requested);
        }
    }

    #[test]
    fn dialog_windows_center_by_default_but_keep_their_requested_size() {
        let mut manager = Manager::new_test(vec!["1".to_owned()]);
        manager.screen_create_handler(Screen::default());

        let requested: Xyhw = XyhwBuilder {
            x: 120,
            y: 80,
            w: 240,
            h: 160,
            ..XyhwBuilder::default()
        }
        .into();
        let handle = WindowHandle::<MockHandle>(1);
        let mut window = Window::new(handle, None, None);
        window.r#type = WindowType::Dialog;
        window.requested = Some(requested);
        let mut expected = requested;
        expected.center_relative(manager.state.workspaces[0].xyhw_avoided, window.border);
        manager.window_created_handler(window, -1, -1);

        let actual = manager
            .state
            .windows
            .iter()
            .find(|window| window.handle == handle)
            .expect("expected the dialog window")
            .exact_xyhw();
        assert_eq!(actual, expected);
        assert_eq!((actual.w(), actual.h()), (requested.w(), requested.h()));
        assert_ne!((actual.x(), actual.y()), (requested.x(), requested.y()));
    }

    #[test]
    fn mouse_warp_permission_does_not_bypass_global_focus_settings() {
        let cases = [
            (false, FocusBehaviour::Sloppy, true),
            (true, FocusBehaviour::ClickTo, true),
            (true, FocusBehaviour::Sloppy, false),
        ];

        for (focus_new_windows, focus_behaviour, sloppy_mouse_follows_focus) in cases {
            let window = Window::new(WindowHandle(1), None, None);

            assert!(!follows_mouse_on_creation(
                window,
                focus_new_windows,
                focus_behaviour,
                sloppy_mouse_follows_focus,
            ));
        }
    }

    #[test]
    fn dialog_like_windows_without_geometry_keep_the_centered_fallback() {
        for (handle, window_type) in dialog_like_types().into_iter().enumerate() {
            let mut manager = Manager::new_test(vec!["1".to_owned()]);
            manager.config.respect_dialog_position = true;
            manager.screen_create_handler(Screen::default());
            let expected = manager.state.workspaces[0].center_halfed();

            let handle = WindowHandle::<MockHandle>(handle as i32 + 1);
            let mut window = Window::new(handle, None, None);
            window.r#type = window_type;
            manager.window_created_handler(window, -1, -1);

            let actual = manager
                .state
                .windows
                .iter()
                .find(|window| window.handle == handle)
                .expect("expected the dialog-like window")
                .exact_xyhw();
            assert_eq!(actual, expected);
        }
    }

    #[test]
    fn dialog_like_configure_changes_only_update_requested_fields_when_enabled() {
        for (index, window_type) in dialog_like_types().into_iter().enumerate() {
            let mut manager = Manager::new_test(vec!["1".to_owned()]);
            manager.config.respect_dialog_position = true;
            manager.screen_create_handler(Screen::default());

            let parent_handle = WindowHandle::<MockHandle>(1);
            manager.window_created_handler(Window::new(parent_handle, None, None), -1, -1);

            let requested: Xyhw = XyhwBuilder {
                x: 120,
                y: 80,
                w: 240,
                h: 160,
                ..XyhwBuilder::default()
            }
            .into();
            let handle = WindowHandle::<MockHandle>(index as i32 + 2);
            let mut window = Window::new(handle, None, None);
            window.r#type = window_type;
            window.transient = Some(parent_handle);
            window.border = 0;
            window.requested = Some(requested);
            manager.window_created_handler(window, -1, -1);

            let mut resize = WindowChange::new(handle);
            resize.floating = Some(XyhwChange {
                w: Some(300),
                h: Some(190),
                ..XyhwChange::default()
            });
            manager.window_changed_handler(resize);

            let resized = manager
                .state
                .windows
                .iter()
                .find(|window| window.handle == handle)
                .expect("expected the resized dialog-like window")
                .exact_xyhw();
            assert_eq!((resized.x(), resized.y()), (120, 80));
            assert_eq!((resized.w(), resized.h()), (300, 190));

            let mut movement = WindowChange::new(handle);
            movement.floating = Some(XyhwChange {
                x: Some(-40),
                y: Some(210),
                ..XyhwChange::default()
            });
            manager.window_changed_handler(movement);

            let moved = manager
                .state
                .windows
                .iter()
                .find(|window| window.handle == handle)
                .expect("expected the moved dialog-like window")
                .exact_xyhw();
            assert_eq!((moved.x(), moved.y()), (-40, 210));
            assert_eq!((moved.w(), moved.h()), (300, 190));
        }
    }

    #[test]
    fn dialog_configure_centers_by_default_but_keeps_the_requested_size() {
        let mut manager = Manager::new_test(vec!["1".to_owned()]);
        manager.screen_create_handler(Screen::default());

        let parent_handle = WindowHandle::<MockHandle>(1);
        manager.window_created_handler(Window::new(parent_handle, None, None), -1, -1);
        let parent = manager
            .state
            .windows
            .iter()
            .find(|window| window.handle == parent_handle)
            .expect("expected the parent window")
            .exact_xyhw();

        let handle = WindowHandle::<MockHandle>(2);
        let mut window = Window::new(handle, None, None);
        window.r#type = WindowType::Dialog;
        window.transient = Some(parent_handle);
        window.border = 0;
        window.requested = Some(
            XyhwBuilder {
                x: 120,
                y: 80,
                w: 240,
                h: 160,
                ..XyhwBuilder::default()
            }
            .into(),
        );
        manager.window_created_handler(window, -1, -1);

        let mut requested: Xyhw = XyhwBuilder {
            x: -40,
            y: 210,
            w: 300,
            h: 190,
            ..XyhwBuilder::default()
        }
        .into();
        let mut change = WindowChange::new(handle);
        change.floating = Some(XyhwChange {
            x: Some(requested.x()),
            y: Some(requested.y()),
            w: Some(requested.w()),
            h: Some(requested.h()),
            ..XyhwChange::default()
        });
        manager.window_changed_handler(change);

        requested.center_relative(parent, 0);
        let actual = manager
            .state
            .windows
            .iter()
            .find(|window| window.handle == handle)
            .expect("expected the dialog window")
            .exact_xyhw();
        assert_eq!(actual, requested);
        assert_eq!((actual.w(), actual.h()), (300, 190));
        assert_ne!((actual.x(), actual.y()), (-40, 210));
    }

    #[test]
    fn dialog_is_visible_and_stacked_above_fullscreen_without_focus() {
        let mut manager = Manager::new_test(vec!["1".to_string()]);
        manager.screen_create_handler(Screen::default());

        let mut fullscreen = Window::new(WindowHandle::<MockHandle>(1), None, None);
        fullscreen.states.push(WindowState::Fullscreen);
        manager.window_created_handler(fullscreen, -1, -1);

        let mut dialog = Window::new(WindowHandle::<MockHandle>(2), None, None);
        dialog.r#type = WindowType::Dialog;
        manager.window_created_handler(dialog, -1, -1);

        assert_eq!(
            manager
                .state
                .focus_manager
                .window(&manager.state.windows)
                .map(|window| window.handle),
            Some(WindowHandle(1))
        );
        assert_eq!(
            last_window_order(&manager.state),
            vec![WindowHandle(2), WindowHandle(1)]
        );

        manager.update_windows();
        assert!(
            manager
                .state
                .windows
                .iter()
                .find(|window| window.handle == WindowHandle(2))
                .is_some_and(Window::visible)
        );
    }

    #[test]
    fn late_transient_hint_restacks_dialog_above_fullscreen_parent() {
        let mut manager = Manager::new_test(vec!["1".to_string()]);
        manager.screen_create_handler(Screen::default());

        let mut fullscreen = Window::new(WindowHandle::<MockHandle>(1), None, None);
        fullscreen.states.push(WindowState::Fullscreen);
        manager.window_created_handler(fullscreen, -1, -1);

        let mut dialog = Window::new(WindowHandle::<MockHandle>(2), None, None);
        dialog.r#type = WindowType::Dialog;
        manager.window_created_handler(dialog, -1, -1);

        manager.state.actions.clear();
        let mut change = WindowChange::new(WindowHandle(2));
        change.transient = Some(Some(WindowHandle(1)));

        assert!(manager.window_changed_handler(change));
        assert_eq!(
            last_window_order(&manager.state),
            vec![WindowHandle(2), WindowHandle(1)]
        );

        manager.update_windows();
        assert!(
            manager
                .state
                .windows
                .iter()
                .find(|window| window.handle == WindowHandle(2))
                .is_some_and(Window::visible)
        );
    }

    #[test]
    fn insert_behavior_bottom_add_window_at_the_end_of_the_stack() {
        let mut manager = Manager::new_test(vec![]);
        manager.state.insert_behavior = InsertBehavior::Bottom;

        manager.screen_create_handler(Screen::default());
        manager.window_created_handler(
            Window::new(WindowHandle::<MockHandle>(1), None, None),
            -1,
            -1,
        );
        manager.window_created_handler(
            Window::new(WindowHandle::<MockHandle>(2), None, None),
            -1,
            -1,
        );

        let expected = vec![WindowHandle::<MockHandle>(1), WindowHandle::<MockHandle>(2)];

        let actual: Vec<WindowHandle<MockHandle>> =
            manager.state.windows.iter().map(|w| w.handle).collect();

        assert_eq!(actual, expected);
    }

    #[test]
    fn insert_behavior_top_add_window_at_the_top_of_the_stack() {
        let mut manager = Manager::new_test(vec![]);
        manager.state.insert_behavior = InsertBehavior::Top;

        manager.screen_create_handler(Screen::default());
        manager.window_created_handler(
            Window::new(WindowHandle::<MockHandle>(1), None, None),
            -1,
            -1,
        );
        manager.window_created_handler(
            Window::new(WindowHandle::<MockHandle>(2), None, None),
            -1,
            -1,
        );

        let expected = vec![WindowHandle::<MockHandle>(2), WindowHandle::<MockHandle>(1)];
        let actual: Vec<WindowHandle<MockHandle>> =
            manager.state.windows.iter().map(|w| w.handle).collect();

        assert_eq!(actual, expected);
    }

    #[test]
    fn insert_behavior_after_current_add_window_after_the_current_window() {
        let mut manager = Manager::new_test(vec![]);
        manager.state.insert_behavior = InsertBehavior::AfterCurrent;

        manager.screen_create_handler(Screen::default());
        manager.window_created_handler(
            Window::new(WindowHandle::<MockHandle>(1), None, None),
            -1,
            -1,
        );
        manager.window_created_handler(
            Window::new(WindowHandle::<MockHandle>(2), None, None),
            -1,
            -1,
        );
        manager.window_created_handler(
            Window::new(WindowHandle::<MockHandle>(3), None, None),
            -1,
            -1,
        );

        let expected = vec![
            WindowHandle::<MockHandle>(1),
            WindowHandle::<MockHandle>(3),
            WindowHandle::<MockHandle>(2),
        ];
        let actual: Vec<WindowHandle<MockHandle>> =
            manager.state.windows.iter().map(|w| w.handle).collect();

        assert_eq!(actual, expected);
    }

    #[test]
    fn insert_behavior_before_current_add_window_before_the_current_window() {
        let mut manager = Manager::new_test(vec![]);
        manager.state.insert_behavior = InsertBehavior::BeforeCurrent;

        manager.screen_create_handler(Screen::default());
        manager.window_created_handler(
            Window::new(WindowHandle::<MockHandle>(1), None, None),
            -1,
            -1,
        );
        manager.window_created_handler(
            Window::new(WindowHandle::<MockHandle>(2), None, None),
            -1,
            -1,
        );

        manager.window_created_handler(
            Window::new(WindowHandle::<MockHandle>(3), None, None),
            -1,
            -1,
        );

        let expected = vec![
            WindowHandle::<MockHandle>(2),
            WindowHandle::<MockHandle>(3),
            WindowHandle::<MockHandle>(1),
        ];
        let actual: Vec<WindowHandle<MockHandle>> =
            manager.state.windows.iter().map(|w| w.handle).collect();

        assert_eq!(actual, expected);
    }

    #[test]
    fn single_window_has_no_border() {
        let mut manager = Manager::new_test_with_border(vec![], 1);
        manager.screen_create_handler(Screen::default());

        manager.window_created_handler(
            Window::new(WindowHandle::<MockHandle>(1), None, None),
            -1,
            -1,
        );

        assert_eq!((manager.state.windows[0]).border(), 0);
    }

    #[test]
    fn multiple_windows_have_borders() {
        let mut manager = Manager::new_test_with_border(vec![], 1);
        manager.screen_create_handler(Screen::default());

        manager.window_created_handler(
            Window::new(WindowHandle::<MockHandle>(1), None, None),
            -1,
            -1,
        );
        manager.window_created_handler(
            Window::new(WindowHandle::<MockHandle>(2), None, None),
            -1,
            -1,
        );

        assert_eq!((manager.state.windows[0]).border(), 1);
        assert_eq!((manager.state.windows[1]).border(), 1);
    }

    #[test]
    fn remaining_single_window_has_no_border() {
        let mut manager = Manager::new_test_with_border(vec![], 1);
        manager.screen_create_handler(Screen::default());

        manager.window_created_handler(
            Window::new(WindowHandle::<MockHandle>(1), None, None),
            -1,
            -1,
        );
        manager.window_created_handler(
            Window::new(WindowHandle::<MockHandle>(2), None, None),
            -1,
            -1,
        );

        manager.window_destroyed_handler(&manager.state.windows[1].handle.clone());

        assert_eq!((manager.state.windows[0]).border(), 0);
    }

    #[test]
    fn single_windows_on_different_tags_have_no_border() {
        let mut manager = Manager::new_test_with_border(vec!["1".to_string(), "2".to_string()], 1);
        manager.screen_create_handler(Screen::default());

        let mut first_window = Window::new(WindowHandle::<MockHandle>(1), None, None);
        first_window.tag(&1);
        manager.window_created_handler(first_window, -1, -1);

        let mut second_window = Window::new(WindowHandle::<MockHandle>(2), None, None);
        second_window.tag(&2);
        manager.window_created_handler(second_window, -1, -1);

        assert_eq!((manager.state.windows[0]).border(), 0);
        assert_eq!((manager.state.windows[1]).border(), 0);
    }

    #[test]
    fn single_window_has_no_border_and_windows_on_another_tag_have_borders() {
        let mut manager = Manager::new_test_with_border(vec!["1".to_string(), "2".to_string()], 1);
        manager.screen_create_handler(Screen::default());

        let mut first_window = Window::new(WindowHandle::<MockHandle>(1), None, None);
        first_window.tag(&1);
        manager.window_created_handler(first_window, -1, -1);

        let mut second_window = Window::new(WindowHandle::<MockHandle>(2), None, None);
        second_window.tag(&2);
        manager.window_created_handler(second_window, -1, -1);

        let mut third_window = Window::new(WindowHandle::<MockHandle>(3), None, None);
        third_window.tag(&2);
        manager.window_created_handler(third_window, -1, -1);

        assert_eq!((manager.state.windows[0]).border(), 0);
        assert_eq!((manager.state.windows[1]).border(), 1);
        assert_eq!((manager.state.windows[2]).border(), 1);
    }

    #[test]
    fn remaining_single_window_on_another_tag_has_no_border() {
        let mut manager = Manager::new_test_with_border(vec!["1".to_string(), "2".to_string()], 1);
        manager.screen_create_handler(Screen::default());

        let mut first_window = Window::new(WindowHandle::<MockHandle>(1), None, None);
        first_window.tag(&1);
        manager.window_created_handler(first_window, -1, -1);

        let mut second_window = Window::new(WindowHandle::<MockHandle>(2), None, None);
        second_window.tag(&2);
        manager.window_created_handler(second_window, -1, -1);

        let mut third_window = Window::new(WindowHandle::<MockHandle>(3), None, None);
        third_window.tag(&2);
        manager.window_created_handler(third_window, -1, -1);

        manager.window_destroyed_handler(&manager.state.windows[2].handle.clone());

        assert_eq!((manager.state.windows[0]).border(), 0);
        assert_eq!((manager.state.windows[1]).border(), 0);
    }

    #[test]
    fn monocle_layout_only_has_single_windows() {
        let mut manager = Manager::new_test_with_border(vec!["1".to_string()], 1);
        manager.screen_create_handler(Screen::default());
        manager.state.layout_manager.set_layout(1, 1, MONOCLE);
        // manager.state.tags.get_mut(1).unwrap().set_layout(String::from("Monocle"));
        manager.window_created_handler(
            Window::new(WindowHandle::<MockHandle>(1), None, None),
            -1,
            -1,
        );
        manager.window_created_handler(
            Window::new(WindowHandle::<MockHandle>(2), None, None),
            -1,
            -1,
        );
        assert_eq!((manager.state.windows[0]).border(), 0);
        assert_eq!((manager.state.windows[1]).border(), 0);
    }
}