atagen

monolith

public
Star0
Watch0
9baaafa4b167e25d7cb218cd600ac24cd2a18f4b
1
ssh://brewery@pls.lobotomise.me:33/atagen/monolith.git
crates/layout/src/lib.rsRust908 lines26.7 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 tree;
6
7
#[cfg(test)]
8
mod tests;
9
10
pub use monolith_planner::Rect;
11
pub use tree::{Axis, Dir, Tree};
12
13
use slotmap::{SlotMap, new_key_type};
14
use std::collections::HashMap;
15
16
new_key_type! {
17
    pub struct WindowId;
18
    pub struct TagId;
19
    pub struct OutputId;
20
}
21
22
pub const HOMELESS: &str = "homeless";
23
24
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25
pub enum ExpandScope {
26
    Window,
27
    Block,
28
    All,
29
}
30
31
#[derive(Clone, Copy, Debug, PartialEq)]
32
pub struct Gaps {
33
    pub inner: f64,
34
    pub outer: f64,
35
}
36
37
impl Default for Gaps {
38
    fn default() -> Self {
39
        Self {
40
            inner: 8.0,
41
            outer: 8.0,
42
        }
43
    }
44
}
45
46
#[derive(Clone, Debug)]
47
pub struct Window {
48
    pub output: Option<OutputId>,
49
    pub tag: TagId,
50
    pub floating: bool,
51
    pub float_rect: Option<Rect>,
52
    pub fullscreen: bool,
53
    pub sticky: bool,
54
    pub scratchpad: Option<usize>,
55
    evicted_from: Option<String>,
56
}
57
58
#[derive(Clone, Debug)]
59
pub struct Tag {
60
    pub name: String,
61
    pub urgent: bool,
62
}
63
64
#[derive(Clone, Debug)]
65
pub struct Output {
66
    pub name: String,
67
    pub area: Rect,
68
    pub tree: Tree<WindowId>,
69
    /// Viewed tags besides the homeless tag, which is always viewed.
70
    pub viewed: Vec<TagId>,
71
    /// Floating windows, bottom to top.
72
    pub floating: Vec<WindowId>,
73
}
74
75
#[derive(Clone, Debug)]
76
pub struct Scratchpad {
77
    pub name: String,
78
    pub windows: Vec<WindowId>,
79
    pub shown: Option<usize>,
80
    pub output: Option<OutputId>,
81
}
82
83
#[derive(Clone, Debug)]
84
struct Parked {
85
    tree: Tree<WindowId>,
86
    viewed: Vec<TagId>,
87
    floating: Vec<WindowId>,
88
    area: Rect,
89
}
90
91
#[derive(Clone, Debug, Default)]
92
pub struct Arrangement {
93
    /// Every tiled window on the output. Hidden ones are zero-size seeds.
94
    pub tiled: Vec<Placed>,
95
    /// Visible floating windows and shown scratchpads, bottom to top.
96
    pub floating: Vec<(WindowId, Rect)>,
97
    pub fullscreen: Option<WindowId>,
98
}
99
100
#[derive(Clone, Copy, Debug)]
101
pub struct Placed {
102
    pub window: WindowId,
103
    pub rect: Rect,
104
    pub visible: bool,
105
}
106
107
#[derive(Clone, Debug)]
108
pub struct Layout {
109
    windows: SlotMap<WindowId, Window>,
110
    tags: SlotMap<TagId, Tag>,
111
    tag_order: Vec<TagId>,
112
    homeless: TagId,
113
    outputs: SlotMap<OutputId, Output>,
114
    active: Option<OutputId>,
115
    /// Focus history, most recent last.
116
    history: Vec<WindowId>,
117
    scratchpads: Vec<Scratchpad>,
118
    last_scratchpad: Option<usize>,
119
    parked: HashMap<String, Parked>,
120
    pub gaps: Gaps,
121
}
122
123
impl Default for Layout {
124
    fn default() -> Self {
125
        let mut tags = SlotMap::with_key();
126
        let homeless = tags.insert(Tag {
127
            name: HOMELESS.into(),
128
            urgent: false,
129
        });
130
        Self {
131
            windows: SlotMap::with_key(),
132
            tags,
133
            tag_order: vec![homeless],
134
            homeless,
135
            outputs: SlotMap::with_key(),
136
            active: None,
137
            history: Vec::new(),
138
            scratchpads: Vec::new(),
139
            last_scratchpad: None,
140
            parked: HashMap::new(),
141
            gaps: Gaps::default(),
142
        }
143
    }
144
}
145
146
impl Layout {
147
    pub fn homeless(&self) -> TagId {
148
        self.homeless
149
    }
150
151
    /// Looks a tag up by name, creating it at the end of the order.
152
    pub fn tag(&mut self, name: &str) -> TagId {
153
        if let Some(id) = self.tag_id(name) {
154
            return id;
155
        }
156
        let id = self.tags.insert(Tag {
157
            name: name.into(),
158
            urgent: false,
159
        });
160
        self.tag_order.push(id);
161
        id
162
    }
163
164
    pub fn tag_id(&self, name: &str) -> Option<TagId> {
165
        self.tag_order
166
            .iter()
167
            .copied()
168
            .find(|&t| self.tags[t].name == name)
169
    }
170
171
    pub fn tags(&self) -> impl Iterator<Item = (TagId, &Tag)> {
172
        self.tag_order.iter().map(|&t| (t, &self.tags[t]))
173
    }
174
175
    pub fn reorder_tag(&mut self, tag: TagId, index: usize) {
176
        if let Some(i) = self.tag_order.iter().position(|&t| t == tag) {
177
            self.tag_order.remove(i);
178
            let index = index.min(self.tag_order.len());
179
            self.tag_order.insert(index, tag);
180
        }
181
    }
182
183
    pub fn window(&self, w: WindowId) -> Option<&Window> {
184
        self.windows.get(w)
185
    }
186
187
    pub fn windows(&self) -> impl Iterator<Item = (WindowId, &Window)> {
188
        self.windows.iter()
189
    }
190
191
    pub fn output(&self, o: OutputId) -> Option<&Output> {
192
        self.outputs.get(o)
193
    }
194
195
    pub fn outputs(&self) -> impl Iterator<Item = (OutputId, &Output)> {
196
        self.outputs.iter()
197
    }
198
199
    pub fn scratchpads(&self) -> &[Scratchpad] {
200
        &self.scratchpads
201
    }
202
203
    pub fn active_output(&self) -> Option<OutputId> {
204
        self.active
205
    }
206
207
    pub fn set_active_output(&mut self, o: OutputId) {
208
        if self.outputs.contains_key(o) {
209
            self.active = Some(o);
210
        }
211
    }
212
213
    /// Adds an output. One that was unplugged before gets back its tree,
214
    /// views and the windows that had to leave it.
215
    pub fn add_output(&mut self, name: &str, area: Rect) -> OutputId {
216
        let id = self.outputs.insert(Output {
217
            name: name.into(),
218
            area,
219
            tree: Tree::default(),
220
            viewed: Vec::new(),
221
            floating: Vec::new(),
222
        });
223
        if let Some(parked) = self.parked.remove(name) {
224
            self.restore(id, parked);
225
        }
226
        self.active.get_or_insert(id);
227
        let detached: Vec<WindowId> = self
228
            .windows
229
            .iter()
230
            .filter(|(_, w)| w.output.is_none())
231
            .map(|(id, _)| id)
232
            .collect();
233
        for w in detached {
234
            self.windows[w].output = Some(id);
235
            self.place(w);
236
        }
237
        id
238
    }
239
240
    fn restore(&mut self, id: OutputId, parked: Parked) {
241
        let name = self.outputs[id].name.clone();
242
        let ours = |l: &Self, w: WindowId| {
243
            l.windows
244
                .get(w)
245
                .is_some_and(|x| x.evicted_from.as_deref() == Some(&name) && x.scratchpad.is_none())
246
        };
247
        let mut tree = parked.tree;
248
        tree.retain(|w| ours(self, w) && !self.windows[w].floating);
249
        let floating: Vec<WindowId> = parked
250
            .floating
251
            .into_iter()
252
            .filter(|&w| ours(self, w) && self.windows[w].floating)
253
            .collect();
254
        for w in tree
255
            .windows()
256
            .chain(floating.iter().copied())
257
            .collect::<Vec<_>>()
258
        {
259
            self.unplace(w);
260
            let win = &mut self.windows[w];
261
            if let (Some(from), Some(rect)) = (win.output, win.float_rect) {
262
                win.float_rect = Some(translate(rect, self.outputs[from].area, parked.area));
263
            }
264
            win.output = Some(id);
265
            win.evicted_from = None;
266
        }
267
        let out = &mut self.outputs[id];
268
        out.tree = tree;
269
        out.floating = floating;
270
        out.viewed = parked
271
            .viewed
272
            .into_iter()
273
            .filter(|&t| self.tags.contains_key(t))
274
            .collect();
275
    }
276
277
    /// Removes an output. Its windows move to an output viewing their tag,
278
    /// or the active one, and remember where they came from.
279
    pub fn remove_output(&mut self, o: OutputId) {
280
        let Some(out) = self.outputs.remove(o) else {
281
            return;
282
        };
283
        self.parked.insert(
284
            out.name.clone(),
285
            Parked {
286
                tree: out.tree,
287
                viewed: out.viewed,
288
                floating: out.floating,
289
                area: out.area,
290
            },
291
        );
292
        if self.active == Some(o) {
293
            self.active = self.outputs.keys().next();
294
        }
295
        for sp in &mut self.scratchpads {
296
            if sp.output == Some(o) {
297
                sp.output = self.active;
298
            }
299
        }
300
        let leaving: Vec<WindowId> = self
301
            .windows
302
            .iter()
303
            .filter(|(_, w)| w.output == Some(o))
304
            .map(|(id, _)| id)
305
            .collect();
306
        for w in leaving {
307
            let tag = self.windows[w].tag;
308
            let target = self
309
                .outputs
310
                .keys()
311
                .find(|&t| self.is_viewed(t, tag))
312
                .or(self.active);
313
            let win = &mut self.windows[w];
314
            if let (Some(t), Some(rect)) = (target, win.float_rect) {
315
                win.float_rect = Some(translate(rect, out.area, self.outputs[t].area));
316
            }
317
            win.output = target;
318
            if win.scratchpad.is_some() {
319
                continue;
320
            }
321
            win.evicted_from = Some(out.name.clone());
322
            if target.is_some() {
323
                self.place(w);
324
            }
325
        }
326
    }
327
328
    pub fn set_output_area(&mut self, o: OutputId, area: Rect) {
329
        if let Some(out) = self.outputs.get_mut(o) {
330
            out.area = area;
331
        }
332
    }
333
334
    pub fn is_viewed(&self, o: OutputId, tag: TagId) -> bool {
335
        tag == self.homeless
336
            || self
337
                .outputs
338
                .get(o)
339
                .is_some_and(|out| out.viewed.contains(&tag))
340
    }
341
342
    /// Views `tag` alone, besides the homeless tag.
343
    pub fn view(&mut self, o: OutputId, tag: TagId) {
344
        let Some(out) = self.outputs.get_mut(o) else {
345
            return;
346
        };
347
        out.viewed.clear();
348
        if tag != self.homeless {
349
            out.viewed.push(tag);
350
        }
351
        self.tags[tag].urgent = false;
352
    }
353
354
    pub fn toggle_view(&mut self, o: OutputId, tag: TagId) {
355
        if tag == self.homeless {
356
            return;
357
        }
358
        let Some(out) = self.outputs.get_mut(o) else {
359
            return;
360
        };
361
        if let Some(i) = out.viewed.iter().position(|&t| t == tag) {
362
            out.viewed.remove(i);
363
        } else {
364
            out.viewed.push(tag);
365
            self.tags[tag].urgent = false;
366
        }
367
    }
368
369
    pub fn view_everywhere(&mut self, tag: TagId) {
370
        for o in self.outputs.keys().collect::<Vec<_>>() {
371
            self.view(o, tag);
372
        }
373
    }
374
375
    pub fn visible(&self, w: WindowId) -> bool {
376
        let Some(win) = self.windows.get(w) else {
377
            return false;
378
        };
379
        let Some(o) = win.output else {
380
            return false;
381
        };
382
        match win.scratchpad {
383
            Some(s) => {
384
                let sp = &self.scratchpads[s];
385
                sp.output == Some(o) && sp.shown.map(|i| sp.windows[i]) == Some(w)
386
            }
387
            None => win.sticky || self.is_viewed(o, win.tag),
388
        }
389
    }
390
391
    /// Adds a window on `output` (default the active one) and `tag` (default
392
    /// homeless). A window landing on a tag its output is not viewing marks
393
    /// the tag urgent.
394
    pub fn add_window(
395
        &mut self,
396
        output: Option<OutputId>,
397
        tag: Option<TagId>,
398
        floating: Option<Rect>,
399
    ) -> WindowId {
400
        let output = output
401
            .filter(|&o| self.outputs.contains_key(o))
402
            .or(self.active);
403
        let tag = tag
404
            .filter(|&t| self.tags.contains_key(t))
405
            .unwrap_or(self.homeless);
406
        let w = self.windows.insert(Window {
407
            output,
408
            tag,
409
            floating: floating.is_some(),
410
            float_rect: floating,
411
            fullscreen: false,
412
            sticky: false,
413
            scratchpad: None,
414
            evicted_from: None,
415
        });
416
        if let Some(o) = output {
417
            if !self.is_viewed(o, tag) {
418
                self.tags[tag].urgent = true;
419
            }
420
            self.place(w);
421
        }
422
        w
423
    }
424
425
    pub fn remove_window(&mut self, w: WindowId) {
426
        if !self.windows.contains_key(w) {
427
            return;
428
        }
429
        self.unplace(w);
430
        self.history.retain(|&h| h != w);
431
        if let Some(s) = self.windows[w].scratchpad {
432
            self.leave_scratchpad(s, w);
433
        }
434
        self.windows.remove(w);
435
    }
436
437
    /// Puts a window into its output's tree or floating stack. Tiled windows
438
    /// go next to the focused window if both are visible, else next to the
439
    /// latest window of their tag, else into a new row.
440
    fn place(&mut self, w: WindowId) {
441
        let win = &self.windows[w];
442
        let Some(o) = win.output else { return };
443
        if win.scratchpad.is_some() {
444
            return;
445
        }
446
        if win.floating {
447
            if win.float_rect.is_none() {
448
                let rect = centred(self.outputs[o].area, 0.6);
449
                self.windows[w].float_rect = Some(rect);
450
            }
451
            self.outputs[o].floating.push(w);
452
            return;
453
        }
454
        let tag = win.tag;
455
        let tree = &self.outputs[o].tree;
456
        let focused = self
457
            .focused()
458
            .filter(|&f| tree.contains(f) && self.is_viewed(o, tag));
459
        let anchor = focused.or_else(|| {
460
            self.history
461
                .iter()
462
                .rev()
463
                .copied()
464
                .find(|&h| tree.contains(h) && self.windows[h].tag == tag)
465
        });
466
        let tree = &mut self.outputs[o].tree;
467
        match anchor {
468
            Some(a) => tree.insert_after(w, a),
469
            None => tree.insert_row(w),
470
        }
471
    }
472
473
    fn unplace(&mut self, w: WindowId) {
474
        let Some(o) = self.windows[w].output else {
475
            return;
476
        };
477
        let out = &mut self.outputs[o];
478
        out.tree.remove(w);
479
        out.floating.retain(|&f| f != w);
480
    }
481
482
    pub fn focus(&mut self, w: WindowId) {
483
        let Some(win) = self.windows.get(w) else {
484
            return;
485
        };
486
        self.active = win.output.or(self.active);
487
        if let Some(o) = win.output {
488
            let stack = &mut self.outputs[o].floating;
489
            if let Some(i) = stack.iter().position(|&f| f == w) {
490
                stack.remove(i);
491
                stack.push(w);
492
            }
493
        }
494
        self.history.retain(|&h| h != w);
495
        self.history.push(w);
496
    }
497
498
    /// The most recently focused visible window.
499
    pub fn focused(&self) -> Option<WindowId> {
500
        self.history
501
            .iter()
502
            .rev()
503
            .copied()
504
            .find(|&w| self.visible(w))
505
    }
506
507
    /// The most recently focused visible window on `o`.
508
    pub fn focused_on(&self, o: OutputId) -> Option<WindowId> {
509
        self.history
510
            .iter()
511
            .rev()
512
            .copied()
513
            .find(|&w| self.windows[w].output == Some(o) && self.visible(w))
514
    }
515
516
    /// Focuses the nearest visible window in `dir`, crossing to the next
517
    /// output when there is none on this one.
518
    pub fn focus_dir(&mut self, dir: Dir) -> Option<WindowId> {
519
        let o = self.active?;
520
        let from = self.focused_on(o).and_then(|f| self.rect_of(f));
521
        let target = from.and_then(|from| {
522
            let arr = self.arrange(o);
523
            let candidates = arr
524
                .tiled
525
                .iter()
526
                .filter(|p| p.visible)
527
                .map(|p| (p.window, p.rect))
528
                .chain(arr.floating.iter().copied())
529
                .filter(|&(w, _)| Some(w) != self.focused_on(o));
530
            nearest(from, dir, candidates)
531
        });
532
        if let Some(w) = target {
533
            self.focus(w);
534
            return Some(w);
535
        }
536
        let here = self.outputs[o].area;
537
        let next = nearest(
538
            here,
539
            dir,
540
            self.outputs.iter().map(|(id, out)| (id, out.area)),
541
        )?;
542
        self.active = Some(next);
543
        let w = self.focused_on(next);
544
        if let Some(w) = w {
545
            self.focus(w);
546
        }
547
        w
548
    }
549
550
    fn rect_of(&self, w: WindowId) -> Option<Rect> {
551
        let o = self.windows.get(w)?.output?;
552
        let arr = self.arrange(o);
553
        arr.tiled
554
            .iter()
555
            .find(|p| p.window == w)
556
            .map(|p| p.rect)
557
            .or_else(|| arr.floating.iter().find(|f| f.0 == w).map(|f| f.1))
558
    }
559
560
    fn vis_on(&self, o: OutputId) -> impl Fn(WindowId) -> bool + '_ {
561
        move |w| self.windows[w].output == Some(o) && self.visible(w)
562
    }
