detail.rs 17.4 KB
Newer Older
Sophie Herold's avatar
Sophie Herold committed
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
use chrono::prelude::*;
use gio::prelude::*;
use gtk::prelude::*;

use crate::borg;
use crate::borg::Run;
use crate::shared;
use crate::shared::*;
use crate::ui;
use crate::ui::globals::*;
use crate::ui::prelude::*;
use crate::ui::utils::{self, WidgetEnh};

pub fn init() {
    main_ui().backup_run().connect_clicked(on_backup_run);

    main_ui()
        .target_listbox()
        .connect_row_activated(|_, _| ui::storage::show());

    main_ui()
        .include_home()
        .connect_property_active_notify(|switch| {
            if switch.get_sensitive() {
                let change: bool = if switch.get_active() {
                    true
                } else {
                    ui::utils::dialog_yes_no(gettext(
                        "Are you sure you want to remove the home directory from this backup?",
                    ))
                };

                SETTINGS.update(|settings| {
                    if !change {
                        switch.set_active(!switch.get_active());
                    } else if switch.get_active() {
                        settings
                            .backups
                            .get_active_mut()
                            .unwrap()
                            .include
                            .insert(std::path::PathBuf::new());
                    } else {
                        settings
                            .backups
                            .get_active_mut()
                            .unwrap()
                            .include
                            .remove(&std::path::PathBuf::new());
                    }
                });

                if change {
                    super::write_config();
                    refresh();
                }
            }
        });

    main_ui().include().connect_row_activated(|_, row| {
        if let Some(ref name) = row.get_widget_name() {
            if name == "-add" {
                add_include();
            }
        }
    });

    main_ui().backup_exclude().connect_row_activated(|_, row| {
        if let Some(ref name) = row.get_widget_name() {
            if name == "-add" {
                add_exclude();
            }
        }
    });

    main_ui().delete_backup_conf().connect_clicked(|_| {
        let delete = ui::utils::dialog_yes_no(gettext(
            "Are you sure you want to delete this backup configuration?",
        ));

        if delete {
            ui::utils::dialog_catch_err(
                ui::utils::secret_service_delete_passwords(
                    SETTINGS.get().backups.get_active().unwrap(),
                ),
                "Failed to remove potentially remaining passwords from key storage.",
            );
            {
                SETTINGS.update(|settings| {
                    settings.backups.remove(&ACTIVE_BACKUP_ID.get().unwrap());
                });
            }

            super::write_config();
            ui::overview::refresh();
            main_ui().main_stack().set_visible_child_name("main");
        }
    });

    main_ui()
        .stop_backup_create()
        .connect_clicked(|_| stop_backup_create());

    gtk::timeout_add(500, || {
        refresh_statusx();
        Continue(true)
    });
}

fn stop_backup_create() {
    if !ui::utils::dialog_yes_no(gettext("Are you sure you want abort the running backup?")) {
        return;
    }

    if let Some(communication) = BACKUP_COMMUNICATION.load().get_active() {
        communication.instruction.update(|inst| {
            *inst = borg::Instruction::Abort;
        });
    }
}

