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
use regex::Regex;
use river_layout_toolkit::{GeneratedLayout, Layout, Rectangle};
use std::fmt::Display;

/// Wrapper for errors relating to the creation or operation of a `BSPLayout`
#[non_exhaustive]
#[derive(Debug)]
pub enum BSPLayoutError {

    /// Encountered when a failure occurs in `user_cmd`
    CmdError(String),
}

impl Display for BSPLayoutError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self)
    }
}

impl std::error::Error for BSPLayoutError {}

/// Create a Binary Space Partitioned layout. Specifically, this layout recursively
/// divides the screen in half. The split will alternate between vertical and horizontal
/// based on which side of the container is longer. This will result in a grid like
/// layout with more-or-less equal sized windows even distributed across the screen
pub struct BSPLayout {

    /// Number of pixels to put between the edge of the display and each window
    pub outer_gap: u32,

    /// Number of pixels to put between the inside edge of adjacent windows
    pub inner_gap: u32,
}

impl BSPLayout {

    /// Initialize a new instance of BSPLayout with given inner and outer gaps
    ///
    /// # Arguments 
    ///
    /// * `outer_gap` - Number of pixels to put between the edge of the display and the outside
    /// edge of the nearest windows 
    ///
    /// * `inner_gap` - Number of pixels to put between the inside edge of adjacent windows 
    ///
    /// # Returns 
    ///
    /// A new `BSPLayout`
    pub fn new(outer_gap: u32, inner_gap: u32) -> BSPLayout {
        BSPLayout {
            outer_gap,
            inner_gap,
        }
    }

    /// Perform the recursive division by two to evenly divide the screen as best
    /// as possible
    ///
    /// # Arguments
    ///
    /// * `origin_x` - The x position of the top left of the space to be divided
    /// relative to the entire display. For example, if you are dividing the entire
    /// display, then the top left corner is 0, 0. If you are dividing the right
    /// half of a 1920x1080 monitor, then the top left corner would be at 960, 0
    ///
    /// * `origin_y` - The y position of the top left of the space to be divided
    /// relative to the entire display. For example, if you are dividing the entire
    /// display, then the top left corner is 0, 0. If you are dividing the bottom
    /// half of a 1920x1080 monitor, then the top left corner would be at 0, 540
    ///
    /// * `canvas_width` - The width in pixels of the area being divided. If you
    /// are dividing all of a 1920x1080 monitor, then the `canvas_width` would be 1920.
    /// If you are dividing the right half of the monitor, then the width is 960.
    ///
    /// * `canvas_height` - The height in pixels of the area being divided. If you
    /// are dividing all of a 1920x1080 monitor, then the height would be 1080.
    /// If you are dividing the bottom half of the monitor, then the height is 540.
    ///
    /// * `view_count` - How many windows / containers / apps / division the function
    /// needs to make in total.
    ///
    /// # Returns
    ///
    /// A `GeneratedLayout` with `view_count` cells evenly distributed across the screen
    /// in a grid
    fn handle_layout_helper(
        &self,
        origin_x: i32,
        origin_y: i32,
        canvas_width: u32,
        canvas_height: u32,
        view_count: u32,
    ) -> GeneratedLayout {
        let mut layout = GeneratedLayout {
            layout_name: "bsp-layout".to_string(),
            views: Vec::with_capacity(view_count as usize),
        };

        // Exit condition. When there is only one window left, it should take up the
        // entire available canvas
        if view_count == 1 {
            layout.views.push(Rectangle {
                x: origin_x,
                y: origin_y,
                width: canvas_width,
                height: canvas_height,
            });

            return layout;
        }

        let half_view_count = view_count / 2;
        let views_remaining = view_count % 2; // In case there are odd number of views

        let h1_width: u32;
        let h1_height: u32;

        let h2_width: u32;
        let h2_height: u32;
        let h2_x: i32;
        let h2_y: i32;

        if canvas_width >= canvas_height {
            /* Vertical Split */

            // In case the width of the area is odd, add one extra pixel if needed
            h1_width =
                canvas_width / 2 + canvas_width % 2 - self.inner_gap / 2 - self.inner_gap % 2;
            h1_height = canvas_height;

            h2_width = canvas_width / 2 - self.inner_gap / 2;
            h2_height = canvas_height;
            h2_x = h1_width as i32 + origin_x + self.inner_gap as i32;
            h2_y = origin_y;
        } else {
            /* Horizontal Split */

            h1_width = canvas_width;
            h1_height =
                canvas_height / 2 + canvas_height % 2 - self.inner_gap / 2 - self.inner_gap % 2;

            h2_width = canvas_width;

            // In case the width of the area is odd, add one extra pixel if needed
            h2_height = canvas_height / 2 - self.inner_gap / 2;
            h2_x = origin_x;
            h2_y = h1_height as i32 + origin_y + self.inner_gap as i32;
        }

        /* Recursively split the two halves of the window */
        let mut first_half =
            self.handle_layout_helper(origin_x, origin_y, h1_width, h1_height, half_view_count);

        let mut sec_half = self.handle_layout_helper(
            h2_x,
            h2_y,
            h2_width,
            h2_height,
            half_view_count + views_remaining,
        );

        layout.views.append(&mut first_half.views);
        layout.views.append(&mut sec_half.views);

        layout
    }
}

