-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
445 lines (379 loc) · 16.8 KB
/
Copy pathMainWindow.xaml.cs
File metadata and controls
445 lines (379 loc) · 16.8 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
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Threading;
using FluentTune.Services;
using FluentTune.ViewModels;
using WinForms = System.Windows.Forms;
using Drawing = System.Drawing;
namespace FluentTune;
public partial class MainWindow : Window
{
private readonly MediaService _media = new();
private readonly VolumeService _volume = new();
private readonly AudioSpectrumService _spectrumService = new();
private readonly NowPlayingViewModel _vm = new();
private SpectrumWindow? _spectrum;
private LockKeyWindow? _lockKeys;
// Global mouse hook to close the flyout when the user clicks anywhere outside it.
private delegate IntPtr LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")] private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelMouseProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll")] private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll")] private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)] private static extern IntPtr GetModuleHandle(string? lpModuleName);
private const int WH_MOUSE_LL = 14;
private const int WM_LBUTTONDOWN = 0x0201;
[StructLayout(LayoutKind.Sequential)] private struct POINT { public int X; public int Y; }
[StructLayout(LayoutKind.Sequential)]
private struct MSLLHOOKSTRUCT { public POINT pt; public uint mouseData; public uint flags; public uint time; public IntPtr dwExtraInfo; }
private IntPtr _mouseHook;
private LowLevelMouseProc? _mouseProc;
private int _flyL, _flyT, _flyR, _flyB; // flyout bounds in physical pixels
// Global hotkey (Ctrl+Alt+M) to toggle the flyout.
[DllImport("user32.dll")] private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
[DllImport("user32.dll")] private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
private const int HOTKEY_ID = 0xB001;
private const uint MOD_ALT = 0x1, MOD_CONTROL = 0x2, MOD_SHIFT = 0x4;
private const int WM_HOTKEY = 0x0312;
private IntPtr _hotkeyHwnd;
private string _hotkeyName = "";
private static readonly (uint Mod, uint Vk, string Name)[] HotkeyCandidates =
{
(MOD_CONTROL | MOD_ALT, 0x4D, "Ctrl+Alt+M"),
(MOD_CONTROL | MOD_ALT, 0x4B, "Ctrl+Alt+K"),
(MOD_CONTROL | MOD_SHIFT, 0x4D, "Ctrl+Shift+M"),
(MOD_CONTROL | MOD_ALT, 0x50, "Ctrl+Alt+P"),
(MOD_CONTROL | MOD_SHIFT, 0x78, "Ctrl+Shift+F9"),
};
private readonly DispatcherTimer _positionTimer = new() { Interval = TimeSpan.FromMilliseconds(500) };
private WinForms.NotifyIcon? _tray;
// Baseline for interpolating the playback position between updates.
private TimeSpan _basePosition;
private TimeSpan _baseDuration;
private DateTime _baseTimestamp;
private bool _isPlaying;
private bool _canSeek;
private bool _userSeeking;
private bool _suppressVolume;
private bool _reallyExit;
private static readonly Color DefaultAccent = Color.FromRgb(0x4C, 0xC2, 0xFF);
private Color _accent = DefaultAccent;
private bool _shownOnce;
public MainWindow()
{
InitializeComponent();
DataContext = _vm;
Wave.Interacting += () => _userSeeking = true;
Wave.Seek += async seconds =>
{
_userSeeking = false;
if (_canSeek) await _media.SeekAsync(TimeSpan.FromSeconds(seconds));
};
Wave.LevelProvider = () => _spectrumService.GetLevel(); // wave pulses with the music
Loaded += OnLoaded;
ContentRendered += OnContentRendered;
Closing += (_, e) =>
{
if (!_reallyExit) { e.Cancel = true; HideWidget(); }
};
}
private async void OnLoaded(object sender, RoutedEventArgs e)
{
SetupTray();
_positionTimer.Tick += (_, _) => UpdateInterpolatedPosition();
_positionTimer.Start();
// Volume
VolumeSlider.IsEnabled = _volume.IsAvailable;
_volume.VolumeChanged += v => Dispatcher.Invoke(() => SetVolumeSlider(v));
SetVolumeSlider(_volume.GetVolume());
// Taskbar spectrum overlay + mini now-playing (left side of the taskbar)
_spectrumService.Start();
_spectrum = new SpectrumWindow(_spectrumService, _vm);
_spectrum.WidgetClicked += ToggleWidget; // click the taskbar widget to open/close the flyout
_spectrum.WidgetScrolled += steps => // scroll over the widget = system volume
_volume.SetVolume(_volume.GetVolume() + steps * 0.04f);
_spectrum.Show();
_spectrum.SetAccent(_accent);
// Close the flyout when the user clicks anywhere outside it.
_mouseProc = MouseHookCallback;
_mouseHook = SetWindowsHookEx(WH_MOUSE_LL, _mouseProc, GetModuleHandle(null), 0);
// Centered OSD for Caps / Num / Scroll Lock.
_lockKeys = new LockKeyWindow();
_lockKeys.Show();
_lockKeys.Hide();
// Media
_media.NowPlayingChanged += OnNowPlaying;
_media.TimelineChanged += OnTimeline;
await _media.InitializeAsync();
}
private IntPtr MouseHookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && wParam.ToInt32() == WM_LBUTTONDOWN && IsVisible && Opacity > 0.5)
{
var data = Marshal.PtrToStructure<MSLLHOOKSTRUCT>(lParam);
int x = data.pt.X, y = data.pt.Y;
bool insideFlyout = x >= _flyL && x <= _flyR && y >= _flyT && y <= _flyB;
// Clicks on the taskbar widget are handled by its own toggle — ignore them here.
var wb = _spectrum?.WidgetBounds ?? (0, 0, 0, 0);
bool insideWidget = x >= wb.L && x <= wb.R && y >= wb.T && y <= wb.B;
if (!insideFlyout && !insideWidget)
Dispatcher.BeginInvoke(new Action(HideWidget));
}
return CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);
}
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
_hotkeyHwnd = new WindowInteropHelper(this).Handle;
foreach (var (mod, vk, name) in HotkeyCandidates)
{
if (RegisterHotKey(_hotkeyHwnd, HOTKEY_ID, mod, vk))
{
_hotkeyName = name;
break;
}
}
App.Log($"hotkey bound = '{_hotkeyName}'");
HwndSource.FromHwnd(_hotkeyHwnd)?.AddHook(HotkeyProc);
}
private IntPtr HotkeyProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == WM_HOTKEY && wParam.ToInt32() == HOTKEY_ID)
{
ToggleWidget();
handled = true;
}
return IntPtr.Zero;
}
private void OnContentRendered(object? sender, EventArgs e)
{
if (_shownOnce) return;
_shownOnce = true;
Hide(); // start hidden — the flyout opens only when the taskbar widget is clicked
}
// ---------- Media ----------
private void OnNowPlaying(NowPlayingInfo info)
{
// GSMTC events arrive on a background thread — marshal to the UI.
Dispatcher.Invoke(() =>
{
_vm.HasMedia = info.HasMedia;
_vm.Title = info.HasMedia ? info.Title : "Nada sonando";
_vm.Artist = info.HasMedia ? info.Artist : "Reproduce algo para empezar";
_vm.IsPlaying = info.IsPlaying;
_vm.Thumbnail = info.Thumbnail;
_vm.CanSeek = info.CanSeek;
ApplyAccent(info.HasMedia
? ColorExtractor.GetAccent(info.Thumbnail, DefaultAccent)
: DefaultAccent);
if (_tray is not null)
{
string tip = info.HasMedia ? $"{info.Title} — {info.Artist}" : "FluentTune";
if (tip.Length > 63) tip = tip[..60] + "...";
_tray.Text = tip;
}
_spectrum?.SetActive(info.HasMedia);
SetTimelineBase(info.Position, info.Duration, info.IsPlaying, info.CanSeek);
AnimateArt();
// The flyout is opened manually (click the taskbar widget) — it no longer
// auto-pops on every track change.
});
}
private void OnTimeline(TimelineInfo t)
{
Dispatcher.Invoke(() =>
{
_vm.CanSeek = t.CanSeek;
SetTimelineBase(t.Position, t.Duration, t.IsPlaying, t.CanSeek);
});
}
private void SetTimelineBase(TimeSpan pos, TimeSpan dur, bool playing, bool canSeek)
{
_basePosition = pos;
_baseDuration = dur;
_baseTimestamp = DateTime.UtcNow;
_isPlaying = playing;
_canSeek = canSeek;
_vm.DurationSeconds = dur.TotalSeconds;
_vm.DurationText = Fmt(dur);
if (!_userSeeking) UpdateInterpolatedPosition();
}
private void UpdateInterpolatedPosition()
{
if (_userSeeking) return;
var pos = _basePosition;
if (_isPlaying) pos += DateTime.UtcNow - _baseTimestamp;
if (_baseDuration > TimeSpan.Zero && pos > _baseDuration) pos = _baseDuration;
if (pos < TimeSpan.Zero) pos = TimeSpan.Zero;
_vm.PositionSeconds = pos.TotalSeconds;
_vm.PositionText = Fmt(pos);
}
private static string Fmt(TimeSpan t) => t.TotalHours >= 1 ? t.ToString(@"h\:mm\:ss") : t.ToString(@"m\:ss");
// ---------- Transport ----------
private async void Previous_Click(object sender, RoutedEventArgs e) => await _media.PreviousAsync();
private async void PlayPauseBorder_Click(object sender, MouseButtonEventArgs e) => await _media.TogglePlayPauseAsync();
private async void Next_Click(object sender, RoutedEventArgs e) => await _media.NextAsync();
// ---------- Volume ----------
private void SetVolumeSlider(float scalar)
{
_suppressVolume = true;
VolumeSlider.Value = Math.Clamp(scalar, 0f, 1f);
_suppressVolume = false;
}
private void Volume_Changed(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (_suppressVolume) return;
_volume.SetVolume((float)e.NewValue);
}
// ---------- Show / hide ----------
private void ShowWidget()
{
PositionAboveTaskbar();
Show();
Visibility = Visibility.Visible;
BeginAnimation(OpacityProperty, null);
RootTransform.BeginAnimation(System.Windows.Media.TranslateTransform.YProperty, null);
RootTransform.Y = 48;
Opacity = 0;
var slide = new DoubleAnimation(48, 0, TimeSpan.FromMilliseconds(500))
{
EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut },
};
var fade = new DoubleAnimation(0, 1, TimeSpan.FromMilliseconds(360));
RootTransform.BeginAnimation(System.Windows.Media.TranslateTransform.YProperty, slide);
BeginAnimation(OpacityProperty, fade);
}
private void HideWidget()
{
var slide = new DoubleAnimation(0, 48, TimeSpan.FromMilliseconds(320))
{
EasingFunction = new CubicEase { EasingMode = EasingMode.EaseIn },
};
var fade = new DoubleAnimation(Opacity, 0, TimeSpan.FromMilliseconds(300));
fade.Completed += (_, _) => { if (Opacity < 0.02) Hide(); };
RootTransform.BeginAnimation(System.Windows.Media.TranslateTransform.YProperty, slide);
BeginAnimation(OpacityProperty, fade);
}
private void ToggleWidget()
{
if (IsVisible && Opacity > 0.5) HideWidget();
else ShowWidget();
}
private void PositionAboveTaskbar()
{
// Bottom-left, just above the taskbar. The card sits ~24px inside the window
// (transparent margin left for the drop shadow), so nudge left to hug the edge.
var wa = SystemParameters.WorkArea;
var h = ActualHeight > 0 ? ActualHeight : 200;
Left = wa.Left - 8;
Top = wa.Bottom - h + 16;
// Physical bounds of the visible card (window minus the shadow margin) for click-outside.
var src = PresentationSource.FromVisual(this);
double dpiX = src?.CompositionTarget?.TransformToDevice.M11 ?? 1.0;
double dpiY = src?.CompositionTarget?.TransformToDevice.M22 ?? 1.0;
const double margin = 24;
double w = ActualWidth > 0 ? ActualWidth : Width;
_flyL = (int)Math.Round((Left + margin) * dpiX);
_flyT = (int)Math.Round((Top + margin) * dpiY);
_flyR = (int)Math.Round((Left + w - margin) * dpiX);
_flyB = (int)Math.Round((Top + h - margin) * dpiY);
}
private void AnimateArt()
{
var fade = new DoubleAnimation(0, 1, TimeSpan.FromMilliseconds(300))
{
EasingFunction = new QuadraticEase { EasingMode = EasingMode.EaseOut },
};
ArtBorder.BeginAnimation(OpacityProperty, fade);
}
/// <summary>Recolour the accent brush + glow to match the album artwork.</summary>
private void ApplyAccent(Color accent)
{
_accent = accent;
var target = new SolidColorBrush(accent);
target.Freeze();
_vm.AccentBrush = target;
// Dark icon on a light accent, white icon on a dark one.
double luminance = 0.299 * accent.R + 0.587 * accent.G + 0.114 * accent.B;
_vm.AccentForeground = luminance > 150 ? new SolidColorBrush(Color.FromRgb(0x14, 0x14, 0x14)) : Brushes.White;
// Colour bleeds in from behind the album art (left) and fades across the card.
var glow = new RadialGradientBrush
{
GradientOrigin = new Point(0.12, 0.4),
Center = new Point(0.12, 0.4),
RadiusX = 1.4,
RadiusY = 1.6,
};
glow.GradientStops.Add(new GradientStop(Color.FromArgb(0x8C, accent.R, accent.G, accent.B), 0));
glow.GradientStops.Add(new GradientStop(Color.FromArgb(0x30, accent.R, accent.G, accent.B), 0.5));
glow.GradientStops.Add(new GradientStop(Color.FromArgb(0x00, accent.R, accent.G, accent.B), 1));
glow.Freeze();
_vm.GlowBrush = glow;
_spectrum?.SetAccent(accent);
}
private void Close_Click(object sender, MouseButtonEventArgs e) => HideWidget();
// ---------- Tray ----------
private void SetupTray()
{
_tray = new WinForms.NotifyIcon
{
Icon = CreateTrayIcon(),
Visible = true,
Text = "FluentTune",
};
var menu = new WinForms.ContextMenuStrip();
string showLabel = string.IsNullOrEmpty(_hotkeyName) ? "Mostrar" : $"Mostrar ({_hotkeyName})";
menu.Items.Add(showLabel, null, (_, _) => ShowWidget());
var startup = new WinForms.ToolStripMenuItem("Iniciar con Windows")
{
Checked = StartupService.IsEnabled(),
CheckOnClick = true,
};
startup.CheckedChanged += (s, _) => StartupService.SetEnabled(((WinForms.ToolStripMenuItem)s!).Checked);
menu.Items.Add(startup);
menu.Items.Add(new WinForms.ToolStripSeparator());
menu.Items.Add("Salir", null, (_, _) => ExitApp());
_tray.ContextMenuStrip = menu;
_tray.MouseClick += (_, e) => { if (e.Button == WinForms.MouseButtons.Left) ToggleWidget(); };
}
private static Drawing.Icon CreateTrayIcon()
{
// Prefer the real app icon embedded in the exe; fall back to a drawn note.
try
{
var exe = Environment.ProcessPath;
if (!string.IsNullOrEmpty(exe))
{
var ico = Drawing.Icon.ExtractAssociatedIcon(exe);
if (ico is not null) return ico;
}
}
catch { /* fall back below */ }
using var bmp = new Drawing.Bitmap(32, 32);
using (var g = Drawing.Graphics.FromImage(bmp))
{
g.SmoothingMode = Drawing.Drawing2D.SmoothingMode.AntiAlias;
g.Clear(Drawing.Color.Transparent);
using var brush = new Drawing.SolidBrush(Drawing.Color.FromArgb(0x4C, 0xC2, 0xFF));
using var font = new Drawing.Font("Segoe UI Symbol", 22, Drawing.FontStyle.Bold, Drawing.GraphicsUnit.Pixel);
g.DrawString("♪", font, brush, new Drawing.PointF(6, 2));
}
return Drawing.Icon.FromHandle(bmp.GetHicon());
}
private void ExitApp()
{
_reallyExit = true;
if (_hotkeyHwnd != IntPtr.Zero) UnregisterHotKey(_hotkeyHwnd, HOTKEY_ID);
_positionTimer.Stop();
if (_mouseHook != IntPtr.Zero) { UnhookWindowsHookEx(_mouseHook); _mouseHook = IntPtr.Zero; }
if (_tray is not null) { _tray.Visible = false; _tray.Dispose(); }
_lockKeys?.Close();
_spectrum?.Close();
_spectrumService.Dispose();
_volume.Dispose();
System.Windows.Application.Current.Shutdown();
}
}