stitchpane-iced 0.1.0

Spec-Driven Image Editor In Rust
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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
//! iced user interface. All editing behavior lives in [`stitchpane_core::editor::Editor`];
//! this crate shows its frame, forwards input to it, and provides the dialogs.

mod dialogs;

use std::path::PathBuf;
use std::process::ExitCode;

use dialogs::Modal;
use iced::keyboard::{self, key::Named};
use iced::mouse::{self, ScrollDelta};
use iced::widget::canvas::{self, Canvas, Frame, Geometry, Program};
use iced::widget::{
    Space, button, column, container, image, mouse_area, opaque, pick_list, pin, row, stack, text,
    text_input, tooltip,
};
use iced::{
    Element, Event, Length, Point as IPoint, Rectangle, Renderer, Size, Task, Theme, window,
};
use stitchpane_core::editor::{
    AspectChoice, Button as PointerButton, Command, Cursor, Editor, Key, KeyOutcome, MenuEntry,
    Modifiers,
};
use stitchpane_core::geometry::{PixelRect, Point};
use stitchpane_core::model::SmearKind;

pub fn run() -> ExitCode {
    let paths: Vec<PathBuf> = std::env::args_os().skip(1).map(PathBuf::from).collect();
    let result = iced::application(move || App::new(paths.clone()), App::update, App::view)
        .title(App::title)
        .subscription(App::subscription)
        .exit_on_close_request(false)
        .window_size((1200.0, 800.0))
        .run();
    match result {
        Ok(()) => ExitCode::SUCCESS,
        Err(error) => {
            eprintln!("{error}");
            ExitCode::FAILURE
        }
    }
}

#[derive(Clone, Debug)]
pub enum Message {
    Resized(Size),
    PointerDown(IPoint, PointerButton),
    PointerMove(IPoint),
    PointerUp(IPoint),
    Scroll(IPoint, f32, f32),
    Key(keyboard::Key, keyboard::Modifiers),
    Modifiers(keyboard::Modifiers),
    Command(Command),
    CloseMenu,
    FileDropped(PathBuf),
    FlushDrops,
    CloseRequested(window::Id),
    Modal(dialogs::ModalMessage),
    /// Files chosen in a file dialog, for a purpose.
    Picked(dialogs::Purpose, Vec<PathBuf>),
    /// Checks for finished background resamples (UI-009).
    PollBackground,
    CropField(usize, String),
    CropAspect(String),
    CropCustom(usize, String),
    Exif,
    Locate,
    OpenMenu(MenuKind),
    /// The status bar's zoom level was clicked (UI-010).
    ZoomMenu,
    SmearChoice(String),
    /// Size or strength typed in the smear bar.
    SmearField(usize, String),
}

/// The main menus.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MenuKind {
    File,
    Edit,
    View,
    Image,
}

impl MenuKind {
    const ALL: [MenuKind; 4] = [
        MenuKind::File,
        MenuKind::Edit,
        MenuKind::View,
        MenuKind::Image,
    ];

    fn label(self) -> &'static str {
        match self {
            MenuKind::File => "File",
            MenuKind::Edit => "Edit",
            MenuKind::View => "View",
            MenuKind::Image => "Image",
        }
    }
}

/// Choices in the crop bar's aspect list (CROP-003).
const ASPECTS: [&str; 7] = ["Free", "Original", "1:1", "4:3", "3:2", "16:9", "Custom"];

pub struct App {
    editor: Editor,
    frame: Option<image::Handle>,
    frame_size: Size,
    labels: Vec<(Point, String)>,
    canvas_size: Size,
    modifiers: keyboard::Modifiers,
    pointer: IPoint,
    cursor: Cursor,
    menu: Option<(IPoint, Vec<MenuEntry>)>,
    modal: Option<Modal>,
    crop_fields: [String; 4],
    /// Brush size and strength (%) as typed in the smear bar (SMEAR-003).
    smear_fields: [String; 2],
    custom_aspect: [String; 2],
    window: Option<window::Id>,
    /// Status bar notices, computed in refresh() (META-001, PROJ-005).
    exif_notice: Option<String>,
    missing_notice: Option<String>,
    /// Files dropped together, added as one batch (PLACE-001).
    drops: Vec<PathBuf>,
}

