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            match self
340                .ctrl
341                .load_new_image_if_triggered(&mut self.world, &mut self.history)
342            {
343                Ok(iip) => iip,
344                Err(e) => {
345                    self.menu.show_info(Info::Error(format!("{e:?}")));
346                    None
347                }
348            }
349        };
350
351        if let Some((world, file_label_idx)) = world_idx_pair {
352            self.world = world;
353            if let Some(active_tool_name) = find_active_tool(&self.tools) {
354                self.world
355                    .request_redraw_annotations(active_tool_name, Visibility::All);
356            }
357            if file_label_idx.is_some() {
358                self.ctrl.paths_navigator.select_label_idx(file_label_idx);
359                let meta_data = self.ctrl.meta_data(
360                    self.ctrl.file_selected_idx,
361                    Some(self.ctrl.flags().is_loading_screen_active),
362                );
363                self.world.data.meta_data = meta_data;
364                for t in &mut self.tools {
365                    if t.is_active() {
366                        (self.world, self.history) = t
367                            .file_changed(mem::take(&mut self.world), mem::take(&mut self.history));
368                    }
369                }
370            }
371        }
372
373        if are_tools_active(&self.menu, &self.tools_select_menu) {
374            let meta_data = self.ctrl.meta_data(
375                self.ctrl.file_selected_idx,
376                Some(self.ctrl.flags().is_loading_screen_active),
377            );
378            self.world.data.meta_data = meta_data;
379            (self.world, self.history) = apply_tools(
380                &mut self.tools,
381                mem::take(&mut self.world),
382                mem::take(&mut self.history),
383                e,
384            );
385        }
386
387        // show position and rgb value
388        if let Some(idx) = self.ctrl.paths_navigator.file_label_selected_idx() {
389            let pixel_pos = e.mouse_pos_on_orig.map(|mp| mp.into());
390            let data_point = get_pixel_on_orig_str(&self.world, &pixel_pos);
391            let shape = self.world.shape_orig();
392            let file_label = self.ctrl.file_label(idx);
393            let active_tool = self.tools.iter().find(|t| t.is_active());
394            let tool_string = if let Some(t) = active_tool {
395                format!("{} tool is active", t.name)
396            } else {
397                "".to_string()
398            };
399            let s = match data_point {
400                Some(s) => ImageInfo {
401                    filename: file_label.to_string(),
402                    shape_info: format!("{}x{}", shape.w, shape.h),
403                    pixel_value: s,
404                    tool_info: tool_string,
405                },
406                None => ImageInfo {
407                    filename: file_label.to_string(),
408                    shape_info: format!("{}x{}", shape.w, shape.h),
409                    pixel_value: "(x, y) -> (r, g, b)".to_string(),
410                    tool_info: tool_string,
411                },
412            };
413            self.world.update_view.image_info = Some(s);
414        }
415        if let Some(n_autosaves) = self.ctrl.cfg.usr.n_autosaves {
416            if self.autosave_timer.elapsed().as_secs() > AUTOSAVE_INTERVAL_S {
417                self.autosave_timer = Instant::now();
418                let homefolder = self.ctrl.cfg.home_folder().to_string();
419                let current_prj_path = self.ctrl.cfg.current_prj_path().to_path_buf();
420                let save_prj = |prj_path| {
421                    self.ctrl
422                        .save(prj_path, &self.world.data.tools_data_map, false)
423                };
424                trace_ok_err(autosave(
425                    &current_prj_path,
426                    homefolder,
427                    n_autosaves,
428                    save_prj,
429                ));
430            }
431        }
432
433        Ok((
434            mem::take(&mut self.world.update_view),
435            get_prj_name(self.ctrl.cfg.current_prj_path(), None),
436        ))
437    }
438    pub fn load_prj_during_startup(&mut self, file_path: Option<PathBuf>) -> RvResult<()> {
439        if let Some(file_path) = file_path {
440            info!("loaded project {file_path:?}");
441            self.world.data.tools_data_map = self.ctrl.load(file_path)?;
442        } else {
443            let pp = self.ctrl.cfg.current_prj_path().to_path_buf();
444            // load last project
445            match self.ctrl.load(pp) {
446                Ok(td) => {
447                    info!(
448                        "loaded last saved project {:?}",
449                        self.ctrl.cfg.current_prj_path()
450                    );
451                    self.world.data.tools_data_map = td;
452                }
453                Err(e) => {
454                    if DEFAULT_PRJ_PATH.as_os_str() != self.ctrl.cfg.current_prj_path().as_os_str()
455                    {
456                        info!(
457                            "could not read last saved project {:?} due to {e:?} ",
458                            self.ctrl.cfg.current_prj_path()
459                        );
460                    }
461                }
462            }
463        }
464        Ok(())
465    }
466    pub fn import_prj(&mut self, file_path: &Path) -> RvResult<()> {
467        self.world.data.tools_data_map = self.ctrl.replace_with_save(file_path)?;
468        Ok(())
469    }
470}