NotificationHelper.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using Avalonia;
  2. using Avalonia.Controls;
  3. using Avalonia.Controls.Notifications;
  4. using Avalonia.Threading;
  5. using Ryujinx.Ava.Common.Locale;
  6. using System;
  7. using System.Collections.Concurrent;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. namespace Ryujinx.Ava.UI.Helpers
  11. {
  12. public static class NotificationHelper
  13. {
  14. private const int MaxNotifications = 4;
  15. private const int NotificationDelayInMs = 5000;
  16. private static WindowNotificationManager _notificationManager;
  17. private static readonly ManualResetEvent _templateAppliedEvent = new(false);
  18. private static readonly BlockingCollection<Notification> _notifications = new();
  19. public static void SetNotificationManager(Window host)
  20. {
  21. _notificationManager = new WindowNotificationManager(host)
  22. {
  23. Position = NotificationPosition.BottomRight,
  24. MaxItems = MaxNotifications,
  25. Margin = new Thickness(0, 0, 15, 40)
  26. };
  27. _notificationManager.TemplateApplied += (sender, args) =>
  28. {
  29. _templateAppliedEvent.Set();
  30. };
  31. Task.Run(async () =>
  32. {
  33. _templateAppliedEvent.WaitOne();
  34. foreach (var notification in _notifications.GetConsumingEnumerable())
  35. {
  36. Dispatcher.UIThread.Post(() =>
  37. {
  38. _notificationManager.Show(notification);
  39. });
  40. await Task.Delay(NotificationDelayInMs / MaxNotifications);
  41. }
  42. });
  43. }
  44. public static void Show(string title, string text, NotificationType type, bool waitingExit = false, Action onClick = null, Action onClose = null)
  45. {
  46. var delay = waitingExit ? TimeSpan.FromMilliseconds(0) : TimeSpan.FromMilliseconds(NotificationDelayInMs);
  47. _notifications.Add(new Notification(title, text, type, delay, onClick, onClose));
  48. }
  49. public static void ShowError(string message)
  50. {
  51. Show(LocaleManager.Instance[LocaleKeys.DialogErrorTitle], $"{LocaleManager.Instance[LocaleKeys.DialogErrorMessage]}\n\n{message}", NotificationType.Error);
  52. }
  53. }
  54. }