/ src / Ryujinx / UI / Helpers / NotificationHelper.cs
NotificationHelper.cs
 1  using Avalonia;
 2  using Avalonia.Controls;
 3  using Avalonia.Controls.Notifications;
 4  using Avalonia.Threading;
 5  using Ryujinx.Ava.Common.Locale;
 6  using Ryujinx.Common;
 7  using System;
 8  using System.Collections.Concurrent;
 9  using System.Threading;
10  
11  namespace Ryujinx.Ava.UI.Helpers
12  {
13      public static class NotificationHelper
14      {
15          private const int MaxNotifications = 4;
16          private const int NotificationDelayInMs = 5000;
17  
18          private static WindowNotificationManager _notificationManager;
19  
20          private static readonly BlockingCollection<Notification> _notifications = new();
21  
22          public static void SetNotificationManager(Window host)
23          {
24              _notificationManager = new WindowNotificationManager(host)
25              {
26                  Position = NotificationPosition.BottomRight,
27                  MaxItems = MaxNotifications,
28                  Margin = new Thickness(0, 0, 15, 40),
29              };
30  
31              var maybeAsyncWorkQueue = new Lazy<AsyncWorkQueue<Notification>>(
32                  () => new AsyncWorkQueue<Notification>(notification =>
33                      {
34                          Dispatcher.UIThread.Post(() =>
35                          {
36                              _notificationManager.Show(notification);
37                          });
38                      },
39                      "UI.NotificationThread",
40                      _notifications),
41                  LazyThreadSafetyMode.ExecutionAndPublication);
42  
43              _notificationManager.TemplateApplied += (sender, args) =>
44              {
45                  // NOTE: Force creation of the AsyncWorkQueue.
46                  _ = maybeAsyncWorkQueue.Value;
47              };
48  
49              host.Closing += (sender, args) =>
50              {
51                  if (maybeAsyncWorkQueue.IsValueCreated)
52                  {
53                      maybeAsyncWorkQueue.Value.Dispose();
54                  }
55              };
56          }
57  
58          public static void Show(string title, string text, NotificationType type, bool waitingExit = false, Action onClick = null, Action onClose = null)
59          {
60              var delay = waitingExit ? TimeSpan.FromMilliseconds(0) : TimeSpan.FromMilliseconds(NotificationDelayInMs);
61  
62              _notifications.Add(new Notification(title, text, type, delay, onClick, onClose));
63          }
64  
65          public static void ShowError(string message)
66          {
67              Show(LocaleManager.Instance[LocaleKeys.DialogErrorTitle], $"{LocaleManager.Instance[LocaleKeys.DialogErrorMessage]}\n\n{message}", NotificationType.Error);
68          }
69      }
70  }