impl Layout for BSPLayout {
    type Error = BSPLayoutError;

    const NAMESPACE: &'static str = "bsp-layout";

    /// Handle commands passed to the layout with `send-layout-cmd`. Currently supports
    /// "outer-gap #" and "inner-gap #", which will set set the outer and inner gaps
    /// of the window at runtime
    ///
    /// # Examples
    ///
    /// ```
    /// use river_bsp_layout::BSPLayout;
    /// use river_layout_toolkit::Layout;
    ///
    /// // Initialize layout with 0 gaps
    /// let mut bsp = BSPLayout::new(0, 0);
    ///
    /// // Set gap between windows and the monitor edge to be 5 pixels
    /// let res = bsp.user_cmd("outer-gap 5".to_string(), None, "eDP-1").unwrap();
    /// assert_eq!(bsp.outer_gap, 5);
    /// ```
    ///
    /// # Errors
    ///
    /// Will return `BSPLayoutError::CmdError` if an unrecognized command is passed
    /// or if an invalid argument is passed to a valid command.
    fn user_cmd(
        &mut self,
        _cmd: String,
        _tags: Option<u32>,
        _output: &str,
    ) -> Result<(), Self::Error> {
        let outer_re = Regex::new(r"^outer-gap \d+$").unwrap();
        let inner_re = Regex::new(r"^inner-gap \d+$").unwrap();

        if outer_re.is_match(&_cmd) {
            let new_gap_str = match _cmd.split(" ").last() {
                Some(s) => s,
                None => {
                    return Err(BSPLayoutError::CmdError(
                        "outer-gap missing argument".to_string(),
                    ));
                }
            };
            let new_gap = match new_gap_str.parse::<u32>() {
                Ok(i) => i,
                Err(_) => {
                    return Err(BSPLayoutError::CmdError(
                        "Could not parse u32 from outer-gap argument".to_string(),
                    ));
                }
            };

            self.outer_gap = new_gap;
        } else if inner_re.is_match(&_cmd) {
            let new_gap_str = match _cmd.split(" ").last() {
                Some(s) => s,
                None => {
                    return Err(BSPLayoutError::CmdError(
                        "inner-gap missing argument".to_string(),
                    ))
                }
            };
            let new_gap = match new_gap_str.parse::<u32>() {
                Ok(i) => i,
                Err(_) => {
                    return Err(BSPLayoutError::CmdError(
                        "Could not parse u32 from inner-gap argument".to_string(),
                    ))
                }
            };

            self.inner_gap = new_gap;
        } else {
            return Err(BSPLayoutError::CmdError(format!(
                "Command not recognized: {}",
                _cmd
            )));
        }
        Ok(())
    }

