This repository was archived by the owner on Nov 21, 2025. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathlaunch.rs
More file actions
2650 lines (2413 loc) · 132 KB
/
launch.rs
File metadata and controls
2650 lines (2413 loc) · 132 KB
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
use crate::{
entities::{
RemotesColumn, RemotesEntity, RemotesModel, SyncDirsActiveModel, SyncDirsColumn,
SyncDirsEntity, SyncDirsModel, SyncItemsActiveModel, SyncItemsColumn, SyncItemsEntity,
},
gtk_util,
login::{self},
migrations::{Migrator, MigratorTrait},
rclone::{self, RcloneListFilter},
traits::prelude::*,
util,
};
use adw::{
glib,
gtk::{
pango::EllipsizeMode, Align, Box, Button, ButtonsType, Entry, EntryCompletion,
FileChooserDialog, FileFilter, GestureClick, Image, Inhibit, Label, ListBox, ListBoxRow,
ListStore, MessageDialog, Orientation, PolicyType, Popover, PositionType, ResponseType,
ScrolledWindow, SelectionMode, Separator, Spinner, Stack, StackSidebar,
StackTransitionType, Widget,
},
prelude::*,
Application, ApplicationWindow, Bin, EntryRow, HeaderBar, Leaflet, LeafletTransitionType,
WindowTitle,
};
use file_lock::{FileLock, FileOptions};
use indexmap::IndexMap;
use sea_orm::{entity::prelude::*, ActiveValue, Database, DatabaseConnection};
use std::{
boxed,
cell::RefCell,
collections::HashMap,
fs::{self, File, OpenOptions},
io::Write,
path::{Path, PathBuf},
rc::Rc,
sync::{Arc, Mutex},
thread,
time::{Duration, SystemTime},
};
// The location for file ignore lists.
static FILE_IGNORE_NAME: &str = ".sync-exclude.lst";
// A [`HashMap`] containing the status and progress for a directory sync label.
// This is done here because if we try to get the child from a `Box` or
// something we just get a generic gtk `Widget`, which we can't use.
type DirectoryMap = Rc<RefCell<IndexMap<String, IndexMap<(String, String), SyncDir>>>>;
// A [`Vec`] for a deletion queue to remove remotes.
type RemoteDeletionQueue = Rc<RefCell<Vec<String>>>;
// A [`Vec`] for a deletion queue to stop syncing directories - we store this in
// a queue so we can stop syncing directories safely while syncs may still be
// occurring.
type SyncDirDeletionQueue = Rc<RefCell<Vec<(String, String, String)>>>;
/// The errors that can be found while syncing.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum SyncError {
/// A general catch-all error. A tuple of the path the error happened at,
/// and the error message itself.
General(String, String),
/// An error when both the local and remote file are more current than at
/// the last sync. A tuple of the local and remote file.
BothMoreCurrent(String, String),
}
impl SyncError {
fn generate_ui(&self) -> Box {
let error_container = Box::builder()
.orientation(Orientation::Vertical)
.spacing(2)
.margin_top(6)
.margin_end(6)
.margin_bottom(6)
.margin_start(6)
.build();
match self {
SyncError::General(file_path, err) => {
let err_label = Label::builder()
.label(file_path)
.halign(Align::Start)
.ellipsize(EllipsizeMode::End)
.build();
let file_label = Label::builder()
.label(err)
.halign(Align::Start)
.ellipsize(EllipsizeMode::End)
.css_classes(vec!["caption".to_string(), "dim-label".to_string()])
.build();
error_container.append(&err_label);
error_container.append(&file_label);
}
SyncError::BothMoreCurrent(local_path, remote_path) => {
let err_msg = tr::tr!(
"Both '{}' and '{}' are more recent than at last sync.",
local_path,
remote_path
);
let err_label = Label::builder()
.label(&err_msg)
.halign(Align::Start)
.ellipsize(EllipsizeMode::End)
.build();
error_container.append(&err_label);
}
}
error_container
}
}
/// A struct representing all the data that belongs to a sync directory.
struct SyncDir {
/// The parent stack for [`Self::container`], this contains all the UI
/// listing for sync directories.
parent_list: ListBox,
/// The Box containing things like the progress icon, status text, etc.
container: ListBoxRow,
/// The container for the progress icon.
status_icon: Bin,
/// The label for reporting errors in the current sync status.
error_status_text: Label,
/// The label for reporting the current sync status (things like 'Awaiting
/// sync check...').
status_text: Label,
/// The error list in the UI.
error_list: ListBox,
/// The list of error items, as generated by 'SyncError::generate_ui' above.
error_items: HashMap<SyncError, Box>,
/// A closure to update the UI error listing.
update_error_ui: boxed::Box<dyn Fn()>,
}
lazy_static::lazy_static! {
// A [`Mutex`] to keep track of any recorded close requests.
pub static ref CLOSE_REQUEST: Arc<Mutex<bool>> = Arc::new(Mutex::new(false));
// A [`Mutex`] to keep track of open requests from the tray icon.
pub static ref OPEN_REQUEST: Arc<Mutex<bool>> = Arc::new(Mutex::new(false));
}
/// Get an icon for use as the status icon for directory syncs.
fn get_image(icon_name: &str) -> Image {
Image::builder()
.icon_name(icon_name)
.width_request(10)
.height_request(10)
.build()
}
pub fn launch(app: &Application, background: bool) {
// Create the configuration directory if it doesn't exist.
let config_path = util::get_config_dir();
if !config_path.exists()
&& let Err(err) = fs::create_dir_all(&config_path)
{
gtk_util::show_error(
&tr::tr!("Unable to create Celeste's config directory [{}].", err),
None,
);
return;
}
// Create the database file if it doesn't exist.
let mut db_path = config_path;
db_path.push("celeste.db");
if !db_path.exists() {
if let Err(err) = fs::File::create(&db_path) {
gtk_util::show_error(
&tr::tr!("Unable to create Celeste's database file [{}].", err),
None,
);
return;
}
};
// Connect to the database.
let db = util::await_future(Database::connect(format!("sqlite://{}", db_path.display())));
if let Err(err) = &db {
gtk_util::show_error(&tr::tr!("Unable to connect to database [{}].", err), None);
return;
};
let db = db.unwrap();
// Run migrations.
if let Err(err) = util::await_future(Migrator::up(&db, None)) {
gtk_util::show_error(
&tr::tr!("Unable to run database migrations [{}]", err),
None,
);
return;
}
// Get our remotes.
let mut remotes = util::await_future(RemotesEntity::find().all(&db)).unwrap();
if remotes.is_empty() {
if login::login(app, &db).is_none() {
return;
}
remotes = util::await_future(RemotesEntity::find().all(&db)).unwrap();
}
// Create the main UI.
let window = ApplicationWindow::builder()
.application(app)
.title(&util::get_title!("Servers"))
.build();
window.add_css_class("celeste-global-padding");
let stack_sidebar = StackSidebar::builder()
.width_request(150)
.height_request(500)
.vexpand_set(true)
.vexpand(true)
.build();
let stack = Stack::new();
stack_sidebar.set_stack(&stack);
let directory_map: DirectoryMap = Rc::new(RefCell::new(IndexMap::new()));
// Store any remote deletions (values of the remote names) in a queue so they
// can be processed when syncing is at a good point of stopping.
let remote_deletion_queue: RemoteDeletionQueue = Rc::new(RefCell::new(vec![]));
// Store any sync deletions (the remote + local directory + remote directory) in
// a queue so they can be processed when syncing is at a good point of stopping.
let sync_dir_deletion_queue: SyncDirDeletionQueue = Rc::new(RefCell::new(vec![]));
// Add servers.
let gen_remote_window = glib::clone!(@strong window, @strong remote_deletion_queue, @strong sync_dir_deletion_queue, @strong directory_map, @strong db => move |remote: RemotesModel| {
let remote_name = remote.name;
// The stack containing the window of sync status', as well as extra information for each sync pair.
let sections = Stack::builder()
.transition_type(StackTransitionType::OverLeft)
.transition_duration(500)
.build();
// The sections of this stack's window.
let page = Box::builder()
.orientation(Orientation::Vertical)
.vexpand_set(true)
.vexpand(true)
.css_classes(vec!["background".to_string()])
.build();
// The list of directories to sync.
let sync_dirs = ListBox::builder()
.selection_mode(SelectionMode::None)
.css_classes(vec!["boxed-list".to_string()])
.build();
// Add a directory to the stack.
let add_dir = glib::clone!(@weak window, @weak sections, @weak page, @weak sync_dirs, @strong remote_name, @strong directory_map, @strong sync_dir_deletion_queue => move |
server_name: String,
local_path: String,
remote_path: String,
| {
let server_name_owned = server_name.to_string();
let formatted_local_path = util::fmt_home(&local_path);
let formatted_remote_path = format!("/{remote_path}");
// The sync status row.
let sync_status_sections = Box::builder().orientation(Orientation::Vertical).margin_start(10).margin_end(10).build();
let row_sections = Box::builder().orientation(Orientation::Horizontal).build();
let status_container = Bin::builder().width_request(30).build();
status_container.set_child(Some(&get_image("content-loading-symbolic")));
row_sections.append(&status_container);
let text_sections = Box::builder().orientation(Orientation::Vertical).valign(Align::Center).margin_start(10).margin_end(10).margin_top(5).margin_bottom(5).build();
let title = {
let sections = Box::builder().orientation(Orientation::Horizontal).build();
let local_label = Label::builder().label(&formatted_local_path).ellipsize(EllipsizeMode::Start).build();
let remote_label = Label::builder().label(&formatted_remote_path).ellipsize(EllipsizeMode::Start).build();
let arrow = Image::builder().icon_name("go-next-symbolic").build();
sections.append(&local_label);
sections.append(&arrow);
sections.append(&remote_label);
sections
};
let text_status_container = Box::builder().orientation(Orientation::Horizontal).build();
let error_status = Label::builder()
.halign(Align::Start)
.css_classes(vec!["caption".to_string(), "dim-label".to_string(), "error".to_string()])
.build();
let status = Label::builder()
.label(&tr::tr!("Awaiting sync check..."))
.halign(Align::Start)
.css_classes(vec!["caption".to_string(), "dim-label".to_string()])
.ellipsize(EllipsizeMode::End)
.build();
text_status_container.append(&error_status);
text_status_container.append(&status);
text_sections.append(&title);
text_sections.append(&text_status_container);
row_sections.append(&text_sections);
let more_info_button = Image::builder()
.icon_name("go-next-symbolic")
.halign(Align::End)
.hexpand_set(true)
.hexpand(true)
.build();
row_sections.append(&more_info_button);
sync_status_sections.append(&row_sections);
// The more info page.
let more_info_page = Box::builder()
.orientation(Orientation::Vertical)
.vexpand_set(true)
.vexpand(true)
.css_classes(vec!["background".to_string()])
.build();
let more_info_header_buttons = Box::builder()
.orientation(Orientation::Horizontal)
.margin_bottom(10)
.build();
// The errors section.
let more_info_errors_label = Label::builder()
.label(&tr::tr!("Sync Errors"))
.halign(Align::Start)
.hexpand_set(true)
.hexpand(true)
.valign(Align::End)
.visible(false)
.margin_bottom(10)
.css_classes(vec!["heading".to_string()])
.build();
let more_info_errors_list = ListBox::builder().selection_mode(SelectionMode::None).css_classes(vec!["boxed-list".to_string()]).margin_top(5).margin_end(5).margin_bottom(5).margin_start(5).build();
let more_info_errors_list_scrolled = ScrolledWindow::builder().child(&more_info_errors_list).valign(Align::Start).visible(false).build();
// The exclusion list.
let more_info_exclusions_header = Box::builder().orientation(Orientation::Horizontal).margin_top(20).margin_bottom(10).build();
let more_info_exclusions_label = Label::builder()
.label(&tr::tr!("File/Folder Exclusions"))
.halign(Align::Start)
.hexpand_set(true)
.hexpand(true)
.valign(Align::End)
.css_classes(vec!["heading".to_string()])
.build();
let more_info_exclusions_add_button = Button::builder()
.icon_name("list-add-symbolic")
.halign(Align::End)
.build();
more_info_exclusions_header.append(&more_info_exclusions_label);
more_info_exclusions_header.append(&more_info_exclusions_add_button);
let more_info_exclusions_list = ListBox::builder().selection_mode(SelectionMode::None).css_classes(vec!["boxed-list".to_string()]).valign(Align::Start).margin_top(5).margin_end(5).margin_bottom(5).margin_start(5).build();
let more_info_exclusions_list_scrolled = ScrolledWindow::builder().child(&more_info_exclusions_list).vexpand_set(true).vexpand(true).build();
// Read the ignore file to see if anything exists in it so far.
let file_ignore_path_string = format!("{local_path}/{FILE_IGNORE_NAME}");
let get_lock = glib::clone!(@strong file_ignore_path_string => move || {
// This will return an [`Err`] if the parent folder doesn't exist, so handle that case instead of `.unwrap`ing it.
FileLock::lock(&file_ignore_path_string, true, FileOptions::new().create(true).read(true).write(true).append(false))
});
let file_ignore_content = if get_lock().is_ok() {
Some(fs::read_to_string(&file_ignore_path_string).unwrap())
} else {
None
};
let ignore_rules: Rc<RefCell<IndexMap<EntryRow, String>>> = Rc::new(RefCell::new(IndexMap::new()));
let write_file = glib::clone!(@strong file_ignore_path_string, @strong ignore_rules, @strong get_lock => move || {
let ptr = ignore_rules.get_ref();
let strings: Vec<String> = ptr.values().map(|item| item.to_owned()).collect();
// First truncate the file.
OpenOptions::new().write(true).truncate(true).open(&file_ignore_path_string).unwrap();
// And then write to it.
if let Ok(mut lock) = get_lock() {
lock.file.write_all(strings.join("\n").as_bytes()).unwrap()
};
});
let gen_ignore_row = glib::clone!(@strong get_lock, @strong write_file, @strong ignore_rules, @strong more_info_exclusions_list => move |content: Option<String>| {
let row = EntryRow::builder().css_classes(vec!["celeste-no-title".to_string()]).build();
if let Some(text) = content {
row.set_text(&text);
} else {
row.set_show_apply_button(true);
}
let remove_button = Button::builder().icon_name("list-remove-symbolic").valign(Align::Center).css_classes(vec!["flat".to_string()]).build();
row.connect_apply(glib::clone!(@strong get_lock, @strong write_file, @strong ignore_rules => move |row| {
// Make sure our ignore rules has the latest string for this item.
let mut ptr = ignore_rules.get_mut_ref();
ptr.insert(row.clone(), row.text().to_string());
drop(ptr);
// Write out all the current ignore rules to the file.
write_file();
}));
remove_button.connect_clicked(glib::clone!(@strong get_lock, @strong write_file, @strong ignore_rules, @weak row, @weak more_info_exclusions_list => move |_| {
row.set_sensitive(false);
more_info_exclusions_list.remove(&row);
// This returns [`None`] if the item hasn't been added via `row.connect_apply` above yet.
let mut ptr = ignore_rules.get_mut_ref();
if ptr.remove(&row).is_none() {
return;
}
drop(ptr);
write_file();
}));
row.connect_changed(|row| {
let text = row.text().to_string();
// If this row is valid, show the apply button. Otherwise, hide it.
if let Err(err) = glob::Pattern::new(&text) {
row.set_show_apply_button(false);
row.add_css_class("error");
row.set_tooltip_text(Some(&err.to_string()));
} else {
row.remove_css_class("error");
row.set_tooltip_text(None);
row.set_show_apply_button(true);
}
});
row.add_suffix(&remove_button);
row
});
more_info_exclusions_add_button.connect_clicked(glib::clone!(@weak more_info_exclusions_list, @strong gen_ignore_row => move |_| {
more_info_exclusions_list.append(&gen_ignore_row(None));
}));
if let Some(ignore_content) = file_ignore_content {
for line in ignore_content.lines() {
let line_owned = line.to_owned();
let row = gen_ignore_row(Some(line_owned.clone()));
more_info_exclusions_list.append(&row);
ignore_rules.get_mut_ref().insert(row, line_owned);
}
}
// The back button to go back to the main page.
let more_info_back_button = Button::builder()
.icon_name("go-previous-symbolic")
.halign(Align::Start)
.hexpand_set(true)
.hexpand(true)
.build();
more_info_back_button.connect_clicked(glib::clone!(@weak sections => move |_| {
// Temporarily reverse the transition direction so it looks like we're going back a page.
let previous_transition_type = sections.transition_type();
sections.set_transition_type(StackTransitionType::OverRight);
sections.set_visible_child_name("main");
sections.set_transition_type(previous_transition_type);
}));
let more_info_delete_button = Button::builder()
.icon_name("user-trash-symbolic")
.has_tooltip(true)
.tooltip_text(&tr::tr!("Stop syncing this directory"))
.halign(Align::End)
.build();
// Store the pages element's in a vector. When the delete button is pressed and we confirm a deletion, we want the entire page to not be sensitive except for the back button, and we do that by only making the back button sensitive.
let more_info_widgets: Vec<Widget> = vec![
more_info_errors_label.clone().into(),
more_info_errors_list_scrolled.clone().into(),
more_info_exclusions_header.clone().into(),
more_info_exclusions_list_scrolled.clone().into(),
more_info_back_button.clone().into(),
more_info_delete_button.clone().into(),
];
more_info_delete_button.connect_clicked(glib::clone!(@strong sync_dir_deletion_queue, @strong server_name, @strong local_path, @strong remote_path, @strong formatted_local_path, @strong formatted_remote_path, @weak sections, @weak more_info_back_button, @weak more_info_delete_button, @strong more_info_widgets => move |_| {
more_info_widgets.iter().for_each(|item| item.set_sensitive(false));
let dialog = MessageDialog::builder()
.text(
&tr::tr!("Are you sure you want to stop syncing '{}' to '{}'?", formatted_local_path, formatted_remote_path)
)
.buttons(ButtonsType::YesNo)
.build();
dialog.connect_response(glib::clone!(@strong sync_dir_deletion_queue, @strong server_name, @strong local_path, @strong remote_path, @weak sections, @weak more_info_back_button, @weak more_info_delete_button, @strong more_info_widgets => move |dialog, resp| {
match resp {
ResponseType::Yes => {
let data = (server_name.clone(), local_path.clone(), remote_path.clone());
sync_dir_deletion_queue.get_mut_ref().push(data);
more_info_delete_button.set_tooltip_text(Some(&tr::tr!("This directory is currently being processed to no longer be synced.")));
more_info_back_button.set_sensitive(true);
dialog.close();
},
ResponseType::No => {
dialog.close();
more_info_widgets.iter().for_each(|item| item.set_sensitive(true));
},
_ => ()
}
}));
dialog.show();
}));
more_info_header_buttons.append(&more_info_back_button);
more_info_header_buttons.append(&more_info_delete_button);
more_info_page.append(&more_info_header_buttons);
more_info_page.append(&more_info_errors_label);
more_info_page.append(&more_info_errors_list_scrolled);
more_info_page.append(&more_info_exclusions_header);
more_info_page.append(&more_info_exclusions_list_scrolled);
// Show the window upon click.
let stack_child_name = format!("{local_path}/{remote_path}");
let gesture = GestureClick::new();
let update_error_list = glib::clone!(@weak error_status, @weak more_info_errors_list_scrolled => move || {
// Ensure the errors section is set up correctly.
let num_errors = error_status.text().as_str().split_whitespace().next().unwrap_or("0").parse::<i32>().unwrap();
// Hide the section if we have no errors.
if num_errors == 0 {
error_status.set_visible(false);
more_info_errors_list_scrolled.set_visible(false);
} else if num_errors <= 3 {
error_status.set_visible(true);
more_info_errors_list_scrolled.set_visible(true);
more_info_errors_list_scrolled.set_vscrollbar_policy(PolicyType::Never);
more_info_errors_list_scrolled.set_min_content_height(-1);
} else {
error_status.set_visible(true);
more_info_errors_list_scrolled.set_visible(true);
more_info_errors_list_scrolled.set_vscrollbar_policy(PolicyType::Always);
more_info_errors_list_scrolled.set_min_content_height(150 /* 50 px * 3 entries - seems to be the height of a ListBoxRow in Libadwaita */);
}
});
gesture.connect_released(glib::clone!(@weak sections, @strong stack_child_name, @strong update_error_list => move |_, _, _, _| {
update_error_list();
sections.set_visible_child_name(&stack_child_name);
}));
sync_status_sections.add_controller(&gesture);
// Add the items to the directory map.
let sync_status_sections_container = ListBoxRow::builder().child(&sync_status_sections).build();
let mut dmap = directory_map.borrow_mut();
if !dmap.contains_key(&server_name_owned) {
dmap.insert(server_name_owned, IndexMap::new());
}
dmap.get_mut(&server_name).unwrap().insert(
(local_path, remote_path),
SyncDir {
parent_list: sync_dirs.clone(),
container: sync_status_sections_container.clone(),
status_icon: status_container,
error_status_text: error_status,
status_text: status,
error_list: more_info_errors_list,
error_items: HashMap::new(),
update_error_ui: boxed::Box::new(update_error_list)
}
);
sync_dirs.append(&sync_status_sections_container);
sections.add_named(&more_info_page, Some(&stack_child_name));
});
// Create the remote in the database if it doesn't current exist.
let db_remote = util::await_future(
RemotesEntity::find()
.filter(RemotesColumn::Name.eq(remote_name.clone()))
.one(&db),
)
.unwrap().unwrap();
// The directory header, directory addition button, and remote deletion button.
{
let section = Box::builder().orientation(Orientation::Horizontal).build();
let label = Label::builder()
.label(&tr::tr!("Directories"))
.halign(Align::Start)
.hexpand(true)
.hexpand_set(true)
.valign(Align::End)
.margin_end(10)
.css_classes(vec!["heading".to_string()])
.build();
let new_folder_button = Button::builder()
.icon_name("folder-new")
.halign(Align::End)
.valign(Align::Start)
.build();
new_folder_button.connect_clicked(glib::clone!(@weak window, @weak sections, @weak page, @strong remote_name, @strong sync_dirs, @strong db, @strong directory_map, @strong db_remote, @strong add_dir => @default-panic, move |_| {
window.set_sensitive(false);
let folder_window = ApplicationWindow::builder()
.title(&util::get_title!("Remote Folder Picker"))
.build();
folder_window.add_css_class("celeste-global-padding");
let folder_sections = Box::builder().orientation(Orientation::Vertical).build();
folder_sections.append(&HeaderBar::new());
// Get the local folder to sync with.
let local_label = Label::builder().label(&tr::tr!("Local folder:")).halign(Align::Start).css_classes(vec!["heading".to_string()]).build();
let local_entry = Entry::builder()
.secondary_icon_activatable(true)
.secondary_icon_name("folder-symbolic")
.secondary_icon_sensitive(true)
.build();
local_entry.connect_icon_press(glib::clone!(@weak folder_window, @weak local_label => move |local_entry, _| {
folder_window.set_sensitive(false);
let filter = FileFilter::new();
filter.add_mime_type("inode/directory");
let dialog = FileChooserDialog::builder()
.title(&util::get_title!("Local Folder Picker"))
.select_multiple(false)
.create_folders(true)
.filter(&filter)
.build();
let cancel_button = Button::with_label(&tr::tr!("Cancel"));
let ok_button = Button::with_label(&tr::tr!("Ok"));
dialog.add_action_widget(&cancel_button, ResponseType::Cancel);
dialog.add_action_widget(&ok_button, ResponseType::Ok);
dialog.connect_close_request(glib::clone!(@strong folder_window => move |_| {
folder_window.set_sensitive(true);
Inhibit(false)
}));
cancel_button.connect_clicked(glib::clone!(@weak folder_window, @weak dialog => move |_| {
dialog.close();
}));
ok_button.connect_clicked(glib::clone!(@weak folder_window, @weak local_entry, @weak dialog => move |_| {
local_entry.set_text(&dialog.file().unwrap().path().unwrap().into_os_string().into_string().unwrap());
dialog.close();
}));
dialog.show();
}));
// Get the remote folder to sync with, and add it.
// The entry completion code is largely inspired by https://github.com/gtk-rs/gtk4-rs/blob/master/examples/entry_completion/main.rs. I honestly have no clue what half the code for that is doing, I just know the current code is working well enough, and it can be fixed later if it breaks.
let remote_label = Label::builder().label(&tr::tr!("Remote folder:")).halign(Align::Start).css_classes(vec!["heading".to_string()]).build();
let entry_completion = EntryCompletion::new();
let store = ListStore::new(&[glib::Type::STRING]);
// The path that this store is currently valid on, excluding everything after the
// last `/` in the UI. We use this to detect when we need to obtain the list of
// directories from the remote again. The [`Vec`] of [`String`]s is a vector of
// rightmost dir items (i.e. it would contain `bar` instead of `/foo/bar`) because
// of how `update_options` is called below, so checks need to be done to make sure
// that the currently typed in path is the same as the one in the tuple's [`Path`]
// element.
let store_path: Rc<RefCell<(PathBuf, Vec<String>)>> = Rc::new(RefCell::new((Path::new("").to_owned(), vec![])));
entry_completion.set_text_column(0);
entry_completion.set_popup_completion(true);
entry_completion.set_model(Some(&store));
let remote_entry = Entry::builder().completion(&entry_completion).build();
remote_entry.insert_text("/", &mut -1);
// Get the current path, up to the last '/'.
let get_current_path = glib::clone!(@weak remote_entry => @default-panic, move || {
let text = remote_entry.text().to_string();
if text.ends_with('/') {
Path::new(&text).to_path_buf()
} else {
Path::new(&text).parent().unwrap_or_else(|| Path::new("")).to_path_buf()
}
});
// Update the UI completions against the list of stored directories.
let update_completions = glib::clone!(@weak entry_completion, @strong store, @weak remote_entry, @weak store, @strong store_path, @strong get_current_path => move || {
// Get the current specified directory.
let current_item_text = remote_entry.text();
let current_item = Path::new(current_item_text.as_str()).file_name().map(|path| path.to_str().unwrap()).unwrap_or("");
// Clear the current list of completions.
store.clear();
// See if any of the currently stored matches start with the same characters as
// our path, and if they do, append them to the valid completions list.
for item in &store_path.get_ref().1 {
if item.starts_with(current_item) {
store.set(&store.append(), &[(0, item)]);
}
}
});
// The entry completion logic.
entry_completion.set_match_func(glib::clone!(@weak remote_entry => @default-panic, move |entry_completion, _entry_str, tree_iter| {
let tree_model = entry_completion.model().unwrap();
let text_column = entry_completion.text_column();
let text_value = match tree_model.get_value(tree_iter, text_column).get::<String>() {
// Not quite sure when this could fail, but it does sometimes, so return early when that's the case.
Ok(value) => value,
Err(_) => return false
};
// The last component of the directory specified by the user.
let remote_entry_text = remote_entry.text().to_string();
let entry_final_path_item = Path::new(&remote_entry_text).file_name().map(|path| path.to_str().unwrap()).unwrap_or("");
text_value.starts_with(entry_final_path_item)
}));
entry_completion.connect_match_selected(glib::clone!(@weak remote_entry => @default-panic, move |_, model, iter| {
let selected_entry = model.get::<String>(iter, 0);
// The current text up to the last slash (i.e. 'hi' in '/foo/bar/hi').
let up_to_slash_text = 'slash: {
let current_text = remote_entry.text().to_string();
// If the current text doesn't contain a slash, just return all the currently entered text.
if !current_text.contains('/') {
break 'slash current_text
}
// Otherwise return the text up to the last slash.
break 'slash match current_text.rsplit_once('/') {
Some((_, string)) => string.to_string(),
None => String::new()
}
};
// Get the text that we need to append.
let mut to_append = selected_entry.strip_prefix(&up_to_slash_text).unwrap().to_string();
to_append.push('/');
// Append the text, and set the position to the end of the entry box.
remote_entry.insert_text(&to_append, &mut -1);
remote_entry.set_position(-1);
// Stop the default matching behavior since we handled it here.
Inhibit(true)
}));
// Update the stored list of autocompletions to the parent of those of the currently typed in directory.
let update_options = glib::clone!(@strong remote_name, @strong store_path, @weak remote_entry, @strong update_completions, @strong get_current_path => move || {
let current_path = get_current_path();
let current_path_string = current_path.as_os_str().to_owned().into_string().unwrap();
let items = if let Ok(items) = rclone::sync::list(&remote_name, ¤t_path_string, false, RcloneListFilter::Dirs) {
items.into_iter().map(|item| item.name).collect()
} else {
vec![]
};
// If the current parent path is still the same (i.e. after the file listing above has finished, which may have taken a bit), then update the completions to reflect the items we got.
let mut store_path_ref = store_path.get_mut_ref();
if store_path_ref.0 == current_path {
store_path_ref.1 = items;
// Drop `store_path_ref` so `update_completions` can get its own reference.
drop(store_path_ref);
update_completions();
}
});
remote_entry.connect_cursor_position_notify(glib::clone!(@strong remote_name, @weak store_path, @strong update_completions, @strong update_options, @strong get_current_path => move |_| {
// For some reason we have to clone the closure to pass the borrow checker, even though we clone it via the 'glib::clone!' above. Not sure why yet.
let update_options = update_options.clone();
let current_path = get_current_path();
let mut store_path_ref = store_path.get_mut_ref();
if store_path_ref.0 == current_path {
// Drop our ref to `store_path_ref` so `update_completions` can get it's own.
drop(store_path_ref);
update_completions();
} else {
store_path_ref.0 = current_path;
// Drop our ref to `store_path_ref` so `update_options` can get it's own.
drop(store_path_ref);
update_options();
}
}));
folder_sections.append(&local_label);
folder_sections.append(&local_entry);
folder_sections.append(&Separator::builder().orientation(Orientation::Vertical).css_classes(vec!["spacer".to_string()]).build());
folder_sections.append(&remote_label);
folder_sections.append(&remote_entry);
let confirm_box = Box::builder().orientation(Orientation::Horizontal).spacing(10).halign(Align::End).build();
let cancel_button = Button::with_label(&tr::tr!("Cancel"));
let ok_button = Button::with_label(&tr::tr!("Ok"));
confirm_box.append(&cancel_button);
confirm_box.append(&ok_button);
folder_sections.append(&Separator::builder().orientation(Orientation::Vertical).css_classes(vec!["spacer".to_string()]).build());
folder_sections.append(&confirm_box);
// If either entry is empty, don't allow the button to be clicked.
// Also initialize the button as non-clickable.
ok_button.set_sensitive(false);
local_entry.connect_changed(glib::clone!(@weak ok_button, @weak remote_entry => move |local_entry| {
if local_entry.to_string().is_empty() || remote_entry.to_string().is_empty() {
ok_button.set_sensitive(false);
} else {
ok_button.set_sensitive(true);
}
}));
remote_entry.connect_changed(glib::clone!(@weak ok_button, @weak local_entry => move |remote_entry| {
if local_entry.to_string().is_empty() || remote_entry.to_string().is_empty() {
ok_button.set_sensitive(false);
} else {
ok_button.set_sensitive(true);
}
}));
folder_window.connect_close_request(glib::clone!(@strong window => move |_| {
window.set_sensitive(true);
Inhibit(false)
}));
cancel_button.connect_clicked(glib::clone!(@strong window, @weak folder_window => move |_| {
folder_window.close();
window.set_sensitive(true);
}));
ok_button.connect_clicked(glib::clone!(@strong window, @weak sections, @weak folder_window, @weak sync_dirs, @weak local_entry, @weak remote_entry, @strong db_remote, @strong db, @weak directory_map, @strong remote_name, @strong add_dir => move |_| {
folder_window.set_sensitive(false);
// The local path needs to start with a slash, but not end with one. The remote
// needs to not start or end with a slash.
let local_text = "/".to_string() + &util::strip_slashes(local_entry.text().as_str());
let remote_text = util::strip_slashes(remote_entry.text().as_str());
let local_path = Path::new(&local_text);
match rclone::sync::stat(&remote_name, &remote_text) {
Ok(path) => {
if path.is_none() {
gtk_util::show_error(&tr::tr!("The specified remote directory doesn't exist"), None);
folder_window.set_sensitive(true);
return;
} else {
path
}
},
Err(err) => {
gtk_util::show_error(&tr::tr!("Failed to check if the specified remote directory exists"), Some(&err.error));
folder_window.set_sensitive(true);
return;
}
};
let sync_dir = util::await_future(
SyncDirsEntity::find().filter(SyncDirsColumn::LocalPath.eq(local_text.clone())).filter(SyncDirsColumn::RemotePath.eq(remote_text.clone())).one(&db)
).unwrap();
if sync_dir.is_some() {
gtk_util::show_error(&tr::tr!("The specified directory pair is already being synced"), None);
folder_window.set_sensitive(true);
} else if !local_path.exists() {
gtk_util::show_error(&tr::tr!("The specified local directory doesn't exist"), None);
folder_window.set_sensitive(true);
} else if !local_path.is_dir() {
gtk_util::show_error(&tr::tr!("The specified local path isn't a directory"), None);
folder_window.set_sensitive(true);
} else if !local_path.is_absolute() {
gtk_util::show_error(&tr::tr!("The specified local directory needs to be an absolute path"), None);
folder_window.set_sensitive(true);
} else {
util::await_future(
SyncDirsActiveModel {
remote_id: ActiveValue::Set(db_remote.id),
local_path: ActiveValue::Set(local_text.clone()),
remote_path: ActiveValue::Set(remote_text.clone()),
..Default::default()
}.insert(&db)
).unwrap();
add_dir(remote_name.clone(), local_text, remote_text);
folder_window.close();
}
}));
folder_window.set_content(Some(&folder_sections));
folder_window.show();
}));
let delete_remote_button = Button::builder()
.icon_name("user-trash-symbolic")
.halign(Align::End)
.valign(Align::Start)
.margin_start(10)
.build();
delete_remote_button.connect_clicked(glib::clone!(@strong remote_deletion_queue, @strong page, @strong remote_name => move |delete_remote_button| {
page.set_sensitive(false);
let dialog = MessageDialog::builder()
.text(&tr::tr!("Are you sure you want to delete this remote?"))
.secondary_text(&tr::tr!("All the directories associated with this remote will also stop syncing."))
.buttons(ButtonsType::YesNo)
.build();
dialog.connect_response(glib::clone!(@strong remote_deletion_queue, @strong page, @strong remote_name, @weak delete_remote_button => move |dialog, resp| {
match resp {
ResponseType::Yes => {
remote_deletion_queue.get_mut_ref().push(remote_name.clone());
dialog.close();
},
ResponseType::No => {
dialog.close();
page.set_sensitive(true);
}
_ => ()
}
}));
dialog.show();
}));
section.append(&label);
section.append(&new_folder_button);
section.append(&delete_remote_button);
page.append(§ion);
}
// The directory listing.
{
// Get the currently present directories.
let dirs = util::await_future(
SyncDirsEntity::find()
.filter(SyncDirsColumn::RemoteId.eq(db_remote.id))
.all(&db),
)
.unwrap();
// Create the entry for each directory.
for dir in dirs {
add_dir(
db_remote.name.clone(),
dir.local_path.clone(),
dir.remote_path.clone(),
);
}
}
page.append(>k_util::separator());
page.append(&sync_dirs);
sections.add_named(&page, Some("main"));
sections.set_visible_child_name("main");
sections
});
for remote in remotes {
let window = gen_remote_window(remote.clone());
stack.add_titled(&window, Some(&remote.name), &remote.name);
}
// Set up the main sections.
let sections = Leaflet::builder()
.transition_type(LeafletTransitionType::Slide)
.css_classes(vec!["main".to_string()])
.build();
let sidebar_box = Box::builder()
.orientation(Orientation::Vertical)
.css_classes(vec!["sidebar".to_string()])
.build();
let sidebar_header = HeaderBar::builder().decoration_layout("").build();
let sidebar_add_server_button = Button::from_icon_name("list-add-symbolic");
sidebar_add_server_button.connect_clicked(
glib::clone!(@weak app, @weak window, @weak stack, @strong gen_remote_window, @strong db => move |_| {
window.set_sensitive(false);
if let Some(remote) = login::login(&app, &db) {
let window = gen_remote_window(remote.clone());
stack.add_titled(&window, Some(&remote.name), &remote.name);
}
window.set_sensitive(true);
}),
);
let sidebar_menu_button = Button::from_icon_name("open-menu-symbolic");
let sidebar_menu_popover_sections = Box::new(Orientation::Vertical, 5);
let sidebar_menu_popover = Popover::builder()
.child(&sidebar_menu_popover_sections)
.position(PositionType::Bottom)
.build();
let sidebar_menu_about_button = Button::builder()
.label("About")
.css_classes(vec!["flat".to_string()])
.build();
sidebar_menu_about_button.connect_clicked(
glib::clone!(@weak app, @weak sidebar_menu_popover => move |_| {
sidebar_menu_popover.popdown();
crate::about::about_window(&app);
}),
);
let sidebar_menu_quit_button = Button::builder()
.label("Quit")
.css_classes(vec!["flat".to_string()])
.build();
sidebar_menu_quit_button.connect_clicked(glib::clone!(@weak sidebar_menu_popover => move |_| {
sidebar_menu_popover.popdown();
*(*CLOSE_REQUEST).lock().unwrap() = true;
}));
sidebar_menu_popover_sections.append(&sidebar_menu_about_button);
sidebar_menu_popover_sections.append(&sidebar_menu_quit_button);
sidebar_menu_popover.set_parent(&sidebar_menu_button);
sidebar_menu_button.connect_clicked(glib::clone!(@weak sidebar_menu_popover => move |_| {
sidebar_menu_popover.popup();
}));
let sidebar_nav_right_button = Button::from_icon_name("go-next-symbolic");
sidebar_header.pack_start(&sidebar_add_server_button);
sidebar_header.pack_end(&sidebar_menu_button);
sidebar_box.append(&sidebar_header);
sidebar_box.append(&stack_sidebar);
let stack_box = Box::builder()
.orientation(Orientation::Vertical)
.hexpand_set(true)
.hexpand(true)
.css_classes(vec!["stack".to_string()])
.build();
let stack_window_title = WindowTitle::new(