563
564
    fn focused_tiled(&self) -> Option<(WindowId, OutputId)> {
565
        let w = self.focused()?;
566
        let o = self.windows[w].output?;
567
        self.outputs[o].tree.contains(w).then_some((w, o))
568
    }
569
570
    pub fn move_window(&mut self, dir: Dir) -> bool {
571
        let Some((w, o)) = self.focused_tiled() else {
572
            return false;
573
        };
574
        let mut tree = std::mem::take(&mut self.outputs[o].tree);
575
        let moved = tree.move_window(w, dir, self.vis_on(o));
576
        self.outputs[o].tree = tree;
577
        moved
578
    }
579
580
    pub fn move_block(&mut self, dir: Dir) -> bool {
581
        let Some((w, o)) = self.focused_tiled() else {
582
            return false;
583
        };
584
        let mut tree = std::mem::take(&mut self.outputs[o].tree);
585
        let moved = tree.move_block(w, dir, self.vis_on(o));
586
        self.outputs[o].tree = tree;
587
        moved
588
    }
589
590
    pub fn resize(&mut self, axis: Axis, delta: f64) -> bool {
591
        let Some((w, o)) = self.focused_tiled() else {
592
            return false;
593
        };
594
        let mut tree = std::mem::take(&mut self.outputs[o].tree);
595
        let done = tree.resize(w, axis, delta, self.vis_on(o));
596
        self.outputs[o].tree = tree;
597
        done
598
    }
