rvimage 0.8.3

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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
use crate::{
    cfg::{ExportPath, ExportPathConnection},
    file_util::path_to_str,
    menu::{
        params_menu::{
            ExistingParamMenuAction, add_buffer_sorted, add_parameter_menu, existing_params_menu,
            no_more_cols,
        },
        ui_util::{process_number, removable_rows},
    },
    parameters::ParamVal,
    result::trace_ok_err,
    tools::{BBOX_NAME, BRUSH_NAME, get_visible_inactive_names},
    tools_data::{
        AnnotationsMap, AttributesToolData, BrushToolData, CoreOptions, ImportExportTrigger,
        InstanceAnnotate, LabelInfo, OUTLINE_THICKNESS_CONVERSION, ToolSpecifics, ToolsData,
        VisibleInactiveToolsState,
        annotations::SplitMode,
        bbox_data::BboxToolData,
        brush_data::{MAX_INTENSITY, MAX_THICKNESS, MIN_INTENSITY, MIN_THICKNESS},
        predictive_labeling::PredictiveLabelingData,
    },
};
use egui::Ui;
use rvimage_domain::TPtF;
use rvimage_domain::{RvResult, to_rv};
use std::{mem, path::PathBuf, str::FromStr};
use tracing;
use tracing::{info, warn};

use super::ui_util::{slider, text_edit_singleline};

enum LabelEditMode {
    Add,
    Rename,
}

fn new_label_text(
    ui: &mut Ui,
    new_label: &mut String,
    are_tools_active: &mut bool,
) -> Option<(String, LabelEditMode)> {
    text_edit_singleline(ui, new_label, are_tools_active);
    ui.horizontal(|ui| {
        if ui.button("add").clicked() {
            Some((new_label.clone(), LabelEditMode::Add))
        } else if ui.button("rename").clicked() {
            Some((new_label.clone(), LabelEditMode::Rename))
        } else {
            None
        }
    })
    .inner
}

fn show_inactive_tool_menu(
    ui: &mut Ui,
    tool_name: &'static str,
    visible: &mut VisibleInactiveToolsState,
) -> bool {
    ui.label("Show inactive tool");
    let mut changed = false;
    let inactives = get_visible_inactive_names(tool_name);
    for (name, show) in inactives.iter().zip(visible.iter_mut()) {
        changed |= ui.checkbox(show, *name).changed();
    }
    changed
}

#[derive(Default)]
pub struct LabelMenuResult {
    pub label_change: bool,
    pub show_only_change: bool,
}

pub fn label_menu<'a, T>(
    ui: &mut Ui,
    label_info: &mut LabelInfo,
    annotations_map: &mut AnnotationsMap<T>,
    are_tools_active: &mut bool,
) -> LabelMenuResult
where
    T: InstanceAnnotate + 'a,
{
    let mut new_idx = label_info.cat_idx_current;
    let mut label_change = false;
    let mut show_only_change = false;
    let new_label = new_label_text(ui, &mut label_info.new_label, are_tools_active);
    let default_label = label_info.find_default();
    if let (Some(default_label), Some((new_label, _))) = (default_label, new_label.as_ref()) {
        info!("replaced default '{default_label}' label by '{new_label}'");
        default_label.clone_from(new_label);
        label_change = true;
    } else if let Some((new_label, edit_mode)) = new_label {
        match edit_mode {
            LabelEditMode::Add => {
                if let Err(e) = label_info.push(new_label, None, None) {
                    warn!("{e:?}");
                    return LabelMenuResult::default();
                }
                label_change = true;
                new_idx = label_info.len() - 1;
            }
            LabelEditMode::Rename => {
                if let Err(e) = label_info.rename_label(label_info.cat_idx_current, new_label) {
                    warn!("{e:?}");
                    return LabelMenuResult::default();
                }
                label_change = true;
            }
        }
    }
    let mut show_only_current = label_info.show_only_current;
    let mut to_be_removed = None;
    let n_rows = label_info.labels().len();
    egui::Grid::new("label_grid").num_columns(3).show(ui, |ui| {
        to_be_removed = removable_rows(ui, n_rows, |ui, label_idx| {
            let label = label_info.labels().get(label_idx);
            if let Some(label) = label {
                let checked = label_idx == label_info.cat_idx_current;
                let label = if show_only_current && checked {
                    egui::RichText::new(label).monospace().strong().italics()
                } else {
                    egui::RichText::new(label).monospace()
                };
                if ui.selectable_label(checked, label).clicked() {
                    if checked {
                        show_only_current = !label_info.show_only_current;
                        show_only_change = true;
                    }
                    new_idx = label_idx;
                }
            }
            let rgb = label_info.colors().get(label_idx);
            if let Some(rgb) = rgb {
                ui.label(
                    egui::RichText::new("â– ")
                        .heading()
                        .strong()
                        .color(egui::Color32::from_rgb(rgb[0], rgb[1], rgb[2])),
                );
            }
            ui.end_row();
        });
    });
    label_info.show_only_current = show_only_current;
    if new_idx != label_info.cat_idx_current {
        for (annos, _) in annotations_map.values_mut() {
            annos.label_selected(new_idx);
        }
        label_change = true;
        label_info.cat_idx_current = new_idx;
    }
    if let Some(tbr) = to_be_removed {
        label_change = true;
        label_info.remove_catidx(tbr, annotations_map)
    }
    if label_change {
        label_info.show_only_current = false;
    }
    LabelMenuResult {
        label_change,
        show_only_change,
    }
}

