aboutsummaryrefslogtreecommitdiff
path: root/src/Ryujinx.Ava/UI/Helpers/NotificationHelper.cs
blob: 7e2afb8bd987abcc2e65fb4e819fed2c8360f060 (plain) (blame)
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
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Notifications;
using Avalonia.Threading;
using Ryujinx.Ava.Common.Locale;
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;

namespace Ryujinx.Ava.UI.Helpers
{
    public static class NotificationHelper
    {
        private const int MaxNotifications      = 4; 
        private const int NotificationDelayInMs = 5000;

        private static WindowNotificationManager _notificationManager;

        private static readonly ManualResetEvent                 _templateAppliedEvent = new(false);
        private static readonly BlockingCollection<Notification> _notifications        = new();

        public static void SetNotificationManager(Window host)
        {
            _notificationManager = new WindowNotificationManager(host)
            {
                Position = NotificationPosition.BottomRight,
                MaxItems = MaxNotifications,
                Margin   = new Thickness(0, 0, 15, 40)
            };

            _notificationManager.TemplateApplied += (sender, args) =>
            {
                _templateAppliedEvent.Set();
            };

            Task.Run(async () =>
            {
                _templateAppliedEvent.WaitOne();

                foreach (var notification in _notifications.GetConsumingEnumerable())
                {
                    Dispatcher.UIThread.Post(() =>
                    {
                        _notificationManager.Show(notification);
                    });

                    await Task.Delay(NotificationDelayInMs / MaxNotifications);
                }
            });
        }

        public static void Show(string title, string text, NotificationType type, bool waitingExit = false, Action onClick = null, Action onClose = null)
        {
            var delay = waitingExit ? TimeSpan.FromMilliseconds(0) : TimeSpan.FromMilliseconds(NotificationDelayInMs);

            _notifications.Add(new Notification(title, text, type, delay, onClick, onClose));
        }

        public static void ShowError(string message)
        {
            Show(LocaleManager.Instance[LocaleKeys.DialogErrorTitle], $"{LocaleManager.Instance[LocaleKeys.DialogErrorMessage]}\n\n{message}", NotificationType.Error);
        }
    }
}