penrose 0.4.0

A tiling window manager library inspired by dwm and xmonad
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
//! Built-in layouts.
use crate::{
    builtin::layout::messages::{ExpandMain, IncMain, Mirror, Rotate, ShrinkMain},
    core::layout::{Layout, Message},
    pure::{geometry::Rect, Stack},
    Xid,
};

pub mod messages;
pub mod transformers;

// NOTE: When adding new layouts to this module, they should have a corresponding quickcheck
//       test added to ensure that the layout logic does not panic when given arbitrary inputs.
#[cfg(test)]
pub mod quickcheck_tests;

#[derive(Debug, Clone, Copy)]
enum StackPosition {
    Side,
    Bottom,
}

impl StackPosition {
    fn rotate(&self) -> Self {
        match self {
            StackPosition::Side => StackPosition::Bottom,
            StackPosition::Bottom => StackPosition::Side,
        }
    }
}

/// A simple [Layout] with main and secondary regions.
///
/// - `MainAndStack::side` give a main region to the left and remaining clients to the right.
/// - `MainAndStack::bottom` give a main region to the top and remaining clients to the bottom.
///
/// The ratio between the main and secondary stack regions can be adjusted by sending [ShrinkMain]
/// and [ExpandMain] messages to this layout. The number of clients in the main area can be
/// increased or decreased by sending an [IncMain] message. To flip between the side and bottom
/// behaviours you can send a [Rotate] message.
///
/// ```text
/// ..................................
/// .                  .             .
/// .                  .             .
/// .                  .             .
/// .                  ...............
/// .                  .             .
/// .                  .             .
/// .                  .             .
/// .                  ...............
/// .                  .             .
/// .                  .             .
/// .                  .             .
/// ..................................
/// ```
#[derive(Debug, Clone, Copy)]
pub struct MainAndStack {
    pos: StackPosition,
    max_main: u32,
    ratio: f32,
    ratio_step: f32,
    mirrored: bool,
}

impl Default for MainAndStack {
    fn default() -> Self {
        Self {
            pos: StackPosition::Side,
            max_main: 1,
            ratio: 0.6,
            ratio_step: 0.1,
            mirrored: false,
        }
    }
}

impl MainAndStack {
    /// Create a new default [MainAndStack] [Layout] as a trait object ready to be added to your
    /// [LayoutStack][crate::core::layout::LayoutStack].
    pub fn boxed_default() -> Box<dyn Layout> {
        Box::<Self>::default()
    }

    /// Create a new rotated default [MainAndStack] [Layout] as a trait object ready to be added to
    /// your [LayoutStack][crate::core::layout::LayoutStack].
    pub fn boxed_default_rotated() -> Box<dyn Layout> {
        let mut l = Self::default();
        l.rotate();

        Box::new(l)
    }

    /// Create a new [MainAndStack] [Layout] with the main area on the left and remaining windows
    /// stacked to the right.
    pub fn side(max_main: u32, ratio: f32, ratio_step: f32) -> Box<dyn Layout> {
        Box::new(Self::side_unboxed(max_main, ratio, ratio_step, false))
    }

    /// Create a new [MainAndStack] [Layout] with the main area on the right and remaining windows
    /// stacked to the left.
    pub fn side_mirrored(max_main: u32, ratio: f32, ratio_step: f32) -> Box<dyn Layout> {
        Box::new(Self::side_unboxed(max_main, ratio, ratio_step, true))
    }

    /// Create a new [MainAndStack] [Layout] with the main area and remaining windows
    /// stacked to the side.
    pub fn side_unboxed(max_main: u32, ratio: f32, ratio_step: f32, mirrored: bool) -> Self {
        Self {
            pos: StackPosition::Side,
            max_main,
            ratio,
            ratio_step,
            mirrored,
        }
    }

    /// Create a new [MainAndStack] [Layout] with the main area on the top and remaining windows
    /// stacked on the bottom.
    pub fn bottom(max_main: u32, ratio: f32, ratio_step: f32) -> Box<dyn Layout> {
        Box::new(Self::bottom_unboxed(max_main, ratio, ratio_step, false))
    }