fn hide_menu(ui: &mut Ui, mut core_options: CoreOptions) -> CoreOptions {
    let mut hide = !core_options.visible;
    if ui.checkbox(&mut hide, "hide").changed() {
        core_options.is_redraw_annos_triggered = true;
        core_options.visible = !hide;
    }
    core_options
}

fn export_file_menu(
    ui: &mut Ui,
    label: &str,
    export_path: &mut ExportPath,
    are_tools_active: &mut bool,
    import_export_trigger: &mut ImportExportTrigger,
    double_check_shape: Option<&mut bool>,
    skip_import_mode: bool,
) -> RvResult<()> {
    let mut file_txt = path_to_str(&export_path.path)?.to_string();
    ui.horizontal(|ui| {
        ui.label(label);
        ui.radio_value(&mut export_path.conn, ExportPathConnection::Local, "local");
        ui.radio_value(&mut export_path.conn, ExportPathConnection::Ssh, "ssh");
    });
    text_edit_singleline(ui, &mut file_txt, are_tools_active)
        .on_hover_text(path_to_str(&export_path.path)?);

    if path_to_str(&export_path.path)? != file_txt {
        export_path.path = PathBuf::from_str(&file_txt).map_err(to_rv)?;
    }
    ui.horizontal(|ui| {
        if ui.button("export").clicked() {
            tracing::info!("clicked on export trigger");
            import_export_trigger.trigger_export();
        }
        if ui.button("import").clicked() {
            tracing::info!("clicked on import trigger");
            import_export_trigger.trigger_import();
        }
        if let Some(double_check_shape) = double_check_shape {
            ui.checkbox(double_check_shape, "double check shape")
                .on_hover_text(
                "For shape correction the image needs to be loaded which slows down the export.",
            );
        }
        if skip_import_mode {
            let mut checked = import_export_trigger.merge_mode();
            ui.checkbox(&mut checked, "merge import");
            if checked {
                import_export_trigger.use_merge_import();
            } else {
                import_export_trigger.use_replace_import();
            }
        }
    });
    Ok(())
}

