atagen

monolith

public
Star0
Watch0
92fbde37d644730f3a5e29e4b19fc684bbfae899
1
ssh://brewery@pls.lobotomise.me:33/atagen/monolith.git
crates/layout/src/lib.rsRust1084 lines34.0 KB
1
//! Window organisation without smithay. Tags with per-output views, one
2
//! tiling tree per output filtered by those views, floating windows,
3
//! scratchpads, focus, and restoring windows when an output comes back.
4
5
mod outputs;
6
mod scratchpad;
7
mod tree;
8
9
#[cfg(test)]
10
mod tests;
11
12
pub use monolith_planner::Rect;
13
pub use tree::{Axis, Dir, Tree};
14
15
use outputs::Parked;
16
use slotmap::{SlotMap, new_key_type};
17
use std::collections::HashMap;
18
19
new_key_type! {
20
    pub struct WindowId;
21
    pub struct TagId;
22
    pub struct OutputId;
23
}
24
25
pub const HOMELESS: &str = "homeless";
26
27
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28
pub enum ExpandScope {
29
    Window,
30
    Container,
31
    All,
32
}
33
34
/// Space taken from an output's edges by bars and other panels.
35
#[derive(Clone, Copy, Debug, PartialEq, Default)]
36
pub struct Insets {
37
    pub top: f64,
38
    pub right: f64,
39
    pub bottom: f64,
40
    pub left: f64,
41
}
42
43
#[derive(Clone, Copy, Debug, PartialEq)]
44
pub struct Gaps {
45
    pub inner: f64,
46
    pub outer: f64,
47
}
48
49
impl Default for Gaps {
50
    fn default() -> Self {
51
        Self {
52
            inner: 8.0,
53
            outer: 8.0,
54
        }
55
    }
56
}
57
58
#[derive(Clone, Debug)]
59
pub struct Window {
60
    pub output: Option<OutputId>,
61
    pub tag: TagId,
62
    pub floating: bool,
63
    pub float_rect: Option<Rect>,
64
    /// `float_rect` is the layout's default, not a size the window or the
65
    /// user chose.
66
    pub float_default: bool,
67
    pub fullscreen: bool,
68
    /// The window this one is a dialog or other transient of.
69
    pub parent: Option<WindowId>,
70
    /// Focus aimed at the parent goes to this window while it is mapped.
71
    pub modal: bool,
72
    pub sticky: bool,
73
    pub scratchpad: Option<usize>,
74
    pub urgent: bool,
75
    /// Its client took the buffer away, as when hiding to a tray. The entry
76
    /// stays for when the client maps it again, but nothing shows or focuses it.
77
    pub hidden: bool,
78
    evicted_from: Option<String>,
79
}
80
81
#[derive(Clone, Debug)]
82
pub struct Tag {
83
    pub name: String,
84
    pub urgent: bool,
85
}
86
87
#[derive(Clone, Debug)]
88
pub struct Output {
89
    pub name: String,
90
    pub area: Rect,
91
    pub reserved: Insets,
92
    pub tree: Tree<WindowId>,
93
    /// Viewed tags besides the homeless tag, which is always viewed.
94
    pub viewed: Vec<TagId>,
95
    /// Floating windows, bottom to top.
96
    pub floating: Vec<WindowId>,
97
}
98
99
impl Output {
100
    /// The area left once bars and panels have taken their edges.
101
    pub fn usable(&self) -> Rect {
102
        let (a, r) = (self.area, self.reserved);
103
        Rect::new(
104
            a.x + r.left,
105
            a.y + r.top,
106
            (a.w - r.left - r.right).max(0.0),
107
            (a.h - r.top - r.bottom).max(0.0),
108
        )
109
    }
110
}
111
112
#[derive(Clone, Debug)]
113
pub struct Scratchpad {
114
    pub name: String,
115
    pub windows: Vec<WindowId>,
116
    pub shown: Option<usize>,
117
    pub output: Option<OutputId>,
118
}
119
120
#[derive(Clone, Debug, Default)]
121
pub struct Arrangement {
122
    /// Every tiled window on the output. Hidden ones are zero-size seeds.
123
    pub tiled: Vec<Placed>,
124
    /// Visible floating windows and shown scratchpads, bottom to top.
125
    pub floating: Vec<(WindowId, Rect)>,
126
    pub fullscreen: Option<WindowId>,
127
    /// Floating transients of the fullscreen window and shown scratchpads,
128
    /// which stay above it.
129
    pub over: Vec<WindowId>,
130
}
131
132
#[derive(Clone, Copy, Debug)]
133
pub struct Placed {
134
    pub window: WindowId,
135
    pub rect: Rect,
136
    pub visible: bool,
137
}
138
139
#[derive(Clone, Debug)]
140
pub struct Layout {
141
    windows: SlotMap<WindowId, Window>,
142
    tags: SlotMap<TagId, Tag>,
143
    tag_order: Vec<TagId>,
144
    homeless: TagId,
145
    outputs: SlotMap<OutputId, Output>,
146
    active: Option<OutputId>,
147
    /// Focus history, most recent last.
148
    history: Vec<WindowId>,
149
    /// How many windows are modal, so focus lookups skip the scan for one.
150
    modals: usize,
151
    scratchpads: Vec<Scratchpad>,
152
    last_scratchpad: Option<usize>,
153
    parked: HashMap<String, Parked>,
154
    pub gaps: Gaps,
155
    pub autotile: bool,
156
}
157
158
impl Default for Layout {
159
    fn default() -> Self {
160
        let mut tags = SlotMap::with_key();
161
        let homeless = tags.insert(Tag {
162
            name: HOMELESS.into(),
163
            urgent: false,
164
        });
165
        Self {
166
            windows: SlotMap::with_key(),
167
            tags,
168
            tag_order: vec![homeless],
169
            homeless,
170
            outputs: SlotMap::with_key(),
171
            active: None,
172
            history: Vec::new(),
173
            modals: 0,
174
            scratchpads: Vec::new(),
175
            last_scratchpad: None,
176
            parked: HashMap::new(),
177
            gaps: Gaps::default(),
178
            autotile: false,
179
        }
180
    }
181
}
182
183
impl Layout {
184
    pub fn homeless(&self) -> TagId {
185
        self.homeless
186
    }
187
188
    /// Looks a tag up by name, creating it at the end of the order.
189
    pub fn tag(&mut self, name: &str) -> TagId {
190
        if let Some(id) = self.tag_id(name) {
191
            return id;
192
        }
193
        let id = self.tags.insert(Tag {
194
            name: name.into(),
195
            urgent: false,
196
        });
197
        self.tag_order.push(id);
198
        id
199
    }
200
201
    pub fn tag_id(&self, name: &str) -> Option<TagId> {
202
        self.tag_order
203
            .iter()
204
            .copied()
205
            .find(|&t| self.tags[t].name == name)
206
    }
207
208
    pub fn tags(&self) -> impl Iterator<Item = (TagId, &Tag)> {
209
        self.tag_order.iter().map(|&t| (t, &self.tags[t]))
210
    }
211
212
    pub fn reorder_tag(&mut self, tag: TagId, index: usize) {
213
        if let Some(i) = self.tag_order.iter().position(|&t| t == tag) {
214
            self.tag_order.remove(i);
215
            let index = index.min(self.tag_order.len());
216
            self.tag_order.insert(index, tag);
217
        }
218
    }
219
220
    pub fn window(&self, w: WindowId) -> Option<&Window> {
221
        self.windows.get(w)
222
    }
223
224
    pub fn windows(&self) -> impl Iterator<Item = (WindowId, &Window)> {
225
        self.windows.iter()
226
    }
227
228
    pub fn output(&self, o: OutputId) -> Option<&Output> {
229
        self.outputs.get(o)
230
    }
231
232
    pub fn outputs(&self) -> impl Iterator<Item = (OutputId, &Output)> {
233
        self.outputs.iter()
234
    }
235
236
    pub fn scratchpads(&self) -> &[Scratchpad] {
237
        &self.scratchpads
238
    }
239
240
    pub fn active_output(&self) -> Option<OutputId> {
241
        self.active
242
    }
243
244
    pub fn set_active_output(&mut self, o: OutputId) {
245
        if self.outputs.contains_key(o) {
246
            self.active = Some(o);
247
        }
248
    }
249
250
    pub fn is_viewed(&self, o: OutputId, tag: TagId) -> bool {
251
        tag == self.homeless
252
            || self
253
                .outputs
254
                .get(o)
255
                .is_some_and(|out| out.viewed.contains(&tag))
256
    }
257
258
    /// Views `tag` alone, besides the homeless tag.
259
    pub fn view(&mut self, o: OutputId, tag: TagId) {
260
        let Some(out) = self.outputs.get_mut(o) else {
261
            return;
262
        };
263
        out.viewed.clear();
264
        if tag != self.homeless {
265
            out.viewed.push(tag);
266
        }
267
        self.tags[tag].urgent = false;
268
    }
269
270
    pub fn toggle_view(&mut self, o: OutputId, tag: TagId) {
271
        if tag == self.homeless {
272
            return;
273
        }
274
        let Some(out) = self.outputs.get_mut(o) else {
275
            return;
276
        };
277
        if let Some(i) = out.viewed.iter().position(|&t| t == tag) {
278
            out.viewed.remove(i);
279
        } else {
280
            out.viewed.push(tag);
281
            self.tags[tag].urgent = false;
282
        }
283
    }
284
285
    /// Brings `w`'s tag into view beside the others when `w` is the only
286
    /// window on it there.
287
    pub fn view_if_alone(&mut self, w: WindowId) {
288
        let Some(win) = self.windows.get(w) else {
289
            return;
290
        };
291
        let (Some(o), tag) = (win.output, win.tag) else {
292
            return;
293
        };
294
        if win.scratchpad.is_some() || self.is_viewed(o, tag) {
295
            return;
296
        }
297
        let alone = !self.windows.iter().any(|(x, v)| {
298
            x != w && v.output == Some(o) && v.tag == tag && v.scratchpad.is_none() && !v.hidden
299
        });
300
        if alone {
301
            self.toggle_view(o, tag);
302
        }
303
    }
304
305
    /// The tag a launch from `o` belongs to. The focused window's tag, else
306
    /// the first viewed tag, else homeless. Homeless is always on screen, so
307
    /// focusing one of its windows does not mean the user left their tag.
308
    pub fn launch_tag(&self, o: OutputId) -> TagId {
309
        self.focused_on(o)
310
            .map(|w| &self.windows[w])
311
            .filter(|w| w.scratchpad.is_none() && !w.sticky && w.tag != self.homeless)
312
            .map(|w| w.tag)
313
            .or_else(|| self.outputs.get(o)?.viewed.first().copied())
314
            .unwrap_or(self.homeless)
315
    }
316
317
    pub fn view_everywhere(&mut self, tag: TagId) {
318
        for o in self.outputs.keys().collect::<Vec<_>>() {
319
            self.view(o, tag);
320
        }
321
    }
322
323
    pub fn visible(&self, w: WindowId) -> bool {
324
        let Some(win) = self.windows.get(w) else {
325
            return false;
326
        };
327
        let Some(o) = win.output.filter(|_| !win.hidden) else {
328
            return false;
329
        };
330
        match win.scratchpad {
331
            Some(s) => {
332
                let sp = &self.scratchpads[s];
333
                sp.output == Some(o) && sp.shown.map(|i| sp.windows[i]) == Some(w)
334
            }
335
            None => win.sticky || self.is_viewed(o, win.tag),
336
        }
337
    }
338
339
    /// Adds a window on `output` (default the active one) and `tag` (default
340
    /// homeless). A window landing on a tag its output is not viewing marks
341
    /// the tag urgent.
342
    pub fn add_window(
343
        &mut self,
344
        output: Option<OutputId>,
345
        tag: Option<TagId>,
346
        floating: Option<Rect>,
347
    ) -> WindowId {
348
        let output = output
349
            .filter(|&o| self.outputs.contains_key(o))
350
            .or(self.active);
351
        let tag = tag
352
            .filter(|&t| self.tags.contains_key(t))
353
            .unwrap_or(self.homeless);
354
        let w = self.windows.insert(Window {
355
            output,
356
            tag,
357
            floating: floating.is_some(),
358
            float_rect: floating,
359
            float_default: false,
360
            fullscreen: false,
361
            parent: None,
362
            modal: false,
363
            sticky: false,
364
            scratchpad: None,
365
            urgent: false,
366
            hidden: false,
367
            evicted_from: None,
368
        });
369
        if let Some(o) = output {
370
            if !self.is_viewed(o, tag) {
371
                self.tags[tag].urgent = true;
372
            }
373
            self.place(w);
374
        }
375
        w
376
    }
377
378
    pub fn remove_window(&mut self, w: WindowId) {
379
        if !self.windows.contains_key(w) {
380
            return;
381
        }
382
        self.unplace(w);
383
        self.history.retain(|&h| h != w);
384
        self.modals -= usize::from(self.windows[w].modal);
385
        if let Some(s) = self.windows[w].scratchpad {
386
            self.leave_scratchpad(s, w);
387
        }
388
        for win in self.windows.values_mut() {
389
            if win.parent == Some(w) {
390
                win.parent = None;
391
            }
392
        }
393
        self.windows.remove(w);
394
    }
395
396
    /// Puts a window into its output's tree or floating stack. Tiled windows
397
    /// go next to the focused window if both are visible, else next to the
398
    /// latest window of their tag, else into a new row.
399
    fn place(&mut self, w: WindowId) {
400
        let win = &self.windows[w];
401
        let Some(o) = win.output else { return };
402
        if win.scratchpad.is_some() {
403
            return;
404
        }
405
        if win.floating {
406
            if win.float_rect.is_none() {
407
                let rect = centred(self.outputs[o].area, 0.6);
408
                self.windows[w].float_rect = Some(rect);
409
                self.windows[w].float_default = true;
410
            }
411
            self.outputs[o].floating.push(w);
412
            return;
413
        }
414
        let tag = win.tag;
415
        let tree = &self.outputs[o].tree;
416
        let focused = self
417
            .focused()
418
            .filter(|&f| tree.contains(f) && self.is_viewed(o, tag));
419
        let anchor = focused.or_else(|| {
420
            self.history
421
                .iter()
422
                .rev()
423
                .copied()
424
                .find(|&h| tree.contains(h) && self.windows[h].tag == tag)
425
        });
426
        let split = anchor
427
            .filter(|_| self.autotile)
428
            .and_then(|a| self.split_axis(o, a));
429
        let tree = &mut self.outputs[o].tree;
430
        match (anchor, split) {
431
            (Some(a), Some(axis)) => tree.insert_split(w, a, axis),
432
            (Some(a), None) => tree.insert_after(w, a),
433
            (None, _) => tree.insert_row(w),
434
        }
435
    }
436
437
    /// The axis a window opening beside `anchor` should split it along, the
438
    /// way the anchor is laid out right now. Hidden anchors have no shape.
439
    fn split_axis(&self, o: OutputId, anchor: WindowId) -> Option<Axis> {
440
        let rect = self
441
            .arrange(o)
442
            .tiled
443
            .iter()
444
            .find(|p| p.window == anchor && p.visible)?
445
            .rect;
446
        let axis = if rect.w > rect.h {
447
            Axis::Horizontal
448
        } else {
449
            Axis::Vertical
450
        };
451
        (rect.w > 0.0 && rect.h > 0.0).then_some(axis)
452
    }
453
454
    fn unplace(&mut self, w: WindowId) {
455
        let Some(o) = self.windows[w].output else {
456
            return;
457
        };
458
        let out = &mut self.outputs[o];
459
        out.tree.remove(w);
460
        out.floating.retain(|&f| f != w);
461
    }
462
463
    /// Focuses `w`, or the deepest modal dialog over it, which is returned.
464
    /// The windows between stay below it in the history, and a modal dialog
465
    /// focused on its own brings its parent up beneath it, so closing the
466
    /// dialog hands focus back to its parent.
467
    pub fn focus(&mut self, mut w: WindowId) -> Option<WindowId> {
468
        loop {
469
            let win = self.windows.get(w)?;
470
            self.active = win.output.or(self.active);
471
            if let Some(o) = win.output {
472
                let stack = &mut self.outputs[o].floating;
473
                if let Some(i) = stack.iter().position(|&f| f == w) {
474
                    stack.remove(i);
475
                    stack.push(w);
476
                }
477
            }
478
            let parent = win.parent.filter(|_| win.modal);
479
            self.history.retain(|&h| h != w);
480
            self.history.push(w);
481
            if let Some(p) = parent {
482
                self.history.retain(|&h| h != p);
483
                self.history.insert(self.history.len() - 1, p);
484
            }
485
            self.windows[w].urgent = false;
486
            match self.modal_child(w) {
487
                Some(child) => w = child,
488
                None => return Some(w),
489
            }
490
        }
491
    }
492
493
    /// Marks `w` as a modal dialog of its parent, or not.
494
    pub fn set_modal(&mut self, w: WindowId, modal: bool) {
495
        if let Some(win) = self.windows.get_mut(w)
496
            && std::mem::replace(&mut win.modal, modal) != modal
497
        {
498
            self.modals = if modal {
499
                self.modals + 1
500
            } else {
501
                self.modals - 1
502
            };
503
        }
504
    }
505
506
    /// The visible modal dialog of `w` on its output, the most recently
507
    /// focused if it has several.
508
    pub fn modal_child(&self, w: WindowId) -> Option<WindowId> {
509
        if self.modals == 0 {
510
            return None;
511
        }
512
        let output = self.windows.get(w)?.output;
513
        self.windows
514
            .iter()
515
            .filter(|&(c, win)| {
516
                win.modal && win.parent == Some(w) && win.output == output && self.visible(c)
517
            })
518
            .max_by_key(|&(c, _)| self.history.iter().rposition(|&h| h == c))
519
            .map(|(c, _)| c)
520
    }
521
522
    /// The window that takes focus aimed at `w`, the deepest modal dialog
523
    /// over it or `w` itself.
524
    pub fn modal_leaf(&self, mut w: WindowId) -> WindowId {
525
        while let Some(child) = self.modal_child(w) {
526
            w = child;
527
        }
528
        w
529
    }
530
531
    /// Whether focus aimed at `w` would change nothing.
532
    pub fn is_focused(&self, w: WindowId) -> bool {
533
        self.focused() == Some(self.modal_leaf(w))
534
    }
535
536
    /// The most recently focused visible window on the active output. Focus
537
    /// falling back to another output would leave keybinds acting on one
538
    /// output while the keyboard and pointer sit on another.
539
    pub fn focused(&self) -> Option<WindowId> {
540
        self.focused_on(self.active?)
541
    }
542
543
    /// The most recently focused visible window on `o`.
544
    pub fn focused_on(&self, o: OutputId) -> Option<WindowId> {
545
        self.history
546
            .iter()
547
            .rev()
548
            .copied()
549
            .find(|&w| self.windows[w].output == Some(o) && self.visible(w))
550
            .map(|w| self.modal_leaf(w))
551
    }
552
553
    /// Focuses the nearest visible window in `dir`, crossing to the next
554
    /// output when there is none on this one.
555
    pub fn focus_dir(&mut self, dir: Dir) -> Option<WindowId> {
556
        let o = self.active?;
557
        let current = self.focused_on(o);
558
        let from = current.and_then(|f| self.rect_of(f));
559
        let target = from.and_then(|from| {
560
            let arr = self.arrange(o);
561
            let reachable = |w| {
562
                arr.fullscreen
563
                    .is_none_or(|f| w == f || arr.over.contains(&w))
564
            };
565
            let candidates = arr
566
                .tiled
567
                .iter()
568
                .filter(|p| p.visible)
569
                .map(|p| (p.window, p.rect))
570
                .chain(arr.floating.iter().copied())
571
                .filter(|&(w, _)| Some(self.modal_leaf(w)) != current && reachable(w));
572
            nearest(from, dir, candidates)
573
        });
574
        if let Some(w) = target {
575
            return self.focus(w);
576
        }
577
        let next = self.output_towards(o, dir)?;
578
        self.active = Some(next);
579
        let w = self.focused_on(next);
580
        if let Some(w) = w {
581
            self.focus(w);
582
        }
583
        w
584
    }
585
586
    pub fn output_towards(&self, from: OutputId, dir: Dir) -> Option<OutputId> {
587
        let here = self.outputs.get(from)?.area;
588
        let others = self
589
            .outputs
590
            .iter()
591
            .filter(|&(id, _)| id != from)
592
            .map(|(id, out)| (id, out.area));
593
        nearest(here, dir, others)
594
    }
595
596
    fn rect_of(&self, w: WindowId) -> Option<Rect> {
597
        let o = self.windows.get(w)?.output?;
598
        let arr = self.arrange(o);
599
        arr.tiled
600
            .iter()
601
            .find(|p| p.window == w)
602
            .map(|p| p.rect)
603
            .or_else(|| arr.floating.iter().find(|f| f.0 == w).map(|f| f.1))
604
    }
605
606
    fn vis_on(&self, o: OutputId) -> impl Fn(WindowId) -> bool + '_ {
607
        move |w| self.windows[w].output == Some(o) && self.visible(w)
608
    }
