Skip to content

Commit 9d79b42

Browse files
authored
Implement toast notifications and enhance operations panel feedback (#5065)
1 parent 4014277 commit 9d79b42

13 files changed

Lines changed: 381 additions & 133 deletions

File tree

‎src/Languages/lang_en.json‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -850,5 +850,9 @@
850850
"Log in failed: ": "Log in failed: ",
851851
"Log out failed: ": "Log out failed: ",
852852
"Package backup settings": "Package backup settings",
853-
"Show the release notes after UniGetUI is updated": "Show the release notes after UniGetUI is updated"
853+
"Show the release notes after UniGetUI is updated": "Show the release notes after UniGetUI is updated",
854+
"Operations completed": "Operations completed",
855+
"Operations finished with errors": "Operations finished with errors",
856+
"{0} of {1} succeeded, {2} failed": "{0} of {1} succeeded, {2} failed",
857+
"Show an in-app summary toast when a batch of operations finishes": "Show an in-app summary toast when a batch of operations finishes"
854858
}
Lines changed: 3 additions & 0 deletions
Loading

‎src/UniGetUI.Avalonia/Assets/Styles/Styles.Common.axaml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,9 @@
8585
<SolidColorBrush x:Key="SettingWarningTextForeground" Color="#9D5D00"/>
8686
<!-- Operation log output text -->
8787
<SolidColorBrush x:Key="LogOutputVerboseForeground" Color="#5C5C5C"/>
88+
<!-- Toast: failure-badge red and drop shadow (light) -->
89+
<SolidColorBrush x:Key="ToastBadgeBrush" Color="#C42B1C"/>
90+
<BoxShadows x:Key="ToastShadow">0 4 16 0 #33000000</BoxShadows>
8891
</ResourceDictionary>
8992
<ResourceDictionary x:Key="Dark">
9093
<!-- Accent fills (lighter accents on dark bg) -->
@@ -164,6 +167,9 @@
164167
<SolidColorBrush x:Key="SettingWarningTextForeground" Color="#FCE100"/>
165168
<!-- Operation log output text -->
166169
<SolidColorBrush x:Key="LogOutputVerboseForeground" Color="#9D9D9D"/>
170+
<!-- Toast: failure-badge red and drop shadow (dark) -->
171+
<SolidColorBrush x:Key="ToastBadgeBrush" Color="#FF5449"/>
172+
<BoxShadows x:Key="ToastShadow">0 4 18 0 #80000000</BoxShadows>
167173
</ResourceDictionary>
168174
</ResourceDictionary.ThemeDictionaries>
169175
</ResourceDictionary>

‎src/UniGetUI.Avalonia/Infrastructure/AvaloniaOperationRegistry.cs‎

Lines changed: 6 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -196,19 +196,8 @@ private static void ShowOperationProgressNotification(AbstractOperation op)
196196
$"{title}. {message}",
197197
AutomationLiveSetting.Polite);
198198

199-
if (OperatingSystem.IsWindows() && WindowsAppNotificationBridge.ShowProgress(op))
200-
return;
201-
202-
if (OperatingSystem.IsMacOS() && MacOsNotificationBridge.ShowProgress(op))
203-
return;
204-
205-
if (TryGetMainWindow() is not { } mainWindow)
206-
return;
207-
208-
mainWindow.ShowRuntimeNotification(
209-
title,
210-
message,
211-
UniGetUI.Avalonia.Views.MainWindow.RuntimeNotificationLevel.Progress);
199+
if (OperatingSystem.IsWindows()) WindowsAppNotificationBridge.ShowProgress(op);
200+
else if (OperatingSystem.IsMacOS()) MacOsNotificationBridge.ShowProgress(op);
212201
}
213202

214203
private static void ShowOperationSuccessNotification(AbstractOperation op)
@@ -230,11 +219,8 @@ private static void ShowOperationSuccessNotification(AbstractOperation op)
230219

231220
WindowsAppNotificationBridge.RemoveProgress(op);
232221

233-
if (OperatingSystem.IsWindows() && WindowsAppNotificationBridge.ShowSuccess(op))
234-
return;
235-
236-
if (OperatingSystem.IsMacOS() && MacOsNotificationBridge.ShowSuccess(op))
237-
return;
222+
if (OperatingSystem.IsWindows()) WindowsAppNotificationBridge.ShowSuccess(op);
223+
else if (OperatingSystem.IsMacOS()) MacOsNotificationBridge.ShowSuccess(op);
238224
}
239225