fn toggle_erase(ui: &mut Ui, mut options: CoreOptions) -> CoreOptions {
    if ui.checkbox(&mut options.erase, "erase").clicked() {
        if options.erase {
            info!("start erasing");
        } else {
            info!("stop erasing");
        }
    }
    options
}
fn transparency_slider(
    ui: &mut Ui,
    are_tools_active: &mut bool,
    alpha: &mut u8,
    name: &str,
) -> bool {
    let mut transparency: f32 = *alpha as f32 / 255.0 * 100.0;
    let is_redraw_triggered =
        slider(ui, are_tools_active, &mut transparency, 0.0..=100.0, name).changed();
    *alpha = (transparency / 100.0 * 255.0).round() as u8;
    is_redraw_triggered
}
pub fn bbox_menu(
    ui: &mut Ui,
    mut window_open: bool,
    mut data: BboxToolData,
    are_tools_active: &mut bool,
    mut visible_inactive_tools: VisibleInactiveToolsState,
) -> RvResult<ToolsData> {
    let LabelMenuResult {
        label_change,
        show_only_change,
    } = label_menu(
        ui,
        &mut data.label_info,
        &mut data.annotations_map,
        are_tools_active,
    );
    if label_change {
        data.options.core = data.options.core.trigger_redraw_and_hist();
    }
    if show_only_change {
        data.options.core.is_redraw_annos_triggered = true;
    }
    ui.separator();

    data.options.core = toggle_erase(ui, data.options.core);
    data.options.core = hide_menu(ui, data.options.core);

    ui.checkbox(&mut data.options.core.auto_paste, "auto paste");

    let mut export_file_menu_result = Ok(());
    egui::CollapsingHeader::new("advanced").show(ui, |ui| {
        ui.checkbox(&mut data.options.core.track_changes, "track changes");
        ui.horizontal(|ui| {
            ui.separator();
            ui.label("split mode");
            ui.radio_value(&mut data.options.split_mode, SplitMode::None, "none");
            ui.radio_value(
                &mut data.options.split_mode,
                SplitMode::Horizontal,
                "horizontal",
            );
            ui.radio_value(
                &mut data.options.split_mode,
                SplitMode::Vertical,
                "vertical",
            );
        });
        egui::CollapsingHeader::new("View").show(ui, |ui| {
            if transparency_slider(
                ui,
                are_tools_active,
                &mut data.options.fill_alpha,
                "fill transparency",
            ) {
                data.options.core.is_redraw_annos_triggered = true;
            }
            if transparency_slider(
                ui,
                are_tools_active,
                &mut data.options.outline_alpha,
                "outline transparency",
            ) {
                data.options.core.is_redraw_annos_triggered = true;
            }
            let mut outline_thickness_f =
                data.options.outline_thickness as TPtF / OUTLINE_THICKNESS_CONVERSION;
            if slider(
                ui,
                are_tools_active,
                &mut outline_thickness_f,
                0.0..=10.0,
                "outline thickness",
            )
            .changed()
            {
                data.options.core.is_redraw_annos_triggered = true;
            }
            data.options.outline_thickness =
                (outline_thickness_f * OUTLINE_THICKNESS_CONVERSION).round() as u16;
            if slider(
                ui,
                are_tools_active,
                &mut data.options.drawing_distance,
                1..=50,
                "drawing distance parameter",
            )
            .changed()
            {
                data.options.core.is_redraw_annos_triggered = true;
            }
            ui.separator();
            if ui.button("new random colors").clicked() {
                data.options.core.is_colorchange_triggered = true;
            }
        });

        egui::CollapsingHeader::new("Coco Import/Export").show(ui, |ui| {
            let skip_import_mode = false;
            export_file_menu_result = export_file_menu(
                ui,
                "coco file",
                &mut data.coco_file,
                are_tools_active,
                &mut data.options.core.import_export_trigger,
                Some(&mut data.options.core.doublecheck_cocoexport_shape),
                skip_import_mode,
            );
        });

        egui::CollapsingHeader::new("Predictive Labeling").show(ui, |ui| {
            let mut pd = mem::take(&mut data.predictive_labeling_data);
            trace_ok_err(predictive_labeling_menu(ui, &mut pd, are_tools_active));
            data.predictive_labeling_data = pd;
        });
    });
    export_file_menu_result?;
    ui.separator();
    if show_inactive_tool_menu(ui, BBOX_NAME, &mut visible_inactive_tools) {
        data.options.core.is_redraw_annos_triggered = true;
    }
    ui.separator();
    ui.horizontal(|ui| {
        if ui.button("close").clicked() {
            window_open = false;
        }
    });
    Ok(ToolsData {
        specifics: ToolSpecifics::Bbox(data),
        menu_active: window_open,
        visible_inactive_tools,
    })
}

