upload
This commit is contained in:
commit
1c7a8cf25f
579 files changed
+83196
No files matched your search
@@ -0,0 +1,37 @@
|
||||
using System;
|
||||
|
||||
namespace VibranceHud.Display;
|
||||
|
||||
public sealed class AbCompare
|
||||
{
|
||||
private readonly IClock _clock;
|
||||
|
||||
private readonly TimeSpan _cooldown;
|
||||
|
||||
private DateTime _lastToggle = DateTime.MinValue;
|
||||
|
||||
public bool ShowingNeutral { get; private set; }
|
||||
|
||||
public AbCompare(IClock? clock = null, TimeSpan? cooldown = null)
|
||||
{
|
||||
_clock = clock ?? new SystemClock();
|
||||
_cooldown = cooldown ?? TimeSpan.FromMilliseconds(250.0);
|
||||
}
|
||||
|
||||
public bool TryToggle()
|
||||
{
|
||||
DateTime utcNow = _clock.UtcNow;
|
||||
if (utcNow - _lastToggle < _cooldown)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
_lastToggle = utcNow;
|
||||
ShowingNeutral = !ShowingNeutral;
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
ShowingNeutral = false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
namespace VibranceHud.Display;
|
||||
|
||||
public readonly record struct CustomModeAdvice(CustomModeStanding Standing, string Message, int Width, int Height, int Hz);
|
||||
@@ -0,0 +1,108 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace VibranceHud.Display;
|
||||
|
||||
public static class CustomModeAdvisor
|
||||
{
|
||||
public static string PanelLine(PanelSize panel)
|
||||
{
|
||||
if (!panel.Known)
|
||||
{
|
||||
return "Windows didn't report a size for this monitor.";
|
||||
}
|
||||
return $"Your monitor is {panel.Width} x {panel.Height}.";
|
||||
}
|
||||
|
||||
public static CustomModeAdvice Advise(string widthText, string heightText, string rateText, IReadOnlyList<DisplayMode> reported, bool canRegister, string vendorHelp)
|
||||
{
|
||||
PanelSize panel = CustomModePanel.Native(reported);
|
||||
if (!TryRead(widthText, out var value) || !TryRead(heightText, out var value2))
|
||||
{
|
||||
return new CustomModeAdvice(CustomModeStanding.NothingTyped, Hint(canRegister), 0, 0, 0);
|
||||
}
|
||||
int result = 0;
|
||||
string text = (rateText ?? "").Trim();
|
||||
if (text.Length > 0 && (!int.TryParse(text, out result) || result <= 0))
|
||||
{
|
||||
return new CustomModeAdvice(CustomModeStanding.RefreshTooHigh, "Refresh rate should be a plain number, like 144 - or leave the box blank.", value, value2, 0);
|
||||
}
|
||||
switch (CustomModeLimits.Judge(value, value2, result, reported))
|
||||
{
|
||||
case CustomModeVerdict.TooSmall:
|
||||
return new CustomModeAdvice(CustomModeStanding.TooSmall, $"{value} x {value2} is too small to run a desktop in - try something like 1440 and 1080.", value, value2, result);
|
||||
case CustomModeVerdict.RefreshOutOfRange:
|
||||
return new CustomModeAdvice(CustomModeStanding.RefreshTooHigh, TooFast(result, reported), value, value2, result);
|
||||
case CustomModeVerdict.BiggerThanThePanel:
|
||||
return new CustomModeAdvice(CustomModeStanding.Impossible, CannotBeShown(value, value2, panel), value, value2, result);
|
||||
default:
|
||||
if (DisplayModes.IsSupported(reported, value, value2))
|
||||
{
|
||||
return new CustomModeAdvice(CustomModeStanding.AlreadyListed, $"{value} x {value2} is on your monitor's list - press Apply to switch to it.", value, value2, result);
|
||||
}
|
||||
if (canRegister)
|
||||
{
|
||||
return new CustomModeAdvice(CustomModeStanding.NeedsRegistering, $"Windows doesn't list {value} x {value2}, but your monitor can show it - press Apply " + "and PlexusX adds it to your graphics driver.", value, value2, result);
|
||||
}
|
||||
return new CustomModeAdvice(CustomModeStanding.CannotRegister, Join($"Windows doesn't list {value} x {value2} for this monitor, so PlexusX won't force it - " + "that is how people end up on a black screen.", vendorHelp, "Then come back and press Apply."), value, value2, result);
|
||||
}
|
||||
}
|
||||
|
||||
public static string CannotBeShown(int w, int h, PanelSize panel)
|
||||
{
|
||||
if (panel.Known)
|
||||
{
|
||||
bool flag = w > panel.Width;
|
||||
bool flag2 = h > panel.Height;
|
||||
string value;
|
||||
if (flag & flag2)
|
||||
{
|
||||
value = $"Your monitor is {panel.Width} x {panel.Height}, so {w} x {h} cannot be shown.";
|
||||
}
|
||||
else
|
||||
{
|
||||
value = (flag2 ? $"Your monitor is {panel.Height} tall, so {h} tall cannot be shown." : $"Your monitor is {panel.Width} wide, so {w} wide cannot be shown.");
|
||||
}
|
||||
DisplayMode displayMode = CustomModePanel.FitInside(w, h, panel);
|
||||
return $"{value} The closest that fits is {displayMode.Width} x {displayMode.Height}.";
|
||||
}
|
||||
return $"{w} x {h} is bigger than any monitor - nothing could show it.";
|
||||
}
|
||||
|
||||
private static string TooFast(int hz, IReadOnlyList<DisplayMode> reported)
|
||||
{
|
||||
int num = ((reported.Count != 0) ? reported.Max((DisplayMode m) => m.RefreshHz) : 0);
|
||||
if (num <= 0)
|
||||
{
|
||||
return $"{hz} Hz is faster than any monitor runs - leave the box blank for its own rate.";
|
||||
}
|
||||
return $"{hz} Hz is faster than this monitor goes - it tops out at {num} Hz. " + "Leave the box blank for its own rate.";
|
||||
}
|
||||
|
||||
private static string Hint(bool canRegister)
|
||||
{
|
||||
if (!canRegister)
|
||||
{
|
||||
return "Anything your monitor reports. If it refuses one, nothing changes.";
|
||||
}
|
||||
return "Type any size that fits - if Windows doesn't list it, PlexusX adds it to your graphics driver.";
|
||||
}
|
||||
|
||||
private static string Join(params string[] parts)
|
||||
{
|
||||
return string.Join(" ", from p in parts
|
||||
where !string.IsNullOrWhiteSpace(p)
|
||||
select p.Trim());
|
||||
}
|
||||
|
||||
private static bool TryRead(string? text, out int value)
|
||||
{
|
||||
value = 0;
|
||||
string text2 = (text ?? "").Trim();
|
||||
if (text2.Length > 0 && int.TryParse(text2, out value))
|
||||
{
|
||||
return value > 0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
namespace VibranceHud.Display;
|
||||
|
||||
public readonly record struct CustomModeAttempt(CustomModeOutcome Outcome, CustomModeVerdict Verdict, int Hz, bool Stretched);
|
||||
@@ -0,0 +1,129 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace VibranceHud.Display;
|
||||
|
||||
public static class CustomModeLimits
|
||||
{
|
||||
internal const int MinWidth = 640;
|
||||
|
||||
internal const int MinHeight = 480;
|
||||
|
||||
private const int MaxWidth = 15360;
|
||||
|
||||
private const int MaxHeight = 8640;
|
||||
|
||||
private const int MaxHz = 1000;
|
||||
|
||||
public static int NativeRateFor(int typedHz, IReadOnlyList<DisplayMode> reported, int running)
|
||||
{
|
||||
PanelSize panelSize = CustomModePanel.Native(reported);
|
||||
IReadOnlyList<int> readOnlyList2;
|
||||
if (!panelSize.Known)
|
||||
{
|
||||
IReadOnlyList<int> readOnlyList = Array.Empty<int>();
|
||||
readOnlyList2 = readOnlyList;
|
||||
}
|
||||
else
|
||||
{
|
||||
readOnlyList2 = DisplayModes.RefreshRatesFor(reported, panelSize.Width, panelSize.Height);
|
||||
}
|
||||
IReadOnlyList<int> rates = readOnlyList2;
|
||||
return SelectNativeRate(typedHz, rates, running);
|
||||
}
|
||||
|
||||
internal static int SelectNativeRate(int typedHz, IReadOnlyList<int> rates, int running)
|
||||
{
|
||||
if (rates.Count == 0)
|
||||
{
|
||||
if (typedHz <= 0)
|
||||
{
|
||||
return running;
|
||||
}
|
||||
return typedHz;
|
||||
}
|
||||
int num = rates[0];
|
||||
foreach (int rate in rates)
|
||||
{
|
||||
bool num2;
|
||||
if (typedHz > 0)
|
||||
{
|
||||
if (Math.Abs(rate - typedHz) < Math.Abs(num - typedHz))
|
||||
{
|
||||
goto IL_0062;
|
||||
}
|
||||
if (Math.Abs(rate - typedHz) != Math.Abs(num - typedHz))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
num2 = rate > num;
|
||||
}
|
||||
else
|
||||
{
|
||||
num2 = rate > num;
|
||||
}
|
||||
if (!num2)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
goto IL_0062;
|
||||
IL_0062:
|
||||
num = rate;
|
||||
}
|
||||
return num;
|
||||
}
|
||||
|
||||
public static CustomModeVerdict Judge(int width, int height, int hz, IReadOnlyList<DisplayMode> reported)
|
||||
{
|
||||
if (width < 640 || height < 480)
|
||||
{
|
||||
return CustomModeVerdict.TooSmall;
|
||||
}
|
||||
if (hz > 1000)
|
||||
{
|
||||
return CustomModeVerdict.RefreshOutOfRange;
|
||||
}
|
||||
PanelSize panelSize = CustomModePanel.Native(reported);
|
||||
if (!panelSize.Known)
|
||||
{
|
||||
if (width <= 15360 && height <= 8640)
|
||||
{
|
||||
return CustomModeVerdict.Fine;
|
||||
}
|
||||
return CustomModeVerdict.BiggerThanThePanel;
|
||||
}
|
||||
int num = 0;
|
||||
foreach (DisplayMode item in reported)
|
||||
{
|
||||
if (item.RefreshHz > num)
|
||||
{
|
||||
num = item.RefreshHz;
|
||||
}
|
||||
}
|
||||
if (hz > 0 && num > 0 && hz > num)
|
||||
{
|
||||
return CustomModeVerdict.RefreshOutOfRange;
|
||||
}
|
||||
if (width <= panelSize.Width && height <= panelSize.Height)
|
||||
{
|
||||
return CustomModeVerdict.Fine;
|
||||
}
|
||||
return CustomModeVerdict.BiggerThanThePanel;
|
||||
}
|
||||
|
||||
public static bool NeedsStretching(int width, int height, IReadOnlyList<DisplayMode> reported)
|
||||
{
|
||||
if (width <= 0 || height <= 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
PanelSize panelSize = CustomModePanel.Native(reported);
|
||||
if (!panelSize.Known)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
double num = (double)panelSize.Width / (double)panelSize.Height;
|
||||
double num2 = (double)width / (double)height;
|
||||
return Math.Abs(num - num2) > 0.01;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace VibranceHud.Display;
|
||||
|
||||
public static class CustomModeOffers
|
||||
{
|
||||
private static readonly DisplayMode[] FourThreeLadder = new DisplayMode[4]
|
||||
{
|
||||
new DisplayMode(1600, 1200, 0),
|
||||
new DisplayMode(1280, 960, 0),
|
||||
new DisplayMode(1024, 768, 0),
|
||||
new DisplayMode(800, 600, 0)
|
||||
};
|
||||
|
||||
private const int LadderRungs = 2;
|
||||
|
||||
public static IReadOnlyList<DisplayMode> For(PanelSize panel)
|
||||
{
|
||||
if (!panel.Known)
|
||||
{
|
||||
return Array.Empty<DisplayMode>();
|
||||
}
|
||||
List<DisplayMode> list = new List<DisplayMode>();
|
||||
Offer(list, panel, panel.Height, panel.Height);
|
||||
Offer(list, panel, CustomModePanel.Even(panel.Height * 4 / 3), panel.Height);
|
||||
int num = 0;
|
||||
DisplayMode[] fourThreeLadder = FourThreeLadder;
|
||||
for (int i = 0; i < fourThreeLadder.Length; i++)
|
||||
{
|
||||
DisplayMode displayMode = fourThreeLadder[i];
|
||||
if (num >= 2)
|
||||
{
|
||||
break;
|
||||
}
|
||||
if (displayMode.Height < panel.Height && Offer(list, panel, displayMode.Width, displayMode.Height))
|
||||
{
|
||||
num++;
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
private static bool Offer(List<DisplayMode> into, PanelSize panel, int w, int h)
|
||||
{
|
||||
if (w > panel.Width || h > panel.Height)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (w < 640 || h < 480)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (w == panel.Width && h == panel.Height)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
DisplayMode item = new DisplayMode(w, h, 0);
|
||||
if (into.Contains(item))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
into.Add(item);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace VibranceHud.Display;
|
||||
|
||||
public enum CustomModeOutcome
|
||||
{
|
||||
Applied,
|
||||
Reverted,
|
||||
RevertFailed,
|
||||
OutOfRange,
|
||||
NotAvailable,
|
||||
DriverRefused,
|
||||
AppliedButNotSaved,
|
||||
ScalingFailed
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace VibranceHud.Display;
|
||||
|
||||
public static class CustomModePanel
|
||||
{
|
||||
public static PanelSize Native(IReadOnlyList<DisplayMode> reported)
|
||||
{
|
||||
int width = 0;
|
||||
int height = 0;
|
||||
long num = 0L;
|
||||
foreach (DisplayMode item in reported)
|
||||
{
|
||||
long num2 = (long)item.Width * (long)item.Height;
|
||||
if (num2 > num)
|
||||
{
|
||||
num = num2;
|
||||
width = item.Width;
|
||||
height = item.Height;
|
||||
}
|
||||
}
|
||||
return new PanelSize(width, height);
|
||||
}
|
||||
|
||||
public static DisplayMode FitInside(int width, int height, PanelSize panel)
|
||||
{
|
||||
if (width <= 0 || height <= 0 || !panel.Known)
|
||||
{
|
||||
return new DisplayMode(panel.Width, panel.Height, 0);
|
||||
}
|
||||
double num = Math.Min((double)panel.Width / (double)width, (double)panel.Height / (double)height);
|
||||
if (num >= 1.0)
|
||||
{
|
||||
return new DisplayMode(Even(width), Even(height), 0);
|
||||
}
|
||||
int num2 = Even((int)Math.Floor((double)width * num));
|
||||
int num3 = Even((int)Math.Floor((double)height * num));
|
||||
if (num2 < 640 || num3 < 480)
|
||||
{
|
||||
return new DisplayMode(panel.Width, panel.Height, 0);
|
||||
}
|
||||
return new DisplayMode(num2, num3, 0);
|
||||
}
|
||||
|
||||
internal static int Even(int value)
|
||||
{
|
||||
return value - Math.Abs(value % 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,368 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using VibranceHud.Controls;
|
||||
|
||||
namespace VibranceHud.Display;
|
||||
|
||||
public sealed class CustomModeRegistrar
|
||||
{
|
||||
private readonly ICustomModeDriver _driver;
|
||||
|
||||
private readonly Func<string?, IReadOnlyList<DisplayMode>> _supportedModes;
|
||||
|
||||
private readonly Func<string?, DisplayMode?> _current;
|
||||
|
||||
private readonly Func<DisplayMode, string?, bool> _restore;
|
||||
|
||||
private readonly Func<string, TimeSpan, bool> _confirm;
|
||||
|
||||
private readonly Func<string?, ScalingMode?> _readScaling;
|
||||
|
||||
private readonly Func<ScalingMode, bool, string?, bool> _setScaling;
|
||||
|
||||
private readonly IDesktopLayout _layout;
|
||||
|
||||
private readonly Func<string?, string?> _linkHint;
|
||||
|
||||
private readonly ShapeFit? _fit;
|
||||
|
||||
[ThreadStatic]
|
||||
private static bool _switching;
|
||||
|
||||
public bool HoldsTheRealLayout => _layout is DesktopLayout.RealDesktopLayout;
|
||||
|
||||
public bool Available => Guarded(() => _driver.Available) == true;
|
||||
|
||||
public CustomModeRegistrar(ICustomModeDriver driver, Func<string?, IReadOnlyList<DisplayMode>>? supportedModes = null, Func<string?, DisplayMode?>? current = null, Func<DisplayMode, string?, bool>? restore = null, Func<string, TimeSpan, bool>? confirm = null, Func<string?, ScalingMode?>? readScaling = null, Func<ScalingMode, bool, string?, bool>? setScaling = null, IDesktopLayout? layout = null, Func<string?, string?>? linkHint = null, ShapeFit? fit = null)
|
||||
{
|
||||
_driver = driver;
|
||||
_fit = fit;
|
||||
_layout = layout ?? DesktopLayout.None;
|
||||
_linkHint = linkHint ?? ((Func<string, string>)((string? _) => (string?)null));
|
||||
_supportedModes = supportedModes ?? ((Func<string, IReadOnlyList<DisplayMode>>)((string? d) => DisplayController.SupportedModes(d)));
|
||||
_current = current ?? ((Func<string, DisplayMode?>)((string? d) => DisplayController.Current(d)));
|
||||
_restore = restore ?? ((Func<DisplayMode, string, bool>)((DisplayMode m, string? d) => DisplayController.Restore(m, d)));
|
||||
_confirm = confirm ?? new Func<string, TimeSpan, bool>(AskWithTheCountdown);
|
||||
_readScaling = readScaling ?? ((Func<string, ScalingMode?>)((string? d) => ScalingModeController.Stored(d)));
|
||||
_setScaling = setScaling ?? ((Func<ScalingMode, bool, string, bool>)((ScalingMode m, bool p, string? d) => ScalingModeController.TrySet(m, p, d)));
|
||||
}
|
||||
|
||||
public static CustomModeRegistrar Real()
|
||||
{
|
||||
return new CustomModeRegistrar(new NvidiaCustomModeDriver(), null, null, null, null, null, null, DesktopLayout.Real(), EdidLinkReader.Hint, ShapeFit.Shared);
|
||||
}
|
||||
|
||||
public static CustomModeRegistrar Disabled()
|
||||
{
|
||||
return new CustomModeRegistrar(new NoCustomModeDriver(), (string? _) => Array.Empty<DisplayMode>(), (string? _) => (DisplayMode?)null, (DisplayMode _, string? _) => false, (string _, TimeSpan _) => false, (string? _) => (ScalingMode?)null, (ScalingMode _, bool _, string? _) => false);
|
||||
}
|
||||
|
||||
public string? LinkHint(string? deviceName)
|
||||
{
|
||||
return GuardedValue(() => _linkHint(deviceName), null);
|
||||
}
|
||||
|
||||
public IReadOnlyList<DisplayMode> SavedSizes(string? deviceName)
|
||||
{
|
||||
if (Guarded(() => _driver.Available) != true)
|
||||
{
|
||||
return Array.Empty<DisplayMode>();
|
||||
}
|
||||
return GuardedValue(() => _driver.Saved(deviceName) ?? Array.Empty<DisplayMode>(), Array.Empty<DisplayMode>());
|
||||
}
|
||||
|
||||
public bool SwitchToSaved(int width, int height, int hz, string? deviceName)
|
||||
{
|
||||
if (_switching)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
_switching = true;
|
||||
try
|
||||
{
|
||||
DisplayMode? displayMode = null;
|
||||
foreach (DisplayMode item in SavedSizes(deviceName))
|
||||
{
|
||||
if (item.Width == width && item.Height == height && (hz <= 0 || item.RefreshHz <= 0 || item.RefreshHz == hz))
|
||||
{
|
||||
displayMode = item;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (displayMode.HasValue)
|
||||
{
|
||||
DisplayMode valueOrDefault = displayMode.GetValueOrDefault();
|
||||
IReadOnlyList<DisplayMode> reported = GuardedValue(() => _supportedModes(deviceName), Array.Empty<DisplayMode>());
|
||||
int judgedHz = ((hz > 0) ? hz : valueOrDefault.RefreshHz);
|
||||
if (CustomModeLimits.Judge(width, height, judgedHz, reported) != CustomModeVerdict.Fine)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
DisplayMode? native = NativeOf(reported);
|
||||
if (Guarded(() => _driver.IsOnTheNativeSignal(deviceName, width, height, judgedHz, native)) != true)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
DisplayMode? displayMode2 = GuardedValue(() => _current(deviceName), null);
|
||||
if (displayMode2.HasValue)
|
||||
{
|
||||
DisplayMode valueOrDefault2 = displayMode2.GetValueOrDefault();
|
||||
if (valueOrDefault2.Width == width && valueOrDefault2.Height == height)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
int rate;
|
||||
if (hz > 0)
|
||||
{
|
||||
rate = hz;
|
||||
}
|
||||
else
|
||||
{
|
||||
rate = ((valueOrDefault.RefreshHz > 0) ? valueOrDefault.RefreshHz : valueOrDefault2.RefreshHz);
|
||||
}
|
||||
IReadOnlyList<MonitorPlacement> layoutBefore = GuardedValue(() => _layout.Read(), Array.Empty<MonitorPlacement>());
|
||||
ScalingMode? scalingMode = GuardedValue(() => _readScaling(deviceName), null);
|
||||
if (CustomModeLimits.NeedsStretching(width, height, reported) && scalingMode != ScalingMode.FullScreen)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (Guarded(() => _driver.Trial(deviceName, width, height, rate, native)) != true || !IsShowing(width, height, deviceName))
|
||||
{
|
||||
UndoEverything(valueOrDefault2, deviceName, null, stretched: false, layoutBefore);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_switching = false;
|
||||
}
|
||||
}
|
||||
|
||||
public CustomModeAttempt TryApply(int width, int height, int hz, string? deviceName, TimeSpan grace)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Attempt(width, height, hz, deviceName, grace);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return new CustomModeAttempt(CustomModeOutcome.NotAvailable, CustomModeVerdict.Fine, hz, Stretched: false);
|
||||
}
|
||||
}
|
||||
|
||||
private CustomModeAttempt Attempt(int width, int height, int hz, string? deviceName, TimeSpan grace)
|
||||
{
|
||||
IReadOnlyList<DisplayMode> reported = GuardedValue(() => _supportedModes(deviceName), Array.Empty<DisplayMode>());
|
||||
CustomModeVerdict customModeVerdict = CustomModeLimits.Judge(width, height, hz, reported);
|
||||
if (customModeVerdict != CustomModeVerdict.Fine)
|
||||
{
|
||||
return new CustomModeAttempt(CustomModeOutcome.OutOfRange, customModeVerdict, hz, Stretched: false);
|
||||
}
|
||||
if (Guarded(() => _driver.Available) != true)
|
||||
{
|
||||
return NotAvailable(hz);
|
||||
}
|
||||
DisplayMode? displayMode = GuardedValue(() => _current(deviceName), null);
|
||||
if (displayMode.HasValue)
|
||||
{
|
||||
DisplayMode original = displayMode.GetValueOrDefault();
|
||||
int rate = CustomModeLimits.NativeRateFor(hz, reported, original.RefreshHz);
|
||||
IReadOnlyList<MonitorPlacement> readOnlyList = GuardedValue(() => _layout.Read(), Array.Empty<MonitorPlacement>());
|
||||
ScalingMode? scalingMode = GuardedValue(() => _readScaling(deviceName), null);
|
||||
bool flag = false;
|
||||
DisplayMode? native = NativeOf(reported);
|
||||
bool? flag2 = Guarded(() => _driver.Trial(deviceName, width, height, rate, native));
|
||||
if (!flag2.HasValue)
|
||||
{
|
||||
UndoEverything(original, deviceName, scalingMode, flag, readOnlyList);
|
||||
return NotAvailable(rate);
|
||||
}
|
||||
if (flag2 == false)
|
||||
{
|
||||
UndoEverything(original, deviceName, scalingMode, flag, readOnlyList);
|
||||
return new CustomModeAttempt(CustomModeOutcome.DriverRefused, customModeVerdict, rate, flag);
|
||||
}
|
||||
if (!IsShowing(width, height, deviceName))
|
||||
{
|
||||
UndoEverything(original, deviceName, scalingMode, flag, readOnlyList);
|
||||
return new CustomModeAttempt(CustomModeOutcome.DriverRefused, customModeVerdict, rate, flag);
|
||||
}
|
||||
bool flag3 = CustomModeLimits.NeedsStretching(width, height, reported);
|
||||
string message = $"Switched to {width} x {height}" + ((rate > 0) ? $" at {rate} Hz" : "") + ".";
|
||||
if (Guarded(() => _confirm(message, grace)) == true)
|
||||
{
|
||||
if (Guarded(() => _driver.Save(deviceName)) != true)
|
||||
{
|
||||
return new CustomModeAttempt(CustomModeOutcome.AppliedButNotSaved, customModeVerdict, rate, flag);
|
||||
}
|
||||
if (flag3 && IsShowing(width, height, deviceName))
|
||||
{
|
||||
flag = SetScalingChecked(ScalingMode.FullScreen, persist: true, deviceName);
|
||||
NoteTheStretch(width, height, flag, deviceName);
|
||||
if (flag)
|
||||
{
|
||||
_fit?.Remember(scalingMode, deviceName);
|
||||
}
|
||||
}
|
||||
if (flag3 && !flag)
|
||||
{
|
||||
return new CustomModeAttempt(CustomModeOutcome.ScalingFailed, customModeVerdict, rate, Stretched: false);
|
||||
}
|
||||
return new CustomModeAttempt(CustomModeOutcome.Applied, customModeVerdict, rate, flag);
|
||||
}
|
||||
bool valueOrDefault = Guarded(() => _driver.Revert(deviceName)) == true;
|
||||
bool flag4 = IsShowing(original.Width, original.Height, deviceName) || (Guarded(() => _restore(original, deviceName)) == true && IsShowing(original.Width, original.Height, deviceName));
|
||||
bool flag5 = RestoreScaling(scalingMode, flag, deviceName);
|
||||
PutTheLayoutBack(readOnlyList);
|
||||
return new CustomModeAttempt((valueOrDefault & flag4 & flag5) ? CustomModeOutcome.Reverted : CustomModeOutcome.RevertFailed, customModeVerdict, rate, flag);
|
||||
}
|
||||
return NotAvailable(hz);
|
||||
}
|
||||
|
||||
private void PutTheLayoutBack(IReadOnlyList<MonitorPlacement> before)
|
||||
{
|
||||
if (before.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
IReadOnlyList<MonitorPlacement> now = GuardedValue(() => _layout.Read(), Array.Empty<MonitorPlacement>());
|
||||
IReadOnlyList<MonitorPlacement> moved = DesktopLayout.WhatMoved(before, now);
|
||||
if (moved.Count != 0)
|
||||
{
|
||||
Guarded(() => _layout.Place(moved));
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsShowing(int width, int height, string? deviceName)
|
||||
{
|
||||
DisplayMode? displayMode = GuardedValue(() => _current(deviceName), null);
|
||||
if (displayMode.HasValue)
|
||||
{
|
||||
DisplayMode valueOrDefault = displayMode.GetValueOrDefault();
|
||||
if (valueOrDefault.Width == width)
|
||||
{
|
||||
return valueOrDefault.Height == height;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static DisplayMode? NativeOf(IReadOnlyList<DisplayMode> reported)
|
||||
{
|
||||
return NvidiaCustomModeDriver.NativeModeOf(reported);
|
||||
}
|
||||
|
||||
private static CustomModeAttempt NotAvailable(int hz)
|
||||
{
|
||||
return new CustomModeAttempt(CustomModeOutcome.NotAvailable, CustomModeVerdict.Fine, hz, Stretched: false);
|
||||
}
|
||||
|
||||
private void UndoEverything(DisplayMode original, string? deviceName, ScalingMode? previousScaling, bool stretched, IReadOnlyList<MonitorPlacement> layoutBefore)
|
||||
{
|
||||
Guarded(() => _driver.Revert(deviceName));
|
||||
if (!IsShowing(original.Width, original.Height, deviceName))
|
||||
{
|
||||
Guarded(() => _restore(original, deviceName));
|
||||
}
|
||||
RestoreScaling(previousScaling, stretched, deviceName);
|
||||
PutTheLayoutBack(layoutBefore);
|
||||
}
|
||||
|
||||
private void NoteTheStretch(int width, int height, bool stretched, string? deviceName)
|
||||
{
|
||||
try
|
||||
{
|
||||
string status = "refused";
|
||||
if (stretched)
|
||||
{
|
||||
string text = "unknown";
|
||||
try
|
||||
{
|
||||
text = _readScaling(deviceName)?.ToString() ?? "unknown";
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
status = "written, driver now holds " + text;
|
||||
}
|
||||
NvapiFallbackLog.NoteCustomModeStep($"stretch {width}x{height}", status);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private bool SetScalingChecked(ScalingMode mode, bool persist, string? deviceName)
|
||||
{
|
||||
if (Guarded(() => _setScaling(mode, persist, deviceName)) == true)
|
||||
{
|
||||
ScalingMode? scalingMode = GuardedValue(() => _readScaling(deviceName), null);
|
||||
if (scalingMode.HasValue)
|
||||
{
|
||||
ScalingMode valueOrDefault = scalingMode.GetValueOrDefault();
|
||||
return valueOrDefault == mode;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private bool RestoreScaling(ScalingMode? previous, bool stretched, string? deviceName)
|
||||
{
|
||||
if (!stretched)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if (previous.HasValue)
|
||||
{
|
||||
ScalingMode valueOrDefault = previous.GetValueOrDefault();
|
||||
return SetScalingChecked(valueOrDefault, persist: false, deviceName);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool AskWithTheCountdown(string message, TimeSpan grace)
|
||||
{
|
||||
bool confirmed = false;
|
||||
using RevertConfirmForm revertConfirmForm = new RevertConfirmForm(message, Math.Max(1, (int)Math.Ceiling(grace.TotalSeconds)));
|
||||
revertConfirmForm.Confirmed += () =>
|
||||
{
|
||||
confirmed = true;
|
||||
};
|
||||
revertConfirmForm.ShowDialog();
|
||||
return confirmed;
|
||||
}
|
||||
|
||||
private static bool? Guarded(Func<bool> call)
|
||||
{
|
||||
try
|
||||
{
|
||||
return call();
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static T GuardedValue<T>(Func<T> call, T fallback)
|
||||
{
|
||||
try
|
||||
{
|
||||
return call();
|
||||
}
|
||||
catch
|
||||
{
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace VibranceHud.Display;
|
||||
|
||||
public enum CustomModeStanding
|
||||
{
|
||||
NothingTyped,
|
||||
TooSmall,
|
||||
RefreshTooHigh,
|
||||
Impossible,
|
||||
AlreadyListed,
|
||||
NeedsRegistering,
|
||||
CannotRegister
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace VibranceHud.Display;
|
||||
|
||||
public enum CustomModeVerdict
|
||||
{
|
||||
Fine,
|
||||
TooSmall,
|
||||
BiggerThanThePanel,
|
||||
RefreshOutOfRange
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace VibranceHud.Display;
|
||||
|
||||
public static class DesktopLayout
|
||||
{
|
||||
private sealed class NoDesktopLayout : IDesktopLayout
|
||||
{
|
||||
public IReadOnlyList<MonitorPlacement> Read()
|
||||
{
|
||||
return Array.Empty<MonitorPlacement>();
|
||||
}
|
||||
|
||||
public bool Place(IReadOnlyList<MonitorPlacement> placements)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class RealDesktopLayout : IDesktopLayout
|
||||
{
|
||||
public IReadOnlyList<MonitorPlacement> Read()
|
||||
{
|
||||
return DisplayController.Placements();
|
||||
}
|
||||
|
||||
public bool Place(IReadOnlyList<MonitorPlacement> placements)
|
||||
{
|
||||
return DisplayController.PlaceMonitors(placements);
|
||||
}
|
||||
}
|
||||
|
||||
public static IDesktopLayout None { get; } = new NoDesktopLayout();
|
||||
|
||||
public static IDesktopLayout Real()
|
||||
{
|
||||
return new RealDesktopLayout();
|
||||
}
|
||||
|
||||
public static IReadOnlyList<MonitorPlacement> WhatMoved(IReadOnlyList<MonitorPlacement> before, IReadOnlyList<MonitorPlacement> now)
|
||||
{
|
||||
List<MonitorPlacement> list = new List<MonitorPlacement>();
|
||||
foreach (MonitorPlacement item in before)
|
||||
{
|
||||
foreach (MonitorPlacement item2 in now)
|
||||
{
|
||||
if (string.Equals(item.DeviceName, item2.DeviceName, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (item.X != item2.X || item.Y != item2.Y)
|
||||
{
|
||||
list.Add(item);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace VibranceHud.Display;
|
||||
|
||||
public static class EdidLink
|
||||
{
|
||||
public static int MaxVerticalHz(byte[]? edid)
|
||||
{
|
||||
if (edid == null || edid.Length < 128)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
for (int i = 54; i <= 108; i += 18)
|
||||
{
|
||||
if (edid[i] == 0 && edid[i + 1] == 0 && edid[i + 3] == 253)
|
||||
{
|
||||
return edid[i + 6] + (((edid[i + 4] & 2) != 0) ? 255 : 0);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static bool IsDisplayPort(byte[]? edid)
|
||||
{
|
||||
if (edid != null && edid.Length >= 21 && edid[18] == 1 && edid[19] >= 4 && (edid[20] & 0x80) != 0)
|
||||
{
|
||||
return (edid[20] & 0xF) == 5;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static string? CeilingHint(int fastestListed, byte[]? current, IReadOnlyList<byte[]> sameModel)
|
||||
{
|
||||
if (fastestListed <= 0 || current == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
int num = 0;
|
||||
bool flag = false;
|
||||
foreach (byte[] item in sameModel)
|
||||
{
|
||||
int num2 = MaxVerticalHz(item);
|
||||
if (num2 > num)
|
||||
{
|
||||
num = num2;
|
||||
flag = IsDisplayPort(item);
|
||||
}
|
||||
}
|
||||
if (num <= fastestListed || num <= MaxVerticalHz(current))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if (flag && !IsDisplayPort(current))
|
||||
{
|
||||
return $"Your monitor does {num} Hz over DisplayPort. On this cable it stops at {fastestListed} Hz - plug in a DisplayPort cable to get {num} Hz.";
|
||||
}
|
||||
return $"Your monitor has run {num} Hz on another port. On this one it stops at {fastestListed} Hz.";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows.Forms;
|
||||
using Microsoft.Win32;
|
||||
|
||||
namespace VibranceHud.Display;
|
||||
|
||||
internal static class EdidLinkReader
|
||||
{
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
||||
private struct DISPLAY_DEVICE
|
||||
{
|
||||
public int cb;
|
||||
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
|
||||
public string DeviceName;
|
||||
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
|
||||
public string DeviceString;
|
||||
|
||||
public int StateFlags;
|
||||
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
|
||||
public string DeviceID;
|
||||
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
|
||||
public string DeviceKey;
|
||||
}
|
||||
|
||||
private const int EDD_GET_DEVICE_INTERFACE_NAME = 1;
|
||||
|
||||
[DllImport("user32.dll", CharSet = CharSet.Unicode, EntryPoint = "EnumDisplayDevicesW")]
|
||||
private static extern bool EnumDisplayDevices(string? lpDevice, int iDevNum, ref DISPLAY_DEVICE dd, int flags);
|
||||
|
||||
public static string? Hint(string? deviceName)
|
||||
{
|
||||
try
|
||||
{
|
||||
string text = deviceName ?? Screen.PrimaryScreen?.DeviceName ?? "";
|
||||
if (text.Length == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
DISPLAY_DEVICE dd = new DISPLAY_DEVICE
|
||||
{
|
||||
cb = Marshal.SizeOf<DISPLAY_DEVICE>()
|
||||
};
|
||||
if (!EnumDisplayDevices(text, 0, ref dd, 1))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
string[] array = (dd.DeviceID ?? "").Split('#');
|
||||
if (array.Length < 3)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
using RegistryKey registryKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
|
||||
using RegistryKey registryKey2 = registryKey.OpenSubKey("SYSTEM\\CurrentControlSet\\Enum\\DISPLAY\\" + array[1], writable: false);
|
||||
if (registryKey2 == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
byte[] current = null;
|
||||
List<byte[]> list = new List<byte[]>();
|
||||
string[] subKeyNames = registryKey2.GetSubKeyNames();
|
||||
foreach (string text2 in subKeyNames)
|
||||
{
|
||||
using RegistryKey registryKey3 = registryKey2.OpenSubKey(text2 + "\\Device Parameters", writable: false);
|
||||
if (registryKey3?.GetValue("EDID") is byte[] array2)
|
||||
{
|
||||
list.Add(array2);
|
||||
if (string.Equals(text2, array[2], StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
current = array2;
|
||||
}
|
||||
}
|
||||
}
|
||||
int num = 0;
|
||||
foreach (DisplayMode item in DisplayController.SupportedModes(text))
|
||||
{
|
||||
if (item.RefreshHz > num)
|
||||
{
|
||||
num = item.RefreshHz;
|
||||
}
|
||||
}
|
||||
return EdidLink.CeilingHint(num, current, list);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using System;
|
||||
|
||||
namespace VibranceHud.Display;
|
||||
|
||||
public interface IClock
|
||||
{
|
||||
DateTime UtcNow { get; }
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace VibranceHud.Display;
|
||||
|
||||
public interface ICustomModeDriver
|
||||
{
|
||||
bool Available { get; }
|
||||
|
||||
bool Trial(string? deviceName, int width, int height, int hz);
|
||||
|
||||
bool Trial(string? deviceName, int width, int height, int hz, DisplayMode? native)
|
||||
{
|
||||
return Trial(deviceName, width, height, hz);
|
||||
}
|
||||
|
||||
bool IsOnTheNativeSignal(string? deviceName, int width, int height, int hz, DisplayMode? native)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Save(string? deviceName);
|
||||
|
||||
bool Revert(string? deviceName);
|
||||
|
||||
IReadOnlyList<DisplayMode> Saved(string? deviceName)
|
||||
{
|
||||
return Array.Empty<DisplayMode>();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace VibranceHud.Display;
|
||||
|
||||
public interface IDesktopLayout
|
||||
{
|
||||
IReadOnlyList<MonitorPlacement> Read();
|
||||
|
||||
bool Place(IReadOnlyList<MonitorPlacement> placements);
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
using System;
|
||||
using VibranceHud.Capabilities;
|
||||
using VibranceHud.Controls;
|
||||
|
||||
namespace VibranceHud.Display;
|
||||
|
||||
public sealed class ModeApplier
|
||||
{
|
||||
internal sealed record Steps(Func<string?, DisplayMode?> Current, Func<int, int, int, string?, bool, DispChangeResult> Apply, Func<DisplayMode, string?, bool> Restore, Func<string, TimeSpan, bool> Confirm);
|
||||
|
||||
private readonly Func<int, int, int, string?, TimeSpan, DispChangeResult> _apply;
|
||||
|
||||
private readonly Func<bool, string?, TimeSpan, HdrSwitchOutcome>? _setHdr;
|
||||
|
||||
public bool MovesARealScreen { get; }
|
||||
|
||||
public ModeApplier(Func<int, int, int, string?, TimeSpan, DispChangeResult> apply, bool movesARealScreen, Func<bool, string?, TimeSpan, HdrSwitchOutcome>? setHdr = null)
|
||||
{
|
||||
_apply = apply;
|
||||
_setHdr = setHdr;
|
||||
MovesARealScreen = movesARealScreen;
|
||||
}
|
||||
|
||||
public HdrSwitchOutcome SetHdr(bool enabled, string? deviceName, TimeSpan grace)
|
||||
{
|
||||
return _setHdr?.Invoke(enabled, deviceName, grace) ?? HdrSwitchOutcome.Failed;
|
||||
}
|
||||
|
||||
public static ModeApplier Real()
|
||||
{
|
||||
return new ModeApplier((int width, int height, int hz, string? deviceName, TimeSpan grace) => ApplyThenFit(width, height, hz, deviceName, grace, RealSteps(), ShapeFit.Shared), movesARealScreen: true, HdrDetection.SwitchWithRevertReal);
|
||||
}
|
||||
|
||||
private static Steps RealSteps()
|
||||
{
|
||||
return new Steps((string? d) => DisplayController.Current(d), (int w, int h, int hz, string? d, bool persist) => DisplayController.ApplyEx(w, h, hz, d, persist), (DisplayMode m, string? d) => DisplayController.Restore(m, d), (string message, TimeSpan grace) =>
|
||||
{
|
||||
bool confirmed = false;
|
||||
using RevertConfirmForm revertConfirmForm = new RevertConfirmForm(message, Math.Max(1, (int)Math.Ceiling(grace.TotalSeconds)));
|
||||
revertConfirmForm.Confirmed += () =>
|
||||
{
|
||||
confirmed = true;
|
||||
};
|
||||
revertConfirmForm.ShowDialog();
|
||||
return confirmed;
|
||||
});
|
||||
}
|
||||
|
||||
internal static DispChangeResult ApplyThenFit(int width, int height, int hz, string? deviceName, TimeSpan grace, Steps steps, ShapeFit fit)
|
||||
{
|
||||
DisplayMode? displayMode = steps.Current(deviceName);
|
||||
if (displayMode.HasValue)
|
||||
{
|
||||
DisplayMode valueOrDefault = displayMode.GetValueOrDefault();
|
||||
ScalingMode? before = fit.ReadBefore(deviceName);
|
||||
DispChangeResult dispChangeResult = steps.Apply(width, height, hz, deviceName, arg5: false);
|
||||
if (dispChangeResult != DispChangeResult.Successful)
|
||||
{
|
||||
return dispChangeResult;
|
||||
}
|
||||
ShapeFit.Change change = fit.Fill(width, height, deviceName, before);
|
||||
if (change.Result == ShapeFit.Outcome.Failed)
|
||||
{
|
||||
steps.Restore(valueOrDefault, deviceName);
|
||||
fit.Undo(change, deviceName);
|
||||
return DispChangeResult.Failed;
|
||||
}
|
||||
if (!steps.Confirm($"Switched to {width} x {height}" + ((hz > 0) ? $" at {hz} Hz" : "") + ".", grace))
|
||||
{
|
||||
bool flag = steps.Restore(valueOrDefault, deviceName);
|
||||
ShapeFit.Outcome outcome = fit.Undo(change, deviceName);
|
||||
if (!flag || outcome == ShapeFit.Outcome.Failed)
|
||||
{
|
||||
return DispChangeResult.Failed;
|
||||
}
|
||||
return DispChangeResult.Reverted;
|
||||
}
|
||||
DispChangeResult dispChangeResult2 = steps.Apply(width, height, hz, deviceName, arg5: true);
|
||||
if (dispChangeResult2 != DispChangeResult.Successful)
|
||||
{
|
||||
steps.Restore(valueOrDefault, deviceName);
|
||||
fit.Undo(change, deviceName);
|
||||
return dispChangeResult2;
|
||||
}
|
||||
if (fit.Keep(change, deviceName) != ShapeFit.Outcome.Failed)
|
||||
{
|
||||
return dispChangeResult2;
|
||||
}
|
||||
return DispChangeResult.Failed;
|
||||
}
|
||||
return DispChangeResult.Failed;
|
||||
}
|
||||
|
||||
public static ModeApplier Dead()
|
||||
{
|
||||
return new ModeApplier((int _, int _, int _, string? _, TimeSpan _) => DispChangeResult.Failed, movesARealScreen: false);
|
||||
}
|
||||
|
||||
public DispChangeResult Apply(int width, int height, int hz, string? deviceName, TimeSpan grace)
|
||||
{
|
||||
return _apply(width, height, hz, deviceName, grace);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
|
||||
namespace VibranceHud.Display;
|
||||
|
||||
public readonly record struct MonitorCode(int Width, int Height, int RefreshHz, ScalingMode Scaling)
|
||||
{
|
||||
private const string Prefix = "PXM-";
|
||||
|
||||
private const string Alphabet = "23456789ABCDEFGHJKMNPQRSTUVWXYZ#";
|
||||
|
||||
private const int BodyLength = 11;
|
||||
|
||||
public const int MinDimension = 640;
|
||||
|
||||
public const int MaxWidth = 15360;
|
||||
|
||||
public const int MaxHeight = 8640;
|
||||
|
||||
public const int MinRefresh = 1;
|
||||
|
||||
public const int MaxRefresh = 1000;
|
||||
|
||||
private static int ClampWidth(int v)
|
||||
{
|
||||
return Math.Clamp(v, 640, 15360);
|
||||
}
|
||||
|
||||
private static int ClampHeight(int v)
|
||||
{
|
||||
return Math.Clamp(v, 640, 8640);
|
||||
}
|
||||
|
||||
private static int ClampRefresh(int v)
|
||||
{
|
||||
return Math.Clamp(v, 1, 1000);
|
||||
}
|
||||
|
||||
public string Label()
|
||||
{
|
||||
if (RefreshHz > 0)
|
||||
{
|
||||
return $"{Width} × {Height} @ {RefreshHz} Hz";
|
||||
}
|
||||
return $"{Width} × {Height}";
|
||||
}
|
||||
|
||||
public static string Encode(MonitorCode mode)
|
||||
{
|
||||
StringBuilder stringBuilder = new StringBuilder(11);
|
||||
Append3(stringBuilder, ClampWidth(mode.Width));
|
||||
Append3(stringBuilder, ClampHeight(mode.Height));
|
||||
Append2(stringBuilder, ClampRefresh(mode.RefreshHz));
|
||||
Append2(stringBuilder, ScalingToWire(mode.Scaling));
|
||||
stringBuilder.Append("23456789ABCDEFGHJKMNPQRSTUVWXYZ#"[Checksum(stringBuilder.ToString())]);
|
||||
return "PXM-" + stringBuilder;
|
||||
}
|
||||
|
||||
internal static string EncodeUnclampedForTest(int width, int height, int refresh, int scalingWire)
|
||||
{
|
||||
StringBuilder stringBuilder = new StringBuilder(11);
|
||||
Append3(stringBuilder, width);
|
||||
Append3(stringBuilder, height);
|
||||
Append2(stringBuilder, refresh);
|
||||
Append2(stringBuilder, scalingWire);
|
||||
stringBuilder.Append("23456789ABCDEFGHJKMNPQRSTUVWXYZ#"[Checksum(stringBuilder.ToString())]);
|
||||
return "PXM-" + stringBuilder;
|
||||
}
|
||||
|
||||
internal static string WithWrongPrefixForTest(string code)
|
||||
{
|
||||
return "PXZ-" + code.Substring("PXM-".Length);
|
||||
}
|
||||
|
||||
public static bool TryDecode(string? code, out MonitorCode mode)
|
||||
{
|
||||
mode = default;
|
||||
if (string.IsNullOrWhiteSpace(code))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
string text = ShareCodeText.Normalize(code).Trim().ToUpperInvariant();
|
||||
if (!text.StartsWith("PXM-", StringComparison.Ordinal))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
string text2 = text.Substring("PXM-".Length);
|
||||
if (text2.Length != 11)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
int[] array = new int[text2.Length];
|
||||
for (int i = 0; i < text2.Length; i++)
|
||||
{
|
||||
array[i] = "23456789ABCDEFGHJKMNPQRSTUVWXYZ#".IndexOf(text2[i]);
|
||||
if (array[i] < 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
int num = array[^1];
|
||||
string text3 = text2;
|
||||
if (num != Checksum(text3.Substring(0, text3.Length - 1)))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
int v = array[0] * 1024 + array[1] * 32 + array[2];
|
||||
int v2 = array[3] * 1024 + array[4] * 32 + array[5];
|
||||
int v3 = array[6] * 32 + array[7];
|
||||
int wire = array[8] * 32 + array[9];
|
||||
mode = new MonitorCode(ClampWidth(v), ClampHeight(v2), ClampRefresh(v3), ScalingFromWire(wire));
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void Append3(StringBuilder body, int value)
|
||||
{
|
||||
int num = Math.Clamp(value, 0, 32767);
|
||||
body.Append("23456789ABCDEFGHJKMNPQRSTUVWXYZ#"[num / 1024]);
|
||||
body.Append("23456789ABCDEFGHJKMNPQRSTUVWXYZ#"[num / 32 % 32]);
|
||||
body.Append("23456789ABCDEFGHJKMNPQRSTUVWXYZ#"[num % 32]);
|
||||
}
|
||||
|
||||
private static void Append2(StringBuilder body, int value)
|
||||
{
|
||||
int num = Math.Clamp(value, 0, 1023);
|
||||
body.Append("23456789ABCDEFGHJKMNPQRSTUVWXYZ#"[num / 32]);
|
||||
body.Append("23456789ABCDEFGHJKMNPQRSTUVWXYZ#"[num % 32]);
|
||||
}
|
||||
|
||||
private static int ScalingToWire(ScalingMode mode)
|
||||
{
|
||||
return mode switch
|
||||
{
|
||||
ScalingMode.AspectRatio => 1,
|
||||
ScalingMode.NoScaling => 2,
|
||||
ScalingMode.FullScreen => 3,
|
||||
ScalingMode.Integer => 4,
|
||||
_ => 3,
|
||||
};
|
||||
}
|
||||
|
||||
private static ScalingMode ScalingFromWire(int wire)
|
||||
{
|
||||
return wire switch
|
||||
{
|
||||
1 => ScalingMode.AspectRatio,
|
||||
2 => ScalingMode.NoScaling,
|
||||
3 => ScalingMode.FullScreen,
|
||||
4 => ScalingMode.Integer,
|
||||
_ => ScalingMode.FullScreen,
|
||||
};
|
||||
}
|
||||
|
||||
private static int Checksum(string body)
|
||||
{
|
||||
int num = 0;
|
||||
for (int i = 0; i < body.Length; i++)
|
||||
{
|
||||
num += ("23456789ABCDEFGHJKMNPQRSTUVWXYZ#".IndexOf(body[i]) + 1) * (2 * i + 1);
|
||||
}
|
||||
return num % 32;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
namespace VibranceHud.Display;
|
||||
|
||||
public readonly record struct MonitorPlacement(string DeviceName, int X, int Y);
|
||||
@@ -0,0 +1,21 @@
|
||||
namespace VibranceHud.Display;
|
||||
|
||||
public sealed class NoCustomModeDriver : ICustomModeDriver
|
||||
{
|
||||
public bool Available => false;
|
||||
|
||||
public bool Trial(string? deviceName, int width, int height, int hz)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool Save(string? deviceName)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool Revert(string? deviceName)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using NvAPIWrapper;
|
||||
|
||||
namespace VibranceHud.Display;
|
||||
|
||||
internal static class Nvapi
|
||||
{
|
||||
private static bool? _ready;
|
||||
|
||||
internal static bool Ready()
|
||||
{
|
||||
bool? ready = _ready;
|
||||
if (ready.HasValue)
|
||||
{
|
||||
return ready == true;
|
||||
}
|
||||
try
|
||||
{
|
||||
NVIDIA.Initialize();
|
||||
_ready = true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
_ready = false;
|
||||
}
|
||||
return _ready.Value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,423 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using NvAPIWrapper.Display;
|
||||
using NvAPIWrapper.Native;
|
||||
using NvAPIWrapper.Native.Display;
|
||||
using NvAPIWrapper.Native.Display.Structures;
|
||||
using NvAPIWrapper.Native.Exceptions;
|
||||
using NvAPIWrapper.Native.General;
|
||||
using VibranceHud.Capabilities;
|
||||
|
||||
namespace VibranceHud.Display;
|
||||
|
||||
public sealed class NvidiaCustomModeDriver : ICustomModeDriver
|
||||
{
|
||||
private const uint ColourDepth = 32u;
|
||||
|
||||
internal static readonly TimingOverride[] NativeTimingFormulas = new TimingOverride[3]
|
||||
{
|
||||
TimingOverride.EDID,
|
||||
TimingOverride.Current,
|
||||
TimingOverride.CVTReducedBlanking
|
||||
};
|
||||
|
||||
private readonly Func<string?, IReadOnlyList<DisplayMode>> _supportedModes;
|
||||
|
||||
public bool Available
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!Nvapi.Ready())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
try
|
||||
{
|
||||
return GpuDetection.PrimaryVendor() == GpuVendor.Nvidia && Device(null) != null;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static (uint W, uint H, uint Hz)? OutputFor(int width, int height, int hz, DisplayMode native)
|
||||
{
|
||||
if (native.Width <= 0 || native.Height <= 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if (width <= 0 || height <= 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if (width > native.Width || height > native.Height)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
int num = ((hz > 0) ? hz : native.RefreshHz);
|
||||
if (num <= 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return ((uint)native.Width, (uint)native.Height, (uint)num);
|
||||
}
|
||||
|
||||
internal static bool IsNativeSignal(int visibleWidth, int visibleHeight, DisplayMode native)
|
||||
{
|
||||
if (native.Width > 0 && native.Height > 0 && visibleWidth == native.Width)
|
||||
{
|
||||
return visibleHeight == native.Height;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
internal static bool TimingFitsThisMonitor(int savedPixelClock10K, int savedHTotal, int savedVTotal, int ownPixelClock10K, int ownHTotal, int ownVTotal)
|
||||
{
|
||||
if (savedPixelClock10K <= 0 || savedHTotal <= 0 || savedVTotal <= 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (ownPixelClock10K <= 0 || ownHTotal <= 0 || ownVTotal <= 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (Close(savedPixelClock10K, ownPixelClock10K))
|
||||
{
|
||||
return Close((double)savedPixelClock10K / (double)savedHTotal, (double)ownPixelClock10K / (double)ownHTotal);
|
||||
}
|
||||
return false;
|
||||
static bool Close(double a, double b)
|
||||
{
|
||||
return Math.Abs(a - b) <= 0.05 * b;
|
||||
}
|
||||
}
|
||||
|
||||
internal static DisplayMode? NativeModeOf(IReadOnlyList<DisplayMode> reported)
|
||||
{
|
||||
PanelSize panelSize = CustomModePanel.Native(reported);
|
||||
if (!panelSize.Known)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
int num = 0;
|
||||
foreach (DisplayMode item in reported)
|
||||
{
|
||||
if (item.Width == panelSize.Width && item.Height == panelSize.Height && item.RefreshHz > num)
|
||||
{
|
||||
num = item.RefreshHz;
|
||||
}
|
||||
}
|
||||
return new DisplayMode(panelSize.Width, panelSize.Height, num);
|
||||
}
|
||||
|
||||
public NvidiaCustomModeDriver(Func<string?, IReadOnlyList<DisplayMode>>? supportedModes = null)
|
||||
{
|
||||
_supportedModes = supportedModes ?? ((Func<string, IReadOnlyList<DisplayMode>>)((string? d) => DisplayController.SupportedModes(d)));
|
||||
}
|
||||
|
||||
private DisplayMode? NativeFor(string? deviceName, DisplayMode? given)
|
||||
{
|
||||
if (given.HasValue)
|
||||
{
|
||||
return given.GetValueOrDefault();
|
||||
}
|
||||
try
|
||||
{
|
||||
return NativeModeOf(_supportedModes(deviceName));
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
internal static bool MeansNoPathAtAll(Status status)
|
||||
{
|
||||
return status switch
|
||||
{
|
||||
Status.NvidiaDeviceNotFound => true,
|
||||
Status.NVIDIADisplayNotFound => true,
|
||||
Status.ApiNotInitialized => true,
|
||||
Status.NoImplementation => true,
|
||||
Status.LibraryNotFound => true,
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
|
||||
bool ICustomModeDriver.Trial(string? deviceName, int width, int height, int hz)
|
||||
{
|
||||
return Trial(deviceName, width, height, hz, null);
|
||||
}
|
||||
|
||||
public bool Trial(string? deviceName, int width, int height, int hz, DisplayMode? native)
|
||||
{
|
||||
if (!Nvapi.Ready())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
DisplayDevice displayDevice = Device(deviceName);
|
||||
if ((object)displayDevice == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
DisplayMode? displayMode = NativeFor(deviceName, native);
|
||||
if (displayMode.HasValue)
|
||||
{
|
||||
DisplayMode valueOrDefault = displayMode.GetValueOrDefault();
|
||||
(uint, uint, uint)? tuple = OutputFor(width, height, hz, valueOrDefault);
|
||||
if (tuple.HasValue)
|
||||
{
|
||||
(uint, uint, uint) valueOrDefault2 = tuple.GetValueOrDefault();
|
||||
NvAPIWrapper.Native.Display.Structures.Timing? timing = TimingFor(displayDevice.DisplayId, (int)valueOrDefault2.Item1, (int)valueOrDefault2.Item2, (int)valueOrDefault2.Item3);
|
||||
if (timing.HasValue)
|
||||
{
|
||||
NvAPIWrapper.Native.Display.Structures.Timing valueOrDefault3 = timing.GetValueOrDefault();
|
||||
CustomResolution customResolution = new CustomResolution((uint)width, (uint)height, 32u, valueOrDefault3);
|
||||
try
|
||||
{
|
||||
displayDevice.TrialCustomResolution(customResolution, hardwareModeSetOnly: false);
|
||||
return true;
|
||||
}
|
||||
catch (NVIDIAApiException ex) when (!MeansNoPathAtAll(ex.Status))
|
||||
{
|
||||
NvapiFallbackLog.NoteCustomMode($"trial {width}x{height}@{hz}", ex.Status.ToString());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool Save(string? deviceName)
|
||||
{
|
||||
if (!Nvapi.Ready())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
DisplayDevice displayDevice = Device(deviceName);
|
||||
if ((object)displayDevice == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
try
|
||||
{
|
||||
displayDevice.SaveCustomResolution(isThisOutputIdOnly: false);
|
||||
NvapiFallbackLog.NoteCustomModeStep("save", "ok");
|
||||
return true;
|
||||
}
|
||||
catch (NVIDIAApiException ex) when (!MeansNoPathAtAll(ex.Status))
|
||||
{
|
||||
NvapiFallbackLog.NoteCustomMode("save", ex.Status.ToString());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public bool Revert(string? deviceName)
|
||||
{
|
||||
if (!Nvapi.Ready())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
DisplayDevice displayDevice = Device(deviceName);
|
||||
if ((object)displayDevice == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
try
|
||||
{
|
||||
displayDevice.RevertCustomResolution();
|
||||
return true;
|
||||
}
|
||||
catch (NVIDIAApiException ex) when (!MeansNoPathAtAll(ex.Status))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public IReadOnlyList<DisplayMode> Saved(string? deviceName)
|
||||
{
|
||||
if (!Nvapi.Ready())
|
||||
{
|
||||
return Array.Empty<DisplayMode>();
|
||||
}
|
||||
List<DisplayMode> list = new List<DisplayMode>();
|
||||
try
|
||||
{
|
||||
DisplayDevice displayDevice = Device(deviceName);
|
||||
if ((object)displayDevice == null)
|
||||
{
|
||||
return list;
|
||||
}
|
||||
foreach (CustomResolution customResolution in displayDevice.GetCustomResolutions())
|
||||
{
|
||||
int refreshRate = customResolution.Timing.Extra.RefreshRate;
|
||||
DisplayMode item = new DisplayMode((int)customResolution.Width, (int)customResolution.Height, refreshRate);
|
||||
if (item.Width > 0 && item.Height > 0 && !list.Contains(item))
|
||||
{
|
||||
list.Add(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
public bool IsOnTheNativeSignal(string? deviceName, int width, int height, int hz, DisplayMode? native)
|
||||
{
|
||||
if (!Nvapi.Ready())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
try
|
||||
{
|
||||
DisplayDevice displayDevice = Device(deviceName);
|
||||
if ((object)displayDevice == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
DisplayMode? displayMode = NativeFor(deviceName, native);
|
||||
if (!displayMode.HasValue)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
DisplayMode valueOrDefault = displayMode.GetValueOrDefault();
|
||||
foreach (CustomResolution customResolution in displayDevice.GetCustomResolutions())
|
||||
{
|
||||
if (customResolution.Width != width || customResolution.Height != height)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
int refreshRate = customResolution.Timing.Extra.RefreshRate;
|
||||
if (hz <= 0 || refreshRate <= 0 || refreshRate == hz)
|
||||
{
|
||||
if (!IsNativeSignal(customResolution.Timing.HorizontalVisible, customResolution.Timing.VerticalVisible, valueOrDefault))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return SignalFitsThisMonitor(displayDevice.DisplayId, valueOrDefault, (refreshRate > 0) ? refreshRate : hz, customResolution.Timing.PixelClockIn10KHertz, customResolution.Timing.HorizontalTotal, customResolution.Timing.VerticalTotal);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool SignalFitsThisMonitor(uint displayId, DisplayMode panel, int hz, int savedPixelClock10K, int savedHTotal, int savedVTotal)
|
||||
{
|
||||
if (hz <= 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
NvAPIWrapper.Native.Display.Structures.Timing? timing = TimingFor(displayId, panel.Width, panel.Height, hz);
|
||||
if (timing.HasValue)
|
||||
{
|
||||
NvAPIWrapper.Native.Display.Structures.Timing valueOrDefault = timing.GetValueOrDefault();
|
||||
return TimingFitsThisMonitor(savedPixelClock10K, savedHTotal, savedVTotal, valueOrDefault.PixelClockIn10KHertz, valueOrDefault.HorizontalTotal, valueOrDefault.VerticalTotal);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
internal bool CanComputeTiming(string? deviceName, int width, int height, int hz)
|
||||
{
|
||||
if (!Nvapi.Ready())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
DisplayDevice displayDevice = Device(deviceName);
|
||||
if ((object)displayDevice == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
DisplayMode? displayMode = NativeFor(deviceName, null);
|
||||
if (displayMode.HasValue)
|
||||
{
|
||||
DisplayMode valueOrDefault = displayMode.GetValueOrDefault();
|
||||
(uint, uint, uint)? tuple = OutputFor(width, height, hz, valueOrDefault);
|
||||
if (tuple.HasValue)
|
||||
{
|
||||
(uint, uint, uint) valueOrDefault2 = tuple.GetValueOrDefault();
|
||||
return TimingFor(displayDevice.DisplayId, (int)valueOrDefault2.Item1, (int)valueOrDefault2.Item2, (int)valueOrDefault2.Item3).HasValue;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static NvAPIWrapper.Native.Display.Structures.Timing? TimingFor(uint displayId, int width, int height, int hz)
|
||||
{
|
||||
if (!Nvapi.Ready())
|
||||
{
|
||||
return null;
|
||||
}
|
||||
TimingOverride[] nativeTimingFormulas = NativeTimingFormulas;
|
||||
foreach (TimingOverride timingType in nativeTimingFormulas)
|
||||
{
|
||||
try
|
||||
{
|
||||
NvAPIWrapper.Native.Display.Structures.Timing timing = DisplayApi.GetTiming(displayId, new TimingInput((uint)width, (uint)height, hz, timingType, isInterlaced: false, 0));
|
||||
if (timing.HorizontalVisible == width && timing.VerticalVisible == height)
|
||||
{
|
||||
return timing;
|
||||
}
|
||||
}
|
||||
catch (NVIDIAApiException ex) when (!MeansNoPathAtAll(ex.Status))
|
||||
{
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static int? StoredScaling(string? deviceName)
|
||||
{
|
||||
if (!Nvapi.Ready())
|
||||
{
|
||||
return null;
|
||||
}
|
||||
try
|
||||
{
|
||||
DisplayDevice displayDevice = Device(deviceName);
|
||||
if ((object)displayDevice == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
PathInfo[] displaysConfig = PathInfo.GetDisplaysConfig();
|
||||
for (int i = 0; i < displaysConfig.Length; i++)
|
||||
{
|
||||
PathTargetInfo[] targetsInfo = displaysConfig[i].TargetsInfo;
|
||||
foreach (PathTargetInfo pathTargetInfo in targetsInfo)
|
||||
{
|
||||
if (pathTargetInfo.DisplayDevice.DisplayId == displayDevice.DisplayId)
|
||||
{
|
||||
return (int)pathTargetInfo.Scaling;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static DisplayDevice? Device(string? deviceName)
|
||||
{
|
||||
if (!Nvapi.Ready())
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(deviceName))
|
||||
{
|
||||
return DisplayDevice.GetGDIPrimaryDisplayDevice();
|
||||
}
|
||||
return new DisplayDevice(deviceName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
namespace VibranceHud.Display;
|
||||
|
||||
public readonly record struct PanelSize(int Width, int Height)
|
||||
{
|
||||
public bool Known
|
||||
{
|
||||
get
|
||||
{
|
||||
if (Width > 0)
|
||||
{
|
||||
return Height > 0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return $"{Width} x {Height}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace VibranceHud.Display;
|
||||
|
||||
public enum ScalingMode
|
||||
{
|
||||
AspectRatio,
|
||||
NoScaling,
|
||||
FullScreen,
|
||||
Integer
|
||||
}
|
||||
@@ -0,0 +1,516 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using NvAPIWrapper;
|
||||
using NvAPIWrapper.Display;
|
||||
using NvAPIWrapper.Native.Display;
|
||||
using VibranceHud.Capabilities;
|
||||
using VibranceHud.Controls;
|
||||
|
||||
namespace VibranceHud.Display;
|
||||
|
||||
public static class ScalingModeController
|
||||
{
|
||||
internal sealed record ScalingIo(Func<string?, ScalingMode?> Current, Func<string?, uint?> Raw, Func<ScalingMode, bool, string?, bool> Set, Func<string, TimeSpan, bool> Confirm);
|
||||
|
||||
private struct DISPLAYCONFIG_DEVICE_INFO_HEADER
|
||||
{
|
||||
public uint type;
|
||||
|
||||
public int size;
|
||||
|
||||
public LUID adapterId;
|
||||
|
||||
public uint id;
|
||||
}
|
||||
|
||||
[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 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 const uint QDC_ONLY_ACTIVE_PATHS = 2u;
|
||||
|
||||
private const uint SDC_USE_SUPPLIED_DISPLAY_CONFIG = 32u;
|
||||
|
||||
private const uint SDC_APPLY = 128u;
|
||||
|
||||
private const uint SDC_SAVE_TO_DATABASE = 512u;
|
||||
|
||||
private const uint SDC_ALLOW_CHANGES = 1024u;
|
||||
|
||||
private const uint DISPLAYCONFIG_SCALING_IDENTITY = 1u;
|
||||
|
||||
private const uint DISPLAYCONFIG_SCALING_CENTERED = 2u;
|
||||
|
||||
private const uint DISPLAYCONFIG_SCALING_STRETCHED = 3u;
|
||||
|
||||
private const uint DISPLAYCONFIG_SCALING_ASPECTRATIOCENTEREDMAX = 4u;
|
||||
|
||||
private static bool? _nvidiaReady;
|
||||
|
||||
private const uint DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME = 1u;
|
||||
|
||||
internal static uint ToDisplayConfigScaling(ScalingMode mode)
|
||||
{
|
||||
return mode switch
|
||||
{
|
||||
ScalingMode.AspectRatio => 4u,
|
||||
ScalingMode.NoScaling => 1u,
|
||||
ScalingMode.FullScreen => 3u,
|
||||
_ => 1u,
|
||||
};
|
||||
}
|
||||
|
||||
internal static ScalingMode? FromDisplayConfigScaling(uint value)
|
||||
{
|
||||
return value switch
|
||||
{
|
||||
4u => (ScalingMode?)ScalingMode.AspectRatio,
|
||||
1u => ScalingMode.NoScaling,
|
||||
2u => ScalingMode.NoScaling,
|
||||
3u => ScalingMode.FullScreen,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
internal static int ToNvidiaScaling(ScalingMode mode)
|
||||
{
|
||||
return mode switch
|
||||
{
|
||||
ScalingMode.FullScreen => 2,
|
||||
ScalingMode.AspectRatio => 5,
|
||||
ScalingMode.NoScaling => 3,
|
||||
ScalingMode.Integer => 8,
|
||||
_ => 1,
|
||||
};
|
||||
}
|
||||
|
||||
private static uint ExpectedRawAfterNvidia(ScalingMode mode)
|
||||
{
|
||||
return mode switch
|
||||
{
|
||||
ScalingMode.FullScreen => 3u,
|
||||
ScalingMode.AspectRatio => 4u,
|
||||
ScalingMode.NoScaling => 2u,
|
||||
ScalingMode.Integer => 4u,
|
||||
_ => 1u,
|
||||
};
|
||||
}
|
||||
|
||||
internal static (int Target, int Path) MarshalledSizesForTest()
|
||||
{
|
||||
return (Target: Marshal.SizeOf<DISPLAYCONFIG_PATH_TARGET_INFO>(), Path: Marshal.SizeOf<DISPLAYCONFIG_PATH_INFO>());
|
||||
}
|
||||
|
||||
internal static uint? RawScaling(string? gdiDeviceName = null)
|
||||
{
|
||||
if (!QueryActivePaths(out DISPLAYCONFIG_PATH_INFO[] paths, out DISPLAYCONFIG_MODE_INFO[] _, out uint _, out uint _))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
IReadOnlyList<int> readOnlyList = PickPaths(SourceNamesOf(paths), gdiDeviceName, PrimaryDeviceName);
|
||||
if (readOnlyList.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return paths[readOnlyList[0]].targetInfo.scaling;
|
||||
}
|
||||
|
||||
public static ScalingMode? Current(string? gdiDeviceName = null)
|
||||
{
|
||||
uint? num = RawScaling(gdiDeviceName);
|
||||
if (num.HasValue)
|
||||
{
|
||||
uint valueOrDefault = num.GetValueOrDefault();
|
||||
return FromDisplayConfigScaling(valueOrDefault);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
internal static ScalingMode? FromNvidiaScaling(int value)
|
||||
{
|
||||
return value switch
|
||||
{
|
||||
2 => (ScalingMode?)ScalingMode.FullScreen,
|
||||
5 => ScalingMode.AspectRatio,
|
||||
3 => ScalingMode.NoScaling,
|
||||
8 => ScalingMode.Integer,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
public static ScalingMode? Stored(string? gdiDeviceName = null)
|
||||
{
|
||||
if (GpuDetection.PrimaryVendor() == GpuVendor.Nvidia)
|
||||
{
|
||||
int? num = NvidiaCustomModeDriver.StoredScaling(gdiDeviceName);
|
||||
if (num.HasValue)
|
||||
{
|
||||
int valueOrDefault = num.GetValueOrDefault();
|
||||
return FromNvidiaScaling(valueOrDefault);
|
||||
}
|
||||
}
|
||||
uint? num2 = RawScaling(gdiDeviceName);
|
||||
if (num2.HasValue)
|
||||
{
|
||||
uint valueOrDefault2 = num2.GetValueOrDefault();
|
||||
if (valueOrDefault2 != 1)
|
||||
{
|
||||
return FromDisplayConfigScaling(valueOrDefault2);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
internal static IReadOnlyList<int> PickPaths(IReadOnlyList<string> sourceNames, string? gdiDeviceName, Func<string?> primaryName)
|
||||
{
|
||||
string text = (string.IsNullOrWhiteSpace(gdiDeviceName) ? primaryName() : gdiDeviceName);
|
||||
List<int> list = new List<int>();
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
return list;
|
||||
}
|
||||
for (int i = 0; i < sourceNames.Count; i++)
|
||||
{
|
||||
if (string.Equals(sourceNames[i], text, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
list.Add(i);
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
private static string? PrimaryDeviceName()
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (MonitorDescriptor item in DisplayController.Monitors())
|
||||
{
|
||||
if (item.IsPrimary)
|
||||
{
|
||||
return item.DeviceName;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static bool QueryActivePaths(out DISPLAYCONFIG_PATH_INFO[] paths, out DISPLAYCONFIG_MODE_INFO[] modes, out uint pathCount, out uint modeCount)
|
||||
{
|
||||
paths = Array.Empty<DISPLAYCONFIG_PATH_INFO>();
|
||||
modes = Array.Empty<DISPLAYCONFIG_MODE_INFO>();
|
||||
if (GetDisplayConfigBufferSizes(2u, out pathCount, out modeCount) != 0 || pathCount == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
paths = new DISPLAYCONFIG_PATH_INFO[pathCount];
|
||||
modes = new DISPLAYCONFIG_MODE_INFO[modeCount];
|
||||
return QueryDisplayConfig(2u, ref pathCount, paths, ref modeCount, modes, IntPtr.Zero) == 0;
|
||||
}
|
||||
|
||||
private static string[] SourceNamesOf(DISPLAYCONFIG_PATH_INFO[] paths)
|
||||
{
|
||||
string[] array = new string[paths.Length];
|
||||
for (int i = 0; i < paths.Length; i++)
|
||||
{
|
||||
try
|
||||
{
|
||||
DISPLAYCONFIG_SOURCE_DEVICE_NAME request = new DISPLAYCONFIG_SOURCE_DEVICE_NAME
|
||||
{
|
||||
header = new DISPLAYCONFIG_DEVICE_INFO_HEADER
|
||||
{
|
||||
type = 1u,
|
||||
size = Marshal.SizeOf<DISPLAYCONFIG_SOURCE_DEVICE_NAME>(),
|
||||
adapterId = paths[i].sourceInfo.adapterId,
|
||||
id = paths[i].sourceInfo.id
|
||||
}
|
||||
};
|
||||
array[i] = ((DisplayConfigGetDeviceInfo(ref request) == 0) ? (request.viewGdiDeviceName ?? "").TrimEnd('\0') : "");
|
||||
}
|
||||
catch
|
||||
{
|
||||
array[i] = "";
|
||||
}
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
public static bool TrySet(ScalingMode mode, bool persist = false, string? gdiDeviceName = null)
|
||||
{
|
||||
if (GpuDetection.PrimaryVendor() == GpuVendor.Nvidia && TrySetNvidia(ToNvidiaScaling(mode), persist, gdiDeviceName))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if (mode == ScalingMode.Integer)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (!QueryActivePaths(out DISPLAYCONFIG_PATH_INFO[] paths, out DISPLAYCONFIG_MODE_INFO[] modes, out uint pathCount, out uint modeCount))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
IReadOnlyList<int> readOnlyList = PickPaths(SourceNamesOf(paths), gdiDeviceName, PrimaryDeviceName);
|
||||
if (readOnlyList.Count == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
uint scaling = ToDisplayConfigScaling(mode);
|
||||
foreach (int item in readOnlyList)
|
||||
{
|
||||
DISPLAYCONFIG_PATH_TARGET_INFO targetInfo = paths[item].targetInfo;
|
||||
targetInfo.scaling = scaling;
|
||||
paths[item].targetInfo = targetInfo;
|
||||
}
|
||||
uint num = 1184u;
|
||||
if (persist)
|
||||
{
|
||||
num |= 0x200;
|
||||
}
|
||||
return SetDisplayConfig(pathCount, paths, modeCount, modes, num) == 0;
|
||||
}
|
||||
|
||||
internal static ScalingOutcome Classify(ScalingMode mode, uint? raw)
|
||||
{
|
||||
uint? num = raw;
|
||||
if (num.HasValue)
|
||||
{
|
||||
if (num == 1 && mode != ScalingMode.NoScaling)
|
||||
{
|
||||
return ScalingOutcome.SavedForLater;
|
||||
}
|
||||
if (mode == ScalingMode.Integer)
|
||||
{
|
||||
return ScalingOutcome.Unconfirmed;
|
||||
}
|
||||
if (raw == ExpectedRawAfterNvidia(mode))
|
||||
{
|
||||
return ScalingOutcome.Applied;
|
||||
}
|
||||
if (raw == ToDisplayConfigScaling(mode))
|
||||
{
|
||||
return ScalingOutcome.Applied;
|
||||
}
|
||||
return ScalingOutcome.Failed;
|
||||
}
|
||||
return ScalingOutcome.Unreadable;
|
||||
}
|
||||
|
||||
private static bool Undo(ScalingMode? previous, string? gdiDeviceName, ScalingIo io)
|
||||
{
|
||||
if (previous.HasValue)
|
||||
{
|
||||
ScalingMode valueOrDefault = previous.GetValueOrDefault();
|
||||
return io.Set(valueOrDefault, arg2: false, gdiDeviceName);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static ScalingIo RealIo()
|
||||
{
|
||||
return new ScalingIo((string? d) => Current(d), (string? d) => RawScaling(d), (ScalingMode m, bool persist, string? d) => TrySet(m, persist, d), (string message, TimeSpan grace) =>
|
||||
{
|
||||
bool confirmed = false;
|
||||
using RevertConfirmForm revertConfirmForm = new RevertConfirmForm(message, Math.Max(1, (int)Math.Ceiling(grace.TotalSeconds)));
|
||||
revertConfirmForm.Confirmed += () =>
|
||||
{
|
||||
confirmed = true;
|
||||
};
|
||||
revertConfirmForm.ShowDialog();
|
||||
return confirmed;
|
||||
});
|
||||
}
|
||||
|
||||
public static ScalingOutcome TrySetWithRevert(ScalingMode mode, TimeSpan grace, string? gdiDeviceName = null)
|
||||
{
|
||||
return RunWithRevert(mode, grace, gdiDeviceName, RealIo());
|
||||
}
|
||||
|
||||
internal static ScalingOutcome RunWithRevert(ScalingMode mode, TimeSpan grace, string? gdiDeviceName, ScalingIo io)
|
||||
{
|
||||
ScalingMode? previous = io.Current(gdiDeviceName);
|
||||
if (!io.Set(mode, arg2: false, gdiDeviceName))
|
||||
{
|
||||
return ScalingOutcome.Failed;
|
||||
}
|
||||
ScalingOutcome scalingOutcome = Classify(mode, io.Raw(gdiDeviceName));
|
||||
switch (scalingOutcome)
|
||||
{
|
||||
case ScalingOutcome.Failed:
|
||||
Undo(previous, gdiDeviceName, io);
|
||||
return ScalingOutcome.Failed;
|
||||
case ScalingOutcome.SavedForLater:
|
||||
io.Set(mode, arg2: true, gdiDeviceName);
|
||||
return scalingOutcome;
|
||||
default:
|
||||
if (io.Confirm("Scaling set to " + mode.Label() + ".", grace))
|
||||
{
|
||||
io.Set(mode, arg2: true, gdiDeviceName);
|
||||
return scalingOutcome;
|
||||
}
|
||||
if (!Undo(previous, gdiDeviceName, io))
|
||||
{
|
||||
return ScalingOutcome.RevertFailed;
|
||||
}
|
||||
return ScalingOutcome.Reverted;
|
||||
}
|
||||
}
|
||||
|
||||
internal static bool NvidiaReadyForTest()
|
||||
{
|
||||
return NvidiaReady();
|
||||
}
|
||||
|
||||
private static bool NvidiaReady()
|
||||
{
|
||||
bool? nvidiaReady = _nvidiaReady;
|
||||
if (nvidiaReady.HasValue)
|
||||
{
|
||||
return nvidiaReady == true;
|
||||
}
|
||||
try
|
||||
{
|
||||
Initialise();
|
||||
_nvidiaReady = true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
_nvidiaReady = false;
|
||||
}
|
||||
return _nvidiaReady.Value;
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
static void Initialise()
|
||||
{
|
||||
NVIDIA.Initialize();
|
||||
}
|
||||
}
|
||||
|
||||
internal static bool TrySetNvidia(int nvScaling, bool persist = false, string? gdiDeviceName = null)
|
||||
{
|
||||
if (!NvidiaReady())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
try
|
||||
{
|
||||
return Write(nvScaling, persist, gdiDeviceName);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
static bool Write(int scaling, bool flag2, string? text)
|
||||
{
|
||||
PathInfo[] displaysConfig = PathInfo.GetDisplaysConfig();
|
||||
if (displaysConfig == null || displaysConfig.Length == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
uint num = (string.IsNullOrWhiteSpace(text) ? DisplayDevice.GetGDIPrimaryDisplayDevice().DisplayId : new DisplayDevice(text).DisplayId);
|
||||
bool flag = false;
|
||||
PathInfo[] array = displaysConfig;
|
||||
for (int i = 0; i < array.Length; i++)
|
||||
{
|
||||
PathTargetInfo[] targetsInfo = array[i].TargetsInfo;
|
||||
foreach (PathTargetInfo pathTargetInfo in targetsInfo)
|
||||
{
|
||||
if (pathTargetInfo.DisplayDevice.DisplayId == num)
|
||||
{
|
||||
pathTargetInfo.Scaling = (Scaling)scaling;
|
||||
flag = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!flag)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
PathInfo.SetDisplaysConfig(displaysConfig, flag2 ? DisplayConfigFlags.SaveToPersistence : DisplayConfigFlags.None);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
[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_SOURCE_DEVICE_NAME request);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern int SetDisplayConfig(uint numPathArrayElements, [In] DISPLAYCONFIG_PATH_INFO[] pathArray, uint numModeInfoArrayElements, [In] DISPLAYCONFIG_MODE_INFO[] modeInfoArray, uint flags);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
namespace VibranceHud.Display;
|
||||
|
||||
public static class ScalingModeNames
|
||||
{
|
||||
public static string Label(this ScalingMode mode)
|
||||
{
|
||||
return mode switch
|
||||
{
|
||||
ScalingMode.AspectRatio => "Aspect ratio",
|
||||
ScalingMode.NoScaling => "No scaling",
|
||||
ScalingMode.FullScreen => "Full screen",
|
||||
ScalingMode.Integer => "Integer",
|
||||
_ => mode.ToString(),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace VibranceHud.Display;
|
||||
|
||||
public enum ScalingOutcome
|
||||
{
|
||||
Applied,
|
||||
SavedForLater,
|
||||
Unconfirmed,
|
||||
Unreadable,
|
||||
Reverted,
|
||||
RevertFailed,
|
||||
Failed
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace VibranceHud.Display;
|
||||
|
||||
public sealed class ShapeFit
|
||||
{
|
||||
public enum Outcome
|
||||
{
|
||||
NotNeeded,
|
||||
Applied,
|
||||
Failed
|
||||
}
|
||||
|
||||
public readonly record struct Change(bool Written, ScalingMode Wrote, ScalingMode? Before, Outcome Result = Outcome.Applied);
|
||||
|
||||
private readonly Func<string?, IReadOnlyList<DisplayMode>> _supportedModes;
|
||||
|
||||
private readonly Func<string?, ScalingMode?> _stored;
|
||||
|
||||
private readonly Func<ScalingMode, bool, string?, bool> _set;
|
||||
|
||||
private readonly Dictionary<string, ScalingMode> _before = new Dictionary<string, ScalingMode>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
private readonly object _gate = new object();
|
||||
|
||||
public static ShapeFit Shared { get; } = new ShapeFit((string? d) => DisplayController.SupportedModes(d), (string? d) => ScalingModeController.Stored(d), (ScalingMode mode, bool persist, string? d) => ScalingModeController.TrySet(mode, persist, d));
|
||||
|
||||
public ShapeFit(Func<string?, IReadOnlyList<DisplayMode>> supportedModes, Func<string?, ScalingMode?> stored, Func<ScalingMode, bool, string?, bool> set)
|
||||
{
|
||||
_supportedModes = supportedModes;
|
||||
_stored = stored;
|
||||
_set = set;
|
||||
}
|
||||
|
||||
private static string Key(string? deviceName)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(deviceName))
|
||||
{
|
||||
return deviceName;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
public ScalingMode? ReadBefore(string? deviceName)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _stored(deviceName);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public Change Fill(int width, int height, string? deviceName, ScalingMode? before)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (CustomModeLimits.NeedsStretching(width, height, _supportedModes(deviceName)))
|
||||
{
|
||||
return Write(ScalingMode.FullScreen, deviceName, before);
|
||||
}
|
||||
ScalingMode value;
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_before.TryGetValue(Key(deviceName), out value))
|
||||
{
|
||||
return new Change(Written: false, ScalingMode.FullScreen, before, Outcome.NotNeeded);
|
||||
}
|
||||
}
|
||||
return Write(value, deviceName, before);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return new Change(Written: false, ScalingMode.FullScreen, before, Outcome.Failed);
|
||||
}
|
||||
}
|
||||
|
||||
private Change Write(ScalingMode mode, string? deviceName, ScalingMode? before)
|
||||
{
|
||||
bool flag = _set(mode, arg2: false, deviceName);
|
||||
return new Change(flag, mode, before, (flag && Matches(mode, deviceName)) ? Outcome.Applied : Outcome.Failed);
|
||||
}
|
||||
|
||||
private bool Matches(ScalingMode mode, string? deviceName)
|
||||
{
|
||||
ScalingMode? scalingMode = ReadBefore(deviceName);
|
||||
if (scalingMode.HasValue)
|
||||
{
|
||||
ScalingMode valueOrDefault = scalingMode.GetValueOrDefault();
|
||||
return valueOrDefault == mode;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public Outcome Keep(Change change, string? deviceName)
|
||||
{
|
||||
if (change.Result != Outcome.Applied)
|
||||
{
|
||||
return change.Result;
|
||||
}
|
||||
if (!change.Written)
|
||||
{
|
||||
return Outcome.NotNeeded;
|
||||
}
|
||||
try
|
||||
{
|
||||
if (!_set(change.Wrote, arg2: true, deviceName) || !Matches(change.Wrote, deviceName))
|
||||
{
|
||||
return Outcome.Failed;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
return Outcome.Failed;
|
||||
}
|
||||
if (change.Wrote == ScalingMode.FullScreen)
|
||||
{
|
||||
Remember(change.Before, deviceName);
|
||||
}
|
||||
else
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_before.Remove(Key(deviceName));
|
||||
}
|
||||
}
|
||||
return Outcome.Applied;
|
||||
}
|
||||
|
||||
public Outcome Undo(Change change, string? deviceName)
|
||||
{
|
||||
if (!change.Written)
|
||||
{
|
||||
return Outcome.NotNeeded;
|
||||
}
|
||||
ScalingMode? before = change.Before;
|
||||
if (before.HasValue)
|
||||
{
|
||||
ScalingMode valueOrDefault = before.GetValueOrDefault();
|
||||
try
|
||||
{
|
||||
return (_set(valueOrDefault, arg2: false, deviceName) && Matches(valueOrDefault, deviceName)) ? Outcome.Applied : Outcome.Failed;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return Outcome.Failed;
|
||||
}
|
||||
}
|
||||
return Outcome.Failed;
|
||||
}
|
||||
|
||||
public void Remember(ScalingMode? before, string? deviceName)
|
||||
{
|
||||
if (!before.HasValue)
|
||||
{
|
||||
return;
|
||||
}
|
||||
ScalingMode valueOrDefault = before.GetValueOrDefault();
|
||||
if (valueOrDefault == ScalingMode.FullScreen)
|
||||
{
|
||||
return;
|
||||
}
|
||||
lock (_gate)
|
||||
{
|
||||
_before.TryAdd(Key(deviceName), valueOrDefault);
|
||||
}
|
||||
}
|
||||
|
||||
public void Forget(string? deviceName)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_before.Remove(Key(deviceName));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using System;
|
||||
|
||||
namespace VibranceHud.Display;
|
||||
|
||||
public sealed class SystemClock : IClock
|
||||
{
|
||||
public DateTime UtcNow => DateTime.UtcNow;
|
||||
}
|
||||
Reference in new issue
Block a user