Skip to main content

rustapi/actions/
import_palette.rs

1use crate::{
2    editor::{DOCKMANAGER, UNDOMANAGER},
3    prelude::*,
4};
5
6pub struct ImportPalette {
7    id: TheId,
8    nodeui: TheNodeUI,
9}
10
11impl Action for ImportPalette {
12    fn new() -> Self
13    where
14        Self: Sized,
15    {
16        let nodeui: TheNodeUI = TheNodeUI::default();
17
18        Self {
19            id: TheId::named(&fl!("action_import_palette")),
20            nodeui,
21        }
22    }
23
24    fn id(&self) -> TheId {
25        self.id.clone()
26    }
27
28    fn info(&self) -> String {
29        fl!("action_import_palette_desc")
30    }
31
32    fn role(&self) -> ActionRole {
33        ActionRole::Dock
34    }
35
36    fn accel(&self) -> Option<TheAccelerator> {
37        None
38    }
39
40    fn is_applicable(
41        &self,
42        _map: &Map,
43        _ctx: &mut TheContext,
44        _server_ctx: &ServerContext,
45    ) -> bool {
46        DOCKMANAGER.read().unwrap().dock == "Tiles"
47    }
48
49    fn apply_project(
50        &self,
51        _project: &mut Project,
52        _ui: &mut TheUI,
53        ctx: &mut TheContext,
54        _server_ctx: &mut ServerContext,
55    ) {
56        ctx.ui.open_file_requester(
57            TheId::named_with_id("actionImportPalette", Uuid::new_v4()),
58            "Import Palette".into(),
59            TheFileExtension::new("Paint.net".into(), vec!["txt".to_string()]),
60        );
61    }
62
63    fn params(&self) -> TheNodeUI {
64        self.nodeui.clone()
65    }
66
67    fn handle_event(
68        &mut self,
69        event: &TheEvent,
70        project: &mut Project,
71        ui: &mut TheUI,
72        ctx: &mut TheContext,
73        server_ctx: &mut ServerContext,
74    ) -> bool {
75        match event {
76            TheEvent::FileRequesterResult(id, paths) => {
77                if id.name == "actionImportPalette" {
78                    for p in paths {
79                        if let Ok(contents) = std::fs::read_to_string(p) {
80                            let prev = project.palette.clone();
81
82                            project.palette.load_from_txt(contents);
83                            apply_palette(ui, ctx, server_ctx, project);
84
85                            let undo_atom =
86                                ProjectUndoAtom::PaletteEdit(prev, project.palette.clone());
87                            UNDOMANAGER.write().unwrap().add_undo(undo_atom, ctx);
88                            return true;
89                        }
90                    }
91                }
92            }
93            _ => {}
94        }
95        false
96    }
97}