240226
private static void ShowOperationFailureNotification(AbstractOperation op)
@@ -256,27 +242,8 @@ private static void ShowOperationFailureNotification(AbstractOperation op)
256242

257243
WindowsAppNotificationBridge.RemoveProgress(op);
258244

259-
if (OperatingSystem.IsWindows() && WindowsAppNotificationBridge.ShowError(op))
260-
return;
261-
262-
if (OperatingSystem.IsMacOS() && MacOsNotificationBridge.ShowError(op))
263-
return;
264-
265-
if (TryGetMainWindow() is not { } mainWindow)
266-
return;
267-
268-
mainWindow.ShowRuntimeNotification(
269-
title,
270-
message,
271-
UniGetUI.Avalonia.Views.MainWindow.RuntimeNotificationLevel.Error);
272-
}
273-
274-
private static UniGetUI.Avalonia.Views.MainWindow? TryGetMainWindow()
275-
{
276-
return Application.Current?.ApplicationLifetime
277-
is IClassicDesktopStyleApplicationLifetime { MainWindow: UniGetUI.Avalonia.Views.MainWindow mw }
278-
? mw
279-
: null;
245+
if (OperatingSystem.IsWindows()) WindowsAppNotificationBridge.ShowError(op);
246+
else if (OperatingSystem.IsMacOS()) MacOsNotificationBridge.ShowError(op);
280247
}
281248

282249
private static void AppendOperationHistory(AbstractOperation op)

‎src/UniGetUI.Avalonia/Infrastructure/WindowsAppNotificationBridge.cs‎

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,10 @@ namespace UniGetUI.Avalonia.Infrastructure;
1818
/// single-instance handler foregrounds the window. The inline action buttons carried
1919
/// by the old WinRT toasts are intentionally dropped; activation is surfaced via
2020
/// <see cref="NotificationActivated"/> only when the app is already running and the toast
21-
/// is clicked, so the main-window view model keeps its handler. On non-Windows, or if
22-
/// the toast COM surface is unavailable, every call falls back to the in-app Avalonia
23-
/// banner via <see cref="MainWindow.ShowRuntimeNotification"/>.
21+
/// is clicked, so the main-window view model keeps its handler. When the toast COM surface
22+
/// is unavailable, feature notifications fall back to the in-app Avalonia banner via
23+
/// <see cref="MainWindow.ShowRuntimeNotification"/>; per-operation results do not (they
24+
/// already appear in the operations panel — see the <c>allowInAppFallback</c> flag on Show).
2425
/// </summary>
2526
internal static class WindowsAppNotificationBridge
2627
{
@@ -64,7 +65,7 @@ public static bool ShowProgress(AbstractOperation operation)
6465
? operation.Metadata.Status
6566
: CoreTools.Translate("Please wait...");
6667

67-
return Show(title, message, MainWindow.RuntimeNotificationLevel.Progress, launchAction: NotificationArguments.Show);
68+
return Show(title, message, MainWindow.RuntimeNotificationLevel.Progress, launchAction: NotificationArguments.Show, allowInAppFallback: false);
6869
}
6970

7071
public static bool ShowSuccess(AbstractOperation operation)
@@ -77,7 +78,7 @@ public static bool ShowSuccess(AbstractOperation operation)
7778
? operation.Metadata.SuccessMessage
7879
: CoreTools.Translate("Success!");
7980

80-
return Show(title, message, MainWindow.RuntimeNotificationLevel.Success, launchAction: NotificationArguments.Show);
81+
return Show(title, message, MainWindow.RuntimeNotificationLevel.Success, launchAction: NotificationArguments.Show, allowInAppFallback: false);
8182
}
8283

8384
public static bool ShowError(AbstractOperation operation)
@@ -90,7 +91,7 @@ public static bool ShowError(AbstractOperation operation)
9091
? operation.Metadata.FailureMessage
9192
: CoreTools.Translate("An error occurred while processing this package");
9293

93-
return Show(title, message, MainWindow.RuntimeNotificationLevel.Error, launchAction: NotificationArguments.Show);
94+
return Show(title, message, MainWindow.RuntimeNotificationLevel.Error, launchAction: NotificationArguments.Show, allowInAppFallback: false);
9495
}
9596

