This commit is contained in:
TinyHerm committed 2026-11-24 23:40:08 +03:00
commit 1c7a8cf25f
579 files changed
+83196

No files matched your search

+317
View File
@@ -0,0 +1,317 @@
using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Threading;
namespace VibranceHud.Music;
internal sealed class GsmtcSource : INowPlayingSource
{
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetPointer(nint self, out nint value);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetInt(nint self, out int value);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetBool(nint self, out byte value);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int NoArgs(nint self);
private sealed class Com : IDisposable
{
internal nint Ptr;
internal Com(nint ptr)
{
Ptr = ptr;
}
internal Com As(Guid iid)
{
_cancellation.ThrowIfCancellationRequested();
Check(Marshal.QueryInterface(Ptr, in iid, out var ppv));
return new Com(ppv);
}
public void Dispose()
{
if (Ptr != IntPtr.Zero)
{
Marshal.Release(Ptr);
Ptr = IntPtr.Zero;
}
}
}
[ThreadStatic]
private static CancellationToken _cancellation;
private static readonly Guid Statics = new Guid("2050C4EE-11A0-57DE-AED7-C97C70338245");
private static readonly Guid Manager = new Guid("CACE8EAC-E86E-504A-AB31-5FF8FF1BCE49");
private static readonly Guid Session = new Guid("7148C835-9B14-5AE2-AB85-DC9B1C14E1A8");
private static readonly Guid Properties = new Guid("68856CF6-ADB4-54B2-AC16-05837907ACB6");
private static readonly Guid Playback = new Guid("94B4B6CF-E8BA-51AD-87A7-C10ADE106127");
private static readonly Guid Controls = new Guid("6501A3E6-BC7A-503A-BB1B-68F158F3FB03");
private static readonly Guid StreamReference = new Guid("33EE3134-1DD6-4E3A-8067-D1C162E8642B");
private static readonly Guid AsyncInfo = new Guid("00000036-0000-0000-C000-000000000046");
private static readonly Guid StreamIid = new Guid("0000000C-0000-0000-C000-000000000046");
public bool NeedsWorker => true;
[DllImport("combase.dll")]
private static extern int RoInitialize(uint type);
[DllImport("combase.dll")]
private static extern void RoUninitialize();
[DllImport("combase.dll", CharSet = CharSet.Unicode)]
private static extern int WindowsCreateString(string value, uint length, out nint result);
[DllImport("combase.dll")]
private static extern int WindowsDeleteString(nint value);
[DllImport("combase.dll")]
private static extern nint WindowsGetStringRawBuffer(nint value, out uint length);
[DllImport("combase.dll")]
private static extern int RoGetActivationFactory(nint name, in Guid iid, out nint result);
[DllImport("shcore.dll")]
private static extern int CreateStreamOverRandomAccessStream(nint random, in Guid iid, out nint stream);
private static void Check(int hr)
{
Marshal.ThrowExceptionForHR(hr);
}
private static T Slot<T>(Com c, int slot) where T : Delegate
{
_cancellation.ThrowIfCancellationRequested();
return Marshal.GetDelegateForFunctionPointer<T>(Marshal.ReadIntPtr(Marshal.ReadIntPtr(c.Ptr), slot * IntPtr.Size));
}
private static Com Pointer(Com c, int slot)
{
Check(Slot<GetPointer>(c, slot)(c.Ptr, out var value));
return new Com(value);
}
private static int Integer(Com c, int slot)
{
Check(Slot<GetInt>(c, slot)(c.Ptr, out var value));
return value;
}
private static bool Boolean(Com c, int slot)
{
Check(Slot<GetBool>(c, slot)(c.Ptr, out var value));
return value != 0;
}
private static string Text(Com c, int slot)
{
using Com com = Pointer(c, slot);
nint ptr = com.Ptr;
com.Ptr = IntPtr.Zero;
try
{
uint length;
return Marshal.PtrToStringUni(WindowsGetStringRawBuffer(ptr, out length), checked((int)length)) ?? "";
}
finally
{
WindowsDeleteString(ptr);
}
}
private static void Wait(Com operation)
{
using Com com = operation.As(AsyncInfo);
Stopwatch stopwatch = Stopwatch.StartNew();
while (Integer(com, 7) == 0)
{
if (stopwatch.ElapsedMilliseconds >= 1400)
{
Slot<NoArgs>(com, 9)(com.Ptr);
throw new TimeoutException();
}
Thread.Sleep(20);
}
if (Integer(com, 7) != 1)
{
throw new InvalidOperationException("Media operation did not complete.");
}
}
private static Com Result(Com operation)
{
Wait(operation);
return Pointer(operation, 8);
}
private static Com Current()
{
_cancellation.ThrowIfCancellationRequested();
Check(WindowsCreateString("Windows.Media.Control.GlobalSystemMediaTransportControlsSessionManager", (uint)"Windows.Media.Control.GlobalSystemMediaTransportControlsSessionManager".Length, out var result));
try
{
Check(RoGetActivationFactory(result, in Statics, out var result2));
using Com c = new Com(result2);
using Com operation = Pointer(c, 6);
using Com com = Result(operation);
using Com c2 = com.As(Manager);
using Com com2 = Pointer(c2, 6);
return (com2.Ptr == IntPtr.Zero) ? new Com(IntPtr.Zero) : com2.As(Session);
}
finally
{
WindowsDeleteString(result);
}
}
private static T OnMta<T>(Func<T> read, CancellationToken cancellation = default(CancellationToken))
{
cancellation.ThrowIfCancellationRequested();
if (Thread.CurrentThread.GetApartmentState() != ApartmentState.MTA)
{
throw new InvalidOperationException("Windows media must be read on an MTA worker.");
}
Check(RoInitialize(1u));
_cancellation = cancellation;
try
{
return read();
}
finally
{
_cancellation = default;
RoUninitialize();
}
}
public NowPlaying? Read()
{
return Read(CancellationToken.None);
}
public NowPlaying? Read(CancellationToken cancellation)
{
return OnMta(() =>
{
using Com com = Current();
if (com.Ptr != IntPtr.Zero)
{
using Com operation = Pointer(com, 7);
using Com com2 = Result(operation);
using Com com3 = com2.As(Properties);
using Com com4 = Pointer(com, 9);
using Com c = com4.As(Playback);
using Com com5 = Pointer(c, 6);
using Com c2 = com5.As(Controls);
string text = Text(com3, 6);
if (string.IsNullOrWhiteSpace(text))
{
return (NowPlaying)null;
}
return new NowPlaying(Text(com3, 9), text)
{
AppName = Text(com, 6),
IsPlaying = (Integer(c, 7) == 4),
CanNext = Boolean(c2, 12),
CanPrevious = Boolean(c2, 13),
CanPlayPause = Boolean(c2, 16),
Art = ReadArt(com3)
};
}
return (NowPlaying)null;
}, cancellation);
}
public bool TryCommand(MediaKey key)
{
return OnMta(() =>
{
using Com com = Current();
if (com.Ptr != IntPtr.Zero)
{
Com c = com;
int slot = ((key == MediaKey.Next) ? 16 : ((key == MediaKey.Previous) ? 17 : 20));
using Com com2 = Pointer(c, slot);
Wait(com2);
return Boolean(com2, 8);
}
return false;
});
}
private static Bitmap? ReadArt(Com properties)
{
try
{
using Com com = Pointer(properties, 15);
if (com.Ptr == IntPtr.Zero)
{
return null;
}
using Com c = com.As(StreamReference);
using Com operation = Pointer(c, 6);
using Com com2 = Result(operation);
Check(CreateStreamOverRandomAccessStream(com2.Ptr, in StreamIid, out var stream));
object obj = null;
try
{
obj = Marshal.GetObjectForIUnknown(stream);
IStream stream2 = (IStream)obj;
stream2.Stat(out var pstatstg, 1);
if (pstatstg.cbSize <= 0 || pstatstg.cbSize > 8388608)
{
return null;
}
byte[] array = new byte[(int)pstatstg.cbSize];
nint num = Marshal.AllocCoTaskMem(4);
try
{
stream2.Read(array, array.Length, num);
int num2 = Marshal.ReadInt32(num);
if (num2 <= 0)
{
return null;
}
using MemoryStream stream3 = new MemoryStream(array, 0, num2);
using Image image = Image.FromStream(stream3);
double num3 = Math.Min(1.0, 256.0 / (double)Math.Max(image.Width, image.Height));
return new Bitmap(image, Math.Max(1, (int)((double)image.Width * num3)), Math.Max(1, (int)((double)image.Height * num3)));
}
finally
{
Marshal.FreeCoTaskMem(num);
}
}
finally
{
if (obj != null)
{
Marshal.ReleaseComObject(obj);
}
Marshal.Release(stream);
}
}
catch
{
return null;
}
}
}
+6
View File
@@ -0,0 +1,6 @@
namespace VibranceHud.Music;
internal interface IMediaKeys
{
void Send(MediaKey key);
}
+29
View File
@@ -0,0 +1,29 @@
using System.Threading;
namespace VibranceHud.Music;
internal interface INowPlayingSource
{
bool NeedsWorker => false;
NowPlaying? Read()
{
return NowPlaying.FromSpotifyTitle(SpotifyWindowTitle());
}
NowPlaying? Read(CancellationToken cancellation)
{
cancellation.ThrowIfCancellationRequested();
return Read();
}
bool TryCommand(MediaKey key)
{
return false;
}
string? SpotifyWindowTitle()
{
return null;
}
}
+122
View File
@@ -0,0 +1,122 @@
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace VibranceHud.Music;
internal sealed class MediaGlyphButton : Control
{
private bool _hover;
private bool _playing;
internal MediaKey Key { get; }
internal bool IsPlaying
{
get
{
return _playing;
}
set
{
_playing = value;
if (Key == MediaKey.PlayPause)
{
AccessibleName = (value ? "Pause" : "Play");
}
Invalidate();
}
}
internal MediaGlyphButton(MediaKey key)
{
Key = key;
SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true);
BackColor = Color.Transparent;
Cursor = Cursors.Hand;
TabStop = false;
AccessibleRole = AccessibleRole.PushButton;
AccessibleName = key switch
{
MediaKey.Next => "Next track",
MediaKey.Previous => "Previous track",
_ => "Play or pause",
};
}
protected override void OnMouseEnter(EventArgs e)
{
_hover = true;
Invalidate();
base.OnMouseEnter(e);
}
protected override void OnMouseLeave(EventArgs e)
{
_hover = false;
Invalidate();
base.OnMouseLeave(e);
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics graphics = e.Graphics;
graphics.SmoothingMode = SmoothingMode.AntiAlias;
int dpi = ControlInk.Dpi(this);
if (_hover)
{
using SolidBrush brush = new SolidBrush(ControlInk.Hover);
using GraphicsPath path = Glass.RoundedPath(new RectangleF(0f, 0f, Width - 1, Height - 1), ControlInk.PxF(dpi, 4f));
graphics.FillPath(brush, path);
}
float num = ControlInk.PxF(dpi, 10f);
float num2 = ((float)Width - num) / 2f;
float num3 = ((float)Height - num) / 2f;
Color color;
if (Enabled)
{
color = (_hover ? ControlInk.Text1 : ControlInk.Text2);
}
else
{
color = ControlInk.Text3;
}
using SolidBrush brush2 = new SolidBrush(color);
float num4 = Math.Max(1.5f, ControlInk.PxF(dpi, 1.6f));
switch (Key)
{
case MediaKey.Previous:
graphics.FillRectangle(brush2, num2, num3, num4, num);
graphics.FillPolygon(brush2, new PointF[3]
{
new PointF(num2 + num, num3),
new PointF(num2 + num, num3 + num),
new PointF(num2 + num4 + 0.5f, num3 + num / 2f)
});
return;
case MediaKey.Next:
graphics.FillPolygon(brush2, new PointF[3]
{
new PointF(num2, num3),
new PointF(num2, num3 + num),
new PointF(num2 + num - num4 - 0.5f, num3 + num / 2f)
});
graphics.FillRectangle(brush2, num2 + num - num4, num3, num4, num);
return;
}
if (IsPlaying)
{
graphics.FillRectangle(brush2, num2 + num4, num3, num4, num);
graphics.FillRectangle(brush2, num2 + num - 2f * num4, num3, num4, num);
return;
}
graphics.FillPolygon(brush2, new PointF[3]
{
new PointF(num2, num3),
new PointF(num2, num3 + num),
new PointF(num2 + num, num3 + num / 2f)
});
}
}
+8
View File
@@ -0,0 +1,8 @@
namespace VibranceHud.Music;
internal enum MediaKey
{
PlayPause,
Next,
Previous
}
+149
View File
@@ -0,0 +1,149 @@
using System;
using System.Runtime.InteropServices;
namespace VibranceHud.Music;
internal sealed class MusicHotkey : IDisposable
{
private const int Id = 1;
private readonly HotkeyWindow _window;
private bool _disposed;
internal static readonly HotkeySlot[] Slots = new HotkeySlot[4]
{
HotkeySlot.MusicMini,
HotkeySlot.MusicPlayPause,
HotkeySlot.MusicNext,
HotkeySlot.MusicPrevious
};
[DllImport("user32.dll", SetLastError = true)]
private static extern bool RegisterHotKey(nint hWnd, int id, uint fsModifiers, uint vk);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool UnregisterHotKey(nint hWnd, int id);
private MusicHotkey(HotkeyWindow window)
{
_window = window;
}
internal static MusicHotkey? TryRegister(AppSettings settings, Action onPressed)
{
return TryRegister(settings, HotkeySlot.MusicMini, onPressed);
}
internal static (bool Enabled, uint Mask, uint Key) Binding(AppSettings s, HotkeySlot slot)
{
return slot switch
{
HotkeySlot.MusicMini => (Enabled: s.MusicHotkeyEnabled, Mask: s.MusicHotkeyModifierMask, Key: s.MusicHotkeyVirtualKey),
HotkeySlot.MusicPlayPause => (Enabled: s.MusicPlayPauseHotkeyEnabled, Mask: s.MusicPlayPauseHotkeyModifierMask, Key: s.MusicPlayPauseHotkeyVirtualKey),
HotkeySlot.MusicNext => (Enabled: s.MusicNextHotkeyEnabled, Mask: s.MusicNextHotkeyModifierMask, Key: s.MusicNextHotkeyVirtualKey),
HotkeySlot.MusicPrevious => (Enabled: s.MusicPreviousHotkeyEnabled, Mask: s.MusicPreviousHotkeyModifierMask, Key: s.MusicPreviousHotkeyVirtualKey),
_ => throw new ArgumentOutOfRangeException("slot"),
};
}
internal static void SetBinding(AppSettings s, HotkeySlot slot, bool enabled, uint mask, uint key)
{
switch (slot)
{
case HotkeySlot.MusicMini:
s.MusicHotkeyEnabled = enabled;
s.MusicHotkeyModifierMask = mask;
s.MusicHotkeyVirtualKey = key;
break;
case HotkeySlot.MusicPlayPause:
s.MusicPlayPauseHotkeyEnabled = enabled;
s.MusicPlayPauseHotkeyModifierMask = mask;
s.MusicPlayPauseHotkeyVirtualKey = key;
break;
case HotkeySlot.MusicNext:
s.MusicNextHotkeyEnabled = enabled;
s.MusicNextHotkeyModifierMask = mask;
s.MusicNextHotkeyVirtualKey = key;
break;
case HotkeySlot.MusicPrevious:
s.MusicPreviousHotkeyEnabled = enabled;
s.MusicPreviousHotkeyModifierMask = mask;
s.MusicPreviousHotkeyVirtualKey = key;
break;
default:
throw new ArgumentOutOfRangeException("slot");
}
}
internal static MusicHotkey? TryRegister(AppSettings settings, HotkeySlot slot, Action onPressed)
{
(bool, uint, uint) tuple = Binding(settings, slot);
if (!tuple.Item1 || tuple.Item3 == 0)
{
return null;
}
if (Clashes(settings, slot, tuple.Item2, tuple.Item3))
{
return null;
}
HotkeyWindow hotkeyWindow = new HotkeyWindow();
if (!RegisterHotKey(hotkeyWindow.Handle, 1, tuple.Item2 | 0x4000, tuple.Item3))
{
hotkeyWindow.DestroyHandle();
return null;
}
hotkeyWindow.HotkeyPressed += (object? _, EventArgs e) =>
{
if (e is HotkeyEventArgs { HotkeyId: 1 })
{
onPressed();
}
};
return new MusicHotkey(hotkeyWindow);
}
internal static bool ClashesWithAnAppKey(AppSettings s)
{
return Clashes(s, HotkeySlot.MusicMini, s.MusicHotkeyModifierMask, s.MusicHotkeyVirtualKey);
}
internal static bool Clashes(AppSettings s, HotkeySlot slot, uint mask, uint vk)
{
if (HotkeyConflicts.Owner(s, slot, mask, vk).HasValue)
{
return true;
}
foreach (PresetKeyBinding presetKeyBinding in s.PresetKeyBindings)
{
if (vk != 0 && presetKeyBinding.ModifierMask == mask && presetKeyBinding.VirtualKey == vk)
{
return true;
}
}
return false;
}
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
try
{
UnregisterHotKey(_window.Handle, 1);
}
catch
{
}
try
{
_window.DestroyHandle();
}
catch
{
}
}
}
+279
View File
@@ -0,0 +1,279 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows.Forms;
using VibranceHud.Hotkeys;
namespace VibranceHud.Music;
internal static class MusicPlayer
{
internal sealed class TrayAttachment : IDisposable
{
private readonly INowPlayingSource _source;
private readonly IMediaKeys _keys;
private readonly List<MusicHotkey> _hotkeys = new List<MusicHotkey>();
private readonly AppSettings _settings;
private readonly Action? _savePosition;
private readonly ContextMenuStrip _menu;
private readonly HotkeyCaptureRelease _captureRelease;
private MusicMiniWindow? _mini;
internal ToolStripItem NowPlayingItem { get; }
internal MusicMiniWindow? MiniWindow => _mini;
internal bool KeyBound => _hotkeys.Count != 0;
internal TrayAttachment(ContextMenuStrip menu, AppSettings settings, INowPlayingSource source, IMediaKeys keys, Action? savePosition)
{
_source = source;
_keys = keys;
_settings = settings;
_savePosition = savePosition;
_menu = menu;
_captureRelease = new HotkeyCaptureRelease(HotkeyCaptureGate.Shared, ReleaseKeys, () =>
{
Rebind();
});
menu.Items.Add(new ToolStripSeparator
{
Tag = TrayTag
});
NowPlayingItem = Add(menu, "Now playing: ", null);
NowPlayingItem.Enabled = false;
NowPlayingItem.Visible = false;
Add(menu, "Play / pause", () =>
{
Command(MediaKey.PlayPause);
});
Add(menu, "Next track", () =>
{
Command(MediaKey.Next);
});
Add(menu, "Previous track", () =>
{
Command(MediaKey.Previous);
});
Add(menu, "Music mini player", ToggleMini);
menu.Opening += (object? _, CancelEventArgs _) =>
{
ReadNow();
};
Rebind();
HotkeysChanged += Rebind;
menu.Disposed += (object? _, EventArgs _) =>
{
Dispose();
};
Application.ApplicationExit += OnExit;
}
private static ToolStripItem Add(ContextMenuStrip menu, string words, Action? onClick)
{
EventHandler onClick2 = ((onClick == null) ? null : ((EventHandler)((object? _, EventArgs _) =>
{
onClick();
})));
ToolStripItem toolStripItem = menu.Items.Add(words, null, onClick2);
toolStripItem.Tag = TrayTag;
return toolStripItem;
}
internal void ReadNow()
{
if (_source.NeedsWorker)
{
Task.Run(() =>
{
NowPlaying result;
try
{
result = _source.Read();
}
catch
{
result = null;
}
try
{
_menu.BeginInvoke(() =>
{
SetTraySnapshot(result);
result?.Art?.Dispose();
});
}
catch
{
result?.Art?.Dispose();
}
});
}
else
{
NowPlaying traySnapshot;
try
{
traySnapshot = _source.Read();
}
catch
{
traySnapshot = null;
}
SetTraySnapshot(traySnapshot);
}
}
private void SetTraySnapshot(NowPlaying? now)
{
if (!_menu.IsDisposed)
{
NowPlayingItem.Text = ((now == null) ? "Now playing: " : ("Now playing: " + now.Line));
NowPlayingItem.Visible = now != null;
}
}
private void Command(MediaKey key)
{
MusicPoller.For(_source).Command(key, _keys, _menu);
}
private bool Rebind(HotkeySlot? requested = null)
{
ReleaseKeys();
if (HotkeyCaptureGate.Shared.IsCapturing)
{
return true;
}
bool result = true;
HotkeySlot[] slots = MusicHotkey.Slots;
foreach (HotkeySlot slot in slots)
{
(bool, uint, uint) tuple = MusicHotkey.Binding(_settings, slot);
if (!tuple.Item1 || tuple.Item3 == 0)
{
continue;
}
Action onPressed = ((slot == HotkeySlot.MusicMini) ? new Action(ToggleMini) : ((Action)(() =>
{
Command((slot == HotkeySlot.MusicNext) ? MediaKey.Next : ((slot == HotkeySlot.MusicPrevious) ? MediaKey.Previous : MediaKey.PlayPause));
})));
MusicHotkey musicHotkey = MusicHotkey.TryRegister(_settings, slot, onPressed);
if (musicHotkey == null)
{
if (!requested.HasValue || requested == slot)
{
result = false;
}
}
else
{
_hotkeys.Add(musicHotkey);
}
}
return result;
}
private void ReleaseKeys()
{
foreach (MusicHotkey hotkey in _hotkeys)
{
hotkey.Dispose();
}
_hotkeys.Clear();
}
internal void ToggleMini()
{
if (_mini == null || _mini.IsDisposed)
{
_mini = new MusicMiniWindow(_source, _keys, _settings, _savePosition);
}
_mini.Toggle();
}
private void OnExit(object? sender, EventArgs e)
{
Dispose();
}
public void Dispose()
{
Application.ApplicationExit -= OnExit;
HotkeysChanged -= Rebind;
_captureRelease.Dispose();
ReleaseKeys();
if (_mini != null && !_mini.IsDisposed)
{
_mini.Dispose();
}
_mini = null;
}
}
internal const bool Enabled = true;
internal static readonly object TrayTag = new object();
internal const string NowPlayingPrefix = "Now playing: ";
internal const string PlayPauseWords = "Play / pause";
internal const string NextWords = "Next track";
internal const string PreviousWords = "Previous track";
internal const string MiniPlayerWords = "Music mini player";
internal static INowPlayingSource DefaultSource { get; set; } = new WindowsSessionSource();
internal static IMediaKeys DefaultKeys { get; set; } = new WindowsMediaKeys();
internal static event Func<HotkeySlot?, bool>? HotkeysChanged;
internal static bool RebindHotkeys(HotkeySlot? slot = null)
{
return HotkeysChanged?.Invoke(slot) ?? true;
}
internal static TrayAttachment? AttachToTray(ContextMenuStrip menu, AppSettings settings, bool enabled = true, INowPlayingSource? source = null, IMediaKeys? keys = null, Action? savePosition = null)
{
if (!enabled)
{
return null;
}
return new TrayAttachment(menu, settings, source ?? DefaultSource, keys ?? DefaultKeys, savePosition);
}
internal static MusicStrip? AttachToPopup(Form popup, Control slot, bool enabled = true, INowPlayingSource? source = null, IMediaKeys? keys = null)
{
if (!enabled)
{
return null;
}
MusicStrip strip = new MusicStrip(slot, source ?? DefaultSource, keys ?? DefaultKeys);
popup.Controls.Add(strip);
strip.BringToFront();
strip.AttachPoller(popup);
popup.VisibleChanged += (object? _, EventArgs _) =>
{
if (popup.Visible)
{
strip.ReadNow();
}
};
popup.Activated += (object? _, EventArgs _) =>
{
strip.ReadNow();
};
return strip;
}
}
+284
View File
@@ -0,0 +1,284 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace VibranceHud.Music;
internal sealed class MusicPoller
{
private static readonly ConditionalWeakTable<INowPlayingSource, MusicPoller> Pollers = new ConditionalWeakTable<INowPlayingSource, MusicPoller>();
private readonly INowPlayingSource _source;
private readonly System.Windows.Forms.Timer _timer;
private readonly Dictionary<Control, Action<NowPlaying?>> _views = new Dictionary<Control, Action<NowPlaying>>();
private volatile bool _busy;
private int _generation;
private Control? _lastHost;
private CancellationTokenSource? _readCancellation;
private NowPlaying? _snapshot;
internal bool Running => _timer.Enabled;
private Control? Host => _views.Keys.FirstOrDefault((Control c) => !c.IsDisposed && c.Visible && c.IsHandleCreated);
internal static MusicPoller For(INowPlayingSource source)
{
return Pollers.GetValue(source, (INowPlayingSource s) => new MusicPoller(s));
}
internal MusicPoller(INowPlayingSource source)
{
_source = source;
_timer = new System.Windows.Forms.Timer
{
Interval = 1000
};
_timer.Tick += (object? _, EventArgs _) =>
{
Refresh();
};
}
internal void Attach(Control owner, Action<NowPlaying?> show)
{
_views[owner] = show;
owner.VisibleChanged += (object? _, EventArgs _) =>
{
Reassess();
};
owner.HandleDestroyed += (object? _, EventArgs _) =>
{
if (!owner.RecreatingHandle && owner == _lastHost)
{
_lastHost = null;
_generation++;
_readCancellation?.Cancel();
_busy = false;
}
};
owner.Disposed += (object? _, EventArgs _) =>
{
_views.Remove(owner);
Reassess();
if (_views.Count == 0)
{
_timer.Dispose();
_snapshot?.Art?.Dispose();
_snapshot = null;
Pollers.Remove(_source);
}
};
Reassess();
}
private void Reassess()
{
Control host = Host;
bool flag = host != null;
if (host != _lastHost)
{
_lastHost = host;
_generation++;
_readCancellation?.Cancel();
_busy = false;
}
if (!flag)
{
_timer.Stop();
_generation++;
_readCancellation?.Cancel();
_busy = false;
}
else if (!_timer.Enabled)
{
_timer.Start();
Refresh();
}
}
internal void Refresh()
{
Control host = Host;
if (host == null || _busy)
{
return;
}
if (!_source.NeedsWorker)
{
Apply(SafeRead());
return;
}
_busy = true;
int generation = _generation;
_readCancellation?.Dispose();
_readCancellation = new CancellationTokenSource();
CancellationToken cancellation = _readCancellation.Token;
Task.Run(() =>
{
NowPlaying snapshot;
try
{
snapshot = _source.Read(cancellation);
}
catch
{
snapshot = null;
}
try
{
if (host.IsDisposed || !host.IsHandleCreated)
{
snapshot?.Art?.Dispose();
if (generation == _generation)
{
_busy = false;
}
}
else
{
host.BeginInvoke(() =>
{
if (generation != _generation || Host == null)
{
snapshot?.Art?.Dispose();
}
else
{
_busy = false;
Apply(snapshot);
}
});
}
}
catch
{
snapshot?.Art?.Dispose();
if (generation == _generation)
{
_busy = false;
}
}
});
}
private NowPlaying? SafeRead()
{
try
{
return _source.Read();
}
catch
{
return null;
}
}
private void Apply(NowPlaying? snapshot)
{
NowPlaying snapshot2 = _snapshot;
_snapshot = snapshot;
Action<NowPlaying>[] array = _views.Values.ToArray();
for (int i = 0; i < array.Length; i++)
{
array[i](snapshot);
}
if (snapshot2?.Art != snapshot?.Art)
{
snapshot2?.Art?.Dispose();
}
}
internal void ReadForTestOrRefresh(Action<NowPlaying?> show)
{
if (_source.NeedsWorker)
{
Refresh();
}
else
{
show(SafeRead());
}
}
internal void Command(MediaKey key, IMediaKeys fallback, Control? commandHost = null)
{
Control host = Host ?? commandHost;
if (host != null && !host.IsHandleCreated)
{
_ = host.Handle;
}
if (!_source.NeedsWorker)
{
bool flag;
try
{
flag = _source.TryCommand(key);
}
catch
{
flag = false;
}
if (!flag)
{
fallback.Send(key);
}
RefreshAfterCommand();
return;
}
Task.Run(() =>
{
bool flag2;
try
{
flag2 = _source.TryCommand(key);
}
catch
{
flag2 = false;
}
if (!flag2 && host != null)
{
try
{
host.BeginInvoke(() =>
{
fallback.Send(key);
});
}
catch
{
}
}
if (host != null)
{
try
{
host.BeginInvoke(RefreshAfterCommand);
}
catch
{
}
}
});
}
internal async void RefreshAfterCommand()
{
if (Host != null)
{
await Task.Delay(300);
Refresh();
}
}
}
+114
View File
@@ -0,0 +1,114 @@
using System;
using System.Drawing;
using System.Windows.Forms;
using VibranceHud.Design;
namespace VibranceHud.Music;
internal sealed class MusicStrip : Control
{
private readonly Control _slot;
private readonly IMediaKeys _keys;
private readonly MusicPoller _poller;
private readonly MediaGlyphButton[] _buttons;
internal NowPlaying? Showing { get; private set; }
internal MusicStrip(Control slot, INowPlayingSource source, IMediaKeys keys)
{
_slot = slot;
_keys = keys;
_poller = MusicPoller.For(source);
SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true);
BackColor = Color.Transparent;
Bounds = slot.Bounds;
Visible = false;
TabStop = false;
AccessibleName = "Now playing";
_buttons = new MediaGlyphButton[3]
{
new MediaGlyphButton(MediaKey.Previous),
new MediaGlyphButton(MediaKey.PlayPause),
new MediaGlyphButton(MediaKey.Next)
};
MediaGlyphButton[] buttons = _buttons;
foreach (MediaGlyphButton mediaGlyphButton in buttons)
{
MediaKey key = mediaGlyphButton.Key;
mediaGlyphButton.Click += (object? _, EventArgs _) =>
{
_poller.Command(key, _keys);
};
Controls.Add(mediaGlyphButton);
}
LayoutButtons();
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
LayoutButtons();
}
internal void AttachPoller(Form popup)
{
_poller.Attach(popup, ShowSnapshot);
}
private void LayoutButtons()
{
if (_buttons != null)
{
int dpi = ControlInk.Dpi(this);
int num = Math.Min(Height, ControlInk.Px(dpi, 24));
int y = (Height - num) / 2;
int num2 = ControlInk.Px(dpi, 3) + ((Showing?.Art != null) ? (num + ControlInk.Px(dpi, 4)) : 0);
MediaGlyphButton[] buttons = _buttons;
for (int i = 0; i < buttons.Length; i++)
{
buttons[i].Bounds = new Rectangle(num2, y, num, num);
num2 += num;
}
}
}
internal void ReadNow()
{
_poller.ReadForTestOrRefresh(ShowSnapshot);
}
internal void ShowSnapshot(NowPlaying? now)
{
bool flag = now != Showing;
Showing = now;
Visible = now != null;
_slot.Visible = now == null;
_buttons[0].Enabled = now?.CanPrevious ?? false;
_buttons[1].Enabled = now?.CanPlayPause ?? false;
_buttons[1].IsPlaying = now?.IsPlaying ?? false;
_buttons[2].Enabled = now?.CanNext ?? false;
LayoutButtons();
if (flag)
{
Invalidate();
}
}
protected override void OnPaint(PaintEventArgs e)
{
if (!(Showing == null))
{
int dpi = ControlInk.Dpi(this);
if (Showing.Art != null)
{
int num = Math.Min(Height, ControlInk.Px(dpi, 24));
e.Graphics.DrawImage(Showing.Art, new Rectangle(ControlInk.Px(dpi, 3), (Height - num) / 2, num, num));
}
int num2 = _buttons[^1].Right + ControlInk.Px(dpi, 6);
TextRenderer.DrawText(bounds: new Rectangle(num2, 0, Math.Max(0, Width - num2), Height), dc: e.Graphics, text: Showing.Line, font: Fonts.Caption, foreColor: ControlInk.Text2, flags: TextFormatFlags.EndEllipsis | TextFormatFlags.NoPrefix | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter);
}
}
}
+8
View File
@@ -0,0 +1,8 @@
namespace VibranceHud.Music;
internal sealed class NoMediaKeys : IMediaKeys
{
public void Send(MediaKey key)
{
}
}
+9
View File
@@ -0,0 +1,9 @@
namespace VibranceHud.Music;
internal sealed class NoMusicSource : INowPlayingSource
{
public string? SpotifyWindowTitle()
{
return null;
}
}
+58
View File
@@ -0,0 +1,58 @@
using System;
using System.Drawing;
namespace VibranceHud.Music;
internal sealed record NowPlaying(string Artist, string Song)
{
internal string Title => Song;
internal string? AppName { get; init; }
internal bool IsPlaying { get; init; } = true;
internal bool CanPrevious { get; init; } = true;
internal bool CanNext { get; init; } = true;
internal bool CanPlayPause { get; init; } = true;
internal Bitmap? Art { get; init; }
internal string Line
{
get
{
if (!string.IsNullOrWhiteSpace(Artist))
{
return Title + " – " + Artist;
}
return Title;
}
}
internal static NowPlaying? FromSpotifyTitle(string? title)
{
if (string.IsNullOrWhiteSpace(title))
{
return null;
}
string text = title.Trim();
if (text.StartsWith("Spotify", StringComparison.OrdinalIgnoreCase))
{
return null;
}
int num = text.IndexOf(" - ", StringComparison.Ordinal);
if (num <= 0)
{
return null;
}
string text2 = text.Substring(0, num).Trim();
string text3 = text.Substring(num + 3).Trim();
if (text2.Length == 0 || text3.Length == 0)
{
return null;
}
return new NowPlaying(text2, text3);
}
}
@@ -0,0 +1,39 @@
using System.Diagnostics;
namespace VibranceHud.Music;
internal sealed class SpotifyWindowTitleSource : INowPlayingSource
{
public string? SpotifyWindowTitle()
{
Process[] processesByName;
try
{
processesByName = Process.GetProcessesByName("Spotify");
}
catch
{
return null;
}
string text = null;
Process[] array = processesByName;
foreach (Process process in array)
{
try
{
if (text == null && !string.IsNullOrWhiteSpace(process.MainWindowTitle))
{
text = process.MainWindowTitle;
}
}
catch
{
}
finally
{
process.Dispose();
}
}
return text;
}
}
+40
View File
@@ -0,0 +1,40 @@
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace VibranceHud.Music;
internal sealed class WindowsMediaKeys : IMediaKeys
{
private const int WM_APPCOMMAND = 793;
private const int APPCOMMAND_MEDIA_NEXTTRACK = 11;
private const int APPCOMMAND_MEDIA_PREVIOUSTRACK = 12;
private const int APPCOMMAND_MEDIA_PLAY_PAUSE = 14;
private NativeWindow? _window;
[DllImport("user32.dll")]
private static extern nint SendMessage(nint hWnd, int msg, nint wParam, nint lParam);
internal static int AppCommandFor(MediaKey key)
{
return key switch
{
MediaKey.Next => 11,
MediaKey.Previous => 12,
_ => 14,
};
}
public void Send(MediaKey key)
{
if (_window == null)
{
_window = new NativeWindow();
_window.CreateHandle(new CreateParams());
}
SendMessage(_window.Handle, 793, _window.Handle, AppCommandFor(key) << 16);
}
}
+59
View File
@@ -0,0 +1,59 @@
using System;
using System.Threading;
namespace VibranceHud.Music;
internal sealed class WindowsSessionSource : INowPlayingSource
{
private readonly INowPlayingSource _windows;
private readonly INowPlayingSource _spotify;
public bool NeedsWorker => true;
internal WindowsSessionSource(INowPlayingSource? windows = null, INowPlayingSource? spotify = null)
{
_windows = windows ?? new GsmtcSource();
_spotify = spotify ?? new SpotifyWindowTitleSource();
}
public NowPlaying? Read()
{
return Read(CancellationToken.None);
}
public NowPlaying? Read(CancellationToken cancellation)
{
try
{
return _windows.Read(cancellation);
}
catch (OperationCanceledException)
{
return null;
}
catch
{
try
{
return _spotify.Read(cancellation);
}
catch
{
return null;
}
}
}
public bool TryCommand(MediaKey key)
{
try
{
return _windows.TryCommand(key);
}
catch
{
return false;
}
}
}