-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
490 lines (422 loc) · 20.1 KB
/
Copy pathMainWindow.xaml.cs
File metadata and controls
490 lines (422 loc) · 20.1 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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
using CommunityToolkit.Mvvm.Messaging;
using NineLivesAudio.Messages;
using NineLivesAudio.Services;
using NineLivesAudio.ViewModels;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.UI.Dispatching;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media;
using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
namespace NineLivesAudio
{
public sealed partial class MainWindow : Window
{
private readonly IAppInitializer _initializer;
private readonly ILoggingService _logger;
private readonly IAudioPlaybackService _playbackService;
private readonly INotificationService _notifications;
private readonly IMetadataNormalizer _normalizer;
private readonly IConnectivityService _connectivity;
private readonly INavigationService _navigationService;
private readonly MainViewModel _mainViewModel;
private DateTime _lastMiniPlayerUpdate = DateTime.MinValue;
// Window reference for preset sizing
private Microsoft.UI.Windowing.AppWindow? _appWindow;
public MainWindow()
{
this.InitializeComponent();
Title = "Nine Lives Audio";
// Set initial window size (portrait default) — user can freely resize/maximize
var hwnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
var windowId = Microsoft.UI.Win32Interop.GetWindowIdFromWindow(hwnd);
_appWindow = Microsoft.UI.Windowing.AppWindow.GetFromWindowId(windowId);
_appWindow?.Resize(new Windows.Graphics.SizeInt32(550, 660)); // 10% larger than minimum
_appWindow?.SetIcon("Assets\\app-icon.ico"); // Taskbar + title bar icon
// Set title bar icon via Win32 (SetIcon doesn't reliably set the small icon)
try
{
var icoPath = Path.Combine(AppContext.BaseDirectory, "Assets", "app-icon.ico");
if (File.Exists(icoPath))
{
var smallIcon = LoadImage(IntPtr.Zero, icoPath, 1 /*IMAGE_ICON*/, 16, 16, 0x0010 /*LR_LOADFROMFILE*/);
var largeIcon = LoadImage(IntPtr.Zero, icoPath, 1, 32, 32, 0x0010);
if (smallIcon != IntPtr.Zero) SendMessage(hwnd, WM_SETICON, (IntPtr)ICON_SMALL, smallIcon);
if (largeIcon != IntPtr.Zero) SendMessage(hwnd, WM_SETICON, (IntPtr)ICON_BIG, largeIcon);
}
}
catch { /* Non-fatal — icon is cosmetic */ }
// Color title bar to match dark void theme
if (_appWindow?.TitleBar is { } titleBar)
{
// Active window
titleBar.BackgroundColor = Windows.UI.Color.FromArgb(0xFF, 0x05, 0x08, 0x10); // VoidDeep
titleBar.ForegroundColor = Windows.UI.Color.FromArgb(0xFF, 0xE0, 0xE0, 0xE8); // StarlightDim
titleBar.ButtonBackgroundColor = Windows.UI.Color.FromArgb(0xFF, 0x05, 0x08, 0x10);
titleBar.ButtonForegroundColor = Windows.UI.Color.FromArgb(0xFF, 0xE0, 0xE0, 0xE8);
titleBar.ButtonHoverBackgroundColor = Windows.UI.Color.FromArgb(0xFF, 0x11, 0x18, 0x27); // VoidSurface
titleBar.ButtonHoverForegroundColor = Windows.UI.Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF);
titleBar.ButtonPressedBackgroundColor = Windows.UI.Color.FromArgb(0xFF, 0x1A, 0x22, 0x36); // VoidElevated
titleBar.ButtonPressedForegroundColor = Windows.UI.Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF);
// Inactive window
titleBar.InactiveBackgroundColor = Windows.UI.Color.FromArgb(0xFF, 0x05, 0x08, 0x10);
titleBar.InactiveForegroundColor = Windows.UI.Color.FromArgb(0xFF, 0x6B, 0x72, 0x80); // MistFaint
titleBar.ButtonInactiveBackgroundColor = Windows.UI.Color.FromArgb(0xFF, 0x05, 0x08, 0x10);
titleBar.ButtonInactiveForegroundColor = Windows.UI.Color.FromArgb(0xFF, 0x6B, 0x72, 0x80);
}
// Enforce minimum size only — no aspect ratio enforcement, no blocking maximize
SetMinimumWindowSize(hwnd, 500, 600);
_initializer = App.Services.GetRequiredService<IAppInitializer>();
_logger = App.Services.GetRequiredService<ILoggingService>();
_playbackService = App.Services.GetRequiredService<IAudioPlaybackService>();
_notifications = App.Services.GetRequiredService<INotificationService>();
_normalizer = App.Services.GetRequiredService<IMetadataNormalizer>();
_connectivity = App.Services.GetRequiredService<IConnectivityService>();
_navigationService = App.Services.GetRequiredService<INavigationService>();
_mainViewModel = App.Services.GetRequiredService<MainViewModel>();
this.Closed += MainWindow_Closed;
// Wire MiniPlayer to playback events via Messenger
WeakReferenceMessenger.Default.Register<PlaybackStateChangedMessage>(this, (r, m) =>
((MainWindow)r).OnPlaybackStateChanged(m.Value));
WeakReferenceMessenger.Default.Register<PositionChangedMessage>(this, (r, m) =>
((MainWindow)r).OnPositionChanged(m.Value));
// Wire notification service via Messenger
WeakReferenceMessenger.Default.Register<NotificationRequestedMessage>(this, (r, m) =>
{
((MainWindow)r).OnNotificationRequested(m.Value);
});
// Wire connectivity monitoring via Messenger
WeakReferenceMessenger.Default.Register<ConnectivityChangedMessage>(this, (r, m) =>
{
((MainWindow)r).OnConnectivityChanged(m.Value);
});
// Kick off async init after the window content is loaded
if (this.Content is FrameworkElement rootElement)
rootElement.Loaded += OnContentLoaded;
}
private async void OnContentLoaded(object sender, RoutedEventArgs e)
{
if (sender is FrameworkElement el)
el.Loaded -= OnContentLoaded; // Only once
await RunInitializationAsync();
}
private async Task RunInitializationAsync()
{
try
{
InitOverlay.Visibility = Visibility.Visible;
InitErrorPanel.Visibility = Visibility.Collapsed;
AppContent.Visibility = Visibility.Collapsed;
InitStatusText.Text = "Initializing...";
await _initializer.InitializeAsync();
if (_initializer.State == InitState.Ready)
{
ShowApp();
}
else
{
ShowInitError(_initializer.ErrorMessage ?? "Unknown initialization error");
}
}
catch (Exception ex)
{
_logger.LogError("MainWindow init failed", ex);
ShowInitError(ex.Message);
}
}
private void ShowApp()
{
InitOverlay.Visibility = Visibility.Collapsed;
InitErrorPanel.Visibility = Visibility.Collapsed;
AppContent.Visibility = Visibility.Visible;
// Initialize navigation service with frame and nav view
_navigationService.Initialize(ContentFrame, NavView);
NavView.SelectedItem = NavView.MenuItems[0]; // Home
NavigateToPage("Home");
// Start connectivity monitoring
_ = _connectivity.StartMonitoringAsync();
UpdateConnectivityUI(_connectivity.IsOnline, _connectivity.IsServerReachable);
}
private void ShowInitError(string message)
{
InitOverlay.Visibility = Visibility.Collapsed;
InitErrorPanel.Visibility = Visibility.Visible;
AppContent.Visibility = Visibility.Collapsed;
InitErrorText.Text = message;
}
private async void RetryInit_Click(object sender, RoutedEventArgs e)
{
await RunInitializationAsync();
}
private void OpenLogs_Click(object sender, RoutedEventArgs e)
{
try
{
var logDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"NineLivesAudio", "Logs");
Process.Start(new ProcessStartInfo { FileName = logDir, UseShellExecute = true });
}
catch (Exception ex)
{
_logger.LogError("Failed to open logs folder", ex);
}
}
private async void ResetConnection_Click(object sender, RoutedEventArgs e)
{
try
{
var settings = App.Services.GetRequiredService<ISettingsService>();
await settings.ClearAuthTokenAsync();
settings.Settings.ServerUrl = string.Empty;
settings.Settings.Username = string.Empty;
await settings.SaveSettingsAsync();
_logger.Log("Connection reset by user from init error screen");
await RunInitializationAsync();
}
catch (Exception ex)
{
_logger.LogError("Reset connection failed", ex);
}
}
// --- Connectivity ---
private void OnConnectivityChanged(ConnectivityChangedEventArgs e)
{
DispatcherQueue.TryEnqueue(() => UpdateConnectivityUI(e.IsOnline, e.IsServerReachable));
}
private void UpdateConnectivityUI(bool isOnline, bool isServerReachable)
{
// Always use a solid circle dot — color indicates status
ConnectivityIcon.Glyph = "\u25CF"; // ● solid circle
ConnectivityIcon.Opacity = 1.0;
if (!isOnline)
{
ConnectivityIcon.Foreground = (Brush)Application.Current.Resources["RitualErrorBrush"];
ConnectivityText.Text = "Offline";
ConnectivityText.Foreground = (Brush)Application.Current.Resources["MistFaintBrush"];
}
else if (!isServerReachable)
{
ConnectivityIcon.Foreground = (Brush)Application.Current.Resources["RitualWarningBrush"];
ConnectivityText.Text = "Server unreachable";
ConnectivityText.Foreground = (Brush)Application.Current.Resources["MistFaintBrush"];
}
else
{
ConnectivityIcon.Foreground = (Brush)Application.Current.Resources["RitualSuccessBrush"];
ConnectivityText.Text = "Connected";
ConnectivityText.Foreground = (Brush)Application.Current.Resources["StarlightBrush"];
}
}
// --- Window Sizing: Minimum size via Win32 WM_GETMINMAXINFO hook ---
private const int WM_GETMINMAXINFO = 0x0024;
private const int GWLP_WNDPROC = -4;
private delegate IntPtr WndProcDelegate(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
private static WndProcDelegate? _newWndProc; // prevent GC of delegate
private static IntPtr _oldWndProc;
private static int _minWidthPx;
private static int _minHeightPx;
[StructLayout(LayoutKind.Sequential)]
private struct POINT { public int X; public int Y; }
[StructLayout(LayoutKind.Sequential)]
private struct MINMAXINFO
{
public POINT ptReserved;
public POINT ptMaxSize;
public POINT ptMaxPosition;
public POINT ptMinTrackSize;
public POINT ptMaxTrackSize;
}
[DllImport("user32.dll", EntryPoint = "SetWindowLongPtrW")]
private static extern IntPtr SetWindowLongPtr(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
[DllImport("user32.dll")]
private static extern IntPtr CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
// Title bar icon via Win32
private const int WM_SETICON = 0x0080;
private const int ICON_SMALL = 0;
private const int ICON_BIG = 1;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr LoadImage(IntPtr hInst, string lpszName, uint uType,
int cxDesired, int cyDesired, uint fuLoad);
[DllImport("user32.dll")]
private static extern uint GetDpiForWindow(IntPtr hwnd);
/// <summary>
/// Enforce a minimum window size via Win32 subclass hook.
/// Accounts for DPI scaling (WM_GETMINMAXINFO uses physical pixels).
/// </summary>
private static void SetMinimumWindowSize(IntPtr hwnd, int minWidth, int minHeight)
{
var dpi = GetDpiForWindow(hwnd);
var scale = dpi / 96.0;
_minWidthPx = (int)(minWidth * scale);
_minHeightPx = (int)(minHeight * scale);
_newWndProc = new WndProcDelegate(MinSizeWndProc);
_oldWndProc = SetWindowLongPtr(hwnd, GWLP_WNDPROC,
Marshal.GetFunctionPointerForDelegate(_newWndProc));
}
private static IntPtr MinSizeWndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
{
if (msg == WM_GETMINMAXINFO)
{
var info = Marshal.PtrToStructure<MINMAXINFO>(lParam);
info.ptMinTrackSize.X = _minWidthPx;
info.ptMinTrackSize.Y = _minHeightPx;
Marshal.StructureToPtr(info, lParam, false);
return IntPtr.Zero;
}
return CallWindowProc(_oldWndProc, hWnd, msg, wParam, lParam);
}
// --- Navigation ---
private void NavView_BackRequested(NavigationView sender, NavigationViewBackRequestedEventArgs args)
{
_navigationService.GoBack();
}
private void NavView_SelectionChanged(NavigationView sender, NavigationViewSelectionChangedEventArgs args)
{
if (args.IsSettingsSelected)
{
UpdateNavGlow(null);
NavigateToPage("Settings");
}
else if (args.SelectedItemContainer is NavigationViewItem selectedItem)
{
UpdateNavGlow(selectedItem);
var tag = selectedItem.Tag?.ToString();
if (!string.IsNullOrEmpty(tag))
NavigateToPage(tag);
}
}
/// <summary>
/// Apply faint gold background glow to the selected navigation item.
/// </summary>
private void UpdateNavGlow(NavigationViewItem? selected)
{
foreach (var item in NavView.MenuItems.OfType<NavigationViewItem>())
item.Background = new SolidColorBrush(Microsoft.UI.Colors.Transparent);
if (selected != null)
selected.Background = new SolidColorBrush(
Windows.UI.Color.FromArgb(0x1A, 0xC5, 0xA5, 0x5A)); // SigilGoldGlow
}
private void NavigateToPage(string pageTag)
{
Type? pageType = pageTag switch
{
"Home" => typeof(Views.HomePage),
"Library" => typeof(Views.LibraryPage),
"Player" => typeof(Views.PlayerPage),
"Downloads" => typeof(Views.DownloadsPage),
"Settings" => typeof(Views.SettingsPage),
_ => null
};
if (pageType != null)
_navigationService.NavigateTo(pageType);
}
// --- MiniPlayer wiring ---
private void OnPlaybackStateChanged(PlaybackStateChangedEventArgs e)
{
DispatcherQueue.TryEnqueue(() =>
{
var book = _playbackService.CurrentAudioBook;
bool showMini = book != null && e.State != PlaybackState.Stopped;
MiniPlayerBar.Visibility = showMini ? Visibility.Visible : Visibility.Collapsed;
if (book != null)
{
// Use normalized metadata for display
var normalized = _normalizer.Normalize(book);
MiniPlayerTitle.Text = normalized.DisplayTitle;
MiniPlayerAuthor.Text = normalized.DisplayAuthor;
MiniPlayPauseIcon.Glyph = e.State == PlaybackState.Playing ? "\uE769" : "\uE768";
// Gold play icon when playing, default when paused
MiniPlayPauseIcon.Foreground = e.State == PlaybackState.Playing
? new SolidColorBrush(Windows.UI.Color.FromArgb(0xFF, 0xC5, 0xA5, 0x5A)) // SigilGold
: new SolidColorBrush(Windows.UI.Color.FromArgb(0xFF, 0xE0, 0xE0, 0xE8)); // StarlightDim
MiniPlayerArt.Source = CoverImageService.LoadThumbnail(book.CoverPath);
}
});
}
private void OnPositionChanged(TimeSpan position)
{
// Throttle mini player updates to ~4/sec
var now = DateTime.UtcNow;
if ((now - _lastMiniPlayerUpdate).TotalMilliseconds < 250)
return;
_lastMiniPlayerUpdate = now;
DispatcherQueue.TryEnqueue(() =>
{
var duration = _playbackService.Duration;
if (duration.TotalSeconds > 0)
MiniPlayerProgress.Value = position.TotalSeconds / duration.TotalSeconds * 100;
});
}
private void MiniPlayer_PointerPressed(object sender, PointerRoutedEventArgs e)
{
var point = e.GetCurrentPoint(sender as UIElement);
if (point.Properties.IsLeftButtonPressed)
{
if (NavView.MenuItems.Count > 2)
NavView.SelectedItem = NavView.MenuItems[2]; // Player
_navigationService.NavigateTo(typeof(Views.PlayerPage));
}
}
private async void MiniPlayPause_Click(object sender, RoutedEventArgs e)
{
if (_playbackService.State == PlaybackState.Playing)
await _playbackService.PauseAsync();
else
await _playbackService.PlayAsync();
}
private async void MiniRewind_Click(object sender, RoutedEventArgs e)
{
var pos = _playbackService.Position - TimeSpan.FromSeconds(10);
if (pos < TimeSpan.Zero) pos = TimeSpan.Zero;
await _playbackService.SeekAsync(pos);
}
private async void MiniForward_Click(object sender, RoutedEventArgs e)
{
var pos = _playbackService.Position + TimeSpan.FromSeconds(30);
if (pos > _playbackService.Duration) pos = _playbackService.Duration;
await _playbackService.SeekAsync(pos);
}
// --- Notification handling ---
private void OnNotificationRequested(NotificationEventArgs e)
{
DispatcherQueue.TryEnqueue(() =>
{
if (e.ShouldDismiss)
{
AppNotification.IsOpen = false;
return;
}
AppNotification.Title = e.Title ?? string.Empty;
AppNotification.Message = e.Message;
AppNotification.Severity = e.Type switch
{
NotificationType.Success => InfoBarSeverity.Success,
NotificationType.Error => InfoBarSeverity.Error,
NotificationType.Warning => InfoBarSeverity.Warning,
_ => InfoBarSeverity.Informational
};
AppNotification.IsOpen = true;
});
}
private void AppNotification_Closed(InfoBar sender, InfoBarClosedEventArgs args)
{
// Auto-closed or user closed
}
private void MainWindow_Closed(object sender, WindowEventArgs args)
{
WeakReferenceMessenger.Default.UnregisterAll(this);
this.Closed -= MainWindow_Closed;
if (_mainViewModel is IDisposable disposable)
{
disposable.Dispose();
}
}
}
}