fn on_backup_run(button: &gtk::Button) {
    button.set_sensitive(false);

    let config = SETTINGS.load().backups.get_active().unwrap().clone();
    let backup_id = ACTIVE_BACKUP_ID.get().unwrap();

    if ACTIVE_MOUNTS.load().contains(&backup_id) {
        debug!("Trying to run borg::create on a backup that is currently mounted.");

        let unmount = ui::utils::dialog_yes_no(gettext(
            "The backup repository is currently reserved for browsing files. \
Sophie Herold's avatar
Sophie Herold committed
133
             Do you want to disable browsing and start the Backup?",
Sophie Herold's avatar
Sophie Herold committed
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
        ));
        if unmount {
            trace!("User decided to unmount repo.");
            if !ui::utils::dialog_catch_err(
                borg::Borg::new(config).umount(),
                gettext("Failed to unmount repository."),
            ) {
                ACTIVE_MOUNTS.update(|mounts| {
                    mounts.remove(&backup_id);
                });
            }
        } else {
            trace!("User decided to abort backup.");
            return;
        }
    }

    let backups = &SETTINGS.load().backups;
    let backup = backups.get(&backup_id).unwrap().clone();

    let communication: borg::Communication = Default::default();

    BACKUP_COMMUNICATION.update(|x| {
        x.insert(backup_id.clone(), communication.clone());
    });
    refresh_status(&communication);

    ui::utils::Async::borg(
        "borg::create",
        borg::Borg::new(backup),
        move |borg| borg.create(communication),
        move |result| {
            BACKUP_COMMUNICATION.update(|c| {
                c.remove(&backup_id);
            });
            let result_string_err = result.map_err(|err| format!("{}", err));
            let run_info = Some(shared::RunInfo::new(result_string_err.clone()));
            refresh_offline(&run_info);
            SETTINGS.update(|settings| {
                settings.backups.get_mut(&backup_id).unwrap().last_run = run_info.clone()
            });
            ui::write_config();
            ui::utils::dialog_catch_errb(&result_string_err, gettext("Backup failed"));
        },
    );
}

pub fn add_list_row(list: &gtk::ListBox, file: &std::path::Path, position: i32) -> gtk::Button {
    let (row, horizontal_box) = ui::utils::add_list_box_row(list, None, position);

    row.set_activatable(false);

    if let Some(img) = ui::utils::file_icon(&shared::absolute(file), gtk::IconSize::Dialog) {
        horizontal_box.add(&img);
    }

    let label = gtk::Label::new(file.to_str());
    label.set_line_wrap(true);
    label.set_line_wrap_mode(pango::WrapMode::WordChar);
    label.set_xalign(0.0);
    horizontal_box.add(&label);

    let button = gtk::Button::new();
    button.add(&gtk::Image::new_from_icon_name(
        Some("window-close-symbolic"),
        gtk::IconSize::Button,
    ));
    button.add_css_class("circular");
    button.set_valign(gtk::Align::Center);
    horizontal_box.pack_end(&button, false, false, 0);

    button
}