609
610
    fn focused_tiled(&self) -> Option<(WindowId, OutputId)> {
611
        let w = self.focused()?;
612
        let o = self.windows[w].output?;
613
        self.outputs[o].tree.contains(w).then_some((w, o))
614
    }
615
616
    pub fn move_window(&mut self, dir: Dir) -> bool {
617
        let Some((w, o)) = self.focused_tiled() else {
618
            return false;
619
        };
620
        let mut tree = std::mem::take(&mut self.outputs[o].tree);
621
        let moved = tree.move_window(w, dir, self.vis_on(o));
622
        self.outputs[o].tree = tree;
623
        moved
624
    }
625
626
    pub fn move_container(&mut self, dir: Dir) -> bool {
627
        let Some((w, o)) = self.focused_tiled() else {
628
            return false;
629
        };
630
        let mut tree = std::mem::take(&mut self.outputs[o].tree);
631
        let moved = tree.move_container(w, dir, self.vis_on(o));
632
        self.outputs[o].tree = tree;
633
        moved
634
    }
635
636
    pub fn merge_window(&mut self, dir: Dir) -> bool {
637
        let Some((w, o)) = self.focused_tiled() else {
638
            return false;
639
        };
640
        let mut tree = std::mem::take(&mut self.outputs[o].tree);
641
        let merged = tree.merge_window(w, dir, self.vis_on(o));
642
        self.outputs[o].tree = tree;
643
        merged
644
    }
