Skip to main content

rvlib/
main_loop.rs

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