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

+448
View File
@@ -0,0 +1,448 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Windows.Forms;
namespace VibranceHud.Capabilities;
public static class CapabilityProbe
{
private sealed class PerDeviceGammaTarget : IPerDeviceGammaProbeTarget
{
public IReadOnlyList<string> Devices()
{
return MultiMonitorGammaRamp.Devices();
}
public bool TrySet(string device, ushort[] ramp)
{
return MultiMonitorGammaRamp.SetRampOn(device, ramp);
}
public ushort[]? TryGet(string device)
{
return MultiMonitorGammaRamp.ReadRampOn(device);
}
}
private struct POINT
{
public int X;
public int Y;
}
private sealed class ScreenGammaTarget : IGammaProbeTarget
{
[DllImport("user32.dll")]
private static extern nint GetDC(nint hWnd);
[DllImport("user32.dll")]
private static extern int ReleaseDC(nint hWnd, nint hDC);
[DllImport("gdi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetDeviceGammaRamp(nint hDC, ushort[] ramp);
[DllImport("gdi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetDeviceGammaRamp(nint hDC, ushort[] ramp);
public bool TrySet(ushort[] ramp)
{
nint dC = GetDC(IntPtr.Zero);
if (dC == IntPtr.Zero)
{
return false;
}
try
{
return SetDeviceGammaRamp(dC, ramp);
}
finally
{
ReleaseDC(IntPtr.Zero, dC);
}
}
public ushort[]? TryGet()
{
nint dC = GetDC(IntPtr.Zero);
if (dC == IntPtr.Zero)
{
return null;
}
try
{
ushort[] array = new ushort[768];
return GetDeviceGammaRamp(dC, array) ? array : null;
}
finally
{
ReleaseDC(IntPtr.Zero, dC);
}
}
}
internal const int SameCurveTolerance = 512;
internal const float TestGamma = 6f;
private const int MONITOR_DEFAULTTONEAREST = 2;
internal static GammaSupport Classify(ushort[] written, ushort[]? readback, ushort[] identity)
{
if (readback == null || written.Length == 0 || readback.Length != written.Length)
{
return GammaSupport.Untested;
}
double num = MeanAbsoluteDifference(readback, written);
double num2 = MeanAbsoluteDifference(readback, identity);
if (num <= 512.0)
{
return GammaSupport.Working;
}
if (num2 <= 512.0)
{
return GammaSupport.Refused;
}
return GammaSupport.Clamped;
}
private static double MeanAbsoluteDifference(ushort[] a, ushort[] b)
{
long num = 0L;
for (int i = 0; i < a.Length; i++)
{
num += Math.Abs(a[i] - b[i]);
}
return (double)num / (double)a.Length;
}
internal static GammaRefusal WhyRefused(GammaSupport result, bool writeAccepted, bool elevated, bool hdrActive, ushort[]? before, ushort[] identity)
{
if (result != GammaSupport.Refused)
{
return GammaRefusal.None;
}
if (hdrActive)
{
return GammaRefusal.HdrOn;
}
if (!elevated)
{
return GammaRefusal.NotElevated;
}
if (!writeAccepted)
{
return GammaRefusal.WriteFailed;
}
if (before != null && before.Length == identity.Length && MeanAbsoluteDifference(before, identity) > 512.0)
{
return GammaRefusal.RampHeldByOther;
}
return GammaRefusal.ReadbackIdentity;
}
internal static ushort[] TestRamp()
{
return GammaCurve.Build(6f);
}
internal static ushort[] GentleRamp()
{
return GammaCurve.Build(1.15f);
}
private static bool GentleGetsThrough(Func<ushort[], bool> trySet, Func<ushort[]?> tryGet)
{
ushort[] array = GentleRamp();
if (trySet(array))
{
return Classify(array, tryGet(), GammaCurve.Identity()) == GammaSupport.Working;
}
return false;
}
internal static GammaSupport ProbeGamma(IGammaProbeTarget target)
{
bool couldRead;
return ProbeGamma(target, out couldRead);
}
internal static GammaSupport ProbeGamma(IGammaProbeTarget target, out bool couldRead)
{
couldRead = false;
if (target == null)
{
return GammaSupport.Untested;
}
ushort[] array = null;
try
{
array = target.TryGet();
couldRead = array != null;
if (array == null)
{
return GammaSupport.Refused;
}
ushort[] array2 = TestRamp();
GammaSupport gammaSupport = (target.TrySet(array2) ? Classify(array2, target.TryGet(), GammaCurve.Identity()) : GammaSupport.Refused);
if (gammaSupport == GammaSupport.Refused && GentleGetsThrough(target.TrySet, target.TryGet))
{
return GammaSupport.Clamped;
}
return gammaSupport;
}
catch
{
return GammaSupport.Untested;
}
finally
{
try
{
if (array != null)
{
target.TrySet(array);
}
}
catch
{
}
}
}
internal static IReadOnlyList<DeviceGamma> ProbeDevices(IPerDeviceGammaProbeTarget target, bool elevated, bool hdrActive)
{
bool anyReadable;
return ProbeDevices(target, elevated, hdrActive, out anyReadable);
}
internal static IReadOnlyList<DeviceGamma> ProbeDevices(IPerDeviceGammaProbeTarget target, bool elevated, bool hdrActive, out bool anyReadable)
{
anyReadable = false;
List<DeviceGamma> list = new List<DeviceGamma>();
if (target == null)
{
return list;
}
IReadOnlyList<string> readOnlyList;
try
{
readOnlyList = target.Devices() ?? Array.Empty<string>();
}
catch
{
return list;
}
ushort[] identity = GammaCurve.Identity();
foreach (string device in readOnlyList)
{
ushort[] array = null;
try
{
array = target.TryGet(device);
if (array != null)
{
anyReadable = true;
ushort[] array2 = TestRamp();
bool flag = target.TrySet(device, array2);
ushort[] readback = (flag ? target.TryGet(device) : null);
GammaSupport gammaSupport = (flag ? Classify(array2, readback, identity) : GammaSupport.Refused);
if (gammaSupport == GammaSupport.Refused && GentleGetsThrough((ushort[] r) => target.TrySet(device, r), () => target.TryGet(device)))
{
gammaSupport = GammaSupport.Clamped;
}
list.Add(new DeviceGamma(device, gammaSupport, WhyRefused(gammaSupport, flag, elevated, hdrActive, array, identity)));
}
else
{
list.Add(new DeviceGamma(device, GammaSupport.Untested, GammaRefusal.None));
}
}
catch
{
list.Add(new DeviceGamma(device, GammaSupport.Untested, GammaRefusal.None));
}
finally
{
try
{
if (array != null)
{
target.TrySet(device, array);
}
}
catch
{
}
}
}
return list;
}
public static MachineCapabilities Run(bool driverVibrance, OverlayMode overlayPath, IGammaProbeTarget? gammaTarget = null, IPerDeviceGammaProbeTarget? perDeviceTarget = null)
{
GammaProbeMemory measured;
return Run(driverVibrance, overlayPath, null, out measured, gammaTarget, perDeviceTarget);
}
public static MachineCapabilities Run(bool driverVibrance, OverlayMode overlayPath, GammaProbeMemory? remembered, out GammaProbeMemory? measured, IGammaProbeTarget? gammaTarget = null, IPerDeviceGammaProbeTarget? perDeviceTarget = null)
{
measured = null;
bool elevated = SafeElevated();
bool flag = SafeHdr();
IPerDeviceGammaProbeTarget perDeviceGammaProbeTarget = perDeviceTarget ?? new PerDeviceGammaTarget();
perDeviceTarget = perDeviceGammaProbeTarget;
IReadOnlyList<string> devices;
try
{
devices = perDeviceGammaProbeTarget.Devices() ?? Array.Empty<string>();
}
catch
{
devices = Array.Empty<string>();
}
string key = GammaProbeMemory.KeyFor(devices, elevated, flag, AppInfo.VersionText);
if (remembered != null && remembered.Reusable(key))
{
measured = remembered;
return new MachineCapabilities(remembered.Ramp, flag, SafeVendor(), driverVibrance, SafeMonitorCount(), SafeMixedDpi(), elevated, overlayPath, remembered.Why, remembered.Devices);
}
GammaSupport gammaSupport = GammaSupport.Untested;
bool couldRead = false;
try
{
gammaSupport = ProbeGamma(gammaTarget ?? new ScreenGammaTarget(), out couldRead);
}
catch
{
}
IReadOnlyList<DeviceGamma> readOnlyList = Array.Empty<DeviceGamma>();
bool anyReadable = false;
try
{
readOnlyList = ProbeDevices(perDeviceTarget ?? new PerDeviceGammaTarget(), elevated, flag, out anyReadable);
}
catch
{
}
GammaRefusal gammaRefusal = GammaRefusal.None;
foreach (DeviceGamma item in readOnlyList)
{
if (item.Why != GammaRefusal.None)
{
gammaRefusal = item.Why;
break;
}
}
if (gammaRefusal == GammaRefusal.None)
{
gammaRefusal = WhyRefused(gammaSupport, writeAccepted: true, elevated, flag, null, GammaCurve.Identity());
}
if (gammaSupport == GammaSupport.Refused && !couldRead && !anyReadable)
{
gammaRefusal = GammaRefusal.ScreenUnreadable;
}
if (gammaSupport != GammaSupport.Refused)
{
measured = new GammaProbeMemory(key, gammaSupport, gammaRefusal, new List<DeviceGamma>(readOnlyList));
}
return new MachineCapabilities(gammaSupport, flag, SafeVendor(), driverVibrance, SafeMonitorCount(), SafeMixedDpi(), elevated, overlayPath, gammaRefusal, readOnlyList);
}
private static bool SafeHdr()
{
try
{
return HdrDetection.AnyDisplayInHdr();
}
catch
{
return false;
}
}
private static GpuVendor SafeVendor()
{
try
{
return GpuDetection.PrimaryVendor();
}
catch
{
return GpuVendor.Unknown;
}
}
private static int SafeMonitorCount()
{
try
{
return Math.Max(1, Screen.AllScreens.Length);
}
catch
{
return 1;
}
}
private static bool SafeMixedDpi()
{
try
{
Screen[] allScreens = Screen.AllScreens;
if (allScreens.Length < 2)
{
return false;
}
uint num = DpiOf(allScreens[0]);
for (int i = 1; i < allScreens.Length; i++)
{
if (DpiOf(allScreens[i]) != num)
{
return true;
}
}
return false;
}
catch
{
return false;
}
}
private static uint DpiOf(Screen screen)
{
if (GetDpiForMonitor(MonitorFromPoint(new POINT
{
X = screen.Bounds.Left + 1,
Y = screen.Bounds.Top + 1
}, 2), 0, out var x, out var _) != 0)
{
return 96u;
}
return x;
}
private static bool SafeElevated()
{
try
{
using WindowsIdentity ntIdentity = WindowsIdentity.GetCurrent();
return new WindowsPrincipal(ntIdentity).IsInRole(WindowsBuiltInRole.Administrator);
}
catch
{
return false;
}
}
[DllImport("user32.dll")]
private static extern nint MonitorFromPoint(POINT pt, int flags);
[DllImport("shcore.dll")]
private static extern int GetDpiForMonitor(nint monitor, int type, out uint x, out uint y);
}
+3
View File
@@ -0,0 +1,3 @@
namespace VibranceHud.Capabilities;
public sealed record DeviceGamma(string Device, GammaSupport Result, GammaRefusal Why);
@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace VibranceHud.Capabilities;
public sealed record GammaProbeMemory(string Key, GammaSupport Ramp, GammaRefusal Why, List<DeviceGamma> Devices)
{
internal const string Version = "g1";
internal static string KeyFor(IEnumerable<string> devices, bool elevated, bool hdr, string appVersion)
{
return "g1|" + appVersion + "|" + (elevated ? "E" : "e") + (hdr ? "H" : "h") + "|" + string.Join(";", devices.OrderBy((string d) => d, StringComparer.OrdinalIgnoreCase));
}
internal bool Reusable(string key)
{
bool flag = Key == key;
if (flag)
{
GammaSupport ramp = Ramp;
bool flag2 = (uint)(ramp - 1) <= 1u;
flag = flag2;
}
if (flag)
{
return Why != GammaRefusal.ScreenUnreadable;
}
return false;
}
}
+12
View File
@@ -0,0 +1,12 @@
namespace VibranceHud.Capabilities;
public enum GammaRefusal
{
None,
NotElevated,
HdrOn,
RampHeldByOther,
WriteFailed,
ReadbackIdentity,
ScreenUnreadable
}
+9
View File
@@ -0,0 +1,9 @@
namespace VibranceHud.Capabilities;
public enum GammaSupport
{
Untested,
Working,
Clamped,
Refused
}
+24
View File
@@ -0,0 +1,24 @@
using SharpDX.DXGI;
namespace VibranceHud.Capabilities;
internal static class GpuDetection
{
public static GpuVendor PrimaryVendor()
{
using Factory1 factory = new Factory1();
using Adapter1 adapter = factory.GetAdapter1(0);
switch (adapter.Description1.VendorId)
{
case 4318:
return GpuVendor.Nvidia;
case 4098:
case 4130:
return GpuVendor.Amd;
case 32902:
return GpuVendor.Intel;
default:
return GpuVendor.Other;
}
}
}
+10
View File
@@ -0,0 +1,10 @@
namespace VibranceHud.Capabilities;
public enum GpuVendor
{
Unknown,
Nvidia,
Amd,
Intel,
Other
}
+559
View File
@@ -0,0 +1,559 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using VibranceHud.Controls;
namespace VibranceHud.Capabilities;
internal static class HdrDetection
{
private struct DISPLAYCONFIG_SET_ADVANCED_COLOR_STATE
{
public DISPLAYCONFIG_DEVICE_INFO_HEADER header;
public uint value;
}
private struct LUID
{
public uint LowPart;
public int HighPart;
}
private struct DISPLAYCONFIG_PATH_SOURCE_INFO
{
public LUID adapterId;
public uint id;
public uint modeInfoIdx;
public uint statusFlags;
}
private struct DISPLAYCONFIG_RATIONAL
{
public uint Numerator;
public uint Denominator;
}
private struct DISPLAYCONFIG_PATH_TARGET_INFO
{
public LUID adapterId;
public uint id;
public uint modeInfoIdx;
public uint outputTechnology;
public uint rotation;
public uint scaling;
public DISPLAYCONFIG_RATIONAL refreshRate;
public uint scanLineOrdering;
[MarshalAs(UnmanagedType.Bool)]
public bool targetAvailable;
public uint statusFlags;
}
private struct DISPLAYCONFIG_PATH_INFO
{
public DISPLAYCONFIG_PATH_SOURCE_INFO sourceInfo;
public DISPLAYCONFIG_PATH_TARGET_INFO targetInfo;
public uint flags;
}
[StructLayout(LayoutKind.Sequential, Size = 64)]
private struct DISPLAYCONFIG_MODE_INFO
{
}
private struct DISPLAYCONFIG_DEVICE_INFO_HEADER
{
public int type;
public int size;
public LUID adapterId;
public uint id;
}
private struct DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO
{
public DISPLAYCONFIG_DEVICE_INFO_HEADER header;
public uint value;
public uint colorEncoding;
public int bitsPerColorChannel;
}
private struct DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO_2
{
public DISPLAYCONFIG_DEVICE_INFO_HEADER header;
public uint value;
public uint colorEncoding;
public uint bitsPerColorChannel;
public uint activeColorMode;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct DISPLAYCONFIG_SOURCE_DEVICE_NAME
{
public DISPLAYCONFIG_DEVICE_INFO_HEADER header;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string viewGdiDeviceName;
}
private const uint ColorModeWcg = 1u;
private const uint ColorModeHdr = 2u;
private const uint QDC_ONLY_ACTIVE_PATHS = 2u;
private const int DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME = 1;
private const int DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO = 9;
private const int DISPLAYCONFIG_DEVICE_INFO_SET_ADVANCED_COLOR_STATE = 10;
private const int DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO_2 = 15;
private const int DISPLAYCONFIG_DEVICE_INFO_SET_HDR_STATE = 16;
public static bool AnyDisplayInHdr()
{
return AnyDisplayInHdr(ActivePaths(), AdvancedColourOf);
}
public static IReadOnlyList<HdrDisplay> Report()
{
try
{
return Report(ActivePaths(), AdvancedColourOf, SourceNameOf);
}
catch
{
return Array.Empty<HdrDisplay>();
}
}
internal static bool AnyDisplayInHdr<TPath>(IReadOnlyList<TPath>? paths, Func<TPath, (uint Flags, int BitsPerColorChannel)?> advancedColour)
{
return Displays(paths, advancedColour, (TPath _) => "", includeNames: false).Any((HdrDisplay d) => d.Enabled);
}
internal static IReadOnlyList<HdrDisplay> Report<TPath>(IReadOnlyList<TPath>? paths, Func<TPath, (uint Flags, int BitsPerColorChannel)?> advancedColour, Func<TPath, string> sourceName)
{
return Displays(paths, advancedColour, sourceName, includeNames: true).ToList();
}
private static IEnumerable<HdrDisplay> Displays<TPath>(IReadOnlyList<TPath>? paths, Func<TPath, (uint Flags, int BitsPerColorChannel)?> advancedColour, Func<TPath, string> sourceName, bool includeNames)
{
if (paths == null)
{
yield break;
}
foreach (TPath path in paths)
{
(uint, int)? tuple = advancedColour(path);
if (tuple.HasValue)
{
(uint, int) valueOrDefault = tuple.GetValueOrDefault();
string device = (includeNames ? sourceName(path) : "");
bool supported = (valueOrDefault.Item1 & 1) != 0;
bool enabled = (valueOrDefault.Item1 & 2) != 0 && (valueOrDefault.Item1 & 4) == 0;
int item = valueOrDefault.Item2;
yield return new HdrDisplay(device, supported, enabled, (item > 0 && item < 64) ? valueOrDefault.Item2 : 0);
}
}
}
internal static (uint Flags, int BitsPerColorChannel) FromAdvancedColorInfo2(uint value, uint activeColorMode, int bitsPerColorChannel)
{
uint num = 0u;
if ((value & 0x10) != 0)
{
num |= 1;
}
switch (activeColorMode)
{
case 2u:
num |= 2;
break;
case 1u:
num |= 6;
break;
}
return (Flags: num, BitsPerColorChannel: bitsPerColorChannel);
}
internal static IReadOnlyList<(string Device, uint Value, uint Mode)>? RawInfo2ForTest()
{
IReadOnlyList<DISPLAYCONFIG_PATH_INFO> readOnlyList = ActivePaths();
if (readOnlyList == null)
{
return null;
}
List<(string, uint, uint)> list = new List<(string, uint, uint)>();
foreach (DISPLAYCONFIG_PATH_INFO item in readOnlyList)
{
(uint, uint, uint)? tuple = ReadInfo2(item);
if (tuple.HasValue)
{
(uint, uint, uint) valueOrDefault = tuple.GetValueOrDefault();
list.Add((SourceNameOf(item), valueOrDefault.Item1, valueOrDefault.Item2));
continue;
}
return null;
}
return list;
}
internal static IReadOnlyList<int> PickPaths(IReadOnlyList<string> sourceNames, string? device)
{
List<int> list = new List<int>();
if (string.IsNullOrEmpty(device))
{
return list;
}
for (int i = 0; i < sourceNames.Count; i++)
{
if (string.Equals(sourceNames[i], device, StringComparison.OrdinalIgnoreCase))
{
list.Add(i);
}
}
return list;
}
internal static bool AllColouredDisplaysInHdr(IReadOnlyList<string> coloured, IReadOnlyList<HdrDisplay> report)
{
if (coloured.Count == 0)
{
return false;
}
foreach (string device in coloured)
{
if (!report.Any((HdrDisplay d) => d.Enabled && string.Equals(d.Device, device, StringComparison.OrdinalIgnoreCase)))
{
return false;
}
}
return true;
}
public static bool AllColouredDisplaysInHdr()
{
try
{
return AllColouredDisplaysInHdr(MultiMonitorGammaRamp.Devices(), Report());
}
catch
{
return false;
}
}
public static bool? IsHdrOn(string? gdiDeviceName)
{
try
{
string b = ResolveDevice(gdiDeviceName);
foreach (HdrDisplay item in Report())
{
if (string.Equals(item.Device, b, StringComparison.OrdinalIgnoreCase))
{
return item.Enabled;
}
}
}
catch
{
}
return null;
}
private static string? ResolveDevice(string? gdiDeviceName)
{
if (!string.IsNullOrEmpty(gdiDeviceName))
{
return gdiDeviceName;
}
return Screen.PrimaryScreen?.DeviceName;
}
internal static HdrSwitchOutcome SwitchWithRevert(bool enabled, string? device, Func<string?, bool?> isHdrOn, Func<bool, string?, bool> set, Func<bool> keep)
{
bool? flag = isHdrOn(device);
if (flag.HasValue)
{
bool valueOrDefault = flag == true;
if (valueOrDefault == enabled)
{
return HdrSwitchOutcome.Unchanged;
}
if (!set(enabled, device))
{
return HdrSwitchOutcome.Failed;
}
if (isHdrOn(device) != enabled)
{
set(valueOrDefault, device);
return HdrSwitchOutcome.Failed;
}
if (keep())
{
return HdrSwitchOutcome.Kept;
}
if (!set(valueOrDefault, device))
{
return HdrSwitchOutcome.Failed;
}
return HdrSwitchOutcome.Reverted;
}
return HdrSwitchOutcome.Failed;
}
internal static HdrSwitchOutcome SwitchWithRevertReal(bool enabled, string? device, TimeSpan grace)
{
string name = ResolveDevice(device) ?? "";
return SwitchWithRevert(enabled, name, IsHdrOn, TrySetHdr, () =>
{
bool confirmed = false;
using RevertConfirmForm revertConfirmForm = new RevertConfirmForm($"HDR is now {(enabled ? "on" : "off")} for {name}.", Math.Max(1, (int)Math.Ceiling(grace.TotalSeconds)));
revertConfirmForm.Confirmed += () =>
{
confirmed = true;
};
revertConfirmForm.ShowDialog();
return confirmed;
});
}
private static IReadOnlyList<DISPLAYCONFIG_PATH_INFO>? ActivePaths()
{
if (GetDisplayConfigBufferSizes(2u, out var pathCount, out var modeCount) != 0)
{
return null;
}
DISPLAYCONFIG_PATH_INFO[] array = new DISPLAYCONFIG_PATH_INFO[pathCount];
DISPLAYCONFIG_MODE_INFO[] modes = new DISPLAYCONFIG_MODE_INFO[modeCount];
if (QueryDisplayConfig(2u, ref pathCount, array, ref modeCount, modes, IntPtr.Zero) != 0)
{
return null;
}
return new ArraySegment<DISPLAYCONFIG_PATH_INFO>(array, 0, (int)pathCount);
}
private static (uint Flags, int BitsPerColorChannel)? AdvancedColourOf(DISPLAYCONFIG_PATH_INFO path)
{
(uint, uint, uint)? tuple = ReadInfo2(path);
if (tuple.HasValue)
{
(uint, uint, uint) valueOrDefault = tuple.GetValueOrDefault();
return FromAdvancedColorInfo2(valueOrDefault.Item1, valueOrDefault.Item2, (int)valueOrDefault.Item3);
}
DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO info = new DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO
{
header = new DISPLAYCONFIG_DEVICE_INFO_HEADER
{
type = 9,
size = Marshal.SizeOf<DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO>(),
adapterId = path.targetInfo.adapterId,
id = path.targetInfo.id
}
};
if (DisplayConfigGetDeviceInfo(ref info) != 0)
{
return null;
}
return (info.value, info.bitsPerColorChannel);
}
private static (uint Value, uint Mode, uint Bits)? ReadInfo2(DISPLAYCONFIG_PATH_INFO path)
{
DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO_2 info = new DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO_2
{
header = new DISPLAYCONFIG_DEVICE_INFO_HEADER
{
type = 15,
size = Marshal.SizeOf<DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO_2>(),
adapterId = path.targetInfo.adapterId,
id = path.targetInfo.id
}
};
if (DisplayConfigGetDeviceInfo(ref info) != 0)
{
return null;
}
return (info.value, info.activeColorMode, info.bitsPerColorChannel);
}
private static string SourceNameOf(DISPLAYCONFIG_PATH_INFO path)
{
try
{
DISPLAYCONFIG_SOURCE_DEVICE_NAME info = new DISPLAYCONFIG_SOURCE_DEVICE_NAME
{
header = new DISPLAYCONFIG_DEVICE_INFO_HEADER
{
type = 1,
size = Marshal.SizeOf<DISPLAYCONFIG_SOURCE_DEVICE_NAME>(),
adapterId = path.sourceInfo.adapterId,
id = path.sourceInfo.id
}
};
return (DisplayConfigGetDeviceInfo(ref info) == 0) ? (info.viewGdiDeviceName ?? "").TrimEnd('\0') : "";
}
catch
{
return "";
}
}
public static bool TrySetHdr(bool enabled, string? gdiDeviceName)
{
IReadOnlyList<DISPLAYCONFIG_PATH_INFO> readOnlyList = ActivePaths();
if (readOnlyList == null)
{
return false;
}
IReadOnlyList<int> readOnlyList2 = PickPaths(readOnlyList.Select(SourceNameOf).ToList(), ResolveDevice(gdiDeviceName));
if (readOnlyList2.Count == 0)
{
return false;
}
bool result = false;
foreach (int item in readOnlyList2)
{
DISPLAYCONFIG_PATH_INFO path = readOnlyList[item];
(uint, uint, uint)? tuple = ReadInfo2(path);
if (tuple.HasValue)
{
(uint, uint, uint) valueOrDefault = tuple.GetValueOrDefault();
if ((valueOrDefault.Item1 & 0x10) == 0)
{
continue;
}
if (valueOrDefault.Item2 == 2 == enabled)
{
result = true;
continue;
}
DISPLAYCONFIG_SET_ADVANCED_COLOR_STATE info = new DISPLAYCONFIG_SET_ADVANCED_COLOR_STATE
{
header = SetHeader(16, path),
value = (enabled ? 1u : 0u)
};
if (DisplayConfigSetDeviceInfo(ref info) != 0)
{
continue;
}
for (int i = 0; i < 4; i++)
{
tuple = ReadInfo2(path);
if (tuple.HasValue && tuple.GetValueOrDefault().Item2 == 2 == enabled)
{
result = true;
break;
}
Thread.Sleep(150);
}
continue;
}
DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO info2 = new DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO
{
header = new DISPLAYCONFIG_DEVICE_INFO_HEADER
{
type = 9,
size = Marshal.SizeOf<DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO>(),
adapterId = path.targetInfo.adapterId,
id = path.targetInfo.id
}
};
if (DisplayConfigGetDeviceInfo(ref info2) != 0 || (info2.value & 1) == 0)
{
continue;
}
if (((info2.value & 2) != 0 && (info2.value & 4) == 0) == enabled)
{
result = true;
continue;
}
DISPLAYCONFIG_SET_ADVANCED_COLOR_STATE info3 = new DISPLAYCONFIG_SET_ADVANCED_COLOR_STATE
{
header = SetHeader(10, path),
value = (enabled ? 1u : 0u)
};
if (DisplayConfigSetDeviceInfo(ref info3) == 0)
{
result = true;
}
}
return result;
}
private static DISPLAYCONFIG_DEVICE_INFO_HEADER SetHeader(int type, DISPLAYCONFIG_PATH_INFO path)
{
return new DISPLAYCONFIG_DEVICE_INFO_HEADER
{
type = type,
size = Marshal.SizeOf<DISPLAYCONFIG_SET_ADVANCED_COLOR_STATE>(),
adapterId = path.targetInfo.adapterId,
id = path.targetInfo.id
};
}
[DllImport("user32.dll")]
private static extern int DisplayConfigSetDeviceInfo(ref DISPLAYCONFIG_SET_ADVANCED_COLOR_STATE info);
[DllImport("user32.dll")]
private static extern int GetDisplayConfigBufferSizes(uint flags, out uint pathCount, out uint modeCount);
[DllImport("user32.dll")]
private static extern int QueryDisplayConfig(uint flags, ref uint pathCount, [Out] DISPLAYCONFIG_PATH_INFO[] paths, ref uint modeCount, [Out] DISPLAYCONFIG_MODE_INFO[] modes, nint currentTopologyId);
[DllImport("user32.dll")]
private static extern int DisplayConfigGetDeviceInfo(ref DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO info);
[DllImport("user32.dll")]
private static extern int DisplayConfigGetDeviceInfo(ref DISPLAYCONFIG_SOURCE_DEVICE_NAME info);
[DllImport("user32.dll")]
private static extern int DisplayConfigGetDeviceInfo(ref DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO_2 info);
internal static (int Target, int Path) MarshalledSizesForTest()
{
return (Target: Marshal.SizeOf<DISPLAYCONFIG_PATH_TARGET_INFO>(), Path: Marshal.SizeOf<DISPLAYCONFIG_PATH_INFO>());
}
internal static int SourceNameSizeForTest()
{
return Marshal.SizeOf<DISPLAYCONFIG_SOURCE_DEVICE_NAME>();
}
internal static int AdvancedColorInfo2SizeForTest()
{
return Marshal.SizeOf<DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO_2>();
}
}
+3
View File
@@ -0,0 +1,3 @@
namespace VibranceHud.Capabilities;
public readonly record struct HdrDisplay(string Device, bool Supported, bool Enabled, int BitsPerChannel);
@@ -0,0 +1,9 @@
namespace VibranceHud.Capabilities;
public enum HdrSwitchOutcome
{
Failed,
Unchanged,
Kept,
Reverted
}
+37
View File
@@ -0,0 +1,37 @@
using System.Collections.Generic;
using System.Linq;
namespace VibranceHud.Capabilities;
public static class HdrWords
{
private const string Method = "PlexusX reads Windows' own advanced colour setting for each display";
public static string DetectionLine(IReadOnlyList<HdrDisplay> displays, bool coloursLimited = true)
{
if (displays == null || displays.Count == 0)
{
return "PlexusX couldn't read HDR from Windows on this PC.";
}
List<HdrDisplay> list = displays.Where((HdrDisplay d) => d.Enabled).ToList();
if (list.Count != 0)
{
if (coloursLimited)
{
return $"HDR is on for {Names(list)}, which is why screen-colour changes are limited there. {"PlexusX reads Windows' own advanced colour setting for each display"}.";
}
return $"HDR is on for {Names(list)}. {"PlexusX reads Windows' own advanced colour setting for each display"}.";
}
return $"HDR is off on {Names(displays)}. {"PlexusX reads Windows' own advanced colour setting for each display"}.";
}
private static string Names(IReadOnlyList<HdrDisplay> displays)
{
List<string> list = displays.Select((HdrDisplay d) => (!string.IsNullOrWhiteSpace(d.Device)) ? d.Device : "an unnamed display").ToList();
if (list.Count == 1)
{
return list[0];
}
return string.Join(", ", list.Take(list.Count - 1)) + " and " + list[list.Count - 1];
}
}
@@ -0,0 +1,8 @@
namespace VibranceHud.Capabilities;
public interface IGammaProbeTarget
{
bool TrySet(ushort[] ramp);
ushort[]? TryGet();
}
@@ -0,0 +1,12 @@
using System.Collections.Generic;
namespace VibranceHud.Capabilities;
public interface IPerDeviceGammaProbeTarget
{
IReadOnlyList<string> Devices();
bool TrySet(string device, ushort[] ramp);
ushort[]? TryGet(string device);
}
+38
View File
@@ -0,0 +1,38 @@
namespace VibranceHud.Capabilities;
public static class Machine
{
public static MachineCapabilities Current { get; private set; } = MachineCapabilities.Unknown;
public static void Measure(bool driverVibrance, OverlayMode overlayPath)
{
Current = CapabilityProbe.Run(driverVibrance, overlayPath);
}
public static bool MeasureOrReuse(bool driverVibrance, OverlayMode overlayPath, AppSettings settings)
{
Current = CapabilityProbe.Run(driverVibrance, overlayPath, settings.GammaProbeMemory, out GammaProbeMemory measured);
if (measured == null || object.Equals(measured, settings.GammaProbeMemory))
{
return false;
}
settings.GammaProbeMemory = measured;
return true;
}
public static bool MeasureAndRemember(bool driverVibrance, OverlayMode overlayPath, AppSettings settings)
{
Current = CapabilityProbe.Run(driverVibrance, overlayPath, null, out GammaProbeMemory measured);
if (measured == null || object.Equals(measured, settings.GammaProbeMemory))
{
return false;
}
settings.GammaProbeMemory = measured;
return true;
}
internal static void OverrideForTests(MachineCapabilities caps)
{
Current = caps;
}
}
@@ -0,0 +1,69 @@
using System;
using System.Collections.Generic;
namespace VibranceHud.Capabilities;
public sealed record MachineCapabilities(GammaSupport GammaRamp = GammaSupport.Untested, bool HdrActive = false, GpuVendor Gpu = GpuVendor.Unknown, bool DriverVibrance = false, int MonitorCount = 1, bool MixedDpi = false, bool Elevated = false, OverlayMode OverlayPath = OverlayMode.Mag, GammaRefusal RefusedWhy = GammaRefusal.None, IReadOnlyList<DeviceGamma>? PerDeviceGamma = null)
{
public static MachineCapabilities Unknown => new MachineCapabilities();
public IReadOnlyList<DeviceGamma> Devices => PerDeviceGamma ?? Array.Empty<DeviceGamma>();
public bool ToneControlsWork
{
get
{
GammaSupport gammaRamp = GammaRamp;
if ((uint)(gammaRamp - 1) <= 1u)
{
return true;
}
return false;
}
}
public string ToneLimitation
{
get
{
switch (GammaRamp)
{
case GammaSupport.Refused:
{
if (HdrActive)
{
return "HDR is on, and Windows ignores screen-colour changes while it is. Turn HDR off to use these.";
}
if (RefusedWhy == GammaRefusal.ScreenUnreadable)
{
return "PlexusX couldn't find your screen when it started - maybe the monitor was off. Restart PlexusX with the screen on to use these. Saturation above works either way.";
}
if (!Elevated)
{
return "Windows is blocking screen-colour changes because PlexusX is not running as administrator. Settings has a Fix this button that restarts it properly. Saturation above works either way.";
}
if (Gpu == GpuVendor.Nvidia)
{
return "Your NVIDIA driver is refusing screen-colour changes. Something else is usually holding them - Windows Night light, f.lux, or NVIDIA Freestyle. Close those and reopen PlexusX. Saturation above works either way.";
}
GpuVendor gpu = Gpu;
if ((uint)(gpu - 2) <= 1u)
{
return "Your graphics driver is refusing screen-colour changes. Check for a colour or night-light setting in your GPU control panel, and close anything else that tints the screen. Saturation above works either way.";
}
return "Your graphics driver is refusing screen-colour changes, so these won't do anything. Saturation and vibrance above still work.";
}
case GammaSupport.Clamped:
if (HdrActive)
{
return "HDR is on, so Windows is limiting these. They'll work, but weaker than the numbers suggest.";
}
return "Windows is limiting how far these can go on this PC, so they'll be weaker than the numbers suggest.";
case GammaSupport.Untested:
return "";
default:
return "";
}
}
}
}
@@ -0,0 +1,19 @@
namespace VibranceHud.Capabilities;
internal static class RemeasurePolicy
{
internal const int MaxTries = 3;
internal static bool ShouldRemeasure(MachineCapabilities current, int triesSoFar)
{
if (current.GammaRamp != GammaSupport.Refused)
{
return false;
}
if (current.RefusedWhy != GammaRefusal.ScreenUnreadable)
{
return triesSoFar < 1;
}
return triesSoFar < 3;
}
}
+110
View File
@@ -0,0 +1,110 @@
using System;
using System.Diagnostics;
namespace VibranceHud.Capabilities;
public static class Repair
{
public static string RelaunchArguments => "--relaunch";
public static RepairKind Plan(MachineCapabilities caps)
{
return Plan(caps, FlavourPolicy.Current);
}
public static RepairKind Plan(MachineCapabilities caps, FlavourPolicy policy)
{
GammaSupport gammaRamp = caps.GammaRamp;
if ((uint)(gammaRamp - 2) > 1u)
{
return RepairKind.None;
}
if (caps.HdrActive)
{
return RepairKind.OpenHdrSettings;
}
if (caps.RefusedWhy == GammaRefusal.ScreenUnreadable)
{
return RepairKind.None;
}
if (!caps.Elevated)
{
if (!policy.OffersElevation)
{
return RepairKind.None;
}
return RepairKind.RestartAsAdministrator;
}
return RepairKind.None;
}
public static string ButtonText(RepairKind kind)
{
return kind switch
{
RepairKind.RestartAsAdministrator => "Fix this",
RepairKind.OpenHdrSettings => "Open HDR settings",
_ => "",
};
}
public static string Explain(RepairKind kind)
{
return kind switch
{
RepairKind.RestartAsAdministrator => "PlexusX will close and open again as administrator. Windows will ask you to confirm.",
RepairKind.OpenHdrSettings => "Opens the Windows HDR page. Turn HDR off there, then come back.",
_ => "",
};
}
public static bool Run(RepairKind kind, Action? beforeRestart = null)
{
return Run(kind, FlavourPolicy.Current, (ProcessStartInfo elevated) => Process.Start(elevated), beforeRestart);
}
internal static bool Run(RepairKind kind, FlavourPolicy policy, Func<ProcessStartInfo, Process?> start, Action? beforeRestart)
{
try
{
switch (kind)
{
case RepairKind.RestartAsAdministrator:
{
if (!policy.OffersElevation)
{
return false;
}
string processPath = Environment.ProcessPath;
if (string.IsNullOrEmpty(processPath))
{
return false;
}
ProcessStartInfo arg = new ProcessStartInfo(processPath, RelaunchArguments)
{
UseShellExecute = true,
Verb = "runas"
};
if (start(arg) == null)
{
return false;
}
beforeRestart?.Invoke();
return true;
}
case RepairKind.OpenHdrSettings:
Process.Start(new ProcessStartInfo("ms-settings:display")
{
UseShellExecute = true
});
return true;
default:
return false;
}
}
catch
{
return false;
}
}
}
+8
View File
@@ -0,0 +1,8 @@
namespace VibranceHud.Capabilities;
public enum RepairKind
{
None,
RestartAsAdministrator,
OpenHdrSettings
}
@@ -0,0 +1,60 @@
using System;
using Microsoft.Win32;
namespace VibranceHud.Capabilities;
public static class WindowsRampRule
{
public const int DefaultRange = 128;
public const int UnlockedRange = 256;
public static bool WindowsAcceptsRamp(ushort[] ramp, int range = 128)
{
if (ramp.Length != 768)
{
return false;
}
if (range >= 256)
{
return true;
}
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 256; j++)
{
if (Math.Abs((ramp[i * 256 + j] >> 8) - j) > range)
{
return false;
}
}
}
return true;
}
public static int? ReadGammaRange()
{
try
{
using RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ICM");
return (registryKey?.GetValue("GdiIcmGammaRange") is int value) ? new int?(value) : ((int?)null);
}
catch
{
return null;
}
}
public static int WorstDeviation(ushort[] ramp)
{
int num = 0;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 256; j++)
{
num = Math.Max(num, Math.Abs((ramp[i * 256 + j] >> 8) - j));
}
}
return num;
}
}