madamiru 0.6.0

Dynamic multi-multimedia player
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
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
use std::{collections::HashSet, num::NonZeroUsize, sync::LazyLock};

use iced::{
    Alignment, Length, Task, alignment,
    keyboard::Modifiers,
    padding,
    widget::{self, mouse_area, opaque, rule, scrollable},
};
use itertools::Itertools;

use crate::{
    gui::{
        button,
        common::{BrowseFileSubject, BrowseSubject, EditAction, Message, UndoSubject},
        grid,
        icon::Icon,
        shortcuts::{Shortcut, TextHistories, TextHistory},
        style,
        widget::{Column, Container, Element, Row, Scrollable, Space, Stack, checkbox, pick_list, text},
    },
    lang::{self, Language},
    media::{self, Media},
    path::StrictPath,
    prelude::Error,
    resource::{
        config::{self, Config, Theme},
        playlist,
    },
};

const RELEASE_URL: &str = "https://github.com/mtkennerly/madamiru/releases";
static SCROLLABLE: LazyLock<widget::Id> = LazyLock::new(widget::Id::unique);

pub fn scroll_down() -> Task<Message> {
    widget::operation::scroll_by(
        (*SCROLLABLE).clone(),
        scrollable::AbsoluteOffset { x: 0.0, y: f32::MAX },
    )
}

#[derive(Debug, Clone)]
pub enum Event {
    EditedSource { action: EditAction },
    EditedSourceKind { index: usize, kind: media::SourceKind },
    SelectedGridTab { tab: GridTab },
    EditedGridContentFit { content_fit: playlist::ContentFit },
    EditedGridOrientation { orientation: playlist::Orientation },
    EditedGridOrientationLimitKind { fixed: bool },
    EditedGridOrientationLimit { raw_limit: String },
    Save,
    PlayMedia(Media),
}

pub enum Update {
    SavedGridSettings {
        grid_id: grid::Id,
        settings: grid::Settings,
    },
    PlayMedia {
        grid_id: grid::Id,
        media: Media,
    },
    Task(Task<Message>),
}

pub enum ModalVariant {
    Info,
    Confirm,
    Editor,
}

#[derive(Debug, Clone)]
pub enum Modal {
    Settings,
    GridSettings {
        grid_id: grid::Id,
        tab: GridTab,
        settings: grid::Settings,
        histories: GridHistories,
    },
    GridMedia {
        grid_id: grid::Id,
        sources: Vec<media::Source>,
    },
    Error {
        variant: Error,
    },
    Errors {
        errors: Vec<Error>,
    },
    AppUpdate {
        release: crate::metadata::Release,
    },
    ConfirmLoadPlaylist {
        path: Option<StrictPath>,
    },
    ConfirmDiscardPlaylist {
        exit: bool,
    },
}

impl Modal {
    pub fn new_grid_settings(grid_id: grid::Id, mut settings: grid::Settings) -> Self {
        let mut histories = GridHistories::default();

        if settings.sources.is_empty() {
            settings.sources.push(media::Source::default());
            histories.sources.push(TextHistory::default())
        } else {
            for source in &settings.sources {
                histories.sources.push(TextHistory::raw(source.raw()));
            }
        }

        let raw_limit = match settings.orientation_limit {
            playlist::OrientationLimit::Automatic => playlist::OrientationLimit::DEFAULT_FIXED.to_string(),
            playlist::OrientationLimit::Fixed(limit) => limit.to_string(),
        };
        histories.orientation_limit.push(&raw_limit);

        Self::GridSettings {
            grid_id,
            tab: GridTab::default(),
            settings,
            histories,
        }
    }

    pub fn grid_id(&self) -> Option<grid::Id> {
        match self {
            Self::Settings => None,
            Self::GridSettings { grid_id, .. } => Some(*grid_id),
            Self::GridMedia { grid_id, .. } => Some(*grid_id),
            Self::Error { .. } => None,
            Self::Errors { .. } => None,
            Self::AppUpdate { .. } => None,
            Self::ConfirmLoadPlaylist { .. } => None,
            Self::ConfirmDiscardPlaylist { .. } => None,
        }
    }

