ludusavi 0.18.0

Game save backup tool
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
use std::collections::HashSet;

use iced::{alignment::Horizontal as HorizontalAlignment, keyboard::Modifiers, widget::tooltip, Alignment, Length};

use crate::{
    gui::{
        badge::Badge,
        button,
        common::{BackupPhase, GameAction, Message, Operation, RestorePhase, Screen, ScrollSubject},
        file_tree::FileTree,
        icon::Icon,
        search::FilterComponent,
        shortcuts::TextHistories,
        style,
        widget::{
            Button, Checkbox, Column, Container, IcedButtonExt, IcedParentExt, PickList, Row, Text, TextInput, Tooltip,
        },
    },
    lang::TRANSLATOR,
    resource::{
        cache::Cache,
        config::{Config, Sort},
        manifest::{Manifest, Os},
    },
    scan::{layout::GameLayout, BackupInfo, DuplicateDetector, OperationStatus, ScanChange, ScanInfo},
};

#[derive(Default)]
pub struct GameListEntry {
    pub scan_info: ScanInfo,
    pub backup_info: Option<BackupInfo>,
    pub selected_backup: Option<String>,
    pub tree: Option<FileTree>,
    pub popup_menu: crate::gui::popup_menu::State<GameAction>,
    pub show_comment_editor: bool,
    pub game_layout: Option<GameLayout>,
    /// The `scan_info` gets mutated in response to things like toggling saves off,
    /// so we need a persistent flag to say if the game has been scanned yet.
    pub scanned: bool,
}