645
646
    /// Whether a tiled window fills its output through expansion.
647
    pub fn maximized(&self, w: WindowId) -> bool {
648
        let Some(o) = self.windows.get(w).and_then(|w| w.output) else {
649
            return false;
650
        };
651
        self.outputs[o].tree.maximized(w, self.vis_on(o))
652
    }
653
654
    pub fn resize(&mut self, axis: Axis, delta: f64) -> bool {
655
        let Some((w, o)) = self.focused_tiled() else {
656
            return false;
657
        };
658
        let mut tree = std::mem::take(&mut self.outputs[o].tree);
659
        let done = tree.resize(w, axis, delta, self.vis_on(o));
660
        self.outputs[o].tree = tree;
661
        done
662
    }
663
664
    /// Whether `w` is tiled with a visible window across the split on side `dir`.
665
    pub fn has_split(&self, w: WindowId, dir: Dir) -> bool {
666
        let Some(o) = self.windows.get(w).and_then(|w| w.output) else {
667
            return false;
668
        };
669
        self.outputs[o].tree.has_split(w, dir, self.vis_on(o))
670
    }
671
672
    /// Moves the split on side `dir` of the tiled window `w` by `px`, positive
673
    /// toward the right or bottom.
674
    pub fn move_split(&mut self, w: WindowId, dir: Dir, px: f64) -> bool {
675
        let Some(o) = self.windows.get(w).and_then(|w| w.output) else {
676
            return false;
677
        };
678
        let area = inset(self.outputs[o].usable(), self.gaps.outer);
679
        let mut tree = std::mem::take(&mut self.outputs[o].tree);
680
        let moved = tree.move_split(w, dir, px, area, self.gaps.inner, self.vis_on(o));
681
        self.outputs[o].tree = tree;
682
        moved
683
    }