    pub fn variant(&self) -> ModalVariant {
        match self {
            Self::Error { .. } | Self::Errors { .. } | Self::GridMedia { .. } => ModalVariant::Info,
            Self::GridSettings { .. }
            | Self::AppUpdate { .. }
            | Self::ConfirmLoadPlaylist { .. }
            | Self::ConfirmDiscardPlaylist { .. } => ModalVariant::Confirm,
            Self::Settings => ModalVariant::Editor,
        }
    }

    pub fn title(&self, _config: &Config) -> Option<Element> {
        match self {
            Self::Settings => None,
            Self::GridSettings { tab, .. } => Some(
                Row::new()
                    .spacing(20)
                    .push(GridTab::Sources.view(*tab))
                    .push(GridTab::Layout.view(*tab))
                    .into(),
            ),
            Self::GridMedia { .. } => None,
            Self::Error { .. } => None,
            Self::Errors { .. } => None,
            Self::AppUpdate { .. } => None,
            Self::ConfirmLoadPlaylist { .. } => None,
            Self::ConfirmDiscardPlaylist { .. } => None,
        }
    }

    pub fn message(&self) -> Option<Message> {
        match self {
            Self::Settings => Some(Message::CloseModal),
            Self::GridSettings { .. } => Some(Message::Modal { event: Event::Save }),
            Self::GridMedia { .. } => Some(Message::CloseModal),
            Self::Error { .. } => Some(Message::CloseModal),
            Self::Errors { .. } => Some(Message::CloseModal),
            Self::AppUpdate { release } => Some(Message::OpenUrlAndCloseModal(release.url.clone())),
            Self::ConfirmLoadPlaylist { path } => match path {
                Some(path) => Some(Message::PlaylistLoad { path: path.clone() }),
                None => Some(Message::PlaylistSelect { force: true }),
            },
            Self::ConfirmDiscardPlaylist { exit } => {
                if *exit {
                    Some(Message::Exit { force: true })
                } else {
                    Some(Message::PlaylistReset { force: true })
                }
            }
        }
    }