pub fn brush_menu(
    ui: &mut Ui,
    mut window_open: bool,
    mut data: BrushToolData,
    are_tools_active: &mut bool,
    mut visible_inactive_tools: VisibleInactiveToolsState,
) -> RvResult<ToolsData> {
    let LabelMenuResult {
        label_change,
        show_only_change,
    } = label_menu(
        ui,
        &mut data.label_info,
        &mut data.annotations_map,
        are_tools_active,
    );
    if label_change {
        data.options.core = data.options.core.trigger_redraw_and_hist();
    }
    if show_only_change {
        data.options.core.is_redraw_annos_triggered = true;
    }

    ui.separator();
    data.options.core = toggle_erase(ui, data.options.core);
    data.options.core = hide_menu(ui, data.options.core);
    ui.checkbox(&mut data.options.core.auto_paste, "auto paste");
    egui::CollapsingHeader::new("advanced").show(ui, |ui| {
        ui.checkbox(&mut data.options.core.track_changes, "track changes");
        ui.separator();
        ui.label("properties");
        if slider(
            ui,
            are_tools_active,
            &mut data.options.thickness,
            MIN_THICKNESS..=MAX_THICKNESS,
            "thickness",
        )
        .changed()
        {
            data.options.is_selection_change_needed = true;
        }
        if slider(
            ui,
            are_tools_active,
            &mut data.options.intensity,
            MIN_INTENSITY..=MAX_INTENSITY,
            "intensity",
        )
        .changed()
        {
            data.options.is_selection_change_needed = true;
        }
        ui.separator();
        ui.label("visualization");
        if transparency_slider(
            ui,
            are_tools_active,
            &mut data.options.fill_alpha,
            "transparency",
        ) {
            data.options.core.is_redraw_annos_triggered = true;
        }
        if ui.button("new random colors").clicked() {
            data.options.core.is_colorchange_triggered = true;
        }
        ui.separator();
        ui.checkbox(
            &mut data.options.per_file_crowd,
            "export merged annotations per file",
        );
        egui::CollapsingHeader::new("Coco Import/Export").show(ui, |ui| {
            let skip_import_mode = false;
            trace_ok_err(export_file_menu(
                ui,
                "coco file",
                &mut data.coco_file,
                are_tools_active,
                &mut data.options.core.import_export_trigger,
                Some(&mut data.options.core.doublecheck_cocoexport_shape),
                skip_import_mode,
            ));
        });
        egui::CollapsingHeader::new("Predictive Labeling").show(ui, |ui| {
            let mut pd = mem::take(&mut data.predictive_labeling_data);
            trace_ok_err(predictive_labeling_menu(ui, &mut pd, are_tools_active));
            data.predictive_labeling_data = pd;
        });
    });
    ui.separator();
    if show_inactive_tool_menu(ui, BRUSH_NAME, &mut visible_inactive_tools) {
        data.options.core.is_redraw_annos_triggered = true;
    }
    ui.separator();
    if ui.button("close").clicked() {
        window_open = false;
    }
    Ok(ToolsData {
        specifics: ToolSpecifics::Brush(data),
        menu_active: window_open,
        visible_inactive_tools,
    })
}

