using System.Windows;
using System.Windows.Interop;
using Moli.Desktop.Configuration;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Layout;
namespace Moli.Desktop.Interop;
/// Default Win32 facade for window styles, desktop placement, and monitor discovery.
public sealed class Win32InteropService : IWin32InteropService
{
private readonly IReadOnlyList _strategies;
private readonly IDiagnosticsService _diagnostics;
public Win32InteropService(IEnumerable strategies, IDiagnosticsService diagnostics)
{
_strategies = [.. strategies];
_diagnostics = diagnostics;
}
public IntPtr GetWindowHandle(Window window) => new WindowInteropHelper(window).Handle;
public void SetClickThrough(IntPtr hwnd, bool enabled)
{
SetStyleFlag(hwnd, NativeMethods.WsExLayered | NativeMethods.WsExTransparent, enabled, "SetClickThrough");
}
public void SetToolWindow(IntPtr hwnd, bool enabled)
{
SetStyleFlag(hwnd, NativeMethods.WsExToolWindow, enabled, "SetToolWindow");
}
public void SetNoActivate(IntPtr hwnd, bool enabled)
{
SetStyleFlag(hwnd, NativeMethods.WsExNoActivate, enabled, "SetNoActivate");
}
public void SetLayered(IntPtr hwnd, bool enabled, byte opacity)
{
SetStyleFlag(hwnd, NativeMethods.WsExLayered, enabled, "SetLayered");
if (enabled && !NativeMethods.SetLayeredWindowAttributes(hwnd, 0, opacity, NativeMethods.LwaAlpha))
{
RecordWin32Failure("SetLayeredWindowAttributes", hwnd);
}
}
public void MoveToDesktopLayer(IntPtr hwnd, DesktopLayerMode mode, MonitorInfo monitor)
{
var candidates = mode == DesktopLayerMode.WorkerW
? _strategies.OrderBy(strategy => strategy is WorkerWDesktopLayerStrategy ? 0 : 1)
: _strategies.OrderBy(strategy => strategy is BottomDesktopLayerStrategy ? 0 : 1);
foreach (var strategy in candidates)
{
if (!strategy.IsSupported())
{
continue;
}
if (strategy.TryAttachWallpaperWindow(hwnd, monitor, out var error))
{
return;
}
_diagnostics.Record(
DiagnosticSeverity.Warning,
DiagnosticCodes.DesktopLayerAttachFailed,
"Desktop layer strategy failed.",
new Dictionary
{
["strategy"] = strategy.Name,
["reason"] = error ?? "Unknown"
});
}
}
public void SetBottomMost(IntPtr hwnd)
{
if (!NativeMethods.SetWindowPos(
hwnd,
NativeMethods.HwndBottom,
0,
0,
0,
0,
NativeMethods.SwpNoMove | NativeMethods.SwpNoSize | NativeMethods.SwpNoActivate))
{
RecordWin32Failure("SetBottomMost", hwnd);
}
}
public IReadOnlyList GetMonitors()
{
var monitors = new List();
NativeMethods.EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, (
IntPtr hMonitor,
IntPtr hdcMonitor,
ref NativeMethods.Rect monitorRect,
IntPtr data) =>
{
var native = new NativeMethods.MonitorInfoEx
{
Size = System.Runtime.InteropServices.Marshal.SizeOf(),
DeviceName = string.Empty
};
if (!NativeMethods.GetMonitorInfo(hMonitor, ref native))
{
return true;
}
var id = string.IsNullOrWhiteSpace(native.DeviceName)
? $"monitor-{monitors.Count + 1}"
: native.DeviceName;
monitors.Add(new MonitorInfo
{
Id = new MonitorId(native.Flags ? "primary" : id),
Bounds = ToRectD(native.Monitor),
WorkArea = ToRectD(native.WorkArea),
IsPrimary = native.Flags,
Scale = 1
});
return true;
}, IntPtr.Zero);
return monitors.Count > 0
? monitors
: [new MonitorInfo
{
Id = new MonitorId("primary"),
Bounds = new RectD(0, 0, SystemParameters.PrimaryScreenWidth, SystemParameters.PrimaryScreenHeight),
WorkArea = new RectD(0, 0, SystemParameters.WorkArea.Width, SystemParameters.WorkArea.Height),
IsPrimary = true
}];
}
private void SetStyleFlag(IntPtr hwnd, int flag, bool enabled, string operation)
{
var current = NativeMethods.GetWindowLongPtr(hwnd, NativeMethods.GwlExStyle).ToInt64();
var styleFlag = unchecked((uint)flag);
var currentStyle = unchecked((uint)current);
var updated = enabled ? currentStyle | styleFlag : currentStyle & ~styleFlag;
NativeMethods.SetWindowLongPtr(hwnd, NativeMethods.GwlExStyle, new IntPtr(updated));
var error = NativeMethods.GetLastError();
if (error != 0)
{
_diagnostics.Record(
DiagnosticSeverity.Warning,
DiagnosticCodes.Win32InteropFailed,
$"{operation} failed.",
new Dictionary { ["hwnd"] = hwnd.ToString("X"), ["error"] = error.ToString() });
}
}
private void RecordWin32Failure(string operation, IntPtr hwnd)
{
_diagnostics.Record(
DiagnosticSeverity.Warning,
DiagnosticCodes.Win32InteropFailed,
$"{operation} failed.",
new Dictionary
{
["hwnd"] = hwnd.ToString("X"),
["error"] = NativeMethods.GetLastError().ToString()
});
}
private static RectD ToRectD(NativeMethods.Rect rect)
{
return new RectD(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top);
}
}