599
600
    pub fn expand(&mut self, scope: ExpandScope) -> bool {
601
        let Some((w, o)) = self.focused_tiled() else {
602
            return false;
603
        };
604
        let (skip, count) = match scope {
605
            ExpandScope::Window => (0, 1),
606
            ExpandScope::Block => (1, 1),
607
            ExpandScope::All => (0, usize::MAX),
608
        };
609
        self.outputs[o].tree.toggle_expand(w, skip, count)
610
    }
611
612
    pub fn flip(&mut self, o: OutputId) {
613
        if let Some(out) = self.outputs.get_mut(o) {
614
            out.tree.flip();
615
        }
616
    }
617
618
    /// Retags a window. It keeps its slot and disappears if the new tag is
619
    /// not viewed.
620
    pub fn set_tag(&mut self, w: WindowId, tag: TagId) {
621
        if self.tags.contains_key(tag)
622
            && let Some(win) = self.windows.get_mut(w)
623
        {
624
            win.tag = tag;
625
        }
626
    }
627
628
    pub fn send_to_output(&mut self, w: WindowId, o: OutputId) {
629
        let Some(win) = self.windows.get(w) else {
630
            return;
631
        };
632
        if !self.outputs.contains_key(o) || win.output == Some(o) || win.scratchpad.is_some() {
633
            return;
634
        }
635
        let from = win.output.map(|f| self.outputs[f].area);
636
        self.unplace(w);
637
        let win = &mut self.windows[w];
638
        if let (Some(from), Some(rect)) = (from, win.float_rect) {
639
            win.float_rect = Some(translate(rect, from, self.outputs[o].area));
640
        }
641
        win.output = Some(o);
642
        win.evicted_from = None;
643
        self.place(w);
644
    }