fn modifiers(m: keyboard::Modifiers) -> Modifiers {
    Modifiers {
        shift: m.shift(),
        ctrl: m.control(),
        alt: m.alt(),
    }
}

fn point(p: IPoint) -> Point {
    Point::new(f64::from(p.x), f64::from(p.y))
}

fn map_key(key: &keyboard::Key) -> Option<Key> {
    Some(match key.as_ref() {
        keyboard::Key::Named(Named::ArrowLeft) => Key::Left,
        keyboard::Key::Named(Named::ArrowRight) => Key::Right,
        keyboard::Key::Named(Named::ArrowUp) => Key::Up,
        keyboard::Key::Named(Named::ArrowDown) => Key::Down,
        keyboard::Key::Named(Named::Escape) => Key::Escape,
        keyboard::Key::Named(Named::Enter) => Key::Enter,
        keyboard::Key::Named(Named::Delete) => Key::Delete,
        keyboard::Key::Named(Named::Backspace) => Key::Backspace,
        keyboard::Key::Character(c) => match c {
            "[" | "{" => Key::BracketLeft,
            "]" | "}" => Key::BracketRight,
            "+" | "=" => Key::Plus,
            "-" | "_" => Key::Minus,
            other => Key::Char(other.chars().next()?.to_ascii_lowercase()),
        },
        _ => return None,
    })
}

fn interaction(cursor: Cursor) -> mouse::Interaction {
    match cursor {
        Cursor::Default => mouse::Interaction::Idle,
        Cursor::Move => mouse::Interaction::Move,
        Cursor::Grab => mouse::Interaction::Grab,
        Cursor::ResizeHorizontal => mouse::Interaction::ResizingHorizontally,
        Cursor::ResizeVertical => mouse::Interaction::ResizingVertically,
        Cursor::ResizeDiagonal => mouse::Interaction::ResizingDiagonallyDown,
        Cursor::Rotate | Cursor::Brush => mouse::Interaction::Crosshair,
    }
}

impl App {
    fn new(paths: Vec<PathBuf>) -> (Self, Task<Message>) {
        let mut editor = Editor::new();
        editor.set_background_rendering(true);
        let mut app = Self {
            editor,
            frame: None,
            frame_size: Size::ZERO,
            labels: Vec::new(),
            canvas_size: Size::ZERO,
            modifiers: keyboard::Modifiers::default(),
            pointer: IPoint::ORIGIN,
            cursor: Cursor::Default,
            menu: None,
            modal: None,
            crop_fields: Default::default(),
            smear_fields: Default::default(),
            custom_aspect: ["3".to_owned(), "4".to_owned()],
            window: None,
            exif_notice: None,
            missing_notice: None,
            drops: Vec::new(),
        };
        let result = match paths.as_slice() {
            [] => Ok(()),
            [path] => app.editor.open(path),
            _ => app.editor.open_images(&paths),
        };
        if let Err(e) = result {
            app.modal = Some(Modal::Error(e));
        }
        app.refresh();
        (app, Task::none())
    }

    fn title(&self) -> String {
        self.editor.title()
    }

    /// Re-renders the frame and syncs the crop fields after any change.
    fn refresh(&mut self) {
        if let Some(message) = self.editor.take_message() {
            self.modal = Some(Modal::Error(message));
        }
        if self.canvas_size.width >= 1.0 && self.canvas_size.height >= 1.0 {
            let frame = self.editor.frame();
            let (w, h) = frame.dimensions();
            self.frame_size = Size::new(w as f32, h as f32);
            self.frame = Some(image::Handle::from_rgba(w, h, frame.into_raw()));
            self.labels = self.editor.labels();
        }
        self.exif_notice = self.editor.exif_notice();
        let missing = self.editor.missing_sources();
        self.missing_notice = match missing.as_slice() {
            [] => None,
            [(_, name, ..)] => Some(format!("{name} is missing")),
            n => Some(format!("{} source images are missing", n.len())),
        };
        if let Some(crop) = self.editor.crop_tool() {
            let r = crop.pixel_rect();
            self.crop_fields = [r.left, r.top, r.width, r.height].map(|v| v.to_string());
        }
        if let Some(tool) = self.editor.smear_tool() {
            self.smear_fields = [
                tool.size.to_string(),
                (tool.strength * 100.0).round().to_string(),
            ];
        }
    }

