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

+5
View File
@@ -0,0 +1,5 @@
using System.Drawing;
namespace VibranceHud.Monitors;
public sealed record ColourMonitor(string Identity, string DeviceName, string Name, Rectangle Bounds, bool Primary = false, int RefreshHz = 0);
@@ -0,0 +1,10 @@
using System.Drawing;
namespace VibranceHud.Monitors;
public sealed record ColourMonitorGroup(string DeviceName, string[] Identities, string Name, Rectangle Bounds, bool Primary, int RefreshHz)
{
public string Identity => string.Join("|", Identities);
public bool IsClone => Identities.Length > 1;
}
@@ -0,0 +1,239 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace VibranceHud.Monitors;
internal static class ColourMonitorInventory
{
private struct Luid
{
public uint Low;
public int High;
}
private struct Rational
{
public uint Numerator;
public uint Denominator;
}
private struct Source
{
public Luid Adapter;
public uint Id;
public uint Mode;
public uint Status;
}
private struct Target
{
public Luid Adapter;
public uint Id;
public uint Mode;
public uint Technology;
public uint Rotation;
public uint Scaling;
public Rational Refresh;
public uint Scanline;
public int Available;
public uint Status;
}
private struct Path
{
public Source Source;
public Target Target;
public uint Flags;
}
[StructLayout(LayoutKind.Explicit, Size = 64)]
private struct Mode
{
[FieldOffset(0)]
public uint Type;
}
private struct Header
{
public uint Type;
public uint Size;
public Luid Adapter;
public uint Id;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct SourceName
{
public Header Header;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string Name;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct TargetName
{
public Header Header;
public uint Flags;
public uint Technology;
public ushort Manufacturer;
public ushort Product;
public uint Connector;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
public string Name;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string DevicePath;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct Device
{
public int Size;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string Name;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string Description;
public uint Flags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string Id;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string Key;
}
[DllImport("user32.dll")]
private static extern int GetDisplayConfigBufferSizes(uint flags, out uint paths, out uint modes);
[DllImport("user32.dll")]
private static extern int QueryDisplayConfig(uint flags, ref uint paths, [In][Out] Path[] pathInfo, ref uint modes, [In][Out] Mode[] modeInfo, nint topology);
[DllImport("user32.dll", EntryPoint = "DisplayConfigGetDeviceInfo")]
private static extern int GetSourceName(ref SourceName name);
[DllImport("user32.dll", EntryPoint = "DisplayConfigGetDeviceInfo")]
private static extern int GetTargetName(ref TargetName name);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern bool EnumDisplayDevices(string device, uint index, ref Device monitor, uint flags);
private static string InterfacePath(string deviceName)
{
Device monitor = new Device
{
Size = Marshal.SizeOf<Device>()
};
if (!EnumDisplayDevices(deviceName, 0u, ref monitor, 1u))
{
return "";
}
return monitor.Id ?? "";
}
internal static IReadOnlyList<ColourMonitor> Read()
{
Screen[] allScreens = Screen.AllScreens;
List<ColourMonitor> list = new List<ColourMonitor>();
for (int i = 0; i < 3; i++)
{
if (GetDisplayConfigBufferSizes(2u, out var paths, out var modes) != 0 || paths > 256 || modes > 1024)
{
break;
}
Path[] p = new Path[paths];
Mode[] modeInfo = new Mode[modes];
switch (QueryDisplayConfig(2u, ref paths, p, ref modes, modeInfo, IntPtr.Zero))
{
case 0:
{
int j;
for (j = 0; j < paths; j++)
{
SourceName source = new SourceName
{
Header = new Header
{
Type = 1u,
Size = (uint)Marshal.SizeOf<SourceName>(),
Adapter = p[j].Source.Adapter,
Id = p[j].Source.Id
}
};
TargetName name = new TargetName
{
Header = new Header
{
Type = 2u,
Size = (uint)Marshal.SizeOf<TargetName>(),
Adapter = p[j].Target.Adapter,
Id = p[j].Target.Id
}
};
if (GetSourceName(ref source) != 0)
{
continue;
}
Screen screen = allScreens.FirstOrDefault((Screen s) => string.Equals(s.DeviceName, source.Name, StringComparison.OrdinalIgnoreCase));
if (screen != null)
{
bool flag = GetTargetName(ref name) == 0;
string text = (flag ? (name.DevicePath ?? "") : "");
if (string.IsNullOrWhiteSpace(text) && p.Take((int)paths).Count((Path x) => x.Source.Adapter.Low == p[j].Source.Adapter.Low && x.Source.Adapter.High == p[j].Source.Adapter.High && x.Source.Id == p[j].Source.Id) == 1)
{
text = InterfacePath(screen.DeviceName);
}
string name2 = ((flag && !string.IsNullOrWhiteSpace(name.Name)) ? name.Name : source.Name);
int refreshHz = ((p[j].Target.Refresh.Denominator != 0) ? ((int)Math.Round((double)p[j].Target.Refresh.Numerator / (double)p[j].Target.Refresh.Denominator)) : 0);
list.Add(new ColourMonitor(text, screen.DeviceName, name2, screen.Bounds, screen.Primary, refreshHz));
}
}
break;
}
case 122:
continue;
}
break;
}
Screen[] array = allScreens;
foreach (Screen screen2 in array)
{
if (!list.Any((ColourMonitor x) => string.Equals(x.DeviceName, screen2.DeviceName, StringComparison.OrdinalIgnoreCase)))
{
list.Add(new ColourMonitor(InterfacePath(screen2.DeviceName), screen2.DeviceName, screen2.DeviceName, screen2.Bounds, screen2.Primary));
}
}
return list;
}
}
@@ -0,0 +1,74 @@
namespace VibranceHud.Monitors;
public sealed class Dxva2MonitorWriter : IMonitorWriter
{
public bool SetBrightnessPercent(int monitorIndex, PanelRange range, int percent)
{
return MonitorControl.SetBrightnessPercent(monitorIndex, range, percent);
}
public bool SetContrastPercent(int monitorIndex, PanelRange range, int percent)
{
return MonitorControl.SetContrastPercent(monitorIndex, range, percent);
}
public bool SetLowBlueLight(int monitorIndex, PanelRange gain, int strength)
{
return MonitorControl.SetLowBlueLight(monitorIndex, gain, strength);
}
public bool SetRedGainPercent(int monitorIndex, PanelRange range, int percent)
{
return MonitorControl.SetRedGainPercent(monitorIndex, range, percent);
}
public bool SetGreenGainPercent(int monitorIndex, PanelRange range, int percent)
{
return MonitorControl.SetGreenGainPercent(monitorIndex, range, percent);
}
public bool SetInputSource(int monitorIndex, byte value)
{
return MonitorControl.SetInputSource(monitorIndex, value);
}
public bool RestoreBrightness(int monitorIndex, int raw)
{
return MonitorControl.RestoreBrightness(monitorIndex, raw);
}
public bool RestoreContrast(int monitorIndex, int raw)
{
return MonitorControl.RestoreContrast(monitorIndex, raw);
}
public bool RestoreBlueGain(int monitorIndex, int raw)
{
return MonitorControl.RestoreBlueGain(monitorIndex, raw);
}
public bool RestoreRedGain(int monitorIndex, int raw)
{
return MonitorControl.RestoreRedGain(monitorIndex, raw);
}
public bool RestoreGreenGain(int monitorIndex, int raw)
{
return MonitorControl.RestoreGreenGain(monitorIndex, raw);
}
public (bool Brightness, bool Contrast, bool BlueGain, bool RedGain, bool GreenGain) RestoreAll(int monitorIndex, int? brightness, int? contrast, int? blueGain, int? redGain = null, int? greenGain = null)
{
return MonitorControl.RestoreAll(monitorIndex, brightness, contrast, blueGain, redGain, greenGain);
}
public int? ReadTrustedBrightness(int monitorIndex)
{
return MonitorControl.ReadTrustedBrightness(monitorIndex);
}
public bool RestoreColourDefaults(int monitorIndex)
{
return MonitorControl.RestoreColourDefaults(monitorIndex);
}
}
@@ -0,0 +1,8 @@
using System;
namespace VibranceHud.Monitors;
public interface IMonitorIdentifyWindow : IDisposable
{
void ShowNumber();
}
+32
View File
@@ -0,0 +1,32 @@
namespace VibranceHud.Monitors;
public interface IMonitorWriter
{
bool SetBrightnessPercent(int monitorIndex, PanelRange range, int percent);
bool SetContrastPercent(int monitorIndex, PanelRange range, int percent);
bool SetLowBlueLight(int monitorIndex, PanelRange gain, int strength);
bool SetRedGainPercent(int monitorIndex, PanelRange range, int percent);
bool SetGreenGainPercent(int monitorIndex, PanelRange range, int percent);
bool SetInputSource(int monitorIndex, byte value);
bool RestoreBrightness(int monitorIndex, int raw);
bool RestoreContrast(int monitorIndex, int raw);
bool RestoreBlueGain(int monitorIndex, int raw);
bool RestoreRedGain(int monitorIndex, int raw);
bool RestoreGreenGain(int monitorIndex, int raw);
(bool Brightness, bool Contrast, bool BlueGain, bool RedGain, bool GreenGain) RestoreAll(int monitorIndex, int? brightness, int? contrast, int? blueGain, int? redGain = null, int? greenGain = null);
int? ReadTrustedBrightness(int monitorIndex);
bool RestoreColourDefaults(int monitorIndex);
}
+29
View File
@@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
namespace VibranceHud.Monitors;
public sealed record MonitorCapability(string Description, bool SupportsBrightness, bool SupportsContrast, bool SupportsRgbGain, int BrightnessMin, int BrightnessCurrent, int BrightnessMax, string Refusal)
{
public PanelRange Brightness { get; init; } = new PanelRange(BrightnessMin, BrightnessCurrent, BrightnessMax);
public PanelRange Contrast { get; init; }
public PanelRange BlueGain { get; init; }
public bool SupportsRedGain { get; init; }
public bool SupportsGreenGain { get; init; }
public PanelRange RedGain { get; init; }
public PanelRange GreenGain { get; init; }
public IReadOnlyList<byte> InputSourceValues { get; init; } = Array.Empty<byte>();
public bool SupportsInputSource => InputSourceValues.Count > 0;
public byte? CurrentInputSource { get; init; }
public int Index { get; init; }
}
+318
View File
@@ -0,0 +1,318 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace VibranceHud.Monitors;
public static class MonitorControl
{
private struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct PHYSICAL_MONITOR
{
public nint hPhysicalMonitor;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string szPhysicalMonitorDescription;
}
private delegate bool MonitorEnumProc(nint hMonitor, nint hdc, ref RECT rect, nint data);
private const uint Red = 0u;
private const uint Green = 1u;
private const uint Blue = 2u;
private const byte VcpInputSource = 96;
private const byte VcpRestoreColourDefaults = 8;
[DllImport("user32.dll")]
private static extern bool EnumDisplayMonitors(nint hdc, nint clip, MonitorEnumProc proc, nint data);
[DllImport("dxva2.dll", SetLastError = true)]
private static extern bool GetNumberOfPhysicalMonitorsFromHMONITOR(nint h, ref uint count);
[DllImport("dxva2.dll", SetLastError = true)]
private static extern bool GetPhysicalMonitorsFromHMONITOR(nint h, uint count, [Out] PHYSICAL_MONITOR[] monitors);
[DllImport("dxva2.dll", SetLastError = true)]
private static extern bool DestroyPhysicalMonitor(nint h);
[DllImport("dxva2.dll", SetLastError = true)]
private static extern bool SetMonitorBrightness(nint h, uint value);
[DllImport("dxva2.dll", SetLastError = true)]
private static extern bool GetMonitorBrightness(nint h, ref uint min, ref uint cur, ref uint max);
[DllImport("dxva2.dll", SetLastError = true)]
private static extern bool SetMonitorContrast(nint h, uint value);
[DllImport("dxva2.dll", SetLastError = true)]
private static extern bool SetMonitorRedGreenOrBlueGain(nint h, uint gainType, uint value);
[DllImport("dxva2.dll", SetLastError = true)]
private static extern bool SetVCPFeature(nint h, byte vcpCode, uint value);
public static bool RestoreColourDefaults(int monitorIndex)
{
return OnMonitor(monitorIndex, (nint h) => SetVCPFeature(h, 8, 1u));
}
public static bool SetBrightnessPercent(int monitorIndex, PanelRange range, int percent)
{
return OnMonitor(monitorIndex, (nint h) => SetMonitorBrightness(h, (uint)range.FromPercent(percent)));
}
public static bool SetContrastPercent(int monitorIndex, PanelRange range, int percent)
{
return OnMonitor(monitorIndex, (nint h) => SetMonitorContrast(h, (uint)range.FromPercent(percent)));
}
internal static int LowBlueTarget(PanelRange gain, int strength)
{
int num = (gain.Current - gain.Min) / 2;
return gain.Current - num * Math.Clamp(strength, 0, 100) / 100;
}
public static bool SetLowBlueLight(int monitorIndex, PanelRange gain, int strength)
{
int target = LowBlueTarget(gain, strength);
return OnMonitor(monitorIndex, (nint h) => SetMonitorRedGreenOrBlueGain(h, 2u, (uint)Math.Clamp(target, gain.Min, gain.Max)));
}
public static bool SetRedGainPercent(int monitorIndex, PanelRange range, int percent)
{
return OnMonitor(monitorIndex, (nint h) => SetMonitorRedGreenOrBlueGain(h, 0u, (uint)range.FromPercent(percent)));
}
public static bool SetGreenGainPercent(int monitorIndex, PanelRange range, int percent)
{
return OnMonitor(monitorIndex, (nint h) => SetMonitorRedGreenOrBlueGain(h, 1u, (uint)range.FromPercent(percent)));
}
public static bool SetInputSource(int monitorIndex, byte value)
{
return OnMonitor(monitorIndex, (nint h) => SetVCPFeature(h, 96, value));
}
public static bool RestoreBrightness(int monitorIndex, int raw)
{
return OnMonitor(monitorIndex, (nint h) => SetMonitorBrightness(h, (uint)raw));
}
public static bool RestoreContrast(int monitorIndex, int raw)
{
return OnMonitor(monitorIndex, (nint h) => SetMonitorContrast(h, (uint)raw));
}
public static bool RestoreBlueGain(int monitorIndex, int raw)
{
return OnMonitor(monitorIndex, (nint h) => SetMonitorRedGreenOrBlueGain(h, 2u, (uint)raw));
}
public static bool RestoreRedGain(int monitorIndex, int raw)
{
return OnMonitor(monitorIndex, (nint h) => SetMonitorRedGreenOrBlueGain(h, 0u, (uint)raw));
}
public static bool RestoreGreenGain(int monitorIndex, int raw)
{
return OnMonitor(monitorIndex, (nint h) => SetMonitorRedGreenOrBlueGain(h, 1u, (uint)raw));
}
public static (bool Brightness, bool Contrast, bool BlueGain, bool RedGain, bool GreenGain) RestoreAll(int monitorIndex, int? brightness, int? contrast, int? blueGain, int? redGain = null, int? greenGain = null)
{
bool bOk = false;
bool cOk = false;
bool gOk = false;
bool rOk = false;
bool grOk = false;
OnMonitor(monitorIndex, (nint h) =>
{
if (brightness.HasValue)
{
bOk = SetMonitorBrightness(h, (uint)brightness.Value);
}
if (contrast.HasValue)
{
cOk = SetMonitorContrast(h, (uint)contrast.Value);
}
if (blueGain.HasValue)
{
gOk = SetMonitorRedGreenOrBlueGain(h, 2u, (uint)blueGain.Value);
}
if (redGain.HasValue)
{
rOk = SetMonitorRedGreenOrBlueGain(h, 0u, (uint)redGain.Value);
}
if (greenGain.HasValue)
{
grOk = SetMonitorRedGreenOrBlueGain(h, 1u, (uint)greenGain.Value);
}
return true;
});
return (Brightness: bOk, Contrast: cOk, BlueGain: gOk, RedGain: rOk, GreenGain: grOk);
}
public static int? ReadTrustedBrightness(int monitorIndex)
{
int? result = ReadBrightness(monitorIndex);
if (!result.HasValue || result.GetValueOrDefault() != 0)
{
return result;
}
int? result2 = ReadBrightness(monitorIndex);
if (!result2.HasValue || result2.GetValueOrDefault() != 0)
{
return result2;
}
return null;
}
private static int? ReadBrightness(int monitorIndex)
{
int? result = null;
OnMonitor(monitorIndex, (nint h) =>
{
uint min = 0u;
uint cur = 0u;
uint max = 0u;
if (!GetMonitorBrightness(h, ref min, ref cur, ref max))
{
return false;
}
if (max <= min)
{
return false;
}
result = (int)cur;
return true;
});
return result;
}
private static bool OnMonitor(int monitorIndex, Func<nint, bool> action)
{
try
{
List<nint> handles = new List<nint>();
EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, Collect, IntPtr.Zero);
return OnMonitorCore(monitorIndex, handles, OpenPhysical, ReleasePhysical, action);
bool Collect(nint h, nint hdc, ref RECT r, nint d)
{
try
{
handles.Add(h);
}
catch
{
}
return true;
}
}
catch
{
return false;
}
}
private static nint[]? OpenPhysical(nint hMonitor)
{
uint count = 0u;
if (!GetNumberOfPhysicalMonitorsFromHMONITOR(hMonitor, ref count) || count == 0)
{
return null;
}
PHYSICAL_MONITOR[] array = new PHYSICAL_MONITOR[count];
if (!GetPhysicalMonitorsFromHMONITOR(hMonitor, count, array))
{
return null;
}
nint[] array2 = new nint[array.Length];
for (int i = 0; i < array.Length; i++)
{
array2[i] = array[i].hPhysicalMonitor;
}
return array2;
}
private static void ReleasePhysical(nint[] handles)
{
foreach (nint h in handles)
{
try
{
DestroyPhysicalMonitor(h);
}
catch
{
}
}
}
internal static bool OnMonitorCore(int monitorIndex, IReadOnlyList<nint> hMonitors, Func<nint, nint[]?> open, Action<nint[]> release, Func<nint, bool> action)
{
int num = 0;
foreach (nint hMonitor in hMonitors)
{
nint[] array;
try
{
array = open(hMonitor);
}
catch
{
array = null;
}
if (array == null || array.Length == 0)
{
if (num++ == monitorIndex)
{
return false;
}
continue;
}
try
{
nint[] array2 = array;
foreach (nint arg in array2)
{
if (num++ == monitorIndex)
{
try
{
return action(arg);
}
catch
{
return false;
}
}
}
}
finally
{
try
{
release(array);
}
catch
{
}
}
}
return false;
}
}
+62
View File
@@ -0,0 +1,62 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace VibranceHud.Monitors;
public static class MonitorDevices
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct MONITORINFOEX
{
public int cbSize;
public RECT rcMonitor;
public RECT rcWork;
public uint dwFlags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string szDevice;
}
private struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
private delegate bool MonitorEnumProc(nint hMonitor, nint hdc, nint rect, nint data);
[DllImport("user32.dll")]
private static extern bool EnumDisplayMonitors(nint hdc, nint clip, MonitorEnumProc proc, nint data);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern bool GetMonitorInfo(nint hMonitor, ref MONITORINFOEX info);
public static string? DeviceNameForIndex(int index)
{
List<string> names = new List<string>();
EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, Collect, IntPtr.Zero);
if (index < 0 || index >= names.Count || names[index].Length <= 0)
{
return null;
}
return names[index];
bool Collect(nint hMonitor, nint hdc, nint rect, nint data)
{
MONITORINFOEX info = new MONITORINFOEX
{
cbSize = Marshal.SizeOf<MONITORINFOEX>()
};
names.Add(GetMonitorInfo(hMonitor, ref info) ? info.szDevice : "");
return true;
}
}
}
+95
View File
@@ -0,0 +1,95 @@
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using VibranceHud.Controls;
namespace VibranceHud.Monitors;
public sealed class MonitorIdentifier : IDisposable
{
private readonly Func<ColourMonitorGroup, int, IMonitorIdentifyWindow> _factory;
private readonly Action<Action>? _expire;
private readonly List<IMonitorIdentifyWindow> _windows = new List<IMonitorIdentifyWindow>();
private Timer? _timer;
private int _generation;
private bool _disposed;
public MonitorIdentifier(Func<ColourMonitorGroup, int, IMonitorIdentifyWindow>? factory = null, Action<Action>? expire = null)
{
_factory = factory ?? ((Func<ColourMonitorGroup, int, IMonitorIdentifyWindow>)((ColourMonitorGroup g, int n) => new MonitorNumberWindow(g.Bounds, n)));
_expire = expire;
}
public void Identify(IReadOnlyList<ColourMonitorGroup> groups)
{
if (_disposed)
{
return;
}
CloseWindows();
int generation = ++_generation;
try
{
for (int i = 0; i < groups.Count; i++)
{
IMonitorIdentifyWindow monitorIdentifyWindow = _factory(groups[i], i + 1);
_windows.Add(monitorIdentifyWindow);
monitorIdentifyWindow.ShowNumber();
}
if (_windows.Count == 0)
{
return;
}
if (_expire != null)
{
_expire(Expire);
return;
}
_timer = new Timer
{
Interval = 2000
};
_timer.Tick += (object? _, EventArgs _) =>
{
Expire();
};
_timer.Start();
}
catch
{
CloseWindows();
throw;
}
void Expire()
{
if (generation == _generation)
{
CloseWindows();
}
}
}
private void CloseWindows()
{
_timer?.Stop();
_timer?.Dispose();
_timer = null;
foreach (IMonitorIdentifyWindow window in _windows)
{
window.Dispose();
}
_windows.Clear();
}
public void Dispose()
{
_disposed = true;
_generation++;
CloseWindows();
}
}
+288
View File
@@ -0,0 +1,288 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace VibranceHud.Monitors;
public static class MonitorPanicRestore
{
private enum Mode
{
None,
Originals,
Defaults
}
private sealed record Plan(AppSettings.PanelSettings Panel, Mode Mode, int? Brightness, int? Contrast, int? Blue, int? Red, int? Green);
public const string Restored = "Monitor restored";
public const string Refused = "Your monitor refused - use its menu: Reset";
public const string NothingSaved = "Colours reset. PlexusX had nothing saved for the monitor itself - if it still looks wrong, use the monitor's own menu.";
public static string KeyFor(MonitorCapability cap, Func<int, string?> deviceName)
{
return deviceName(cap.Index) + "|" + cap.Description;
}
public static bool DidNothingToThePanels(PanicResult r)
{
if (r.PanelsRestored == 0 && r.PanelsReset == 0)
{
return r.PanelsRefused == 0;
}
return false;
}
public static string BalloonText(PanicResult? result)
{
if (!(result == null) && result.PanelsRefused <= 0)
{
if (!DidNothingToThePanels(result))
{
return "Monitor restored";
}
return "Colours reset. PlexusX had nothing saved for the monitor itself - if it still looks wrong, use the monitor's own menu.";
}
return "Your monitor refused - use its menu: Reset";
}
internal static bool BlueLooksAlreadyCut(MonitorCapability cap)
{
if (!cap.SupportsRgbGain || !cap.SupportsRedGain || !cap.SupportsGreenGain)
{
return false;
}
if (!cap.BlueGain.IsUsable || !cap.RedGain.IsUsable || !cap.GreenGain.IsUsable)
{
return false;
}
int num = cap.BlueGain.ToPercent(cap.BlueGain.Current);
int num2 = Math.Min(cap.RedGain.ToPercent(cap.RedGain.Current), cap.GreenGain.ToPercent(cap.GreenGain.Current));
return (double)num < (double)num2 * 0.7;
}
public static IReadOnlyList<string> KeysFor(IEnumerable<MonitorCapability> caps, Func<int, string?> deviceName)
{
return caps.Select((MonitorCapability c) => KeyFor(c, deviceName)).ToList();
}
private static bool Owned(bool supported, PanelRange now, int wrote)
{
if (supported && wrote >= 0 && now.IsUsable)
{
return now.Current == wrote;
}
return false;
}
private static bool HasWriteRecord(AppSettings.PanelSettings p)
{
if (p.WroteBrightness < 0 && p.WroteContrast < 0 && p.WroteBlueGain < 0 && p.WroteRedGain < 0)
{
return p.WroteGreenGain >= 0;
}
return true;
}
private static bool DescriptionIsUnique(string key, IReadOnlyCollection<string> connected)
{
string d = Desc(key);
if (d.Length > 0)
{
return Enumerable.Count(connected, (string k) => Desc(k) == d) <= 1;
}
return false;
static string Desc(string k)
{
int num = k.LastIndexOf('|');
if (num < 0)
{
return k;
}
return k.Substring(num + 1);
}
}
private static Plan PlanFor(AppSettings s, MonitorCapability cap, string key, IReadOnlyCollection<string> connected, bool userInitiated)
{
AppSettings.PanelSettings panelSettings = s.PanelFor(key, cap.Index, connected);
bool flag = userInitiated && panelSettings.HasOriginals && !HasWriteRecord(panelSettings) && DescriptionIsUnique(key, connected);
if (panelSettings.HasOriginals)
{
int? brightness = ((cap.SupportsBrightness && panelSettings.OriginalBrightness > cap.Brightness.Min && (flag || Owned(supported: true, cap.Brightness, panelSettings.WroteBrightness))) ? new int?(panelSettings.OriginalBrightness) : ((int?)null));
int? contrast = (((flag && cap.SupportsContrast) || Owned(cap.SupportsContrast, cap.Contrast, panelSettings.WroteContrast)) ? new int?(panelSettings.OriginalContrast) : ((int?)null));
int? blue = ((panelSettings.OriginalBlueGain >= 0 && ((flag && cap.SupportsRgbGain) || Owned(cap.SupportsRgbGain, cap.BlueGain, panelSettings.WroteBlueGain))) ? new int?(panelSettings.OriginalBlueGain) : ((int?)null));
int? red = (((flag && cap.SupportsRedGain) || Owned(cap.SupportsRedGain, cap.RedGain, panelSettings.WroteRedGain)) ? new int?(panelSettings.OriginalRedGain) : ((int?)null));
int? green = (((flag && cap.SupportsGreenGain) || Owned(cap.SupportsGreenGain, cap.GreenGain, panelSettings.WroteGreenGain)) ? new int?(panelSettings.OriginalGreenGain) : ((int?)null));
if (brightness.HasValue || contrast.HasValue || blue.HasValue || red.HasValue || green.HasValue)
{
return new Plan(panelSettings, Mode.Originals, brightness, contrast, blue, red, green);
}
}
bool flag2 = ((panelSettings.WroteBlueGain < 0 && panelSettings.WroteRedGain < 0 && panelSettings.WroteGreenGain < 0) ? (panelSettings.LowBlue >= 0 || panelSettings.RedGain >= 0 || panelSettings.GreenGain >= 0) : (Owned(cap.SupportsRgbGain, cap.BlueGain, panelSettings.WroteBlueGain) || Owned(cap.SupportsRedGain, cap.RedGain, panelSettings.WroteRedGain) || Owned(cap.SupportsGreenGain, cap.GreenGain, panelSettings.WroteGreenGain)));
return new Plan(panelSettings, flag2 ? Mode.Defaults : Mode.None, null, null, null, null, null);
}
public static PanicResult Run(AppSettings s, SettingsStore store, IMonitorWriter writer, Func<IReadOnlyList<MonitorCapability>> probe, Action gammaLinear, Action driverBaseline, Func<int, string?>? deviceName = null, int? onlyMonitorIndex = null, Action<Action>? runOnUi = null, bool userInitiated = false)
{
if (deviceName == null)
{
deviceName = MonitorDevices.DeviceNameForIndex;
}
Action<Action> action = runOnUi ?? ((Action<Action>)((Action a) =>
{
a();
}));
int num = 0;
int num2 = 0;
int num3 = 0;
try
{
IReadOnlyList<MonitorCapability> readOnlyList;
try
{
readOnlyList = probe() ?? Array.Empty<MonitorCapability>();
}
catch
{
readOnlyList = Array.Empty<MonitorCapability>();
}
IReadOnlyList<string> connected = KeysFor(readOnlyList, deviceName);
foreach (MonitorCapability cap in readOnlyList)
{
if (onlyMonitorIndex.HasValue && cap.Index != onlyMonitorIndex.Value)
{
continue;
}
try
{
Plan plan = null;
action(() =>
{
plan = PlanFor(s, cap, KeyFor(cap, deviceName), connected, userInitiated);
});
if (plan == null || plan.Mode == Mode.None)
{
continue;
}
if (plan.Mode == Mode.Originals)
{
(bool Brightness, bool Contrast, bool BlueGain, bool RedGain, bool GreenGain) r = writer.RestoreAll(cap.Index, plan.Brightness, plan.Contrast, plan.Blue, plan.Red, plan.Green);
bool all = (!plan.Brightness.HasValue || r.Brightness) && (!plan.Contrast.HasValue || r.Contrast) && (!plan.Blue.HasValue || r.BlueGain) && (!plan.Red.HasValue || r.RedGain) && (!plan.Green.HasValue || r.GreenGain);
action(() =>
{
AppSettings.PanelSettings panel = plan.Panel;
if (plan.Brightness.HasValue && r.Brightness)
{
panel.Brightness = -1;
panel.WroteBrightness = -1;
}
if (plan.Contrast.HasValue && r.Contrast)
{
panel.Contrast = -1;
panel.WroteContrast = -1;
}
if (plan.Blue.HasValue && r.BlueGain)
{
panel.LowBlue = -1;
panel.WroteBlueGain = -1;
}
if (plan.Red.HasValue && r.RedGain)
{
panel.RedGain = -1;
panel.WroteRedGain = -1;
}
if (plan.Green.HasValue && r.GreenGain)
{
panel.GreenGain = -1;
panel.WroteGreenGain = -1;
}
if (all)
{
panel.PanelTouched = false;
}
});
if (all)
{
num++;
}
else
{
num3++;
}
continue;
}
bool flag = writer.RestoreColourDefaults(cap.Index);
if (flag)
{
action(() =>
{
AppSettings.PanelSettings panel = plan.Panel;
panel.LowBlue = -1;
panel.RedGain = -1;
panel.GreenGain = -1;
panel.WroteBlueGain = -1;
panel.WroteRedGain = -1;
panel.WroteGreenGain = -1;
panel.PanelTouched = false;
});
}
if (flag)
{
num2++;
}
else
{
num3++;
}
}
catch
{
num3++;
}
}
}
catch
{
}
bool gammaLinear2 = false;
bool driverBack = false;
try
{
action(gammaLinear);
gammaLinear2 = true;
}
catch
{
}
try
{
action(driverBaseline);
driverBack = true;
}
catch
{
}
try
{
action(() =>
{
if (s.MonitorColours != null)
{
foreach (MonitorColourSetting monitorColour in s.MonitorColours)
{
monitorColour.GammaPercent = 100;
monitorColour.WarmthPercent = 0;
}
}
store.Save(s);
});
}
catch
{
}
return new PanicResult(num, num2, num3, gammaLinear2, driverBack);
}
}
+352
View File
@@ -0,0 +1,352 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
namespace VibranceHud.Monitors;
public static class MonitorProbe
{
private struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct PHYSICAL_MONITOR
{
public nint hPhysicalMonitor;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string szPhysicalMonitorDescription;
}
private delegate bool MonitorEnumProc(nint hMonitor, nint hdc, ref RECT rect, nint data);
[DllImport("user32.dll")]
private static extern bool EnumDisplayMonitors(nint hdc, nint clip, MonitorEnumProc proc, nint data);
[DllImport("dxva2.dll", SetLastError = true)]
private static extern bool GetNumberOfPhysicalMonitorsFromHMONITOR(nint hMonitor, ref uint count);
[DllImport("dxva2.dll", SetLastError = true)]
private static extern bool GetPhysicalMonitorsFromHMONITOR(nint hMonitor, uint count, [Out] PHYSICAL_MONITOR[] monitors);
[DllImport("dxva2.dll", SetLastError = true)]
private static extern bool DestroyPhysicalMonitor(nint hMonitor);
[DllImport("dxva2.dll", SetLastError = true)]
private static extern bool GetMonitorBrightness(nint h, ref uint min, ref uint cur, ref uint max);
[DllImport("dxva2.dll", SetLastError = true)]
private static extern bool GetMonitorContrast(nint h, ref uint min, ref uint cur, ref uint max);
[DllImport("dxva2.dll", SetLastError = true)]
private static extern bool GetMonitorRedGreenOrBlueGain(nint h, uint gainType, ref uint min, ref uint cur, ref uint max);
[DllImport("dxva2.dll", SetLastError = true)]
private static extern bool GetCapabilitiesStringLength(nint h, ref uint length);
[DllImport("dxva2.dll", SetLastError = true)]
private static extern bool CapabilitiesRequestAndCapabilitiesReply(nint h, [Out] byte[] buffer, uint bufferLength);
[DllImport("dxva2.dll", SetLastError = true)]
private static extern bool GetVCPFeatureAndVCPFeatureReply(nint h, byte vcpCode, nint pvct, ref uint currentValue, ref uint maxValue);
public static IReadOnlyList<MonitorCapability> Probe()
{
List<MonitorCapability> list = new List<MonitorCapability>();
try
{
List<nint> handles = new List<nint>();
EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, Collect, IntPtr.Zero);
list.AddRange(NumberThem(handles, Describe));
bool Collect(nint hMonitor, nint hdc, ref RECT rect, nint data)
{
try
{
handles.Add(hMonitor);
}
catch
{
}
return true;
}
}
catch (Exception ex)
{
list.Add(new MonitorCapability("Display", SupportsBrightness: false, SupportsContrast: false, SupportsRgbGain: false, 0, 0, 0, "Windows would not list the monitors: " + ex.Message));
}
if (list.Count == 0)
{
list.Add(new MonitorCapability("Display", SupportsBrightness: false, SupportsContrast: false, SupportsRgbGain: false, 0, 0, 0, "No monitor answered. This is normal on a laptop's built-in screen."));
}
return list;
}
internal static List<MonitorCapability> NumberThem(IReadOnlyList<nint> hMonitors, Func<nint, List<MonitorCapability>> describe)
{
List<MonitorCapability> list = new List<MonitorCapability>();
foreach (nint hMonitor in hMonitors)
{
foreach (MonitorCapability item in describe(hMonitor))
{
list.Add(item with
{
Index = list.Count
});
}
}
return list;
}
private static List<MonitorCapability> Describe(nint hMonitor)
{
List<MonitorCapability> list = new List<MonitorCapability>();
uint count = 0u;
PHYSICAL_MONITOR[] array;
try
{
if (!GetNumberOfPhysicalMonitorsFromHMONITOR(hMonitor, ref count) || count == 0)
{
list.Add(Refused("Display", "This display does not expose a physical monitor to Windows."));
return list;
}
array = new PHYSICAL_MONITOR[count];
if (!GetPhysicalMonitorsFromHMONITOR(hMonitor, count, array))
{
list.Add(Refused("Display", "Windows could not open a connection to this monitor."));
return list;
}
}
catch (Exception ex)
{
list.Add(Refused("Display", "This monitor could not be opened: " + ex.Message));
return list;
}
PHYSICAL_MONITOR[] array2 = array;
for (int i = 0; i < array2.Length; i++)
{
PHYSICAL_MONITOR m = array2[i];
try
{
list.Add(Interrogate(m));
}
catch (Exception ex2)
{
list.Add(Refused(Name(m.szPhysicalMonitorDescription), "This monitor stopped responding while being read: " + ex2.Message));
}
finally
{
try
{
DestroyPhysicalMonitor(m.hPhysicalMonitor);
}
catch
{
}
}
}
return list;
}
internal static int TrustFirstBrightnessRead(int min, int first, Func<int?> readAgain)
{
if (first > min)
{
return first;
}
int? num = readAgain();
if (num.HasValue)
{
int valueOrDefault = num.GetValueOrDefault();
if (valueOrDefault > min)
{
return valueOrDefault;
}
}
return -1;
}
private static MonitorCapability Interrogate(PHYSICAL_MONITOR m)
{
string description = Name(m.szPhysicalMonitorDescription);
uint bMin = 0u;
uint bCur = 0u;
uint bMax = 0u;
bool flag = TryRead(() => GetMonitorBrightness(m.hPhysicalMonitor, ref bMin, ref bCur, ref bMax));
if (flag && (bMax <= bMin || bCur < bMin || bCur > bMax))
{
flag = false;
bMin = (bCur = (bMax = 0u));
}
int brightnessCurrent = (int)bCur;
if (flag)
{
brightnessCurrent = TrustFirstBrightnessRead((int)bMin, (int)bCur, () =>
{
uint min2 = 0u;
uint cur2 = 0u;
uint max2 = 0u;
return (!TryRead(() => GetMonitorBrightness(m.hPhysicalMonitor, ref min2, ref cur2, ref max2)) || max2 <= min2 || cur2 < min2 || cur2 > max2) ? ((int?)null) : new int?((int)cur2);
});
}
uint cMin = 0u;
uint cCur = 0u;
uint cMax = 0u;
bool flag2 = TryRead(() => GetMonitorContrast(m.hPhysicalMonitor, ref cMin, ref cCur, ref cMax)) && cMax > cMin;
uint gMin = 0u;
uint gCur = 0u;
uint gMax = 0u;
bool flag3 = TryRead(() => GetMonitorRedGreenOrBlueGain(m.hPhysicalMonitor, 2u, ref gMin, ref gCur, ref gMax)) && gMax > gMin;
uint rMin = 0u;
uint rCur = 0u;
uint rMax = 0u;
bool flag4 = TryRead(() => GetMonitorRedGreenOrBlueGain(m.hPhysicalMonitor, 0u, ref rMin, ref rCur, ref rMax)) && rMax > rMin;
uint grMin = 0u;
uint grCur = 0u;
uint grMax = 0u;
bool flag5 = TryRead(() => GetMonitorRedGreenOrBlueGain(m.hPhysicalMonitor, 1u, ref grMin, ref grCur, ref grMax)) && grMax > grMin;
IReadOnlyList<byte> readOnlyList = TryReadInputSourceValues(m.hPhysicalMonitor);
byte? currentInputSource = null;
if (readOnlyList.Count > 0)
{
uint ivCur = 0u;
uint ivMax = 0u;
if (TryRead(() => GetVCPFeatureAndVCPFeatureReply(m.hPhysicalMonitor, 96, IntPtr.Zero, ref ivCur, ref ivMax)))
{
currentInputSource = (byte)ivCur;
}
}
string refusal = ((flag | flag2 | flag3) ? "" : "This monitor is connected but will not accept DDC/CI control. That is usually a monitor setting - look for \"DDC/CI\" in its on-screen menu.");
return new MonitorCapability(description, flag, flag2, flag3, (int)bMin, brightnessCurrent, (int)bMax, refusal)
{
Contrast = (flag2 ? new PanelRange((int)cMin, (int)cCur, (int)cMax) : default(PanelRange)),
BlueGain = (flag3 ? new PanelRange((int)gMin, (int)gCur, (int)gMax) : default(PanelRange)),
SupportsRedGain = flag4,
SupportsGreenGain = flag5,
RedGain = (flag4 ? new PanelRange((int)rMin, (int)rCur, (int)rMax) : default(PanelRange)),
GreenGain = (flag5 ? new PanelRange((int)grMin, (int)grCur, (int)grMax) : default(PanelRange)),
InputSourceValues = readOnlyList,
CurrentInputSource = currentInputSource
};
}
private static IReadOnlyList<byte> TryReadInputSourceValues(nint h)
{
try
{
uint length = 0u;
if (!GetCapabilitiesStringLength(h, ref length) || length == 0)
{
return Array.Empty<byte>();
}
byte[] array = new byte[length];
if (!CapabilitiesRequestAndCapabilitiesReply(h, array, length))
{
return Array.Empty<byte>();
}
int num = Array.IndexOf(array, (byte)0);
return ParseFeatureValues(Encoding.ASCII.GetString(array, 0, (num < 0) ? array.Length : num), 96);
}
catch
{
return Array.Empty<byte>();
}
}
internal static IReadOnlyList<byte> ParseFeatureValues(string capabilities, byte code)
{
string text = code.ToString("X2");
int startIndex = 0;
int i;
while (true)
{
startIndex = capabilities.IndexOf(text, startIndex, StringComparison.OrdinalIgnoreCase);
if (startIndex < 0)
{
return Array.Empty<byte>();
}
int num = startIndex + text.Length;
bool num2 = startIndex == 0 || !IsHexDigit(capabilities[startIndex - 1]);
bool flag = num >= capabilities.Length || !IsHexDigit(capabilities[num]);
if (num2 & flag)
{
for (i = num; i < capabilities.Length && capabilities[i] == ' '; i++)
{
}
if (i < capabilities.Length && capabilities[i] == '(')
{
break;
}
startIndex = num;
}
else
{
startIndex = num;
}
}
int num3 = capabilities.IndexOf(')', i);
if (num3 < 0)
{
return Array.Empty<byte>();
}
List<byte> list = new List<byte>();
int num4 = i + 1;
string[] array = capabilities.Substring(num4, num3 - num4).Split(' ', StringSplitOptions.RemoveEmptyEntries);
for (int j = 0; j < array.Length; j++)
{
if (byte.TryParse(array[j], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var result))
{
list.Add(result);
}
}
return list;
}
private static bool IsHexDigit(char c)
{
if ((c < '0' || c > '9') && (c < 'A' || c > 'F'))
{
if (c >= 'a')
{
return c <= 'f';
}
return false;
}
return true;
}
private static bool TryRead(Func<bool> call)
{
try
{
return call();
}
catch
{
return false;
}
}
private static string Name(string? description)
{
if (!string.IsNullOrWhiteSpace(description))
{
return description.Trim();
}
return "Display";
}
private static MonitorCapability Refused(string name, string why)
{
return new MonitorCapability(name, SupportsBrightness: false, SupportsContrast: false, SupportsRgbGain: false, 0, 0, 0, why);
}
}
+223
View File
@@ -0,0 +1,223 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace VibranceHud.Monitors;
public sealed class MonitorSelection
{
private readonly AppSettings _settings;
private readonly Func<IReadOnlyList<ColourMonitor>> _inventory;
private HashSet<string> _ambiguous = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
private const string DeviceKeyPrefix = "device:";
private const string StableOptOutPrefix = "monitor:";
private const string InventoryPrefix = "inventory:";
public IReadOnlyList<ColourMonitorGroup> Groups { get; private set; } = Array.Empty<ColourMonitorGroup>();
public bool AllowsMatrix => Groups.All(IsSelected);
internal bool WorthShowing
{
get
{
if (Groups.Count < 2)
{
return Groups.Any((ColourMonitorGroup g) => !IsSelected(g));
}
return true;
}
}
public event Action? Changed;
public MonitorSelection(AppSettings settings, Func<IReadOnlyList<ColourMonitor>> inventory)
{
_settings = settings;
_inventory = inventory;
Refresh();
}
public void Refresh()
{
IReadOnlyList<ColourMonitor> source;
try
{
source = _inventory();
}
catch
{
source = Array.Empty<ColourMonitor>();
}
_ambiguous = (from g in source.GroupBy((ColourMonitor x) => x.Identity, StringComparer.OrdinalIgnoreCase)
where string.IsNullOrWhiteSpace(g.Key) || g.Select((ColourMonitor x) => x.DeviceName).Distinct(StringComparer.OrdinalIgnoreCase).Count() > 1
select g.Key).ToHashSet(StringComparer.OrdinalIgnoreCase);
Groups = (from g in source.GroupBy((ColourMonitor x) => x.DeviceName, StringComparer.OrdinalIgnoreCase)
select new ColourMonitorGroup(g.Key, g.Select((ColourMonitor x) => x.Identity).Distinct(StringComparer.OrdinalIgnoreCase).OrderBy((string x) => x, StringComparer.OrdinalIgnoreCase)
.ToArray(), string.Join(" + ", g.Select((ColourMonitor x) => x.Name).Distinct()), g.First().Bounds, g.Any((ColourMonitor x) => x.Primary), g.First().RefreshHz) into x
orderby x.Primary descending, x.Bounds.X, x.Bounds.Y
select x).ThenBy((ColourMonitorGroup x) => x.Identity, StringComparer.OrdinalIgnoreCase).ToArray();
PreserveOptOuts();
Changed?.Invoke();
}
private void PreserveOptOuts()
{
List<string> untickedDeviceKeys = _settings.UntickedDeviceKeys;
if (untickedDeviceKeys == null || untickedDeviceKeys.Count <= 0)
{
return;
}
HashSet<string> hashSet = new HashSet<string>(untickedDeviceKeys, StringComparer.OrdinalIgnoreCase);
foreach (ColourMonitorGroup item2 in Groups.Where(Resolved))
{
if (hashSet.Remove("device:" + item2.DeviceName) || hashSet.Remove(item2.DeviceName))
{
hashSet.Add("monitor:" + item2.Identity);
}
}
HashSet<string> current2 = Groups.Select((ColourMonitorGroup g) => g.DeviceName).ToHashSet(StringComparer.OrdinalIgnoreCase);
bool flag = hashSet.Any((string k) => (k.StartsWith("device:", StringComparison.OrdinalIgnoreCase) && !current2.Contains(k.Substring("device:".Length))) || ((k.StartsWith("DISPLAY", StringComparison.OrdinalIgnoreCase) || k.StartsWith("\\\\.\\DISPLAY", StringComparison.OrdinalIgnoreCase)) && !current2.Contains(k)));
string item = InventoryKey();
bool flag2 = hashSet.Any((string k) => k.StartsWith("inventory:", StringComparison.OrdinalIgnoreCase)) && !hashSet.Contains(item) && Groups.Any((ColourMonitorGroup g) => !Resolved(g)) && hashSet.Any((string k) => k.StartsWith("device:", StringComparison.OrdinalIgnoreCase));
if ((flag | flag2) && !hashSet.Contains(item))
{
hashSet.RemoveWhere((string k) => k.StartsWith("inventory:", StringComparison.OrdinalIgnoreCase));
foreach (ColourMonitorGroup item3 in Groups.Where((ColourMonitorGroup g) => !Resolved(g)))
{
hashSet.Add("device:" + item3.DeviceName);
}
hashSet.Add(item);
}
_settings.UntickedDeviceKeys = ((hashSet.Count == 0) ? null : hashSet.OrderBy((string k) => k, StringComparer.OrdinalIgnoreCase).ToList());
}
private string InventoryKey()
{
return "inventory:" + string.Join("|", Groups.Select((ColourMonitorGroup g) => g.DeviceName + ":" + g.Identity).OrderBy((string k) => k, StringComparer.OrdinalIgnoreCase));
}
private bool Resolved(ColourMonitorGroup group)
{
if (group.Identities.Length != 0)
{
return group.Identities.All((string id) => !string.IsNullOrWhiteSpace(id) && !_ambiguous.Contains(id));
}
return false;
}
public string GroupKey(ColourMonitorGroup group)
{
if (!Resolved(group))
{
return "device:" + group.DeviceName;
}
return group.Identity;
}
public bool IsSelected(ColourMonitorGroup group)
{
List<string> untickedDeviceKeys = _settings.UntickedDeviceKeys;
if ((untickedDeviceKeys != null && untickedDeviceKeys.Contains("monitor:" + group.Identity, StringComparer.OrdinalIgnoreCase)) || (untickedDeviceKeys != null && untickedDeviceKeys.Contains("device:" + group.DeviceName, StringComparer.OrdinalIgnoreCase)) || (untickedDeviceKeys != null && untickedDeviceKeys.Contains(group.DeviceName, StringComparer.OrdinalIgnoreCase)))
{
return false;
}
if (Resolved(group) && _settings.SelectedMonitorIds != null)
{
return group.Identities.All((string id) => _settings.SelectedMonitorIds.Contains(id, StringComparer.OrdinalIgnoreCase));
}
return true;
}
public bool IncludesDevice(string device)
{
ColourMonitorGroup colourMonitorGroup = Groups.FirstOrDefault((ColourMonitorGroup g) => string.Equals(g.DeviceName, device, StringComparison.OrdinalIgnoreCase));
if (!(colourMonitorGroup == null))
{
return IsSelected(colourMonitorGroup);
}
return true;
}
public string? IdentityFor(string device)
{
ColourMonitorGroup colourMonitorGroup = Groups.FirstOrDefault((ColourMonitorGroup g) => string.Equals(g.DeviceName, device, StringComparison.OrdinalIgnoreCase));
if (!(colourMonitorGroup != null) || !Resolved(colourMonitorGroup))
{
return null;
}
return colourMonitorGroup.Identity;
}
public string KeyFor(string device)
{
return IdentityFor(device) ?? ("device:" + device);
}
public string? DeviceFor(string identity)
{
if (identity.StartsWith("device:", StringComparison.Ordinal))
{
return identity.Substring("device:".Length);
}
return Groups.FirstOrDefault((ColourMonitorGroup g) => Resolved(g) && string.Equals(g.Identity, identity, StringComparison.OrdinalIgnoreCase))?.DeviceName;
}
public void SetSelected(ColourMonitorGroup group, bool selected)
{
if (selected)
{
List<string> untickedDeviceKeys = _settings.UntickedDeviceKeys;
if (untickedDeviceKeys != null)
{
untickedDeviceKeys.RemoveAll((string k) => string.Equals(k, "monitor:" + group.Identity, StringComparison.OrdinalIgnoreCase) || string.Equals(k, "device:" + group.DeviceName, StringComparison.OrdinalIgnoreCase) || string.Equals(k, group.DeviceName, StringComparison.OrdinalIgnoreCase));
if (untickedDeviceKeys.All((string k) => k.StartsWith("inventory:", StringComparison.OrdinalIgnoreCase)))
{
_settings.UntickedDeviceKeys = null;
}
}
}
if (!Resolved(group))
{
string item = GroupKey(group);
HashSet<string> hashSet = new HashSet<string>(_settings.UntickedDeviceKeys ?? new List<string>(), StringComparer.OrdinalIgnoreCase);
if (selected)
{
hashSet.Remove(item);
}
else
{
hashSet.Add(item);
}
hashSet.RemoveWhere((string k) => k.StartsWith("inventory:", StringComparison.OrdinalIgnoreCase));
if (hashSet.Count > 0)
{
hashSet.Add(InventoryKey());
}
_settings.UntickedDeviceKeys = ((hashSet.Count == 0) ? null : hashSet.OrderBy((string k) => k, StringComparer.OrdinalIgnoreCase).ToList());
Changed?.Invoke();
return;
}
IEnumerable<string> selectedMonitorIds = _settings.SelectedMonitorIds;
HashSet<string> hashSet2 = new HashSet<string>(selectedMonitorIds ?? Groups.Where(Resolved).SelectMany((ColourMonitorGroup g) => g.Identities), StringComparer.OrdinalIgnoreCase);
string[] identities = group.Identities;
foreach (string item2 in identities)
{
if (selected)
{
hashSet2.Add(item2);
}
else
{
hashSet2.Remove(item2);
}
}
_settings.SelectedMonitorIds = hashSet2.OrderBy((string id) => id, StringComparer.OrdinalIgnoreCase).ToList();
Changed?.Invoke();
}
}
+32
View File
@@ -0,0 +1,32 @@
using System;
namespace VibranceHud.Monitors;
public readonly record struct PanelRange(int Min, int Current, int Max)
{
public bool IsUsable
{
get
{
if (Max > Min && Current >= Min)
{
return Current <= Max;
}
return false;
}
}
public int FromPercent(int percent)
{
return Min + (int)Math.Round((double)((Max - Min) * Math.Clamp(percent, 0, 100)) / 100.0);
}
public int ToPercent(int raw)
{
if (Max <= Min)
{
return 0;
}
return Math.Clamp((int)Math.Round((double)(raw - Min) * 100.0 / (double)(Max - Min)), 0, 100);
}
}
+3
View File
@@ -0,0 +1,3 @@
namespace VibranceHud.Monitors;
public sealed record PanicResult(int PanelsRestored, int PanelsReset, int PanelsRefused, bool GammaLinear, bool DriverBack);
@@ -0,0 +1,155 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace VibranceHud.Monitors;
internal sealed class SelectedVibranceController : IVibranceController
{
private readonly IVibranceController _driver;
private readonly MonitorSelection _selection;
private readonly AppSettings _settings;
private readonly Action _save;
public int CurrentLevel => ReadEveryDisplayLevel().FirstOrDefault(new KeyValuePair<string, int>("", 50)).Value;
public int DefaultLevel => _driver.DefaultLevel;
public bool IsAvailable => _driver.IsAvailable;
public VibranceDriverState DriverState => _driver.DriverState;
public SelectedVibranceController(IVibranceController driver, MonitorSelection selection, AppSettings settings, Action save)
{
_driver = driver;
_selection = selection;
_settings = settings;
_save = save;
AppSettings appSettings = settings;
if (appSettings.OwnedMonitorVibrance == null)
{
Dictionary<string, int> dictionary = (appSettings.OwnedMonitorVibrance = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase));
}
appSettings = settings;
if (appSettings.OwnedMonitorVibranceLastWritten == null)
{
Dictionary<string, int> dictionary = (appSettings.OwnedMonitorVibranceLastWritten = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase));
}
}
public bool EveryDisplayIsAt(int level)
{
return ReadEveryDisplayLevel().All((KeyValuePair<string, int> x) => x.Value == level);
}
public IReadOnlyList<KeyValuePair<string, int>> ReadEveryDisplayLevel()
{
return (from x in _driver.ReadEveryDisplayLevel()
where _selection.IncludesDevice(x.Key)
select x).ToArray();
}
public void SetLevel(int level)
{
ReleaseExcluded();
foreach (KeyValuePair<string, int> item in ReadEveryDisplayLevel())
{
SetLevelFor(item.Key, level);
}
}
public void SetLevelFor(string id, int level)
{
if (!_selection.IncludesDevice(id))
{
return;
}
string key = _selection.KeyFor(id);
KeyValuePair<string, int> keyValuePair = _driver.ReadEveryDisplayLevel().FirstOrDefault((KeyValuePair<string, int> x) => string.Equals(x.Key, id, StringComparison.OrdinalIgnoreCase));
if (keyValuePair.Key == null)
{
return;
}
level = Math.Clamp(level, 0, 100);
if (keyValuePair.Value != level)
{
if (!_settings.OwnedMonitorVibrance.ContainsKey(key) || (_settings.OwnedMonitorVibranceLastWritten.TryGetValue(key, out var value) && keyValuePair.Value != value))
{
_settings.OwnedMonitorVibrance[key] = keyValuePair.Value;
}
_settings.OwnedMonitorVibranceLastWritten[key] = level;
_settings.NvapiRestorePending = true;
_save();
_driver.SetLevelFor(id, level);
}
}
public void ReleaseExcluded()
{
Restore((string g) => !_selection.IncludesDevice(g));
}
public void RestoreOwned()
{
Restore((string _) => true);
try
{
_save();
}
catch
{
}
}
private void Restore(Func<string, bool> release)
{
KeyValuePair<string, int>[] array = _settings.OwnedMonitorVibrance.ToArray();
for (int i = 0; i < array.Length; i++)
{
var (text2, num2) = array[i];
try
{
string device = _selection.DeviceFor(text2);
if (device == null || !release(device))
{
continue;
}
IReadOnlyList<KeyValuePair<string, int>> source = _driver.ReadEveryDisplayLevel();
KeyValuePair<string, int> keyValuePair2 = source.FirstOrDefault((KeyValuePair<string, int> x) => string.Equals(x.Key, device, StringComparison.OrdinalIgnoreCase));
bool flag;
if (keyValuePair2.Key != null)
{
flag = _settings.OwnedMonitorVibranceLastWritten.TryGetValue(text2, out var value) && keyValuePair2.Value != value && keyValuePair2.Value != num2;
if (flag || keyValuePair2.Value == num2)
{
goto IL_0124;
}
_driver.SetLevelFor(device, num2);
KeyValuePair<string, int> keyValuePair3 = _driver.ReadEveryDisplayLevel().FirstOrDefault((KeyValuePair<string, int> x) => string.Equals(x.Key, device, StringComparison.OrdinalIgnoreCase));
if (keyValuePair3.Key != null && keyValuePair3.Value == num2)
{
goto IL_0124;
}
}
continue;
IL_0124:
KeyValuePair<string, int> keyValuePair4 = source.FirstOrDefault((KeyValuePair<string, int> x) => _selection.IncludesDevice(x.Key));
if (string.Equals(device, keyValuePair4.Key, StringComparison.OrdinalIgnoreCase))
{
_settings.DriverVibranceWeLastWrote = (flag ? ((int?)null) : new int?(num2));
}
_settings.OwnedMonitorVibrance.Remove(text2);
_settings.OwnedMonitorVibranceLastWritten.Remove(text2);
_settings.NvapiRestorePending = _settings.OwnedMonitorVibrance.Count > 0;
_save();
}
catch
{
}
}
_settings.NvapiRestorePending = _settings.OwnedMonitorVibrance.Count > 0;
}
}