    /// Create a new [MainAndStack] [Layout] with the main area on the bottom and remaining windows
    /// stacked on the top.
    pub fn top(max_main: u32, ratio: f32, ratio_step: f32) -> Box<dyn Layout> {
        Box::new(Self::bottom_unboxed(max_main, ratio, ratio_step, true))
    }

    /// Create a new [MainAndStack] [Layout] with a main area and the remaining windows
    /// stacked either on the top or the bottom.
    pub fn bottom_unboxed(max_main: u32, ratio: f32, ratio_step: f32, mirrored: bool) -> Self {
        Self {
            pos: StackPosition::Bottom,
            max_main,
            ratio,
            ratio_step,
            mirrored,
        }
    }

    /// Rotate the main axis of this layout
    pub fn rotate(&mut self) {
        self.pos = self.pos.rotate();
    }

    fn ratio(&self) -> f32 {
        if self.mirrored {
            1.0 - self.ratio
        } else {
            self.ratio
        }
    }

    // In each of these four cases we no longer have a split point giving
    // us independent stacks.
    fn all_windows_in_single_stack(&self, n: u32) -> bool {
        n <= self.max_main || self.max_main == 0 || self.ratio == 1.0 || self.ratio == 0.0
    }

    fn layout_side(&self, s: &Stack<Xid>, r: Rect) -> Vec<(Xid, Rect)> {
        let n = s.len() as u32;

        if self.all_windows_in_single_stack(n) {
            r.as_rows(n).iter().zip(s).map(|(r, c)| (*c, *r)).collect()
        } else {
            // We have two stacks so split the screen in two and then build a stack for each
            let (mut main, mut stack) = r
                .split_at_width_perc(self.ratio())
                .expect("split point to be valid");
            if self.mirrored {
                (main, stack) = (stack, main);
            }

            main.as_rows(self.max_main)
                .into_iter()
                .chain(stack.as_rows(n.saturating_sub(self.max_main)))
                .zip(s)
                .map(|(r, c)| (*c, r))
                .collect()
        }
    }

    fn layout_bottom(&self, s: &Stack<Xid>, r: Rect) -> Vec<(Xid, Rect)> {
        let n = s.len() as u32;

        if self.all_windows_in_single_stack(n) {
            r.as_columns(n)
                .iter()
                .zip(s)
                .map(|(r, c)| (*c, *r))
                .collect()
        } else {
            let (mut main, mut stack) = r
                .split_at_height_perc(self.ratio())
                .expect("split point to be valid");
            if self.mirrored {
                (main, stack) = (stack, main);
            }

            main.as_columns(self.max_main)
                .into_iter()
                .chain(stack.as_columns(n.saturating_sub(self.max_main)))
                .zip(s)
                .map(|(r, c)| (*c, r))
                .collect()
        }
    }
}

impl Layout for MainAndStack {
    fn name(&self) -> String {
        match (self.pos, self.mirrored) {
            (StackPosition::Side, false) => "Side".to_owned(),
            (StackPosition::Side, true) => "Mirror".to_owned(),
            (StackPosition::Bottom, false) => "Bottom".to_owned(),
            (StackPosition::Bottom, true) => "Top".to_owned(),
        }
    }

    fn boxed_clone(&self) -> Box<dyn Layout> {
        Box::new(*self)
    }

    fn layout(&mut self, s: &Stack<Xid>, r: Rect) -> (Option<Box<dyn Layout>>, Vec<(Xid, Rect)>) {
        let positions = match self.pos {
            StackPosition::Side => self.layout_side(s, r),
            StackPosition::Bottom => self.layout_bottom(s, r),
        };

        (None, positions)
    }