645
646
    pub fn toggle_floating(&mut self, w: WindowId) {
647
        let Some(win) = self.windows.get(w) else {
648
            return;
649
        };
650
        if win.scratchpad.is_some() {
651
            return;
652
        }
653
        self.unplace(w);
654
        let win = &mut self.windows[w];
655
        win.floating = !win.floating;
656
        self.place(w);
657
    }
658
659
    pub fn set_float_rect(&mut self, w: WindowId, rect: Rect) {
660
        if let Some(win) = self.windows.get_mut(w) {
661
            win.float_rect = Some(rect);
662
        }
663
    }
664
665
    pub fn toggle_fullscreen(&mut self, w: WindowId) {
666
        if let Some(win) = self.windows.get_mut(w) {
667
            win.fullscreen = !win.fullscreen;
668
        }
669
    }
670
671
    pub fn toggle_sticky(&mut self, w: WindowId) {
672
        if let Some(win) = self.windows.get_mut(w) {
673
            win.sticky = !win.sticky;
674
        }
675
    }
676
677
    /// Adds a window to a named scratchpad, creating it. Scratchpad windows
678
    /// float and are shown only by summoning.
679
    pub fn scratchpad_add(&mut self, w: WindowId, name: &str) {
680
        let Some(win) = self.windows.get(w) else {
681
            return;
682
        };
683
        if let Some(s) = win.scratchpad {
684
            self.leave_scratchpad(s, w);
685
        }
686
        self.unplace(w);
687
        let s = match self.scratchpads.iter().position(|sp| sp.name == name) {
688
            Some(s) => s,
689
            None => {
690
                self.scratchpads.push(Scratchpad {
691
                    name: name.into(),
692
                    windows: Vec::new(),
693
                    shown: None,
694
                    output: None,
695
                });
696
                self.scratchpads.len() - 1
697
            }
698
        };
699
        self.scratchpads[s].windows.push(w);
700
        let area = self.windows[w].output.map(|o| self.outputs[o].area);
701
        let win = &mut self.windows[w];
702
        win.scratchpad = Some(s);
703
        win.floating = true;
704
        if win.float_rect.is_none() {
705
            win.float_rect = area.map(|a| centred(a, 0.6));
706
        }
707
    }