684
685
    pub fn expand(&mut self, scope: ExpandScope) -> bool {
686
        let Some((w, o)) = self.focused_tiled() else {
687
            return false;
688
        };
689
        let (skip, count) = match scope {
690
            ExpandScope::Window => (0, 1),
691
            ExpandScope::Container => (1, 1),
692
            ExpandScope::All => (0, usize::MAX),
693
        };
694
        let mut tree = std::mem::take(&mut self.outputs[o].tree);
695
        let expanded = tree.toggle_expand(w, skip, count, self.vis_on(o));
696
        self.outputs[o].tree = tree;
697
        expanded
698
    }
699
700
    pub fn flip(&mut self, o: OutputId) {
701
        if let Some(out) = self.outputs.get_mut(o) {
702
            out.tree.flip();
703
        }
704
    }
705
706
    /// Retags a window. It keeps its slot and disappears if the new tag is
707
    /// not viewed.
708
    pub fn set_tag(&mut self, w: WindowId, tag: TagId) {
709
        if self.tags.contains_key(tag)
710
            && let Some(win) = self.windows.get_mut(w)
711
        {
712
            win.tag = tag;
713
        }
714
    }
715
716
    /// Moves a window to `tag` on `o`, marking the tag urgent when the window
717
    /// ends up out of sight.