9697
public static void RemoveProgress(AbstractOperation operation)
@@ -258,12 +259,15 @@ public static void ShowNewShortcutsNotification(IReadOnlyList<string> shortcuts)
258259
/// argument so the single-instance handler can route the activation when the toast
259260
/// is clicked. Returns <c>true</c> once the notification has been surfaced (toast or
260261
/// banner), so callers skip their own fallback banner and avoid double-showing.
262+
/// <paramref name="allowInAppFallback"/> is <c>false</c> for per-operation results:
263+
/// those already live in the operations panel, so we don't duplicate them as a toast.
261264
/// </summary>
262265
private static bool Show(
263266
string title,
264267
string message,
265268
MainWindow.RuntimeNotificationLevel level,
266-
string launchAction)
269+
string launchAction,
270+
bool allowInAppFallback = true)
267271
{
268272
#if WINDOWS
269273
if (OperatingSystem.IsWindows() && Win32ToastNotifier.IsAvailable())
@@ -281,7 +285,7 @@ private static bool Show(
281285
}
282286
#endif
283287

284-
return ShowInAppBanner(title, message, level);
288+
return allowInAppFallback && ShowInAppBanner(title, message, level);
285289
}
286290

287291
private static bool ShowInAppBanner(

‎src/UniGetUI.Avalonia/ViewModels/MainWindowViewModel.cs‎

Lines changed: 173 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
using System.Collections.ObjectModel;
12
using System.Collections.Specialized;
23
using Avalonia;
34
using Avalonia.Automation;
@@ -63,12 +64,24 @@ public partial class MainWindowViewModel : ViewModelBase
6364
public AvaloniaList<OperationViewModel> Operations => AvaloniaOperationRegistry.OperationViewModels;
6465

6566
[ObservableProperty]
67+
[NotifyPropertyChangedFor(nameof(ShowFailedOperationBadge))]
6668
private bool _operationsPanelVisible;
6769

6870
[ObservableProperty]
71+
[NotifyPropertyChangedFor(nameof(ShowFailedOperationBadge))]
6972
private bool _operationsPanelExpanded = true;
7073

7174
private readonly List<AbstractOperation> _operationBatch = new();
75+
private bool _batchSummaryShown;
76+
77+
public bool HasFailedOperations => Operations.Any(o => o.Operation.Status is OperationStatus.Failed);
78+
79+
public OperationViewModel? FirstFailedOperation =>
80+
Operations.FirstOrDefault(o => o.Operation.Status is OperationStatus.Failed);
81+
82+
// Red badge on the chevron when the panel is collapsed and an operation failed
83+
// (failures no longer pop a toast; expanded, the failure is already visible).
84+
public bool ShowFailedOperationBadge => OperationsPanelVisible && !OperationsPanelExpanded && HasFailedOperations;
7285

7386
public string OperationsHeaderText
7487
{
@@ -91,6 +104,7 @@ private void AddToBatch(AbstractOperation op)
91104
foreach (var old in _operationBatch)
92105
old.StatusChanged -= OnOperationStatusChanged;
93106
_operationBatch.Clear();
107+
_batchSummaryShown = false;
94108
}
95109

96110
if (!_operationBatch.Contains(op))
@@ -101,7 +115,42 @@ private void AddToBatch(AbstractOperation op)
101115
}
102116