    pub fn body(
        &self,
        config: &Config,
        histories: &TextHistories,
        modifiers: &Modifiers,
        playlist: Option<&StrictPath>,
        collection: &media::Collection,
        active_media: HashSet<&Media>,
    ) -> Option<Column> {
        let mut col = Column::new().spacing(15).padding(padding::right(10));

        match self {
            Self::Settings => {
                col = col
                    .push(text(lang::field(&lang::thing::application())))
                    .push(
                        Container::new(
                            Column::new()
                                .spacing(10)
                                .padding(10)
                                .push(
                                    Row::new()
                                        .align_y(Alignment::Center)
                                        .spacing(20)
                                        .push(text(lang::field(&lang::thing::language())))
                                        .push(pick_list(Language::ALL, Some(config.view.language), |value| {
                                            Message::Config {
                                                event: config::Event::Language(value),
                                            }
                                        })),
                                )
                                .push(
                                    Row::new()
                                        .align_y(Alignment::Center)
                                        .spacing(20)
                                        .push(text(lang::field(&lang::thing::theme())))
                                        .push(pick_list(Theme::ALL, Some(config.view.theme), |value| {
                                            Message::Config {
                                                event: config::Event::Theme(value),
                                            }
                                        })),
                                )
                                .push(
                                    Row::new()
                                        .align_y(Alignment::Center)
                                        .spacing(20)
                                        .push(checkbox(
                                            lang::action::check_for_updates(),
                                            config.release.check,
                                            |value| Message::Config {
                                                event: config::Event::CheckRelease(value),
                                            },
                                        ))
                                        .push(
                                            button::icon(Icon::OpenInBrowser)
                                                .on_press(Message::OpenUrl(RELEASE_URL.to_string()))
                                                .tooltip(lang::action::view_releases())
                                                .padding([0, 10]),
                                        ),
                                )
                                .push(checkbox(
                                    lang::action::pause_when_window_loses_focus(),
                                    config.playback.pause_on_unfocus,
                                    |value| Message::Config {
                                        event: config::Event::PauseWhenWindowLosesFocus(value),
                                    },
                                ))
                                .push(checkbox(
                                    lang::action::confirm_when_discarding_unsaved_playlist(),
                                    config.view.confirm_discard_playlist,
                                    |value| Message::Config {
                                        event: config::Event::ConfirmWhenDiscardingUnsavedPlaylist(value),
                                    },
                                ))
                                .push(checkbox(
                                    lang::action::show_fullscreen_controls(),
                                    config.view.show_fullscreen_controls,
                                    |value| Message::Config {
                                        event: config::Event::ShowFullscreenControls(value),
                                    },
                                ))
                                .push(checkbox(
                                    lang::action::show_media_borders(),
                                    config.view.show_media_borders,
                                    |value| Message::Config {
                                        event: config::Event::ShowMediaBorders(value),
                                    },
                                ))
                                .push(
                                    Row::new()
                                        .spacing(10)
                                        .push(
                                            Column::new()
                                                .spacing(10)
                                                .push(text(lang::field(&lang::thing::media_padding())))
                                                .push(text(lang::field(&lang::thing::grid_padding())))
                                                .push(text(lang::field(&lang::thing::group_padding()))),
                                        )
                                        .push(
                                            Column::new()
                                                .spacing(10)
                                                .push(
                                                    Row::new()
                                                        .spacing(10)
                                                        .push(
                                                            iced::widget::slider(
                                                                0..=10,
                                                                config.view.media_padding,
                                                                |value| Message::Config {
                                                                    event: config::Event::MediaPadding(value),
                                                                },
                                                            )
                                                            .step(1)
                                                            .width(150),
                                                        )
                                                        .push(text(config.view.media_padding)),
                                                )
                                                .push(
                                                    Row::new()
                                                        .spacing(10)
                                                        .push(
                                                            iced::widget::slider(
                                                                0..=10,
                                                                config.view.grid_padding,
                                                                |value| Message::Config {
                                                                    event: config::Event::GridPadding(value),
                                                                },
                                                            )
                                                            .step(1)
                                                            .width(150),
                                                        )
                                                        .push(text(config.view.grid_padding)),
                                                )
                                                .push(
                                                    Row::new()
                                                        .spacing(10)
                                                        .push(
                                                            iced::widget::slider(
                                                                0..=10,
                                                                config.view.group_padding,
                                                                |value| Message::Config {
                                                                    event: config::Event::GroupPadding(value),
                                                                },
                                                            )
                                                            .step(1)
                                                            .width(150),
                                                        )
                                                        .push(text(config.view.group_padding)),
                                                ),
                                        ),
                                ),
                        )
                        .class(style::Container::Control),
                    )
                    .push(text(lang::field(&lang::thing::audio())))
                    .push(
                        Container::new(
                            Column::new().spacing(10).padding(10).push(
                                Row::new()
                                    .spacing(10)
                                    .align_y(alignment::Vertical::Center)
                                    .push(
                                        button::icon(if config.playback.muted {
                                            Icon::Mute
                                        } else {
                                            Icon::VolumeHigh
                                        })
                                        .on_press(Message::SetMute(!config.playback.muted))
                                        .tooltip(if config.playback.muted {
                                            lang::action::unmute()
                                        } else {
                                            lang::action::mute()
                                        }),
                                    )
                                    .push(
                                        iced::widget::slider(0.01..=1.0, config.playback.volume, |volume| {
                                            Message::SetVolume { volume }
                                        })
                                        .step(0.01_f32)
                                        .width(150),
                                    )
                                    .push(
                                        text(format!("{:.0}%", config.playback.volume * 100.0))
                                            .width(50)
                                            .align_x(alignment::Horizontal::Center),
                                    ),
                            ),
                        )
                        .class(style::Container::Control),
                    )
                    .push(text(lang::field(&lang::thing::image())))
                    .push(
                        Container::new(
                            Column::new()
                                .spacing(10)
                                .padding(10)
                                .push(
                                    Row::new()
                                        .align_y(Alignment::Center)
                                        .spacing(20)
                                        .push(text(lang::field(&lang::action::play_for_this_many_seconds())))
                                        .push(UndoSubject::ImageDuration.view_with(histories)),
                                )
                                .push(
                                    Row::new()
                                        .align_y(Alignment::Center)
                                        .spacing(20)
                                        .push(text(lang::field(&lang::thing::minimum_animation_loops())))
                                        .push(UndoSubject::MinimumAnimationLoops.view_with(histories)),
                                ),
                        )
                        .class(style::Container::Control),
                    );
            }
            Self::GridSettings {
                tab: GridTab::Sources,
                settings,
                histories,
                ..
            } => {
                for (index, source) in settings.sources.iter().enumerate() {
                    col = col.push(
                        Row::new()
                            .spacing(20)
                            .align_y(alignment::Vertical::Center)
                            .push(
                                Row::new()
                                    .spacing(10)
                                    .align_y(alignment::Vertical::Center)
                                    .push(button::move_up(
                                        |action| Message::Modal {
                                            event: Event::EditedSource { action },
                                        },
                                        index,
                                    ))
                                    .push(button::move_down(
                                        |action| Message::Modal {
                                            event: Event::EditedSource { action },
                                        },
                                        index,
                                        settings.sources.len(),
                                    ))
                                    .push(pick_list(media::SourceKind::ALL, Some(source.kind()), move |kind| {
                                        Message::Modal {
                                            event: Event::EditedSourceKind { index, kind },
                                        }
                                    })),
                            )
                            .push(UndoSubject::Source { index }.view(&histories.sources[index].current()))
                            .push(match source {
                                media::Source::Path { path } => Row::new()
                                    .spacing(10)
                                    .align_y(alignment::Vertical::Center)
                                    .push(button::choose_folder(
                                        BrowseSubject::Source { index },
                                        media::fill_placeholders_in_path(path, playlist),
                                        modifiers,
                                    ))
                                    .push(button::choose_file(
                                        BrowseFileSubject::Source { index },
                                        media::fill_placeholders_in_path(path, playlist),
                                        modifiers,
                                    ))
                                    .push(
                                        button::icon(Icon::Close)
                                            .on_press(Message::Modal {
                                                event: Event::EditedSource {
                                                    action: EditAction::Remove(index),
                                                },
                                            })
                                            .enabled(settings.sources.len() > 1),
                                    ),
                                media::Source::Glob { .. } => {
                                    Row::new().spacing(10).align_y(alignment::Vertical::Center).push(
                                        button::icon(Icon::Close)
                                            .on_press(Message::Modal {
                                                event: Event::EditedSource {
                                                    action: EditAction::Remove(index),
                                                },
                                            })
                                            .enabled(settings.sources.len() > 1),
                                    )
                                }
                            }),
                    );
                }

                col = col.push(button::icon(Icon::Add).on_press(Message::Modal {
                    event: Event::EditedSource {
                        action: EditAction::Add,
                    },
                }));
            }
            Self::GridSettings {
                tab: GridTab::Layout,
                settings,
                histories,
                ..
            } => {
                col = col
                    .push(
                        Row::new()
                            .align_y(Alignment::Center)
                            .spacing(20)
                            .push(text(lang::field(&lang::thing::orientation())))
                            .push(pick_list(
                                playlist::Orientation::ALL,
                                Some(settings.orientation),
                                |orientation| Message::Modal {
                                    event: Event::EditedGridOrientation { orientation },
                                },
                            )),
                    )
                    .push(
                        Row::new()
                            .align_y(Alignment::Center)
                            .spacing(20)
                            .push(checkbox(
                                lang::field(&lang::thing::items_per_line()),
                                settings.orientation_limit.is_fixed(),
                                |fixed| Message::Modal {
                                    event: Event::EditedGridOrientationLimitKind { fixed },
                                },
                            ))
                            .push(UndoSubject::OrientationLimit.view(&histories.orientation_limit.current())),
                    )
                    .push(
                        Row::new()
                            .align_y(Alignment::Center)
                            .spacing(20)
                            .push(text(lang::field(&lang::thing::content_fit())))
                            .push(pick_list(
                                playlist::ContentFit::ALL,
                                Some(settings.content_fit),
                                |content_fit| Message::Modal {
                                    event: Event::EditedGridContentFit { content_fit },
                                },
                            )),
                    );
            }
            Self::GridMedia { sources, .. } => {
                col = col.spacing(2);

                let all_media = collection.all_for_sources(sources);

                if all_media.is_empty() {
                    col = col.push(text(lang::tell::no_media_found_in_sources()));
                }

                for media in all_media {
                    col = col.push(
                        Row::new()
                            .spacing(10)
                            .align_y(Alignment::Center)
                            .push(if collection.is_error(media) {
                                button::icon(Icon::Error)
                            } else {
                                button::icon(Icon::Play).on_press_maybe((!active_media.contains(media)).then(|| {
                                    Message::Modal {
                                        event: Event::PlayMedia(media.clone()),
                                    }
                                }))
                            })
                            .push(
                                match media.category() {
                                    media::Category::Image => Icon::Image,
                                    #[cfg(feature = "audio")]
                                    media::Category::Audio => Icon::Music,
                                    #[cfg(feature = "video")]
                                    media::Category::Video => Icon::Movie,
                                }
                                .small_control(),
                            )
                            .push(button::open_path(media.path().clone(), modifiers))
                            .push(text(media.path().raw())),
                    );
                }
            }
            Self::Error { variant } => {
                col = col.push(text(lang::handle_error(variant)));
            }
            Self::Errors { errors } => {
                col = col.push(text(errors.iter().map(lang::handle_error).join("\n\n")));
            }
            Self::AppUpdate { release } => {
                col = col
                    .push(text(lang::tell::new_version_available(
                        release.version.to_string().as_str(),
                    )))
                    .push(text(lang::ask::view_release_notes()));
            }
            Self::ConfirmLoadPlaylist { .. } => {
                col = col.push(text(lang::join!(
                    lang::tell::playlist_has_unsaved_changes(),
                    lang::ask::load_new_playlist_anyway()
                )));
            }
            Self::ConfirmDiscardPlaylist { .. } => {
                col = col.push(text(lang::join!(
                    lang::tell::playlist_has_unsaved_changes(),
                    lang::ask::discard_changes()
                )));
            }
        }

        Some(col)
    }