impl GameListEntry {
    fn view(
        &self,
        restoring: bool,
        config: &Config,
        manifest: &Manifest,
        duplicate_detector: &DuplicateDetector,
        operation: &Operation,
        expanded: bool,
        modifiers: &Modifiers,
        filtering_duplicates: bool,
    ) -> Container {
        let successful = match &self.backup_info {
            Some(x) => x.successful(),
            _ => true,
        };

        let enabled = config.is_game_enabled_for_operation(&self.scan_info.game_name, restoring);
        let all_items_ignored = self.scan_info.all_ignored();
        let customized = config.is_game_customized(&self.scan_info.game_name);
        let customized_pure = customized && !manifest.0.contains_key(&self.scan_info.game_name);
        let name_for_checkbox = self.scan_info.game_name.clone();
        let name_for_comment = self.scan_info.game_name.clone();
        let name_for_comment2 = self.scan_info.game_name.clone();
        let name_for_duplicate_toggle = self.scan_info.game_name.clone();
        let operating = !operation.idle();
        let changes = self.scan_info.overall_change();
        let duplication = duplicate_detector.is_game_duplicated(&self.scan_info.game_name);

        Container::new(
            Column::new()
                .padding(5)
                .spacing(5)
                .align_items(Alignment::Center)
                .push(
                    Row::new()
                        .spacing(15)
                        .align_items(Alignment::Center)
                        .push(
                            Checkbox::new("", enabled, move |enabled| Message::ToggleGameListEntryEnabled {
                                name: name_for_checkbox.clone(),
                                enabled,
                                restoring,
                            })
                            .spacing(0)
                            .style(style::Checkbox),
                        )
                        .push(
                            Button::new(
                                Text::new(self.scan_info.game_name.clone())
                                    .horizontal_alignment(HorizontalAlignment::Center),
                            )
                            .on_press_some(if self.scanned {
                                Some(Message::ToggleGameListEntryExpanded {
                                    name: self.scan_info.game_name.clone(),
                                })
                            } else if !operating {
                                if restoring {
                                    Some(Message::Restore(RestorePhase::Start {
                                        preview: true,
                                        games: Some(vec![self.scan_info.game_name.clone()]),
                                    }))
                                } else {
                                    Some(Message::Backup(BackupPhase::Start {
                                        preview: true,
                                        games: Some(vec![self.scan_info.game_name.clone()]),
                                    }))
                                }
                            } else {
                                None
                            })
                            .style(if !self.scanned {
                                style::Button::GameListEntryTitleUnscanned
                            } else if !enabled || all_items_ignored {
                                style::Button::GameListEntryTitleDisabled
                            } else if successful {
                                style::Button::GameListEntryTitle
                            } else {
                                style::Button::GameListEntryTitleFailed
                            })
                            .width(Length::Fill)
                            .padding(2),
                        )
                        .push_some(|| match changes {
                            ScanChange::New => Some(Badge::new_entry().view()),
                            ScanChange::Different => Some(Badge::changed_entry().view()),
                            ScanChange::Removed => None,
                            ScanChange::Same => None,
                            ScanChange::Unknown => None,
                        })
                        .push_if(
                            || self.scan_info.any_ignored(),
                            || {
                                Badge::new(
                                    &TRANSLATOR
                                        .processed_subset(self.scan_info.total_items(), self.scan_info.enabled_items()),
                                )
                                .view()
                            },
                        )
                        .push_if(
                            || !duplication.unique(),
                            || {
                                Badge::new(&TRANSLATOR.badge_duplicates())
                                    .faded(duplication.resolved())
                                    .on_press(Message::FilterDuplicates {
                                        restoring,
                                        game: (!filtering_duplicates).then_some(name_for_duplicate_toggle),
                                    })
                                    .view()
                            },
                        )
                        .push_if(|| !successful, || Badge::new(&TRANSLATOR.badge_failed()).view())
                        .push_some(|| {
                            self.scan_info
                                .backup
                                .as_ref()
                                .and_then(|backup| backup.comment().as_ref())
                                .map(|comment| {
                                    Tooltip::new(
                                        Icon::Comment.as_text().width(Length::Shrink),
                                        comment,
                                        tooltip::Position::Top,
                                    )
                                    .size(16)
                                    .gap(5)
                                    .style(style::Container::Tooltip)
                                })
                        })
                        .push_some(|| {
                            self.scan_info
                                .backup
                                .as_ref()
                                .and_then(|backup| backup.os())
                                .and_then(|os| {
                                    (os != Os::HOST && os != Os::Other).then(|| Badge::new(&format!("{os:?}")).view())
                                })
                        })
                        .push_some(|| {
                            self.scan_info.backup.as_ref().and_then(|backup| {
                                backup.locked().then_some(Icon::Lock.into_text().width(Length::Shrink))
                            })
                        })
                        .push(
                            Row::new()
                                .push_some(|| {
                                    if self.scan_info.available_backups.len() == 1 {
                                        self.scan_info.backup.as_ref().map(|backup| {
                                            Container::new(Text::new(backup.label()).size(18))
                                                .padding([2, 0, 0, 0])
                                                .width(165)
                                                .align_x(HorizontalAlignment::Center)
                                        })
                                    } else if !self.scan_info.available_backups.is_empty() {
                                        if operating {
                                            return self.scan_info.backup.as_ref().map(|backup| {
                                                Container::new(Text::new(backup.label()).size(15))
                                                    .padding(2)
                                                    .width(165)
                                                    .height(25)
                                                    .center_x()
                                                    .center_y()
                                                    .style(style::Container::DisabledBackup)
                                            });
                                        }

                                        let game = self.scan_info.game_name.clone();
                                        let content = Container::new(
                                            PickList::new(
                                                &self.scan_info.available_backups,
                                                self.scan_info.backup.as_ref().cloned(),
                                                move |backup| Message::SelectedBackupToRestore {
                                                    game: game.clone(),
                                                    backup,
                                                },
                                            )
                                            .text_size(15)
                                            .style(style::PickList::Backup),
                                        )
                                        .width(165)
                                        .padding([0, 0, 0, 0])
                                        .align_x(HorizontalAlignment::Center);
                                        Some(content)
                                    } else {
                                        None
                                    }
                                })
                                .push({
                                    let confirm = !modifiers.alt();
                                    let action = if modifiers.shift() {
                                        Some(if restoring {
                                            GameAction::PreviewRestore
                                        } else {
                                            GameAction::PreviewBackup
                                        })
                                    } else if modifiers.command() {
                                        Some(if restoring {
                                            GameAction::Restore { confirm }
                                        } else {
                                            GameAction::Backup { confirm }
                                        })
                                    } else {
                                        None
                                    };
                                    if let Some(action) = action {
                                        let button = Button::new(action.icon().into_text().width(45))
                                            .on_press_if(
                                                || !operating,
                                                || Message::GameAction {
                                                    action,
                                                    game: self.scan_info.game_name.clone(),
                                                },
                                            )
                                            .style(style::Button::GameActionPrimary)
                                            .padding(2);
                                        Container::new(
                                            Tooltip::new(button, action.to_string(), tooltip::Position::Top)
                                                .size(16)
                                                .gap(5)
                                                .style(style::Container::Tooltip),
                                        )
                                    } else {
                                        let options = GameAction::options(
                                            restoring,
                                            operating,
                                            customized,
                                            customized_pure,
                                            self.scan_info.backup.is_some(),
                                            self.scan_info
                                                .backup
                                                .as_ref()
                                                .map(|backup| backup.locked())
                                                .unwrap_or_default(),
                                        );
                                        let game_name = self.scan_info.game_name.clone();

                                        let menu = crate::gui::popup_menu::PopupMenu::new(options, move |action| {
                                            Message::GameAction {
                                                action,
                                                game: game_name.clone(),
                                            }
                                        })
                                        .style(style::PickList::Popup);
                                        Container::new(menu)
                                    }
                                })
                                .push(
                                    Container::new(Text::new({
                                        let summed = self.scan_info.sum_bytes(self.backup_info.as_ref());
                                        if summed == 0 && !self.scan_info.found_anything() {
                                            "".to_string()
                                        } else {
                                            TRANSLATOR.adjusted_size(summed)
                                        }
                                    }))
                                    .width(115)
                                    .center_x(),
                                ),
                        ),
                )
                .push_some(move || {
                    if !self.show_comment_editor {
                        return None;
                    }
                    let comment = self
                        .scan_info
                        .backup
                        .as_ref()
                        .and_then(|x| x.comment().as_ref())
                        .map(|x| x.as_str())
                        .unwrap_or_else(|| "");
                    Some(
                        Row::new()
                            .align_items(Alignment::Center)
                            .padding([0, 20])
                            .spacing(20)
                            .push(Text::new(TRANSLATOR.comment_label()))
                            .push(
                                TextInput::new(&TRANSLATOR.comment_label(), comment).on_input(move |value| {
                                    Message::EditedBackupComment {
                                        game: name_for_comment.clone(),
                                        comment: value,
                                    }
                                }),
                            )
                            .push(button::close(Message::GameAction {
                                action: GameAction::Comment,
                                game: name_for_comment2,
                            })),
                    )
                })
                .push_some(|| {
                    expanded
                        .then(|| {
                            self.tree.as_ref().map(|tree| {
                                tree.view(&self.scan_info.game_name, config, restoring)
                                    .width(Length::Fill)
                            })
                        })
                        .flatten()
                }),
        )
        .style(style::Container::GameListEntry)
    }

