rvlib/
main_loop.rs

1#![deny(clippy::all)]
2#![forbid(unsafe_code)]
3use crate::autosave::{autosave, AUTOSAVE_INTERVAL_S};
4use crate::control::{Control, Info};
5use crate::drawme::ImageInfo;
6use crate::events::{Events, KeyCode};
7use crate::file_util::{get_prj_name, DEFAULT_PRJ_PATH};
8use crate::history::{History, Record};
9use crate::menu::{are_tools_active, Menu, ToolSelectMenu};
10use crate::result::trace_ok_err;
11use crate::tools::{
12    make_tool_vec, Manipulate, ToolState, ToolWrapper, ALWAYS_ACTIVE_ZOOM, BBOX_NAME, ZOOM_NAME,
13};
14use crate::util::Visibility;
15use crate::world::World;
16use crate::{apply_tool_method_mut, httpserver, image_util, Annotation, UpdateView};
17use egui::Context;
18use image::{DynamicImage, GenericImageView};
19use image::{ImageBuffer, Rgb};
20use rvimage_domain::{PtI, RvResult, ShapeF};
21use std::collections::HashMap;
22use std::fmt::Debug;
23use std::mem;
24use std::path::{Path, PathBuf};
25use std::sync::mpsc::Receiver;
26use std::time::Instant;
27use tracing::{error, info, warn};
28
29const START_WIDTH: u32 = 640;
30const START_HEIGHT: u32 = 480;
31
32fn pos_2_string_gen<T>(im: &T, x: u32, y: u32) -> String
33where
34    T: GenericImageView,
35    <T as GenericImageView>::Pixel: Debug,
36{
37    let p = format!("{:?}", im.get_pixel(x, y));
38    format!("({x}, {y}) -> ({})", &p[6..p.len() - 2])
39}
40
41fn pos_2_string(im: &DynamicImage, x: u32, y: u32) -> String {
42    if x < im.width() && y < im.height() {
43        image_util::apply_to_matched_image(
44            im,
45            |im| pos_2_string_gen(im, x, y),
46            |im| pos_2_string_gen(im, x, y),
47            |im| pos_2_string_gen(im, x, y),
48            |im| pos_2_string_gen(im, x, y),
49        )
50    } else {
51        "".to_string()
52    }
53}
54
55fn get_pixel_on_orig_str(world: &World, mouse_pos: &Option<PtI>) -> Option<String> {
56    mouse_pos.map(|p| pos_2_string(world.data.im_background(), p.x, p.y))
57}
58
59fn apply_tools(
60    tools: &mut [ToolState],
61    mut world: World,
62    mut history: History,
63    input_event: &Events,
64) -> (World, History) {
65    let aaz = tools
66        .iter_mut()
67        .find(|t| t.name == ALWAYS_ACTIVE_ZOOM)
68        .unwrap();
69    (world, history) = apply_tool_method_mut!(aaz, events_tf, world, history, input_event);
70    let aaz_hbu = apply_tool_method_mut!(aaz, has_been_used, input_event);
71    let not_aaz = tools
72        .iter_mut()
73        .filter(|t| t.name != ALWAYS_ACTIVE_ZOOM && t.is_active());
74    for t in not_aaz {
75        (world, history) = apply_tool_method_mut!(t, events_tf, world, history, input_event);
76        if aaz_hbu == Some(true) {
77            (world, history) = apply_tool_method_mut!(t, on_always_active_zoom, world, history);
78        }
79    }
80    (world, history)
81}
82
83macro_rules! activate_tool_event {
84    ($key:ident, $name:expr, $input:expr, $rat:expr, $tools:expr) => {
85        if $input.held_alt() && $input.pressed(KeyCode::$key) {
86            $rat = Some(
87                $tools
88                    .iter()
89                    .enumerate()
90                    .find(|(_, t)| t.name == $name)
91                    .unwrap()
92                    .0,
93            );
94        }
95    };
96}
97
98fn empty_world() -> World {
99    World::from_real_im(
100        DynamicImage::ImageRgb8(ImageBuffer::<Rgb<u8>, _>::new(START_WIDTH, START_HEIGHT)),
101        HashMap::new(),
102        None,
103        None,
104        Path::new(""),
105        None,
106    )
107}
108
109fn find_active_tool(tools: &[ToolState]) -> Option<&str> {
110    tools
111        .iter()
112        .find(|t| t.is_active() && !t.is_always_active())
113        .map(|t| t.name)
114}
115
116pub struct MainEventLoop {
117    menu: Menu,
118    tools_select_menu: ToolSelectMenu,
119    world: World,
120    ctrl: Control,
121    history: History,
122    tools: Vec<ToolState>,
123    recently_clicked_tool_idx: Option<usize>,
124    rx_from_http: Option<Receiver<RvResult<String>>>,
125    http_addr: String,
126    autosave_timer: Instant,
127}
128impl Default for MainEventLoop {
129    fn default() -> Self {
130        let file_path = std::env::args().nth(1).map(PathBuf::from);
131        Self::new(file_path)
132    }
133}
134
135impl MainEventLoop {
136    pub fn new(prj_file_path: Option<PathBuf>) -> Self {
137        let ctrl = Control::new();
138
139        let mut world = empty_world();
140        let mut tools = make_tool_vec();
141        for t in &mut tools {
142            if t.is_active() {
143                (world, _) = t.activate(world, History::default());
144            }
145        }
146        let http_addr = ctrl.http_address();
147        // http server state
148        let rx_from_http = if let Ok((_, rx)) = httpserver::launch(http_addr.clone()) {
149            Some(rx)
150        } else {
151            None
152        };
153        let mut self_ = Self {
154            world,
155            ctrl,
156            tools,
157            http_addr,
158            tools_select_menu: ToolSelectMenu::default(),
159            menu: Menu::default(),
160            history: History::default(),
161            recently_clicked_tool_idx: None,
162            rx_from_http,
163            autosave_timer: Instant::now(),
164        };
165
166        trace_ok_err(self_.load_prj_during_startup(prj_file_path));
167        self_
168    }
169    pub fn one_iteration(
170        &mut self,
171        e: &Events,
172        ui_image_rect: Option<ShapeF>,
173        tmp_anno_buffer: Option<Annotation>,
174        ctx: &Context,
175    ) -> RvResult<(UpdateView, &str)> {
176        self.world.set_image_rect(ui_image_rect);
177        self.world.update_view.tmp_anno_buffer = tmp_anno_buffer;
178        let project_loaded_in_curr_iter = self.menu.ui(
179            ctx,
180            &mut self.ctrl,
181            &mut self.world.data.tools_data_map,
182            find_active_tool(&self.tools),
183        );
184        self.world.data.meta_data.ssh_cfg = Some(self.ctrl.cfg.ssh_cfg());
185        if project_loaded_in_curr_iter {
186            for t in &mut self.tools {
187                self.world = t.deactivate(mem::take(&mut self.world));
188            }
189        }
190        if let Some(elf) = &self.ctrl.log_export_path {
191            trace_ok_err(self.ctrl.export_logs(elf));
192        }
193        if self.ctrl.log_export_path.is_some() {
194            self.ctrl.log_export_path = None;
195        }
196        if e.held_ctrl() && e.pressed(KeyCode::S) {
197            let prj_path = self.ctrl.cfg.current_prj_path().to_path_buf();
198            if let Err(e) = self
199                .ctrl
200                .save(prj_path, &self.world.data.tools_data_map, true)
201            {
202                self.menu
203                    .show_info(Info::Error(format!("could not save project due to {e:?}")));
204            }
205        }
206        egui::SidePanel::right("my_panel")
207            .show(ctx, |ui| {
208                ui.vertical(|ui| {
209                    self.tools_select_menu.ui(
210                        ui,
211                        &mut self.tools,
212                        &mut self.world.data.tools_data_map,
213                    )
214                })
215                .inner
216            })
217            .inner?;
218
219        // tool activation
220        if self.recently_clicked_tool_idx.is_none() {
221            self.recently_clicked_tool_idx = self.tools_select_menu.recently_clicked_tool();
222        }
223        if let (Some(idx_active), Some(_)) = (
224            self.recently_clicked_tool_idx,
225            &self.world.data.meta_data.file_path_absolute(),
226        ) {
227            if !self.ctrl.flags().is_loading_screen_active {
228                // first deactivate, then activate
229                for (i, t) in self.tools.iter_mut().enumerate() {
230                    if i != idx_active && t.is_active() && !t.is_always_active() {
231                        let meta_data = self.ctrl.meta_data(
232                            self.ctrl.file_selected_idx,
233                            Some(self.ctrl.flags().is_loading_screen_active),
234                        );
235                        self.world.data.meta_data = meta_data;
236                        self.world = t.deactivate(mem::take(&mut self.world));
237                    }
238                }
239                for (i, t) in self.tools.iter_mut().enumerate() {
240                    if i == idx_active {
241                        (self.world, self.history) =
242                            t.activate(mem::take(&mut self.world), mem::take(&mut self.history));
243                    }
244                }
245                self.recently_clicked_tool_idx = None;
246            }
247        }
248
249        if e.held_alt() && e.pressed(KeyCode::Q) {
250            info!("deactivate all tools");
251            let was_any_tool_active = self
252                .tools
253                .iter()
254                .any(|t| t.is_active() && !t.is_always_active());
255            for t in self.tools.iter_mut() {
256                if !t.is_always_active() && t.is_active() {
257                    let meta_data = self.ctrl.meta_data(
258                        self.ctrl.file_selected_idx,
259                        Some(self.ctrl.flags().is_loading_screen_active),
260                    );
261                    self.world.data.meta_data = meta_data;
262                    self.world = t.deactivate(mem::take(&mut self.world));
263                }
264            }
265            if was_any_tool_active {
266                self.history
267                    .push(Record::new(self.world.clone(), "deactivation of all tools"));
268            }
269        }
270        // tool activation keyboard shortcuts
271        activate_tool_event!(B, BBOX_NAME, e, self.recently_clicked_tool_idx, self.tools);
272        activate_tool_event!(Z, ZOOM_NAME, e, self.recently_clicked_tool_idx, self.tools);
273
274        if e.held_ctrl() && e.pressed(KeyCode::M) {
275            self.menu.toggle();
276        }
277        if e.released(KeyCode::F5) {
278            if let Err(e) = self.ctrl.reload(None) {
279                self.menu
280                    .show_info(Info::Error(format!("could not reload due to {e:?}")));
281            }
282        }
283        if e.pressed(KeyCode::PageDown) {
284            self.ctrl.paths_navigator.next();
285        }
286        if e.pressed(KeyCode::PageUp) {
287            self.ctrl.paths_navigator.prev();
288        }
289        if e.pressed(KeyCode::Escape) {
290            self.world.set_zoom_box(None);
291        }
292
293        // check for new image requests from http server
294        let rx_match = &self.rx_from_http.as_ref().map(|rx| rx.try_iter().last());
295        if let Some(Some(Ok(file_label))) = rx_match {
296            self.ctrl.paths_navigator.select_file_label(file_label);
297            self.ctrl
298                .paths_navigator
299                .activate_scroll_to_selected_label();
300        } else if let Some(Some(Err(e))) = rx_match {
301            // if the server thread sends an error we restart the server
302            warn!("{e:?}");
303            (self.http_addr, self.rx_from_http) =
304                match httpserver::restart_with_increased_port(&self.http_addr) {
305                    Ok(x) => x,
306                    Err(e) => {
307                        error!("{e:?}");
308                        (self.http_addr.to_string(), None)
309                    }
310                };
311        }
312
313        // load new image if requested by a menu click or by the http server
314        let world_idx_pair = if e.held_ctrl() && e.pressed(KeyCode::Z) {
315            info!("undo");
316            self.ctrl.undo(&mut self.history)
317        } else if e.held_ctrl() && e.pressed(KeyCode::Y) {
318            info!("redo");
319            self.ctrl.redo(&mut self.history)
320        } else {
321            match self
322                .ctrl
323                .load_new_image_if_triggered(&self.world, &mut self.history)
324            {
325                Ok(iip) => iip,
326                Err(e) => {
327                    self.menu.show_info(Info::Error(format!("{e:?}")));
328                    None
329                }
330            }
331        };
332
333        if let Some((world, file_label_idx)) = world_idx_pair {
334            self.world = world;
335            if let Some(active_tool_name) = find_active_tool(&self.tools) {
336                self.world
337                    .request_redraw_annotations(active_tool_name, Visibility::All);
338            }
339            if file_label_idx.is_some() {
340                self.ctrl.paths_navigator.select_label_idx(file_label_idx);
341                let meta_data = self.ctrl.meta_data(
342                    self.ctrl.file_selected_idx,
343                    Some(self.ctrl.flags().is_loading_screen_active),
344                );
345                self.world.data.meta_data = meta_data;
346                for t in &mut self.tools {
347                    if t.is_active() {
348                        (self.world, self.history) = t
349                            .file_changed(mem::take(&mut self.world), mem::take(&mut self.history));
350                    }
351                }
352            }
353        }
354
355        if are_tools_active(&self.menu, &self.tools_select_menu) {
356            let meta_data = self.ctrl.meta_data(
357                self.ctrl.file_selected_idx,
358                Some(self.ctrl.flags().is_loading_screen_active),
359            );
360            self.world.data.meta_data = meta_data;
361            (self.world, self.history) = apply_tools(
362                &mut self.tools,
363                mem::take(&mut self.world),
364                mem::take(&mut self.history),
365                e,
366            );
367        }
368
369        // show position and rgb value
370        if let Some(idx) = self.ctrl.paths_navigator.file_label_selected_idx() {
371            let pixel_pos = e.mouse_pos_on_orig.map(|mp| mp.into());
372            let data_point = get_pixel_on_orig_str(&self.world, &pixel_pos);
373            let shape = self.world.shape_orig();
374            let file_label = self.ctrl.file_label(idx);
375            let active_tool = self.tools.iter().find(|t| t.is_active());
376            let tool_string = if let Some(t) = active_tool {
377                format!("{} tool is active", t.name)
378            } else {
379                "".to_string()
380            };
381            let s = match data_point {
382                Some(s) => ImageInfo {
383                    filename: file_label.to_string(),
384                    shape_info: format!("{}x{}", shape.w, shape.h),
385                    pixel_value: s,
386                    tool_info: tool_string,
387                },
388                None => ImageInfo {
389                    filename: file_label.to_string(),
390                    shape_info: format!("{}x{}", shape.w, shape.h),
391                    pixel_value: "(x, y) -> (r, g, b)".to_string(),
392                    tool_info: tool_string,
393                },
394            };
395            self.world.update_view.image_info = Some(s);
396        }
397        if let Some(n_autosaves) = self.ctrl.cfg.usr.n_autosaves {
398            if self.autosave_timer.elapsed().as_secs() > AUTOSAVE_INTERVAL_S {
399                self.autosave_timer = Instant::now();
400                let homefolder = self.ctrl.cfg.home_folder().to_string();
401                let current_prj_path = self.ctrl.cfg.current_prj_path().to_path_buf();
402                let save_prj = |prj_path| {
403                    self.ctrl
404                        .save(prj_path, &self.world.data.tools_data_map, false)
405                };
406                trace_ok_err(autosave(
407                    &current_prj_path,
408                    homefolder,
409                    n_autosaves,
410                    save_prj,
411                ));
412            }
413        }
414
415        Ok((
416            mem::take(&mut self.world.update_view),
417            get_prj_name(self.ctrl.cfg.current_prj_path(), None),
418        ))
419    }
420    pub fn load_prj_during_startup(&mut self, file_path: Option<PathBuf>) -> RvResult<()> {
421        if let Some(file_path) = file_path {
422            info!("loaded project {file_path:?}");
423            self.world.data.tools_data_map = self.ctrl.load(file_path)?;
424        } else {
425            let pp = self.ctrl.cfg.current_prj_path().to_path_buf();
426            // load last project
427            match self.ctrl.load(pp) {
428                Ok(td) => {
429                    info!(
430                        "loaded last saved project {:?}",
431                        self.ctrl.cfg.current_prj_path()
432                    );
433                    self.world.data.tools_data_map = td;
434                }
435                Err(e) => {
436                    if DEFAULT_PRJ_PATH.as_os_str() != self.ctrl.cfg.current_prj_path().as_os_str()
437                    {
438                        info!(
439                            "could not read last saved project {:?} due to {e:?} ",
440                            self.ctrl.cfg.current_prj_path()
441                        );
442                    }
443                }
444            }
445        }
446        Ok(())
447    }
448    pub fn import_prj(&mut self, file_path: &Path) -> RvResult<()> {
449        self.world.data.tools_data_map = self.ctrl.replace_with_save(file_path)?;
450        Ok(())
451    }
452}