using System.Windows;
using System.Windows.Interop;
using System.Windows.Threading;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Hotkeys;
using Moli.Desktop.Interop;
using Application = System.Windows.Application;
namespace Moli.Desktop.Runtime;
public sealed class Win32HotkeyApi : INativeHotkeyApi
{
public bool Register(IntPtr hwnd, int id, uint modifiers, uint virtualKey, out int win32Error)
{
var succeeded = NativeMethods.RegisterHotKey(hwnd, id, modifiers, virtualKey);
win32Error = succeeded ? 0 : NativeMethods.GetLastError();
return succeeded;
}
public bool Unregister(IntPtr hwnd, int id)
=> NativeMethods.UnregisterHotKey(hwnd, id);
}
///
/// Hidden top-level window that receives WM_HOTKEY. Message-only windows and
/// thread-pool HWNDs never pump those messages, so this must be created on the WPF UI thread.
///
public sealed class WpfHotkeyMessageWindow : IHotkeyMessageWindow
{
private HwndSource? _source;
public IntPtr Handle => _source?.Handle ?? IntPtr.Zero;
public event Action? HotkeyPosted;
public void EnsureCreated()
{
if (_source is not null)
{
return;
}
var parameters = new HwndSourceParameters("MoliHotkeyMonitor")
{
Width = 1,
Height = 1,
PositionX = -32000,
PositionY = -32000,
WindowStyle = unchecked((int)NativeMethods.WsPopup),
ExtendedWindowStyle = NativeMethods.WsExToolWindow | NativeMethods.WsExNoActivate
};
_source = new HwndSource(parameters);
_source.AddHook(WndProc);
}
public void Dispose()
{
if (_source is null)
{
return;
}
_source.RemoveHook(WndProc);
_source.Dispose();
_source = null;
}
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg != NativeMethods.WmHotkey)
{
return IntPtr.Zero;
}
HotkeyPosted?.Invoke(wParam.ToInt32());
handled = true;
return IntPtr.Zero;
}
}
public sealed class HotkeyService : IHotkeyService
{
private readonly IDiagnosticsService _diagnostics;
private readonly INativeHotkeyApi _api;
private readonly IHotkeyMessageWindow _window;
private readonly object _gate = new();
private readonly Dictionary _registered = [];
private readonly List _registrations = [];
private IReadOnlyList _bindings = [];
private IntPtr _hwnd;
private bool _paused;
private bool _disposed;
private bool _subscribed;
public HotkeyService(
IDiagnosticsService diagnostics,
INativeHotkeyApi? api = null,
IHotkeyMessageWindow? messageWindow = null)
{
_diagnostics = diagnostics;
_api = api ?? new Win32HotkeyApi();
_window = messageWindow ?? new WpfHotkeyMessageWindow();
}
public event Func? HotkeyPressed;
public IReadOnlyList Registrations
{
get
{
lock (_gate)
{
return [.. _registrations];
}
}
}
public Task ReplaceBindingsAsync(IReadOnlyList bindings, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
return RunOnUiAsync(() =>
{
cancellationToken.ThrowIfCancellationRequested();
lock (_gate)
{
EnsureMessageWindow();
UnregisterAllCore();
_bindings = bindings.ToArray();
if (!_paused)
{
RegisterAllCore();
}
else
{
_registrations.Clear();
foreach (var binding in _bindings)
{
_registrations.Add(ToPausedRegistration(binding));
}
}
}
});
}
public void Pause()
{
RunOnUi(() =>
{
lock (_gate)
{
if (_paused)
{
return;
}
_paused = true;
UnregisterAllCore();
_registrations.Clear();
foreach (var binding in _bindings)
{
_registrations.Add(ToPausedRegistration(binding));
}
}
});
}
public void Resume()
{
RunOnUi(() =>
{
lock (_gate)
{
if (!_paused)
{
return;
}
_paused = false;
EnsureMessageWindow();
RegisterAllCore();
}
});
}
public void UnregisterAll()
{
RunOnUi(() =>
{
lock (_gate)
{
UnregisterAllCore();
}
});
}
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
RunOnUi(() =>
{
lock (_gate)
{
UnregisterAllCore();
if (_subscribed)
{
_window.HotkeyPosted -= OnHotkeyPosted;
_subscribed = false;
}
_window.Dispose();
_hwnd = IntPtr.Zero;
}
});
}
private void EnsureMessageWindow()
{
try
{
_window.EnsureCreated();
}
catch (InvalidOperationException ex)
{
_diagnostics.Record(
DiagnosticSeverity.Error,
DiagnosticCodes.HotkeyMessageWindowFailed,
"Failed to create the hotkey message window on the UI thread.",
new Dictionary { ["exception"] = ex.Message });
}
_hwnd = _window.Handle;
if (_subscribed)
{
return;
}
_window.HotkeyPosted += OnHotkeyPosted;
_subscribed = true;
}
private void RegisterAllCore()
{
UnregisterAllCore();
if (_hwnd == IntPtr.Zero)
{
_diagnostics.Record(
DiagnosticSeverity.Error,
DiagnosticCodes.HotkeyMessageWindowFailed,
"Hotkey message window handle is zero; WM_HOTKEY would never be delivered.");
foreach (var binding in _bindings)
{
_registrations.Add(new HotkeyRegistration
{
BindingId = binding.Id,
Keys = binding.Keys,
State = binding.Enabled ? HotkeyRegistrationState.Invalid : HotkeyRegistrationState.Disabled,
Detail = binding.Enabled ? DiagnosticCodes.HotkeyMessageWindowFailed : null
});
}
return;
}
var nextId = 1;
foreach (var binding in _bindings)
{
if (!binding.Enabled)
{
_registrations.Add(new HotkeyRegistration
{
BindingId = binding.Id,
Keys = binding.Keys,
State = HotkeyRegistrationState.Disabled
});
continue;
}
if (!HotkeyChord.TryParse(binding.Keys, out var chord, out var errorCode))
{
_registrations.Add(new HotkeyRegistration
{
BindingId = binding.Id,
Keys = binding.Keys,
State = HotkeyRegistrationState.Invalid,
Detail = errorCode
});
continue;
}
var id = nextId++;
if (_api.Register(_hwnd, id, chord.RegisterModifiers, chord.VirtualKey, out var win32Error))
{
_registered[id] = binding;
_registrations.Add(new HotkeyRegistration
{
BindingId = binding.Id,
Keys = chord.Canonical,
State = HotkeyRegistrationState.Registered
});
_diagnostics.Record(
DiagnosticSeverity.Info,
DiagnosticCodes.HotkeyRegistered,
$"Registered hotkey {chord.Canonical}.",
new Dictionary
{
["id"] = binding.Id,
["keys"] = chord.Canonical,
["hwnd"] = _hwnd.ToString("X")
});
continue;
}
var conflict = win32Error == NativeMethods.ErrorHotkeyAlreadyRegistered;
_registrations.Add(new HotkeyRegistration
{
BindingId = binding.Id,
Keys = chord.Canonical,
State = conflict ? HotkeyRegistrationState.Conflict : HotkeyRegistrationState.Invalid,
Detail = win32Error.ToString()
});
_diagnostics.Record(
conflict ? DiagnosticSeverity.Warning : DiagnosticSeverity.Error,
conflict ? DiagnosticCodes.HotkeyConflict : DiagnosticCodes.Win32InteropFailed,
conflict
? $"Hotkey {chord.Canonical} is already registered."
: $"Failed to register hotkey {chord.Canonical}.",
new Dictionary
{
["id"] = binding.Id,
["keys"] = chord.Canonical,
["win32Error"] = win32Error.ToString()
});
}
}
private void UnregisterAllCore()
{
foreach (var id in _registered.Keys.ToArray())
{
_api.Unregister(_hwnd, id);
if (_registered.TryGetValue(id, out var binding))
{
_diagnostics.Record(
DiagnosticSeverity.Info,
DiagnosticCodes.HotkeyUnregistered,
$"Unregistered hotkey {binding.Keys}.",
new Dictionary { ["id"] = binding.Id, ["keys"] = binding.Keys });
}
}
_registered.Clear();
_registrations.Clear();
}
private static HotkeyRegistration ToPausedRegistration(HotkeyBinding binding)
=> new()
{
BindingId = binding.Id,
Keys = binding.Keys,
State = HotkeyRegistrationState.Disabled,
Detail = "paused"
};
private void OnHotkeyPosted(int id)
{
HotkeyBinding? binding = null;
lock (_gate)
{
if (_registered.TryGetValue(id, out var found))
{
binding = found;
}
}
if (binding is null)
{
return;
}
_diagnostics.Record(
DiagnosticSeverity.Info,
DiagnosticCodes.HotkeyInvoked,
$"Hotkey {binding.Keys} invoked.",
new Dictionary { ["id"] = binding.Id, ["keys"] = binding.Keys });
var handler = HotkeyPressed;
if (handler is not null)
{
_ = Task.Run(() => handler(binding));
}
}
private static void RunOnUi(Action action)
{
var dispatcher = Application.Current?.Dispatcher;
if (dispatcher is null || dispatcher.CheckAccess())
{
action();
return;
}
dispatcher.Invoke(action, DispatcherPriority.Send);
}
private static Task RunOnUiAsync(Action action)
{
var dispatcher = Application.Current?.Dispatcher;
if (dispatcher is null || dispatcher.CheckAccess())
{
action();
return Task.CompletedTask;
}
return dispatcher.InvokeAsync(action, DispatcherPriority.Send).Task;
}
}