    pub fn refresh_tree(&mut self, duplicate_detector: &DuplicateDetector, config: &Config, restoring: bool) {
        match self.tree.as_mut() {
            Some(tree) => tree.reset_nodes(
                self.scan_info.clone(),
                &self.backup_info,
                duplicate_detector,
                config,
                restoring,
            ),
            None => {
                self.tree = Some(FileTree::new(
                    self.scan_info.clone(),
                    &self.backup_info,
                    duplicate_detector,
                    config,
                    restoring,
                ))
            }
        }
    }

    pub fn clear_tree(&mut self) {
        if let Some(tree) = self.tree.as_mut() {
            tree.clear_nodes();
        }
    }
}

#[derive(Default)]
pub struct GameList {
    pub entries: Vec<GameListEntry>,
    pub search: FilterComponent,
    expanded_games: HashSet<String>,
    pub modifiers: Modifiers,
    pub filter_duplicates_of: Option<String>,
}

impl GameList {
    pub fn view(
        &self,
        restoring: bool,
        config: &Config,
        manifest: &Manifest,
        duplicate_detector: &DuplicateDetector,
        operation: &Operation,
        histories: &TextHistories,
    ) -> Container {
        let duplicatees = self.filter_duplicates_of.as_ref().and_then(|game| {
            let mut duplicatees = duplicate_detector.duplicate_games(game);
            if duplicatees.is_empty() {
                None
            } else {
                duplicatees.insert(game.clone());
                Some(duplicatees)
            }
        });

        Container::new(
            Column::new()
                .push_some(|| {
                    self.search.view(
                        if restoring { Screen::Restore } else { Screen::Backup },
                        histories,
                        config.scan.show_deselected_games,
                    )
                })
                .push({
                    let content = self
                        .entries
                        .iter()
                        .filter(|x| {
                            config.should_show_game(
                                &x.scan_info.game_name,
                                restoring,
                                x.scan_info.overall_change().is_changed(),
                                x.scan_info.found_anything(),
                            )
                        })
                        .filter(|x| {
                            !self.search.show
                                || self.search.qualifies(
                                    &x.scan_info,
                                    config.is_game_enabled_for_operation(&x.scan_info.game_name, restoring),
                                    duplicate_detector.is_game_duplicated(&x.scan_info.game_name),
                                    config.scan.show_deselected_games,
                                )
                        })
                        .filter(|x| {
                            duplicatees
                                .as_ref()
                                .map(|xs| xs.contains(&x.scan_info.game_name))
                                .unwrap_or(true)
                        })
                        .fold(
                            Column::new().width(Length::Fill).padding([0, 15, 5, 15]).spacing(5),
                            |parent, x| {
                                parent.push(x.view(
                                    restoring,
                                    config,
                                    manifest,
                                    duplicate_detector,
                                    operation,
                                    self.expanded_games.contains(&x.scan_info.game_name),
                                    &self.modifiers,
                                    duplicatees.is_some(),
                                ))
                            },
                        );
                    ScrollSubject::game_list(restoring).into_widget(content)
                }),
        )
    }

