-
Notifications
You must be signed in to change notification settings - Fork 134
/
Copy pathmod.rs
1319 lines (1114 loc) · 45.9 KB
/
mod.rs
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
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2023 System76 <[email protected]>
// SPDX-License-Identifier: GPL-3.0-only
mod config;
pub mod widgets;
pub use config::Config;
use url::Url;
use std::{
collections::HashMap,
path::{Path, PathBuf},
sync::Arc,
};
use apply::Apply;
use cosmic::{command, Command};
use cosmic::{
dialog::file_chooser,
widget::{
button, dropdown, list_column, row,
segmented_button::{self, SingleSelectModel},
settings, text, toggler, view_switcher,
},
};
use cosmic::{
iced::{wayland::actions::window::SctkWindowSettings, window, Color, Length},
prelude::CollectionWidget,
};
use cosmic::{
iced_core::Alignment,
iced_sctk::commands::window::{close_window, get_window},
widget::icon,
};
use cosmic::{
iced_core::{alignment, layout},
iced_runtime::core::image::Handle as ImageHandle,
};
use cosmic::{
widget::{color_picker::ColorPickerUpdate, ColorPickerModel},
Element,
};
use cosmic_settings_page::Section;
use cosmic_settings_page::{self as page, section};
use cosmic_settings_wallpaper::{self as wallpaper, Entry, ScalingMode};
use image::imageops::FilterType::Lanczos3;
use image::{ImageBuffer, Rgba};
use slotmap::{DefaultKey, SecondaryMap, SlotMap};
const ZOOM: usize = 0;
const FIT: usize = 1;
const SIMULATED_WIDTH: u16 = 300;
const SIMULATED_HEIGHT: u16 = 169;
const MINUTES_5: usize = 0;
const MINUTES_10: usize = 1;
const MINUTES_15: usize = 2;
const MINUTES_30: usize = 3;
const HOUR_1: usize = 4;
const HOUR_2: usize = 5;
pub type Image = ImageBuffer<Rgba<u8>, Vec<u8>>;
#[derive(Clone, Debug)]
struct OutputName(String);
#[derive(Clone, Debug)]
pub struct InitUpdate {
service_config: wallpaper::Config,
displays: HashMap<String, (String, (u32, u32))>,
selection: Context,
}
/// Messages for the wallpaper view.
#[derive(Clone, Debug)]
pub enum Message {
/// Adds a new wallpaper folder.
AddFolder(Arc<Result<Url, file_chooser::Error>>),
/// Adds a new image file the system wallpaper folder.
AddFile(Arc<Result<Url, file_chooser::Error>>),
/// Selects an option in the category dropdown menu.
ChangeCategory(Category),
/// Changes the displayed images in the wallpaper view.
ChangeFolder(Context),
/// Creates a color dialog
ColorAddDialog,
/// Handles messages from the color dialog.
ColorDialogUpdate(ColorPickerUpdate),
/// Removes a custom color from the color view.
ColorRemove(wallpaper::Color),
/// Selects a color in the color view.
ColorSelect(wallpaper::Color),
/// Handles the drag message in the color dialog.
DragColorDialog,
/// Sets the wallpaper fit parameter.
Fit(usize),
/// Adds a new custom image to the wallpaper view.
ImageAdd(Option<Arc<(PathBuf, Image, Image)>>),
/// Creates an image dialog.
ImageAddDialog,
/// Removes a custom image from the wallpaper view.
ImageRemove(DefaultKey),
/// Initializes the view.
Init(Box<InitUpdate>),
/// Changes the active output display that is to be configured.
Output(segmented_button::Entity),
/// Changes the rotation frequency of wallpaper images in slideshow mode.
RotationFrequency(usize),
/// If set, all outputs will use the same wallpaper.
SameWallpaper(bool),
/// Selects an background option from the list of selections in the view.
Select(DefaultKey),
/// Changes the slideshow parameter.
Slideshow(bool),
}
impl From<Message> for crate::app::Message {
fn from(message: Message) -> Self {
let page_message = crate::pages::Message::DesktopWallpaper(message);
crate::app::Message::PageMessage(page_message)
}
}
/// Messages defined for the category dropdown menu.
#[derive(Clone, Debug, PartialEq)]
pub enum Category {
/// Opens a dialog for adding a folder
AddFolder,
/// Changes the view to the color view.
Colors,
/// Changes the view to an added folder.
RecentFolder(usize),
/// Changes the view to the system wallpaper view.
Wallpapers,
}
/// The page struct for the wallpaper view.
pub struct Page {
/// The display that is currently being configured.
///
/// If set to `None`, all displays will have the same wallpaper.
active_output: Option<String>,
/// Configuration parameters used by the cosmic-bg service.
wallpaper_service_config: wallpaper::Config,
/// Cache for storing the image used by the display preview.
cached_display_handle: Option<ImageHandle>,
/// Model for the category dropdown, which has categories and recent folders.
categories: dropdown::multi::Model<String, Category>,
/// The window ID of the color dialog.
pub color_dialog: window::Id,
/// The color model updated by the color dialog.
color_model: ColorPickerModel,
/// Settings for this page, stored by cosmic-config.
config: Config,
/// Model containing available wallpaper fit options.
fit_options: Vec<String>,
/// Model for selecting between display outputs.
outputs: SingleSelectModel,
/// Current value of the slideshow rotation frequency.
rotation_frequency: u64,
/// Model for available options for rotation frequencies.
rotation_options: Vec<String>,
/// The ID of the currently-selected wallpaper fit.
selected_fit: usize,
/// The ID of the currently-selected slideshow rotation.
selected_rotation: usize,
/// Stores custom colors, custom images, and all image data for every wallpaper.
selection: Context,
/// When set, applys a config update after images are loaded.
update_config: Option<(usize, HashMap<String, (String, (u32, u32))>)>,
}
impl page::Page<crate::pages::Message> for Page {
fn content(
&self,
sections: &mut SlotMap<section::Entity, Section<crate::pages::Message>>,
) -> Option<page::Content> {
Some(vec![sections.insert(settings())])
}
fn info(&self) -> page::Info {
page::Info::new("wallpaper", "preferences-desktop-wallpaper-symbolic")
.title(fl!("wallpaper"))
.description(fl!("wallpaper", "desc"))
}
fn reload(&mut self, _page: page::Entity) -> Command<crate::pages::Message> {
let current_folder = self.config.current_folder().to_owned();
command::future(async move {
let (service_config, displays) = wallpaper::config().await;
let selection = change_folder(current_folder).await;
crate::pages::Message::DesktopWallpaper(Message::Init(Box::new(InitUpdate {
service_config,
displays,
selection,
})))
})
}
}
impl page::AutoBind<crate::pages::Message> for Page {}
impl Default for Page {
fn default() -> Self {
let mut page = Page {
active_output: None,
cached_display_handle: None,
categories: {
let mut categories = dropdown::multi::model();
categories.insert(dropdown::multi::list(
None,
vec![(fl!("wallpaper", "plural"), Category::Wallpapers)],
));
categories.insert(dropdown::multi::list(
None,
vec![(fl!("colors"), Category::Colors)],
));
categories.insert(dropdown::multi::list(
None,
vec![(fl!("open-new-folder"), Category::AddFolder)],
));
categories.insert(dropdown::multi::list(
Some(fl!("recent-folders")),
Vec::with_capacity(5),
));
categories.selected = Some(Category::Wallpapers);
categories
},
wallpaper_service_config: wallpaper::Config::default(),
color_dialog: window::Id::unique(),
color_model: ColorPickerModel::new(fl!("hex"), fl!("rgb"), None, Some(Color::WHITE)),
config: Config::new(),
fit_options: vec![fl!("fill"), fl!("fit-to-screen")],
outputs: SingleSelectModel::default(),
rotation_frequency: 300,
rotation_options: vec![
// FIX: fluent is inserting extra unicode characters in formatting
fl!("x-minutes", number = 5)
.replace('\u{2068}', "")
.replace('\u{2069}', ""),
fl!("x-minutes", number = 10)
.replace('\u{2068}', "")
.replace('\u{2069}', ""),
fl!("x-minutes", number = 15)
.replace('\u{2068}', "")
.replace('\u{2069}', ""),
fl!("x-minutes", number = 30)
.replace('\u{2068}', "")
.replace('\u{2069}', ""),
fl!("x-hours", number = 1)
.replace('\u{2068}', "")
.replace('\u{2069}', ""),
fl!("x-hours", number = 2)
.replace('\u{2068}', "")
.replace('\u{2069}', ""),
],
selected_fit: 0,
selected_rotation: 0,
selection: Context::default(),
update_config: None,
};
page.assign_recent_folders();
page
}
}
impl Page {
fn add_recent_folder(&mut self, folder: PathBuf) {
if let Err(why) = self.config.add_recent_folder(folder) {
tracing::error!(?why, "cannot add recent folder to config");
}
self.assign_recent_folders();
}
fn assign_recent_folders(&mut self) {
let recent_list = &mut self.categories.lists[3];
recent_list.options.clear();
for (id, folder) in self.config.recent_folders().iter().enumerate() {
if let Some(name) = folder.file_name() {
let name = name.to_string_lossy();
recent_list
.options
.push((name.to_string(), Category::RecentFolder(id)));
}
}
}
fn cache_display_image(&mut self) {
self.cached_display_handle = None;
let choice = match self.selection.active {
Choice::Wallpaper(id) => self.selection.display_images.get(id),
Choice::Slideshow => self
.config_output()
.and_then(|output| {
let path = wallpaper::current_image(output).ok()?;
let id = self.wallpaper_id_from_path(&path)?;
Some(&self.selection.display_images[id])
})
.or(self.selection.display_images.values().next()),
Choice::Color(_) => None,
};
let Some(image) = choice else {
return;
};
let temp_image;
let image = match self.selected_fit {
ZOOM => {
let (w, h) = (image.width(), image.height());
let ratio =
(SIMULATED_WIDTH as f64 / w as f64).max(SIMULATED_HEIGHT as f64 / h as f64);
let (new_width, new_height) = (
(w as f64 * ratio).round() as u32,
(h as f64 * ratio).round() as u32,
);
let mut new_image = image::imageops::resize(image, new_width, new_height, Lanczos3);
temp_image = image::imageops::crop(
&mut new_image,
(new_width - SIMULATED_WIDTH as u32) / 2,
(new_height - SIMULATED_HEIGHT as u32) / 2,
SIMULATED_WIDTH as u32,
SIMULATED_HEIGHT as u32,
)
.to_image();
&temp_image
}
FIT => image,
_ => return,
};
self.cached_display_handle = Some(ImageHandle::from_pixels(
image.width(),
image.height(),
image.to_vec(),
));
}
fn config_output(&self) -> Option<&str> {
if self.wallpaper_service_config.same_on_all {
Some("all")
} else {
self.outputs
.active_data::<OutputName>()
.map(|name| name.0.as_str())
}
}
/// Applies the current settings to cosmic-bg.
pub fn config_apply(&mut self) {
let Some(output) = self.config_output().map(String::from) else {
return;
};
if self.wallpaper_service_config.same_on_all {
self.wallpaper_service_config.backgrounds.clear();
self.wallpaper_service_config.outputs.clear();
} else if let Some(pos) = self
.wallpaper_service_config
.backgrounds
.iter()
.position(|entry| entry.output == output)
{
let _removed = self.wallpaper_service_config.backgrounds.swap_remove(pos);
}
let entry = match self.selection.active {
Choice::Slideshow => {
match self
.config_wallpaper_entry(output, self.config.current_folder().to_path_buf())
{
Some(entry) => entry,
None => return,
}
}
Choice::Wallpaper(key) => {
if let Some(path) = self.selection.paths.get(key) {
match self.config_wallpaper_entry(output, path.clone()) {
Some(entry) => entry,
None => return,
}
} else {
return;
}
}
Choice::Color(ref color) => Entry::new(output, wallpaper::Source::Color(color.clone())),
};
wallpaper::set(&mut self.wallpaper_service_config, entry);
}
/// Locate the ID of a wallpaper that's already stored in memory
fn wallpaper_id_from_path(&self, path: &Path) -> Option<DefaultKey> {
self.selection
.paths
.iter()
.find(|(_id, wallpaper)| *wallpaper == path)
.map(|(id, _)| id)
}
/// Updates configuration from the wallpaper service.
fn wallpaper_service_config_update(&mut self, displays: HashMap<String, (String, (u32, u32))>) {
let mut first = None;
for (name, (_model, physical)) in displays {
let is_internal = "eDP-1" == name;
let entity = self
.outputs
.insert()
.text(crate::utils::display_name(&name, physical))
.data(OutputName(name));
if is_internal || first.is_none() {
first = Some(entity.id());
}
}
if let Some(id) = first {
self.outputs.activate(id);
}
self.apply_active_selection();
}
/// Apply the selection for the active output.
fn apply_active_selection(&mut self) {
if self.wallpaper_service_config.same_on_all
|| self.wallpaper_service_config.backgrounds.is_empty()
{
let entry = self.wallpaper_service_config.default_background.clone();
self.select_wallpaper_entry(&entry);
} else if let Some(OutputName(output)) = self.outputs.active_data() {
let mut wallpapers = Vec::new();
std::mem::swap(
&mut self.wallpaper_service_config.backgrounds,
&mut wallpapers,
);
for wallpaper in &wallpapers {
if wallpaper.output == *output {
self.active_output = Some(output.clone());
self.select_wallpaper_entry(wallpaper);
break;
}
}
std::mem::swap(
&mut self.wallpaper_service_config.backgrounds,
&mut wallpapers,
);
}
}
/// Changes the selection category, such as wallpaper select or color select.
fn change_category(&mut self, category: Category) -> Command<crate::app::Message> {
let mut command = Command::none();
match category {
Category::Wallpapers => {
if self.config.current_folder.is_some() {
let _ = self.config.set_current_folder(None);
command = cosmic::command::future(async move {
let folder = change_folder(Config::default_folder().to_owned()).await;
Message::ChangeFolder(folder).into()
});
} else {
self.select_first_wallpaper();
}
}
Category::Colors => {
self.selection.active = Choice::Color(wallpaper::DEFAULT_COLORS[0].clone());
self.cache_display_image();
}
Category::RecentFolder(id) => {
if let Some(path) = self.config.recent_folders().get(id).cloned() {
if let Err(why) = self.config.set_current_folder(Some(path.clone())) {
tracing::error!(?path, ?why, "failed to set current folder");
}
command = cosmic::command::future(async move {
Message::ChangeFolder(change_folder(path).await).into()
});
}
}
Category::AddFolder => {
return cosmic::command::future(async {
let dialog_result = file_chooser::open::Dialog::new()
.title(fl!("wallpaper", "folder-dialog"))
.accept_label(fl!("dialog-add"))
.modal(false)
.open_folder()
.await
.map(|response| response.url().to_owned());
let message = Message::AddFolder(Arc::new(dialog_result));
let page_message = crate::pages::Message::DesktopWallpaper(message);
crate::Message::PageMessage(page_message)
});
}
}
self.categories.selected = Some(category);
command
}
/// Changes the output being configured
pub fn change_output(&mut self, entity: segmented_button::Entity) {
self.outputs.activate(entity);
if let Some(name) = self.outputs.data::<OutputName>(entity) {
self.active_output = Some(name.0.clone());
}
self.apply_active_selection();
self.cache_display_image();
}
/// Changes the slideshow wallpaper rotation frequency
pub fn change_rotation_frequency(&mut self, option: usize) {
self.selected_rotation = option;
self.rotation_frequency = match self.selected_rotation {
MINUTES_5 => 300,
MINUTES_10 => 600,
MINUTES_15 => 900,
MINUTES_30 => 1800,
HOUR_1 => 3600,
HOUR_2 => 7200,
_ => 10800,
};
}
/// Updates configuration for wallpaper image.
fn config_wallpaper_entry(&self, output: String, path: PathBuf) -> Option<Entry> {
let scaling_mode = match self.selected_fit {
ZOOM => ScalingMode::Zoom,
FIT => ScalingMode::Fit([0.0, 0.0, 0.0]),
_ => return None,
};
Entry::new(output, wallpaper::Source::Path(path))
.scaling_mode(scaling_mode)
.rotation_frequency(self.rotation_frequency)
.apply(Some)
}
#[must_use]
pub fn display_image_view(&self) -> cosmic::Element<Message> {
match self.cached_display_handle {
Some(ref handle) => cosmic::widget::image(handle.clone())
.width(Length::Fixed(SIMULATED_WIDTH as f32))
.into(),
None => cosmic::widget::Space::new(SIMULATED_WIDTH, SIMULATED_HEIGHT).into(),
}
}
#[allow(clippy::too_many_lines)]
pub fn update(&mut self, message: Message) -> Command<crate::app::Message> {
match message {
Message::DragColorDialog => {
return cosmic::iced_sctk::commands::window::start_drag_window(self.color_dialog)
}
Message::ColorDialogUpdate(update) => {
let cmd = match update {
ColorPickerUpdate::AppliedColor
| ColorPickerUpdate::Cancel
| ColorPickerUpdate::Reset => {
if let Some(color) = self.color_model.get_applied_color() {
let color = wallpaper::Color::Single([color.r, color.g, color.b]);
if let Err(why) = self.config.add_custom_color(color.clone()) {
tracing::error!(?why, "could not set custom color");
}
self.selection.add_custom_color(color);
}
close_window(self.color_dialog)
}
ColorPickerUpdate::ActionFinished => {
let _res = self
.color_model
.update::<crate::app::Message>(ColorPickerUpdate::AppliedColor);
Command::none()
}
_ => Command::none(),
};
return Command::batch(vec![
cmd,
self.color_model.update::<crate::app::Message>(update),
]);
}
Message::ChangeFolder(mut context) => {
// Reassign custom colors and images to the new context.
std::mem::swap(&mut context, &mut self.selection);
for color in context.custom_colors {
self.selection.add_custom_color(color);
}
for image in context.custom_images {
let path = context.paths.remove(image);
let display = context.display_images.remove(image);
let selection = context.selection_handles.remove(image);
if let Some(((display, selection), path)) = display.zip(selection).zip(path) {
self.selection.add_custom_image(path, display, selection);
}
}
self.select_first_wallpaper();
}
Message::ColorAddDialog => {
return get_window(color_picker_window_settings(self.color_dialog));
}
Message::ColorRemove(color) => {
self.selection.remove_custom_color(&color);
if let Err(why) = self.config.remove_custom_color(&color) {
tracing::error!(?why, "could not remove custom color from config");
}
}
Message::ImageAdd(result) => {
let result = result.and_then(Arc::into_inner);
let Some((path, display, selection)) = result else {
tracing::warn!("image not found for provided wallpaper");
return Command::none();
};
if let Err(why) = self.config.add_custom_image(path.clone()) {
tracing::error!(?path, ?why, "could add custom image to config");
}
self.selection.add_custom_image(
path,
display,
ImageHandle::from_pixels(
selection.width(),
selection.height(),
selection.into_vec(),
),
);
// If an update was queued, apply it after all custom images have been added.
if let Some((mut remaining, displays)) = self.update_config.take() {
remaining -= 1;
if remaining == 0 {
self.wallpaper_service_config_update(displays);
self.config_apply();
} else {
self.update_config = Some((remaining, displays));
}
}
}
Message::ImageAddDialog => {
return cosmic::command::future(async {
let dialog_result = file_chooser::open::Dialog::new()
.title(fl!("wallpaper", "image-dialog"))
.accept_label(fl!("dialog-add"))
.modal(false)
.open_file()
.await
.map(|response| response.url().to_owned());
let message = Message::AddFile(Arc::new(dialog_result));
let page_message = crate::pages::Message::DesktopWallpaper(message);
crate::Message::PageMessage(page_message)
});
}
Message::ImageRemove(image) => {
if let Some(path) = self.selection.remove_custom_image(image) {
if let Err(why) = self.config.remove_custom_image(&path) {
tracing::error!(?why, "could not remove custom image from config");
}
}
}
Message::ChangeCategory(category) => {
return self.change_category(category);
}
Message::ColorSelect(color) => {
self.selection.active = Choice::Color(color);
self.cached_display_handle = None;
}
Message::Fit(selection) => {
self.selected_fit = selection;
self.cache_display_image();
}
Message::Output(id) => {
self.change_output(id);
return Command::none();
}
Message::RotationFrequency(pos) => self.change_rotation_frequency(pos),
Message::SameWallpaper(value) => {
self.wallpaper_service_config.same_on_all = value;
self.wallpaper_service_config.backgrounds.clear();
}
Message::Select(id) => {
self.selection.active = Choice::Wallpaper(id);
self.cache_display_image();
}
Message::Slideshow(enable) => {
if enable {
self.selection.active = Choice::Slideshow;
self.cache_display_image();
} else {
if let Some(output) = self.config_output() {
if let Ok(path) = wallpaper::current_image(output) {
if let Some(entity) = self.wallpaper_id_from_path(&path) {
if let Some(entry) =
self.config_wallpaper_entry(output.to_owned(), path)
{
self.select_wallpaper(&entry, entity, false);
self.config_apply();
return Command::none();
}
}
}
}
self.select_first_wallpaper();
}
}
Message::AddFolder(result) => {
let path = match dialog_response(result) {
DialogResponse::Path(path) => path,
DialogResponse::Error(why) => {
tracing::error!(why, "dialog response error");
return Command::none();
}
};
if path.is_dir() {
tracing::info!(?path, "opening new folder");
let _res = self.config.set_current_folder(Some(path.clone()));
// Add the selected folder to the recent folders list.
self.add_recent_folder(path.clone());
// Select that folder in the recent folders list.
for (id, recent) in self.config.recent_folders().iter().enumerate() {
if &path == recent {
self.categories.selected = Some(Category::RecentFolder(id));
}
}
// Load the wallpapers from the selected folder into the view.
return cosmic::command::future(async move {
let message = Message::ChangeFolder(change_folder(path).await);
let page_message = crate::pages::Message::DesktopWallpaper(message);
crate::Message::PageMessage(page_message)
});
}
}
Message::AddFile(result) => {
let path = match dialog_response(result) {
DialogResponse::Path(path) => path,
DialogResponse::Error(why) => {
tracing::error!(why, "dialog response error");
return Command::none();
}
};
if path.is_file() {
tracing::info!(?path, "opening custom image");
// Loads a single custom image and its thumbnail for display in the backgrounds view.
return cosmic::command::future(async move {
let result =
wallpaper::load_image_with_thumbnail(&mut Vec::new(), path).await;
let message = Message::ImageAdd(result.map(Arc::new));
let page_message = crate::pages::Message::DesktopWallpaper(message);
crate::Message::PageMessage(page_message)
});
}
}
Message::Init(update) => {
self.outputs.clear();
self.wallpaper_service_config = update.service_config;
self.selection = update.selection;
// Sync custom colors from config.
for color in self.config.custom_colors() {
self.selection.add_custom_color(color.clone());
}
// Set the default selection if an image was selected.
if let Choice::Wallpaper(_) | Choice::Slideshow = self.selection.active {
let folder = self.config.current_folder();
for (id, recent) in self.config.recent_folders().iter().enumerate() {
if recent == folder {
self.categories.selected = Some(Category::RecentFolder(id));
}
}
}
// These will need to be loaded before applying the service config.
let custom_images = self.config.custom_images();
// Make note of how many images are to be loaded, with the display update for the service config.
self.update_config = Some((custom_images.len(), update.displays));
// Load preview images concurrently for each custom image stored in the on-disk config.
return cosmic::command::batch(custom_images.iter().cloned().map(|path| {
cosmic::command::future(async move {
let result =
wallpaper::load_image_with_thumbnail(&mut Vec::new(), path).await;
Message::ImageAdd(result.map(Arc::new)).into()
})
}));
}
}
self.config_apply();
Command::none()
}
/// Selects the given wallpaper entry.
fn select_wallpaper_entry(&mut self, entry: &wallpaper::Entry) {
match entry.source {
wallpaper::Source::Path(ref path) => {
if path.is_dir() {
self.selection.active = Choice::Slideshow;
self.cache_display_image();
} else if let Some(entity) = self.wallpaper_id_from_path(path) {
self.select_wallpaper(entry, entity, path.is_dir());
}
}
wallpaper::Source::Color(ref color) => {
self.selection.active = Choice::Color(color.clone());
self.categories.selected = Some(Category::Colors);
self.cache_display_image();
}
}
}
/// Selects the first wallpaper from the wallpaper select options.
fn select_first_wallpaper(&mut self) {
let (entity, path) = if let Some(Category::Wallpapers) = self.categories.selected {
match self.selection.custom_images.last() {
Some(entity) => (*entity, &self.selection.paths[*entity]),
None => match self.selection.paths.iter().next() {
Some(value) => value,
None => return,
},
}
} else {
match self.selection.paths.iter().next() {
Some(value) => value,
None => return,
}
};
if let Some(output) = self.config_output() {
let is_slideshow = path.is_dir();
if let Some(entry) = self.config_wallpaper_entry(output.to_owned(), path.clone()) {
self.select_wallpaper(&entry, entity, is_slideshow);
}
}
}
/// Selects the given wallpaper
fn select_wallpaper(
&mut self,
entry: &wallpaper::Entry,
entity: DefaultKey,
is_slideshow: bool,
) {
self.selection.active = if is_slideshow {
Choice::Slideshow
} else {
Choice::Wallpaper(entity)
};
match entry.scaling_mode {
ScalingMode::Zoom | ScalingMode::Stretch => self.selected_fit = ZOOM,
ScalingMode::Fit(_) => self.selected_fit = FIT,
}
match entry.rotation_frequency {
600 => self.selected_rotation = MINUTES_10,
900 => self.selected_rotation = MINUTES_15,
1800 => self.selected_rotation = MINUTES_30,
3600 => self.selected_rotation = HOUR_1,
7200 => self.selected_rotation = HOUR_2,
_ => self.selected_rotation = MINUTES_5,
}
self.rotation_frequency = entry.rotation_frequency;
self.cache_display_image();
}
pub fn show_color_dialog(&self) -> Element<crate::app::Message> {
color_picker_view(
&self.color_model,
Message::DragColorDialog,
Message::ColorDialogUpdate,
)
.map(|m| crate::app::Message::PageMessage(crate::pages::Message::DesktopWallpaper(m)))
}
}
#[derive(Clone, Debug, PartialEq)]
enum Choice {
Wallpaper(DefaultKey),
Color(wallpaper::Color),
Slideshow,
}
impl Default for Choice {
fn default() -> Self {
Self::Wallpaper(DefaultKey::default())
}
}
#[derive(Clone, Debug, Default)]
pub struct Context {
active: Choice,
custom_images: Vec<DefaultKey>,
custom_colors: Vec<wallpaper::Color>,
paths: SlotMap<DefaultKey, PathBuf>,
is_custom: SecondaryMap<DefaultKey, ()>,
display_images: SecondaryMap<DefaultKey, image::RgbaImage>,
selection_handles: SecondaryMap<DefaultKey, ImageHandle>,
}
impl Context {