708
709
    /// Cycles a scratchpad through off, each window, and off again, on the
710
    /// active output.
711
    pub fn summon(&mut self, name: &str) -> Option<WindowId> {
712
        let s = self.scratchpads.iter().position(|sp| sp.name == name)?;
713
        let o = self.active?;
714
        let sp = &mut self.scratchpads[s];
715
        let next = match sp.shown {
716
            None => 0,
717
            Some(i) => i + 1,
718
        };
719
        if next >= sp.windows.len() {
720
            sp.shown = None;
721
            return None;
722
        }
723
        let from = sp.output.map(|f| self.outputs[f].area);
724
        sp.shown = Some(next);
725
        sp.output = Some(o);
726
        let w = sp.windows[next];
727
        self.last_scratchpad = Some(s);
728
        let area = self.outputs[o].area;
729
        let win = &mut self.windows[w];
730
        if win.output != Some(o) {
731
            win.float_rect = match (from, win.float_rect) {
732
                (Some(from), Some(r)) => Some(translate(r, from, area)),
733
                _ => Some(centred(area, 0.6)),
734
            };
735
            win.output = Some(o);
736
        }
737
        self.focus(w);
738
        Some(w)
739
    }
740
741
    /// Hides a scratchpad, by default the last one summoned.
742
    pub fn dismiss(&mut self, name: Option<&str>) {
743
        let s = match name {
744
            Some(name) => self.scratchpads.iter().position(|sp| sp.name == name),
745
            None => self.last_scratchpad,
746
        };
747
        if let Some(sp) = s.and_then(|s| self.scratchpads.get_mut(s)) {
748
            sp.shown = None;
749
        }
750
    }