    pub fn all_entries_selected(&self, config: &Config, restoring: bool) -> bool {
        self.entries
            .iter()
            .all(|x| config.is_game_enabled_for_operation(&x.scan_info.game_name, restoring))
    }

    pub fn compute_operation_status(&self, config: &Config, restoring: bool) -> OperationStatus {
        let mut status = OperationStatus::default();
        for entry in self.entries.iter() {
            status.total_games += 1;
            status.total_bytes += entry.scan_info.total_possible_bytes();
            if !entry.scan_info.all_ignored()
                && config.is_game_enabled_for_operation(&entry.scan_info.game_name, restoring)
            {
                status.processed_games += 1;
                status.processed_bytes += entry.scan_info.sum_bytes(None);
            }

            status.changed_games.add(entry.scan_info.overall_change());
        }
        status
    }

    pub fn sort(&mut self, sort: &Sort) {
        self.entries.sort_by(|x, y| {
            crate::scan::compare_games(
                sort.key,
                &x.scan_info,
                x.backup_info.as_ref(),
                &y.scan_info,
                y.backup_info.as_ref(),
            )
        });
        if sort.reversed {
            self.entries.reverse();
        }
    }

    pub fn toggle_game_expanded(
        &mut self,
        game: &str,
        duplicate_detector: &DuplicateDetector,
        config: &Config,
        restoring: bool,
    ) {
        if self.expanded_games.contains(game) {
            self.expanded_games.remove(game);
            for entry in self.entries.iter_mut() {
                if entry.scan_info.game_name == game {
                    entry.clear_tree();
                    break;
                }
            }
        } else {
            self.expanded_games.insert(game.to_string());
            for entry in self.entries.iter_mut() {
                if entry.scan_info.game_name == game {
                    entry.refresh_tree(duplicate_detector, config, restoring);
                    break;
                }
            }
        }
    }

    pub fn clear(&mut self) {
        self.entries.clear();
        self.expanded_games.clear();
    }

    pub fn with_recent_games(restoring: bool, config: &Config, cache: &Cache) -> Self {
        let games = if restoring {
            &cache.restore.recent_games
        } else {
            &cache.backup.recent_games
        };
        let sort = if restoring {
            &config.restore.sort
        } else {
            &config.backup.sort
        };

        let mut log = Self::default();
        for game in games {
            log.update_game(
                ScanInfo {
                    game_name: game.clone(),
                    ..Default::default()
                },
                Default::default(),
                sort,
                &DuplicateDetector::default(),
                &Default::default(),
                None,
                config,
                restoring,
            );
        }
        log
    }

    pub fn find_game(&self, game: &str) -> Option<usize> {
        let mut index = None;

        for (i, entry) in self.entries.iter().enumerate() {
            if entry.scan_info.game_name == game {
                index = Some(i);
                break;
            }
        }

        index
    }