    fn handle_message(&mut self, m: &Message) -> Option<Box<dyn Layout>> {
        if let Some(&ExpandMain) = m.downcast_ref() {
            self.ratio += self.ratio_step;
            if self.ratio > 1.0 {
                self.ratio = 1.0;
            }
        } else if let Some(&ShrinkMain) = m.downcast_ref() {
            self.ratio -= self.ratio_step;
            if self.ratio < 0.0 {
                self.ratio = 0.0;
            }
        } else if let Some(&IncMain(n)) = m.downcast_ref() {
            if n < 0 {
                self.max_main = self.max_main.saturating_sub((-n) as u32);
            } else {
                self.max_main += n as u32;
            }
        } else if let Some(&Mirror) = m.downcast_ref() {
            self.mirrored = !self.mirrored;
        } else if let Some(&Rotate) = m.downcast_ref() {
            self.rotate();
        }

        None
    }
}

/// A simple [Layout] with a main and secondary side regions.
///
/// - `CenteredMain::vertical` places the secondary regions to the left and right.
/// - `CenteredMain::horizontal` places the secondary regions to the top and bottom.
///
/// The ratio between the main and secondary stack regions can be adjusted by sending [ShrinkMain]
/// and [ExpandMain] messages to this layout. The number of clients in the main area can be
/// increased or decreased by sending an [IncMain] message. To flip between the vertical and
/// horizontal behaviours you can send a [Rotate] message.
///
/// ```text
/// ...................................
/// .                .                .
/// .                .                .
/// .                .                .
/// ...................................
/// .                                 .
/// .                                 .
/// .                                 .
/// .                                 .
/// .                                 .
/// ...................................
/// .                .                .
/// .                .                .
/// .                .                .
/// ...................................
/// ```
#[derive(Debug, Clone, Copy)]
pub struct CenteredMain {
    pos: StackPosition,
    max_main: u32,
    ratio: f32,
    ratio_step: f32,
}

impl Default for CenteredMain {
    fn default() -> Self {
        Self {
            pos: StackPosition::Side,
            max_main: 1,
            ratio: 0.6,
            ratio_step: 0.1,
        }
    }
}

impl CenteredMain {
    /// Create a new default [CenteredMain] [Layout] as a trait object ready to be added to your
    /// [LayoutStack][crate::core::layout::LayoutStack].
    pub fn boxed_default() -> Box<dyn Layout> {
        Box::<Self>::default()
    }

    /// Create a new rotated default [CenteredMain] [Layout] as a trait object ready to be added to
    /// your [LayoutStack][crate::core::layout::LayoutStack].
    pub fn boxed_default_rotated() -> Box<dyn Layout> {
        let mut l = Self::default();
        l.rotate();

        Box::new(l)
    }

    /// Create a new [CenteredMain] [Layout] with a vertical main area and remaining windows
    /// tiled to the left and right.
    pub fn vertical(max_main: u32, ratio: f32, ratio_step: f32) -> Box<dyn Layout> {
        Box::new(Self::vertical_unboxed(max_main, ratio, ratio_step))
    }

    /// Create a new [CenteredMain] [Layout] with a vertical main area and remaining windows
    /// tiled to the left and right.
    pub fn vertical_unboxed(max_main: u32, ratio: f32, ratio_step: f32) -> Self {
        Self {
            pos: StackPosition::Side,
            max_main,
            ratio,
            ratio_step,
        }
    }

    /// Create a new [CenteredMain] [Layout] with a horizontal main area and remaining windows
    /// tiled above and below.
    pub fn horizontal(max_main: u32, ratio: f32, ratio_step: f32) -> Box<dyn Layout> {
        Box::new(Self::horizontal_unboxed(max_main, ratio, ratio_step))
    }

    /// Create a new [CenteredMain] [Layout] with a horizontal main area and remaining windows
    /// tiled above and below.
    pub fn horizontal_unboxed(max_main: u32, ratio: f32, ratio_step: f32) -> Self {
        Self {
            pos: StackPosition::Bottom,
            max_main,
            ratio,
            ratio_step,
        }
    }

    /// Rotate the main axis of this layout
    pub fn rotate(&mut self) {
        self.pos = self.pos.rotate();
    }

