-
-
Notifications
You must be signed in to change notification settings - Fork 591
Expand file tree
/
Copy pathProgressManagerViewModel.cs
More file actions
414 lines (365 loc) · 15.9 KB
/
Copy pathProgressManagerViewModel.cs
File metadata and controls
414 lines (365 loc) · 15.9 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using AsyncAwaitBestPractices;
using Avalonia.Collections;
using Avalonia.Controls.Notifications;
using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using FluentAvalonia.UI.Controls;
using FluentAvalonia.UI.Media.Animation;
using FluentIcons.Common;
using Injectio.Attributes;
using StabilityMatrix.Avalonia.Controls;
using StabilityMatrix.Avalonia.Languages;
using StabilityMatrix.Avalonia.Services;
using StabilityMatrix.Avalonia.ViewModels.Base;
using StabilityMatrix.Avalonia.ViewModels.Settings;
using StabilityMatrix.Avalonia.Views;
using StabilityMatrix.Core.Attributes;
using StabilityMatrix.Core.Exceptions;
using StabilityMatrix.Core.Helper;
using StabilityMatrix.Core.Models;
using StabilityMatrix.Core.Models.Notifications;
using StabilityMatrix.Core.Models.PackageModification;
using StabilityMatrix.Core.Models.Progress;
using StabilityMatrix.Core.Models.Settings;
using StabilityMatrix.Core.Services;
using Notification = DesktopNotifications.Notification;
using Symbol = FluentIcons.Common.Symbol;
using SymbolIconSource = FluentIcons.Avalonia.Fluent.SymbolIconSource;
namespace StabilityMatrix.Avalonia.ViewModels.Progress;
[View(typeof(ProgressManagerPage))]
[ManagedService]
[RegisterSingleton<ProgressManagerViewModel>]
public partial class ProgressManagerViewModel : PageViewModelBase
{
private readonly ITrackedDownloadService trackedDownloadService;
private readonly INotificationService notificationService;
private readonly INavigationService<MainWindowViewModel> navigationService;
private readonly INavigationService<SettingsViewModel> settingsNavService;
private readonly INotificationHistoryService notificationHistory;
private readonly INotificationActionDispatcher actionDispatcher;
public override string Title => Resources.Label_Activity;
public override IconSource IconSource =>
new SymbolIconSource { Symbol = Symbol.History, IconVariant = IconVariant.Filled };
public AvaloniaList<ProgressItemViewModelBase> ProgressItems { get; } = new();
public AvaloniaList<NotificationItemViewModel> NotificationItems { get; } = new();
[ObservableProperty]
private bool isOpen;
[ObservableProperty]
private int unreadNotificationCount;
[ObservableProperty]
private int selectedTabIndex;
/// <summary>
/// Pick the most-useful tab to show on flyout open: stay on In Progress if there's any active
/// download/install, otherwise jump to Notifications when only history is present.
/// </summary>
public void RecomputePreferredTab()
{
if (ProgressItems.Count == 0 && NotificationItems.Count > 0)
{
SelectedTabIndex = 1;
}
else
{
SelectedTabIndex = 0;
}
}
/// <summary>True when either tab has any content — used to decide whether the footer flyout is reachable.</summary>
public bool HasAnyContent => ProgressItems.Count > 0 || NotificationItems.Count > 0;
/// <summary>Combined counter rendered in the footer InfoBadge.</summary>
public int TotalBadgeCount => ProgressItems.Count + UnreadNotificationCount;
/// <summary>Explicit bool so the InfoBadge can hide cleanly when nothing is pending.</summary>
public bool IsBadgeVisible => TotalBadgeCount > 0;
public ProgressManagerViewModel(
ITrackedDownloadService trackedDownloadService,
INotificationService notificationService,
INavigationService<MainWindowViewModel> navigationService,
INavigationService<SettingsViewModel> settingsNavService,
INotificationHistoryService notificationHistory,
INotificationActionDispatcher actionDispatcher
)
{
this.trackedDownloadService = trackedDownloadService;
this.notificationService = notificationService;
this.navigationService = navigationService;
this.settingsNavService = settingsNavService;
this.notificationHistory = notificationHistory;
this.actionDispatcher = actionDispatcher;
// Attach to the event
trackedDownloadService.DownloadAdded += TrackedDownloadService_OnDownloadAdded;
EventManager.Instance.ToggleProgressFlyout += (_, _) => IsOpen = !IsOpen;
EventManager.Instance.PackageInstallProgressAdded += InstanceOnPackageInstallProgressAdded;
EventManager.Instance.RecommendedModelsDialogClosed += InstanceOnRecommendedModelsDialogClosed;
// Hydrate notifications (entries are stored newest-first)
foreach (var entry in notificationHistory.Entries)
{
NotificationItems.Add(
new NotificationItemViewModel(entry, notificationHistory, actionDispatcher)
);
}
notificationHistory.EntryAdded += OnHistoryEntryAdded;
notificationHistory.EntriesChanged += OnHistoryChanged;
ProgressItems.CollectionChanged += (_, _) =>
{
OnPropertyChanged(nameof(HasAnyContent));
OnPropertyChanged(nameof(TotalBadgeCount));
OnPropertyChanged(nameof(IsBadgeVisible));
};
NotificationItems.CollectionChanged += (_, _) =>
{
OnPropertyChanged(nameof(HasAnyContent));
};
UnreadNotificationCount = notificationHistory.UnreadCount;
}
private void OnHistoryEntryAdded(object? sender, NotificationHistoryEntry entry)
{
Dispatcher.UIThread.Post(() =>
{
NotificationItems.Insert(
0,
new NotificationItemViewModel(entry, notificationHistory, actionDispatcher)
);
// The service evicts the oldest entry (from the tail) once it hits its cap; mirror
// that here so the UI list stays in sync instead of growing unbounded.
while (NotificationItems.Count > notificationHistory.Count)
{
NotificationItems.RemoveAt(NotificationItems.Count - 1);
}
UnreadNotificationCount = notificationHistory.UnreadCount;
});
}
private void OnHistoryChanged(object? sender, EventArgs e)
{
Dispatcher.UIThread.Post(() =>
{
// Drop any entries that were evicted from the underlying service
var liveIds = notificationHistory.Entries.Select(x => x.Id).ToHashSet();
for (var i = NotificationItems.Count - 1; i >= 0; i--)
{
if (!liveIds.Contains(NotificationItems[i].Id))
{
NotificationItems.RemoveAt(i);
}
}
foreach (var item in NotificationItems)
{
item.RefreshReadState();
}
UnreadNotificationCount = notificationHistory.UnreadCount;
});
}
partial void OnUnreadNotificationCountChanged(int value)
{
OnPropertyChanged(nameof(TotalBadgeCount));
OnPropertyChanged(nameof(IsBadgeVisible));
}
[RelayCommand]
private void ClearNotifications() => notificationHistory.Clear();
[RelayCommand]
private void MarkAllNotificationsRead() => notificationHistory.MarkAllRead();
private void InstanceOnRecommendedModelsDialogClosed(object? sender, EventArgs e)
{
var vm = ProgressItems.OfType<PackageInstallProgressItemViewModel>().FirstOrDefault();
vm?.ShowProgressDialog().SafeFireAndForget();
}
private void InstanceOnPackageInstallProgressAdded(object? sender, IPackageModificationRunner runner)
{
AddPackageInstall(runner).SafeFireAndForget();
}
private void TrackedDownloadService_OnDownloadAdded(object? sender, TrackedDownload e)
{
// Attach notification handlers
// Use Changing because Changed might be called after the download is removed
e.ProgressStateChanged += (s, state) =>
{
Debug.WriteLine($"Download {e.FileName} state changed to {state}");
var download = s as TrackedDownload;
switch (state)
{
case ProgressState.Success:
var imageFile = e
.DownloadDirectory.EnumerateFiles(
$"{Path.GetFileNameWithoutExtension(e.FileName)}.preview.*"
)
.FirstOrDefault();
notificationService
.ShowAsync(
NotificationKey.Download_Completed,
new Notification
{
Title = "Download Completed",
Body = $"Download of {e.FileName} completed successfully.",
BodyImagePath = imageFile?.FullPath,
},
action: new OpenFolderAction(e.DownloadDirectory.FullPath)
)
.SafeFireAndForget();
break;
case ProgressState.Failed:
var msg = "";
if (download?.Exception is { } exception)
{
msg =
$"({exception.GetType().Name}) {exception.InnerException?.Message ?? exception.Message}";
if (
exception is EarlyAccessException
|| exception.InnerException is EarlyAccessException
)
{
msg =
"This asset is in Early Access. Please check the asset page for more information.";
}
else if (
exception is CivitLoginRequiredException
|| exception.InnerException is CivitLoginRequiredException
)
{
ShowCivitLoginRequiredDialog();
return;
}
else if (
exception is HuggingFaceLoginRequiredException
|| exception.InnerException is HuggingFaceLoginRequiredException
)
{
ShowHuggingFaceLoginRequiredDialog();
return;
}
else if (
exception is CivitDownloadDisabledException
|| exception.InnerException is CivitDownloadDisabledException
)
{
Dispatcher.UIThread.InvokeAsync(async () =>
await notificationService.ShowPersistentAsync(
NotificationKey.Download_Failed,
new Notification
{
Title = "Download Disabled",
Body =
$"The creator of {e.FileName} has disabled downloads on this file",
},
action: new ToggleProgressFlyoutAction()
)
);
return;
}
}
Dispatcher.UIThread.InvokeAsync(async () =>
await notificationService.ShowPersistentAsync(
NotificationKey.Download_Failed,
new Notification
{
Title = "Download Failed",
Body = $"Download of {e.FileName} failed: {msg}",
},
action: new ToggleProgressFlyoutAction()
)
);
break;
case ProgressState.Cancelled:
notificationService
.ShowAsync(
NotificationKey.Download_Canceled,
new Notification
{
Title = "Download Cancelled",
Body = $"Download of {e.FileName} was cancelled.",
}
)
.SafeFireAndForget();
break;
}
};
var vm = new DownloadProgressItemViewModel(trackedDownloadService, e);
ProgressItems.Add(vm);
}
private void ShowCivitLoginRequiredDialog()
{
Dispatcher.UIThread.InvokeAsync(async () =>
{
var errorDialog = new BetterContentDialog
{
Title = Resources.Label_DownloadFailed,
Content = Resources.Label_CivitAiLoginRequired,
PrimaryButtonText = "Go to Settings",
SecondaryButtonText = "Close",
DefaultButton = ContentDialogButton.Primary,
};
var result = await errorDialog.ShowAsync();
if (result == ContentDialogResult.Primary)
{
navigationService.NavigateTo<SettingsViewModel>(new SuppressNavigationTransitionInfo());
await Task.Delay(100);
settingsNavService.NavigateTo<AccountSettingsViewModel>(
new SuppressNavigationTransitionInfo()
);
}
});
}
private void ShowHuggingFaceLoginRequiredDialog()
{
Dispatcher.UIThread.InvokeAsync(async () =>
{
var errorDialog = new BetterContentDialog
{
Title = Resources.Label_DownloadFailed,
Content = Resources.Label_HuggingFaceLoginRequired,
PrimaryButtonText = "Go to Settings",
SecondaryButtonText = "Close",
DefaultButton = ContentDialogButton.Primary,
};
var result = await errorDialog.ShowAsync();
if (result == ContentDialogResult.Primary)
{
navigationService.NavigateTo<SettingsViewModel>(new SuppressNavigationTransitionInfo());
await Task.Delay(100);
settingsNavService.NavigateTo<AccountSettingsViewModel>(
new SuppressNavigationTransitionInfo()
);
}
});
}
public void AddDownloads(IEnumerable<TrackedDownload> downloads)
{
foreach (var download in downloads)
{
if (ProgressItems.Any(vm => vm.Id == download.Id))
continue;
var vm = new DownloadProgressItemViewModel(trackedDownloadService, download);
ProgressItems.Add(vm);
}
}
private Task AddPackageInstall(IPackageModificationRunner packageModificationRunner)
{
if (ProgressItems.Any(vm => vm.Id == packageModificationRunner.Id))
return Task.CompletedTask;
var vm = new PackageInstallProgressItemViewModel(packageModificationRunner);
ProgressItems.Add(vm);
return packageModificationRunner.ShowDialogOnStart ? vm.ShowProgressDialog() : Task.CompletedTask;
}
private void ShowFailedNotification(string title, string message)
{
notificationService.ShowPersistent(title, message, NotificationType.Error);
}
public void StartEventListener()
{
EventManager.Instance.ProgressChanged += OnProgressChanged;
}
public void ClearDownloads()
{
ProgressItems.RemoveAll(ProgressItems.Where(x => x.IsClearable));
}
private void OnProgressChanged(object? sender, ProgressItem e)
{
if (ProgressItems.Any(x => x.Id == e.ProgressId))
return;
ProgressItems.Add(new ProgressItemViewModel(e));
}
}