    fn update(&mut self, message: Message) -> Task<Message> {
        // Keep what the user is typing in the crop fields (CROP-002).
        let typing = matches!(message, Message::CropField(..) | Message::SmearField(..));
        if matches!(message, Message::PollBackground) && !self.editor.poll_background() {
            return Task::none();
        }
        let task = self.handle(message);
        let fields = self.crop_fields.clone();
        let smear_fields = self.smear_fields.clone();
        self.refresh();
        if typing {
            self.crop_fields = fields;
            self.smear_fields = smear_fields;
        }
        task
    }

    fn handle(&mut self, message: Message) -> Task<Message> {
        let mods = modifiers(self.modifiers);
        match message {
            Message::Resized(size) => {
                self.canvas_size = size;
                self.editor
                    .set_viewport(f64::from(size.width), f64::from(size.height));
            }
            Message::PointerDown(p, button) => {
                self.menu = None;
                self.pointer = p;
                if let Some(menu) = self.editor.pointer_down(point(p), button, mods) {
                    self.menu = Some((p, menu));
                }
            }
            Message::PointerMove(p) => {
                self.pointer = p;
                self.editor.pointer_move(point(p), mods);
                self.cursor = self.editor.cursor_at(point(p));
            }
            Message::PointerUp(p) => self.editor.pointer_up(point(p), mods),
            Message::Scroll(p, dx, dy) => {
                self.editor
                    .scroll(point(p), f64::from(dx), f64::from(dy), mods)
            }
            Message::Modifiers(m) => self.modifiers = m,
            Message::Key(key, m) => {
                self.modifiers = m;
                if self.modal.is_some() {
                    if key == keyboard::Key::Named(Named::Escape) {
                        self.modal = None;
                    }
                    return Task::none();
                }
                if let Some(key) = map_key(&key)
                    && let KeyOutcome::Command(command) = self.editor.key_press(key, modifiers(m))
                {
                    return self.command(command);
                }
            }
            Message::Command(command) => {
                self.menu = None;
                return self.command(command);
            }
            Message::CloseMenu => self.menu = None,
            Message::FileDropped(path) => {
                self.drops.push(path);
                // Every file of one drop arrives before this task's message.
                if self.drops.len() == 1 {
                    return Task::perform(async {}, |()| Message::FlushDrops);
                }
            }
            Message::FlushDrops => {
                let paths = std::mem::take(&mut self.drops);
                if let Err(e) = self.editor.add_images(&paths, None) {
                    self.modal = Some(Modal::Error(e));
                }
            }
            Message::CloseRequested(id) => {
                self.window = Some(id);
                if self.editor.needs_save_prompt() {
                    self.modal = Some(Modal::ConfirmDiscard(dialogs::AfterDiscard::Quit));
                } else {
                    return window::close(id);
                }
            }
            Message::Modal(message) => return dialogs::update(self, message),
            Message::Picked(purpose, paths) => return dialogs::picked(self, purpose, paths),
            Message::PollBackground => {}
            Message::CropField(index, value) => {
                if let Some(field) = self.crop_fields.get_mut(index) {
                    *field = value;
                }
                let parsed: Vec<u32> = self
                    .crop_fields
                    .iter()
                    // a field that is not a number leaves the crop unchanged
                    .filter_map(|v| match v.trim().parse() {
                        Ok(n) => Some(n),
                        Err(_) => None,
                    })
                    .collect();
                if let [l, t, w, h] = parsed[..] {
                    self.editor
                        .set_crop_rect(PixelRect::new(l, t, w.max(1), h.max(1)));
                }
                return Task::none();
            }
            Message::CropAspect(label) => {
                let aspect = ASPECTS
                    .iter()
                    .position(|a| *a == label)
                    .and_then(|i| AspectChoice::PRESETS.get(i).copied())
                    .unwrap_or_else(|| self.custom_aspect());
                self.editor.set_crop_aspect(aspect);
            }
            Message::CropCustom(index, value) => {
                if let Some(field) = self.custom_aspect.get_mut(index) {
                    *field = value;
                }
                let aspect = self.custom_aspect();
                self.editor.set_crop_aspect(aspect);
            }
            Message::Exif => {
                let item = self.editor.exif_viewer_item();
                return self.command(Command::ExifViewer(item));
            }
            Message::OpenMenu(kind) => {
                let index = MenuKind::ALL.iter().position(|k| *k == kind).unwrap_or(0);
                let x = 6.0 + index as f32 * 58.0;
                self.menu = Some((IPoint::new(x, 0.0), self.menu_entries(kind)));
            }
            Message::ZoomMenu => {
                let p = IPoint::new(0.0, self.canvas_size.height);
                self.menu = Some((p, Editor::zoom_menu()));
            }
            Message::SmearChoice(label) => {
                if let Some(kind) = SmearKind::ALL.into_iter().find(|k| k.label() == label) {
                    self.editor.set_smear_kind(kind);
                }
            }
            Message::SmearField(index, value) => {
                if let Ok(v) = value.trim().parse::<f64>() {
                    if index == 0 {
                        self.editor.set_smear_size(v);
                    } else {
                        self.editor.set_smear_strength(v / 100.0);
                    }
                }
                if let Some(field) = self.smear_fields.get_mut(index) {
                    *field = value;
                }
            }
            Message::Locate => {
                if let Some((source, ..)) = self.editor.missing_sources().first() {
                    return self.command(Command::LocateSource(*source));
                }
            }
        }
        Task::none()
    }

