rvimage 0.6.7

A remote image viewer with a labeling tool
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
use tracing::info;

use super::Manipulate;
use crate::{
    annotations_accessor_mut,
    events::Events,
    file_util::PathPair,
    history::{History, Record},
    make_tool_transform,
    result::trace_ok_err,
    tools_data::{
        AttributesToolData,
        attributes_data::set_attrmap_val,
        parameters::{ParamMap, ParamVal},
    },
    tools_data_accessors,
    world::World,
    world_annotations_accessor,
};
use std::mem;
const MISSING_DATA_MSG: &str = "Missing data for Attributes";
pub const ACTOR_NAME: &str = "Attributes";
annotations_accessor_mut!(
    ACTOR_NAME,
    attributes_mut,
    "Attribute didn't work",
    ParamMap
);
world_annotations_accessor!(ACTOR_NAME, attributes, "Attribute didn't work", ParamMap);
tools_data_accessors!(
    ACTOR_NAME,
    MISSING_DATA_MSG,
    attributes_data,
    AttributesToolData,
    attributes,
    attributes_mut
);

fn propagate_annos(
    mut annos: ParamMap,
    attr_names: &[String],
    to_propagate: &[(usize, ParamVal)],
) -> ParamMap {
    for (attr_idx, val) in to_propagate {
        if let Some(attr_val) = annos.get_mut(&attr_names[*attr_idx]) {
            *attr_val = val.clone();
        }
    }
    annos
}

fn get_buffers(world: &World) -> Vec<String> {
    let annos = get_annos(world);
    let data = get_specific(world);
    if let (Some(data), Some(annos)) = (data, annos) {
        data.attr_names()
            .iter()
            .map(|attr_name| {
                if let Some(attrval) = annos.get(attr_name) {
                    attrval.to_string()
                } else {
                    "".to_string()
                }
            })
            .collect()
    } else {
        vec![]
    }
}
fn propagate_buffer(
    mut attribute_buffer: Vec<String>,
    to_propagate: &[(usize, ParamVal)],
) -> Vec<String> {
    for (attr_idx, val) in to_propagate {
        attribute_buffer[*attr_idx] = val.to_string();
    }
    attribute_buffer
}
fn file_change(mut world: World) -> World {
    use_currentimageshape_for_annos(&mut world);
    let attr_buffers = get_buffers(&world);
    let annos = get_annos_mut(&mut world).map(mem::take);
    let data = get_specific_mut(&mut world);

    if let (Some(data), Some(mut annos)) = (data, annos) {
        // add all attributes to a new file
        for (attr_name, attr_val) in data.attr_names().iter().zip(data.attr_vals().iter()) {
            if !annos.contains(attr_name) {
                set_attrmap_val(&mut annos, attr_name, attr_val.clone().reset());
            }
        }

        // the other way around, check if attributes exist in the data but not as part of the tool
        // smells like a corrupt project file if this happens
        for (attr_name, attr_val) in annos.iter() {
            if !data.attr_names().contains(attr_name) {
                tracing::warn!(
                    "Attribute {attr_name} exists in the data but not in the tool data, adding it"
                );
                data.push(attr_name.clone(), attr_val.clone().reset());
            }
        }

        // put string representations of the attribute values into the buffer
        let attr_buffers = propagate_buffer(attr_buffers, &data.to_propagate_attr_val);
        for (i, buffer) in attr_buffers.into_iter().enumerate() {
            *data.attr_value_buffer_mut(i) = buffer;
        }

        annos = propagate_annos(annos, data.attr_names(), &data.to_propagate_attr_val);

        if let Some(annos_) = get_annos_mut(&mut world) {
            *annos_ = annos;
        }
    }
    let current = get_annos(&world).cloned();
    if let Some(data) = get_specific_mut(&mut world) {
        data.current_attr_map = current;
    }
    world
}
fn add_attribute(
    mut world: World,
    mut history: History,
    suppress_exists_err: bool,
) -> (World, History) {
    let attr_map_tmp = get_annos_mut(&mut world).map(mem::take);
    let data = get_specific_mut(&mut world);

    if let (Some(mut attr_map_tmp), Some(data)) = (attr_map_tmp, data) {
        let new_attr_name = data.new_attr_name.clone();
        if data.attr_names().contains(&new_attr_name) && !suppress_exists_err {
            tracing::error!("New attribute {new_attr_name} could not be created, already exists");
        } else {
            let new_attr_val = data.new_attr_val.clone();
            for (_, (val_map, _)) in data.anno_iter_mut() {
                set_attrmap_val(val_map, &new_attr_name, new_attr_val.clone());
            }
            set_attrmap_val(&mut attr_map_tmp, &new_attr_name, new_attr_val.clone());
            if let Some(a) = get_annos_mut(&mut world) {
                a.clone_from(&attr_map_tmp);
            }
            if let Some(data) = get_specific_mut(&mut world) {
                data.current_attr_map = Some(attr_map_tmp);
                data.push(new_attr_name, new_attr_val);
                history.push(Record::new(world.clone(), ACTOR_NAME));
            }
        }
    }
    if let Some(data) = get_specific_mut(&mut world) {
        data.options.is_addition_triggered = false;
        data.new_attr_name = String::new();
        data.new_attr_val = ParamVal::default();
    }
    (world, history)
}

