summaryrefslogtreecommitdiff
path: root/src/state/sheetview.rs
blob: 8108a1da6d244ffb5cb7ea655abdcf4eb07c04d9 (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
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
use std::sync::{Arc, RwLock};

use mlua::{IntoLua, UserData, Value};

use super::GlobalState;
use crate::{
    cursor::{Cursor, CursorMove},
    sheet::{
        register::{Register, SheetId},
        Sheet, SheetLuaRef,
    },
};

#[derive(Default, Debug)]
pub struct SheetViewState {
    pub cursor: Cursor,
    active_sheet: Option<SheetId>,
}

impl SheetViewState {
    pub const fn new() -> Self {
        Self {
            cursor: Cursor::new(),
            active_sheet: None,
        }
    }

    pub fn set_active_sheet(&mut self, sheet: Option<SheetId>) {
        if let Some(id) = sheet {
            if let Some(lock) = Register::get(id) {
                let sheet = lock.read().unwrap();
                self.cursor.set_x_max(sheet.width());
                self.cursor.set_y_max(sheet.height());
            }
        }

        self.active_sheet = sheet
    }

    pub fn active_sheet(&self) -> Option<Arc<RwLock<Sheet>>> {
        if let Some(id) = self.active_sheet {
            Register::get(id)
        } else {
            None
        }
    }
}

macro_rules! cfg {
    () => {
        GlobalState::instance().sheetview
    };
}

macro_rules! cfg_mut {
    () => {
        GlobalState::instance_mut().sheetview
    };
}

impl UserData for SheetViewState {
    fn add_fields<'lua, F: mlua::prelude::LuaUserDataFields<'lua, Self>>(fields: &mut F) {
        fields.add_field_function_get("active", |lua, _| {
            if let Some(id) = cfg!().active_sheet {
                SheetLuaRef::new(id).into_lua(lua)
            } else {
                Ok(Value::Nil)
            }
        });

        fields.add_field_function_set("active", |_, _, sheet: Option<SheetLuaRef>| {
            if let Some(r) = sheet {
                cfg_mut!().active_sheet = Some(r.id())
            } else {
                cfg_mut!().active_sheet = None
            }

            Ok(())
        });

        fields.add_field_function_get("cursor", |lua, _| {
            let table = lua.create_table()?;
            table.set("row", cfg!().cursor.y())?;
            table.set("column", cfg!().cursor.x())?;
            Ok(table)
        })
    }

    fn add_methods<'lua, M: mlua::prelude::LuaUserDataMethods<'lua, Self>>(methods: &mut M) {
        methods.add_function("move_cursor", |_, (row, column): (usize, usize)| {
            cfg_mut!()
                .cursor
                .move_checked(CursorMove::Jump((row, column)));
            Ok(())
        })
    }
}