718
    pub fn relocate(&mut self, w: WindowId, o: Option<OutputId>, tag: TagId) {
719
        if let Some(o) = o {
720
            self.send_to_output(w, o);
721
        }
722
        self.set_tag(w, tag);
723
        self.mark_urgent(w);
724
    }
725
726
    /// Flags a window that wants attention unless it already has the focus,
727
    /// and its tag too when the window is out of sight.
728
    pub fn mark_urgent(&mut self, w: WindowId) {
729
        if self.windows.get(w).is_none_or(|win| win.hidden) {
730
            return;
731
        }
732
        if self.focused() != Some(w) {
733
            self.windows[w].urgent = true;
734
        }
735
        if !self.visible(w) {
736
            let tag = self.windows[w].tag;
737
            self.tags[tag].urgent = true;
738
        }
739
    }
740
741
    /// Drops the flag of the window holding the focus, which can reach it
742
    /// without `focus`, when the window before it closes or its tag is viewed.
743
    pub fn clear_focused_urgent(&mut self) {
744
        if let Some(w) = self.focused() {
745
            self.windows[w].urgent = false;
746
        }
747
    }
748
749
    pub fn send_to_output(&mut self, w: WindowId, o: OutputId) {
750
        let Some(win) = self.windows.get(w) else {
751
            return;
752
        };
753
        if !self.outputs.contains_key(o) || win.output == Some(o) || win.scratchpad.is_some() {
754
            return;
755
        }
756
        let from = win.output.map(|f| self.outputs[f].usable());
757
        self.unplace(w);
758
        let win = &mut self.windows[w];
759
        if let (Some(from), Some(rect)) = (from, win.float_rect) {
760
            win.float_rect = Some(translate(rect, from, self.outputs[o].usable()));
761
        }
762
        win.output = Some(o);
763
        win.evicted_from = None;
764
        self.place(w);
765
    }