    fn single_stack(&self, n: u32) -> bool {
        n <= self.max_main || self.ratio == 1.0 || self.ratio == 0.0
    }

    // NOTE: There are subtle differences between this method and layout_horizontal
    // >> Be careful when refactoring!
    fn layout_vertical(&self, s: &Stack<Xid>, r: Rect) -> Vec<(Xid, Rect)> {
        let n = s.len() as u32;

        if self.single_stack(n) {
            r.as_rows(n).iter().zip(s).map(|(r, c)| (*c, *r)).collect()
        } else if n.saturating_sub(self.max_main) == 1 {
            let (main, stack) = r
                .split_at_width_perc(self.ratio)
                .expect("split point to be valid");

            main.as_rows(self.max_main)
                .into_iter()
                .chain(std::iter::once(stack))
                .zip(s)
                .map(|(r, c)| (*c, r))
                .collect()
        } else {
            let n_right = n.saturating_sub(self.max_main) / 2;
            let n_left = n.saturating_sub(n_right).saturating_sub(self.max_main);
            let (left_and_main, right) = r
                .split_at_width_perc(0.5 + self.ratio / 2.0)
                .expect("split point to be valid");
            let (left, main) = left_and_main
                .split_at_width(right.w)
                .expect("split point to be valid");

            main.as_rows(self.max_main)
                .into_iter()
                .chain(left.as_rows(n_left))
                .chain(right.as_rows(n_right))
                .zip(s)
                .map(|(r, c)| (*c, r))
                .collect()
        }
    }

    // NOTE: There are subtle differences between this method and layout_vertical
    // >> Be careful when refactoring!
    fn layout_horizontal(&self, s: &Stack<Xid>, r: Rect) -> Vec<(Xid, Rect)> {
        let n = s.len() as u32;

        if self.single_stack(n) {
            r.as_columns(n)
                .iter()
                .zip(s)
                .map(|(r, c)| (*c, *r))
                .collect()
        } else if n.saturating_sub(self.max_main) == 1 {
            let (main, stack) = r
                .split_at_height_perc(1.0 - self.ratio)
                .expect("split point to be valid");

            main.as_columns(self.max_main)
                .into_iter()
                .chain(std::iter::once(stack))
                .zip(s)
                .map(|(r, c)| (*c, r))
                .collect()
        } else {
            let n_top = n.saturating_sub(self.max_main) / 2;
            let n_bottom = n.saturating_sub(n_top).saturating_sub(self.max_main);
            let (top_and_main, bottom) = r
                .split_at_height_perc(0.5 + self.ratio / 2.0)
                .expect("split point to be valid");
            let (top, main) = top_and_main
                .split_at_height(bottom.h)
                .expect("split point to be valid");

            main.as_columns(self.max_main)
                .into_iter()
                .chain(top.as_columns(n_top))
                .chain(bottom.as_columns(n_bottom))
                .zip(s)
                .map(|(r, c)| (*c, r))
                .collect()
        }
    }
}

impl Layout for CenteredMain {
    fn name(&self) -> String {
        match self.pos {
            StackPosition::Side => "Center|".to_owned(),
            StackPosition::Bottom => "Center-".to_owned(),
        }
    }

    fn boxed_clone(&self) -> Box<dyn Layout> {
        Box::new(*self)
    }

    fn layout(&mut self, s: &Stack<Xid>, r: Rect) -> (Option<Box<dyn Layout>>, Vec<(Xid, Rect)>) {
        let positions = match self.pos {
            StackPosition::Side => self.layout_vertical(s, r),
            StackPosition::Bottom => self.layout_horizontal(s, r),
        };

        (None, positions)
    }