fn check_remove(mut world: World, mut history: History) -> (World, History) {
    if let Some(removal_idx) = get_specific(&world).map(|d| d.options.removal_idx) {
        let data = get_specific_mut(&mut world);
        if let (Some(data), Some(removal_idx)) = (data, removal_idx) {
            data.remove_attr(removal_idx);
            history.push(Record::new(world.clone(), ACTOR_NAME));
        }
        if let Some(removal_idx) = get_specific_mut(&mut world).map(|d| &mut d.options.removal_idx)
        {
            *removal_idx = None;
        }
    }
    (world, history)
}

#[derive(Clone, Copy, Debug)]
pub struct Attributes;

impl Manipulate for Attributes {
    fn new() -> Self
    where
        Self: Sized,
    {
        Self
    }

    fn on_activate(&mut self, mut world: World) -> World {
        let data = get_data_mut(&mut world);
        if let Some(data) = trace_ok_err(data) {
            data.menu_active = true;
        }
        file_change(world)
    }
    fn on_deactivate(&mut self, mut world: World) -> World {
        let data = get_data_mut(&mut world);
        if let Some(data) = trace_ok_err(data) {
            data.menu_active = false;
        }
        world
    }
    fn on_filechange(&mut self, world: World, history: History) -> (World, History) {
        (file_change(world), history)
    }
    fn events_tf(
        &mut self,
        mut world: World,
        mut history: History,
        _event: &Events,
    ) -> (World, History) {
        let is_addition_triggered = get_specific(&world).map(|d| d.options.is_addition_triggered);
        if is_addition_triggered == Some(true) {
            // handle addition triggered in the GUI
            (world, history) = add_attribute(world, history, false);
        }
        let attr_data = get_specific_mut(&mut world);
        if let Some(attr_data) = attr_data
            && let Some(rename_src_idx) = attr_data.options.rename_src_idx
        {
            let from_name = &attr_data.attr_names()[rename_src_idx].clone();
            let to_name = &attr_data.new_attr_name.clone();
            tracing::info!("Rename attribute {from_name} to {to_name}");
            attr_data.rename(from_name, to_name);
            attr_data.options.rename_src_idx = None;
        }
        let is_update_triggered = get_specific(&world).map(|d| d.options.is_update_triggered);
        if is_update_triggered == Some(true) {
            info!("update attr");
            let current_from_menu_clone =
                get_specific(&world).and_then(|d| d.current_attr_map.clone());
            if let (Some(mut cfm), Some(anno)) =
                (current_from_menu_clone, get_annos_mut(&mut world))
            {
                *anno = mem::take(&mut cfm);
            }
            if let Some(update_current_attr_map) =
                get_specific_mut(&mut world).map(|d| &mut d.options.is_update_triggered)
            {
                *update_current_attr_map = false;
            }
        }
        (world, history) = check_remove(world, history);

        let is_export_triggered =
            get_specific(&world).map(|d| d.options.import_export_trigger.export_triggered());
        if is_export_triggered == Some(true) {
            let ssh_cfg = world.data.meta_data.ssh_cfg.clone();
            let attr_data = get_specific(&world);
            let export_only_opened_folder =
                attr_data.map(|d| d.options.export_only_opened_folder) == Some(true);
            let key_filter = if export_only_opened_folder {
                world
                    .data
                    .meta_data
                    .opened_folder
                    .as_ref()
                    .map(PathPair::path_relative)
            } else {
                None
            };
            let annos_str = get_specific(&world)
                .and_then(|d| trace_ok_err(d.serialize_annotations(key_filter)));
            if let (Some(annos_str), Some(data)) = (annos_str, get_specific(&world))
                && trace_ok_err(data.export_path.conn.write(
                    &annos_str,
                    &data.export_path.path,
                    ssh_cfg.as_ref(),
                ))
                .is_some()
            {
                info!("exported annotations to {:?}", data.export_path.path);
            }

            if let Some(export_triggered) =
                get_specific_mut(&mut world).map(|d| &mut d.options.import_export_trigger)
            {
                export_triggered.untrigger_export();
            }
        }
        let is_import_triggered =
            get_specific(&world).map(|d| d.options.import_export_trigger.import_triggered());
        if is_import_triggered == Some(true) {
            tracing::info!("import attr tiggered");
            let ssh_cfg = world.data.meta_data.ssh_cfg.clone();
            let cur_prj = world.data.meta_data.prj_path().map(|p| p.to_path_buf());
            let attr_data = get_specific_mut(&mut world);
            let imported_map = attr_data.and_then(|data| {
                let in_path = &data.export_path.path;
                tracing::info!("importing attributes from {in_path:?}");
                let json_str = trace_ok_err(data.export_path.conn.read(in_path, ssh_cfg.as_ref()));
                if let Some(s) = json_str {
                    trace_ok_err(AttributesToolData::deserialize_annotations(
                        &s,
                        cur_prj.as_deref(),
                    ))
                } else {
                    None
                }
            });
            if let Some(imported_map) = &imported_map {
                // add attributes in case they don't exist
                for (_, (attr_map, _)) in imported_map.iter() {
                    for (attr_name, attr_val) in attr_map.iter() {
                        let data = get_specific_mut(&mut world);
                        if let Some(d) = data {
                            d.new_attr_name = attr_name.clone();
                            d.new_attr_val = attr_val.clone().reset();
                        }
                        tracing::debug!("inserting attr {attr_name} with value {attr_val}");
                        (world, history) = add_attribute(world, history, true);
                    }
                }
            }
            if let Some(imported_map) = imported_map {
                let data = get_specific_mut(&mut world);
                if let Some(d) = data {
                    d.merge_map(imported_map);
                }
            }
            let annos = get_annos(&world).cloned();
            let attr_buffer = get_buffers(&world);
            if let (Some(data), Some(annos)) = (get_specific_mut(&mut world), annos) {
                data.current_attr_map = Some(annos);
                data.set_new_attr_value_buffer(attr_buffer);
            }
        }
        if let Some(import_trigger) =
            get_specific_mut(&mut world).map(|d| &mut d.options.import_export_trigger)
        {
            import_trigger.untrigger_import();
        }
        make_tool_transform!(self, world, history, event, [])
    }
}
#[cfg(test)]
use {
    crate::tracing_setup::init_tracing_for_tests,
    crate::types::{ThumbIms, ViewImage},
    image::DynamicImage,
    std::collections::HashMap,
    std::fs,
    std::path::Path,
};
#[cfg(test)]
pub(super) fn test_data() -> (World, History) {
    use std::path::Path;

    use crate::ToolsDataMap;

    let im_test = DynamicImage::ImageRgb8(ViewImage::new(64, 64));
    let mut world = World::from_real_im(
        im_test,
        ThumbIms::default(),
        ToolsDataMap::new(),
        None,
        Some("superimage.png".to_string()),
        Path::new("superimage.png"),
        Some(0),
    );
    world.data.meta_data.flags.is_loading_screen_active = Some(false);

    let history = History::default();
    (world, history)
}
#[test]
fn test_import_export() {
    init_tracing_for_tests();
    fn test(testpath: &Path) {
        let (mut world, history) = test_data();
        let data = get_specific_mut(&mut world).unwrap();
        let json_str = fs::read_to_string(testpath).unwrap();
        let reference_data = AttributesToolData::deserialize_annotations(&json_str, None).unwrap();
        tracing::debug!("reference_data: {:?}", reference_data);
        data.export_path.path = testpath.to_path_buf();
        data.options.import_export_trigger.trigger_import();
        let events = Events::default();
        let (world, _) = Attributes {}.events_tf(world, history, &events);
        let annos = world.data.tools_data_map[ACTOR_NAME]
            .specifics
            .attributes()
            .unwrap()
            .anno_iter()
            .collect::<HashMap<_, _>>();
        tracing::debug!("annos: {:?}", annos);
        for k in reference_data.keys() {
            tracing::debug!("k: {:?}", k);
            let (annos, _) = annos.get(k).unwrap();
            let (ref_annos, _) = &reference_data[k];
            assert_eq!(annos, ref_annos);
        }
        let current = get_annos(&world).unwrap();
        for v in current.values() {
            assert!(v.is_default());
        }
    }
    let testpath = Path::new("resources/test_data/attr_import.json");
    test(testpath);
    let testpath = Path::new("resources/test_data/attr_import_untagged.json");
    test(testpath);
}