766
767
    /// Switches a window between tiled and floating. A scratchpad window
768
    /// leaves its scratchpad and tiles on the tag being viewed, since its own
769
    /// tag may well be hidden.
770
    pub fn toggle_floating(&mut self, w: WindowId) {
771
        let Some(win) = self.windows.get(w) else {
772
            return;
773
        };
774
        if let Some(s) = win.scratchpad {
775
            let o = win.output.or(self.active);
776
            let tag = o.map_or(self.homeless, |o| self.launch_tag(o));
777
            self.leave_scratchpad(s, w);
778
            let win = &mut self.windows[w];
779
            win.output = o;
780
            win.tag = tag;
781
            win.floating = false;
782
            self.place(w);
783
            return;
784
        }
785
        self.unplace(w);
786
        let win = &mut self.windows[w];
787
        win.floating = !win.floating;
788
        self.place(w);
789
    }
790
791
    pub fn set_float_rect(&mut self, w: WindowId, rect: Rect) {
792
        if let Some(win) = self.windows.get_mut(w) {
793
            win.float_rect = Some(rect);
794
            win.float_default = false;
795
        }
796
    }
797
798
    /// Places a float without settling its size, so a window still deciding
799
    /// on one is asked again after being tiled.
800
    pub fn hold_float_rect(&mut self, w: WindowId, rect: Rect) {
801
        if let Some(win) = self.windows.get_mut(w) {
802
            win.float_rect = Some(rect);
803
        }
804
    }
805
806
    pub fn toggle_fullscreen(&mut self, w: WindowId) {
807
        if let Some(win) = self.windows.get_mut(w) {
808
            win.fullscreen = !win.fullscreen;
809
        }
810
    }
811
812
    pub fn toggle_sticky(&mut self, w: WindowId) {
813
        if let Some(win) = self.windows.get_mut(w) {
814
            win.sticky = !win.sticky;
815
        }
816
    }
817
818
    /// Hides `w` or shows it again, keeping everything else about it.
819
    pub fn set_hidden(&mut self, w: WindowId, hidden: bool) {
820
        if let Some(win) = self.windows.get_mut(w) {
821
            win.hidden = hidden;
822
            win.urgent &= !hidden;
823
        }
824
    }
825
826
    /// Target geometry for everything on `o`, in output-local logical
827
    /// coordinates offset by the output's area.