103117
private void OnOperationStatusChanged(object? sender, OperationStatus e)
104-
=> Dispatcher.UIThread.Post(() => OnPropertyChanged(nameof(OperationsHeaderText)));
118+
=> Dispatcher.UIThread.Post(() =>
119+
{
120+
OnPropertyChanged(nameof(OperationsHeaderText));
121+
OnPropertyChanged(nameof(HasFailedOperations));
122+
OnPropertyChanged(nameof(ShowFailedOperationBadge));
123+
MaybeShowBatchSummaryToast();
124+
});
125+
126+
// Opt-in: one toast summarizing the batch once every operation in it has finished.
127+
private void MaybeShowBatchSummaryToast()
128+
{
129+
if (_batchSummaryShown || _operationBatch.Count == 0) return;
130+
if (!Settings.Get(Settings.K.ShowOperationSummaryNotifications)) return;
131+
if (_operationBatch.Any(o => o.Status is OperationStatus.InQueue or OperationStatus.Running)) return;
132+
133+
_batchSummaryShown = true;
134+
135+
int total = _operationBatch.Count;
136+
int failed = _operationBatch.Count(o => o.Status is OperationStatus.Failed);
137+
int succeeded = _operationBatch.Count(o => o.Status is OperationStatus.Succeeded);
138+
139+
var toast = new InfoBarViewModel
140+
{
141+
Title = failed > 0
142+
? CoreTools.Translate("Operations finished with errors")
143+
: CoreTools.Translate("Operations completed"),
144+
Message = failed > 0
145+
? CoreTools.Translate("{0} of {1} succeeded, {2} failed", succeeded, total, failed)
146+
: CoreTools.Translate("{0} of {1} operations completed", succeeded, total),
147+
Severity = failed > 0 ? InfoBarSeverity.Error : InfoBarSeverity.Success,
148+
IsClosable = true,
149+
IsOpen = true,
150+
};
151+
toast.OnClosed = () => DismissToast(toast);
152+
ShowToast(toast);
153+
}
105154