#[test]
fn test_add() {
    init_tracing_for_tests();
    let mut attr_tool = Attributes::new();
    let events = Events::default();
    let (mut world, history) = test_data();
    let attr_data = get_specific_mut(&mut world).unwrap();
    attr_data.options.is_addition_triggered = true;
    attr_data.new_attr_name = "a attr".to_string();
    attr_data.new_attr_val = ParamVal::Int(Some(1));
    let (mut world, history) = attr_tool.events_tf(world, history, &events);
    let attr_data = get_specific_mut(&mut world).unwrap();
    attr_data.options.is_addition_triggered = true;
    attr_data.new_attr_name = "c attr".to_string();
    attr_data.new_attr_val = ParamVal::Int(Some(2));
    let (mut world, history) = attr_tool.events_tf(world, history, &events);
    let attr_data = get_specific_mut(&mut world).unwrap();
    attr_data.options.is_addition_triggered = true;
    attr_data.new_attr_name = "b attr".to_string();
    attr_data.new_attr_val = ParamVal::Int(Some(3));
    let (world, _) = attr_tool.events_tf(world, history, &events);
    let data = get_specific(&world).unwrap();
    let cam = data.current_attr_map.as_ref().unwrap();
    let c_attr_val = cam.get("c attr").unwrap();
    assert_eq!(c_attr_val, &ParamVal::Int(Some(2)));
    let b_attr_val = cam.get("b attr").unwrap();
    assert_eq!(b_attr_val, &ParamVal::Int(Some(3)));
    let a_attr_val = cam.get("a attr").unwrap();
    assert_eq!(a_attr_val, &ParamVal::Int(Some(1)));

    // cur map is a BTree and hence sorted
    assert_eq!(data.attr_names(), &["a attr", "b attr", "c attr"]);
    assert_eq!(
        data.attr_vals(),
        &[
            ParamVal::Int(Some(1)),
            ParamVal::Int(Some(3)),
            ParamVal::Int(Some(2)),
        ]
    );
}
#[test]
fn test_rm_add() {
    init_tracing_for_tests();
    let (mut world, history) = test_data();
    let attr_data = get_specific_mut(&mut world).unwrap();
    attr_data.options.is_addition_triggered = true;
    attr_data.new_attr_name = "test_attr".to_string();
    attr_data.new_attr_val = ParamVal::Str("123".into());
    let (mut world, history) = add_attribute(world, history, false);
    let attr_data = get_specific_mut(&mut world).unwrap();
    attr_data.options.removal_idx = Some(0);
    let (mut world, _) = check_remove(world, history);
    let attr_data = get_specific_mut(&mut world).unwrap();
    assert!(!attr_data.options.is_addition_triggered);
    assert!(attr_data.options.removal_idx.is_none());
    assert_eq!(
        attr_data.current_attr_map.as_ref().map(|cam| cam.len()),
        Some(0)
    );
}