// TODO: Function has too many lines
pub fn refresh() {
    let include_home = SETTINGS
        .get()
        .backups
        .get_active()
        .unwrap()
        .include
        .contains(&std::path::PathBuf::new());

    main_ui().include_home().set_sensitive(false);
    main_ui().include_home().set_active(include_home);
    main_ui().include_home().set_sensitive(true);

    if include_home {
        main_ui().home_icon().remove_css_class("not-active");
    } else {
        main_ui().home_icon().add_css_class("not-active");
    }

    let backup = SETTINGS.load().backups.get_active().unwrap().clone();
    // messages
    main_ui().detail_device_not_connected().hide();
    //let repo = backup.repo.clone();
    if let shared::BackupRepo::Local { path, .. } = backup.repo.clone() {
        ui::utils::async_react(
            "check_repo_available",
            move || ui::new_backup::is_backup_repo(&path),
            |available| {
                if !available {
                    gtk::timeout_add(250, || {
                        main_ui().detail_device_not_connected().show();
                        // Workaround for https://bugzilla.gnome.org/show_bug.cgi?id=710888
                        main_ui().detail_device_not_connected().queue_resize();
                        Continue(false)
                    });
                }
            },
        );
    }

    // backup target ui
    let repo_ui = main_ui().target_listbox();
    ui::utils::clear(&repo_ui);
    let (_, horizontal_box) = ui::utils::add_list_box_row(&repo_ui, None, 1);

    if let Ok(icon) = gio::Icon::new_for_string(&utils::repo_icon(&backup.repo)) {
        let img = gtk::Image::new_from_gicon(&icon, gtk::IconSize::Dialog);
        horizontal_box.add(&img);
    }

    match &backup.repo {
        shared::BackupRepo::Local {
            ref device,
            ref label,
            ..
        } => {
            let (vertical_box, _, _) = ui::utils::list_vertical_box(
                label.as_ref().map(String::as_str),
                Some(
                    device
                        .as_ref()
                        .map(String::as_str)
                        .unwrap_or(&backup.repo.to_string()),
                ),
            );
            horizontal_box.add(&vertical_box);
        }
        repo @ shared::BackupRepo::Remote { .. } => {
            let (vertical_box, _, _) = ui::utils::list_vertical_box(Some(&repo.to_string()), None);
            horizontal_box.add(&vertical_box);
        }
    }

    repo_ui.show_all();

    // include list
    ui::utils::clear(&main_ui().include());
    // TODO: Warn if there a no includes, disable backup button
    for file in backup.include.iter().rev() {
        if *file == std::path::PathBuf::new() {
            continue;
        }

        let button = add_list_row(&main_ui().include(), file, 1);

        let path = file.clone();
        button.connect_clicked(move |_| {
            let delete =
                ui::utils::dialog_yes_no(gettext("You no longer want to backup this directory?"));

            if delete {
                SETTINGS.update(|settings| {
                    settings
                        .backups
                        .get_active_mut()
                        .unwrap()
                        .include
                        .remove(&path);
                });
                super::write_config();
                refresh();
            }
        });
    }
    main_ui().include().show_all();

    // exclude list
    ui::utils::clear(&main_ui().backup_exclude());
    for file in backup.exclude.iter().rev() {
        let button = add_list_row(&main_ui().backup_exclude(), file, 0);
        let path = file.clone();
        button.connect_clicked(move |_| {
            SETTINGS.update(|settings| {
                settings
                    .backups
                    .get_active_mut()
                    .unwrap()
                    .exclude
                    .remove(&path);
            });
            super::write_config();
            refresh();
        });
    }
    main_ui().backup_exclude().show_all();

    refresh_statusx();
}

pub fn view_backup_conf(id: &str) {
    ACTIVE_BACKUP_ID.update(|active_id| *active_id = Some(id.to_string()));
    refresh();
    // scroll back to top
    if let Some(adjustment) = main_ui().detail_scrolled().get_vadjustment() {
        adjustment.set_value(adjustment.get_lower());
    }
    main_ui().main_stack().set_visible_child_name("backup_conf");
}

/// Returns a relative path for sub directories of home
fn rel_path(path: &std::path::Path) -> std::path::PathBuf {
    if let Ok(rel_path) = path.strip_prefix(shared::get_home_dir()) {
        rel_path.to_path_buf()
    } else {
        path.to_path_buf()
    }
}

fn add_include() {
    if let Some(path) = ui::utils::folder_chooser_dialog(
        &gettext("Include directory in backup"),
        &main_ui().window(),
    ) {
        SETTINGS.update(|settings| {
            settings
                .backups
                .get_active_mut()
                .unwrap()
                .include
                .insert(rel_path(&path));
        });
        super::write_config();
        refresh();
    }
}

fn add_exclude() {
    if let Some(path) = ui::utils::folder_chooser_dialog(
        &gettext("Exclude directory from backup"),
        &main_ui().window(),
    ) {
        SETTINGS.update(|settings| {
            settings
                .backups
                .get_active_mut()
                .unwrap()
                .exclude
                .insert(rel_path(&path));
        });
        super::write_config();
        refresh();
    }
}

pub fn refresh_statusx() {
    if let Some(communication) = BACKUP_COMMUNICATION.load().get_active() {
        refresh_status(communication);
    } else if let Some(backup) = SETTINGS.load().backups.get_active() {
        refresh_offline(&backup.last_run);
    }
}

