summaryrefslogtreecommitdiff
path: root/src/state/mod.rs
blob: a461d58dfc99bdbe250888d44946c5cc9c503022 (plain)
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
use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};

use mlua::{UserData, UserDataFields};

use self::log::LogState;

pub mod editor;
pub mod log;
pub mod view;
pub mod window;
mod bar;

#[derive(Debug, Default)]
pub struct GlobalState {
    pub sheetview: view::SheetViewState,
    pub editor: editor::EditorState,
    pub active_window: window::Window,
    pub log: log::LogState,
}

static GLOBAL_STATE: RwLock<GlobalState> = RwLock::new(GlobalState::new());
const DUMMY_STATE: GlobalState = GlobalState::new();

impl GlobalState {
    const fn new() -> Self {
        Self {
            sheetview: view::SheetViewState::new(),
            editor: editor::EditorState::new(),
            log: LogState::new(),
            active_window: window::Window::View,
        }
    }

    pub fn instance() -> RwLockReadGuard<'static, Self> {
        GLOBAL_STATE.read().unwrap()
    }

    pub fn instance_mut() -> RwLockWriteGuard<'static, Self> {
        GLOBAL_STATE.write().unwrap()
    }

    pub fn set_focus(&mut self, win: window::Window) {
        self.active_window = win;

        match win {
            window::Window::Editor => self.editor.visible = true,
            window::Window::Log => self.log.visible = true,
            _ => {}
        }
    }
}

impl UserData for GlobalState {
    fn add_fields<'lua, F: UserDataFields<'lua, Self>>(fields: &mut F) {
        fields.add_field_function_get("view", |_, _| Ok(DUMMY_STATE.sheetview));
        fields.add_field_function_get("editor", |_, _| Ok(DUMMY_STATE.editor));
        fields.add_field_function_get("active_window", |_, _| {
            Ok(GlobalState::instance().active_window)
        });
        fields.add_field_function_set("active_window", |_, _, win: window::Window| {
            GlobalState::instance_mut().set_focus(win);
            Ok(())
        });
    }
}