    pub fn update_game(
        &mut self,
        scan_info: ScanInfo,
        backup_info: Option<BackupInfo>,
        sort: &Sort,
        duplicate_detector: &DuplicateDetector,
        duplicates: &HashSet<String>,
        game_layout: Option<GameLayout>,
        config: &Config,
        restoring: bool,
    ) {
        let game_name = scan_info.game_name.clone();
        let index = self.find_game(&game_name);
        let scanned = scan_info.found_anything();

        match index {
            Some(i) => {
                if scan_info.can_report_game() {
                    self.entries[i].scan_info = scan_info;
                    self.entries[i].backup_info = backup_info;
                    self.entries[i].game_layout = game_layout;
                    self.entries[i].scanned = scanned || self.entries[i].scanned;
                    if self.expanded_games.contains(&game_name) {
                        self.entries[i].refresh_tree(duplicate_detector, config, restoring);
                    }
                } else {
                    self.entries.remove(i);
                }
            }
            None => {
                let mut entry = GameListEntry {
                    scan_info,
                    backup_info,
                    game_layout,
                    scanned,
                    ..Default::default()
                };
                if self.expanded_games.contains(&game_name) {
                    entry.refresh_tree(duplicate_detector, config, restoring);
                }
                self.entries.push(entry);
                self.sort(sort);
            }
        }

        if !duplicates.is_empty() {
            for entry in self.entries.iter_mut() {
                if duplicates.contains(&entry.scan_info.game_name)
                    && self.expanded_games.contains(&entry.scan_info.game_name)
                {
                    entry.refresh_tree(duplicate_detector, config, restoring);
                }
            }
        }
    }

    pub fn refresh_game_tree(
        &mut self,
        game: &str,
        config: &Config,
        duplicate_detector: &mut DuplicateDetector,
        restoring: bool,
    ) {
        if let Some(index) = self.find_game(game) {
            // Can't toggle restore items.
            if !restoring {
                self.entries[index]
                    .scan_info
                    .update_ignored(&config.backup.toggled_paths, &config.backup.toggled_registry);
            }

            let stale = duplicate_detector.add_game(
                &self.entries[index].scan_info,
                config.is_game_enabled_for_operation(game, restoring),
            );

            self.entries[index].refresh_tree(duplicate_detector, config, restoring);

            for entry in &mut self.entries {
                if stale.contains(&entry.scan_info.game_name) {
                    entry.refresh_tree(duplicate_detector, config, restoring);
                }
            }
        }
    }

    pub fn remove_game(
        &mut self,
        game: &str,
        duplicate_detector: &DuplicateDetector,
        duplicates: &HashSet<String>,
        config: &Config,
        restoring: bool,
    ) {
        self.entries.retain(|entry| entry.scan_info.game_name != game);
        for entry in self.entries.iter_mut() {
            if duplicates.contains(&entry.scan_info.game_name) {
                entry.refresh_tree(duplicate_detector, config, restoring);
            }
        }
    }

    pub fn unscan_games(&mut self, games: &[String]) {
        for entry in self.entries.iter_mut() {
            if games.contains(&entry.scan_info.game_name) {
                entry.scan_info.found_files.clear();
                entry.scan_info.found_registry_keys.clear();
            }
        }
    }

    pub fn contains_unscanned_games(&self) -> bool {
        self.entries.iter().any(|x| !x.scanned)
    }

    pub fn toggle_backup_comment_editor(&mut self, game: &str) {
        let index = self.find_game(game);

        if let Some(i) = index {
            self.entries[i].show_comment_editor = !self.entries[i].show_comment_editor;
        }
    }

    pub fn set_comment(&mut self, game: &str, comment: String) {
        let Some(index) = self.find_game(game) else { return };
        let entry = &mut self.entries[index];
        let Some(backup) = &mut entry.scan_info.backup else { return };
        let Some(layout) = &mut entry.game_layout else { return };

        layout.set_backup_comment(backup.name(), &comment);
        backup.set_comment(comment);
        layout.save();
    }

    pub fn toggle_locked(&mut self, game: &str) {
        let Some(index) = self.find_game(game) else { return };
        let entry = &mut self.entries[index];
        let Some(backup) = &mut entry.scan_info.backup else { return };
        let Some(layout) = &mut entry.game_layout else { return };

        let new = !backup.locked();

        layout.set_backup_locked(backup.name(), new);
        backup.set_locked(new);
        layout.save();
    }
}