    pub fn controls(&self) -> Element {
        let positive_button = button::primary(match self.variant() {
            ModalVariant::Info => lang::action::close(),
            ModalVariant::Confirm => lang::action::confirm(),
            ModalVariant::Editor => lang::action::close(),
        })
        .on_press_maybe(self.message());

        let negative_button = button::negative(lang::action::cancel()).on_press(Message::CloseModal);

        let row = match self.variant() {
            ModalVariant::Info | ModalVariant::Editor => Row::new().push(positive_button),
            ModalVariant::Confirm => Row::new().push(positive_button).push(negative_button),
        };

        row.spacing(20).padding([0, 30]).into()
    }

    fn content(
        &self,
        viewport: iced::Size,
        config: &Config,
        histories: &TextHistories,
        modifiers: &Modifiers,
        playlist: Option<&StrictPath>,
        collection: &media::Collection,
        active_media: HashSet<&Media>,
    ) -> Container {
        Container::new(
            Column::new()
                .spacing(30)
                .padding(padding::top(30).bottom(30))
                .align_x(Alignment::Center)
                .push(self.title(config))
                .push(
                    self.body(config, histories, modifiers, playlist, collection, active_media)
                        .map(|body| {
                            Container::new(Scrollable::new(body.padding([0, 30])).id((*SCROLLABLE).clone()))
                                .padding(padding::right(5))
                                .max_height(viewport.height - 300.0)
                        }),
                )
                .push(Container::new(self.controls())),
        )
        .class(style::Container::ModalForeground)
    }