751
752
    fn leave_scratchpad(&mut self, s: usize, w: WindowId) {
753
        let sp = &mut self.scratchpads[s];
754
        let Some(i) = sp.windows.iter().position(|&x| x == w) else {
755
            return;
756
        };
757
        sp.windows.remove(i);
758
        sp.shown = match sp.shown {
759
            Some(j) if j == i => None,
760
            Some(j) if j > i => Some(j - 1),
761
            other => other,
762
        };
763
        self.windows[w].scratchpad = None;
764
    }
765
766
    /// Target geometry for everything on `o`, in output-local logical
767
    /// coordinates offset by the output's area.
768
    pub fn arrange(&self, o: OutputId) -> Arrangement {
769
        let Some(out) = self.outputs.get(o) else {
770
            return Arrangement::default();
771
        };
772
        let area = inset(out.area, self.gaps.outer);
773
        let vis = self.vis_on(o);
774
        let tiled = out
775
            .tree
776
            .arrange(area, self.gaps.inner, &vis)
777
            .into_iter()
778
            .map(|(window, rect)| Placed {
779
                window,
780
                rect,
781
                visible: vis(window),
782
            })
783
            .collect();
784
        let mut floating: Vec<(WindowId, Rect)> = out
785
            .floating
786
            .iter()
787
            .copied()
788
            .filter(|&w| vis(w))
789
            .filter_map(|w| Some((w, self.windows[w].float_rect?)))
790
            .collect();
791
        for sp in &self.scratchpads {
792
            if let Some(i) = sp.shown
793
                && sp.output == Some(o)
794
                && let Some(r) = self.windows[sp.windows[i]].float_rect
795
            {
796
                floating.push((sp.windows[i], r));
797
            }
798
        }
799
        let fullscreen = self
800
            .history
801
            .iter()
802
            .rev()
803
            .copied()
804
            .find(|&w| self.windows[w].fullscreen && vis(w));
805
        Arrangement {
806
            tiled,
807
            floating,
808
            fullscreen,
809
        }
810
    }