    fn custom_aspect(&self) -> AspectChoice {
        let [w, h] = &self.custom_aspect;
        AspectChoice::Custom(
            w.trim().parse().unwrap_or(1).max(1),
            h.trim().parse().unwrap_or(1).max(1),
        )
    }

    fn command(&mut self, command: Command) -> Task<Message> {
        if command.needs_ui() {
            dialogs::run(self, command)
        } else {
            self.editor.execute(command);
            Task::none()
        }
    }

    fn subscription(&self) -> iced::Subscription<Message> {
        // UI-009: redraw as background resamples arrive.
        let poll = if self.editor.background_busy() {
            window::frames().map(|_| Message::PollBackground)
        } else {
            iced::Subscription::none()
        };
        let events = iced::event::listen_with(|event, status, id| match event {
            Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. })
                if status == iced::event::Status::Ignored =>
            {
                Some(Message::Key(key, modifiers))
            }
            Event::Keyboard(keyboard::Event::ModifiersChanged(m)) => Some(Message::Modifiers(m)),
            Event::Window(window::Event::FileDropped(path)) => Some(Message::FileDropped(path)),
            Event::Window(window::Event::CloseRequested) => Some(Message::CloseRequested(id)),
            _ => None,
        });
        iced::Subscription::batch([events, poll])
    }

    fn header(&self) -> Element<'_, Message> {
        let tip = |content: Element<'static, Message>, label: String| {
            tooltip(
                content,
                container(text(label))
                    .padding(6)
                    .style(container::rounded_box),
                tooltip::Position::Bottom,
            )
        };
        let action = |label: &'static str, command: Command| {
            button(text(label).size(14)).on_press(Message::Command(command))
        };
        let undo = button(text("Undo").size(14)).on_press_maybe(
            self.editor
                .can_undo()
                .then_some(Message::Command(Command::Undo)),
        );
        let redo = button(text("Redo").size(14)).on_press_maybe(
            self.editor
                .can_redo()
                .then_some(Message::Command(Command::Redo)),
        );
        let undo_label = self
            .editor
            .undo_label()
            .unwrap_or_else(|| "Nothing to undo".to_owned());
        let redo_label = self
            .editor
            .redo_label()
            .unwrap_or_else(|| "Nothing to redo".to_owned());
        let menus = MenuKind::ALL.map(|kind| {
            button(text(kind.label()).size(14))
                .style(button::text)
                .on_press(Message::OpenMenu(kind))
                .into()
        });
        let mut bar = row(menus)
            .spacing(2)
            .padding(6)
            .align_y(iced::Alignment::Center);
        bar = bar
            .push(Space::new().width(12))
            .push(action("Open…", Command::Open))
            .push(action("Add images…", Command::AddImages))
            .push(button(text("Save").size(14)).on_press_maybe(
                (!self.editor.is_empty()).then_some(Message::Command(Command::Save)),
            ))
            .push(tip(undo.into(), undo_label))
            .push(tip(redo.into(), redo_label))
            .push(Space::new().width(Length::Fill))
            .push(action("−", Command::ZoomOut))
            .push(action("Fit", Command::ZoomFit))
            .push(action("100%", Command::Zoom100))
            .push(action("+", Command::ZoomIn));
        bar.spacing(6).into()
    }

    /// Entries of a main menu (the Edit menu names the undo and redo steps, UNDO-003).
    fn menu_entries(&self, kind: MenuKind) -> Vec<MenuEntry> {
        let entry = |label: String, command: Command| MenuEntry {
            label,
            command: Some(command),
        };
        match kind {
            MenuKind::File => vec![
                entry("Open…  (Ctrl+O)".into(), Command::Open),
                entry("Add images…".into(), Command::AddImages),
                entry("Save  (Ctrl+S)".into(), Command::Save),
                entry("Save as…  (Ctrl+Shift+S)".into(), Command::SaveAs),
                entry("Export…  (Ctrl+E)".into(), Command::Export),
            ],
            MenuKind::Edit => vec![
                entry(
                    format!(
                        "{}  (Ctrl+Z)",
                        self.editor.undo_label().unwrap_or_else(|| "Undo".into())
                    ),
                    Command::Undo,
                ),
                entry(
                    format!(
                        "{}  (Ctrl+Shift+Z)",
                        self.editor.redo_label().unwrap_or_else(|| "Redo".into())
                    ),
                    Command::Redo,
                ),
            ],
            MenuKind::View => vec![
                entry("Zoom in  (Ctrl++)".into(), Command::ZoomIn),
                entry("Zoom out  (Ctrl+−)".into(), Command::ZoomOut),
                entry("Fit  (Ctrl+0)".into(), Command::ZoomFit),
                entry("100%  (Ctrl+1)".into(), Command::Zoom100),
                entry(
                    if self.editor.snapping() {
                        "Turn snapping off".into()
                    } else {
                        "Turn snapping on".into()
                    },
                    Command::ToggleSnapping,
                ),
            ],
            MenuKind::Image => vec![
                entry("Canvas size…".into(), Command::CanvasSize),
                entry("Set DPI…".into(), Command::SetDpi),
                entry("Show EXIF metadata…".into(), Command::ExifViewer(None)),
            ],
        }
    }

    /// The smear tool's bar (SMEAR-001 to SMEAR-003).
    fn smear_bar(&self) -> Option<Element<'_, Message>> {
        let tool = self.editor.smear_tool()?;
        let field = |index: usize, label: &'static str| {
            row![
                text(label),
                text_input("", self.smear_fields.get(index).map_or("", String::as_str))
                    .on_input(move |v| Message::SmearField(index, v))
                    .width(70)
            ]
            .spacing(4)
            .align_y(iced::Alignment::Center)
        };
        let kinds: Vec<String> = SmearKind::ALL
            .iter()
            .map(|k| k.label().to_owned())
            .collect();
        let bar = row![
            text("Smear"),
            pick_list(
                kinds,
                Some(tool.kind.label().to_owned()),
                Message::SmearChoice
            ),
            field(0, "Size"),
            field(1, "Strength %"),
            Space::new().width(Length::Fill),
            button(text("Done"))
                .style(button::success)
                .on_press(Message::Command(Command::EndSmear)),
        ]
        .spacing(10)
        .padding(6)
        .align_y(iced::Alignment::Center);
        Some(bar.into())
    }

    fn crop_bar(&self) -> Option<Element<'_, Message>> {
        let crop = self.editor.crop_tool()?;
        let field = |index: usize, label: &'static str| {
            row![
                text(label),
                text_input("", self.crop_fields.get(index).map_or("", String::as_str))
                    .on_input(move |v| Message::CropField(index, v))
                    .width(70)
            ]
            .spacing(4)
            .align_y(iced::Alignment::Center)
        };
        let selected = AspectChoice::PRESETS
            .iter()
            .position(|a| *a == crop.aspect)
            .and_then(|i| ASPECTS.get(i).copied())
            .unwrap_or("Custom");
        let aspect = pick_list(
            ASPECTS.map(str::to_owned).to_vec(),
            Some(selected.to_owned()),
            Message::CropAspect,
        );
        let mut bar = row![
            field(0, "Left"),
            field(1, "Top"),
            field(2, "Width"),
            field(3, "Height"),
            text("Aspect"),
            aspect
        ]
        .spacing(10)
        .padding(6)
        .align_y(iced::Alignment::Center);
        if selected == "Custom" {
            bar = bar.push(
                row![
                    text_input("", &self.custom_aspect[0])
                        .on_input(|v| Message::CropCustom(0, v))
                        .width(50),
                    text(":"),
                    text_input("", &self.custom_aspect[1])
                        .on_input(|v| Message::CropCustom(1, v))
                        .width(50)
                ]
                .spacing(4)
                .align_y(iced::Alignment::Center),
            );
        }
        bar = bar
            .push(Space::new().width(Length::Fill))
            .push(button(text("Cancel")).on_press(Message::Command(Command::CancelCrop)))
            .push(
                button(text("Apply"))
                    .style(button::success)
                    .on_press(Message::Command(Command::ApplyCrop)),
            );
        Some(bar.into())
    }

    fn view(&self) -> Element<'_, Message> {
        let canvas = Canvas::new(CanvasView { app: self })
            .width(Length::Fill)
            .height(Length::Fill);
        let mut layers = stack![canvas];
        if self.editor.is_empty() {
            layers = layers.push(
                container(text("Open an image or drop image files here").size(24))
                    .center(Length::Fill),
            );
        }
        if let Some((p, entries)) = &self.menu {
            layers = layers.push(
                mouse_area(Space::new().width(Length::Fill).height(Length::Fill))
                    .on_press(Message::CloseMenu)
                    .on_right_press(Message::CloseMenu),
            );
            // Keep the menu inside the canvas area.
            let separators = entries.iter().filter(|e| e.command.is_none()).count() as f32;
            let height = (entries.len() as f32 - separators) * 30.0 + separators * 9.0 + 8.0;
            let x = p.x.min(self.canvas_size.width - MENU_WIDTH).max(0.0);
            let y = p.y.min(self.canvas_size.height - height).max(0.0);
            layers = layers.push(pin(context_menu(entries)).x(x).y(y));
        }
        let mut page = column![self.header()];
        if let Some(bar) = self.crop_bar() {
            page = page.push(bar);
        }
        if let Some(bar) = self.smear_bar() {
            page = page.push(bar);
        }
        page = page.push(layers);
        page = page.push(dialogs::status(self));
        let page: Element<'_, Message> = page.into();
        match &self.modal {
            Some(modal) => stack![
                page,
                opaque(
                    container(dialogs::view(self, modal))
                        .center(Length::Fill)
                        .style(|_| container::Style {
                            background: Some(iced::Color::from_rgba(0.0, 0.0, 0.0, 0.4).into()),
                            ..container::Style::default()
                        })
                )
            ]
            .into(),
            None => page,
        }
    }
}

