Skip to main content

rustapi/undo/
mod.rs

1pub mod project_atoms;
2pub mod project_helper;
3pub mod project_undo;
4
5use crate::prelude::*;
6use project_undo::*;
7
8#[derive(Clone, Debug)]
9pub struct UndoManager {
10    pub max_undo: usize,
11
12    project: ProjectUndo,
13}
14
15impl Default for UndoManager {
16    fn default() -> Self {
17        Self::new()
18    }
19}
20
21impl UndoManager {
22    pub fn new() -> Self {
23        Self {
24            max_undo: 30,
25
26            project: ProjectUndo::default(),
27        }
28    }
29
30    pub fn add_undo(&mut self, atom: ProjectUndoAtom, ctx: &mut TheContext) {
31        self.project.add(atom);
32        self.project.truncate_to_limit(self.max_undo);
33        ctx.ui.set_enabled("Undo");
34        self.can_save(ctx);
35    }
36
37    pub fn mark_saved(&mut self) {
38        self.project.mark_saved();
39    }
40
41    pub fn set_undo_state_to_ui(&self, ctx: &mut TheContext) {
42        if !self.project.has_undo() {
43            ctx.ui.set_disabled("Undo");
44        } else {
45            ctx.ui.set_enabled("Undo");
46        }
47
48        if !self.project.has_redo() {
49            ctx.ui.set_disabled("Redo");
50        } else {
51            ctx.ui.set_enabled("Redo");
52        }
53    }
54
55    pub fn undo(
56        &mut self,
57        server_ctx: &mut ServerContext,
58        project: &mut Project,
59        ui: &mut TheUI,
60        ctx: &mut TheContext,
61    ) {
62        if self.project.has_undo() {
63            self.project.undo(project, ui, ctx, server_ctx);
64        }
65
66        self.set_undo_state_to_ui(ctx);
67        self.can_save(ctx);
68    }
69
70    pub fn redo(
71        &mut self,
72        server_ctx: &mut ServerContext,
73        project: &mut Project,
74        ui: &mut TheUI,
75        ctx: &mut TheContext,
76    ) {
77        if self.project.has_redo() {
78            self.project.redo(project, ui, ctx, server_ctx);
79        }
80
81        self.set_undo_state_to_ui(ctx);
82        self.can_save(ctx);
83    }
84
85    /// Checks if the undo manager is empty and disables the save buttons if it is.
86    pub fn can_save(&self, ctx: &mut TheContext) {
87        if self.has_undo() {
88            // ctx.ui.set_disabled("Save");
89            // ctx.ui.set_disabled("Save As");
90        } else {
91            ctx.ui.set_enabled("Save");
92            ctx.ui.set_enabled("Save As");
93        }
94    }
95
96    /// Checks if the undo manager has any undoable actions.
97    pub fn has_undo(&self) -> bool {
98        if self.project.has_undo() {
99            return true;
100        }
101        false
102    }
103
104    /// Returns true if current state differs from the last saved checkpoint.
105    pub fn has_unsaved(&self) -> bool {
106        self.project.has_unsaved()
107    }
108}