    /// Create the geometry for the `BSPLayout`
    ///
    /// # Arguments
    ///
    /// * `view_count` - The number of views / windows / containers to divide the screen into
    /// * `usable_width` - How many pixels wide the whole display is
    /// * `usable_height` - How many pixels tall the whole display is
    /// * `_tags` - Int representing which tags are currently active based on which
    /// bit is toggled
    /// * `_output` - The name of the output to generate the layout on
    ///
    /// # Examples
    ///
    /// ```
    /// use river_bsp_layout::BSPLayout;
    /// use river_layout_toolkit::Layout;
    ///
    /// let mut bsp = BSPLayout::new(10, 10);
    /// bsp.generate_layout(2, 1920, 1080, 0b000000001, "eDP-1").unwrap();
    /// ```
    fn generate_layout(
        &mut self,
        view_count: u32,
        usable_width: u32,
        usable_height: u32,
        _tags: u32,
        _output: &str,
    ) -> Result<GeneratedLayout, Self::Error> {
        let layout = self.handle_layout_helper(
            self.outer_gap as i32,
            self.outer_gap as i32,
            usable_width - self.outer_gap * 2,
            usable_height - self.outer_gap * 2,
            view_count,
        );
        Ok(layout)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_handle_layout_helper_one_container() {
        let bsp = BSPLayout::new(0, 0);
        let layout = bsp.handle_layout_helper(0, 0, 1920, 1080, 1);

        assert_eq!(layout.views.len(), 1);
        let first_view = layout.views.get(0).unwrap();
        assert_eq!(
            (
                first_view.x,
                first_view.y,
                first_view.width,
                first_view.height
            ),
            (0, 0, 1920, 1080)
        );
    }

    #[test]
    fn test_handle_layout_helper_two_containers() {
        let bsp = BSPLayout::new(0, 0);
        let layout = bsp.handle_layout_helper(0, 0, 1920, 1080, 2);

        assert_eq!(layout.views.len(), 2);
        let first_view = layout.views.get(0).unwrap();
        assert_eq!(
            (
                first_view.x,
                first_view.y,
                first_view.width,
                first_view.height
            ),
            (0, 0, 960, 1080)
        );

        let second_view = layout.views.get(1).unwrap();
        assert_eq!(
            (
                second_view.x,
                second_view.y,
                second_view.width,
                second_view.height
            ),
            (960, 0, 960, 1080)
        );
    }

    #[test]
    fn test_handle_layout_helper_three_containers() {
        let bsp = BSPLayout::new(0, 0);
        let layout = bsp.handle_layout_helper(0, 0, 1920, 1080, 3);

        assert_eq!(layout.views.len(), 3);
        let first_view = layout.views.get(0).unwrap();
        assert_eq!(
            (
                first_view.x,
                first_view.y,
                first_view.width,
                first_view.height
            ),
            (0, 0, 960, 1080)
        );

        let second_view = layout.views.get(1).unwrap();
        assert_eq!(
            (
                second_view.x,
                second_view.y,
                second_view.width,
                second_view.height
            ),
            (960, 0, 960, 540)
        );

        let third_view = layout.views.get(2).unwrap();
        assert_eq!(
            (
                third_view.x,
                third_view.y,
                third_view.width,
                third_view.height
            ),
            (960, 540, 960, 540)
        );
    }

    #[test]
    fn test_handle_layout_helper_four_containers() {
        let bsp = BSPLayout::new(0, 0);
        let layout = bsp.handle_layout_helper(0, 0, 1920, 1080, 4);

        assert_eq!(layout.views.len(), 4);
        let first_view = layout.views.get(0).unwrap();
        assert_eq!(
            (
                first_view.x,
                first_view.y,
                first_view.width,
                first_view.height
            ),
            (0, 0, 960, 540)
        );

        let second_view = layout.views.get(1).unwrap();
        assert_eq!(
            (
                second_view.x,
                second_view.y,
                second_view.width,
                second_view.height
            ),
            (0, 540, 960, 540)
        );

        let third_view = layout.views.get(2).unwrap();
        assert_eq!(
            (
                third_view.x,
                third_view.y,
                third_view.width,
                third_view.height
            ),
            (960, 0, 960, 540)
        );

        let fourth_view = layout.views.get(3).unwrap();
        assert_eq!(
            (
                fourth_view.x,
                fourth_view.y,
                fourth_view.width,
                fourth_view.height
            ),
            (960, 540, 960, 540)
        );
    }

    #[test]
    fn test_generate_layout_no_gaps() {
        let mut bsp = BSPLayout::new(0, 0);
        let layout = bsp.generate_layout(4, 1920, 1080, 1, "eDP-1").unwrap();

        assert_eq!(layout.views.len(), 4);
        let first_view = layout.views.get(0).unwrap();
        assert_eq!(
            (
                first_view.x,
                first_view.y,
                first_view.width,
                first_view.height
            ),
            (0, 0, 960, 540)
        );

        let second_view = layout.views.get(1).unwrap();
        assert_eq!(
            (
                second_view.x,
                second_view.y,
                second_view.width,
                second_view.height
            ),
            (0, 540, 960, 540)
        );

        let third_view = layout.views.get(2).unwrap();
        assert_eq!(
            (
                third_view.x,
                third_view.y,
                third_view.width,
                third_view.height
            ),
            (960, 0, 960, 540)
        );

        let fourth_view = layout.views.get(3).unwrap();
        assert_eq!(
            (
                fourth_view.x,
                fourth_view.y,
                fourth_view.width,
                fourth_view.height
            ),
            (960, 540, 960, 540)
        );
    }

    #[test]
    fn test_generate_layout_with_gaps() {
        let mut bsp = BSPLayout::new(10, 20);
        let layout = bsp.generate_layout(4, 1920, 1080, 1, "eDP-1").unwrap();

        assert_eq!(layout.views.len(), 4);
        let first_view = layout.views.get(0).unwrap();
        assert_eq!(
            (
                first_view.x,
                first_view.y,
                first_view.width,
                first_view.height
            ),
            (10, 10, 940, 520)
        );

        let second_view = layout.views.get(1).unwrap();
        assert_eq!(
            (
                second_view.x,
                second_view.y,
                second_view.width,
                second_view.height
            ),
            (10, 550, 940, 520)
        );

        let third_view = layout.views.get(2).unwrap();
        assert_eq!(
            (
                third_view.x,
                third_view.y,
                third_view.width,
                third_view.height
            ),
            (970, 10, 940, 520)
        );

        let fourth_view = layout.views.get(3).unwrap();
        assert_eq!(
            (
                fourth_view.x,
                fourth_view.y,
                fourth_view.width,
                fourth_view.height
            ),
            (970, 550, 940, 520)
        );
    }

    #[test]
    fn test_send_outer_gaps() {
        let mut bsp = BSPLayout::new(0, 0);
        bsp.user_cmd("outer-gap 5".to_string(), None, "eDP-1")
            .unwrap();

        assert_eq!(bsp.inner_gap, 0);
        assert_eq!(bsp.outer_gap, 5);
    }

    #[test]
    fn test_send_inner_gaps() {
        let mut bsp = BSPLayout::new(0, 0);
        bsp.user_cmd("inner-gap 5".to_string(), None, "eDP-1")
            .unwrap();

        assert_eq!(bsp.inner_gap, 5);
        assert_eq!(bsp.outer_gap, 0);
    }

    #[test]
    fn test_invalid_user_command() {
        let mut bsp = BSPLayout::new(0, 0);
        let res = bsp.user_cmd("foo-bar 5678".to_string(), None, "eDP-1");
        assert!(res.is_err());
    }
}