pub fn attributes_menu(
    ui: &mut Ui,
    mut window_open: bool,
    mut data: AttributesToolData,
    are_tools_active: &mut bool,
) -> RvResult<ToolsData> {
    let add_new;
    (data.new_attr_name, data.new_attr_val, add_new) = add_parameter_menu(
        ui,
        mem::take(&mut data.new_attr_name),
        mem::take(&mut data.new_attr_val),
        data.attr_names().iter(),
        are_tools_active,
    );
    if add_new {
        data.options.is_addition_triggered = true;
        data.options.is_update_triggered = true;
    }
    let mut to_propagate = mem::take(&mut data.to_propagate_attr_val);
    let more_cols = |ui: &mut Ui, input_changed: bool, idx_row: usize, attr_val: ParamVal| {
        let mut is_update_triggered = false;
        if input_changed {
            to_propagate.retain(|(idx_attr, _)| *idx_attr != idx_row);
            is_update_triggered = true;
        }
        let checked = to_propagate
            .iter()
            .any(|(idx_attr, _)| *idx_attr == idx_row);
        if ui
            .selectable_label(checked, "propagate")
            .on_hover_text("propagate attribute value to next opened image")
            .clicked()
        {
            if checked {
                to_propagate.retain(|(idx_attr, _)| *idx_attr != idx_row);
            } else {
                to_propagate.push((idx_row, attr_val));
            }
        }
        is_update_triggered
    };
    let param_buffers = mem::take(data.attr_value_buffers_mut());
    if let Some(attr_map) = &mut data.current_attr_map {
        let existing_res = existing_params_menu(
            ui,
            mem::take(attr_map),
            are_tools_active,
            more_cols,
            param_buffers,
        );
        data.current_attr_map = Some(existing_res.param_map);
        *data.attr_value_buffers_mut() = existing_res.buffers;
        data.to_propagate_attr_val = to_propagate;
        match existing_res.action {
            ExistingParamMenuAction::Rename(idx) => {
                data.options.rename_src_idx = Some(idx);
            }
            ExistingParamMenuAction::Remove(idx) => {
                data.options.removal_idx = Some(idx);
            }
            ExistingParamMenuAction::None => (),
        }
        if existing_res.has_value_changed {
            data.options.is_update_triggered = true;
        }
    }

    ui.separator();
    let skip_merge_menu = true;
    ui.checkbox(
        &mut data.options.export_only_opened_folder,
        "export only opened folder",
    );
    export_file_menu(
        ui,
        "export attributes as json",
        &mut data.export_path,
        are_tools_active,
        &mut data.options.import_export_trigger,
        None,
        skip_merge_menu,
    )?;

    ui.separator();
    if ui.button("Close").clicked() {
        window_open = false;
    }

    Ok(ToolsData {
        specifics: ToolSpecifics::Attributes(data),
        menu_active: window_open,
        visible_inactive_tools: VisibleInactiveToolsState::default(),
    })
}

pub fn predictive_labeling_menu(
    ui: &mut Ui,
    data: &mut PredictiveLabelingData,
    are_tools_active: &mut bool,
) -> RvResult<()> {
    ui.label("Parameters");
    let add_param;
    (
        data.new_param_name_buffer,
        data.new_param_val_buffer,
        add_param,
    ) = add_parameter_menu(
        ui,
        mem::take(&mut data.new_param_name_buffer),
        mem::take(&mut data.new_param_val_buffer),
        data.parameters.keys(),
        are_tools_active,
    );
    if add_param {
        add_buffer_sorted(
            &data.parameters,
            &data.new_param_name_buffer,
            "".to_string(),
            &mut data.param_buffers,
        );
        data.parameters.insert(
            mem::take(&mut data.new_param_name_buffer),
            mem::take(&mut data.new_param_val_buffer),
        );
    }
    let res = existing_params_menu(
        ui,
        mem::take(&mut data.parameters),
        are_tools_active,
        no_more_cols,
        mem::take(&mut data.param_buffers),
    );
    res.apply(
        &mut data.parameters,
        &mut data.param_buffers,
        &data.new_param_name_buffer,
    );

    text_edit_singleline(ui, &mut data.url, are_tools_active).on_hover_text("url");

    if data.timeout_buffer.is_empty() {
        data.timeout_buffer = data.timeout_ms.to_string();
    }
    let (_, val) = process_number::<usize>(
        ui,
        are_tools_active,
        "timeout [ms]",
        &mut data.timeout_buffer,
    );
    if let Some(val) = val {
        data.timeout_ms = val;
    }

    if ui.button("Predict").clicked() {
        tracing::info!("Predictive labeling triggered");
        data.trigger_prediction();
    }
    Ok(())
}