    fn handle_message(&mut self, m: &Message) -> Option<Box<dyn Layout>> {
        if let Some(&ExpandMain) = m.downcast_ref() {
            self.ratio += self.ratio_step;
            if self.ratio > 1.0 {
                self.ratio = 1.0;
            }
        } else if let Some(&ShrinkMain) = m.downcast_ref() {
            self.ratio -= self.ratio_step;
            if self.ratio < 0.0 {
                self.ratio = 0.0;
            }
        } else if let Some(&IncMain(n)) = m.downcast_ref() {
            if n < 0 {
                self.max_main = self.max_main.saturating_sub((-n) as u32);
            } else {
                self.max_main += n as u32;
            }
        } else if let Some(&Rotate) = m.downcast_ref() {
            self.rotate();
        }

        None
    }
}

/// A simple monolce layout that gives the maximum available space to the currently
/// focused client and unmaps all other windows.
///
/// ```text
/// ..................................
/// .                                .
/// .                                .
/// .                                .
/// .                                .
/// .                                .
/// .                                .
/// .                                .
/// .                                .
/// .                                .
/// .                                .
/// .                                .
/// ..................................
/// ```
#[derive(Debug, Clone, Copy)]
pub struct Monocle;

impl Monocle {
    /// Create a new [Monocle] [Layout] as a boxed trait object
    pub fn boxed() -> Box<dyn Layout> {
        Box::new(Monocle)
    }
}

impl Layout for Monocle {
    fn name(&self) -> String {
        "Mono".to_owned()
    }

    fn boxed_clone(&self) -> Box<dyn Layout> {
        Self::boxed()
    }

    fn layout(&mut self, s: &Stack<Xid>, r: Rect) -> (Option<Box<dyn Layout>>, Vec<(Xid, Rect)>) {
        (None, vec![(s.focus, r)])
    }

    fn handle_message(&mut self, _: &Message) -> Option<Box<dyn Layout>> {
        None
    }
}

/// A simple grid layout that places windows in the smallest nxn grid that will
/// contain all window present on the workspace.
///
/// ```text
/// ..................................
/// .          .          .          .
/// .          .          .          .
/// .          .          .          .
/// ..................................
/// .          .          .          .
/// .          .          .          .
/// .          .          .          .
/// ..................................
/// .          .          .          .
/// .          .          .          .
/// .          .          .          .
/// ..................................
/// ```
///
/// ### NOTE
/// This will leave unused screen space if there are not a square number of
/// windows present in the workspace being laid out:
/// ```text
/// ..................................
/// .          .          .          .
/// .          .          .          .
/// .          .          .          .
/// ..................................
/// .          .          .          .
/// .          .          .          .
/// .          .          .          .
/// ..................................
/// .          .          .
/// .          .          .
/// .          .          .
/// .......................
/// ```
#[derive(Debug, Default, Copy, Clone)]
pub struct Grid;

impl Grid {
    /// Create a new [Grid] [Layout] as a boxed trait object
    pub fn boxed() -> Box<dyn Layout> {
        Box::new(Grid)
    }
}

impl Layout for Grid {
    fn name(&self) -> String {
        "Grid".to_string()
    }

    fn boxed_clone(&self) -> Box<dyn Layout> {
        Self::boxed()
    }

    fn layout(&mut self, s: &Stack<Xid>, r: Rect) -> (Option<Box<dyn Layout>>, Vec<(Xid, Rect)>) {
        let n = s.len();
        let n_cols = (1..).find(|&i| (i * i) >= n).unwrap_or(1);
        let n_rows = if n_cols * (n_cols - 1) >= n {
            n_cols - 1
        } else {
            n_cols
        };

        let rects = r
            .as_rows(n_rows as u32)
            .into_iter()
            .flat_map(|row| row.as_columns(n_cols as u32));

        let positions = s.iter().zip(rects).map(|(&id, r)| (id, r)).collect();

        (None, positions)
    }

    fn handle_message(&mut self, _: &Message) -> Option<Box<dyn Layout>> {
        None
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        builtin::layout::{messages::IncMain, *},
        core::layout::IntoMessage,
    };

    #[test]
    fn message_handling() {
        let mut l = MainAndStack::side_unboxed(1, 0.6, 0.1, false);

        l.handle_message(&IncMain(2).into_message());

        assert_eq!(l.max_main, 3);
    }
}