rvlib/
world.rs

1use crate::drawme::{Annotation, UpdateImage, UpdateTmpAnno};
2use crate::meta_data::MetaData;
3use crate::result::trace_ok_err;
4use crate::tools::{add_tools_initial_data, get_visible_inactive_names};
5use crate::tools_data::annotations::{ClipboardData, InstanceAnnotations};
6use crate::tools_data::{
7    self, vis_from_lfoption, ExportAsCoco, LabelInfo, ToolSpecifics, ToolsData, ToolsDataMap,
8};
9use crate::types::ViewImage;
10use crate::util::Visibility;
11use crate::{image_util, InstanceAnnotate, UpdatePermAnnos, UpdateView, UpdateZoomBox};
12use image::DynamicImage;
13use rvimage_domain::{BbF, RvError, RvResult, ShapeF, ShapeI};
14use std::path::Path;
15use std::{fmt::Debug, mem};
16
17pub(super) fn get<'a>(
18    world: &'a World,
19    actor: &'static str,
20    error_msg: &'a str,
21) -> RvResult<&'a ToolsData> {
22    world
23        .data
24        .tools_data_map
25        .get(actor)
26        .ok_or_else(|| RvError::new(error_msg))
27}
28pub fn get_specific<T>(
29    f: impl Fn(&ToolSpecifics) -> RvResult<&T>,
30    data: RvResult<&ToolsData>,
31) -> Option<&T> {
32    trace_ok_err(data.map(|d| &d.specifics).and_then(f))
33}
34pub(super) fn get_mut<'a>(
35    world: &'a mut World,
36    actor: &'static str,
37    error_msg: &'a str,
38) -> RvResult<&'a mut ToolsData> {
39    world
40        .data
41        .tools_data_map
42        .get_mut(actor)
43        .ok_or_else(|| RvError::new(error_msg))
44}
45pub fn get_specific_mut<T>(
46    f_data_access: impl FnMut(&mut ToolSpecifics) -> RvResult<&mut T>,
47    data: RvResult<&mut ToolsData>,
48) -> Option<&mut T> {
49    trace_ok_err(data.map(|d| &mut d.specifics).and_then(f_data_access))
50}
51
52/// Often needed meta data when accessing annotations, see different `AnnoMetaAccessors` structs.
53pub trait MetaDataAccess {
54    fn get_core_options(world: &World) -> Option<&tools_data::Options>;
55    fn get_core_options_mut(world: &mut World) -> Option<&mut tools_data::Options>;
56    fn get_track_changes_str(world: &World) -> Option<&'static str>;
57    fn get_label_info(world: &World) -> Option<&LabelInfo>;
58    fn get_label_info_mut(world: &mut World) -> Option<&mut LabelInfo>;
59}
60
61#[macro_export]
62macro_rules! tools_data_accessors {
63    ($actor_name:expr, $missing_data_msg:expr, $data_module:ident, $data_type:ident, $data_func:ident, $data_func_mut:ident) => {
64        #[allow(unused)]
65        pub(super) fn get_data(
66            world: &World,
67        ) -> rvimage_domain::RvResult<&$crate::tools_data::ToolsData> {
68            $crate::world::get(world, $actor_name, $missing_data_msg)
69        }
70        #[allow(unused)]
71        pub(super) fn get_specific(world: &World) -> Option<&$data_module::$data_type> {
72            $crate::world::get_specific(tools_data::$data_func, get_data(world))
73        }
74        pub(super) fn get_data_mut(
75            world: &mut World,
76        ) -> rvimage_domain::RvResult<&mut $crate::tools_data::ToolsData> {
77            $crate::world::get_mut(world, $actor_name, $missing_data_msg)
78        }
79        pub(super) fn get_specific_mut(world: &mut World) -> Option<&mut $data_module::$data_type> {
80            $crate::world::get_specific_mut(tools_data::$data_func_mut, get_data_mut(world))
81        }
82    };
83}
84#[macro_export]
85macro_rules! tools_data_accessors_objects {
86    ($actor_name:expr, $missing_data_msg:expr, $data_module:ident, $data_type:ident, $data_func:ident, $data_func_mut:ident) => {
87        pub(super) fn get_options(world: &World) -> Option<&$data_module::Options> {
88            get_specific(world).map(|d| &d.options)
89        }
90        pub(super) fn get_options_mut(world: &mut World) -> Option<&mut $data_module::Options> {
91            get_specific_mut(world).map(|d| &mut d.options)
92        }
93        pub(super) fn get_track_changes_str(world: &World) -> Option<&'static str> {
94            lazy_static::lazy_static! {
95                static ref TRACK_CHANGE_STR: String = $crate::tools::core::make_track_changes_str(ACTOR_NAME);
96            };
97            let track_changes =
98                get_options(world).map(|o| o.core.track_changes) == Some(true);
99            $crate::util::wrap_if(&TRACK_CHANGE_STR, track_changes)
100        }
101
102        pub(super) fn get_label_info(world: &World) -> Option<&LabelInfo> {
103            get_specific(world).map(|d| &d.label_info)
104        }
105
106        /// when you access annotations, you often also need this metadata
107        pub(super) struct DataAccessors;
108        impl $crate::world::MetaDataAccess for DataAccessors {
109            fn get_core_options(world: &World) -> Option<&$crate::tools_data::Options> {
110                get_options(world).map(|o| &o.core)
111            }
112            fn get_core_options_mut(world: &mut World) -> Option<&mut $crate::tools_data::Options> {
113                get_options_mut(world).map(|o| &mut o.core)
114            }
115            fn get_track_changes_str(world: &World) -> Option<&'static str> {
116                get_track_changes_str(world)
117            }
118            fn get_label_info(world: &World) -> Option<&LabelInfo> {
119                get_label_info(world)
120            }
121            fn get_label_info_mut(world: &mut World) -> Option<&mut LabelInfo> {
122                get_specific_mut(world).map(|d| &mut d.label_info)
123            }
124        }
125
126        pub(super) fn get_visible(world: &World) -> Visibility {
127            let visible = get_options(world).map(|o| o.core.visible) == Some(true);
128            vis_from_lfoption(get_label_info(world), visible)
129        }
130        pub(super) fn set_visible(world: &mut World) {
131            let options_mut = get_options_mut(world);
132            if let Some(options_mut) = options_mut {
133                options_mut.core.visible = true;
134            }
135            let vis = get_visible(world);
136            world.request_redraw_annotations($actor_name, vis);
137        }
138    };
139}
140#[macro_export]
141macro_rules! world_annotations_accessor {
142    ($actor_name:expr, $access_func:ident, $error_msg:expr, $annotations_type:ty) => {
143        pub(super) fn get_annos_(
144            world: &World,
145            is_no_anno_fine: bool,
146        ) -> Option<&$annotations_type> {
147            if let Some(current_file_path) = world.data.meta_data.file_path_relative() {
148                let res = $crate::get_annos_from_tdm!(
149                    $actor_name,
150                    &world.data.tools_data_map,
151                    current_file_path,
152                    $access_func
153                );
154                if res.is_none() && !is_no_anno_fine {
155                    tracing::error!("{}", $error_msg);
156                }
157                res
158            } else {
159                None
160            }
161        }
162        #[allow(unused)]
163        pub(super) fn get_annos(world: &World) -> Option<&$annotations_type> {
164            get_annos_(world, false)
165        }
166        #[allow(unused)]
167        pub(super) fn get_annos_if_some(world: &World) -> Option<&$annotations_type> {
168            get_annos_(world, true)
169        }
170    };
171}
172#[macro_export]
173macro_rules! annotations_accessor_mut {
174    ($actor_name:expr, $access_func:ident, $error_msg:expr, $annotations_type:ty) => {
175        pub(super) fn get_annos_mut_(
176            world: &mut World,
177            is_no_anno_fine: bool,
178        ) -> Option<&mut $annotations_type> {
179            if let Some(current_file_path) = world.data.meta_data.file_path_relative() {
180                let shape_initial = *world.data.shape_initial();
181                let res = world
182                    .data
183                    .tools_data_map
184                    .get_mut($actor_name)
185                    .and_then(|x| x.specifics.$access_func().ok())
186                    .and_then(|d| d.get_annos_mut(&current_file_path, shape_initial));
187                if res.is_none() {
188                    tracing::error!("{}", $error_msg);
189                }
190                res
191            } else {
192                if !is_no_anno_fine {
193                    tracing::error!("could not find filepath in meta data")
194                };
195                None
196            }
197        }
198        pub(super) fn get_annos_mut(world: &mut World) -> Option<&mut $annotations_type> {
199            let is_no_anno_fine = world.data.meta_data.flags.is_file_list_empty == Some(true);
200            get_annos_mut_(world, is_no_anno_fine)
201        }
202    };
203}
204
205pub trait InstanceAnnoAccess<T>
206where
207    T: InstanceAnnotate,
208{
209    fn get_annos(world: &World) -> Option<&InstanceAnnotations<T>>;
210    fn get_annos_mut(world: &mut World) -> Option<&mut InstanceAnnotations<T>>;
211    fn get_clipboard(world: &World) -> Option<&ClipboardData<T>>;
212    fn set_clipboard(world: &mut World, clipboard: Option<ClipboardData<T>>);
213}
214#[macro_export]
215macro_rules! instance_annotations_accessor {
216    ($annotations_type:ty) => {
217        pub(super) struct InstanceAnnoAccessors;
218        impl $crate::world::InstanceAnnoAccess<$annotations_type> for InstanceAnnoAccessors {
219            fn get_annos(world: &World) -> Option<&$crate::tools_data::annotations::InstanceAnnotations<$annotations_type>> {
220                get_annos(world)
221            }
222            fn get_annos_mut(
223                world: &mut World,
224            ) -> Option<&mut $crate::tools_data::annotations::InstanceAnnotations<$annotations_type>> {
225                get_annos_mut(world)
226            }
227            fn get_clipboard(
228                world: &World,
229            ) -> Option<&$crate::tools_data::annotations::ClipboardData<$annotations_type>> {
230                get_specific(world).and_then(|d| d.clipboard.as_ref())
231            }
232            fn set_clipboard(
233                world: &mut World,
234                clipboard: Option<$crate::tools_data::annotations::ClipboardData<$annotations_type>>,
235            ) {
236                let specific_data = get_specific_mut(world);
237                if let Some(d) = specific_data {
238                    d.clipboard = clipboard;
239                }
240            }
241        }
242    };
243}
244
245#[derive(Clone, Default, PartialEq)]
246pub struct DataRaw {
247    im_background: DynamicImage,
248    shape_initial: ShapeI,
249    ui_image_rect: Option<ShapeF>,
250    pub meta_data: MetaData,
251    pub tools_data_map: ToolsDataMap,
252}
253
254impl DataRaw {
255    #[must_use]
256    pub fn new(
257        im_background: DynamicImage,
258        tools_data_map: ToolsDataMap,
259        meta_data: MetaData,
260        ui_image_rect: Option<ShapeF>,
261    ) -> Self {
262        let shape_initial = ShapeI::from_im(&im_background);
263        DataRaw {
264            im_background,
265            shape_initial,
266            ui_image_rect,
267            meta_data,
268            tools_data_map,
269        }
270    }
271
272    #[must_use]
273    pub fn im_background(&self) -> &DynamicImage {
274        &self.im_background
275    }
276
277    #[must_use]
278    pub fn shape_initial(&self) -> &ShapeI {
279        &self.shape_initial
280    }
281
282    pub fn set_image_rect(&mut self, ui_image_rect: Option<ShapeF>) {
283        self.ui_image_rect = ui_image_rect;
284    }
285
286    pub fn apply<FI>(&mut self, mut f_i: FI)
287    where
288        FI: FnMut(DynamicImage) -> DynamicImage,
289    {
290        self.im_background = f_i(mem::take(&mut self.im_background));
291    }
292
293    #[must_use]
294    pub fn shape(&self) -> ShapeI {
295        ShapeI::from_im(&self.im_background)
296    }
297
298    #[must_use]
299    pub fn bg_to_uncropped_view(&self) -> ViewImage {
300        image_util::orig_to_0_255(&self.im_background, &None)
301    }
302}
303
304impl Debug for DataRaw {
305    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
306        write!(
307            f,
308            "\nshape {:?}\ntools data {:?}",
309            self.shape(),
310            self.tools_data_map,
311        )
312    }
313}
314
315fn evaluate_visibility(
316    visibility: Visibility,
317    tool_name: &str,
318    data: &DataRaw,
319) -> Option<Vec<Annotation>> {
320    match (
321        visibility,
322        &data.meta_data.file_path_relative(),
323        data.tools_data_map.get(tool_name),
324    ) {
325        (Visibility::All, Some(file_path_relative), Some(td)) => {
326            td.specifics.to_annotations_view(file_path_relative, None)
327        }
328        (Visibility::Only(idx), Some(file_path), Some(td)) => {
329            td.specifics.to_annotations_view(file_path, Some(idx))
330        }
331        (Visibility::None, _, _) => Some(vec![]),
332        _ => None,
333    }
334}
335/// Everything we need to draw
336#[derive(Clone, Default)]
337pub struct World {
338    pub update_view: UpdateView,
339    pub data: DataRaw,
340    // transforms coordinates from view to raw image
341    zoom_box: Option<BbF>,
342}
343
344impl World {
345    #[must_use]
346    pub fn new(ims_raw: DataRaw, zoom_box: Option<BbF>) -> Self {
347        let im = ims_raw.bg_to_uncropped_view();
348        let world = Self {
349            data: ims_raw,
350            zoom_box,
351            update_view: UpdateView {
352                image: UpdateImage::Yes(im),
353                perm_annos: UpdatePermAnnos::No,
354                tmp_annos: UpdateTmpAnno::No,
355                zoom_box: UpdateZoomBox::Yes(zoom_box),
356                image_info: None,
357                tmp_anno_buffer: None,
358            },
359        };
360        add_tools_initial_data(world)
361    }
362
363    #[must_use]
364    pub fn ui_image_rect(&self) -> Option<ShapeF> {
365        self.data.ui_image_rect
366    }
367
368    /// Annotations shall be drawn again
369    ///
370    /// # Panics
371    /// Panics if a tool name is passed that does not have annotations to be redrawn.
372    pub fn request_redraw_annotations(&mut self, tool_name: &str, visibility_active: Visibility) {
373        let visible_inactive_tools = self
374            .data
375            .tools_data_map
376            .get(tool_name)
377            .map(|td| td.visible_inactive_tools.clone());
378        let tool_names_inactive = get_visible_inactive_names(tool_name);
379        let mut annos_inactive: Option<Vec<Annotation>> = None;
380        if let Some(visible_inactive_tools) = visible_inactive_tools {
381            for (tool_name_inactive, show) in tool_names_inactive
382                .iter()
383                .zip(visible_inactive_tools.iter())
384            {
385                let vli = self.data.tools_data_map.get(*tool_name_inactive).map(|td| {
386                    match &td.specifics {
387                        tools_data::ToolSpecifics::Bbox(bbox_data) => {
388                            (bbox_data.options.core.visible, bbox_data.label_info())
389                        }
390                        tools_data::ToolSpecifics::Brush(brush_data) => {
391                            (brush_data.options.core.visible, brush_data.label_info())
392                        }
393                        _ => {
394                            panic!("tool {tool_name_inactive} does not redraw annotations ");
395                        }
396                    }
397                });
398                let visibility_inactive = if let Some((visible, label_info)) = vli {
399                    vis_from_lfoption(Some(label_info), visible)
400                } else {
401                    Visibility::All
402                };
403                if show && visibility_active != Visibility::None {
404                    if let Some(annos) = &mut annos_inactive {
405                        let annos_inner = evaluate_visibility(
406                            visibility_inactive,
407                            tool_name_inactive,
408                            &self.data,
409                        );
410                        if let Some(annos_inner) = annos_inner {
411                            annos.extend(annos_inner);
412                        }
413                    } else {
414                        annos_inactive = evaluate_visibility(
415                            visibility_inactive,
416                            tool_name_inactive,
417                            &self.data,
418                        );
419                    }
420                }
421            }
422        }
423        let annos_active = evaluate_visibility(visibility_active, tool_name, &self.data);
424        if let Some(annos_active) = annos_active {
425            if let Some(annos_inactive) = annos_inactive {
426                let mut annos = annos_active;
427                annos.extend(annos_inactive);
428                self.update_view.perm_annos = UpdatePermAnnos::Yes(annos);
429            } else {
430                self.update_view.perm_annos = UpdatePermAnnos::Yes(annos_active);
431            }
432        } else if let Some(annos_inactive) = annos_inactive {
433            self.update_view.perm_annos = UpdatePermAnnos::Yes(annos_inactive);
434        }
435    }
436
437    pub fn request_redraw_tmp_anno(&mut self, anno: Annotation) {
438        self.update_view.tmp_annos = UpdateTmpAnno::Yes(anno);
439    }
440
441    pub fn stop_tmp_anno(&mut self) {
442        self.update_view.tmp_annos = UpdateTmpAnno::No;
443    }
444
445    pub fn request_redraw_image(&mut self) {
446        if self.data.meta_data.file_path_relative().is_some() {
447            self.update_view.image = UpdateImage::Yes(self.data.bg_to_uncropped_view());
448        }
449    }
450
451    /// real image in contrast to the loading image
452    #[must_use]
453    pub fn from_real_im(
454        im: DynamicImage,
455        tools_data: ToolsDataMap,
456        ui_image_rect: Option<ShapeF>,
457        file_path: Option<String>,
458        prj_path: &Path,
459        file_selected_idx: Option<usize>,
460    ) -> Self {
461        let meta_data = match (file_path, file_selected_idx) {
462            (Some(fp), Some(fsidx)) => MetaData::from_filepath(fp, fsidx, prj_path),
463            _ => MetaData::default(),
464        };
465        Self::new(DataRaw::new(im, tools_data, meta_data, ui_image_rect), None)
466    }
467
468    #[must_use]
469    pub fn shape_orig(&self) -> ShapeI {
470        self.data.shape()
471    }
472
473    pub fn set_zoom_box(&mut self, zoom_box: Option<BbF>) {
474        let mut set_zb = || {
475            let zoom_box =
476                zoom_box.map(|zb| BbF::new_fit_to_image(zb.x, zb.y, zb.w, zb.h, self.shape_orig()));
477            self.zoom_box = zoom_box;
478            self.update_view = UpdateView::from_zoombox(zoom_box);
479        };
480        if let Some(zb) = zoom_box {
481            if zb.h > 1.0 && zb.w > 1.0 {
482                set_zb();
483            }
484        } else {
485            set_zb();
486        }
487    }
488
489    #[must_use]
490    pub fn zoom_box(&self) -> &Option<BbF> {
491        &self.zoom_box
492    }
493
494    pub fn set_image_rect(&mut self, ui_image_rect: Option<ShapeF>) {
495        self.data.set_image_rect(ui_image_rect);
496    }
497}
498impl Debug for World {
499    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
500        write!(f, "\nims_raw {:?}", &self.data)
501    }
502}
503
504#[cfg(test)]
505fn rgba_at(i: usize, im: &ViewImage) -> [u8; 4] {
506    let x = (i % im.width() as usize) as u32;
507    let y = (i / im.width() as usize) as u32;
508    let rgb = im.get_pixel(x, y).0;
509    let rgb_changed = rgb;
510    [rgb_changed[0], rgb_changed[1], rgb_changed[2], 0xff]
511}
512#[cfg(test)]
513use image::Rgb;
514
515#[test]
516fn test_rgba() {
517    let mut im_test = ViewImage::new(64, 64);
518    im_test.put_pixel(0, 0, Rgb([23, 23, 23]));
519    assert_eq!(rgba_at(0, &im_test), [23, 23, 23, 255]);
520    im_test.put_pixel(0, 1, Rgb([23, 23, 23]));
521    assert_eq!(rgba_at(64, &im_test), [23, 23, 23, 255]);
522    im_test.put_pixel(7, 11, Rgb([23, 23, 23]));
523    assert_eq!(rgba_at(11 * 64 + 7, &im_test), [23, 23, 23, 255]);
524}