106155
[RelayCommand]
107156
private void ToggleOperationsPanel() => OperationsPanelExpanded = !OperationsPanelExpanded;
@@ -169,12 +218,126 @@ private void OnPageViewModelPropertyChanged(object? sender, System.ComponentMode
169218
? $"UniGetUI {CoreTools.Translate("version {0}", CoreData.VersionName)}"
170219
: "UniGetUI";
171220

172-
// ─── Banners ─────────────────────────────────────────────────────────────
221+
// ─── Notifications (bottom-right toasts) ───────────────────────────────────
222+
// Persistent banners kept as singletons; RegisterBannerToast mirrors their IsOpen into Toasts.
173223
public InfoBarViewModel UpdatesBanner { get; } = new() { Severity = InfoBarSeverity.Success };
174-
public InfoBarViewModel ErrorBanner { get; } = new() { Severity = InfoBarSeverity.Error };
175224
public InfoBarViewModel WinGetWarningBanner { get; } = new() { Severity = InfoBarSeverity.Warning };
176225
public InfoBarViewModel TelemetryWarner { get; } = new() { Severity = InfoBarSeverity.Informational };
177226

227+
// Oldest first (rendered bottom-up so the newest sits nearest the corner).
228+
public ObservableCollection<InfoBarViewModel> Toasts { get; } = new();
229+
private readonly Dictionary<InfoBarViewModel, DispatcherTimer> _toastTimers = new();
230+
private const int MaxVisibleToasts = 5;
231+
232+
// A toast with an action button stays until acted on; everything else auto-dismisses.
233+
private static bool IsSticky(InfoBarViewModel t) => !string.IsNullOrEmpty(t.ActionButtonText);
234+
private static TimeSpan ToastDuration(InfoBarViewModel t)
235+
=> t.Severity is InfoBarSeverity.Error or InfoBarSeverity.Warning
236+
? TimeSpan.FromSeconds(8)
237+
: TimeSpan.FromSeconds(5);
238+
239+
public void ShowToast(InfoBarViewModel toast)
240+
{
241+
if (!Dispatcher.UIThread.CheckAccess())
242+
{
243+
Dispatcher.UIThread.Post(() => ShowToast(toast));
244+
return;
245+
}
246+
if (!Toasts.Contains(toast))
247+
{
248+
Toasts.Add(toast);
249+
AnnounceToast(toast);
250+
}
251+
TrimToastStack(keep: toast);
252+
ArmToastTimer(toast);
253+
}
254+
255+
// Keep the stack from overflowing the screen: drop the oldest auto-dismissing toasts,
256+
// but never a sticky (action-button) one or the toast just shown.
257+
private void TrimToastStack(InfoBarViewModel keep)
258+
{
259+
while (Toasts.Count > MaxVisibleToasts)
260+
{
261+
var oldest = Toasts.FirstOrDefault(t => t != keep && !IsSticky(t));
262+
if (oldest is null) break;
263+
DismissToast(oldest);
264+
}
265+
}
266+
267+
// Surface the toast to screen readers via the live region (assertive for errors so it
268+
// interrupts, polite otherwise) — the toast's own automation name isn't announced on its own.
269+
private static void AnnounceToast(InfoBarViewModel toast)
270+
{
271+
string message = string.IsNullOrEmpty(toast.Message)
272+
? toast.Title
273+
: $"{toast.Title}. {toast.Message}";
274+
AccessibilityAnnouncementService.Announce(
275+
message,
276+
toast.Severity is InfoBarSeverity.Error
277+
? AutomationLiveSetting.Assertive
278+
: AutomationLiveSetting.Polite);
279+
}
280+
281+
public void DismissToast(InfoBarViewModel toast)
282+
{
283+
if (!Dispatcher.UIThread.CheckAccess())
284+
{
285+
Dispatcher.UIThread.Post(() => DismissToast(toast));
286+
return;
287+
}
288+
DisposeToastTimer(toast);
289+
Toasts.Remove(toast);
290+
}
291+
292+
// Pause the auto-dismiss countdown while the pointer hovers a toast; restart it on leave.
293+
public void PauseToast(InfoBarViewModel toast)
294+
{
295+
if (_toastTimers.TryGetValue(toast, out var timer)) timer.Stop();
296+
}
297+
298+
public void ResumeToast(InfoBarViewModel toast)
299+
{
300+
if (_toastTimers.TryGetValue(toast, out var timer)) { timer.Stop(); timer.Start(); }
301+
}
302+
303+
private void ArmToastTimer(InfoBarViewModel toast)
304+
{
305+
DisposeToastTimer(toast);
306+
if (IsSticky(toast))
307+
return;
308+
309+
var timer = new DispatcherTimer { Interval = ToastDuration(toast) };
310+
timer.Tick += (_, _) => toast.IsOpen = false;
311+
_toastTimers[toast] = timer;
312+
timer.Start();
313+
}
314+
315+
private void DisposeToastTimer(InfoBarViewModel toast)
316+
{
317+
if (_toastTimers.Remove(toast, out var timer))
318+
timer.Stop();
319+
}
320+
321+
// Mirrors a persistent banner's IsOpen into Toasts so code that just flips IsOpen keeps working.
322+
private void RegisterBannerToast(InfoBarViewModel banner)
323+
{
324+
banner.PropertyChanged += (_, e) =>
325+
{
326+
if (e.PropertyName == nameof(InfoBarViewModel.IsOpen))
327+
{
328+
if (banner.IsOpen) ShowToast(banner);
329+
else DismissToast(banner);
330+
}
331+
// Content can change in place while the banner stays open (the updater cycles
332+
// statuses on the same banner, finally adding the "Update now" action); re-arm so
333+
// stickiness/countdown track the new content instead of a stale timer dismissing it.
334+
else if (banner.IsOpen && Toasts.Contains(banner))
335+
{
336+
ArmToastTimer(banner);
337+
}
338+
};
339+
}
340+
178341
// ─── Constructor ─────────────────────────────────────────────────────────
179342
[RelayCommand]
180343
private void ToggleSidebar() => Sidebar.IsPaneOpen = !Sidebar.IsPaneOpen;
@@ -183,6 +346,11 @@ public MainWindowViewModel()
183346
{
184347
AccessibilityAnnouncementService.AnnouncementRequested += OnAnnouncementRequested;
185348

349+
// Wire before the blocks below flip the banners' IsOpen flags.
350+
RegisterBannerToast(UpdatesBanner);
351+
RegisterBannerToast(WinGetWarningBanner);
352+
RegisterBannerToast(TelemetryWarner);
353+
186354
DiscoverPage = new DiscoverSoftwarePage();
187355
UpdatesPage = new SoftwareUpdatesPage();
188356
InstalledPage = new InstalledPackagesPage();
@@ -264,6 +432,8 @@ public MainWindowViewModel()
264432
AddToBatch(vm.Operation);
265433
OperationsPanelVisible = Operations.Count > 0;
266434
OnPropertyChanged(nameof(OperationsHeaderText));
435+
OnPropertyChanged(nameof(HasFailedOperations));
436+
OnPropertyChanged(nameof(ShowFailedOperationBadge));
267437
};
268438

269439
if (OperatingSystem.IsWindows() && CoreTools.IsAdministrator() && !Settings.Get(Settings.K.AlreadyWarnedAboutAdmin))

0 commit comments

Comments
 (0)