pub fn refresh_offline(run_info_opt: &Option<shared::RunInfo>) {
    let stack = main_ui().stack();
    main_ui().stop_backup_create().hide();
    main_ui().backup_run().set_sensitive(true);

    if let Some(ref run_info) = run_info_opt {
        main_ui().status_button().show();
        match &run_info.result {
            Ok(stats) => {
                main_ui().status_icon().set_visible_child_name("success");
                main_ui()
                    .status_text()
                    .set_text(&gettext("Last backup successful"));

                main_ui().status_subtext().set_text(&gettext!(
                    "About {}",
                    (run_info.end - Local::now()).humanize()
                ));

                stack.set_visible_child_name("archive");
                main_ui().archive_progress().set_fraction(1.0);
                main_ui()
                    .original_size()
                    .set_text(&ui::utils::hsize(stats.archive.stats.original_size));
                main_ui()
                    .deduplicated_size()
                    .set_text(&ui::utils::hsize(stats.archive.stats.deduplicated_size));
            }
            Err(err) => {
                main_ui().status_icon().set_visible_child_name("error");
                main_ui()
                    .status_text()
                    .set_text(&gettext("Last backup failed"));
                main_ui().status_subtext().set_text(&gettext!(
                    "About {}",
                    (run_info.end - Local::now()).humanize()
                ));
                stack.set_visible_child_name("error");
                main_ui().error_message().set_text(err);
            }
        }
    } else {
        main_ui().status_button().hide();
        main_ui().status_icon().set_visible_child_name("unknown");
        main_ui()
            .status_text()
            .set_text(&gettext("Backup never ran"));
        main_ui().status_subtext().set_text("");
    }
}

pub fn refresh_status(communication: &borg::Communication) -> Continue {
    main_ui().backup_run().set_sensitive(false);
    main_ui().stop_backup_create().show();

    let stack = main_ui().stack();
    main_ui().status_subtext().set_text("");

    let status = communication.status.get();

    if let Some(ref last_message) = status.last_message {
        match *last_message {
            Progress::Archive {
                original_size,
                deduplicated_size,
                ..
            } => {
                stack.set_visible_child_name("archive");

                if let Some(total) = status.estimated_size {
                    let fraction = original_size as f64 / total as f64;
                    main_ui().archive_progress().show();
                    main_ui().archive_progress().set_fraction(fraction);
                    main_ui()
                        .status_subtext()
                        .set_text(&format!("{:.1} % finished", fraction * 100.0))
                } else {
                    main_ui().archive_progress().hide();
                }

                main_ui()
                    .original_size()
                    .set_text(&ui::utils::hsize(original_size));
                main_ui()
                    .deduplicated_size()
                    .set_text(&ui::utils::hsize(deduplicated_size));
            }
            Progress::Message {
                message: Some(ref message),
                ..
            } => {
                stack.set_visible_child_name("message");
                main_ui().message().set_text(message);
            }
            Progress::Percent {
                current: Some(current),
                total: Some(total),
                message: Some(ref message),
                ..
            } => {
                stack.set_visible_child_name("percent");
                main_ui()
                    .progress()
                    .set_fraction(current as f64 / total as f64);
                main_ui().percent_message().set_text(message);
            }
            // TODO: cover progress message?
            _ => {}
        }
    }

    main_ui().status_icon().set_visible_child_name("running");

    match status.run {
        Run::Init => {
            main_ui().status_button().hide();
            main_ui()
                .status_text()
                .set_text(&gettext("Preparing backup"));
        }
        Run::SizeEstimation => {
            main_ui().status_button().hide();
            main_ui()
                .status_text()
                .set_text(&gettext("Estimating backup size"));
        }
        Run::Running => {
            main_ui().status_button().show();
            main_ui().status_text().set_text(&gettext("Backup running"));
        }
        Run::Reconnecting => {
            main_ui().status_button().show();
            main_ui().status_text().set_text(&gettext("Reconnecting"));
            main_ui().status_subtext().set_text(&gettext!(
                "Conenction lost, reconnecting {}",
                &crate::BORG_DELAY_RECONNECT.humanize()
            ));
        }
        Run::Stopping => {
            main_ui().status_button().show();
            main_ui()
                .status_text()
                .set_text(&gettext("Stopping backup"));
        }
    };

    Continue(true)
}