const MENU_WIDTH: f32 = 260.0;

fn context_menu(entries: &[MenuEntry]) -> Element<'_, Message> {
    let mut list = column![].spacing(0).width(MENU_WIDTH);
    for entry in entries {
        list = match &entry.command {
            None => list.push(iced::widget::rule::horizontal(1)),
            Some(command) => list.push(
                button(text(entry.label.clone()))
                    .width(Length::Fill)
                    .style(button::text)
                    .on_press(Message::Command(command.clone())),
            ),
        };
    }
    container(list)
        .padding(4)
        .style(container::bordered_box)
        .into()
}

/// The canvas: shows the editor's frame and turns mouse input into messages.
struct CanvasView<'a> {
    app: &'a App,
}

#[derive(Default)]
struct CanvasState {
    size: Size,
    pressed: bool,
}

impl Program<Message> for CanvasView<'_> {
    type State = CanvasState;

    fn update(
        &self,
        state: &mut CanvasState,
        event: &Event,
        bounds: Rectangle,
        cursor: mouse::Cursor,
    ) -> Option<canvas::Action<Message>> {
        let Event::Mouse(event) = event else {
            // Report size changes on non-mouse events so no pointer event is lost.
            if state.size != bounds.size() {
                state.size = bounds.size();
                return Some(canvas::Action::publish(Message::Resized(bounds.size())));
            }
            return None;
        };
        let inside = cursor.position_in(bounds);
        let relative = cursor
            .position()
            .map(|p| IPoint::new(p.x - bounds.x, p.y - bounds.y));
        let message = match event {
            mouse::Event::ButtonPressed(mouse::Button::Left) => {
                let p = inside?;
                state.pressed = true;
                Message::PointerDown(p, PointerButton::Primary)
            }
            mouse::Event::ButtonPressed(mouse::Button::Right) => {
                Message::PointerDown(inside?, PointerButton::Secondary)
            }
            mouse::Event::CursorMoved { .. } => {
                let p = if state.pressed { relative? } else { inside? };
                Message::PointerMove(p)
            }
            mouse::Event::ButtonReleased(mouse::Button::Left) if state.pressed => {
                state.pressed = false;
                Message::PointerUp(relative?)
            }
            mouse::Event::WheelScrolled { delta } => {
                let (dx, dy) = match *delta {
                    ScrollDelta::Lines { x, y } => (-x, -y),
                    ScrollDelta::Pixels { x, y } => (-x / 40.0, -y / 40.0),
                };
                Message::Scroll(inside?, dx, dy)
            }
            _ => return None,
        };
        Some(canvas::Action::publish(message).and_capture())
    }

    fn draw(
        &self,
        _state: &CanvasState,
        renderer: &Renderer,
        _theme: &Theme,
        bounds: Rectangle,
        _cursor: mouse::Cursor,
    ) -> Vec<Geometry> {
        let mut frame = Frame::new(renderer, bounds.size());
        if let Some(handle) = &self.app.frame {
            frame.draw_image(
                Rectangle::new(IPoint::ORIGIN, self.app.frame_size),
                canvas::Image::new(handle.clone()),
            );
        }
        // PROJ-005: label placeholders of missing sources.
        for (p, label) in &self.app.labels {
            frame.fill_text(canvas::Text {
                content: label.clone(),
                position: IPoint::new(p.x as f32, p.y as f32),
                color: iced::Color::WHITE,
                size: 16.into(),
                align_x: iced::alignment::Horizontal::Center.into(),
                align_y: iced::alignment::Vertical::Center,
                ..canvas::Text::default()
            });
        }
        vec![frame.into_geometry()]
    }

    fn mouse_interaction(
        &self,
        _state: &CanvasState,
        bounds: Rectangle,
        cursor: mouse::Cursor,
    ) -> mouse::Interaction {
        if cursor.is_over(bounds) {
            interaction(self.app.cursor)
        } else {
            mouse::Interaction::default()
        }
    }
}

#[cfg(test)]
mod tests;