stitchpane-iced 0.1.2

Spec-Driven Image Editor In Rust
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
//! UI tests driven through the headless iced simulator. Each test names the requirement it
//! verifies in a `spec:` comment.

use std::path::{Path, PathBuf};

use iced::{Size, Theme};
use iced_test::simulator;
use stitchpane_core::codec::{self, EncodeOptions, Format};
use stitchpane_core::model::{ItemId, Step};

use super::*;

struct Scratch(PathBuf);

impl Scratch {
    fn new(name: &str) -> Self {
        let dir =
            std::env::temp_dir().join(format!("stitchpane-iced-{name}-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("scratch dir");
        Self(dir)
    }

    fn image(&self, name: &str, w: u32, h: u32, exif: Option<Vec<u8>>) -> PathBuf {
        let path = self.0.join(name);
        let pixels = ::image::RgbaImage::from_pixel(w, h, ::image::Rgba([200, 40, 40, 255]));
        let options = EncodeOptions {
            format: Format::from_path(&path).expect("format"),
            quality: 90,
            dpi: None,
            exif,
        };
        codec::write(&pixels, &path, &options).expect("write image");
        path
    }
}

impl Drop for Scratch {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

/// A minimal big-endian EXIF block with one tag: Make = "Cam".
fn exif_make() -> Vec<u8> {
    let mut b = b"MM\0\x2a\0\0\0\x08".to_vec();
    b.extend_from_slice(&[0, 1]);
    b.extend_from_slice(&[0x01, 0x0F, 0, 2, 0, 0, 0, 4]);
    b.extend_from_slice(b"Cam\0");
    b.extend_from_slice(&[0, 0, 0, 0]);
    b
}

fn app_with(paths: &[&Path]) -> App {
    let (mut app, _) = App::new(paths.iter().map(|p| p.to_path_buf()).collect());
    let _ = app.update(Message::Resized(Size::new(1024.0, 640.0)));
    app
}

/// Delivers the allocations the headless tests never run, as iced would (UI-011).
fn present(app: &mut App) {
    while let Some(id) = uploading_ids(app).first().copied() {
        let _ = app.update(Message::FrameReady(id, None));
    }
}

fn shown_id(app: &App) -> Option<ImageId> {
    app.frames.shown().map(|f| f.handle.id())
}

/// Frames being uploaded, oldest first.
fn uploading_ids(app: &App) -> Vec<ImageId> {
    app.frames
        .uploading
        .iter()
        .map(|(_, f)| f.handle.id())
        .collect()
}

fn waiting_id(app: &App) -> Option<ImageId> {
    app.frames.next.as_ref().map(|f| f.handle.id())
}

/// Moves the pointer over the canvas, which renders a new frame.
fn pointer_move(app: &mut App, x: f32) {
    let _ = app.update(Message::PointerMove(IPoint::new(x, 300.0)));
}

/// Clicks a widget by its text and feeds the resulting messages to the app.
fn click(app: &mut App, label: &str) {
    let messages: Vec<Message> = {
        let mut ui = simulator(app.view());
        ui.click(label)
            .unwrap_or_else(|e| panic!("cannot click {label:?}: {e:?}"));
        ui.into_messages().collect()
    };
    for message in messages {
        let _ = app.update(message);
    }
}

fn assert_shows(app: &App, label: &str) {
    let mut ui = simulator(app.view());
    if let Err(error) = ui.find(label) {
        panic!("{label:?} is not shown: {error}");
    }
}

fn assert_hides(app: &App, label: &str) {
    let mut ui = simulator(app.view());
    let error = ui.find(label).map(|_| ()).expect_err("label is shown");
    assert!(
        matches!(&error, iced_test::Error::SelectorNotFound { selector } if selector.contains(label)),
        "{error}"
    );
}

fn item(app: &App, id: u32) -> stitchpane_core::model::Item {
    *app.editor
        .project()
        .state()
        .item(ItemId(id))
        .expect("image")
}

#[test]
fn toolbar_undo_and_redo() {
    // spec: UNDO-001, UNDO-002
    let dir = Scratch::new("undo");
    let a = dir.image("a.png", 40, 30, None);
    let mut app = app_with(&[&a]);
    assert!(app.editor.apply(Step::MoveItem {
        item: ItemId(1),
        x: 5,
        y: 5
    }));
    click(&mut app, "Undo");
    assert_eq!((item(&app, 1).x, item(&app, 1).y), (0, 0));
    click(&mut app, "Redo");
    assert_eq!((item(&app, 1).x, item(&app, 1).y), (5, 5));
}

#[test]
fn undo_tooltip_names_the_step() {
    // spec: UNDO-003
    let dir = Scratch::new("tooltip");
    let a = dir.image("a.png", 40, 30, None);
    let mut app = app_with(&[&a]);
    assert!(app.editor.apply(Step::MoveItem {
        item: ItemId(1),
        x: 5,
        y: 5
    }));
    let _ = app.update(Message::PointerMove(IPoint::new(500.0, 300.0)));
    let mut ui = simulator(app.view());
    ui.point_at(IPoint::new(0.0, 0.0));
    if let Err(error) = ui.click("Undo") {
        panic!("Undo is not clickable: {error}");
    }
    assert_eq!(app.editor.undo_label().as_deref(), Some("Undo Move image"));
}

#[test]
fn context_menu_starts_cropping() {
    // spec: UI-004, CROP-001, CROP-002, CROP-004
    let dir = Scratch::new("menu");
    let a = dir.image("a.png", 400, 300, None);
    let mut app = app_with(&[&a]);
    let _ = app.update(Message::PointerDown(
        IPoint::new(512.0, 320.0),
        PointerButton::Secondary,
    ));
    assert_shows(&app, "Resize…");
    click(&mut app, "Crop");
    assert!(app.editor.crop_tool().is_some());
    assert_shows(&app, "Apply");
    let _ = app.update(Message::CropField(2, String::new()));
    assert_eq!(app.crop_fields[2], "");
    let _ = app.update(Message::CropField(2, "100".to_owned()));
    click(&mut app, "Apply");
    assert!(app.editor.crop_tool().is_none());
    assert_eq!(item(&app, 1).width, 100);
}

#[test]
fn exif_notice_opens_viewer_and_strips() {
    // spec: META-001, META-002, META-003, META-004
    let dir = Scratch::new("exif");
    let a = dir.image("a.jpg", 40, 30, Some(exif_make()));
    let mut app = app_with(&[&a]);
    click(&mut app, "ⓘ Contains EXIF metadata");
    assert!(matches!(app.modal, Some(Modal::Exif { .. })));
    assert_shows(&app, "Camera");
    click(&mut app, "Strip metadata");
    assert!(app.modal.is_none());
    assert_hides(&app, "ⓘ Contains EXIF metadata");
}

#[test]
fn closing_with_changes_asks_to_save() {
    // spec: UI-002
    let dir = Scratch::new("close");
    let a = dir.image("a.png", 40, 30, None);
    let mut app = app_with(&[&a]);
    assert!(app.editor.apply(Step::MoveItem {
        item: ItemId(1),
        x: 5,
        y: 5
    }));
    let _ = app.update(Message::CloseRequested(window::Id::unique()));
    assert_shows(&app, "Discard");
    click(&mut app, "Cancel");
    assert!(app.modal.is_none());
}

#[test]
fn opening_several_images_asks_for_the_canvas() {
    // spec: CANVAS-001, UI-001
    let dir = Scratch::new("canvas");
    let a = dir.image("a.png", 100, 50, None);
    let b = dir.image("b.png", 40, 80, None);
    let mut app = app_with(&[]);
    let _ = app.update(Message::Picked(dialogs::Purpose::Open, vec![a, b]));
    assert_shows(&app, "New composition — canvas size");
    let _ = app.update(Message::Modal(dialogs::ModalMessage::Choice(1)));
    click(&mut app, "Create");
    assert_eq!(app.editor.project().state().canvas_size(), (100, 130));
}

#[test]
fn exporting_over_a_source_asks_first() {
    // spec: EXPORT-003
    let dir = Scratch::new("export");
    let a = dir.image("a.png", 40, 30, None);
    let mut app = app_with(&[&a]);
    let _ = app.update(Message::Picked(dialogs::Purpose::Export, vec![a.clone()]));
    assert_shows(&app, "Overwrite");
    click(&mut app, "Overwrite");
    assert_shows(&app, "EXIF metadata from");
    click(&mut app, "Export");
    assert!(app.modal.is_none());
}

#[test]
fn dropping_files_adds_images() {
    // spec: PLACE-001
    let dir = Scratch::new("drop");
    let a = dir.image("a.png", 40, 30, None);
    let b = dir.image("b.png", 20, 20, None);
    let mut app = app_with(&[&a]);
    let c = dir.image("c.png", 20, 20, None);
    let _ = app.update(Message::FileDropped(b));
    let _ = app.update(Message::FileDropped(c));
    let _ = app.update(Message::FlushDrops);
    assert_eq!(app.editor.project().state().items.len(), 3);
}

#[test]
fn snapshot_for_inspection() {
    let Ok(dir) = std::env::var("STITCHPANE_SNAPSHOT_DIR") else {
        return;
    };
    let scratch = Scratch::new("snap");
    let a = scratch.image("a.png", 400, 300, None);
    let b = scratch.image("b.png", 300, 300, None);
    let mut app = app_with(&[&a, &b]);
    let _ = app.update(Message::PointerDown(
        IPoint::new(300.0, 560.0),
        PointerButton::Secondary,
    ));
    present(&mut app);
    let mut ui = simulator(app.view());
    let snapshot = ui.snapshot(&Theme::Light).expect("snapshot");
    let path = format!("{dir}/iced-snap.png");
    let _ = std::fs::remove_file(&path);
    snapshot.matches_image(path).expect("write");
}

#[test]
fn edit_menu_names_the_steps() {
    // spec: UNDO-001, UNDO-003
    let dir = Scratch::new("editmenu");
    let a = dir.image("a.png", 40, 30, None);
    let mut app = app_with(&[&a]);
    assert!(app.editor.apply(Step::MoveItem {
        item: ItemId(1),
        x: 5,
        y: 5
    }));
    click(&mut app, "Edit");
    assert_shows(&app, "Undo Move image  (Ctrl+Z)");
    click(&mut app, "Undo Move image  (Ctrl+Z)");
    assert_eq!((item(&app, 1).x, item(&app, 1).y), (0, 0));
}

#[test]
fn save_button_saves() {
    // spec: UI-008
    let dir = Scratch::new("save");
    let a = dir.image("a.png", 40, 30, None);
    let mut app = app_with(&[&a]);
    app.editor
        .save_as(&dir.0.join("p.stitchpane"))
        .expect("save");
    assert!(app.editor.apply(Step::MoveItem {
        item: ItemId(1),
        x: 5,
        y: 5
    }));
    click(&mut app, "Save");
    assert!(!app.editor.is_dirty());
}

#[test]
fn file_dialogs_remember_the_folder() {
    // spec: UI-007
    let dir = Scratch::new("folder");
    let a = dir.image("a.png", 40, 30, None);
    std::fs::create_dir_all(dir.0.join("sub")).expect("sub dir");
    let b = dir.image("sub/b.png", 20, 20, None);
    let mut app = app_with(&[&a]);
    assert_eq!(app.editor.dialog_folder(), Some(dir.0.as_path()));
    let _ = app.update(Message::Picked(dialogs::Purpose::AddImages, vec![b]));
    assert_eq!(
        app.editor.dialog_folder(),
        Some(dir.0.join("sub").as_path())
    );
}

#[test]
fn resampling_happens_in_the_background() {
    // spec: UI-009
    let dir = Scratch::new("background");
    let a = dir.image("a.png", 400, 300, None);
    let mut app = app_with(&[&a]);
    assert!(app.editor.apply(Step::ResizeItem {
        item: ItemId(1),
        x: 0,
        y: 0,
        width: 200,
        height: 150,
        filter: stitchpane_core::model::Filter::Lanczos3,
    }));
    let _ = app.update(Message::Resized(Size::new(1024.0, 640.0)));
    assert!(app.editor.background_busy());
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
    while app.editor.background_busy() {
        assert!(std::time::Instant::now() < deadline);
        let _ = app.update(Message::PollBackground);
        std::thread::sleep(std::time::Duration::from_millis(5));
    }
}

#[test]
fn status_bar_zoom_opens_the_zoom_menu() {
    // spec: UI-010
    let dir = Scratch::new("zoom");
    let a = dir.image("a.png", 400, 300, None);
    let mut app = app_with(&[&a]);
    let label = app.editor.zoom_text();
    click(&mut app, &label);
    assert_shows(&app, "Zoom in");
    click(&mut app, "100%");
    assert_eq!(app.editor.zoom_text(), "zoom 100%");
}

#[test]
fn smear_bar_sets_the_brush_and_strokes_record_steps() {
    // spec: SMEAR-001, SMEAR-003, SMEAR-004
    let dir = Scratch::new("smear");
    let a = dir.image("a.png", 400, 300, None);
    let mut app = app_with(&[&a]);
    let _ = app.update(Message::PointerDown(
        IPoint::new(512.0, 320.0),
        PointerButton::Secondary,
    ));
    click(&mut app, "Smear");
    assert_shows(&app, "Done");
    let _ = app.update(Message::SmearField(0, "40".to_owned()));
    let _ = app.update(Message::SmearChoice("Blur".to_owned()));
    let tool = app.editor.smear_tool().expect("smear tool");
    assert_eq!((tool.size, tool.kind.label()), (40.0, "Blur"));
    let _ = app.update(Message::PointerDown(
        IPoint::new(500.0, 320.0),
        PointerButton::Primary,
    ));
    let _ = app.update(Message::PointerMove(IPoint::new(540.0, 320.0)));
    let _ = app.update(Message::PointerUp(IPoint::new(560.0, 320.0)));
    assert_eq!(app.editor.undo_label().as_deref(), Some("Undo Smear"));
    click(&mut app, "Done");
    assert!(app.editor.smear_tool().is_none());
}

#[test]
fn delete_removes_the_selected_image() {
    // spec: PLACE-009
    let dir = Scratch::new("remove");
    let a = dir.image("a.png", 40, 30, None);
    let b = dir.image("b.png", 20, 20, None);
    let mut app = app_with(&[&a]);
    let _ = app.update(Message::Picked(dialogs::Purpose::AddImages, vec![b]));
    assert_eq!(app.editor.project().state().items.len(), 2);
    let _ = app.update(Message::Key(
        keyboard::Key::Named(Named::Delete),
        keyboard::Modifiers::default(),
    ));
    assert_eq!(app.editor.project().state().items.len(), 1);
}

#[test]
fn canvas_keeps_the_shown_frame_until_a_newer_is_ready() {
    // spec: UI-011
    let dir = Scratch::new("frames");
    let a = dir.image("a.png", 400, 300, None);
    let mut app = app_with(&[&a]);
    present(&mut app);
    let first = shown_id(&app).expect("a frame is shown");

    // a new frame uploads while the old one stays on the canvas
    pointer_move(&mut app, 500.0);
    pointer_move(&mut app, 510.0);
    let [older, newer] = uploading_ids(&app)[..] else {
        panic!("two frames are uploading");
    };
    assert_eq!(shown_id(&app), Some(first));

    // a report for a frame that is not uploading changes nothing
    let _ = app.update(Message::FrameReady(first, None));
    assert_eq!(shown_id(&app), Some(first));
    assert_eq!(uploading_ids(&app), [older, newer]);

    // the newer frame is shown even if it finishes first; the older is then skipped
    let _ = app.update(Message::FrameReady(newer, None));
    assert_eq!(shown_id(&app), Some(newer));
    let _ = app.update(Message::FrameReady(older, None));
    assert_eq!(shown_id(&app), Some(newer));
    assert!(uploading_ids(&app).is_empty());
}

#[test]
fn canvas_uploads_several_frames_at_once() {
    // spec: UI-012
    let dir = Scratch::new("uploads");
    let a = dir.image("a.png", 400, 300, None);
    let mut app = app_with(&[&a]);
    present(&mut app);

    // each new frame starts uploading without waiting, up to the limit
    for i in 0..MAX_UPLOADS {
        pointer_move(&mut app, 500.0 + i as f32);
        assert_eq!(uploading_ids(&app).len(), i + 1);
    }
    let first = uploading_ids(&app)[0];

    // beyond the limit only the newest frame waits
    pointer_move(&mut app, 600.0);
    pointer_move(&mut app, 610.0);
    let newest = waiting_id(&app).expect("a frame waits");
    assert_eq!(uploading_ids(&app).len(), MAX_UPLOADS);

    // when an upload finishes, the waiting frame starts
    let _ = app.update(Message::FrameReady(first, None));
    assert_eq!(shown_id(&app), Some(first));
    assert_eq!(uploading_ids(&app).last(), Some(&newest));
    assert_eq!(uploading_ids(&app).len(), MAX_UPLOADS);
    assert!(waiting_id(&app).is_none());

    present(&mut app);
    assert_eq!(shown_id(&app), Some(newest));
}

#[test]
fn light_bar_edits_and_applies_the_settings() {
    // spec: LIGHT-001, LIGHT-006
    let dir = Scratch::new("light");
    let a = dir.image("a.png", 400, 300, None);
    let mut app = app_with(&[&a]);
    let _ = app.update(Message::PointerDown(
        IPoint::new(512.0, 320.0),
        PointerButton::Secondary,
    ));
    click(&mut app, "Adjust light");
    assert_shows(&app, "Reset");
    let _ = app.update(Message::LightField(0, "1.5".to_owned()));
    assert_eq!(app.editor.light_tool().map(|t| t.light.exposure), Some(1.5));
    // a field typed out of range leaves the settings as they were
    let _ = app.update(Message::LightField(0, "9".to_owned()));
    assert_eq!(app.light_fields[0], "9");
    assert_eq!(app.editor.light_tool().map(|t| t.light.exposure), Some(1.5));
    let _ = app.update(Message::LightField(0, "1.5".to_owned()));
    click(&mut app, "Apply");
    assert!(app.editor.light_tool().is_none());
    assert_eq!(item(&app, 1).light.map(|l| l.exposure), Some(1.5));
    assert_eq!(
        app.editor.undo_label().as_deref(),
        Some("Undo Adjust light")
    );
}

#[test]
fn dodge_bar_sets_the_brush() {
    // spec: DODGE-001, DODGE-003
    let dir = Scratch::new("dodge");
    let a = dir.image("a.png", 400, 300, None);
    let mut app = app_with(&[&a]);
    let _ = app.update(Message::PointerDown(
        IPoint::new(512.0, 320.0),
        PointerButton::Secondary,
    ));
    click(&mut app, "Dodge and burn");
    assert_shows(&app, "Done");
    let _ = app.update(Message::DodgeField(0, "30".to_owned()));
    let _ = app.update(Message::DodgeKind("Burn".to_owned()));
    let _ = app.update(Message::DodgeRange("Highlights".to_owned()));
    let tool = app.editor.dodge_tool().expect("dodge and burn tool");
    assert_eq!(
        (tool.size, tool.kind, tool.range),
        (30.0, StrokeKind::Burn, ToneRange::Highlights)
    );
    click(&mut app, "Done");
    assert!(app.editor.dodge_tool().is_none());
}

#[test]
fn file_menu_quit_asks_to_save() {
    // spec: UI-013, UI-002
    let dir = Scratch::new("quit");
    let a = dir.image("a.png", 40, 30, None);
    let mut app = app_with(&[&a]);
    assert!(app.editor.apply(Step::MoveItem {
        item: ItemId(1),
        x: 5,
        y: 5
    }));
    click(&mut app, "File");
    click(&mut app, "Quit  (Ctrl+Q)");
    assert!(matches!(
        app.modal,
        Some(Modal::ConfirmDiscard(dialogs::AfterDiscard::Quit))
    ));
    assert_shows(&app, "Discard");
}

#[test]
fn quitting_after_adding_to_the_empty_canvas_asks_to_save() {
    // spec: UI-002, UI-013
    let dir = Scratch::new("addquit");
    let a = dir.image("a.png", 40, 30, None);
    let mut app = app_with(&[]);
    let _ = app.update(Message::Picked(dialogs::Purpose::AddImages, vec![a]));
    let _ = app.update(Message::Command(Command::Quit));
    assert!(matches!(
        app.modal,
        Some(Modal::ConfirmDiscard(dialogs::AfterDiscard::Quit))
    ));
}