811
812
    #[cfg(test)]
813
    pub(crate) fn check(&self) {
814
        for (o, out) in &self.outputs {
815
            out.tree.check();
816
            for w in out.tree.windows() {
817
                let win = &self.windows[w];
818
                assert_eq!(win.output, Some(o));
819
                assert!(!win.floating && win.scratchpad.is_none());
820
            }
821
            for &w in &out.floating {
822
                assert_eq!(self.windows[w].output, Some(o));
823
                assert!(self.windows[w].floating);
824
            }
825
        }
826
        for (w, win) in &self.windows {
827
            let homes = self
828
                .outputs
829
                .values()
830
                .filter(|out| out.tree.contains(w) || out.floating.contains(&w))
831
                .count();
832
            let expected = usize::from(win.output.is_some() && win.scratchpad.is_none());
833
            assert_eq!(homes, expected, "window placed {homes} times");
834
        }
835
    }
836
}
837
838
fn nearest<K: Copy>(
839
    from: Rect,
840
    dir: Dir,
841
    candidates: impl Iterator<Item = (K, Rect)>,
842
) -> Option<K> {
843
    const TOL: f64 = 0.5;
844
    let score = |r: Rect| -> Option<(bool, f64, f64)> {
845
        let (gap, overlap, offset) = match dir {
846
            Dir::Right => (
847
                r.x - from.right(),
848
                span_overlap(from.y, from.h, r.y, r.h),
849
                r.center_y() - from.center_y(),
850
            ),
851
            Dir::Left => (
852
                from.x - r.right(),
853
                span_overlap(from.y, from.h, r.y, r.h),
854
                r.center_y() - from.center_y(),
855
            ),
856
            Dir::Down => (
857
                r.y - from.bottom(),
858
                span_overlap(from.x, from.w, r.x, r.w),
859
                r.center_x() - from.center_x(),
860
            ),
861
            Dir::Up => (
862
                from.y - r.bottom(),
863
                span_overlap(from.x, from.w, r.x, r.w),
864
                r.center_x() - from.center_x(),
865
            ),
866
        };
867
        (gap > -TOL).then_some((overlap <= 0.0, gap.max(0.0), offset.abs()))
868
    };
869
    candidates
870
        .filter_map(|(k, r)| score(r).map(|s| (k, s)))
871
        .min_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal))