    pub fn apply_shortcut(&mut self, subject: UndoSubject, shortcut: Shortcut) -> bool {
        match self {
            Self::Settings
            | Self::GridMedia { .. }
            | Self::Error { .. }
            | Self::Errors { .. }
            | Self::AppUpdate { .. }
            | Self::ConfirmLoadPlaylist { .. }
            | Self::ConfirmDiscardPlaylist { .. } => false,
            Self::GridSettings {
                settings, histories, ..
            } => match subject {
                UndoSubject::ImageDuration => false,
                UndoSubject::MinimumAnimationLoops => false,
                UndoSubject::Source { index } => {
                    settings.sources[index].reset(histories.sources[index].apply(shortcut));
                    true
                }
                UndoSubject::OrientationLimit => {
                    if let Ok(value) = histories.orientation_limit.apply(shortcut).parse::<NonZeroUsize>() {
                        settings.orientation_limit = playlist::OrientationLimit::Fixed(value);
                    }
                    true
                }
            },
        }
    }

    #[must_use]
    pub fn update(&mut self, event: Event) -> Option<Update> {
        match self {
            Self::Settings
            | Self::Error { .. }
            | Self::Errors { .. }
            | Self::AppUpdate { .. }
            | Self::ConfirmLoadPlaylist { .. }
            | Self::ConfirmDiscardPlaylist { .. } => None,
            Self::GridSettings {
                grid_id,
                tab,
                settings,
                histories,
            } => match event {
                Event::EditedSource { action } => {
                    match action {
                        EditAction::Add => {
                            let value = StrictPath::default();
                            histories.sources.push(TextHistory::path(&value));
                            settings.sources.push(media::Source::new_path(value));
                            return Some(Update::Task(scroll_down()));
                        }
                        EditAction::Change(index, value) => {
                            histories.sources[index].push(&value);
                            settings.sources[index].reset(value);
                        }
                        EditAction::Remove(index) => {
                            histories.sources.remove(index);
                            settings.sources.remove(index);
                        }
                        EditAction::Move(index, direction) => {
                            let offset = direction.shift(index);
                            histories.sources.swap(index, offset);
                            settings.sources.swap(index, offset);
                        }
                    }
                    None
                }
                Event::EditedSourceKind { index, kind } => {
                    settings.sources[index].set_kind(kind);
                    None
                }
                Event::SelectedGridTab { tab: new_tab } => {
                    *tab = new_tab;
                    None
                }
                Event::EditedGridContentFit { content_fit } => {
                    settings.content_fit = content_fit;
                    None
                }
                Event::EditedGridOrientation { orientation } => {
                    settings.orientation = orientation;
                    None
                }
                Event::EditedGridOrientationLimitKind { fixed } => {
                    if fixed {
                        let limit = histories
                            .orientation_limit
                            .current()
                            .parse::<NonZeroUsize>()
                            .unwrap_or(playlist::OrientationLimit::default_fixed());
                        settings.orientation_limit = playlist::OrientationLimit::Fixed(limit);
                    } else {
                        settings.orientation_limit = playlist::OrientationLimit::Automatic;
                    }
                    None
                }
                Event::EditedGridOrientationLimit { raw_limit } => {
                    histories.orientation_limit.push(&raw_limit);
                    if settings.orientation_limit.is_fixed()
                        && let Ok(limit) = raw_limit.parse::<NonZeroUsize>()
                    {
                        settings.orientation_limit = playlist::OrientationLimit::Fixed(limit);
                    }
                    None
                }
                Event::Save => {
                    for index in (0..settings.sources.len()).rev() {
                        if settings.sources[index].is_empty() {
                            settings.sources.remove(index);
                        }
                    }

                    Some(Update::SavedGridSettings {
                        grid_id: *grid_id,
                        settings: settings.clone(),
                    })
                }
                Event::PlayMedia(_) => None,
            },
            Self::GridMedia { grid_id, .. } => match event {
                Event::PlayMedia(media) => Some(Update::PlayMedia {
                    grid_id: *grid_id,
                    media,
                }),
                _ => None,
            },
        }
    }

