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
use super::Tag;
use crate::{config::Config, layouts::Layout, Workspace};

use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
pub enum LayoutMode {
    Tag,
    Workspace,
}

impl Default for LayoutMode {
    fn default() -> Self {
        Self::Workspace
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct LayoutManager {
    pub mode: LayoutMode,
    pub layouts: Vec<Layout>,
}

impl LayoutManager {
    pub fn new(config: &impl Config) -> Self {
        Self {
            mode: config.layout_mode(),
            layouts: config.layouts(),
        }
    }

    pub fn new_layout(&self) -> Layout {
        *self.layouts.first().unwrap_or(&Layout::default())
    }

    pub fn next_layout(&self, layout: Layout) -> Layout {
        let mut index = match self.layouts.iter().position(|&x| x == layout) {
            Some(x) => x as isize,
            None => return Layout::default(),
        } + 1;
        if index >= self.layouts.len() as isize {
            index = 0;
        }
        self.layouts[index as usize]
    }

    pub fn previous_layout(&self, layout: Layout) -> Layout {
        let mut index = match self.layouts.iter().position(|&x| x == layout) {
            Some(x) => x as isize,
            None => return Layout::default(),
        } - 1;
        if index < 0 {
            index = self.layouts.len() as isize - 1;
        }
        self.layouts[index as usize]
    }

    pub fn update_layouts(
        &self,
        workspaces: &mut Vec<Workspace>,
        tags: &mut Vec<Tag>,
    ) -> Option<bool> {
        for workspace in workspaces {
            let tag = tags.iter_mut().find(|t| t.id == workspace.tags[0])?;
            match self.mode {
                LayoutMode::Workspace => tag.set_layout(workspace.layout),
                LayoutMode::Tag => workspace.layout = tag.layout,
            }
        }
        Some(true)
    }
}