872
        .map(|(k, _)| k)
873
}
874
875
fn span_overlap(a: f64, al: f64, b: f64, bl: f64) -> f64 {
876
    (a + al).min(b + bl) - a.max(b)
877
}
878
879
fn inset(r: Rect, by: f64) -> Rect {
880
    Rect::new(
881
        r.x + by,
882
        r.y + by,
883
        (r.w - 2.0 * by).max(0.0),
884
        (r.h - 2.0 * by).max(0.0),
885
    )
886
}
887
888
fn centred(area: Rect, frac: f64) -> Rect {
889
    let (w, h) = (area.w * frac, area.h * frac);
890
    Rect::new(
891
        area.x + (area.w - w) / 2.0,
892
        area.y + (area.h - h) / 2.0,
893
        w,
894
        h,
895
    )
896
}
897
898
/// Keeps a rect at the same relative spot when it changes output.
899
fn translate(r: Rect, from: Rect, to: Rect) -> Rect {
900
    let sx = if from.w > 0.0 { to.w / from.w } else { 1.0 };
901
    let sy = if from.h > 0.0 { to.h / from.h } else { 1.0 };
902
    Rect::new(
903
        to.x + (r.x - from.x) * sx,
904
        to.y + (r.y - from.y) * sy,
905
        r.w.min(to.w),
906
        r.h.min(to.h),
907
    )
908
}