    pub fn view(
        &self,
        viewport: iced::Size,
        config: &Config,
        histories: &TextHistories,
        modifiers: &Modifiers,
        playlist: Option<&StrictPath>,
        collection: &media::Collection,
        active_media: HashSet<&Media>,
    ) -> Element {
        Stack::new()
            .push({
                let mut area = mouse_area(
                    Container::new(Space::new().width(Length::Fill).height(Length::Fill))
                        .class(style::Container::ModalBackground),
                );

                match self.variant() {
                    ModalVariant::Info | ModalVariant::Confirm | ModalVariant::Editor => {
                        area = area.on_press(Message::CloseModal);
                    }
                }

                area
            })
            .push(
                Container::new(opaque(self.content(
                    viewport,
                    config,
                    histories,
                    modifiers,
                    playlist,
                    collection,
                    active_media,
                )))
                .center(Length::Fill)
                .padding([0.0, (100.0 + viewport.width - 640.0).clamp(0.0, 100.0)]),
            )
            .into()
    }
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum GridTab {
    #[default]
    Sources,
    Layout,
}

impl GridTab {
    fn view(&self, selected: Self) -> Element {
        let label = match self {
            GridTab::Sources => lang::thing::sources(),
            GridTab::Layout => lang::thing::layout(),
        };

        Column::new()
            .width(80)
            .spacing(2)
            .align_x(alignment::Horizontal::Center)
            .push(button::bare(label).on_press(Message::Modal {
                event: Event::SelectedGridTab { tab: *self },
            }))
            .push((*self == selected).then_some(rule::horizontal(2)))
            .into()
    }
}

#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct GridHistories {
    pub sources: Vec<TextHistory>,
    pub orientation_limit: TextHistory,
}