828
    pub fn arrange(&self, o: OutputId) -> Arrangement {
829
        self.arrange_hiding(o, &[])
830
    }
831
832
    /// Like `arrange` with `hide` treated as hidden, which places them on the
833
    /// seeds they would grow from.
834
    pub fn arrange_hiding(&self, o: OutputId, hide: &[WindowId]) -> Arrangement {
835
        let Some(out) = self.outputs.get(o) else {
836
            return Arrangement::default();
837
        };
838
        let area = inset(out.usable(), self.gaps.outer);
839
        let shown = self.vis_on(o);
840
        let vis = &|w: WindowId| shown(w) && !hide.contains(&w);
841
        let tiled = out
842
            .tree
843
            .arrange(area, self.gaps.inner, vis)
844
            .into_iter()
845
            .map(|(window, rect)| Placed {
846
                window,
847
                rect,
848
                visible: vis(window),
849
            })
850
            .collect();
851
        let mut floating: Vec<(WindowId, Rect)> = out
852
            .floating
853
            .iter()
854
            .copied()
855
            .filter(|&w| vis(w))
856
            .filter_map(|w| Some((w, self.windows[w].float_rect?)))
857
            .collect();
858
        for sp in &self.scratchpads {
859
            if let Some(i) = sp.shown
860
                && sp.output == Some(o)
861
                && !self.windows[sp.windows[i]].hidden
862
                && let Some(r) = self.windows[sp.windows[i]].float_rect
863
            {
864
                floating.push((sp.windows[i], centre_in(out.usable(), r.w, r.h)));
865
            }
866
        }
867
        let is_fullscreen = |w: WindowId| self.windows[w].fullscreen && vis(w);
868
        let fullscreen = self
869
            .history
870
            .iter()
871
            .rev()
872
            .copied()
873
            .find(|&w| is_fullscreen(w))
874
            .or_else(|| self.windows.keys().find(|&w| is_fullscreen(w)));
875
        let over = fullscreen
876
            .map(|f| {
877
                floating
878
                    .iter()
879
                    .map(|&(w, _)| w)
880
                    .filter(|&w| {
881
                        w != f && (self.descends(w, f) || self.windows[w].scratchpad.is_some())
882
                    })
883
                    .collect()
884
            })
885
            .unwrap_or_default();
886
        Arrangement {
887
            tiled,
888
            floating,
889
            fullscreen,
890
            over,
891
        }
892
    }
893
894
    /// Records that `w` is a transient of `parent`.
895
    pub fn set_parent(&mut self, w: WindowId, parent: Option<WindowId>) {
896
        if parent.is_some_and(|p| p == w || self.descends(p, w)) {
897
            return;
898
        }
899
        if let Some(win) = self.windows.get_mut(w) {
900
            win.parent = parent;
901
        }
902
    }
903
904
    fn descends(&self, mut w: WindowId, of: WindowId) -> bool {
905
        for _ in 0..self.windows.len() {
906
            match self.windows.get(w).and_then(|x| x.parent) {
907
                Some(p) if p == of => return true,
908
                Some(p) => w = p,
909
                None => return false,
910
            }
911
        }
912
        false
913
    }
914
915
    /// Moves focus to a fullscreen `w` when it covers the focused window,
916
    /// unless that is one of its own transients.
917
    pub fn focus_if_covering(&mut self, w: WindowId) {
918
        let Some(win) = self.windows.get(w).filter(|win| win.fullscreen) else {
919
            return;
920
        };
921
        let covers = self.focused().is_some_and(|f| {
922
            f != w && self.windows[f].output == win.output && !self.descends(f, w)
923
        });
924
        if covers && self.visible(w) {
925
            self.focus(w);
926
        }
927
    }
928
929
    /// Focuses `w` unless it is out of sight or a fullscreen window hides it,
930
    /// flagging it urgent then. Returns whether it took the focus.
931
    pub fn focus_unless_covered(&mut self, w: WindowId) -> bool {
932
        if self.visible(w) && !self.covered(w) {
933
            self.focus(w);
934
            return true;
935
        }
936
        self.mark_urgent(w);
937
        false
938
    }
939
940
    /// Whether a fullscreen window on `w`'s output hides it. The fullscreen
941
    /// window's transients and shown scratchpads are not hidden, and a window
942
    /// that is itself fullscreen takes over.
943
    pub fn covered(&self, w: WindowId) -> bool {
944
        let Some(win) = self.windows.get(w) else {
945
            return false;
946
        };
947
        let Some(o) = win.output else {
948
            return false;
949
        };
950
        let arr = self.arrange(o);
951
        !win.fullscreen && arr.fullscreen.is_some_and(|f| f != w) && !arr.over.contains(&w)
952
    }
953
954
    #[cfg(test)]
