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    next_image_held_timer: Instant,
128}
129impl Default for MainEventLoop {
130    fn default() -> Self {
131        let file_path = std::env::args().nth(1).map(PathBuf::from);
132        Self::new(file_path)
133    }
134}
135
136impl MainEventLoop {
137    pub fn new(prj_file_path: Option<PathBuf>) -> Self {
138        let ctrl = Control::new();
139
140        let mut world = empty_world();
141        let mut tools = make_tool_vec();
142        for t in &mut tools {
143            if t.is_active() {
144                (world, _) = t.activate(world, History::default());
145            }
146        }
147        let http_addr = ctrl.http_address();
148        // http server state
149        let rx_from_http = if let Ok((_, rx)) = httpserver::launch(http_addr.clone()) {
150            Some(rx)
151        } else {
152            None
153        };
154        let mut self_ = Self {
155            world,
156            ctrl,
157            tools,
158            http_addr,
159            tools_select_menu: ToolSelectMenu::default(),
160            menu: Menu::default(),
161            history: History::default(),
162            recently_clicked_tool_idx: None,
163            rx_from_http,
164            autosave_timer: Instant::now(),
165            next_image_held_timer: Instant::now(),
166        };
167
168        trace_ok_err(self_.load_prj_during_startup(prj_file_path));
169        self_
170    }
171    pub fn one_iteration(
172        &mut self,
173        e: &Events,
174        ui_image_rect: Option<ShapeF>,
175        tmp_anno_buffer: Option<Annotation>,
176        ctx: &Context,
177    ) -> RvResult<(UpdateView, &str)> {
178        self.world.set_image_rect(ui_image_rect);
179        self.world.update_view.tmp_anno_buffer = tmp_anno_buffer;
180        let project_loaded_in_curr_iter = self.menu.ui(
181            ctx,
182            &mut self.ctrl,
183            &mut self.world.data.tools_data_map,
184            find_active_tool(&self.tools),
185        );
186        self.world.data.meta_data.ssh_cfg = Some(self.ctrl.cfg.ssh_cfg());
187        if project_loaded_in_curr_iter {
188            for t in &mut self.tools {
189                self.world = t.deactivate(mem::take(&mut self.world));
190            }
191        }
192        if let Some(elf) = &self.ctrl.log_export_path {
193            trace_ok_err(self.ctrl.export_logs(elf));
194        }
195        if self.ctrl.log_export_path.is_some() {
196            self.ctrl.log_export_path = None;
197        }
198        if e.held_ctrl() && e.pressed(KeyCode::S) {
199            let prj_path = self.ctrl.cfg.current_prj_path().to_path_buf();
200            if let Err(e) = self
201                .ctrl
202                .save(prj_path, &self.world.data.tools_data_map, true)
203            {
204                self.menu
205                    .show_info(Info::Error(format!("could not save project due to {e:?}")));
206            }
207        }
208        egui::SidePanel::right("my_panel")
209            .show(ctx, |ui| {
210                ui.vertical(|ui| {
211                    self.tools_select_menu.ui(
212                        ui,
213                        &mut self.tools,
214                        &mut self.world.data.tools_data_map,
215                    )
216                })
217                .inner
218            })
219            .inner?;
220
221        // tool activation
222        if self.recently_clicked_tool_idx.is_none() {
223            self.recently_clicked_tool_idx = self.tools_select_menu.recently_clicked_tool();
224        }
225        if let (Some(idx_active), Some(_)) = (
226            self.recently_clicked_tool_idx,
227            &self.world.data.meta_data.file_path_absolute(),
228        ) {
229            if !self.ctrl.flags().is_loading_screen_active {
230                // first deactivate, then activate
231                for (i, t) in self.tools.iter_mut().enumerate() {
232                    if i != idx_active && t.is_active() && !t.is_always_active() {
233                        let meta_data = self.ctrl.meta_data(
234                            self.ctrl.file_selected_idx,
235                            Some(self.ctrl.flags().is_loading_screen_active),
236                        );
237                        self.world.data.meta_data = meta_data;
238                        self.world = t.deactivate(mem::take(&mut self.world));
239                    }
240                }
241                for (i, t) in self.tools.iter_mut().enumerate() {
242                    if i == idx_active {
243                        (self.world, self.history) =
244                            t.activate(mem::take(&mut self.world), mem::take(&mut self.history));
245                    }
246                }
247                self.recently_clicked_tool_idx = None;
248            }
249        }
250
251        if e.held_alt() && e.pressed(KeyCode::Q) {
252            info!("deactivate all tools");
253            let was_any_tool_active = self
254                .tools
255                .iter()
256                .any(|t| t.is_active() && !t.is_always_active());
257            for t in self.tools.iter_mut() {
258                if !t.is_always_active() && t.is_active() {
259                    let meta_data = self.ctrl.meta_data(
260                        self.ctrl.file_selected_idx,
261                        Some(self.ctrl.flags().is_loading_screen_active),
262                    );
263                    self.world.data.meta_data = meta_data;
264                    self.world = t.deactivate(mem::take(&mut self.world));
265                }
266            }
267            if was_any_tool_active {
268                self.history
269                    .push(Record::new(self.world.clone(), "deactivation of all tools"));
270            }
271        }
272        // tool activation keyboard shortcuts
273        activate_tool_event!(B, BBOX_NAME, e, self.recently_clicked_tool_idx, self.tools);
274        activate_tool_event!(Z, ZOOM_NAME, e, self.recently_clicked_tool_idx, self.tools);
275
276        const DOUBLE_SKIP_TH_MS: u128 = 500;
277        if e.held_ctrl() && e.pressed(KeyCode::M) {
278            self.menu.toggle();
279        } else if e.released(KeyCode::F5) {
280            if let Err(e) = self.ctrl.reload(None) {
281                self.menu
282                    .show_info(Info::Error(format!("could not reload due to {e:?}")));
283            }
284        } else if e.held(KeyCode::PageDown) || e.held(KeyCode::PageUp) {
285            if self.world.data.meta_data.flags.is_loading_screen_active == Some(true) {
286                self.next_image_held_timer = Instant::now();
287            } else {
288                let elapsed = self.next_image_held_timer.elapsed().as_millis();
289                let interval = self.ctrl.cfg.usr.image_change_delay_on_held_key_ms as u128;
290                if elapsed > interval {
291                    if e.held(KeyCode::PageDown) {
292                        self.ctrl.paths_navigator.next();
293                    } else if e.held(KeyCode::PageUp) {
294                        self.ctrl.paths_navigator.prev();
295                    }
296                    self.next_image_held_timer = Instant::now();
297                }
298            }
299        } else if e.released(KeyCode::PageDown)
300            && self.next_image_held_timer.elapsed().as_millis() > DOUBLE_SKIP_TH_MS
301        {
302            self.ctrl.paths_navigator.next();
303        } else if e.released(KeyCode::PageUp)
304            && self.next_image_held_timer.elapsed().as_millis() > DOUBLE_SKIP_TH_MS
305        {
306            self.ctrl.paths_navigator.prev();
307        } else if e.released(KeyCode::Escape) {
308            self.world.set_zoom_box(None);
309        }
310
311        // check for new image requests from http server
312        let rx_match = &self.rx_from_http.as_ref().map(|rx| rx.try_iter().last());
313        if let Some(Some(Ok(file_label))) = rx_match {
314            self.ctrl.paths_navigator.select_file_label(file_label);
315            self.ctrl
316                .paths_navigator
317                .activate_scroll_to_selected_label();
318        } else if let Some(Some(Err(e))) = rx_match {
319            // if the server thread sends an error we restart the server
320            warn!("{e:?}");
321            (self.http_addr, self.rx_from_http) =
322                match httpserver::restart_with_increased_port(&self.http_addr) {
323                    Ok(x) => x,
324                    Err(e) => {
325                        error!("{e:?}");
326                        (self.http_addr.to_string(), None)
327                    }
328                };
329        }
330
331        // load new image if requested by a menu click or by the http server
332        let world_idx_pair = if e.held_ctrl() && e.pressed(KeyCode::Z) {
333            info!("undo");
334            self.ctrl.undo(&mut self.history)
335        } else if e.held_ctrl() && e.pressed(KeyCode::Y) {
336            info!("redo");
337            self.ctrl.redo(&mut self.history)
338        } else {
339            let mut world = self.world.clone();
340            match self
341                .ctrl
342                .load_new_image_if_triggered(&mut world, &mut self.history)
343            {
344                Ok(iip) => iip,
345                Err(e) => {
346                    self.menu.show_info(Info::Error(format!("{e:?}")));
347                    None
348                }
349            }
350        };
351
352        if let Some((world, file_label_idx)) = world_idx_pair {
353            self.world = world;
354            if let Some(active_tool_name) = find_active_tool(&self.tools) {
355                self.world
356                    .request_redraw_annotations(active_tool_name, Visibility::All);
357            }
358            if file_label_idx.is_some() {
359                self.ctrl.paths_navigator.select_label_idx(file_label_idx);
360                let meta_data = self.ctrl.meta_data(
361                    self.ctrl.file_selected_idx,
362                    Some(self.ctrl.flags().is_loading_screen_active),
363                );
364                self.world.data.meta_data = meta_data;
365                for t in &mut self.tools {
366                    if t.is_active() {
367                        (self.world, self.history) = t
368                            .file_changed(mem::take(&mut self.world), mem::take(&mut self.history));
369                    }
370                }
371            }
372        }
373
374        if are_tools_active(&self.menu, &self.tools_select_menu) {
375            let meta_data = self.ctrl.meta_data(
376                self.ctrl.file_selected_idx,
377                Some(self.ctrl.flags().is_loading_screen_active),
378            );
379            self.world.data.meta_data = meta_data;
380            (self.world, self.history) = apply_tools(
381                &mut self.tools,
382                mem::take(&mut self.world),
383                mem::take(&mut self.history),
384                e,
385            );
386        }
387
388        // show position and rgb value
389        if let Some(idx) = self.ctrl.paths_navigator.file_label_selected_idx() {
390            let pixel_pos = e.mouse_pos_on_orig.map(|mp| mp.into());
391            let data_point = get_pixel_on_orig_str(&self.world, &pixel_pos);
392            let shape = self.world.shape_orig();
393            let file_label = self.ctrl.file_label(idx);
394            let active_tool = self.tools.iter().find(|t| t.is_active());
395            let tool_string = if let Some(t) = active_tool {
396                format!("{} tool is active", t.name)
397            } else {
398                "".to_string()
399            };
400            let s = match data_point {
401                Some(s) => ImageInfo {
402                    filename: file_label.to_string(),
403                    shape_info: format!("{}x{}", shape.w, shape.h),
404                    pixel_value: s,
405                    tool_info: tool_string,
406                },
407                None => ImageInfo {
408                    filename: file_label.to_string(),
409                    shape_info: format!("{}x{}", shape.w, shape.h),
410                    pixel_value: "(x, y) -> (r, g, b)".to_string(),
411                    tool_info: tool_string,
412                },
413            };
414            self.world.update_view.image_info = Some(s);
415        }
416        if let Some(n_autosaves) = self.ctrl.cfg.usr.n_autosaves {
417            if self.autosave_timer.elapsed().as_secs() > AUTOSAVE_INTERVAL_S {
418                self.autosave_timer = Instant::now();
419                let homefolder = self.ctrl.cfg.home_folder().to_string();
420                let current_prj_path = self.ctrl.cfg.current_prj_path().to_path_buf();
421                let save_prj = |prj_path| {
422                    self.ctrl
423                        .save(prj_path, &self.world.data.tools_data_map, false)
424                };
425                trace_ok_err(autosave(
426                    &current_prj_path,
427                    homefolder,
428                    n_autosaves,
429                    save_prj,
430                ));
431            }
432        }
433
434        Ok((
435            mem::take(&mut self.world.update_view),
436            get_prj_name(self.ctrl.cfg.current_prj_path(), None),
437        ))
438    }
439    pub fn load_prj_during_startup(&mut self, file_path: Option<PathBuf>) -> RvResult<()> {
440        if let Some(file_path) = file_path {
441            info!("loaded project {file_path:?}");
442            self.world.data.tools_data_map = self.ctrl.load(file_path)?;
443        } else {
444            let pp = self.ctrl.cfg.current_prj_path().to_path_buf();
445            // load last project
446            match self.ctrl.load(pp) {
447                Ok(td) => {
448                    info!(
449                        "loaded last saved project {:?}",
450                        self.ctrl.cfg.current_prj_path()
451                    );
452                    self.world.data.tools_data_map = td;
453                }
454                Err(e) => {
455                    if DEFAULT_PRJ_PATH.as_os_str() != self.ctrl.cfg.current_prj_path().as_os_str()
456                    {
457                        info!(
458                            "could not read last saved project {:?} due to {e:?} ",
459                            self.ctrl.cfg.current_prj_path()
460                        );
461                    }
462                }
463            }
464        }
465        Ok(())
466    }
467    pub fn import_prj(&mut self, file_path: &Path) -> RvResult<()> {
468        self.world.data.tools_data_map = self.ctrl.replace_with_save(file_path)?;
469        Ok(())
470    }
471}