Repository navigation
Expand file tree
/
Copy pathNotificationWindow.xaml.cs
More file actions
318 lines (253 loc) · 11.3 KB
/
Copy pathNotificationWindow.xaml.cs
File metadata and controls
318 lines (253 loc) · 11.3 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
using NETworkManager.Controls;
using NETworkManager.Localization;
using NETworkManager.Models;
using NETworkManager.Settings;
using NETworkManager.Utilities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
namespace NETworkManager;
/// <summary>
/// A generic, stackable notification popup shown in the bottom-right corner of the primary
/// screen. Contains no feature-specific knowledge — icon, color, title and message are all
/// supplied by the caller (via <see cref="NotificationManager"/>).
/// </summary>
public partial class NotificationWindow : INotifyPropertyChanged
{
#region PropertyChangedEventHandler
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
#region Variables
private readonly DispatcherTimer _timer = new(DispatcherPriority.Render);
private readonly Stopwatch _stopwatch = new();
// Bound properties — all set once in the constructor, no change notifications needed.
// Note: the header property is named NotificationTitle (not Title) to avoid clashing with
// the inherited Window.Title property, which a "{Binding Title}" would otherwise resolve to.
// Opened when the notification is clicked (the tool or its tab)
private readonly ApplicationRequest _request;
// Header: the tool that sent the notification
public Brush ApplicationIconBrush { get; }
public string ApplicationTitle { get; }
public LucideIconKind IconKind { get; }
public Brush IconBrush { get; }
public string NotificationTitle { get; }
public IReadOnlyList<NotificationLineItem> Lines { get; }
// Timestamp shown in the header — captured when the notification is created, which is the
// moment the status change occurred.
public string Time { get; }
public double TimeMax { get; }
public double TimeRemaining
{
get;
private set
{
if (Math.Abs(value - field) < 0.001)
return;
field = value;
OnPropertyChanged();
}
}
// Command — initialized once in the constructor, not recreated on every binding access
public ICommand CloseCommand { get; }
#endregion
#region Constructor
public NotificationWindow(NotificationInfo notification)
{
InitializeComponent();
DataContext = this;
_request = notification.Request ?? new ApplicationRequest(notification.Application);
ApplicationIconBrush = new VisualBrush(ApplicationManager.GetIcon(notification.Application))
{
Stretch = Stretch.Uniform
};
ApplicationTitle = ResourceTranslator.Translate(ResourceIdentifier.ApplicationName, notification.Application);
(IconKind, IconBrush) = GetStatusIcon(notification.Status);
NotificationTitle = notification.Title;
Lines = [.. notification.Lines.Select(x => new NotificationLineItem(
string.IsNullOrEmpty(x.Text) ? string.Empty : x.Text + NotificationLine.Separator, x.Status,
GetStatusBrush(x.StatusKind)))];
Time = DateTime.Now.ToString("HH:mm:ss");
TimeMax = notification.CloseTimeSeconds;
TimeRemaining = notification.CloseTimeSeconds;
CloseCommand = new RelayCommand(_ => CloseWindow());
// The window auto-sizes its height to the content (SizeToContent=Height), so when the
// message wraps to more lines the whole stack must re-anchor to the bottom edge.
SizeChanged += (_, _) => NotificationManager.RepositionAll();
_timer.Interval = TimeSpan.FromMilliseconds(33);
_timer.Tick += Timer_Tick;
}
#endregion
#region ICommands & Actions
private void ShowMainWindow()
{
CloseWindow();
if (System.Windows.Application.Current.MainWindow is MainWindow mainWindow &&
mainWindow.ShowWindowCommand.CanExecute(null))
mainWindow.ShowWindowCommand.Execute(null);
// The tool (and the tab) that sent the notification
NavigationManager.Open(_request);
}
#endregion
#region Methods
/// <summary>
/// Gets a status color of the current theme (status icons, "Since last scan" of the scanners), see
/// <see cref="AppearanceManager"/>.
/// </summary>
/// <param name="key">Resource key of the status brush.</param>
/// <returns>Color of the brush, gray if it is not found.</returns>
private static Color GetStatusColor(string key)
{
return System.Windows.Application.Current.TryFindResource(key) is SolidColorBrush brush
? brush.Color
: Colors.Gray;
}
/// <summary>
/// Gets the icon and its brush of a status: up green, down red, up and down half green / half red (split along the
/// diagonal), changed orange.
/// </summary>
/// <param name="status">Status of the notification.</param>
/// <returns>Icon and brush.</returns>
private static (LucideIconKind kind, Brush brush) GetStatusIcon(NotificationStatus status)
{
var brush = GetStatusBrush(status);
var kind = status switch
{
NotificationStatus.Up => LucideIconKind.MonitorCheck,
NotificationStatus.Down => LucideIconKind.MonitorX,
NotificationStatus.UpAndDown => LucideIconKind.Network,
_ => LucideIconKind.MonitorDot
};
return (kind, brush);
}
/// <summary>
/// Gets the brush of a status (status icon, status text of a line): up green, down red, up and down half green /
/// half red (split along the diagonal), changed orange.
/// </summary>
/// <param name="status">Status.</param>
/// <returns>Frozen brush.</returns>
private static Brush GetStatusBrush(NotificationStatus status)
{
var upColor = GetStatusColor(AppearanceManager.StatusSuccessBrushKey);
var downColor = GetStatusColor(AppearanceManager.StatusErrorBrushKey);
Brush brush = status switch
{
NotificationStatus.Up => new SolidColorBrush(upColor),
NotificationStatus.Down => new SolidColorBrush(downColor),
NotificationStatus.UpAndDown => new LinearGradientBrush(new GradientStopCollection
{
// Two stops at the same offset: a sharp diagonal edge instead of a gradient
new(upColor, 0), new(upColor, 0.5), new(downColor, 0.5), new(downColor, 1)
}, new Point(0, 0), new Point(1, 1)),
_ => new SolidColorBrush(GetStatusColor(AppearanceManager.StatusWarningBrushKey))
};
brush.Freeze();
return brush;
}
/// <summary>
/// Called by <see cref="NotificationManager"/> when the stack changes (a sibling closes or
/// resizes) and this window may need to move.
/// </summary>
internal void Reposition()
{
ApplyPosition();
}
private void ApplyPosition()
{
if (Screen.PrimaryScreen == null)
return;
var scale = System.Windows.Media.VisualTreeHelper.GetDpi(this).DpiScaleX;
var area = Screen.PrimaryScreen.WorkingArea;
// Offset = total height (incl. margins) of all windows stacked below this one. Using the
// actual heights keeps variable-height popups (wrapped messages) bottom-anchored.
var offset = NotificationManager.GetStackOffset(this);
Left = area.Right / scale - Width - NotificationManager.WindowMargin;
Top = area.Bottom / scale - ActualHeight - NotificationManager.WindowMargin - offset;
}
/// <summary>
/// Slides the content of the popup in from the right (40 px) and fades it in (200 ms, quadratic ease-out). The
/// content, not the window: the window would start outside the work area and could show up on a monitor to the
/// right, and it can't fade (not transparent: rounded corners, shadow). The window stays where
/// <see cref="ApplyPosition"/> puts it. Not without animations (<see cref="AppearanceManager.AnimationsEnabled"/>).
/// </summary>
private void SlideIn()
{
if (!AppearanceManager.AnimationsEnabled)
return;
var duration = new Duration(TimeSpan.FromMilliseconds(200));
var easing = new System.Windows.Media.Animation.QuadraticEase
{ EasingMode = System.Windows.Media.Animation.EasingMode.EaseOut };
var translate = new TranslateTransform(SlideInOffset, 0);
Root.RenderTransform = translate;
translate.BeginAnimation(TranslateTransform.XProperty,
new System.Windows.Media.Animation.DoubleAnimation(SlideInOffset, 0, duration) { EasingFunction = easing });
Root.BeginAnimation(OpacityProperty,
new System.Windows.Media.Animation.DoubleAnimation(0, 1, duration) { EasingFunction = easing });
}
private const double SlideInOffset = 40;
private void CloseWindow()
{
_timer.Stop();
_stopwatch.Stop();
Closing -= MetroWindow_Closing;
Close(); // fires Window.Closed → NotificationManager removes from stack and repositions
}
#endregion
#region Events
// Lifecycle — the HWND exists here, so DPI is safe to read for positioning
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
ApplyPosition();
SlideIn();
_stopwatch.Restart();
_timer.Start();
}
// Clicking anywhere on the popup opens the main window. The close button handles its own
// mouse events, so clicking [×] does not bubble up here.
private void Root_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
ShowMainWindow();
}
// Intercept Alt+F4 / OS close so the stack cleanup always runs through CloseWindow()
private void MetroWindow_Closing(object sender, CancelEventArgs e)
{
e.Cancel = true;
CloseWindow();
}
private async void Timer_Tick(object sender, EventArgs e)
{
// Use a local for the close decision — the TimeRemaining setter ignores sub-0.001 changes
// (to throttle the progress bar), so reading the property back could stay stuck at a tiny
// positive value and the window would never close.
var remaining = Math.Max(0.0, TimeMax - _stopwatch.Elapsed.TotalSeconds);
TimeRemaining = remaining;
if (remaining > 0)
return;
_timer.Stop();
_stopwatch.Stop();
await Task.Delay(250); // let the bar visually reach zero before closing
CloseWindow();
}
#endregion
}
/// <summary>
/// A line of the notification as shown: the text with the separator (empty if the line has only a status), the status
/// and its brush (see <see cref="NotificationLine" />).
/// </summary>
/// <param name="Prefix">Text of the line with the separator, e.g. "10.0.0.5 (server) · ".</param>
/// <param name="Status">Status text, e.g. "New".</param>
/// <param name="StatusBrush">Brush of the status text.</param>
public sealed record NotificationLineItem(string Prefix, string Status, Brush StatusBrush);