955
    pub(crate) fn check(&self) {
956
        for (o, out) in &self.outputs {
957
            out.tree.check();
958
            for w in out.tree.windows() {
959
                let win = &self.windows[w];
960
                assert_eq!(win.output, Some(o));
961
                assert!(!win.floating && win.scratchpad.is_none());
962
            }
963
            for &w in &out.floating {
964
                assert_eq!(self.windows[w].output, Some(o));
965
                assert!(self.windows[w].floating);
966
            }
967
        }
968
        for (w, win) in &self.windows {
969
            let homes = self
970
                .outputs
971
                .values()
972
                .filter(|out| out.tree.contains(w) || out.floating.contains(&w))
973
                .count();
974
            let expected = usize::from(win.output.is_some() && win.scratchpad.is_none());
975
            assert_eq!(homes, expected, "window placed {homes} times");
976
        }
977
    }
978
}
979
980
fn nearest<K: Copy>(
981
    from: Rect,
982
    dir: Dir,
983
    candidates: impl Iterator<Item = (K, Rect)>,
984
) -> Option<K> {
985
    const TOL: f64 = 0.5;
986
    let score = |r: Rect| -> Option<(bool, f64, f64)> {
987
        let (gap, overlap, offset) = match dir {
988
            Dir::Right => (
989
                r.x - from.right(),
990
                span_overlap(from.y, from.h, r.y, r.h),
991
                r.center_y() - from.center_y(),
992
            ),
993
            Dir::Left => (
994
                from.x - r.right(),
995
                span_overlap(from.y, from.h, r.y, r.h),
996
                r.center_y() - from.center_y(),
997
            ),
998
            Dir::Down => (
999
                r.y - from.bottom(),
1000
                span_overlap(from.x, from.w, r.x, r.w),
1001
                r.center_x() - from.center_x(),
1002
            ),
1003
            Dir::Up => (
1004
                from.y - r.bottom(),
1005
                span_overlap(from.x, from.w, r.x, r.w),
1006
                r.center_x() - from.center_x(),
1007
            ),
1008
        };
1009
        (gap > -TOL).then_some((overlap <= 0.0, gap.max(0.0), offset.abs()))
1010
    };
1011
    candidates
1012
        .filter_map(|(k, r)| score(r).map(|s| (k, s)))
1013
        .min_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal))
1014
        .map(|(k, _)| k)
1015
}
1016
1017
fn span_overlap(a: f64, al: f64, b: f64, bl: f64) -> f64 {
1018
    (a + al).min(b + bl) - a.max(b)
1019
}
1020
1021
fn inset(r: Rect, by: f64) -> Rect {
1022
    Rect::new(
1023
        r.x + by,
1024
        r.y + by,
1025
        (r.w - 2.0 * by).max(0.0),
1026
        (r.h - 2.0 * by).max(0.0),
1027
    )
1028
}
1029
1030
fn centred(area: Rect, frac: f64) -> Rect {
1031
    centre_in(area, area.w * frac, area.h * frac)
1032
}
1033
1034
/// A w by h rect centred in area, shrunk to fit it.
1035
pub(crate) fn centre_in(area: Rect, w: f64, h: f64) -> Rect {
1036
    let (w, h) = (w.min(area.w), h.min(area.h));
1037
    Rect::new(
1038
        area.x + (area.w - w) / 2.0,
1039
        area.y + (area.h - h) / 2.0,
1040
        w,
1041
        h,
1042
    )
1043
}
1044
1045
/// The smallest a floating window gets when dragged or rescaled.
1046
pub const MIN_FLOAT_SIZE: f64 = 32.0;
1047
1048
/// How much of a floating window stays reachable when it is larger than
1049
/// the area it lives in.
1050
const STRIP: f64 = 64.0;
1051
1052
/// Moves a floating rect to keep it reachable inside bounds. A window that
1053
/// fits stays whole inside, a larger one keeps its top edge and a strip.
1054
pub fn clamp_float(r: Rect, bounds: Rect) -> Rect {
1055
    let x = if r.w <= bounds.w {
1056
        r.x.clamp(bounds.x, bounds.right() - r.w)
1057
    } else {
1058
        let strip = STRIP.min(bounds.w);
1059
        r.x.clamp(bounds.x + strip - r.w, bounds.right() - strip)
1060
    };
1061
    let y = if r.h <= bounds.h {
1062
        r.y.clamp(bounds.y, bounds.bottom() - r.h)
1063
    } else {
1064
        r.y.clamp(bounds.y, bounds.bottom() - STRIP.min(bounds.h))
1065
    };
1066
    Rect::new(x, y, r.w, r.h)
1067
}
1068
1069
/// Keeps a floating rect at the same relative spot and size when the area
1070
/// it lives in changes.
1071
fn translate(r: Rect, from: Rect, to: Rect) -> Rect {
1072
    if to.w <= 0.0 || to.h <= 0.0 {
1073
        return r;
1074
    }
1075
    let sx = if from.w > 0.0 { to.w / from.w } else { 1.0 };
1076
    let sy = if from.h > 0.0 { to.h / from.h } else { 1.0 };
1077
    let scaled = Rect::new(
1078
        to.x + (r.x - from.x) * sx,
1079
        to.y + (r.y - from.y) * sy,
1080
        (r.w * sx).max(MIN_FLOAT_SIZE),
1081
        (r.h * sy).max(MIN_FLOAT_SIZE),
1082
    );
1083
    clamp_float(scaled, to)
1084
}