-
Notifications
You must be signed in to change notification settings - Fork 808
Expand file tree
/
Copy pathMainWindowViewModel.cs
More file actions
455 lines (390 loc) · 19.3 KB
/
MainWindowViewModel.cs
File metadata and controls
455 lines (390 loc) · 19.3 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
using System.Collections.Specialized;
using Avalonia;
using Avalonia.Automation;
using Avalonia.Collections;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using UniGetUI.Avalonia.Infrastructure;
using UniGetUI.Avalonia.ViewModels.Pages;
using UniGetUI.Avalonia.Views;
using UniGetUI.Avalonia.Views.DialogPages;
using UniGetUI.Avalonia.Views.Pages;
using UniGetUI.Avalonia.Views.Pages.LogPages;
using UniGetUI.Avalonia.Views.Pages.SettingsPages;
using UniGetUI.Core.Data;
using UniGetUI.Core.SettingsEngine;
using UniGetUI.Core.Tools;
using UniGetUI.Interface.Enums;
using UniGetUI.PackageEngine;
using UniGetUI.PackageEngine.Enums;
using UniGetUI.PackageEngine.Interfaces;
using UniGetUI.PackageEngine.PackageLoader;
namespace UniGetUI.Avalonia.ViewModels;
public partial class MainWindowViewModel : ViewModelBase
{
// ─── Pages ───────────────────────────────────────────────────────────────
private readonly DiscoverSoftwarePage DiscoverPage;
private readonly SoftwareUpdatesPage UpdatesPage;
private readonly InstalledPackagesPage InstalledPage;
private readonly PackageBundlesPage BundlesPage;
private SettingsBasePage? SettingsPage;
private SettingsBasePage? ManagersPage;
private UniGetUILogPage? UniGetUILogPage;
private ManagerLogsPage? ManagerLogPage;
private OperationHistoryPage? OperationHistoryPage;
private HelpPage? HelpPage;
private ReleaseNotesPage? ReleaseNotesPage;
// ─── Navigation state ────────────────────────────────────────────────────
private PageType _oldPage = PageType.Null;
private PageType _currentPage = PageType.Null;
public PageType CurrentPage_t => _currentPage;
private readonly List<PageType> NavigationHistory = new();
[ObservableProperty]
private object? _currentPageContent;
public event EventHandler<bool>? CanGoBackChanged;
public event EventHandler<PageType>? CurrentPageChanged;
[ObservableProperty]
private string _announcementText = "";
[ObservableProperty]
private AutomationLiveSetting _announcementLiveSetting = AutomationLiveSetting.Polite;
// ─── Operations panel ─────────────────────────────────────────────────────
public AvaloniaList<OperationViewModel> Operations => AvaloniaOperationRegistry.OperationViewModels;
[ObservableProperty]
private bool _operationsPanelVisible;
[ObservableProperty]
private bool _operationsPanelExpanded = true;
[RelayCommand]
private void ToggleOperationsPanel() => OperationsPanelExpanded = !OperationsPanelExpanded;
[RelayCommand]
private void RetryFailedOperations() => AvaloniaOperationRegistry.RetryFailed();
[RelayCommand]
private void ClearSuccessfulOperations() => AvaloniaOperationRegistry.ClearSuccessful();
[RelayCommand]
private void ClearFinishedOperations() => AvaloniaOperationRegistry.ClearFinished();
[RelayCommand]
private void CancelAllOperations() => AvaloniaOperationRegistry.CancelAll();
// ─── Sidebar ─────────────────────────────────────────────────────────────
public SidebarViewModel Sidebar { get; } = new();
// ─── Global search ───────────────────────────────────────────────────────
[ObservableProperty]
private string _globalSearchText = "";
[ObservableProperty]
private bool _globalSearchEnabled;
[ObservableProperty]
private string _globalSearchPlaceholder = "";
// When search text changes, notify the current page
private PackagesPageViewModel? _subscribedPageViewModel;
private bool _syncingSearch;
partial void OnGlobalSearchTextChanged(string value)
{
if (_syncingSearch) return;
if (CurrentPageContent is AbstractPackagesPage page)
page.ViewModel.GlobalQueryText = value;
}
private void SubscribeToPageViewModel(AbstractPackagesPage? page)
{
if (_subscribedPageViewModel is not null)
_subscribedPageViewModel.PropertyChanged -= OnPageViewModelPropertyChanged;
_subscribedPageViewModel = page?.ViewModel;
if (_subscribedPageViewModel is not null)
_subscribedPageViewModel.PropertyChanged += OnPageViewModelPropertyChanged;
}
private void OnPageViewModelPropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(PackagesPageViewModel.GlobalQueryText) && sender is PackagesPageViewModel vm)
{
_syncingSearch = true;
GlobalSearchText = vm.GlobalQueryText;
_syncingSearch = false;
}
}
// ─── Banners ─────────────────────────────────────────────────────────────
public InfoBarViewModel UpdatesBanner { get; } = new() { Severity = InfoBarSeverity.Success };
public InfoBarViewModel ErrorBanner { get; } = new() { Severity = InfoBarSeverity.Error };
public InfoBarViewModel WinGetWarningBanner { get; } = new() { Severity = InfoBarSeverity.Warning };
public InfoBarViewModel TelemetryWarner { get; } = new() { Severity = InfoBarSeverity.Informational };
// ─── Constructor ─────────────────────────────────────────────────────────
[RelayCommand]
private void ToggleSidebar() => Sidebar.IsPaneOpen = !Sidebar.IsPaneOpen;
public MainWindowViewModel()
{
AccessibilityAnnouncementService.AnnouncementRequested += OnAnnouncementRequested;
DiscoverPage = new DiscoverSoftwarePage();
UpdatesPage = new SoftwareUpdatesPage();
InstalledPage = new InstalledPackagesPage();
BundlesPage = new PackageBundlesPage();
// Wire loader status → sidebar badges (loaders are null until package engine initializes)
foreach (var (pageType, loader) in new (PageType, AbstractPackageLoader?)[]
{
(PageType.Discover, DiscoverablePackagesLoader.Instance),
(PageType.Updates, UpgradablePackagesLoader.Instance),
(PageType.Installed, InstalledPackagesLoader.Instance),
})
{
if (loader is null) continue;
var pt = pageType;
loader.FinishedLoading += (_, _) =>
Dispatcher.UIThread.Post(() => Sidebar.SetNavItemLoading(pt, false));
loader.StartedLoading += (_, _) =>
Dispatcher.UIThread.Post(() => Sidebar.SetNavItemLoading(pt, true));
Sidebar.SetNavItemLoading(pt, loader.IsLoading);
}
if (UpgradablePackagesLoader.Instance is { } upgLoader)
{
upgLoader.PackagesChanged += (_, _) =>
Dispatcher.UIThread.Post(() =>
{
Sidebar.UpdatesBadgeCount = upgLoader.Count();
MainWindow.Instance?.UpdateSystemTrayStatus();
});
Sidebar.UpdatesBadgeCount = upgLoader.Count();
// Notifications and auto-update logic are handled by SoftwareUpdatesPage.WhenPackagesLoaded
}
WindowsAppNotificationBridge.NotificationActivated += action =>
Dispatcher.UIThread.Post(() => HandleNotificationActivation(action));
BundlesPage.UnsavedChangesStateChanged += (_, _) =>
Dispatcher.UIThread.Post(() =>
Sidebar.BundlesBadgeVisible = BundlesPage.HasUnsavedChanges);
Sidebar.BundlesBadgeVisible = BundlesPage.HasUnsavedChanges;
Sidebar.NavigationRequested += (_, pageType) => NavigateTo(pageType);
AvaloniaAutoUpdater.UpdateAvailable += version => Dispatcher.UIThread.Post(() =>
{
UpdatesBanner.Title = CoreTools.Translate("UniGetUI {0} is ready to be installed.", version);
UpdatesBanner.Message = CoreTools.Translate("The update process will start after closing UniGetUI");
UpdatesBanner.ActionButtonText = CoreTools.Translate("Update now");
UpdatesBanner.ActionButtonCommand = new CommunityToolkit.Mvvm.Input.RelayCommand(AvaloniaAutoUpdater.TriggerInstall);
UpdatesBanner.IsClosable = true;
UpdatesBanner.IsOpen = true;
});
// Keep OperationsPanelVisible in sync with the live operations list
Operations.CollectionChanged += (_, _) =>
OperationsPanelVisible = Operations.Count > 0;
if (OperatingSystem.IsWindows() && CoreTools.IsAdministrator() && !Settings.Get(Settings.K.AlreadyWarnedAboutAdmin))
{
Settings.Set(Settings.K.AlreadyWarnedAboutAdmin, true);
WinGetWarningBanner.Title = CoreTools.Translate("Administrator privileges");
WinGetWarningBanner.Message = CoreTools.Translate(
"UniGetUI has been ran as administrator, which is not recommended. When running UniGetUI as administrator, EVERY operation launched from UniGetUI will have administrator privileges. You can still use the program, but we highly recommend not running UniGetUI with administrator privileges."
);
WinGetWarningBanner.IsClosable = true;
WinGetWarningBanner.IsOpen = true;
}
if (!Settings.Get(Settings.K.ShownTelemetryBanner))
{
TelemetryWarner.Title = CoreTools.Translate("Share anonymous usage data");
TelemetryWarner.Message = CoreTools.Translate(
"UniGetUI collects anonymous usage data in order to improve the user experience."
);
TelemetryWarner.IsClosable = true;
TelemetryWarner.ActionButtonText = CoreTools.Translate("Accept");
TelemetryWarner.ActionButtonCommand = new CommunityToolkit.Mvvm.Input.RelayCommand(() =>
{
TelemetryWarner.IsOpen = false;
Settings.Set(Settings.K.ShownTelemetryBanner, true);
});
TelemetryWarner.OnClosed = () => Settings.Set(Settings.K.ShownTelemetryBanner, true);
TelemetryWarner.IsOpen = true;
}
LoadDefaultPage();
}
private void OnAnnouncementRequested(object? _, AccessibilityAnnouncement announcement)
{
AnnouncementLiveSetting = announcement.LiveSetting;
AnnouncementText = string.Empty;
Dispatcher.UIThread.Post(
() => AnnouncementText = announcement.Message,
DispatcherPriority.Background);
}
// ─── Navigation ──────────────────────────────────────────────────────────
public void LoadDefaultPage()
{
PageType type = Settings.GetValue(Settings.K.StartupPage) switch
{
"discover" => PageType.Discover,
"updates" => PageType.Updates,
"installed" => PageType.Installed,
"bundles" => PageType.Bundles,
"settings" => PageType.Settings,
_ => UpgradablePackagesLoader.Instance is { } l && l.Count() > 0 ? PageType.Updates : PageType.Discover,
};
NavigateTo(type);
}
private Control GetPageForType(PageType type) =>
type switch
{
PageType.Discover => DiscoverPage,
PageType.Updates => UpdatesPage,
PageType.Installed => InstalledPage,
PageType.Bundles => BundlesPage,
PageType.Settings => SettingsPage ??= new SettingsBasePage(false),
PageType.Managers => ManagersPage ??= new SettingsBasePage(true),
PageType.OwnLog => UniGetUILogPage ??= new UniGetUILogPage(),
PageType.ManagerLog => ManagerLogPage ??= new ManagerLogsPage(),
PageType.OperationHistory => OperationHistoryPage ??= new OperationHistoryPage(),
PageType.Help => HelpPage ??= new HelpPage(),
PageType.ReleaseNotes => ReleaseNotesPage ??= new ReleaseNotesPage(),
PageType.Null => throw new InvalidOperationException("Page type is Null"),
_ => throw new InvalidDataException($"Unknown page type {type}"),
};
public static PageType GetNextPage(PageType type) =>
type switch
{
PageType.Discover => PageType.Updates,
PageType.Updates => PageType.Installed,
PageType.Installed => PageType.Bundles,
PageType.Bundles => PageType.Settings,
PageType.Settings => PageType.Managers,
PageType.Managers => PageType.Discover,
_ => PageType.Discover,
};
public static PageType GetPreviousPage(PageType type) =>
type switch
{
PageType.Discover => PageType.Managers,
PageType.Updates => PageType.Discover,
PageType.Installed => PageType.Updates,
PageType.Bundles => PageType.Installed,
PageType.Settings => PageType.Bundles,
PageType.Managers => PageType.Settings,
_ => PageType.Discover,
};
public void NavigateTo(PageType newPage_t, bool toHistory = true)
{
if (newPage_t is PageType.About) { _ = ShowAboutDialog(); return; }
if (newPage_t is PageType.Quit) { (Application.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)?.Shutdown(); return; }
if (_currentPage == newPage_t)
{
// Re-focus the primary control even when we're already on the page
(CurrentPageContent as AbstractPackagesPage)?.FocusPackageList();
return;
}
Sidebar.SelectNavButtonForPage(newPage_t);
var newPage = GetPageForType(newPage_t);
var oldPage = CurrentPageContent as Control;
if (oldPage is ISearchBoxPage oldSPage)
oldSPage.QueryBackup = GlobalSearchText;
(oldPage as IEnterLeaveListener)?.OnLeave();
CurrentPageContent = newPage;
_oldPage = _currentPage;
_currentPage = newPage_t;
if (toHistory && _oldPage is not PageType.Null)
{
NavigationHistory.Add(_oldPage);
CanGoBackChanged?.Invoke(this, true);
}
(newPage as AbstractPackagesPage)?.FilterPackages();
(newPage as IEnterLeaveListener)?.OnEnter();
if (newPage is ISearchBoxPage newSPage)
{
SubscribeToPageViewModel(newPage as AbstractPackagesPage);
GlobalSearchText = newSPage.QueryBackup;
GlobalSearchPlaceholder = newSPage.SearchBoxPlaceholder;
GlobalSearchEnabled = true;
}
else
{
SubscribeToPageViewModel(null);
GlobalSearchText = "";
GlobalSearchPlaceholder = "";
GlobalSearchEnabled = false;
}
// Focus after search state is restored so MegaQueryVisible is already correct
(newPage as AbstractPackagesPage)?.FocusPackageList();
AccessibilityAnnouncementService.Announce(GetPageAnnouncement(newPage_t));
CurrentPageChanged?.Invoke(this, newPage_t);
}
private static string GetPageAnnouncement(PageType pageType) => pageType switch
{
PageType.Discover => CoreTools.Translate("Discover Packages"),
PageType.Updates => CoreTools.Translate("Software Updates"),
PageType.Installed => CoreTools.Translate("Installed Packages"),
PageType.Bundles => CoreTools.Translate("Package Bundles"),
PageType.Settings => CoreTools.Translate("Settings"),
PageType.Managers => CoreTools.Translate("Package Managers"),
PageType.OwnLog => CoreTools.Translate("UniGetUI Log"),
PageType.ManagerLog => CoreTools.Translate("Package Manager logs"),
PageType.OperationHistory => CoreTools.Translate("Operation history"),
PageType.Help => CoreTools.Translate("Help"),
PageType.ReleaseNotes => CoreTools.Translate("Release notes"),
_ => CoreTools.Translate("UniGetUI"),
};
public void NavigateBack()
{
if (CurrentPageContent is IInnerNavigationPage navPage && navPage.CanGoBack())
{
navPage.GoBack();
}
else if (NavigationHistory.Count > 0)
{
NavigateTo(NavigationHistory.Last(), toHistory: false);
NavigationHistory.RemoveAt(NavigationHistory.Count - 1);
CanGoBackChanged?.Invoke(this,
NavigationHistory.Count > 0
|| ((CurrentPageContent as IInnerNavigationPage)?.CanGoBack() ?? false));
}
}
public void OpenManagerLogs(IPackageManager? manager = null)
{
NavigateTo(PageType.ManagerLog);
if (manager is not null) ManagerLogPage?.LoadForManager(manager);
}
public void OpenManagerSettings(IPackageManager? manager = null)
{
NavigateTo(PageType.Managers);
if (manager is not null) ManagersPage?.NavigateTo(manager);
}
public void OpenSettingsPage(Type page)
{
NavigateTo(PageType.Settings);
SettingsPage?.NavigateTo(page);
}
public void ShowHelp(string uriAttachment = "")
{
NavigateTo(PageType.Help);
HelpPage?.NavigateTo(uriAttachment);
}
public async Task LoadCloudBundleAsync(string content)
{
NavigateTo(PageType.Bundles);
await BundlesPage.OpenFromString(content, BundleFormatType.UBUNDLE, "GitHub Gist");
}
private async Task ShowAboutDialog()
{
Sidebar.SelectNavButtonForPage(PageType.Null);
var owner = (Application.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)?.MainWindow;
if (owner is not null)
await new AboutWindow().ShowDialog(owner);
Sidebar.SelectNavButtonForPage(_currentPage);
}
// ─── Notification activation ─────────────────────────────────────────────
private void HandleNotificationActivation(string action)
{
if (action == NotificationArguments.UpdateAllPackages)
{
_ = AvaloniaPackageOperationHelper.UpdateAllAsync();
}
else if (action == NotificationArguments.ShowOnUpdatesTab)
{
NavigateTo(PageType.Updates);
MainWindow.Instance?.ShowFromTray();
}
else if (action == NotificationArguments.Show)
{
MainWindow.Instance?.ShowFromTray();
}
else if (action == NotificationArguments.ReleaseSelfUpdateLock)
{
AvaloniaAutoUpdater.ReleaseLockForAutoupdate_Notification = true;
}
}
// ─── Search box ──────────────────────────────────────────────────────────
[RelayCommand]
public void SubmitGlobalSearch()
{
if (CurrentPageContent is ISearchBoxPage page)
page.SearchBox_QuerySubmitted(this, EventArgs.Empty);
}
}