commit 1c7a8cf25fd74a80b6b6a5b5d90fdfa413c7bb6e Author: TinyHerm <90570384+TinyHerm@users.noreply.github.com> Date: Tue Nov 24 23:40:08 2026 +0300 upload diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6d2d645 --- /dev/null +++ b/.gitignore @@ -0,0 +1,20 @@ +# Build outputs +bin/ +obj/ +publish/ + +# Visual Studio / IDE +.vs/ +*.user +*.suo +*.userosscache +*.sln.docstates +.idea/ +.vscode/ + +# Logs and temporary files +*.log +*.tmp +*.bak +Thumbs.db +Desktop.ini diff --git a/A/A.cs b/A/A.cs new file mode 100644 index 0000000..8c395fa --- /dev/null +++ b/A/A.cs @@ -0,0 +1,31 @@ +using VibranceHud; +using VibranceHud.Hotkeys; +using VibranceHud.Licensing; + +namespace A; + +internal static class A +{ + internal static bool Available + { + get + { + try + { + return ServedNightVision.Live; + } + catch + { + return false; + } + } + } + + internal static void ForgetIfUnavailable() + { + if (!Available) + { + HotkeyStatus.Forget(HotkeySlot.NightVision); + } + } +} diff --git a/A/E.cs b/A/E.cs new file mode 100644 index 0000000..06360c0 --- /dev/null +++ b/A/E.cs @@ -0,0 +1,36 @@ +using System; +using VibranceHud; +using VibranceHud.Licensing; + +namespace A; + +internal static class e +{ + private static readonly Lazy FallbackCurve = new Lazy(BuildFallback); + + internal static ServedVibranceCurve Fallback => FallbackCurve.Value; + + internal static ServedVibrancePoint A(int P_0, bool P_1, bool P_2) + { + return Fallback.At(P_0, P_1, P_2); + } + + private static ServedVibranceCurve BuildFallback() + { + float[][] array = new float[351][]; + for (int i = 0; i < array.Length; i++) + { + float num = VibranceEngine.SoftwareVibranceFactor(i, driverAvailable: false); + float num2 = VibranceEngine.SoftwareVibranceFactor(i, driverAvailable: true); + array[i] = new float[5] + { + Math.Min(i, 100), + 1f + (num - 1f) * 0.55f, + num, + 1f + (num2 - 1f) * 0.55f, + num2 + }; + } + return new ServedVibranceCurve(array); + } +} diff --git a/Assets/Brand/logo-horizontal-black.png b/Assets/Brand/logo-horizontal-black.png new file mode 100644 index 0000000..c55cffb Binary files /dev/null and b/Assets/Brand/logo-horizontal-black.png differ diff --git a/Assets/Brand/logo-horizontal-white.png b/Assets/Brand/logo-horizontal-white.png new file mode 100644 index 0000000..6d8180f Binary files /dev/null and b/Assets/Brand/logo-horizontal-white.png differ diff --git a/Assets/Icons/PlexusX.ico b/Assets/Icons/PlexusX.ico new file mode 100644 index 0000000..c02e34a Binary files /dev/null and b/Assets/Icons/PlexusX.ico differ diff --git a/Assets/Icons/app.ico b/Assets/Icons/app.ico new file mode 100644 index 0000000..c02e34a Binary files /dev/null and b/Assets/Icons/app.ico differ diff --git a/Assets/Presets/preset-cs2-balanced.png b/Assets/Presets/preset-cs2-balanced.png new file mode 100644 index 0000000..27347ac Binary files /dev/null and b/Assets/Presets/preset-cs2-balanced.png differ diff --git a/Assets/Presets/preset-cs2-concrete.png b/Assets/Presets/preset-cs2-concrete.png new file mode 100644 index 0000000..e89b7af Binary files /dev/null and b/Assets/Presets/preset-cs2-concrete.png differ diff --git a/Assets/Presets/preset-cs2-dust.png b/Assets/Presets/preset-cs2-dust.png new file mode 100644 index 0000000..0fb28ea Binary files /dev/null and b/Assets/Presets/preset-cs2-dust.png differ diff --git a/Assets/Presets/preset-cs2-shadows.png b/Assets/Presets/preset-cs2-shadows.png new file mode 100644 index 0000000..3d29eb8 Binary files /dev/null and b/Assets/Presets/preset-cs2-shadows.png differ diff --git a/Assets/Presets/preset-cs2-vivid.png b/Assets/Presets/preset-cs2-vivid.png new file mode 100644 index 0000000..a42523d Binary files /dev/null and b/Assets/Presets/preset-cs2-vivid.png differ diff --git a/Assets/Presets/preset-fortnite-balanced.png b/Assets/Presets/preset-fortnite-balanced.png new file mode 100644 index 0000000..e40131f Binary files /dev/null and b/Assets/Presets/preset-fortnite-balanced.png differ diff --git a/Assets/Presets/preset-fortnite-daylight.png b/Assets/Presets/preset-fortnite-daylight.png new file mode 100644 index 0000000..32aa20e Binary files /dev/null and b/Assets/Presets/preset-fortnite-daylight.png differ diff --git a/Assets/Presets/preset-fortnite-night.png b/Assets/Presets/preset-fortnite-night.png new file mode 100644 index 0000000..d7144eb Binary files /dev/null and b/Assets/Presets/preset-fortnite-night.png differ diff --git a/Assets/Presets/preset-fortnite-town.png b/Assets/Presets/preset-fortnite-town.png new file mode 100644 index 0000000..8b8031b Binary files /dev/null and b/Assets/Presets/preset-fortnite-town.png differ diff --git a/Assets/Presets/preset-fortnite-vivid.png b/Assets/Presets/preset-fortnite-vivid.png new file mode 100644 index 0000000..5e9587a Binary files /dev/null and b/Assets/Presets/preset-fortnite-vivid.png differ diff --git a/Assets/Presets/preset-pubg-balanced.png b/Assets/Presets/preset-pubg-balanced.png new file mode 100644 index 0000000..4cd8d5c Binary files /dev/null and b/Assets/Presets/preset-pubg-balanced.png differ diff --git a/Assets/Presets/preset-pubg-desert.png b/Assets/Presets/preset-pubg-desert.png new file mode 100644 index 0000000..6041f23 Binary files /dev/null and b/Assets/Presets/preset-pubg-desert.png differ diff --git a/Assets/Presets/preset-pubg-jungle.png b/Assets/Presets/preset-pubg-jungle.png new file mode 100644 index 0000000..3096bf7 Binary files /dev/null and b/Assets/Presets/preset-pubg-jungle.png differ diff --git a/Assets/Presets/preset-pubg-urban.png b/Assets/Presets/preset-pubg-urban.png new file mode 100644 index 0000000..31cd332 Binary files /dev/null and b/Assets/Presets/preset-pubg-urban.png differ diff --git a/Assets/Presets/preset-pubg-vivid.png b/Assets/Presets/preset-pubg-vivid.png new file mode 100644 index 0000000..f188181 Binary files /dev/null and b/Assets/Presets/preset-pubg-vivid.png differ diff --git a/Assets/Presets/preset-rust-balanced.png b/Assets/Presets/preset-rust-balanced.png new file mode 100644 index 0000000..f406aed Binary files /dev/null and b/Assets/Presets/preset-rust-balanced.png differ diff --git a/Assets/Presets/preset-rust-blackholo.png b/Assets/Presets/preset-rust-blackholo.png new file mode 100644 index 0000000..f406aed Binary files /dev/null and b/Assets/Presets/preset-rust-blackholo.png differ diff --git a/Assets/Presets/preset-rust-desert.png b/Assets/Presets/preset-rust-desert.png new file mode 100644 index 0000000..0dbc12d Binary files /dev/null and b/Assets/Presets/preset-rust-desert.png differ diff --git a/Assets/Presets/preset-rust-forest.png b/Assets/Presets/preset-rust-forest.png new file mode 100644 index 0000000..b6e9725 Binary files /dev/null and b/Assets/Presets/preset-rust-forest.png differ diff --git a/Assets/Presets/preset-rust-snow.png b/Assets/Presets/preset-rust-snow.png new file mode 100644 index 0000000..44bb01a Binary files /dev/null and b/Assets/Presets/preset-rust-snow.png differ diff --git a/Assets/Presets/preset-rust-vivid.png b/Assets/Presets/preset-rust-vivid.png new file mode 100644 index 0000000..8ec73c8 Binary files /dev/null and b/Assets/Presets/preset-rust-vivid.png differ diff --git a/Assets/Presets/preset-siege-balanced.png b/Assets/Presets/preset-siege-balanced.png new file mode 100644 index 0000000..3bb5581 Binary files /dev/null and b/Assets/Presets/preset-siege-balanced.png differ diff --git a/Assets/Presets/preset-siege-corners.png b/Assets/Presets/preset-siege-corners.png new file mode 100644 index 0000000..f19b1c7 Binary files /dev/null and b/Assets/Presets/preset-siege-corners.png differ diff --git a/Assets/Presets/preset-siege-daylight.png b/Assets/Presets/preset-siege-daylight.png new file mode 100644 index 0000000..fe7a312 Binary files /dev/null and b/Assets/Presets/preset-siege-daylight.png differ diff --git a/Assets/Presets/preset-siege-doorways.png b/Assets/Presets/preset-siege-doorways.png new file mode 100644 index 0000000..32fd875 Binary files /dev/null and b/Assets/Presets/preset-siege-doorways.png differ diff --git a/Assets/Presets/preset-siege-vivid.png b/Assets/Presets/preset-siege-vivid.png new file mode 100644 index 0000000..3329813 Binary files /dev/null and b/Assets/Presets/preset-siege-vivid.png differ diff --git a/Assets/Presets/preset-valorant-balanced.png b/Assets/Presets/preset-valorant-balanced.png new file mode 100644 index 0000000..dfc1155 Binary files /dev/null and b/Assets/Presets/preset-valorant-balanced.png differ diff --git a/Assets/Presets/preset-valorant-bright-maps.png b/Assets/Presets/preset-valorant-bright-maps.png new file mode 100644 index 0000000..03972fd Binary files /dev/null and b/Assets/Presets/preset-valorant-bright-maps.png differ diff --git a/Assets/Presets/preset-valorant-outlines.png b/Assets/Presets/preset-valorant-outlines.png new file mode 100644 index 0000000..566c8a4 Binary files /dev/null and b/Assets/Presets/preset-valorant-outlines.png differ diff --git a/Assets/Presets/preset-valorant-shade.png b/Assets/Presets/preset-valorant-shade.png new file mode 100644 index 0000000..e1475a4 Binary files /dev/null and b/Assets/Presets/preset-valorant-shade.png differ diff --git a/Assets/Presets/preset-valorant-vivid.png b/Assets/Presets/preset-valorant-vivid.png new file mode 100644 index 0000000..d50389e Binary files /dev/null and b/Assets/Presets/preset-valorant-vivid.png differ diff --git a/Assets/Shaders/PlexusX.saturation.hlsl b/Assets/Shaders/PlexusX.saturation.hlsl new file mode 100644 index 0000000..d3effaa --- /dev/null +++ b/Assets/Shaders/PlexusX.saturation.hlsl @@ -0,0 +1,31 @@ +Texture2D desktopTex : register(t0); +SamplerState linearSampler : register(s0); + +cbuffer ColorMatrix : register(b0) +{ + float4 row0; + float4 row1; + float4 row2; + float4 row3; + float4 row4; +}; + +struct PSInput +{ + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; +}; + +float4 main(PSInput input) : SV_Target +{ + float4 c = desktopTex.Sample(linearSampler, input.uv); + + // Apply the 5x5 color matrix (row-major, identical to ColorAdjust.Build()). + // The bottom row is identity for alpha and the homogeneous w coordinate. + float4 outColor; + outColor.r = dot(row0, float4(c.rgb, 1.0)); + outColor.g = dot(row1, float4(c.rgb, 1.0)); + outColor.b = dot(row2, float4(c.rgb, 1.0)); + outColor.a = c.a; + return outColor; +} diff --git a/Assets/deobf.jpg b/Assets/deobf.jpg new file mode 100644 index 0000000..fa8dbde Binary files /dev/null and b/Assets/deobf.jpg differ diff --git a/Assets/deobf2.png b/Assets/deobf2.png new file mode 100644 index 0000000..1d4014d Binary files /dev/null and b/Assets/deobf2.png differ diff --git a/Assets/hack.jpg b/Assets/hack.jpg new file mode 100644 index 0000000..c4252ef Binary files /dev/null and b/Assets/hack.jpg differ diff --git a/Assets/jak.jpg b/Assets/jak.jpg new file mode 100644 index 0000000..162bfe5 Binary files /dev/null and b/Assets/jak.jpg differ diff --git a/Assets/ss.png b/Assets/ss.png new file mode 100644 index 0000000..041b33a Binary files /dev/null and b/Assets/ss.png differ diff --git a/PlexusX.csproj b/PlexusX.csproj new file mode 100644 index 0000000..8c5b227 --- /dev/null +++ b/PlexusX.csproj @@ -0,0 +1,55 @@ + + + PlexusX + False + WinExe + True + net8.0-windows10.0.19041.0 + x64 + + + 14.0 + True + False + + + Assets\Icons\app.ico + + + + + + + + + + + + + + + libs\SharpDX.DXGI.dll + + + libs\SharpDX.Direct3D11.dll + + + libs\SharpDX.dll + + + libs\SharpDX.D3DCompiler.dll + + + libs\NvAPIWrapper.dll + + + libs\Microsoft.Windows.SDK.NET.dll + + + libs\System.Management.dll + + + libs\WinRT.Runtime.dll + + + diff --git a/PlexusX.sln b/PlexusX.sln new file mode 100644 index 0000000..35b63a0 --- /dev/null +++ b/PlexusX.sln @@ -0,0 +1,18 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PlexusX", "PlexusX.csproj", "{B4E2A9C1-7F3D-4A1E-9B6C-8D5E2F1A3C4B}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B4E2A9C1-7F3D-4A1E-9B6C-8D5E2F1A3C4B}.Debug|x64.ActiveCfg = Debug|x64 + {B4E2A9C1-7F3D-4A1E-9B6C-8D5E2F1A3C4B}.Debug|x64.Build.0 = Debug|x64 + {B4E2A9C1-7F3D-4A1E-9B6C-8D5E2F1A3C4B}.Release|x64.ActiveCfg = Release|x64 + {B4E2A9C1-7F3D-4A1E-9B6C-8D5E2F1A3C4B}.Release|x64.Build.0 = Release|x64 + EndGlobalSection +EndGlobal diff --git a/Properties/AssemblyInfo.cs b/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..9bd6a06 --- /dev/null +++ b/Properties/AssemblyInfo.cs @@ -0,0 +1,17 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.Versioning; + +[assembly: InternalsVisibleTo("VibranceHud.Tests")] +[assembly: AssemblyCompany("PlexusX")] +[assembly: AssemblyConfiguration("Release")] +[assembly: AssemblyCopyright("Copyright © PlexusX")] +[assembly: AssemblyDescription("Digital vibrance, colour, resolution and monitor control for Windows.")] +[assembly: AssemblyFileVersion("2.1.17.0")] +[assembly: AssemblyInformationalVersion("2.1.17")] +[assembly: AssemblyProduct("PlexusX")] +[assembly: AssemblyTitle("PlexusX")] +[assembly: TargetPlatform("Windows10.0.19041.0")] +[assembly: SupportedOSPlatform("Windows10.0.19041.0")] +[assembly: AssemblyVersion("2.1.17.0")] diff --git a/README.md b/README.md new file mode 100644 index 0000000..d83f7a3 --- /dev/null +++ b/README.md @@ -0,0 +1,49 @@ +

+ Skid Solutions Banner +
+ OpenPlexusX +
+ by Skid Solutions +

+ +--- + +

+ https://discord.gg/MqHfS3je6W +

+ +

+ jak + hack + deobf2 + deobf +

+ +This is NOT a Remake or Recreation. + + +--- + +## How to build + +### Prerequisites +- **OS**: Windows 10 (build 19041+) or Windows 11 (x64) +- **.NET SDK**: .NET 10 SDK or newer (required for C# 14 / `14.0` in `PlexusX.csproj`; targets `net8.0-windows10.0.19041.0`) +- **.NET Desktop Runtime**: .NET 8.0 Desktop Runtime (x64) to run the built executable +- Required third-party libraries (`SharpDX`, `NvAPIWrapper`, `Microsoft.Windows.SDK.NET`, `WinRT.Runtime`, `System.Management`) are already bundled in `libs/` + +--- + +### Building PlexusX + +Run from this folder: + +```powershell +dotnet build PlexusX.sln -c Release -p:Platform=x64 +``` + +Alternatively, open `PlexusX.sln` in Visual Studio and build the `Release | x64` configuration. + +Generated `bin/x64/Release/net8.0-windows10.0.19041.0/`: +- `PlexusX.exe` +- `PlexusX.dll` (alongside the copied dependencies from `libs/`) diff --git a/VibranceHud/AnimationClockPolicy.cs b/VibranceHud/AnimationClockPolicy.cs new file mode 100644 index 0000000..07d6675 --- /dev/null +++ b/VibranceHud/AnimationClockPolicy.cs @@ -0,0 +1,20 @@ +using System; + +namespace VibranceHud; + +public static class AnimationClockPolicy +{ + public static int IntervalFor(TimeSpan sinceLastInput, bool movingPicture) + { + if (!movingPicture && !(sinceLastInput < TimeSpan.FromSeconds(3.0))) + { + return 200; + } + return 47; + } + + public static bool ShouldRun(bool visible, bool minimized, bool movingOrSizing, bool goingAway, bool active) + { + return (visible && !minimized && !movingOrSizing && !goingAway) & active; + } +} diff --git a/VibranceHud/AppFolders.cs b/VibranceHud/AppFolders.cs new file mode 100644 index 0000000..07a027a --- /dev/null +++ b/VibranceHud/AppFolders.cs @@ -0,0 +1,32 @@ +using System; +using System.IO; + +namespace VibranceHud; + +public static class AppFolders +{ + public static string Roaming => For(Environment.SpecialFolder.ApplicationData, RootForTest ?? SecurityCandidate.StorageRoot, FlavourPolicy.Current.DataFolderName); + + public static string Local => For(Environment.SpecialFolder.LocalApplicationData, RootForTest ?? SecurityCandidate.StorageRoot, FlavourPolicy.Current.DataFolderName); + + public static string Pictures => For(Environment.SpecialFolder.MyPictures, RootForTest ?? SecurityCandidate.StorageRoot); + + public static string TaskbarPins => PinnedIn(RootForTest ?? SecurityCandidate.StorageRoot); + + internal static string? RootForTest { get; set; } + + internal static string PinnedIn(string? root) + { + return Path.Combine((root == null) ? Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) : Path.Combine(root, Environment.SpecialFolder.ApplicationData.ToString()), "Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar"); + } + + internal static string For(Environment.SpecialFolder folder, string? root) + { + return For(folder, root, "PlexusX"); + } + + internal static string For(Environment.SpecialFolder folder, string? root, string folderName) + { + return Path.Combine((root == null) ? Environment.GetFolderPath(folder) : Path.Combine(root, folder.ToString()), folderName); + } +} diff --git a/VibranceHud/AppIcon.cs b/VibranceHud/AppIcon.cs new file mode 100644 index 0000000..63375eb --- /dev/null +++ b/VibranceHud/AppIcon.cs @@ -0,0 +1,18 @@ +using System.Drawing; +using System.IO; +using System.Reflection; + +namespace VibranceHud; + +public static class AppIcon +{ + private static Icon? _icon; + + public static Icon Value => _icon ?? (_icon = Load()); + + private static Icon Load() + { + using Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("PlexusX.ico"); + return (stream != null) ? new Icon(stream) : SystemIcons.Application; + } +} diff --git a/VibranceHud/AppInfo.cs b/VibranceHud/AppInfo.cs new file mode 100644 index 0000000..3897048 --- /dev/null +++ b/VibranceHud/AppInfo.cs @@ -0,0 +1,30 @@ +using System; + +namespace VibranceHud; + +public static class AppInfo +{ + public const string ProductName = "PlexusX"; + + public const string Tagline = "Sharper colours. Every game."; + + public const string DiscordUrl = "https://plexusx.lol/discord"; + + public const string SiteUrl = "https://plexusx.lol"; + + public const string PresetUploadUrl = "https://plexusx.lol/dashboard?tab=presets"; + + public const string SupportEmail = "support@plexusx.lol"; + + public static string VersionText => FormatVersion(UpdateService.CurrentVersion); + + internal static string PresetReportUrl(string id) + { + return "https://plexusx.lol/presets?report=" + Uri.EscapeDataString(id); + } + + public static string FormatVersion(Version v) + { + return $"v{v.Major}.{v.Minor}.{Math.Max(v.Build, 0)}"; + } +} diff --git a/VibranceHud/AppSettings.cs b/VibranceHud/AppSettings.cs new file mode 100644 index 0000000..cbd8dcb --- /dev/null +++ b/VibranceHud/AppSettings.cs @@ -0,0 +1,562 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json.Serialization; +using VibranceHud.Capabilities; +using VibranceHud.Crosshair; +using VibranceHud.Customize; +using VibranceHud.DarkBoost; + +namespace VibranceHud; + +public sealed class AppSettings +{ + public sealed class PanelSettings + { + public int Index { get; set; } + + public int Brightness { get; set; } = -1; + + public int Contrast { get; set; } = -1; + + public int LowBlue { get; set; } = -1; + + public int RedGain { get; set; } = -1; + + public int GreenGain { get; set; } = -1; + + public string Key { get; set; } = ""; + + public bool PanelTouched { get; set; } + + public int WroteBrightness { get; set; } = -1; + + public int WroteContrast { get; set; } = -1; + + public int WroteBlueGain { get; set; } = -1; + + public int WroteRedGain { get; set; } = -1; + + public int WroteGreenGain { get; set; } = -1; + + public bool HasOriginals { get; set; } + + public int OriginalBrightness { get; set; } + + public int OriginalContrast { get; set; } + + public int OriginalBlueGain { get; set; } + + public int OriginalRedGain { get; set; } + + public int OriginalGreenGain { get; set; } + } + + internal const uint ZoomDefaultVirtualKey = 6u; + + public int Level { get; set; } = 100; + + public int? VibrancePercent { get; set; } + + public int? SaturationPercent { get; set; } + + public int ResolvedVibrance => VibrancePercent ?? Math.Min(Level, 100); + + public int ResolvedSaturation + { + get + { + int? saturationPercent = SaturationPercent; + if (!saturationPercent.HasValue) + { + if (Level <= 100) + { + return 100; + } + return Level; + } + return saturationPercent.GetValueOrDefault(); + } + } + + public bool VibranceChosenByUser { get; set; } + + public int VibranceOwnershipVersion { get; set; } + + public int? DriverVibranceWeLastWrote { get; set; } + + public bool StartWithWindows { get; set; } + + public bool KeepDesktopComposited { get; set; } + + public bool LowLatencyResetDone { get; set; } + + public bool CompositionKeeperDefaultOnDone { get; set; } + + public bool CompositionKeeperDefaultOffDone { get; set; } + + public int OpacityPercent { get; set; } = 100; + + public bool LightTheme { get; set; } + + public string ThemeName { get; set; } = ""; + + public string BackdropLookName { get; set; } = ""; + + public string AccessEndingWarnedFor { get; set; } = ""; + + public string OfflineNoticeShownFor { get; set; } = ""; + + public string ServerNoticeShownId { get; set; } = ""; + + public string ServerNoticeShownAt { get; set; } = ""; + + public string SignInBrowserPath { get; set; } = ""; + + public string SignInBrowserName { get; set; } = ""; + + public string SurfaceStyleName { get; set; } = ""; + + public string ChromeName { get; set; } = ""; + + public int ColourModeLookVersion { get; set; } + + public int Hue { get; set; } + + public int RedGain { get; set; } = 100; + + public int GreenGain { get; set; } = 100; + + public int BlueGain { get; set; } = 100; + + public string TaskbarStyleName { get; set; } = ""; + + public uint TaskbarColorArgb { get; set; } + + public bool TaskbarFollowsAccent { get; set; } + + public int BrightnessPercent { get; set; } = 100; + + public int GammaPercent { get; set; } = 100; + + public int ContrastPercent { get; set; } = 100; + + public int? Temperature { get; set; } + + public bool EyeCare { get; set; } + + public int ResolvedTemperature + { + get + { + int? temperature = Temperature; + if (!temperature.HasValue) + { + if (!EyeCare) + { + return 0; + } + return 50; + } + return temperature.GetValueOrDefault(); + } + } + + public ColourVisionMode ColourVision { get; set; } + + public bool ColourVisionFromPreset { get; set; } + + public ColourVisionMode UserColourVision { get; set; } + + public List CustomPresets { get; set; } = new List(); + + public OverlayMode OverlayMode { get; set; } + + public DxInitFailureKind DxFailure { get; set; } + + public string DxFailureMessage { get; set; } = ""; + + public int DxFailureCode { get; set; } + + public bool QualityColour { get; set; } + + public string CustomBackgroundFile { get; set; } = ""; + + public int CustomBackgroundDim { get; set; } = 40; + + public int CustomBackgroundBlur { get; set; } + + public int CustomBackgroundMatteArgb { get; set; } + + public int SlateGuiOpacityPercent { get; set; } + + public bool SlateMatteBlur { get; set; } = true; + + public int CustomAccentArgb { get; set; } + + public bool NightVisionOn { get; set; } + + public bool DarkBoostBanRiskAccepted { get; set; } + + public bool NightVisionCodeValidated { get; set; } + + public uint NightVisionHotkeyModifierMask { get; set; } + + public uint NightVisionHotkeyVirtualKey { get; set; } + + public bool NightVisionHotkeyEnabled { get; set; } + + public bool ZoomEnabled { get; set; } + + public float ZoomLevel { get; set; } = 2f; + + public uint ZoomHotkeyModifierMask { get; set; } + + public uint ZoomHotkeyVirtualKey { get; set; } + + public bool ZoomSmooth { get; set; } = true; + + public bool ZoomSmoothEdges { get; set; } + + public bool ZoomKeyDefaulted { get; set; } + + public bool CrosshairEnabled { get; set; } + + public CrosshairConfig ActiveCrosshair { get; set; } = new CrosshairConfig(); + + public List SavedCrosshairs { get; set; } = new List(); + + public List FavouriteCrosshairs { get; set; } = new List(); + + public string PendingUpdateInstaller { get; set; } = ""; + + public string PendingUpdateSha256 { get; set; } = ""; + + public string PendingUpdateSignedManifest { get; set; } = ""; + + public string PendingUpdateVersion { get; set; } = ""; + + public string UpdateRefusedSha256 { get; set; } = ""; + + public string UpdateRefusedAtUtc { get; set; } = ""; + + public string UpdateRefusedNoticedSha256 { get; set; } = ""; + + public string LastSeenVersion { get; set; } = ""; + + public bool OnboardingComplete { get; set; } + + public bool ForcedResignInDone { get; set; } + + public string MovedMachineNoticeShownFor { get; set; } = ""; + + public bool PlansShown { get; set; } + + public string FavoriteGame { get; set; } = ""; + + public string CurrentGameId { get; set; } = ""; + + public string PendingGameOfferId { get; set; } = ""; + + public string PendingDisplayRestore { get; set; } = ""; + + public GameLookSnapshot? LookBeforeGame { get; set; } + + public List DeclinedGameOffers { get; set; } = new List(); + + public List MonitorRules { get; set; } = new List(); + + public int RustResolutionWidth { get; set; } + + public int RustResolutionHeight { get; set; } + + public bool AudioEdgeEnabled { get; set; } + + public int AudioEdgeThresholdPercent { get; set; } = 50; + + public float AudioEdgeRestoreVolume { get; set; } = 1f; + + public bool AudioEdgeRestorePending { get; set; } + + public int NvapiRestoreLevel { get; set; } = -1; + + public Dictionary NvapiRestoreLevels { get; set; } = new Dictionary(); + + public bool NvapiRestorePending { get; set; } + + public bool GammaRestorePending { get; set; } + + public int EyeCareWarmth { get; set; } + + public int EyeCareDim { get; set; } + + public uint HotkeyModifierMask { get; set; } = 3u; + + public uint HotkeyVirtualKey { get; set; } = 86u; + + public bool ScreenshotHotkeyEnabled { get; set; } = true; + + public uint ScreenshotHotkeyModifierMask { get; set; } = 3u; + + public uint ScreenshotHotkeyVirtualKey { get; set; } = 83u; + + public int VibranceScaleVersion { get; set; } + + public bool StreamingMode { get; set; } + + public bool CompetitiveMode { get; set; } + + public bool MainHotkeyEnabled { get; set; } + + public uint MainHotkeyModifierMask { get; set; } = 6u; + + public uint MainHotkeyVirtualKey { get; set; } = 77u; + + public List PresetKeyBindings { get; set; } = new List(); + + public List MonitorColours { get; set; } = new List(); + + public List? SelectedMonitorIds { get; set; } + + public List? UntickedDeviceKeys { get; set; } + + public Dictionary? OwnedMonitorVibrance { get; set; } + + public Dictionary? OwnedMonitorVibranceLastWritten { get; set; } + + public Dictionary? OwnedMonitorGamma { get; set; } + + [JsonIgnore] + public bool ManualOverrideActive { get; set; } + + public int PopupX { get; set; } = int.MinValue; + + public int PopupY { get; set; } = int.MinValue; + + public int WindowX { get; set; } + + public int WindowY { get; set; } + + public int WindowWidth { get; set; } + + public int WindowHeight { get; set; } + + public bool WindowMaximized { get; set; } + + public ToneSettings? Tone { get; set; } + + public float[]? Mix { get; set; } + + [JsonIgnore] + public ChannelMix ResolvedMix => ChannelMix.FromArray(Mix); + + public List Panels { get; set; } = new List(); + + public string ColourPresetGame { get; set; } = ""; + + public string ColourPresetName { get; set; } = ""; + + public bool ShowOnDiscord { get; set; } = true; + + [JsonIgnore] + public ToneSettings ResolvedTone + { + get + { + ToneSettings toneSettings = Tone ?? ToneSettings.Neutral; + return toneSettings with + { + Gamma = GammaPercent + }; + } + } + + public CustomizationSettings Customization { get; set; } = new CustomizationSettings(); + + public SaturationMetric SaturationFormula { get; set; } + + public int Darken { get; set; } + + public int DarkenHue { get; set; } = 120; + + public int HueTurn { get; set; } + + public int HueTurnAmount { get; set; } = 100; + + public int HueComplement { get; set; } + + [JsonIgnore] + public ColourDepth Depth + { + get + { + return new ColourDepth(SaturationFormula, Darken, DarkenHue, HueTurn, HueTurnAmount, HueComplement); + } + set + { + SaturationFormula = value.Formula; + Darken = value.Darken; + DarkenHue = value.DarkenHue; + HueTurn = value.HueTurn; + HueTurnAmount = value.HueTurnAmount; + HueComplement = value.HueComplement; + } + } + + public bool MusicHotkeyEnabled { get; set; } + + public uint MusicHotkeyModifierMask { get; set; } = 3u; + + public uint MusicHotkeyVirtualKey { get; set; } = 80u; + + public bool NightVisionHotkeyHold { get; set; } + + public bool HotkeysOnlyInGames { get; set; } = true; + + public List DarkBoostSetups { get; set; } = new List { VibranceHud.DarkBoost.DarkBoostSetups.Default }; + + public int DarkBoostSelected { get; set; } + + public bool DarkBoostFade { get; set; } = true; + + public uint DarkBoostNextKeyModifierMask { get; set; } + + public uint DarkBoostNextKeyVirtualKey { get; set; } + + public int? MusicMiniX { get; set; } + + public int? MusicMiniY { get; set; } + + public bool MusicPlayPauseHotkeyEnabled { get; set; } + + public uint MusicPlayPauseHotkeyModifierMask { get; set; } + + public uint MusicPlayPauseHotkeyVirtualKey { get; set; } + + public bool MusicNextHotkeyEnabled { get; set; } + + public uint MusicNextHotkeyModifierMask { get; set; } + + public uint MusicNextHotkeyVirtualKey { get; set; } + + public bool MusicPreviousHotkeyEnabled { get; set; } + + public uint MusicPreviousHotkeyModifierMask { get; set; } + + public uint MusicPreviousHotkeyVirtualKey { get; set; } + + public GammaProbeMemory? GammaProbeMemory { get; set; } + + public static void MigrateVibranceOwnership(AppSettings settings) + { + if (settings.VibranceOwnershipVersion < 1) + { + settings.VibranceChosenByUser = settings.VibrancePercent.HasValue || settings.Level != 100; + settings.VibranceOwnershipVersion = 1; + } + } + + internal static bool ApplyZoomKeyDefault(AppSettings settings) + { + if (settings.ZoomKeyDefaulted) + { + return false; + } + if (settings.ZoomHotkeyVirtualKey == 0 && !ADarkBoostKeyIsTheZoomDefault(settings) && !HotkeyConflicts.Owner(settings, HotkeySlot.Zoom, 0u, 6u).HasValue) + { + settings.ZoomHotkeyModifierMask = 0u; + settings.ZoomHotkeyVirtualKey = 6u; + } + settings.ZoomKeyDefaulted = true; + return true; + } + + private static bool ADarkBoostKeyIsTheZoomDefault(AppSettings s) + { + if (s.NightVisionHotkeyVirtualKey != 6 || s.NightVisionHotkeyModifierMask != 0) + { + if (s.DarkBoostNextKeyVirtualKey == 6) + { + return s.DarkBoostNextKeyModifierMask == 0; + } + return false; + } + return true; + } + + internal bool HoldsTheNextSetupKey(uint mask, uint vk) + { + if (DarkBoostNextKeyVirtualKey == vk) + { + return DarkBoostNextKeyModifierMask == mask; + } + return false; + } + + public PanelSettings PanelFor(int index) + { + if (Panels == null) + { + List list = (Panels = new List()); + } + PanelSettings panelSettings = Panels.FirstOrDefault((PanelSettings p) => p.Index == index); + if (panelSettings != null) + { + return panelSettings; + } + panelSettings = new PanelSettings + { + Index = index + }; + Panels.Add(panelSettings); + return panelSettings; + } + + public PanelSettings PanelFor(string key, int index, IReadOnlyCollection? connectedKeys = null) + { + if (Panels == null) + { + List list = (Panels = new List()); + } + PanelSettings panelSettings = Panels.FirstOrDefault((PanelSettings p) => p.Key == key); + if (panelSettings != null) + { + panelSettings.Index = index; + return panelSettings; + } + string desc = Desc(key); + if (desc.Length > 0 && connectedKeys != null && Enumerable.Count(connectedKeys, (string k) => Desc(k) == desc) <= 1) + { + List list3 = Panels.Where((PanelSettings p) => p.Key.Length > 0 && Desc(p.Key) == desc && !connectedKeys.Contains(p.Key)).ToList(); + if (list3.Count == 1) + { + PanelSettings panelSettings2 = list3[0]; + panelSettings2.Key = key; + panelSettings2.Index = index; + return panelSettings2; + } + } + PanelSettings panelSettings3 = Panels.FirstOrDefault((PanelSettings p) => p.Key.Length == 0 && p.Index == index); + if (panelSettings3 != null) + { + panelSettings3.Key = key; + return panelSettings3; + } + PanelSettings panelSettings4 = new PanelSettings + { + Index = index, + Key = key + }; + Panels.Add(panelSettings4); + return panelSettings4; + static string Desc(string k) + { + int num = k.LastIndexOf('|'); + if (num < 0) + { + return k; + } + return k.Substring(num + 1); + } + } +} diff --git a/VibranceHud/AppStatus.cs b/VibranceHud/AppStatus.cs new file mode 100644 index 0000000..f0e958f --- /dev/null +++ b/VibranceHud/AppStatus.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; + +namespace VibranceHud; + +public sealed class AppStatus +{ + public Version? MinimumVersion { get; init; } + + public IReadOnlyList BlockedFlavours { get; init; } = Array.Empty(); + + public string Message { get; init; } = ""; + + public string MessageId { get; init; } = ""; + + public string MessageUrl { get; init; } = ""; +} diff --git a/VibranceHud/AppStatusService.cs b/VibranceHud/AppStatusService.cs new file mode 100644 index 0000000..1bf50fb --- /dev/null +++ b/VibranceHud/AppStatusService.cs @@ -0,0 +1,102 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net.Http; +using System.Threading.Tasks; +using VibranceHud.Licensing; + +namespace VibranceHud; + +public static class AppStatusService +{ + private static string StatusUrl => ActivationEndpoint.StatusUrlFor("store"); + + private static string CacheDir => AppFolders.Local; + + private static string CachePath => Path.Combine(CacheDir, "app-status-cache.json"); + + public static AppStatus? LastFetched { get; private set; } + + private static AppStatus ReadCache() + { + try + { + if (!File.Exists(CachePath)) + { + return new AppStatus(); + } + return VersionGate.Parse(File.ReadAllText(CachePath)); + } + catch + { + return new AppStatus(); + } + } + + public static Version? CachedMinimum() + { + return ReadCache().MinimumVersion; + } + + public static IReadOnlyList CachedBlockedFlavours() + { + return ReadCache().BlockedFlavours; + } + + public static string CachedMessage() + { + return ReadCache().Message; + } + + public static bool ThisBuildIsBlocked() + { + AppStatus appStatus = ReadCache(); + return VersionGate.IsBlocked(UpdateService.CurrentVersion, appStatus.MinimumVersion, "store", appStatus.BlockedFlavours); + } + + public static bool ThisBuildIsBlockedByVersion() + { + return VersionGate.IsBlocked(UpdateService.CurrentVersion, ReadCache().MinimumVersion); + } + + public static async Task RefreshAsync() + { + AppStatus cache = ReadCache(); + Version cached = cache.MinimumVersion; + Version fetched = null; + IReadOnlyList fetchedFlavours = Array.Empty(); + string message = ""; + try + { + using HttpClient client = new HttpClient + { + Timeout = TimeSpan.FromSeconds(10.0) + }; + client.DefaultRequestHeaders.UserAgent.ParseAdd(UpdateService.UpdaterUserAgent); + AppStatus appStatus = VersionGate.Parse(await client.GetStringAsync(StatusUrl)); + fetched = appStatus.MinimumVersion; + fetchedFlavours = appStatus.BlockedFlavours; + message = appStatus.Message; + LastFetched = appStatus; + } + catch + { + } + Version version = VersionGate.Resolve(fetched, cached); + IReadOnlyList readOnlyList = VersionGate.ResolveFlavours(fetchedFlavours, cache.BlockedFlavours); + bool num = version != null && (cached == null || version > cached); + bool flag = readOnlyList.Count > cache.BlockedFlavours.Count; + if (num | flag) + { + try + { + Directory.CreateDirectory(CacheDir); + File.WriteAllText(CachePath, VersionGate.Serialize(version, message, readOnlyList)); + } + catch + { + } + } + return version; + } +} diff --git a/VibranceHud/Audio/AudioEdgeService.cs b/VibranceHud/Audio/AudioEdgeService.cs new file mode 100644 index 0000000..0be2560 --- /dev/null +++ b/VibranceHud/Audio/AudioEdgeService.cs @@ -0,0 +1,220 @@ +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace VibranceHud.Audio; + +public sealed class AudioEdgeService : IDisposable +{ + public enum MeterState + { + Off, + NoReading, + Holding, + Clear + } + + public const int TickMs = 30; + + public const float ExternalChangeTolerance = 0.001f; + + public const int HoldTicks = 20; + + public const float WriteEpsilon = 0.002f; + + private readonly IAudioOutput _output; + + private CancellationTokenSource? _cts; + + private float _restoreVolume = 1f; + + private float _lastWritten = float.NaN; + + private readonly float[] _recentPeaks = new float[20]; + + private int _nextPeak; + + internal int WriteCount { get; private set; } + + public float Threshold { get; set; } = 0.3f; + + public bool IsRunning => _cts != null; + + public float Peak => _output.Peak; + + public float CurrentVolume => _output.Volume; + + public float RestoreVolume => _restoreVolume; + + public MeterState Meter + { + get + { + if (!IsRunning) + { + return MeterState.Off; + } + float currentVolume = CurrentVolume; + float restoreVolume = _restoreVolume; + if (float.IsNaN(currentVolume) || float.IsNaN(restoreVolume)) + { + return MeterState.NoReading; + } + if (!(currentVolume < restoreVolume - 0.01f)) + { + return MeterState.Clear; + } + return MeterState.Holding; + } + } + + public event Action? OnRestorePointCaptured; + + public event Action? OnRestoreCompleted; + + public AudioEdgeService(IAudioOutput output) + { + _output = output; + } + + public void Start() + { + Start(runLoop: true); + } + + internal void StartWithoutLoopForTest() + { + Start(runLoop: false); + } + + private void Start(bool runLoop) + { + if (IsRunning) + { + return; + } + float f = (_restoreVolume = _output.Volume); + _lastWritten = float.NaN; + Array.Clear(_recentPeaks); + _nextPeak = 0; + if (!float.IsNaN(f)) + { + OnRestorePointCaptured?.Invoke(_restoreVolume); + } + _cts = new CancellationTokenSource(); + CancellationToken token = _cts.Token; + if (!runLoop) + { + return; + } + Task.Run(async () => + { + try + { + while (!token.IsCancellationRequested) + { + Tick(); + await Task.Delay(30, token); + } + } + catch (OperationCanceledException) + { + } + catch + { + } + finally + { + if (!float.IsNaN(_restoreVolume)) + { + _output.Volume = _restoreVolume; + } + OnRestoreCompleted?.Invoke(); + } + }, token); + } + + public void ForceRestore(float volume) + { + _output.Volume = Math.Clamp(volume, 0f, 1f); + } + + public void Tick() + { + float volume = _output.Volume; + if (float.IsNaN(volume)) + { + return; + } + if (float.IsNaN(_restoreVolume)) + { + _restoreVolume = volume; + _lastWritten = float.NaN; + OnRestorePointCaptured?.Invoke(_restoreVolume); + } + if (!float.IsNaN(_lastWritten)) + { + float num = volume - _lastWritten; + if (MathF.Abs(num) > 0.001f) + { + _restoreVolume = Math.Clamp(_restoreVolume + num, 0.05f, 1f); + OnRestorePointCaptured?.Invoke(_restoreVolume); + } + } + _recentPeaks[_nextPeak] = _output.Peak; + _nextPeak = (_nextPeak + 1) % _recentPeaks.Length; + float num2 = 0f; + float[] recentPeaks = _recentPeaks; + foreach (float y in recentPeaks) + { + num2 = MathF.Max(num2, y); + } + float num3 = AudioLimiter.NextVolume(num2, Threshold, volume, _restoreVolume); + if (MathF.Abs(num3 - volume) > 0.002f) + { + float volume2 = _output.Volume; + if (!float.IsNaN(volume2)) + { + if (MathF.Abs(volume2 - volume) > 0.001f) + { + _restoreVolume = Math.Clamp(_restoreVolume + (volume2 - volume), 0.05f, 1f); + _lastWritten = volume2; + OnRestorePointCaptured?.Invoke(_restoreVolume); + } + else + { + _output.Volume = num3; + _lastWritten = _output.Volume; + WriteCount++; + } + } + } + else + { + _lastWritten = volume; + } + } + + public void Stop() + { + CancellationTokenSource cts = _cts; + _cts = null; + if (cts != null) + { + cts.Cancel(); + cts.Dispose(); + if (!float.IsNaN(_restoreVolume)) + { + _output.Volume = _restoreVolume; + } + _lastWritten = float.NaN; + OnRestoreCompleted?.Invoke(); + } + } + + public void Dispose() + { + Stop(); + (_output as IDisposable)?.Dispose(); + } +} diff --git a/VibranceHud/Audio/AudioLimiter.cs b/VibranceHud/Audio/AudioLimiter.cs new file mode 100644 index 0000000..7ad5440 --- /dev/null +++ b/VibranceHud/Audio/AudioLimiter.cs @@ -0,0 +1,19 @@ +using System; + +namespace VibranceHud.Audio; + +public static class AudioLimiter +{ + public const float MinVolume = 0.05f; + + public const float DefaultAttack = 0.5f; + + public const float DefaultRelease = 0.3f; + + public static float NextVolume(float peak, float threshold, float currentVolume, float maxVolume, float attack = 0.5f, float release = 0.3f) + { + float num = ((peak > 0.0001f) ? MathF.Min(maxVolume, threshold / peak) : maxVolume); + float num2 = ((num < currentVolume) ? attack : release); + return Math.Clamp(currentVolume + (num - currentVolume) * num2, 0.05f, maxVolume); + } +} diff --git a/VibranceHud/Audio/AudioLoopDiagnostic.cs b/VibranceHud/Audio/AudioLoopDiagnostic.cs new file mode 100644 index 0000000..44dabcd --- /dev/null +++ b/VibranceHud/Audio/AudioLoopDiagnostic.cs @@ -0,0 +1,27 @@ +using System; +using System.Threading; + +namespace VibranceHud.Audio; + +internal static class AudioLoopDiagnostic +{ + public static void RunAndPrint() + { + using WindowsAudioOutput windowsAudioOutput = new WindowsAudioOutput(); + float volume = windowsAudioOutput.Volume; + try + { + float[] array = new float[3] { 1f, 0.5f, 0.25f }; + for (int i = 0; i < array.Length; i++) + { + float value = (windowsAudioOutput.Volume = array[i]); + Thread.Sleep(500); + Console.WriteLine($"Volume {value:P0} -> Peak {windowsAudioOutput.Peak:F3}"); + } + } + finally + { + windowsAudioOutput.Volume = volume; + } + } +} diff --git a/VibranceHud/Audio/IAudioOutput.cs b/VibranceHud/Audio/IAudioOutput.cs new file mode 100644 index 0000000..4427fb7 --- /dev/null +++ b/VibranceHud/Audio/IAudioOutput.cs @@ -0,0 +1,8 @@ +namespace VibranceHud.Audio; + +public interface IAudioOutput +{ + float Peak { get; } + + float Volume { get; set; } +} diff --git a/VibranceHud/Audio/RestorePointSaver.cs b/VibranceHud/Audio/RestorePointSaver.cs new file mode 100644 index 0000000..e52e42a --- /dev/null +++ b/VibranceHud/Audio/RestorePointSaver.cs @@ -0,0 +1,110 @@ +using System; +using System.Threading; + +namespace VibranceHud.Audio; + +internal sealed class RestorePointSaver +{ + private readonly Action _save; + + private readonly int _quietMs; + + private readonly Func _startTimer; + + private readonly object _gate = new object(); + + private IDisposable? _timer; + + private int _generation; + + private bool _dirty; + + public RestorePointSaver(Action save, int quietMs = 400, Func? startTimer = null) + { + _save = save; + _quietMs = quietMs; + _startTimer = startTimer ?? new Func(DefaultTimer); + } + + public void Captured(float volume, AppSettings settings) + { + lock (_gate) + { + settings.AudioEdgeRestoreVolume = volume; + if (!settings.AudioEdgeRestorePending) + { + settings.AudioEdgeRestorePending = true; + CancelTimer(); + _dirty = false; + _save(); + return; + } + _dirty = true; + if (_timer == null) + { + CancelTimer(); + int gen = _generation; + _timer = _startTimer(_quietMs, () => + { + OnDue(gen); + }); + } + } + } + + public void Completed(AppSettings settings) + { + lock (_gate) + { + CancelTimer(); + _dirty = false; + settings.AudioEdgeRestorePending = false; + _save(); + } + } + + public void Flush() + { + lock (_gate) + { + CancelTimer(); + if (_dirty) + { + _dirty = false; + _save(); + } + } + } + + private void OnDue(int generation) + { + lock (_gate) + { + if (generation == _generation) + { + _timer?.Dispose(); + _timer = null; + if (_dirty) + { + _dirty = false; + _save(); + } + } + } + } + + private void CancelTimer() + { + _generation++; + _timer?.Dispose(); + _timer = null; + } + + private static IDisposable DefaultTimer(int delayMs, Action callback) + { + return new Timer((object? _) => + { + callback(); + }, null, delayMs, -1); + } +} diff --git a/VibranceHud/Audio/WindowsAudioOutput.cs b/VibranceHud/Audio/WindowsAudioOutput.cs new file mode 100644 index 0000000..35760be --- /dev/null +++ b/VibranceHud/Audio/WindowsAudioOutput.cs @@ -0,0 +1,149 @@ +using System; +using System.Runtime.InteropServices; + +namespace VibranceHud.Audio; + +public sealed class WindowsAudioOutput : IAudioOutput, IDisposable +{ + [ComImport] + [Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")] + private class MMDeviceEnumerator + { + } + + [ComImport] + [Guid("A95664D2-9614-4F35-A746-DE8DB63617E6")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IMMDeviceEnumerator + { + [PreserveSig] + int EnumAudioEndpoints(int dataFlow, int stateMask, out nint devices); + + [PreserveSig] + int GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice device); + } + + [ComImport] + [Guid("D666063F-1587-4E43-81F1-B948E807363F")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IMMDevice + { + [PreserveSig] + int Activate(ref Guid iid, int clsCtx, nint activationParams, [MarshalAs(UnmanagedType.IUnknown)] out object iface); + } + + [ComImport] + [Guid("C02216F6-8C67-4B5B-9D00-D008E73E0064")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IAudioMeterInformation + { + [PreserveSig] + int GetPeakValue(out float peak); + } + + [ComImport] + [Guid("5CDF2C82-841E-4546-9722-0CF74078229A")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IAudioEndpointVolume + { + [PreserveSig] + int RegisterControlChangeNotify(nint notify); + + [PreserveSig] + int UnregisterControlChangeNotify(nint notify); + + [PreserveSig] + int GetChannelCount(out uint count); + + [PreserveSig] + int SetMasterVolumeLevel(float level, ref Guid eventContext); + + [PreserveSig] + int SetMasterVolumeLevelScalar(float level, ref Guid eventContext); + + [PreserveSig] + int GetMasterVolumeLevel(out float level); + + [PreserveSig] + int GetMasterVolumeLevelScalar(out float level); + } + + private const int ERender = 0; + + private const int EConsole = 0; + + private const int ClsCtxAll = 23; + + private static Guid _meterIid = new Guid("C02216F6-8C67-4B5B-9D00-D008E73E0064"); + + private static Guid _volumeIid = new Guid("5CDF2C82-841E-4546-9722-0CF74078229A"); + + private static Guid _noEvent = Guid.Empty; + + private readonly IAudioMeterInformation _meter; + + private readonly IAudioEndpointVolume _volume; + + public float Peak + { + get + { + try + { + float peak; + return (_meter.GetPeakValue(out peak) == 0) ? peak : 0f; + } + catch + { + return 0f; + } + } + } + + public float Volume + { + get + { + try + { + float level; + return (_volume.GetMasterVolumeLevelScalar(out level) == 0) ? level : float.NaN; + } + catch + { + return float.NaN; + } + } + set + { + try + { + _volume.SetMasterVolumeLevelScalar(Math.Clamp(value, 0f, 1f), ref _noEvent); + } + catch + { + } + } + } + + public WindowsAudioOutput() + { + Marshal.ThrowExceptionForHR(((IMMDeviceEnumerator)new MMDeviceEnumerator()).GetDefaultAudioEndpoint(0, 0, out IMMDevice device)); + Marshal.ThrowExceptionForHR(device.Activate(ref _meterIid, 23, IntPtr.Zero, out object iface)); + Marshal.ThrowExceptionForHR(device.Activate(ref _volumeIid, 23, IntPtr.Zero, out object iface2)); + _meter = (IAudioMeterInformation)iface; + _volume = (IAudioEndpointVolume)iface2; + } + + public void Dispose() + { + if (Marshal.IsComObject(_meter)) + { + Marshal.ReleaseComObject(_meter); + } + if (Marshal.IsComObject(_volume)) + { + Marshal.ReleaseComObject(_volume); + } + } +} diff --git a/VibranceHud/BackgroundUpdateChecker.cs b/VibranceHud/BackgroundUpdateChecker.cs new file mode 100644 index 0000000..bf9c3cc --- /dev/null +++ b/VibranceHud/BackgroundUpdateChecker.cs @@ -0,0 +1,149 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; +using VibranceHud.Updates; + +namespace VibranceHud; + +public sealed class BackgroundUpdateChecker : IDisposable +{ + internal const int CheckIntervalMs = 7200000; + + private readonly AppSettings _settings; + + private readonly SettingsStore _store; + + private readonly NotifyIcon _trayIcon; + + private readonly System.Windows.Forms.Timer _timer; + + private readonly Task? _startupUpdateStep; + + private bool _isRunning; + + private int _ticksBegun; + + private int _manifestChecks; + + internal int TicksBegun => Volatile.Read(in _ticksBegun); + + internal int ManifestChecks => Volatile.Read(in _manifestChecks); + + internal Func SafeNowCheck { get; set; } = SafeToRestart.IsNow; + + internal static bool ShouldTick(FlavourPolicy policy) + { + return policy.SelfUpdates; + } + + public BackgroundUpdateChecker(AppSettings settings, SettingsStore store, NotifyIcon trayIcon, Task? startupUpdateStep = null) + { + _settings = settings; + _store = store; + _trayIcon = trayIcon; + _startupUpdateStep = startupUpdateStep; + _timer = new System.Windows.Forms.Timer + { + Interval = 7200000 + }; + _timer.Tick += async (object? s, EventArgs e) => + { + await TickAsync(); + }; + } + + public void Start() + { + _timer.Start(); + FirstTickAsync(); + } + + internal async Task FirstTickAsync() + { + await Task.Delay(3000); + if (_startupUpdateStep != null) + { + try + { + await _startupUpdateStep; + } + catch + { + } + } + await TickAsync(); + } + + private async Task TickAsync() + { + Interlocked.Increment(ref _ticksBegun); + if (!ShouldTick(FlavourPolicy.Current) || _isRunning) + { + return; + } + _isRunning = true; + try + { + if (!RemoteSwitches.IsOn("updates") || UpdateService.InstallerStartedThisRun) + { + return; + } + if (!string.IsNullOrWhiteSpace(_settings.PendingUpdateVersion)) + { + await InstallIfNobodyIsBusyAsync(); + return; + } + Interlocked.Increment(ref _manifestChecks); + ReleaseInfo release = RefusedUpdate.Unless(release: await UpdateService.TryGetSignedUpdateAsync(), settings: _settings); + if (!(release == null) && SafeNowCheck()) + { + string text = await UpdateService.DownloadAndStageAsync(release); + if (!string.IsNullOrWhiteSpace(text)) + { + UpdateService.RecordPending?.Invoke(release, text); + await InstallIfNobodyIsBusyAsync(); + } + } + } + catch + { + } + finally + { + _isRunning = false; + } + } + + private async Task InstallIfNobodyIsBusyAsync() + { + if (!SafeNowCheck()) + { + return; + } + string refusedBefore = _settings.UpdateRefusedSha256 + "|" + _settings.UpdateRefusedNoticedSha256; + await UpdateService.RunPendingUpdateIfAnyAsync(_settings); + if (!(refusedBefore != _settings.UpdateRefusedSha256 + "|" + _settings.UpdateRefusedNoticedSha256)) + { + return; + } + try + { + _store.Save(_settings); + } + catch + { + } + } + + internal Task TickForTest() + { + return TickAsync(); + } + + public void Dispose() + { + _timer.Stop(); + _timer.Dispose(); + } +} diff --git a/VibranceHud/BrandAssets.cs b/VibranceHud/BrandAssets.cs new file mode 100644 index 0000000..c165484 --- /dev/null +++ b/VibranceHud/BrandAssets.cs @@ -0,0 +1,59 @@ +using System.Collections.Generic; +using System.Drawing; +using System.IO; +using System.Reflection; + +namespace VibranceHud; + +public static class BrandAssets +{ + private static readonly Dictionary _cache = new Dictionary(); + + private static readonly object _gate = new object(); + + public static readonly object DrawGate = new object(); + + public static string LogoResourceName(bool light) + { + if (!light) + { + return "logo-horizontal-white.png"; + } + return "logo-horizontal-black.png"; + } + + public static Image? HorizontalLogo(bool light) + { + return Load(LogoResourceName(light)); + } + + public static Image? PresetChip(string art) + { + return Load("preset-" + art + ".png"); + } + + private static Image? Load(string resourceName) + { + lock (_gate) + { + if (_cache.TryGetValue(resourceName, out Image value)) + { + return value; + } + Image image = null; + using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) + { + if (stream != null) + { + using Image original = Image.FromStream(stream); + image = new Bitmap(original); + } + } + if (image != null) + { + _cache[resourceName] = image; + } + return image; + } + } +} diff --git a/VibranceHud/BuildFlavour.cs b/VibranceHud/BuildFlavour.cs new file mode 100644 index 0000000..9986475 --- /dev/null +++ b/VibranceHud/BuildFlavour.cs @@ -0,0 +1,14 @@ +namespace VibranceHud; + +public static class BuildFlavour +{ + public const string Public = "public"; + + public const string NightVision = "nightvision"; + + public const string NightVisionGift = "nightvision-gift"; + + public const string Store = "store"; + + public const string Current = "store"; +} diff --git a/VibranceHud/Capabilities/CapabilityProbe.cs b/VibranceHud/Capabilities/CapabilityProbe.cs new file mode 100644 index 0000000..9a61e68 --- /dev/null +++ b/VibranceHud/Capabilities/CapabilityProbe.cs @@ -0,0 +1,448 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Security.Principal; +using System.Windows.Forms; + +namespace VibranceHud.Capabilities; + +public static class CapabilityProbe +{ + private sealed class PerDeviceGammaTarget : IPerDeviceGammaProbeTarget + { + public IReadOnlyList Devices() + { + return MultiMonitorGammaRamp.Devices(); + } + + public bool TrySet(string device, ushort[] ramp) + { + return MultiMonitorGammaRamp.SetRampOn(device, ramp); + } + + public ushort[]? TryGet(string device) + { + return MultiMonitorGammaRamp.ReadRampOn(device); + } + } + + private struct POINT + { + public int X; + + public int Y; + } + + private sealed class ScreenGammaTarget : IGammaProbeTarget + { + [DllImport("user32.dll")] + private static extern nint GetDC(nint hWnd); + + [DllImport("user32.dll")] + private static extern int ReleaseDC(nint hWnd, nint hDC); + + [DllImport("gdi32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool SetDeviceGammaRamp(nint hDC, ushort[] ramp); + + [DllImport("gdi32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetDeviceGammaRamp(nint hDC, ushort[] ramp); + + public bool TrySet(ushort[] ramp) + { + nint dC = GetDC(IntPtr.Zero); + if (dC == IntPtr.Zero) + { + return false; + } + try + { + return SetDeviceGammaRamp(dC, ramp); + } + finally + { + ReleaseDC(IntPtr.Zero, dC); + } + } + + public ushort[]? TryGet() + { + nint dC = GetDC(IntPtr.Zero); + if (dC == IntPtr.Zero) + { + return null; + } + try + { + ushort[] array = new ushort[768]; + return GetDeviceGammaRamp(dC, array) ? array : null; + } + finally + { + ReleaseDC(IntPtr.Zero, dC); + } + } + } + + internal const int SameCurveTolerance = 512; + + internal const float TestGamma = 6f; + + private const int MONITOR_DEFAULTTONEAREST = 2; + + internal static GammaSupport Classify(ushort[] written, ushort[]? readback, ushort[] identity) + { + if (readback == null || written.Length == 0 || readback.Length != written.Length) + { + return GammaSupport.Untested; + } + double num = MeanAbsoluteDifference(readback, written); + double num2 = MeanAbsoluteDifference(readback, identity); + if (num <= 512.0) + { + return GammaSupport.Working; + } + if (num2 <= 512.0) + { + return GammaSupport.Refused; + } + return GammaSupport.Clamped; + } + + private static double MeanAbsoluteDifference(ushort[] a, ushort[] b) + { + long num = 0L; + for (int i = 0; i < a.Length; i++) + { + num += Math.Abs(a[i] - b[i]); + } + return (double)num / (double)a.Length; + } + + internal static GammaRefusal WhyRefused(GammaSupport result, bool writeAccepted, bool elevated, bool hdrActive, ushort[]? before, ushort[] identity) + { + if (result != GammaSupport.Refused) + { + return GammaRefusal.None; + } + if (hdrActive) + { + return GammaRefusal.HdrOn; + } + if (!elevated) + { + return GammaRefusal.NotElevated; + } + if (!writeAccepted) + { + return GammaRefusal.WriteFailed; + } + if (before != null && before.Length == identity.Length && MeanAbsoluteDifference(before, identity) > 512.0) + { + return GammaRefusal.RampHeldByOther; + } + return GammaRefusal.ReadbackIdentity; + } + + internal static ushort[] TestRamp() + { + return GammaCurve.Build(6f); + } + + internal static ushort[] GentleRamp() + { + return GammaCurve.Build(1.15f); + } + + private static bool GentleGetsThrough(Func trySet, Func tryGet) + { + ushort[] array = GentleRamp(); + if (trySet(array)) + { + return Classify(array, tryGet(), GammaCurve.Identity()) == GammaSupport.Working; + } + return false; + } + + internal static GammaSupport ProbeGamma(IGammaProbeTarget target) + { + bool couldRead; + return ProbeGamma(target, out couldRead); + } + + internal static GammaSupport ProbeGamma(IGammaProbeTarget target, out bool couldRead) + { + couldRead = false; + if (target == null) + { + return GammaSupport.Untested; + } + ushort[] array = null; + try + { + array = target.TryGet(); + couldRead = array != null; + if (array == null) + { + return GammaSupport.Refused; + } + ushort[] array2 = TestRamp(); + GammaSupport gammaSupport = (target.TrySet(array2) ? Classify(array2, target.TryGet(), GammaCurve.Identity()) : GammaSupport.Refused); + if (gammaSupport == GammaSupport.Refused && GentleGetsThrough(target.TrySet, target.TryGet)) + { + return GammaSupport.Clamped; + } + return gammaSupport; + } + catch + { + return GammaSupport.Untested; + } + finally + { + try + { + if (array != null) + { + target.TrySet(array); + } + } + catch + { + } + } + } + + internal static IReadOnlyList ProbeDevices(IPerDeviceGammaProbeTarget target, bool elevated, bool hdrActive) + { + bool anyReadable; + return ProbeDevices(target, elevated, hdrActive, out anyReadable); + } + + internal static IReadOnlyList ProbeDevices(IPerDeviceGammaProbeTarget target, bool elevated, bool hdrActive, out bool anyReadable) + { + anyReadable = false; + List list = new List(); + if (target == null) + { + return list; + } + IReadOnlyList readOnlyList; + try + { + readOnlyList = target.Devices() ?? Array.Empty(); + } + catch + { + return list; + } + ushort[] identity = GammaCurve.Identity(); + foreach (string device in readOnlyList) + { + ushort[] array = null; + try + { + array = target.TryGet(device); + if (array != null) + { + anyReadable = true; + ushort[] array2 = TestRamp(); + bool flag = target.TrySet(device, array2); + ushort[] readback = (flag ? target.TryGet(device) : null); + GammaSupport gammaSupport = (flag ? Classify(array2, readback, identity) : GammaSupport.Refused); + if (gammaSupport == GammaSupport.Refused && GentleGetsThrough((ushort[] r) => target.TrySet(device, r), () => target.TryGet(device))) + { + gammaSupport = GammaSupport.Clamped; + } + list.Add(new DeviceGamma(device, gammaSupport, WhyRefused(gammaSupport, flag, elevated, hdrActive, array, identity))); + } + else + { + list.Add(new DeviceGamma(device, GammaSupport.Untested, GammaRefusal.None)); + } + } + catch + { + list.Add(new DeviceGamma(device, GammaSupport.Untested, GammaRefusal.None)); + } + finally + { + try + { + if (array != null) + { + target.TrySet(device, array); + } + } + catch + { + } + } + } + return list; + } + + public static MachineCapabilities Run(bool driverVibrance, OverlayMode overlayPath, IGammaProbeTarget? gammaTarget = null, IPerDeviceGammaProbeTarget? perDeviceTarget = null) + { + GammaProbeMemory measured; + return Run(driverVibrance, overlayPath, null, out measured, gammaTarget, perDeviceTarget); + } + + public static MachineCapabilities Run(bool driverVibrance, OverlayMode overlayPath, GammaProbeMemory? remembered, out GammaProbeMemory? measured, IGammaProbeTarget? gammaTarget = null, IPerDeviceGammaProbeTarget? perDeviceTarget = null) + { + measured = null; + bool elevated = SafeElevated(); + bool flag = SafeHdr(); + IPerDeviceGammaProbeTarget perDeviceGammaProbeTarget = perDeviceTarget ?? new PerDeviceGammaTarget(); + perDeviceTarget = perDeviceGammaProbeTarget; + IReadOnlyList devices; + try + { + devices = perDeviceGammaProbeTarget.Devices() ?? Array.Empty(); + } + catch + { + devices = Array.Empty(); + } + string key = GammaProbeMemory.KeyFor(devices, elevated, flag, AppInfo.VersionText); + if (remembered != null && remembered.Reusable(key)) + { + measured = remembered; + return new MachineCapabilities(remembered.Ramp, flag, SafeVendor(), driverVibrance, SafeMonitorCount(), SafeMixedDpi(), elevated, overlayPath, remembered.Why, remembered.Devices); + } + GammaSupport gammaSupport = GammaSupport.Untested; + bool couldRead = false; + try + { + gammaSupport = ProbeGamma(gammaTarget ?? new ScreenGammaTarget(), out couldRead); + } + catch + { + } + IReadOnlyList readOnlyList = Array.Empty(); + bool anyReadable = false; + try + { + readOnlyList = ProbeDevices(perDeviceTarget ?? new PerDeviceGammaTarget(), elevated, flag, out anyReadable); + } + catch + { + } + GammaRefusal gammaRefusal = GammaRefusal.None; + foreach (DeviceGamma item in readOnlyList) + { + if (item.Why != GammaRefusal.None) + { + gammaRefusal = item.Why; + break; + } + } + if (gammaRefusal == GammaRefusal.None) + { + gammaRefusal = WhyRefused(gammaSupport, writeAccepted: true, elevated, flag, null, GammaCurve.Identity()); + } + if (gammaSupport == GammaSupport.Refused && !couldRead && !anyReadable) + { + gammaRefusal = GammaRefusal.ScreenUnreadable; + } + if (gammaSupport != GammaSupport.Refused) + { + measured = new GammaProbeMemory(key, gammaSupport, gammaRefusal, new List(readOnlyList)); + } + return new MachineCapabilities(gammaSupport, flag, SafeVendor(), driverVibrance, SafeMonitorCount(), SafeMixedDpi(), elevated, overlayPath, gammaRefusal, readOnlyList); + } + + private static bool SafeHdr() + { + try + { + return HdrDetection.AnyDisplayInHdr(); + } + catch + { + return false; + } + } + + private static GpuVendor SafeVendor() + { + try + { + return GpuDetection.PrimaryVendor(); + } + catch + { + return GpuVendor.Unknown; + } + } + + private static int SafeMonitorCount() + { + try + { + return Math.Max(1, Screen.AllScreens.Length); + } + catch + { + return 1; + } + } + + private static bool SafeMixedDpi() + { + try + { + Screen[] allScreens = Screen.AllScreens; + if (allScreens.Length < 2) + { + return false; + } + uint num = DpiOf(allScreens[0]); + for (int i = 1; i < allScreens.Length; i++) + { + if (DpiOf(allScreens[i]) != num) + { + return true; + } + } + return false; + } + catch + { + return false; + } + } + + private static uint DpiOf(Screen screen) + { + if (GetDpiForMonitor(MonitorFromPoint(new POINT + { + X = screen.Bounds.Left + 1, + Y = screen.Bounds.Top + 1 + }, 2), 0, out var x, out var _) != 0) + { + return 96u; + } + return x; + } + + private static bool SafeElevated() + { + try + { + using WindowsIdentity ntIdentity = WindowsIdentity.GetCurrent(); + return new WindowsPrincipal(ntIdentity).IsInRole(WindowsBuiltInRole.Administrator); + } + catch + { + return false; + } + } + + [DllImport("user32.dll")] + private static extern nint MonitorFromPoint(POINT pt, int flags); + + [DllImport("shcore.dll")] + private static extern int GetDpiForMonitor(nint monitor, int type, out uint x, out uint y); +} diff --git a/VibranceHud/Capabilities/DeviceGamma.cs b/VibranceHud/Capabilities/DeviceGamma.cs new file mode 100644 index 0000000..d7814c8 --- /dev/null +++ b/VibranceHud/Capabilities/DeviceGamma.cs @@ -0,0 +1,3 @@ +namespace VibranceHud.Capabilities; + +public sealed record DeviceGamma(string Device, GammaSupport Result, GammaRefusal Why); diff --git a/VibranceHud/Capabilities/GammaProbeMemory.cs b/VibranceHud/Capabilities/GammaProbeMemory.cs new file mode 100644 index 0000000..675ae34 --- /dev/null +++ b/VibranceHud/Capabilities/GammaProbeMemory.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace VibranceHud.Capabilities; + +public sealed record GammaProbeMemory(string Key, GammaSupport Ramp, GammaRefusal Why, List Devices) +{ + internal const string Version = "g1"; + + internal static string KeyFor(IEnumerable devices, bool elevated, bool hdr, string appVersion) + { + return "g1|" + appVersion + "|" + (elevated ? "E" : "e") + (hdr ? "H" : "h") + "|" + string.Join(";", devices.OrderBy((string d) => d, StringComparer.OrdinalIgnoreCase)); + } + + internal bool Reusable(string key) + { + bool flag = Key == key; + if (flag) + { + GammaSupport ramp = Ramp; + bool flag2 = (uint)(ramp - 1) <= 1u; + flag = flag2; + } + if (flag) + { + return Why != GammaRefusal.ScreenUnreadable; + } + return false; + } +} diff --git a/VibranceHud/Capabilities/GammaRefusal.cs b/VibranceHud/Capabilities/GammaRefusal.cs new file mode 100644 index 0000000..971d1cd --- /dev/null +++ b/VibranceHud/Capabilities/GammaRefusal.cs @@ -0,0 +1,12 @@ +namespace VibranceHud.Capabilities; + +public enum GammaRefusal +{ + None, + NotElevated, + HdrOn, + RampHeldByOther, + WriteFailed, + ReadbackIdentity, + ScreenUnreadable +} diff --git a/VibranceHud/Capabilities/GammaSupport.cs b/VibranceHud/Capabilities/GammaSupport.cs new file mode 100644 index 0000000..69e44f4 --- /dev/null +++ b/VibranceHud/Capabilities/GammaSupport.cs @@ -0,0 +1,9 @@ +namespace VibranceHud.Capabilities; + +public enum GammaSupport +{ + Untested, + Working, + Clamped, + Refused +} diff --git a/VibranceHud/Capabilities/GpuDetection.cs b/VibranceHud/Capabilities/GpuDetection.cs new file mode 100644 index 0000000..d7d41cf --- /dev/null +++ b/VibranceHud/Capabilities/GpuDetection.cs @@ -0,0 +1,24 @@ +using SharpDX.DXGI; + +namespace VibranceHud.Capabilities; + +internal static class GpuDetection +{ + public static GpuVendor PrimaryVendor() + { + using Factory1 factory = new Factory1(); + using Adapter1 adapter = factory.GetAdapter1(0); + switch (adapter.Description1.VendorId) + { + case 4318: + return GpuVendor.Nvidia; + case 4098: + case 4130: + return GpuVendor.Amd; + case 32902: + return GpuVendor.Intel; + default: + return GpuVendor.Other; + } + } +} diff --git a/VibranceHud/Capabilities/GpuVendor.cs b/VibranceHud/Capabilities/GpuVendor.cs new file mode 100644 index 0000000..cede36e --- /dev/null +++ b/VibranceHud/Capabilities/GpuVendor.cs @@ -0,0 +1,10 @@ +namespace VibranceHud.Capabilities; + +public enum GpuVendor +{ + Unknown, + Nvidia, + Amd, + Intel, + Other +} diff --git a/VibranceHud/Capabilities/HdrDetection.cs b/VibranceHud/Capabilities/HdrDetection.cs new file mode 100644 index 0000000..341691b --- /dev/null +++ b/VibranceHud/Capabilities/HdrDetection.cs @@ -0,0 +1,559 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; +using System.Threading; +using System.Windows.Forms; +using VibranceHud.Controls; + +namespace VibranceHud.Capabilities; + +internal static class HdrDetection +{ + private struct DISPLAYCONFIG_SET_ADVANCED_COLOR_STATE + { + public DISPLAYCONFIG_DEVICE_INFO_HEADER header; + + public uint value; + } + + private struct LUID + { + public uint LowPart; + + public int HighPart; + } + + private struct DISPLAYCONFIG_PATH_SOURCE_INFO + { + public LUID adapterId; + + public uint id; + + public uint modeInfoIdx; + + public uint statusFlags; + } + + private struct DISPLAYCONFIG_RATIONAL + { + public uint Numerator; + + public uint Denominator; + } + + private struct DISPLAYCONFIG_PATH_TARGET_INFO + { + public LUID adapterId; + + public uint id; + + public uint modeInfoIdx; + + public uint outputTechnology; + + public uint rotation; + + public uint scaling; + + public DISPLAYCONFIG_RATIONAL refreshRate; + + public uint scanLineOrdering; + + [MarshalAs(UnmanagedType.Bool)] + public bool targetAvailable; + + public uint statusFlags; + } + + private struct DISPLAYCONFIG_PATH_INFO + { + public DISPLAYCONFIG_PATH_SOURCE_INFO sourceInfo; + + public DISPLAYCONFIG_PATH_TARGET_INFO targetInfo; + + public uint flags; + } + + [StructLayout(LayoutKind.Sequential, Size = 64)] + private struct DISPLAYCONFIG_MODE_INFO + { + } + + private struct DISPLAYCONFIG_DEVICE_INFO_HEADER + { + public int type; + + public int size; + + public LUID adapterId; + + public uint id; + } + + private struct DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO + { + public DISPLAYCONFIG_DEVICE_INFO_HEADER header; + + public uint value; + + public uint colorEncoding; + + public int bitsPerColorChannel; + } + + private struct DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO_2 + { + public DISPLAYCONFIG_DEVICE_INFO_HEADER header; + + public uint value; + + public uint colorEncoding; + + public uint bitsPerColorChannel; + + public uint activeColorMode; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + private struct DISPLAYCONFIG_SOURCE_DEVICE_NAME + { + public DISPLAYCONFIG_DEVICE_INFO_HEADER header; + + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] + public string viewGdiDeviceName; + } + + private const uint ColorModeWcg = 1u; + + private const uint ColorModeHdr = 2u; + + private const uint QDC_ONLY_ACTIVE_PATHS = 2u; + + private const int DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME = 1; + + private const int DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO = 9; + + private const int DISPLAYCONFIG_DEVICE_INFO_SET_ADVANCED_COLOR_STATE = 10; + + private const int DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO_2 = 15; + + private const int DISPLAYCONFIG_DEVICE_INFO_SET_HDR_STATE = 16; + + public static bool AnyDisplayInHdr() + { + return AnyDisplayInHdr(ActivePaths(), AdvancedColourOf); + } + + public static IReadOnlyList Report() + { + try + { + return Report(ActivePaths(), AdvancedColourOf, SourceNameOf); + } + catch + { + return Array.Empty(); + } + } + + internal static bool AnyDisplayInHdr(IReadOnlyList? paths, Func advancedColour) + { + return Displays(paths, advancedColour, (TPath _) => "", includeNames: false).Any((HdrDisplay d) => d.Enabled); + } + + internal static IReadOnlyList Report(IReadOnlyList? paths, Func advancedColour, Func sourceName) + { + return Displays(paths, advancedColour, sourceName, includeNames: true).ToList(); + } + + private static IEnumerable Displays(IReadOnlyList? paths, Func advancedColour, Func sourceName, bool includeNames) + { + if (paths == null) + { + yield break; + } + foreach (TPath path in paths) + { + (uint, int)? tuple = advancedColour(path); + if (tuple.HasValue) + { + (uint, int) valueOrDefault = tuple.GetValueOrDefault(); + string device = (includeNames ? sourceName(path) : ""); + bool supported = (valueOrDefault.Item1 & 1) != 0; + bool enabled = (valueOrDefault.Item1 & 2) != 0 && (valueOrDefault.Item1 & 4) == 0; + int item = valueOrDefault.Item2; + yield return new HdrDisplay(device, supported, enabled, (item > 0 && item < 64) ? valueOrDefault.Item2 : 0); + } + } + } + + internal static (uint Flags, int BitsPerColorChannel) FromAdvancedColorInfo2(uint value, uint activeColorMode, int bitsPerColorChannel) + { + uint num = 0u; + if ((value & 0x10) != 0) + { + num |= 1; + } + switch (activeColorMode) + { + case 2u: + num |= 2; + break; + case 1u: + num |= 6; + break; + } + return (Flags: num, BitsPerColorChannel: bitsPerColorChannel); + } + + internal static IReadOnlyList<(string Device, uint Value, uint Mode)>? RawInfo2ForTest() + { + IReadOnlyList readOnlyList = ActivePaths(); + if (readOnlyList == null) + { + return null; + } + List<(string, uint, uint)> list = new List<(string, uint, uint)>(); + foreach (DISPLAYCONFIG_PATH_INFO item in readOnlyList) + { + (uint, uint, uint)? tuple = ReadInfo2(item); + if (tuple.HasValue) + { + (uint, uint, uint) valueOrDefault = tuple.GetValueOrDefault(); + list.Add((SourceNameOf(item), valueOrDefault.Item1, valueOrDefault.Item2)); + continue; + } + return null; + } + return list; + } + + internal static IReadOnlyList PickPaths(IReadOnlyList sourceNames, string? device) + { + List list = new List(); + if (string.IsNullOrEmpty(device)) + { + return list; + } + for (int i = 0; i < sourceNames.Count; i++) + { + if (string.Equals(sourceNames[i], device, StringComparison.OrdinalIgnoreCase)) + { + list.Add(i); + } + } + return list; + } + + internal static bool AllColouredDisplaysInHdr(IReadOnlyList coloured, IReadOnlyList report) + { + if (coloured.Count == 0) + { + return false; + } + foreach (string device in coloured) + { + if (!report.Any((HdrDisplay d) => d.Enabled && string.Equals(d.Device, device, StringComparison.OrdinalIgnoreCase))) + { + return false; + } + } + return true; + } + + public static bool AllColouredDisplaysInHdr() + { + try + { + return AllColouredDisplaysInHdr(MultiMonitorGammaRamp.Devices(), Report()); + } + catch + { + return false; + } + } + + public static bool? IsHdrOn(string? gdiDeviceName) + { + try + { + string b = ResolveDevice(gdiDeviceName); + foreach (HdrDisplay item in Report()) + { + if (string.Equals(item.Device, b, StringComparison.OrdinalIgnoreCase)) + { + return item.Enabled; + } + } + } + catch + { + } + return null; + } + + private static string? ResolveDevice(string? gdiDeviceName) + { + if (!string.IsNullOrEmpty(gdiDeviceName)) + { + return gdiDeviceName; + } + return Screen.PrimaryScreen?.DeviceName; + } + + internal static HdrSwitchOutcome SwitchWithRevert(bool enabled, string? device, Func isHdrOn, Func set, Func keep) + { + bool? flag = isHdrOn(device); + if (flag.HasValue) + { + bool valueOrDefault = flag == true; + if (valueOrDefault == enabled) + { + return HdrSwitchOutcome.Unchanged; + } + if (!set(enabled, device)) + { + return HdrSwitchOutcome.Failed; + } + if (isHdrOn(device) != enabled) + { + set(valueOrDefault, device); + return HdrSwitchOutcome.Failed; + } + if (keep()) + { + return HdrSwitchOutcome.Kept; + } + if (!set(valueOrDefault, device)) + { + return HdrSwitchOutcome.Failed; + } + return HdrSwitchOutcome.Reverted; + } + return HdrSwitchOutcome.Failed; + } + + internal static HdrSwitchOutcome SwitchWithRevertReal(bool enabled, string? device, TimeSpan grace) + { + string name = ResolveDevice(device) ?? ""; + return SwitchWithRevert(enabled, name, IsHdrOn, TrySetHdr, () => + { + bool confirmed = false; + using RevertConfirmForm revertConfirmForm = new RevertConfirmForm($"HDR is now {(enabled ? "on" : "off")} for {name}.", Math.Max(1, (int)Math.Ceiling(grace.TotalSeconds))); + revertConfirmForm.Confirmed += () => + { + confirmed = true; + }; + revertConfirmForm.ShowDialog(); + return confirmed; + }); + } + + private static IReadOnlyList? ActivePaths() + { + if (GetDisplayConfigBufferSizes(2u, out var pathCount, out var modeCount) != 0) + { + return null; + } + DISPLAYCONFIG_PATH_INFO[] array = new DISPLAYCONFIG_PATH_INFO[pathCount]; + DISPLAYCONFIG_MODE_INFO[] modes = new DISPLAYCONFIG_MODE_INFO[modeCount]; + if (QueryDisplayConfig(2u, ref pathCount, array, ref modeCount, modes, IntPtr.Zero) != 0) + { + return null; + } + return new ArraySegment(array, 0, (int)pathCount); + } + + private static (uint Flags, int BitsPerColorChannel)? AdvancedColourOf(DISPLAYCONFIG_PATH_INFO path) + { + (uint, uint, uint)? tuple = ReadInfo2(path); + if (tuple.HasValue) + { + (uint, uint, uint) valueOrDefault = tuple.GetValueOrDefault(); + return FromAdvancedColorInfo2(valueOrDefault.Item1, valueOrDefault.Item2, (int)valueOrDefault.Item3); + } + DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO info = new DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO + { + header = new DISPLAYCONFIG_DEVICE_INFO_HEADER + { + type = 9, + size = Marshal.SizeOf(), + adapterId = path.targetInfo.adapterId, + id = path.targetInfo.id + } + }; + if (DisplayConfigGetDeviceInfo(ref info) != 0) + { + return null; + } + return (info.value, info.bitsPerColorChannel); + } + + private static (uint Value, uint Mode, uint Bits)? ReadInfo2(DISPLAYCONFIG_PATH_INFO path) + { + DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO_2 info = new DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO_2 + { + header = new DISPLAYCONFIG_DEVICE_INFO_HEADER + { + type = 15, + size = Marshal.SizeOf(), + adapterId = path.targetInfo.adapterId, + id = path.targetInfo.id + } + }; + if (DisplayConfigGetDeviceInfo(ref info) != 0) + { + return null; + } + return (info.value, info.activeColorMode, info.bitsPerColorChannel); + } + + private static string SourceNameOf(DISPLAYCONFIG_PATH_INFO path) + { + try + { + DISPLAYCONFIG_SOURCE_DEVICE_NAME info = new DISPLAYCONFIG_SOURCE_DEVICE_NAME + { + header = new DISPLAYCONFIG_DEVICE_INFO_HEADER + { + type = 1, + size = Marshal.SizeOf(), + adapterId = path.sourceInfo.adapterId, + id = path.sourceInfo.id + } + }; + return (DisplayConfigGetDeviceInfo(ref info) == 0) ? (info.viewGdiDeviceName ?? "").TrimEnd('\0') : ""; + } + catch + { + return ""; + } + } + + public static bool TrySetHdr(bool enabled, string? gdiDeviceName) + { + IReadOnlyList readOnlyList = ActivePaths(); + if (readOnlyList == null) + { + return false; + } + IReadOnlyList readOnlyList2 = PickPaths(readOnlyList.Select(SourceNameOf).ToList(), ResolveDevice(gdiDeviceName)); + if (readOnlyList2.Count == 0) + { + return false; + } + bool result = false; + foreach (int item in readOnlyList2) + { + DISPLAYCONFIG_PATH_INFO path = readOnlyList[item]; + (uint, uint, uint)? tuple = ReadInfo2(path); + if (tuple.HasValue) + { + (uint, uint, uint) valueOrDefault = tuple.GetValueOrDefault(); + if ((valueOrDefault.Item1 & 0x10) == 0) + { + continue; + } + if (valueOrDefault.Item2 == 2 == enabled) + { + result = true; + continue; + } + DISPLAYCONFIG_SET_ADVANCED_COLOR_STATE info = new DISPLAYCONFIG_SET_ADVANCED_COLOR_STATE + { + header = SetHeader(16, path), + value = (enabled ? 1u : 0u) + }; + if (DisplayConfigSetDeviceInfo(ref info) != 0) + { + continue; + } + for (int i = 0; i < 4; i++) + { + tuple = ReadInfo2(path); + if (tuple.HasValue && tuple.GetValueOrDefault().Item2 == 2 == enabled) + { + result = true; + break; + } + Thread.Sleep(150); + } + continue; + } + DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO info2 = new DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO + { + header = new DISPLAYCONFIG_DEVICE_INFO_HEADER + { + type = 9, + size = Marshal.SizeOf(), + adapterId = path.targetInfo.adapterId, + id = path.targetInfo.id + } + }; + if (DisplayConfigGetDeviceInfo(ref info2) != 0 || (info2.value & 1) == 0) + { + continue; + } + if (((info2.value & 2) != 0 && (info2.value & 4) == 0) == enabled) + { + result = true; + continue; + } + DISPLAYCONFIG_SET_ADVANCED_COLOR_STATE info3 = new DISPLAYCONFIG_SET_ADVANCED_COLOR_STATE + { + header = SetHeader(10, path), + value = (enabled ? 1u : 0u) + }; + if (DisplayConfigSetDeviceInfo(ref info3) == 0) + { + result = true; + } + } + return result; + } + + private static DISPLAYCONFIG_DEVICE_INFO_HEADER SetHeader(int type, DISPLAYCONFIG_PATH_INFO path) + { + return new DISPLAYCONFIG_DEVICE_INFO_HEADER + { + type = type, + size = Marshal.SizeOf(), + adapterId = path.targetInfo.adapterId, + id = path.targetInfo.id + }; + } + + [DllImport("user32.dll")] + private static extern int DisplayConfigSetDeviceInfo(ref DISPLAYCONFIG_SET_ADVANCED_COLOR_STATE info); + + [DllImport("user32.dll")] + private static extern int GetDisplayConfigBufferSizes(uint flags, out uint pathCount, out uint modeCount); + + [DllImport("user32.dll")] + private static extern int QueryDisplayConfig(uint flags, ref uint pathCount, [Out] DISPLAYCONFIG_PATH_INFO[] paths, ref uint modeCount, [Out] DISPLAYCONFIG_MODE_INFO[] modes, nint currentTopologyId); + + [DllImport("user32.dll")] + private static extern int DisplayConfigGetDeviceInfo(ref DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO info); + + [DllImport("user32.dll")] + private static extern int DisplayConfigGetDeviceInfo(ref DISPLAYCONFIG_SOURCE_DEVICE_NAME info); + + [DllImport("user32.dll")] + private static extern int DisplayConfigGetDeviceInfo(ref DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO_2 info); + + internal static (int Target, int Path) MarshalledSizesForTest() + { + return (Target: Marshal.SizeOf(), Path: Marshal.SizeOf()); + } + + internal static int SourceNameSizeForTest() + { + return Marshal.SizeOf(); + } + + internal static int AdvancedColorInfo2SizeForTest() + { + return Marshal.SizeOf(); + } +} diff --git a/VibranceHud/Capabilities/HdrDisplay.cs b/VibranceHud/Capabilities/HdrDisplay.cs new file mode 100644 index 0000000..2dc423e --- /dev/null +++ b/VibranceHud/Capabilities/HdrDisplay.cs @@ -0,0 +1,3 @@ +namespace VibranceHud.Capabilities; + +public readonly record struct HdrDisplay(string Device, bool Supported, bool Enabled, int BitsPerChannel); diff --git a/VibranceHud/Capabilities/HdrSwitchOutcome.cs b/VibranceHud/Capabilities/HdrSwitchOutcome.cs new file mode 100644 index 0000000..74f6323 --- /dev/null +++ b/VibranceHud/Capabilities/HdrSwitchOutcome.cs @@ -0,0 +1,9 @@ +namespace VibranceHud.Capabilities; + +public enum HdrSwitchOutcome +{ + Failed, + Unchanged, + Kept, + Reverted +} diff --git a/VibranceHud/Capabilities/HdrWords.cs b/VibranceHud/Capabilities/HdrWords.cs new file mode 100644 index 0000000..38304f2 --- /dev/null +++ b/VibranceHud/Capabilities/HdrWords.cs @@ -0,0 +1,37 @@ +using System.Collections.Generic; +using System.Linq; + +namespace VibranceHud.Capabilities; + +public static class HdrWords +{ + private const string Method = "PlexusX reads Windows' own advanced colour setting for each display"; + + public static string DetectionLine(IReadOnlyList displays, bool coloursLimited = true) + { + if (displays == null || displays.Count == 0) + { + return "PlexusX couldn't read HDR from Windows on this PC."; + } + List list = displays.Where((HdrDisplay d) => d.Enabled).ToList(); + if (list.Count != 0) + { + if (coloursLimited) + { + return $"HDR is on for {Names(list)}, which is why screen-colour changes are limited there. {"PlexusX reads Windows' own advanced colour setting for each display"}."; + } + return $"HDR is on for {Names(list)}. {"PlexusX reads Windows' own advanced colour setting for each display"}."; + } + return $"HDR is off on {Names(displays)}. {"PlexusX reads Windows' own advanced colour setting for each display"}."; + } + + private static string Names(IReadOnlyList displays) + { + List list = displays.Select((HdrDisplay d) => (!string.IsNullOrWhiteSpace(d.Device)) ? d.Device : "an unnamed display").ToList(); + if (list.Count == 1) + { + return list[0]; + } + return string.Join(", ", list.Take(list.Count - 1)) + " and " + list[list.Count - 1]; + } +} diff --git a/VibranceHud/Capabilities/IGammaProbeTarget.cs b/VibranceHud/Capabilities/IGammaProbeTarget.cs new file mode 100644 index 0000000..b55d696 --- /dev/null +++ b/VibranceHud/Capabilities/IGammaProbeTarget.cs @@ -0,0 +1,8 @@ +namespace VibranceHud.Capabilities; + +public interface IGammaProbeTarget +{ + bool TrySet(ushort[] ramp); + + ushort[]? TryGet(); +} diff --git a/VibranceHud/Capabilities/IPerDeviceGammaProbeTarget.cs b/VibranceHud/Capabilities/IPerDeviceGammaProbeTarget.cs new file mode 100644 index 0000000..5e37b43 --- /dev/null +++ b/VibranceHud/Capabilities/IPerDeviceGammaProbeTarget.cs @@ -0,0 +1,12 @@ +using System.Collections.Generic; + +namespace VibranceHud.Capabilities; + +public interface IPerDeviceGammaProbeTarget +{ + IReadOnlyList Devices(); + + bool TrySet(string device, ushort[] ramp); + + ushort[]? TryGet(string device); +} diff --git a/VibranceHud/Capabilities/Machine.cs b/VibranceHud/Capabilities/Machine.cs new file mode 100644 index 0000000..154ab20 --- /dev/null +++ b/VibranceHud/Capabilities/Machine.cs @@ -0,0 +1,38 @@ +namespace VibranceHud.Capabilities; + +public static class Machine +{ + public static MachineCapabilities Current { get; private set; } = MachineCapabilities.Unknown; + + public static void Measure(bool driverVibrance, OverlayMode overlayPath) + { + Current = CapabilityProbe.Run(driverVibrance, overlayPath); + } + + public static bool MeasureOrReuse(bool driverVibrance, OverlayMode overlayPath, AppSettings settings) + { + Current = CapabilityProbe.Run(driverVibrance, overlayPath, settings.GammaProbeMemory, out GammaProbeMemory measured); + if (measured == null || object.Equals(measured, settings.GammaProbeMemory)) + { + return false; + } + settings.GammaProbeMemory = measured; + return true; + } + + public static bool MeasureAndRemember(bool driverVibrance, OverlayMode overlayPath, AppSettings settings) + { + Current = CapabilityProbe.Run(driverVibrance, overlayPath, null, out GammaProbeMemory measured); + if (measured == null || object.Equals(measured, settings.GammaProbeMemory)) + { + return false; + } + settings.GammaProbeMemory = measured; + return true; + } + + internal static void OverrideForTests(MachineCapabilities caps) + { + Current = caps; + } +} diff --git a/VibranceHud/Capabilities/MachineCapabilities.cs b/VibranceHud/Capabilities/MachineCapabilities.cs new file mode 100644 index 0000000..dc3afbe --- /dev/null +++ b/VibranceHud/Capabilities/MachineCapabilities.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; + +namespace VibranceHud.Capabilities; + +public sealed record MachineCapabilities(GammaSupport GammaRamp = GammaSupport.Untested, bool HdrActive = false, GpuVendor Gpu = GpuVendor.Unknown, bool DriverVibrance = false, int MonitorCount = 1, bool MixedDpi = false, bool Elevated = false, OverlayMode OverlayPath = OverlayMode.Mag, GammaRefusal RefusedWhy = GammaRefusal.None, IReadOnlyList? PerDeviceGamma = null) +{ + public static MachineCapabilities Unknown => new MachineCapabilities(); + + public IReadOnlyList Devices => PerDeviceGamma ?? Array.Empty(); + + public bool ToneControlsWork + { + get + { + GammaSupport gammaRamp = GammaRamp; + if ((uint)(gammaRamp - 1) <= 1u) + { + return true; + } + return false; + } + } + + public string ToneLimitation + { + get + { + switch (GammaRamp) + { + case GammaSupport.Refused: + { + if (HdrActive) + { + return "HDR is on, and Windows ignores screen-colour changes while it is. Turn HDR off to use these."; + } + if (RefusedWhy == GammaRefusal.ScreenUnreadable) + { + return "PlexusX couldn't find your screen when it started - maybe the monitor was off. Restart PlexusX with the screen on to use these. Saturation above works either way."; + } + if (!Elevated) + { + return "Windows is blocking screen-colour changes because PlexusX is not running as administrator. Settings has a Fix this button that restarts it properly. Saturation above works either way."; + } + if (Gpu == GpuVendor.Nvidia) + { + return "Your NVIDIA driver is refusing screen-colour changes. Something else is usually holding them - Windows Night light, f.lux, or NVIDIA Freestyle. Close those and reopen PlexusX. Saturation above works either way."; + } + GpuVendor gpu = Gpu; + if ((uint)(gpu - 2) <= 1u) + { + return "Your graphics driver is refusing screen-colour changes. Check for a colour or night-light setting in your GPU control panel, and close anything else that tints the screen. Saturation above works either way."; + } + return "Your graphics driver is refusing screen-colour changes, so these won't do anything. Saturation and vibrance above still work."; + } + case GammaSupport.Clamped: + if (HdrActive) + { + return "HDR is on, so Windows is limiting these. They'll work, but weaker than the numbers suggest."; + } + return "Windows is limiting how far these can go on this PC, so they'll be weaker than the numbers suggest."; + case GammaSupport.Untested: + return ""; + default: + return ""; + } + } + } +} diff --git a/VibranceHud/Capabilities/RemeasurePolicy.cs b/VibranceHud/Capabilities/RemeasurePolicy.cs new file mode 100644 index 0000000..b1ab4d7 --- /dev/null +++ b/VibranceHud/Capabilities/RemeasurePolicy.cs @@ -0,0 +1,19 @@ +namespace VibranceHud.Capabilities; + +internal static class RemeasurePolicy +{ + internal const int MaxTries = 3; + + internal static bool ShouldRemeasure(MachineCapabilities current, int triesSoFar) + { + if (current.GammaRamp != GammaSupport.Refused) + { + return false; + } + if (current.RefusedWhy != GammaRefusal.ScreenUnreadable) + { + return triesSoFar < 1; + } + return triesSoFar < 3; + } +} diff --git a/VibranceHud/Capabilities/Repair.cs b/VibranceHud/Capabilities/Repair.cs new file mode 100644 index 0000000..a72af8a --- /dev/null +++ b/VibranceHud/Capabilities/Repair.cs @@ -0,0 +1,110 @@ +using System; +using System.Diagnostics; + +namespace VibranceHud.Capabilities; + +public static class Repair +{ + public static string RelaunchArguments => "--relaunch"; + + public static RepairKind Plan(MachineCapabilities caps) + { + return Plan(caps, FlavourPolicy.Current); + } + + public static RepairKind Plan(MachineCapabilities caps, FlavourPolicy policy) + { + GammaSupport gammaRamp = caps.GammaRamp; + if ((uint)(gammaRamp - 2) > 1u) + { + return RepairKind.None; + } + if (caps.HdrActive) + { + return RepairKind.OpenHdrSettings; + } + if (caps.RefusedWhy == GammaRefusal.ScreenUnreadable) + { + return RepairKind.None; + } + if (!caps.Elevated) + { + if (!policy.OffersElevation) + { + return RepairKind.None; + } + return RepairKind.RestartAsAdministrator; + } + return RepairKind.None; + } + + public static string ButtonText(RepairKind kind) + { + return kind switch + { + RepairKind.RestartAsAdministrator => "Fix this", + RepairKind.OpenHdrSettings => "Open HDR settings", + _ => "", + }; + } + + public static string Explain(RepairKind kind) + { + return kind switch + { + RepairKind.RestartAsAdministrator => "PlexusX will close and open again as administrator. Windows will ask you to confirm.", + RepairKind.OpenHdrSettings => "Opens the Windows HDR page. Turn HDR off there, then come back.", + _ => "", + }; + } + + public static bool Run(RepairKind kind, Action? beforeRestart = null) + { + return Run(kind, FlavourPolicy.Current, (ProcessStartInfo elevated) => Process.Start(elevated), beforeRestart); + } + + internal static bool Run(RepairKind kind, FlavourPolicy policy, Func start, Action? beforeRestart) + { + try + { + switch (kind) + { + case RepairKind.RestartAsAdministrator: + { + if (!policy.OffersElevation) + { + return false; + } + string processPath = Environment.ProcessPath; + if (string.IsNullOrEmpty(processPath)) + { + return false; + } + ProcessStartInfo arg = new ProcessStartInfo(processPath, RelaunchArguments) + { + UseShellExecute = true, + Verb = "runas" + }; + if (start(arg) == null) + { + return false; + } + beforeRestart?.Invoke(); + return true; + } + case RepairKind.OpenHdrSettings: + Process.Start(new ProcessStartInfo("ms-settings:display") + { + UseShellExecute = true + }); + return true; + default: + return false; + } + } + catch + { + return false; + } + } +} diff --git a/VibranceHud/Capabilities/RepairKind.cs b/VibranceHud/Capabilities/RepairKind.cs new file mode 100644 index 0000000..8454495 --- /dev/null +++ b/VibranceHud/Capabilities/RepairKind.cs @@ -0,0 +1,8 @@ +namespace VibranceHud.Capabilities; + +public enum RepairKind +{ + None, + RestartAsAdministrator, + OpenHdrSettings +} diff --git a/VibranceHud/Capabilities/WindowsRampRule.cs b/VibranceHud/Capabilities/WindowsRampRule.cs new file mode 100644 index 0000000..15c18ca --- /dev/null +++ b/VibranceHud/Capabilities/WindowsRampRule.cs @@ -0,0 +1,60 @@ +using System; +using Microsoft.Win32; + +namespace VibranceHud.Capabilities; + +public static class WindowsRampRule +{ + public const int DefaultRange = 128; + + public const int UnlockedRange = 256; + + public static bool WindowsAcceptsRamp(ushort[] ramp, int range = 128) + { + if (ramp.Length != 768) + { + return false; + } + if (range >= 256) + { + return true; + } + for (int i = 0; i < 3; i++) + { + for (int j = 0; j < 256; j++) + { + if (Math.Abs((ramp[i * 256 + j] >> 8) - j) > range) + { + return false; + } + } + } + return true; + } + + public static int? ReadGammaRange() + { + try + { + using RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ICM"); + return (registryKey?.GetValue("GdiIcmGammaRange") is int value) ? new int?(value) : ((int?)null); + } + catch + { + return null; + } + } + + public static int WorstDeviation(ushort[] ramp) + { + int num = 0; + for (int i = 0; i < 3; i++) + { + for (int j = 0; j < 256; j++) + { + num = Math.Max(num, Math.Abs((ramp[i * 256 + j] >> 8) - j)); + } + } + return num; + } +} diff --git a/VibranceHud/Capture/ColourScreenshot.cs b/VibranceHud/Capture/ColourScreenshot.cs new file mode 100644 index 0000000..4b1ffc7 --- /dev/null +++ b/VibranceHud/Capture/ColourScreenshot.cs @@ -0,0 +1,141 @@ +using System; +using System.Drawing; +using System.Drawing.Imaging; +using System.IO; +using System.Runtime.InteropServices; +using System.Threading; +using System.Windows.Forms; + +namespace VibranceHud.Capture; + +public static class ColourScreenshot +{ + public static string Folder => AppFolders.Pictures; + + public static void ApplyLook(Bitmap bmp, float[]? matrix, ushort[]? ramp) + { + if (bmp == null) + { + throw new ArgumentNullException("bmp"); + } + if (matrix == null && ramp == null) + { + return; + } + byte[] array = null; + if (ramp != null) + { + array = new byte[768]; + for (int i = 0; i < 3; i++) + { + for (int j = 0; j < 256; j++) + { + array[i * 256 + j] = (byte)(ramp[i * 256 + j] >> 8); + } + } + } + Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); + BitmapData bitmapData = bmp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); + try + { + int num = Math.Abs(bitmapData.Stride) * bmp.Height; + byte[] array2 = new byte[num]; + Marshal.Copy(bitmapData.Scan0, array2, 0, num); + for (int k = 0; k < num; k += 4) + { + float num2 = (float)(int)array2[k] / 255f; + float num3 = (float)(int)array2[k + 1] / 255f; + float num4 = (float)(int)array2[k + 2] / 255f; + if (matrix != null) + { + float num5 = num4 * matrix[0] + num3 * matrix[5] + num2 * matrix[10] + matrix[20]; + float num6 = num4 * matrix[1] + num3 * matrix[6] + num2 * matrix[11] + matrix[21]; + float num7 = num4 * matrix[2] + num3 * matrix[7] + num2 * matrix[12] + matrix[22]; + num4 = num5; + num3 = num6; + num2 = num7; + } + byte b = Clamp(num4); + byte b2 = Clamp(num3); + byte b3 = Clamp(num2); + if (array != null) + { + b = array[b]; + b2 = array[256 + b2]; + b3 = array[512 + b3]; + } + array2[k] = b3; + array2[k + 1] = b2; + array2[k + 2] = b; + } + Marshal.Copy(array2, 0, bitmapData.Scan0, num); + } + finally + { + bmp.UnlockBits(bitmapData); + } + } + + private static byte Clamp(float v) + { + if (!(v <= 0f)) + { + if (!(v >= 1f)) + { + return (byte)(v * 255f + 0.5f); + } + return byte.MaxValue; + } + return 0; + } + + public static Bitmap Grab() + { + Rectangle virtualScreen = SystemInformation.VirtualScreen; + Bitmap bitmap = new Bitmap(virtualScreen.Width, virtualScreen.Height, PixelFormat.Format32bppArgb); + using Graphics graphics = Graphics.FromImage(bitmap); + graphics.CopyFromScreen(virtualScreen.Left, virtualScreen.Top, 0, 0, virtualScreen.Size, CopyPixelOperation.SourceCopy); + return bitmap; + } + + public static string FileNameFor(DateTime when) + { + return $"PlexusX-{when:yyyy-MM-dd-HHmmss}.png"; + } + + internal static string UniquePath(string folder, DateTime now) + { + string text = Path.Combine(folder, FileNameFor(now)); + int num = 2; + while (File.Exists(text) && num < 100) + { + text = Path.Combine(folder, Path.GetFileNameWithoutExtension(FileNameFor(now)) + " (" + num + ").png"); + num++; + } + return text; + } + + public static string Take(VibranceEngine engine, DateTime now) + { + if (engine == null) + { + throw new ArgumentNullException("engine"); + } + using Bitmap bitmap = Grab(); + ApplyLook(bitmap, engine.CurrentMatrix(), engine.CurrentRamp()); + Directory.CreateDirectory(Folder); + string text = UniquePath(Folder, now); + bitmap.Save(text, ImageFormat.Png); + try + { + Clipboard.SetImage(bitmap); + } + catch (ExternalException) + { + } + catch (ThreadStateException) + { + } + return text; + } +} diff --git a/VibranceHud/CaptureDiagnostic.cs b/VibranceHud/CaptureDiagnostic.cs new file mode 100644 index 0000000..a099f32 --- /dev/null +++ b/VibranceHud/CaptureDiagnostic.cs @@ -0,0 +1,456 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using SharpDX; +using SharpDX.DXGI; +using SharpDX.Direct3D11; +using VibranceHud.Capabilities; + +namespace VibranceHud; + +public static class CaptureDiagnostic +{ + private const int Pairs = 10; + + private const float TestSaturation = 3f; + + private const double ReachesThreshold = 1.4; + + private const double MissesThreshold = 1.1; + + private const int DxgiErrorUnsupported = -2005270524; + + internal const string DifferentChipWords = "This laptop's screen runs on a different graphics chip, so the test can't look. In OBS, try Display Capture with Capture Method 'Windows 10 (1903 and up)'"; + + internal const string GenericWords = "Windows wouldn't let the test look at your screen"; + + internal const string NoScreenOnAnyChipWords = "The test couldn't find your screen on any graphics chip, so it can't look. In OBS, try Display Capture with Capture Method 'Windows 10 (1903 and up)'"; + + private const int DxgiErrorNotFound = -2005270526; + + public static CaptureProbe Probe(ISaturationOverlay overlay) + { + if (overlay == null) + { + return CaptureProbe.Failed("The colour effect isn't running, so there is nothing to test", "no overlay"); + } + Factory1 factory = null; + Adapter1 adapter = null; + SharpDX.Direct3D11.Device device = null; + Output output = null; + Output1 output2 = null; + try + { + Factory1 f; + factory = (f = new Factory1()); + int index = FirstAdapterWithAnOutput(CountAdapters(f), (int i) => AdapterHasAScreen(f, i)); + adapter = factory.GetAdapter1(index); + device = new SharpDX.Direct3D11.Device(adapter, DeviceCreationFlags.BgraSupport); + output = adapter.GetOutput(0); + output2 = output.QueryInterface(); + double[] array = new double[10]; + for (int num = 0; num < 10; num++) + { + overlay.Clear(); + Thread.Sleep(180); + double num2 = MeanChroma(device, output2); + overlay.Apply(SaturationMatrix.Build(3f)); + Thread.Sleep(180); + double num3 = MeanChroma(device, output2); + array[num] = ((num2 > 0.001) ? (num3 / num2) : 1.0); + } + overlay.Clear(); + Array.Sort(array); + double num4 = (array[4] + array[5]) / 2.0; + if (num4 >= 1.4) + { + return new CaptureProbe(Ran: true, num4, ReachesCapture: true, "the colour effect IS in the desktop-duplication path (Discord screen share sees it)"); + } + if (num4 <= 1.1) + { + return new CaptureProbe(Ran: true, num4, ReachesCapture: false, "not in the desktop-duplication path (Discord screen share won't see it; OBS still will)"); + } + return new CaptureProbe(Ran: true, num4, ReachesCapture: false, "inconclusive - the screen was changing too much while measuring"); + } + catch (Exception ex) + { + return FailedBecause(ex); + } + finally + { + output2?.Dispose(); + output?.Dispose(); + device?.Dispose(); + adapter?.Dispose(); + factory?.Dispose(); + } + } + + public static string BuildReport(AppSettings settings, bool driverVibrance, CaptureProbe probe) + { + CultureInfo invariantCulture = CultureInfo.InvariantCulture; + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.AppendLine("PlexusX capture report"); + stringBuilder.AppendLine("----------------------"); + StringBuilder stringBuilder2 = stringBuilder; + StringBuilder stringBuilder3 = stringBuilder2; + StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(15, 1, stringBuilder2); + handler.AppendLiteral("app : "); + handler.AppendFormatted(AppInfo.VersionText); + stringBuilder3.AppendLine(ref handler); + stringBuilder2 = stringBuilder; + StringBuilder stringBuilder4 = stringBuilder2; + handler = new StringBuilder.AppendInterpolatedStringHandler(18, 2, stringBuilder2); + handler.AppendLiteral("windows : "); + handler.AppendFormatted(Environment.OSVersion.Version); + handler.AppendLiteral(" ("); + handler.AppendFormatted(Environment.Is64BitOperatingSystem ? "64-bit" : "32-bit"); + handler.AppendLiteral(")"); + stringBuilder4.AppendLine(ref handler); + stringBuilder2 = stringBuilder; + StringBuilder stringBuilder5 = stringBuilder2; + handler = new StringBuilder.AppendInterpolatedStringHandler(15, 1, stringBuilder2); + handler.AppendLiteral("gpu : "); + handler.AppendFormatted(DescribeAdapters()); + stringBuilder5.AppendLine(ref handler); + stringBuilder2 = stringBuilder; + StringBuilder stringBuilder6 = stringBuilder2; + handler = new StringBuilder.AppendInterpolatedStringHandler(15, 1, stringBuilder2); + handler.AppendLiteral("driver vibr. : "); + handler.AppendFormatted(driverVibrance ? "available (NVIDIA)" : "not available"); + stringBuilder6.AppendLine(ref handler); + stringBuilder2 = stringBuilder; + StringBuilder stringBuilder7 = stringBuilder2; + handler = new StringBuilder.AppendInterpolatedStringHandler(15, 1, stringBuilder2); + handler.AppendLiteral("display path : "); + handler.AppendFormatted((settings.OverlayMode == OverlayMode.Dx) ? "DX11" : "Magnification"); + stringBuilder7.AppendLine(ref handler); + if (settings.OverlayMode != OverlayMode.Dx) + { + stringBuilder2 = stringBuilder; + StringBuilder stringBuilder8 = stringBuilder2; + handler = new StringBuilder.AppendInterpolatedStringHandler(18, 2, stringBuilder2); + handler.AppendLiteral("dx11 failed : "); + handler.AppendFormatted(settings.DxFailure); + handler.AppendLiteral(" - "); + handler.AppendFormatted(settings.DxFailureMessage); + stringBuilder8.AppendLine(ref handler); + if (settings.DxFailureCode != 0) + { + stringBuilder2 = stringBuilder; + StringBuilder stringBuilder9 = stringBuilder2; + handler = new StringBuilder.AppendInterpolatedStringHandler(17, 1, stringBuilder2); + handler.AppendLiteral("dx11 code : 0x"); + handler.AppendFormatted(settings.DxFailureCode, "X8"); + stringBuilder9.AppendLine(ref handler); + } + } + stringBuilder2 = stringBuilder; + StringBuilder stringBuilder10 = stringBuilder2; + handler = new StringBuilder.AppendInterpolatedStringHandler(15, 1, stringBuilder2); + handler.AppendLiteral("composited : "); + handler.AppendFormatted(settings.KeepDesktopComposited ? "forced on" : "off"); + stringBuilder10.AppendLine(ref handler); + stringBuilder2 = stringBuilder; + StringBuilder stringBuilder11 = stringBuilder2; + handler = new StringBuilder.AppendInterpolatedStringHandler(15, 1, stringBuilder2); + handler.AppendLiteral("streaming : "); + handler.AppendFormatted(settings.StreamingMode ? "on" : "off"); + stringBuilder11.AppendLine(ref handler); + stringBuilder2 = stringBuilder; + StringBuilder stringBuilder12 = stringBuilder2; + handler = new StringBuilder.AppendInterpolatedStringHandler(18, 2, stringBuilder2); + handler.AppendLiteral("vibrance/sat : "); + handler.AppendFormatted(settings.VibrancePercent); + handler.AppendLiteral(" / "); + handler.AppendFormatted(settings.SaturationPercent); + stringBuilder12.AppendLine(ref handler); + MachineCapabilities current = Machine.Current; + stringBuilder2 = stringBuilder; + StringBuilder stringBuilder13 = stringBuilder2; + handler = new StringBuilder.AppendInterpolatedStringHandler(15, 1, stringBuilder2); + handler.AppendLiteral("gamma ramp : "); + handler.AppendFormatted(current.GammaRamp); + stringBuilder13.AppendLine(ref handler); + stringBuilder2 = stringBuilder; + StringBuilder stringBuilder14 = stringBuilder2; + handler = new StringBuilder.AppendInterpolatedStringHandler(15, 1, stringBuilder2); + handler.AppendLiteral("hdr : "); + handler.AppendFormatted(current.HdrActive ? "ON" : "off"); + stringBuilder14.AppendLine(ref handler); + stringBuilder2 = stringBuilder; + StringBuilder stringBuilder15 = stringBuilder2; + handler = new StringBuilder.AppendInterpolatedStringHandler(15, 2, stringBuilder2); + handler.AppendLiteral("monitors : "); + handler.AppendFormatted(current.MonitorCount); + handler.AppendFormatted(current.MixedDpi ? " (mixed scaling)" : ""); + stringBuilder15.AppendLine(ref handler); + stringBuilder2 = stringBuilder; + StringBuilder stringBuilder16 = stringBuilder2; + handler = new StringBuilder.AppendInterpolatedStringHandler(15, 1, stringBuilder2); + handler.AppendLiteral("elevated : "); + handler.AppendFormatted(current.Elevated ? "yes" : "no"); + stringBuilder16.AppendLine(ref handler); + stringBuilder.AppendLine(); + if (!probe.Ran) + { + stringBuilder2 = stringBuilder; + StringBuilder stringBuilder17 = stringBuilder2; + handler = new StringBuilder.AppendInterpolatedStringHandler(31, 1, stringBuilder2); + handler.AppendLiteral("capture test : could not run ("); + handler.AppendFormatted(probe.Note); + handler.AppendLiteral(")"); + stringBuilder17.AppendLine(ref handler); + if (!string.IsNullOrEmpty(probe.Detail)) + { + stringBuilder2 = stringBuilder; + StringBuilder stringBuilder18 = stringBuilder2; + handler = new StringBuilder.AppendInterpolatedStringHandler(15, 1, stringBuilder2); + handler.AppendLiteral(" detail : "); + handler.AppendFormatted(probe.Detail); + stringBuilder18.AppendLine(ref handler); + } + } + else + { + stringBuilder2 = stringBuilder; + StringBuilder stringBuilder19 = stringBuilder2; + handler = new StringBuilder.AppendInterpolatedStringHandler(15, 1, stringBuilder2); + handler.AppendLiteral("capture test : "); + handler.AppendFormatted(probe.Note); + stringBuilder19.AppendLine(ref handler); + stringBuilder.AppendLine(" measured : " + probe.MedianRatio.ToString("F3", invariantCulture) + " (1.0 = capture saw no change, ~2.0 = capture saw the effect)"); + } + return stringBuilder.ToString(); + } + + private static string DescribeAdapters() + { + try + { + using Factory1 factory = new Factory1(); + List list = new List(); + int num = 0; + while (true) + { + Adapter1 adapter; + try + { + adapter = factory.GetAdapter1(num); + } + catch (SharpDXException) + { + break; + } + using (adapter) + { + AdapterDescription1 description = adapter.Description1; + if ((description.Flags & AdapterFlags.Software) == 0) + { + list.Add(description.Description.Trim()); + } + } + num++; + } + return (list.Count == 0) ? "none found" : string.Join(" + ", list); + } + catch (Exception ex2) + { + return "unavailable (" + ex2.GetType().Name + ")"; + } + } + + public static CaptureProbe FailedBecause(Exception ex) + { + return FailedBecause(ex, CountHardwareAdapters()); + } + + internal static CaptureProbe FailedBecause(Exception ex, int hardwareAdapters) + { + string detail = ex.GetType().Name + ": " + Short(ex.Message) + $" (0x{ex.HResult:X8})"; + string why; + if (ex.HResult == -2005270524) + { + why = "This laptop's screen runs on a different graphics chip, so the test can't look. In OBS, try Display Capture with Capture Method 'Windows 10 (1903 and up)'"; + } + else + { + why = ((ex.HResult == -2005270526 && hardwareAdapters > 1) ? "The test couldn't find your screen on any graphics chip, so it can't look. In OBS, try Display Capture with Capture Method 'Windows 10 (1903 and up)'" : "Windows wouldn't let the test look at your screen"); + } + return CaptureProbe.Failed(why, detail); + } + + internal static int FirstAdapterWithAnOutput(int adapters, Func hasOutput) + { + for (int i = 0; i < adapters; i++) + { + if (hasOutput(i)) + { + return i; + } + } + return 0; + } + + private static int CountAdapters(Factory1 factory) + { + int num = 0; + while (true) + { + try + { + using (factory.GetAdapter1(num)) + { + } + } + catch (SharpDXException) + { + return num; + } + num++; + } + } + + private static bool AdapterHasAScreen(Factory1 factory, int index) + { + try + { + using Adapter1 adapter = factory.GetAdapter1(index); + if ((adapter.Description1.Flags & AdapterFlags.Software) != 0) + { + return false; + } + using (adapter.GetOutput(0)) + { + return true; + } + } + catch (SharpDXException) + { + return false; + } + } + + private static int CountHardwareAdapters() + { + try + { + using Factory1 factory = new Factory1(); + int num = 0; + int num2 = 0; + while (true) + { + Adapter1 adapter; + try + { + adapter = factory.GetAdapter1(num2); + } + catch (SharpDXException) + { + break; + } + using (adapter) + { + if ((adapter.Description1.Flags & AdapterFlags.Software) == 0) + { + num++; + } + } + num2++; + } + return num; + } + catch (Exception) + { + return 0; + } + } + + private static string Short(string s) + { + if (!string.IsNullOrEmpty(s)) + { + return s.Split('\n')[0].Trim(); + } + return ""; + } + + private static double MeanChroma(SharpDX.Direct3D11.Device device, Output1 output1) + { + using OutputDuplication outputDuplication = output1.DuplicateOutput(device); + SharpDX.DXGI.Resource resource = null; + for (int i = 0; i < 40; i++) + { + if (resource != null) + { + break; + } + if (outputDuplication.TryAcquireNextFrame(250, out var _, out var desktopResourceOut).Success && desktopResourceOut != null) + { + resource = desktopResourceOut; + } + else + { + Thread.Sleep(25); + } + } + if (resource == null) + { + return 0.0; + } + using (resource) + { + using Texture2D texture2D = resource.QueryInterface(); + Texture2DDescription description = texture2D.Description; + using Texture2D texture2D2 = new Texture2D(device, new Texture2DDescription + { + Width = description.Width, + Height = description.Height, + MipLevels = 1, + ArraySize = 1, + Format = description.Format, + SampleDescription = new SampleDescription(1, 0), + Usage = ResourceUsage.Staging, + BindFlags = BindFlags.None, + CpuAccessFlags = CpuAccessFlags.Read, + OptionFlags = ResourceOptionFlags.None + }); + device.ImmediateContext.CopyResource(texture2D, texture2D2); + DataBox dataBox = device.ImmediateContext.MapSubresource(texture2D2, 0, MapMode.Read, SharpDX.Direct3D11.MapFlags.None); + double num = 0.0; + int num2 = 0; + byte[] array = new byte[dataBox.RowPitch]; + for (int j = 0; j < description.Height; j += 4) + { + Marshal.Copy(dataBox.DataPointer + j * dataBox.RowPitch, array, 0, dataBox.RowPitch); + for (int k = 0; k < description.Width; k += 4) + { + int num3 = k * 4; + if (num3 + 2 >= array.Length) + { + break; + } + byte val = array[num3]; + byte val2 = array[num3 + 1]; + byte val3 = array[num3 + 2]; + int num4 = Math.Max(val3, Math.Max(val2, val)); + int num5 = Math.Min(val3, Math.Min(val2, val)); + num += (double)(num4 - num5); + num2++; + } + } + device.ImmediateContext.UnmapSubresource(texture2D2, 0); + try + { + outputDuplication.ReleaseFrame(); + } + catch + { + } + return (num2 == 0) ? 0.0 : (num / (double)num2); + } + } +} diff --git a/VibranceHud/CaptureProbe.cs b/VibranceHud/CaptureProbe.cs new file mode 100644 index 0000000..d064c46 --- /dev/null +++ b/VibranceHud/CaptureProbe.cs @@ -0,0 +1,9 @@ +namespace VibranceHud; + +public sealed record CaptureProbe(bool Ran, double MedianRatio, bool ReachesCapture, string Note, string Detail = "") +{ + public static CaptureProbe Failed(string why, string detail = "") + { + return new CaptureProbe(Ran: false, 0.0, ReachesCapture: false, why, detail); + } +} diff --git a/VibranceHud/CaptureState.cs b/VibranceHud/CaptureState.cs new file mode 100644 index 0000000..574f462 --- /dev/null +++ b/VibranceHud/CaptureState.cs @@ -0,0 +1,8 @@ +namespace VibranceHud; + +public enum CaptureState +{ + Visible, + NeedsStreamingMode, + DependsOnCaptureMethod +} diff --git a/VibranceHud/CaptureStatus.cs b/VibranceHud/CaptureStatus.cs new file mode 100644 index 0000000..b686527 --- /dev/null +++ b/VibranceHud/CaptureStatus.cs @@ -0,0 +1,55 @@ +namespace VibranceHud; + +public static class CaptureStatus +{ + public const string AlwaysTrue = "In OBS use Display Capture, not Game Capture - Game Capture reads the game directly and never sees this. Gamma is never captured either way."; + + public static CaptureState Resolve(OverlayMode overlay, bool driverVibranceAvailable, bool streamingMode) + { + if (overlay == OverlayMode.Mag) + { + return CaptureState.DependsOnCaptureMethod; + } + if (!driverVibranceAvailable) + { + return CaptureState.Visible; + } + if (!streamingMode) + { + return CaptureState.NeedsStreamingMode; + } + return CaptureState.Visible; + } + + public static bool ToggleCanHelp(OverlayMode overlay, bool driverVibranceAvailable) + { + return driverVibranceAvailable; + } + + public static string Headline(CaptureState state) + { + return state switch + { + CaptureState.Visible => "Recordings show your colours.", + CaptureState.NeedsStreamingMode => "Recordings are missing your vibrance right now.", + _ => "Recordings show your colours - screen share may not.", + }; + } + + public static string Reason(CaptureState state, bool driverVibranceAvailable) + { + switch (state) + { + case CaptureState.NeedsStreamingMode: + return "Your vibrance is being applied by the graphics driver, after recording software has already read the screen. Turn on \"Move my colours where recording can see them\" above to move it somewhere they can see it."; + case CaptureState.DependsOnCaptureMethod: + if (driverVibranceAvailable) + { + return "Recordings and screen share both show your colours - most of it comes from your NVIDIA driver, which every capture path can see.\n\nSaturation pushed past 100 is done in software, and that part reaches OBS but not Discord screen share."; + } + return "OBS records your colours with its default Display Capture settings - confirmed on AMD. If they don't appear, open your Display Capture source and set Capture Method to \"Windows 10 (1903 and up)\".\n\nDiscord screen share reads the screen a different way and won't show them. Your card has no driver-level colour for PlexusX to use yet, which is what would fix that."; + default: + return driverVibranceAvailable ? "Your vibrance is being applied early enough for capture to pick it up." : "Your colours are already applied in software, which capture reads - so there was never anything to move. That switch is for NVIDIA driver vibrance."; + } + } +} diff --git a/VibranceHud/CardPanel.cs b/VibranceHud/CardPanel.cs new file mode 100644 index 0000000..2e19f4c --- /dev/null +++ b/VibranceHud/CardPanel.cs @@ -0,0 +1,30 @@ +using System.Drawing; +using System.Windows.Forms; + +namespace VibranceHud; + +public sealed class CardPanel : Panel +{ + private readonly CardSurface _surface = new CardSurface(); + + public CardPanel() + { + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + } + + protected override void OnPaint(PaintEventArgs e) + { + _surface.Paint(this, e.Graphics); + base.OnPaint(e); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _surface.Dispose(); + } + base.Dispose(disposing); + } +} diff --git a/VibranceHud/CardSurface.cs b/VibranceHud/CardSurface.cs new file mode 100644 index 0000000..fa081b7 --- /dev/null +++ b/VibranceHud/CardSurface.cs @@ -0,0 +1,143 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.Runtime.InteropServices; +using System.Windows.Forms; +using VibranceHud.Design; +using VibranceHud.Theming; + +namespace VibranceHud; + +internal sealed class CardSurface : IDisposable +{ + private Bitmap? _glass; + + private Size _glassSize; + + private string _glassTheme = ""; + + private Size _failedSize; + + private string _failedKey = ""; + + private bool _failureLogged; + + private static int Radius => Tokens.Scale(8); + + internal Action? FailPointForTest { get; set; } + + private static bool IsGdiFailure(Exception ex) + { + if (!(ex is OutOfMemoryException) && !(ex is ExternalException) && !(ex is ArgumentException)) + { + return ex is InvalidOperationException; + } + return true; + } + + private void LogOnce(Exception ex) + { + if (!_failureLogged) + { + _failureLogged = true; + CrashLog.Write(ex); + } + } + + internal void Paint(Control owner, Graphics g) + { + try + { + if (SlateSurface.Active && AppBackground.IsSet) + { + Glass.PaintPanel(g, new RectangleF(0.5f, 0.5f, owner.Width - 1, owner.Height - 1), Radius, Glass.BackdropOffsetOf(owner)); + return; + } + Bitmap bitmap = EnsureGlass(owner.Size); + if (bitmap != null) + { + FailPointForTest?.Invoke("draw"); + g.DrawImageUnscaled(bitmap, 0, 0); + } + } + catch (Exception ex) when (IsGdiFailure(ex)) + { + LogOnce(ex); + } + } + + private static void PaintSignalCard(Graphics g, Size size) + { + RectangleF rectangleF = new RectangleF(0.5f, 0.5f, size.Width - 1, size.Height - 1); + float num = Radius; + using GraphicsPath graphicsPath = new GraphicsPath(); + graphicsPath.AddArc(rectangleF.X, rectangleF.Y, num, num, 180f, 90f); + graphicsPath.AddArc(rectangleF.Right - num, rectangleF.Y, num, num, 270f, 90f); + graphicsPath.AddArc(rectangleF.Right - num, rectangleF.Bottom - num, num, num, 0f, 90f); + graphicsPath.AddArc(rectangleF.X, rectangleF.Bottom - num, num, num, 90f, 90f); + graphicsPath.CloseFigure(); + g.SmoothingMode = SmoothingMode.AntiAlias; + g.PixelOffsetMode = PixelOffsetMode.Half; + using (SolidBrush brush = new SolidBrush(SignalTokens.Ash.Surface1)) + { + g.FillPath(brush, graphicsPath); + } + using Pen pen = new Pen(SignalTokens.Ash.Border, 1f); + g.DrawPath(pen, graphicsPath); + } + + private Bitmap? EnsureGlass(Size size) + { + if (size.Width < 2 || size.Height < 2) + { + return null; + } + string text = Theme.CurrentName + "|" + Glass.ActiveChrome; + if (_glass != null && _glassSize == size && _glassTheme == text) + { + return _glass; + } + if (_failedSize == size && _failedKey == text) + { + return null; + } + try + { + FailPointForTest?.Invoke("build"); + _glass?.Dispose(); + _glass = new Bitmap(size.Width, size.Height, PixelFormat.Format32bppArgb); + _glassSize = size; + _glassTheme = text; + using Graphics graphics = Graphics.FromImage(_glass); + graphics.Clear(Color.Transparent); + if (SlateSurface.Active) + { + Glass.PaintPanel(graphics, new RectangleF(0.5f, 0.5f, size.Width - 1, size.Height - 1), Radius); + } + else + { + PaintSignalCard(graphics, size); + } + } + catch + { + _glass?.Dispose(); + _glass = null; + _glassSize = Size.Empty; + _glassTheme = ""; + _failedSize = size; + _failedKey = text; + throw; + } + _failedSize = Size.Empty; + _failedKey = ""; + return _glass; + } + + public void Dispose() + { + _glass?.Dispose(); + _glass = null; + } +} diff --git a/VibranceHud/ChannelMix.cs b/VibranceHud/ChannelMix.cs new file mode 100644 index 0000000..070b56f --- /dev/null +++ b/VibranceHud/ChannelMix.cs @@ -0,0 +1,67 @@ +using System; +using System.Globalization; +using System.Linq; + +namespace VibranceHud; + +public sealed record ChannelMix(float RR, float RG, float RB, float GR, float GG, float GB, float BR, float BG, float BB) +{ + public bool IsIdentity => Near(Identity); + + public static readonly ChannelMix Identity = new ChannelMix(1f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 1f); + + private const float Tolerance = 0.0005f; + + public bool Near(ChannelMix other) + { + return ToArray().Zip(other.ToArray(), (float a, float b) => Math.Abs(a - b)).All((float d) => d <= 0.0005f); + } + + public float[] ToArray() + { + return new float[9] { RR, RG, RB, GR, GG, GB, BR, BG, BB }; + } + + public static ChannelMix FromArray(float[]? nine) + { + if (nine == null || nine.Length != 9 || nine.Any((float v) => float.IsNaN(v) || float.IsInfinity(v))) + { + return Identity; + } + return new ChannelMix(nine[0], nine[1], nine[2], nine[3], nine[4], nine[5], nine[6], nine[7], nine[8]); + } + + public static ChannelMix FromPercent(params int[] nine) + { + if (nine.Length != 9) + { + throw new ArgumentException("a channel mix is nine numbers", "nine"); + } + return FromArray(nine.Select((int v) => (float)v / 100f).ToArray()); + } + + public float[] ToMatrix() + { + return new float[25] + { + RR, RG, RB, 0f, 0f, GR, GG, GB, 0f, 0f, + BR, BG, BB, 0f, 0f, 0f, 0f, 0f, 1f, 0f, + 0f, 0f, 0f, 0f, 1f + }; + } + + public float[] ComposeInto(float[] matrix) + { + if (!IsIdentity) + { + return ColourVision.Compose(matrix, ToMatrix()); + } + return matrix; + } + + public override string ToString() + { + return "[" + string.Join(",", from v in ToArray() + select Math.Round(v * 100f).ToString(CultureInfo.InvariantCulture)) + "]"; + } +} diff --git a/VibranceHud/ChipButton.cs b/VibranceHud/ChipButton.cs new file mode 100644 index 0000000..5f5fbc7 --- /dev/null +++ b/VibranceHud/ChipButton.cs @@ -0,0 +1,288 @@ +using System; +using System.Drawing; +using System.Windows.Forms; +using VibranceHud.Design; + +namespace VibranceHud; + +public sealed class ChipButton : Control +{ + private sealed class ChipAccessibleObject : ControlAccessibleObject + { + private readonly ChipButton _owner; + + public override AccessibleStates State => (AccessibleStates)((int)base.State | (_owner._active ? 16 : 0)); + + public ChipAccessibleObject(ChipButton owner) + : base(owner) + { + _owner = owner; + } + } + + private bool _active; + + private readonly HoverFade _fade; + + private readonly HoverFade _press; + + private readonly OutsideFocusRing _ring; + + private string _suffix = ""; + + private ContentAlignment _align = ContentAlignment.MiddleCenter; + + public int Level { get; init; } + + public bool Active + { + get + { + return _active; + } + set + { + if (_active != value) + { + _active = value; + Invalidate(); + if (IsHandleCreated) + { + AccessibilityNotifyClients(AccessibleEvents.StateChange, -1); + } + } + } + } + + public string Suffix + { + get + { + return _suffix; + } + set + { + if (value == null) + { + value = ""; + } + if (!(_suffix == value)) + { + _suffix = value; + Invalidate(); + } + } + } + + public ContentAlignment TextAlign + { + get + { + return _align; + } + set + { + if (_align != value) + { + _align = value; + Invalidate(); + } + } + } + + protected override AccessibleObject CreateAccessibilityInstance() + { + return new ChipAccessibleObject(this); + } + + public ChipButton() + { + _fade = new HoverFade(this); + _press = new HoverFade(this); + _ring = new OutsideFocusRing(this, () => Radius(ControlInk.Dpi(this))); + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + Cursor = Cursors.Hand; + Height = 32; + TabStop = true; + SetStyle(ControlStyles.Selectable, value: true); + AccessibleRole = AccessibleRole.PushButton; + } + + protected override void OnTextChanged(EventArgs e) + { + base.OnTextChanged(e); + AccessibleName = Text; + } + + protected override void OnGotFocus(EventArgs e) + { + base.OnGotFocus(e); + Invalidate(); + } + + protected override void OnLostFocus(EventArgs e) + { + base.OnLostFocus(e); + Invalidate(); + } + + protected override void OnMouseDown(MouseEventArgs e) + { + base.OnMouseDown(e); + Focus(); + if (e.Button == MouseButtons.Left) + { + _press.Snap(hot: true); + Invalidate(); + } + } + + protected override void OnMouseUp(MouseEventArgs e) + { + base.OnMouseUp(e); + _press.Set(hot: false); + Invalidate(); + } + + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + Keys keyCode = e.KeyCode; + if ((keyCode == Keys.Return || keyCode == Keys.Space) ? true : false) + { + e.Handled = true; + OnClick(EventArgs.Empty); + } + } + + internal void TestPressKey(Keys key) + { + OnKeyDown(new KeyEventArgs(key)); + } + + internal void TestSetHover(bool on) + { + _fade.Snap(on); + } + + internal void TestSetPressed(bool on) + { + _press.Snap(on); + } + + protected override void OnMouseEnter(EventArgs e) + { + base.OnMouseEnter(e); + _fade.Set(hot: true); + Invalidate(); + } + + protected override void OnMouseLeave(EventArgs e) + { + base.OnMouseLeave(e); + _fade.Set(hot: false); + _press.Set(hot: false); + Invalidate(); + } + + protected override void OnEnabledChanged(EventArgs e) + { + base.OnEnabledChanged(e); + Cursor = (Enabled ? Cursors.Hand : Cursors.Default); + _fade.Snap(hot: false); + _press.Snap(hot: false); + Invalidate(); + } + + protected override void OnParentChanged(EventArgs e) + { + base.OnParentChanged(e); + _ring.Rehook(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _ring.Release(); + } + base.Dispose(disposing); + } + + private static float Radius(int dpi) + { + return ControlInk.PxF(dpi, 4f); + } + + private Font LabelFont(bool strong) + { + if (!strong) + { + return Font; + } + if (Math.Abs(Font.SizeInPoints - Fonts.Body.SizeInPoints) < 0.1f) + { + return Fonts.BodyBold; + } + if (Math.Abs(Font.SizeInPoints - Fonts.Caption.SizeInPoints) < 0.1f) + { + return Fonts.CaptionBold; + } + return Font; + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics graphics = e.Graphics; + int dpi = ControlInk.Dpi(this); + Color transparent = Color.Transparent; + float t = (Enabled ? _fade.Value : 0f); + float t2 = (Enabled ? _press.Value : 0f); + Color fill; + Color edge; + Color foreColor; + Color foreColor2; + if (!Enabled) + { + fill = (_active ? ControlInk.Surface2 : transparent); + edge = (_active ? ControlInk.Surface2 : ControlInk.TextDisabled); + foreColor = (foreColor2 = ControlInk.TextDisabledInk); + } + else if (_active) + { + fill = (edge = ControlInk.Accent); + foreColor = ControlInk.OnAccent; + foreColor2 = ControlInk.SelectedSuffix; + } + else + { + Color hover = ControlInk.Hover; + fill = ControlInk.Mix(ControlInk.Mix(Color.FromArgb(0, hover), hover, t), ControlInk.Pressed, t2); + edge = ControlInk.Edge; + foreColor = ControlInk.Text1; + foreColor2 = ControlInk.Text3; + } + ControlInk.PaintBox(graphics, ClientSize, Radius(dpi), ControlInk.Hairline(dpi), fill, edge); + Font font = LabelFont(_active); + int width = TextRenderer.MeasureText(graphics, Text, font, Size.Empty, TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding).Width; + int num = ControlInk.Px(dpi, 8); + Font caption = Fonts.Caption; + int num2 = ((_suffix.Length != 0) ? TextRenderer.MeasureText(graphics, _suffix, caption, Size.Empty, TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding).Width : 0); + int num3 = width + ((num2 > 0) ? (num + num2) : 0); + int num4 = ((_align == ContentAlignment.MiddleLeft) ? ControlInk.Px(dpi, 12) : ((Width - num3) / 2)); + TextRenderer.DrawText(graphics, Text, font, new Rectangle(num4, 0, width + 2, Height), foreColor, TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding); + if (num2 > 0) + { + TextRenderer.DrawText(graphics, _suffix, caption, new Rectangle(num4 + width + num, 0, num2 + 2, Height), foreColor2, TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding); + } + if (Focused && ShowFocusCues) + { + _ring.Show(show: true); + } + else + { + _ring.Show(show: false); + } + } +} diff --git a/VibranceHud/ColorAdjust.cs b/VibranceHud/ColorAdjust.cs new file mode 100644 index 0000000..8c936e0 --- /dev/null +++ b/VibranceHud/ColorAdjust.cs @@ -0,0 +1,65 @@ +using System; + +namespace VibranceHud; + +public static class ColorAdjust +{ + public const float WarmGreenCut = 0.12f; + + public const float WarmBlueCut = 0.38f; + + public const float VibranceRedHold = 0.55f; + + public static float[] Build(float saturation, float brightness, float warmth) + { + return BuildWithVibranceNumbers(saturation, 1f, 1f, 1f, brightness, warmth); + } + + internal static float[] BuildWithVibranceNumbers(float saturation, float red, float chroma, float contrast, float brightness, float warmth) + { + return BuildWithVibranceNumbers(saturation, red, chroma, contrast, brightness, warmth, ColourDepth.Neutral); + } + + internal static float[] BuildWithVibranceNumbers(float saturation, float red, float chroma, float contrast, float brightness, float warmth, ColourDepth depth) + { + float[] array = (depth.IsNeutral ? SaturationMatrix.Build(saturation * red, saturation * chroma, saturation * chroma) : SaturationMetrics.BuildWithVibranceNumbers(depth.Formula, saturation, red, chroma, depth)); + float num = Math.Max(0f, warmth); + float num2 = Math.Max(0f, 0f - warmth); + float num3 = 1f - 0.38f * num2; + float num4 = 1f - 0.12f * (num + num2); + float num5 = 1f - 0.38f * num; + float num6 = brightness * num3 * contrast; + float num7 = brightness * num4 * contrast; + float num8 = brightness * num5 * contrast; + float num9 = 0.5f * (1f - contrast); + for (int i = 0; i < 3; i++) + { + array[i * 5] *= num6; + array[i * 5 + 1] *= num7; + array[i * 5 + 2] *= num8; + } + array[20] = num9; + array[21] = num9; + array[22] = num9; + return array; + } + + public static bool IsIdentity(float saturation, float brightness, float warmth) + { + return IsIdentity(saturation, 1f, brightness, warmth); + } + + public static bool IsIdentity(float saturation, float vibrance, float brightness, float warmth) + { + return IsIdentity(saturation, vibrance, 1f, brightness, warmth); + } + + public static bool IsIdentity(float saturation, float vibrance, float contrast, float brightness, float warmth) + { + if (Math.Abs(saturation - 1f) < 0.001f && Math.Abs(vibrance - 1f) < 0.001f && Math.Abs(contrast - 1f) < 0.001f && Math.Abs(brightness - 1f) < 0.001f) + { + return Math.Abs(warmth) < 0.001f; + } + return false; + } +} diff --git a/VibranceHud/ColourBalance.cs b/VibranceHud/ColourBalance.cs new file mode 100644 index 0000000..9a41e48 --- /dev/null +++ b/VibranceHud/ColourBalance.cs @@ -0,0 +1,126 @@ +using System; + +namespace VibranceHud; + +public static class ColourBalance +{ + public const int MinHue = -180; + + public const int MaxHue = 180; + + public const int MinGain = 50; + + public const int MaxGain = 150; + + public static bool GainsNeutral(int red, int green, int blue) + { + if (red == 100 && green == 100) + { + return blue == 100; + } + return false; + } + + public static bool IsNeutral(int hue, int red, int green, int blue) + { + if (hue == 0) + { + return GainsNeutral(red, green, blue); + } + return false; + } + + public static float[] HueMatrix(int degrees) + { + double num = (double)Math.Clamp(degrees, -180, 180) * Math.PI / 180.0; + double num2 = Math.Cos(num); + double num3 = Math.Sin(num); + double num4 = (1.0 - num2) / 3.0; + double num5 = num3 / Math.Sqrt(3.0); + int[,] array = new int[3, 3] + { + { 0, -1, 1 }, + { 1, 0, -1 }, + { -1, 1, 0 } + }; + float[] array2 = new float[25]; + for (int i = 0; i < 3; i++) + { + for (int j = 0; j < 3; j++) + { + array2[i * 5 + j] = (float)(((i == j) ? num2 : 0.0) + num4 + num5 * (double)array[j, i]); + } + } + array2[18] = 1f; + array2[24] = 1f; + return array2; + } + + public static float[] GainMatrix(int red, int green, int blue) + { + return new float[25] + { + (float)Math.Clamp(red, 50, 150) / 100f, + 0f, + 0f, + 0f, + 0f, + 0f, + (float)Math.Clamp(green, 50, 150) / 100f, + 0f, + 0f, + 0f, + 0f, + 0f, + (float)Math.Clamp(blue, 50, 150) / 100f, + 0f, + 0f, + 0f, + 0f, + 0f, + 1f, + 0f, + 0f, + 0f, + 0f, + 0f, + 1f + }; + } + + public static float[] ComposeInto(float[] matrix, int hue, int red, int green, int blue) + { + if (IsNeutral(hue, red, green, blue)) + { + return matrix; + } + float[] array = matrix; + if (hue != 0) + { + array = Multiply(array, HueMatrix(hue)); + } + if (!GainsNeutral(red, green, blue)) + { + array = Multiply(array, GainMatrix(red, green, blue)); + } + return array; + } + + internal static float[] Multiply(float[] a, float[] b) + { + float[] array = new float[25]; + for (int i = 0; i < 5; i++) + { + for (int j = 0; j < 5; j++) + { + double num = 0.0; + for (int k = 0; k < 5; k++) + { + num += (double)a[i * 5 + k] * (double)b[k * 5 + j]; + } + array[i * 5 + j] = (float)num; + } + } + return array; + } +} diff --git a/VibranceHud/ColourDepth.cs b/VibranceHud/ColourDepth.cs new file mode 100644 index 0000000..d44175d --- /dev/null +++ b/VibranceHud/ColourDepth.cs @@ -0,0 +1,49 @@ +using System; + +namespace VibranceHud; + +public readonly record struct ColourDepth(SaturationMetric Formula = SaturationMetric.Rec709, int Darken = 0, int DarkenHue = 120, int HueTurn = 0, int HueTurnAmount = 100, int HueComplement = 0) +{ + public static ColourDepth Neutral => new ColourDepth(SaturationMetric.Rec709, 0, 120, 0, 100, 0); + + public bool IsNeutral + { + get + { + if (Formula == SaturationMetric.Rec709 && Darken == 0 && HueComplement == 0) + { + if (HueTurn != 0) + { + return HueTurnAmount == 0; + } + return true; + } + return false; + } + } + + public const int MinDarken = 0; + + public const int MaxDarken = 400; + + public const int MinDarkenHue = 0; + + public const int MaxDarkenHue = 359; + + public const int MinHueTurn = -180; + + public const int MaxHueTurn = 180; + + public const int MinHueTurnAmount = 0; + + public const int MaxHueTurnAmount = 100; + + public const int MinHueComplement = 0; + + public const int MaxHueComplement = 100; + + public ColourDepth Clamped() + { + return new ColourDepth(Enum.IsDefined(typeof(SaturationMetric), Formula) ? Formula : SaturationMetric.Rec709, Math.Clamp(Darken, 0, 400), Math.Clamp(DarkenHue, 0, 359), Math.Clamp(HueTurn, -180, 180), Math.Clamp(HueTurnAmount, 0, 100), Math.Clamp(HueComplement, 0, 100)); + } +} diff --git a/VibranceHud/ColourReachFacts.cs b/VibranceHud/ColourReachFacts.cs new file mode 100644 index 0000000..81025a6 --- /dev/null +++ b/VibranceHud/ColourReachFacts.cs @@ -0,0 +1,3 @@ +namespace VibranceHud; + +public readonly record struct ColourReachFacts(bool ExclusiveFullscreen, bool OverlayLive, DxInitFailureKind DxFailure, bool DxTried, bool DisplayIsCarryingTheLook = false, string? WhatTheDisplayCannotHold = null, GammaDelivery RampOutcome = default(GammaDelivery), bool CompetitiveOn = false); diff --git a/VibranceHud/ColourReachLine.cs b/VibranceHud/ColourReachLine.cs new file mode 100644 index 0000000..3be2c6d --- /dev/null +++ b/VibranceHud/ColourReachLine.cs @@ -0,0 +1,3 @@ +namespace VibranceHud; + +public readonly record struct ColourReachLine(ColourReachSeverity Severity, string Text); diff --git a/VibranceHud/ColourReachSeverity.cs b/VibranceHud/ColourReachSeverity.cs new file mode 100644 index 0000000..fce2d30 --- /dev/null +++ b/VibranceHud/ColourReachSeverity.cs @@ -0,0 +1,8 @@ +namespace VibranceHud; + +public enum ColourReachSeverity +{ + Ok, + Note, + Refused +} diff --git a/VibranceHud/ColourReachStatus.cs b/VibranceHud/ColourReachStatus.cs new file mode 100644 index 0000000..e09dc11 --- /dev/null +++ b/VibranceHud/ColourReachStatus.cs @@ -0,0 +1,92 @@ +namespace VibranceHud; + +public static class ColourReachStatus +{ + public const string FullscreenSentence = "Fullscreen: colour comes from the driver. Borderless gives the full look."; + + public const string CompetitiveSentence = "Colour on the driver: in full-screen games Competitive mode keeps your colour on the NVIDIA driver. Hue, channel mix, colour aids and Eye care pause there."; + + public const string ScreenEffectRefusedSentence = "Colour engine off: Windows could not start the screen effect (Magnification). Restart PlexusX; if it stays off, tell us."; + + public const string DisplayCarriesItSentence = "Full screen: your monitor is holding this look. It is the closest it can get."; + + public const string RampRefusedSentence = "Full screen: Windows refused this look on this monitor. Borderless gives the full look."; + + public const string RampIgnoredHdrSentence = "Full screen: HDR is on, and Windows ignores this look there. Borderless gives the full look."; + + public const string LookShowsInBorderless = "This look shows in Borderless or Windowed mode. In exclusive fullscreen the game only gets the driver's colour."; + + public const string LookNeedsPaidColourControls = "This look needs the paid colour controls, and they are off on this PC right now."; + + public static string DisplayCarriesItButNot(string missing) + { + return "Full screen: your monitor is holding this look, but not " + missing + ". Borderless gives the full look."; + } + + public static string RampSoftenedSentence(string step) + { + return "Full screen: Windows only let " + StepWords(step) + " of this look through. Borderless gives the full look."; + } + + private static string StepWords(string step) + { + return step switch + { + "1/2" => "half", + "1/4" => "a quarter", + "1/8" => "an eighth", + _ => "part", + }; + } + + public static ColourReachLine For(ColourReachFacts facts) + { + if (!facts.OverlayLive && (!facts.DxTried || facts.DxFailure == DxInitFailureKind.None)) + { + return new ColourReachLine(ColourReachSeverity.Refused, "Colour engine off: Windows could not start the screen effect (Magnification). Restart PlexusX; if it stays off, tell us."); + } + if (!facts.OverlayLive) + { + return new ColourReachLine(ColourReachSeverity.Refused, "Colour engine off: " + Because(facts.DxFailure) + "."); + } + if (facts.ExclusiveFullscreen && facts.DisplayIsCarryingTheLook && !facts.RampOutcome.IsFull) + { + return new ColourReachLine(ColourReachSeverity.Note, facts.RampOutcome.Kind switch + { + GammaDeliveryKind.Softened => RampSoftenedSentence(facts.RampOutcome.Step), + GammaDeliveryKind.IgnoredHdr => "Full screen: HDR is on, and Windows ignores this look there. Borderless gives the full look.", + _ => "Full screen: Windows refused this look on this monitor. Borderless gives the full look.", + }); + } + if (facts.ExclusiveFullscreen && facts.DisplayIsCarryingTheLook) + { + return new ColourReachLine(ColourReachSeverity.Note, string.IsNullOrEmpty(facts.WhatTheDisplayCannotHold) ? "Full screen: your monitor is holding this look. It is the closest it can get." : DisplayCarriesItButNot(facts.WhatTheDisplayCannotHold)); + } + if (facts.ExclusiveFullscreen) + { + return new ColourReachLine(ColourReachSeverity.Note, "Fullscreen: colour comes from the driver. Borderless gives the full look."); + } + if (facts.CompetitiveOn) + { + return new ColourReachLine(ColourReachSeverity.Note, "Colour on the driver: in full-screen games Competitive mode keeps your colour on the NVIDIA driver. Hue, channel mix, colour aids and Eye care pause there."); + } + return new ColourReachLine(ColourReachSeverity.Ok, ""); + } + + public static string Because(DxInitFailureKind kind) + { + return kind switch + { + DxInitFailureKind.None => "DirectX started but no monitor could be rendered", + DxInitFailureKind.NoCompatibleAdapter => "no graphics card here can do DirectX 11", + DxInitFailureKind.DeviceCreationFailed => "Windows would not give PlexusX a DirectX device", + DxInitFailureKind.NoOutputs => "Windows reported no display", + DxInitFailureKind.DriverIssue => "your display driver turned DirectX 11 down", + DxInitFailureKind.SdkIssue => "the DirectX 11 runtime is not installed", + DxInitFailureKind.OutOfMemory => "your graphics memory is full", + DxInitFailureKind.CaptureInUse => "another app is capturing this display", + DxInitFailureKind.Unknown => "DirectX 11 would not start on this PC", + _ => "DirectX 11 would not start on this PC", + }; + } +} diff --git a/VibranceHud/ColourTrace.cs b/VibranceHud/ColourTrace.cs new file mode 100644 index 0000000..df5a670 --- /dev/null +++ b/VibranceHud/ColourTrace.cs @@ -0,0 +1,99 @@ +using System; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Reflection; +using System.Text; +using VibranceHud.Support; + +namespace VibranceHud; + +internal static class ColourTrace +{ + internal static readonly bool Enabled = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("PLEXUSX_SAT_TRACE")); + + private static readonly string Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "plexusx-sat.log"); + + private static readonly object Gate = new object(); + + private const int Frames = 12; + + public static void Value(string name, int was, int now) + { + if (Enabled && was != now) + { + Write(string.Format(CultureInfo.InvariantCulture, "{0} {1}->{2} {3}", name, was, now, Caller())); + } + } + + public static void Screen(bool cleared, int saturation) + { + if (Enabled) + { + Write(string.Format(CultureInfo.InvariantCulture, "SCREEN {0} (saturation still reads {1}) {2}", cleared ? "CLEARED - picture now neutral" : "applied", saturation, Caller())); + } + } + + public static void Meter(ReassertMeter meter) + { + if (Enabled && meter != null) + { + Write("REASSERT" + Environment.NewLine + meter.Describe()); + } + } + + public static void Refused(string layer, string why) + { + if (Enabled) + { + Write(string.Format(CultureInfo.InvariantCulture, "REFUSED {0}: {1} {2}", layer, why, Caller())); + } + } + + public static void Fallback(string what) + { + if (Enabled) + { + Write(string.Format(CultureInfo.InvariantCulture, "FALLBACK {0} {1}", what, Caller())); + } + } + + private static string Caller() + { + try + { + StackTrace stackTrace = new StackTrace(2, fNeedFileInfo: false); + StringBuilder stringBuilder = new StringBuilder(); + int num = Math.Min(12, stackTrace.FrameCount); + for (int i = 0; i < num; i++) + { + MethodBase methodBase = stackTrace.GetFrame(i)?.GetMethod(); + if (!(methodBase == null)) + { + stringBuilder.Append(methodBase.DeclaringType?.Name).Append('.').Append(methodBase.Name) + .Append(" <- "); + } + } + return stringBuilder.ToString(); + } + catch + { + return "(no stack)"; + } + } + + private static void Write(string message) + { + try + { + string text = string.Format(CultureInfo.InvariantCulture, "{0:HH:mm:ss.fff} {1}", DateTime.Now, message); + lock (Gate) + { + File.AppendAllText(Path, text + Environment.NewLine); + } + } + catch + { + } + } +} diff --git a/VibranceHud/ColourVision.cs b/VibranceHud/ColourVision.cs new file mode 100644 index 0000000..4dde9db --- /dev/null +++ b/VibranceHud/ColourVision.cs @@ -0,0 +1,169 @@ +namespace VibranceHud; + +public static class ColourVision +{ + private static readonly double[,] RgbToLms = new double[3, 3] + { + { 17.8824, 43.5161, 4.11935 }, + { 3.45565, 27.1554, 3.86714 }, + { 0.0299566, 0.184309, 1.46709 } + }; + + private static readonly double[,] LmsToRgb = new double[3, 3] + { + { 0.0809444479, -0.130504409, 0.116721066 }, + { -0.0102485335, 0.0540193266, -0.113614708 }, + { -0.000365296938, -0.00412161469, 0.693511405 } + }; + + private static readonly double[,] ErrorShift = new double[3, 3] + { + { 0.0, 0.0, 0.0 }, + { 0.7, 1.0, 0.0 }, + { 0.7, 0.0, 1.0 } + }; + + private static double[,] Simulation(ColourVisionMode mode) + { + return mode switch + { + ColourVisionMode.RedWeak => new double[3, 3] + { + { 0.0, 2.02344, -2.52581 }, + { 0.0, 1.0, 0.0 }, + { 0.0, 0.0, 1.0 } + }, + ColourVisionMode.GreenWeak => new double[3, 3] + { + { 1.0, 0.0, 0.0 }, + { 0.494207, 0.0, 1.24827 }, + { 0.0, 0.0, 1.0 } + }, + ColourVisionMode.BlueWeak => new double[3, 3] + { + { 1.0, 0.0, 0.0 }, + { 0.0, 1.0, 0.0 }, + { -0.395913, 0.801109, 0.0 } + }, + _ => Identity3(), + }; + } + + public static float[] Matrix(ColourVisionMode mode) + { + float[] array = Identity5(); + switch (mode) + { + case ColourVisionMode.Off: + return array; + case ColourVisionMode.HoloBlack: + return HoloBlack.GreenSubtracted(); + default: + { + double[,] b = Multiply3(LmsToRgb, Multiply3(Simulation(mode), RgbToLms)); + double[,] b2 = Subtract3(Identity3(), b); + double[,] array2 = Add3(Identity3(), Multiply3(ErrorShift, b2)); + for (int i = 0; i < 3; i++) + { + for (int j = 0; j < 3; j++) + { + array[j * 5 + i] = (float)array2[i, j]; + } + } + return array; + } + } + } + + public static float[] Compose(float[] first, float[] second) + { + float[] array = new float[25]; + for (int i = 0; i < 5; i++) + { + for (int j = 0; j < 5; j++) + { + float num = 0f; + for (int k = 0; k < 5; k++) + { + num += first[i * 5 + k] * second[k * 5 + j]; + } + array[i * 5 + j] = num; + } + } + return array; + } + + private static double[,] Identity3() + { + return new double[3, 3] + { + { 1.0, 0.0, 0.0 }, + { 0.0, 1.0, 0.0 }, + { 0.0, 0.0, 1.0 } + }; + } + + private static float[] Identity5() + { + float[] array = new float[25]; + for (int i = 0; i < 5; i++) + { + array[i * 5 + i] = 1f; + } + return array; + } + + private static double[,] Multiply3(double[,] a, double[,] b) + { + double[,] array = new double[3, 3]; + for (int i = 0; i < 3; i++) + { + for (int j = 0; j < 3; j++) + { + double num = 0.0; + for (int k = 0; k < 3; k++) + { + num += a[i, k] * b[k, j]; + } + array[i, j] = num; + } + } + return array; + } + + private static double[,] Add3(double[,] a, double[,] b) + { + double[,] array = new double[3, 3]; + for (int i = 0; i < 3; i++) + { + for (int j = 0; j < 3; j++) + { + array[i, j] = a[i, j] + b[i, j]; + } + } + return array; + } + + private static double[,] Subtract3(double[,] a, double[,] b) + { + double[,] array = new double[3, 3]; + for (int i = 0; i < 3; i++) + { + for (int j = 0; j < 3; j++) + { + array[i, j] = a[i, j] - b[i, j]; + } + } + return array; + } + + public static (double R, double G, double B) Simulate(ColourVisionMode mode, double r, double g, double b) + { + if (mode == ColourVisionMode.Off) + { + return (R: r, G: g, B: b); + } + double[,] array = Multiply3(LmsToRgb, Multiply3(Simulation(mode), RgbToLms)); + return (R: array[0, 0] * r + array[0, 1] * g + array[0, 2] * b, G: array[1, 0] * r + array[1, 1] * g + array[1, 2] * b, B: array[2, 0] * r + array[2, 1] * g + array[2, 2] * b); + } +} diff --git a/VibranceHud/ColourVisionMode.cs b/VibranceHud/ColourVisionMode.cs new file mode 100644 index 0000000..bfd78ae --- /dev/null +++ b/VibranceHud/ColourVisionMode.cs @@ -0,0 +1,10 @@ +namespace VibranceHud; + +public enum ColourVisionMode +{ + Off, + GreenWeak, + RedWeak, + BlueWeak, + HoloBlack +} diff --git a/VibranceHud/ColourWatchdog.cs b/VibranceHud/ColourWatchdog.cs new file mode 100644 index 0000000..85e6678 --- /dev/null +++ b/VibranceHud/ColourWatchdog.cs @@ -0,0 +1,182 @@ +using System; + +namespace VibranceHud; + +public sealed class ColourWatchdog +{ + public static readonly TimeSpan Debounce = TimeSpan.FromMilliseconds(400.0); + + public static readonly TimeSpan TickInterval = TimeSpan.FromSeconds(60.0); + + public static readonly TimeSpan ForegroundSettle = TimeSpan.FromSeconds(2.0); + + public const int FailuresBeforeBackingOff = 5; + + private readonly Action _reapply; + + private readonly Func _isHdrActive; + + private readonly Func _isNeutral; + + private readonly Func _now; + + private readonly Action? _onGaveUp; + + private readonly Action? _worldChanged; + + private DateTime _lastApply = DateTime.MinValue; + + private bool _stopped; + + private int _consecutiveFailures; + + private bool _backedOff; + + private bool _saidSo; + + private DateTime _lastForeground = DateTime.MinValue; + + private DateTime? _foregroundCheckDue; + + internal TimeSpan? ForegroundCheckDelay + { + get + { + if (!_stopped && _foregroundCheckDue.HasValue) + { + return TimeSpan.FromTicks(Math.Max(0L, (_foregroundCheckDue.Value - _now()).Ticks)); + } + return null; + } + } + + internal bool HasBackedOff => _backedOff; + + public ColourWatchdog(Action reapply, Func isHdrActive, Func isNeutral, Func now, Action? onGaveUp = null, Action? onWorldChanged = null) + { + _reapply = reapply; + _isHdrActive = isHdrActive; + _isNeutral = isNeutral; + _now = now; + _onGaveUp = onGaveUp; + _worldChanged = onWorldChanged; + } + + public void OnDisplayChanged() + { + Reassert(force: true, forget: true); + } + + public void OnResume() + { + Reassert(force: true, forget: true); + } + + public void OnSessionUnlock() + { + Reassert(force: true, forget: true); + } + + public void OnForegroundChanged() + { + if (!_stopped) + { + DateTime dateTime = _now(); + DateTime dateTime2 = _lastForeground + ForegroundSettle; + DateTime dateTime3 = _lastApply + Debounce; + if (dateTime3 > dateTime2) + { + dateTime2 = dateTime3; + } + if (dateTime < dateTime2) + { + _foregroundCheckDue = dateTime2; + return; + } + _foregroundCheckDue = null; + _lastForeground = dateTime; + Reassert(force: true, forget: false); + } + } + + public void Tick() + { + if (_stopped) + { + return; + } + DateTime? foregroundCheckDue = _foregroundCheckDue; + if (foregroundCheckDue.HasValue) + { + DateTime valueOrDefault = foregroundCheckDue.GetValueOrDefault(); + if (_now() >= valueOrDefault) + { + _foregroundCheckDue = null; + OnForegroundChanged(); + return; + } + } + Reassert(force: false, forget: false); + } + + public void Stop() + { + _stopped = true; + _foregroundCheckDue = null; + } + + private void Reassert(bool force, bool forget) + { + if (_stopped) + { + return; + } + if (force) + { + _backedOff = false; + } + else if (_backedOff) + { + return; + } + try + { + if (_isNeutral() || _isHdrActive()) + { + return; + } + DateTime dateTime = _now(); + if (!(dateTime - _lastApply < (force ? Debounce : TickInterval))) + { + _lastApply = dateTime; + if (forget) + { + _worldChanged?.Invoke(); + } + _reapply(); + _consecutiveFailures = 0; + } + } + catch (Exception obj) + { + _consecutiveFailures++; + if (_consecutiveFailures < 5) + { + return; + } + _backedOff = true; + if (_saidSo) + { + return; + } + _saidSo = true; + try + { + _onGaveUp?.Invoke(obj); + } + catch + { + } + } + } +} diff --git a/VibranceHud/ColourWriteMeter.cs b/VibranceHud/ColourWriteMeter.cs new file mode 100644 index 0000000..89db142 --- /dev/null +++ b/VibranceHud/ColourWriteMeter.cs @@ -0,0 +1,33 @@ +namespace VibranceHud; + +public sealed class ColourWriteMeter +{ + public int Driver { get; private set; } + + public int Gamma { get; private set; } + + public int Overlay { get; private set; } + + public void CountDriver() + { + Driver++; + } + + internal void CountGamma() + { + Gamma++; + } + + public void CountOverlay() + { + Overlay++; + } + + public void AddGamma(int uploads) + { + if (uploads > 0) + { + Gamma += uploads; + } + } +} diff --git a/VibranceHud/CompositionKeeper.cs b/VibranceHud/CompositionKeeper.cs new file mode 100644 index 0000000..bb416ce --- /dev/null +++ b/VibranceHud/CompositionKeeper.cs @@ -0,0 +1,256 @@ +using System; +using System.Runtime.InteropServices; +using System.Windows.Forms; + +namespace VibranceHud; + +public sealed class CompositionKeeper : IDisposable +{ + private struct WNDCLASSEX + { + public int cbSize; + + public int style; + + public nint lpfnWndProc; + + public int cbClsExtra; + + public int cbWndExtra; + + public nint hInstance; + + public nint hIcon; + + public nint hCursor; + + public nint hbrBackground; + + [MarshalAs(UnmanagedType.LPWStr)] + public string lpszMenuName; + + [MarshalAs(UnmanagedType.LPWStr)] + public string lpszClassName; + + public nint hIconSm; + } + + private delegate nint WndProcDelegate(nint hWnd, uint msg, nint wParam, nint lParam); + + private const int WS_POPUP = int.MinValue; + + private const int WS_VISIBLE = 268435456; + + private const int WS_EX_TOPMOST = 8; + + private const int WS_EX_TRANSPARENT = 32; + + private const int WS_EX_TOOLWINDOW = 128; + + private const int WS_EX_NOACTIVATE = 134217728; + + private const int WS_EX_LAYERED = 524288; + + private const int LWA_ALPHA = 2; + + private const int SW_SHOWNOACTIVATE = 4; + + private static readonly nint HWND_TOPMOST = new IntPtr(-1); + + private const uint SWP_NOMOVE = 2u; + + private const uint SWP_NOSIZE = 1u; + + private const uint SWP_NOACTIVATE = 16u; + + private const uint SWP_SHOWWINDOW = 64u; + + private const int ReassertIntervalMs = 500; + + private const uint GW_HWNDPREV = 3u; + + private static readonly WndProcDelegate s_wndProc = DefWindowProc; + + private static bool s_classRegistered; + + private const string KeeperClass = "PlexusXCompositionKeeper"; + + private nint _hwnd; + + private WinEventListener? _foreground; + + private WinEventListener? _reorder; + + private Timer? _reassert; + + private bool _disposed; + + public bool IsActive => _hwnd != IntPtr.Zero; + + internal bool ListensRatherThanPolls + { + get + { + WinEventListener? foreground = _foreground; + if (foreground != null && foreground.IsHooked) + { + WinEventListener? reorder = _reorder; + if (reorder != null && reorder.IsHooked) + { + return _reassert == null; + } + } + return false; + } + } + + internal bool PollsAsBackstop => _reassert != null; + + [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern ushort RegisterClassEx(ref WNDCLASSEX lpwcx); + + [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern nint CreateWindowEx(int dwExStyle, string lpClassName, string lpWindowName, int dwStyle, int x, int y, int nWidth, int nHeight, nint hWndParent, nint hMenu, nint hInstance, nint lpParam); + + [DllImport("user32.dll")] + private static extern nint DefWindowProc(nint hWnd, uint msg, nint wParam, nint lParam); + + [DllImport("user32.dll")] + private static extern bool ShowWindow(nint hWnd, int nCmdShow); + + [DllImport("user32.dll")] + private static extern bool DestroyWindow(nint hWnd); + + [DllImport("user32.dll")] + private static extern bool SetLayeredWindowAttributes(nint hwnd, uint crKey, byte bAlpha, uint dwFlags); + + [DllImport("user32.dll")] + private static extern bool SetWindowPos(nint hWnd, nint hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); + + [DllImport("user32.dll")] + private static extern nint GetWindow(nint hWnd, uint uCmd); + + [DllImport("kernel32.dll")] + private static extern nint GetModuleHandle(string? lpModuleName); + + public CompositionKeeper() + : this(null) + { + } + + internal CompositionKeeper(Func, WinEventListener>? listenerFactory) + { + try + { + EnsureClass(); + _hwnd = CreateWindowEx(134742184, "PlexusXCompositionKeeper", "PlexusX Composition Keeper", -1879048192, 0, 0, 1, 1, IntPtr.Zero, IntPtr.Zero, GetModuleHandle(null), IntPtr.Zero); + if (_hwnd == IntPtr.Zero) + { + return; + } + SetLayeredWindowAttributes(_hwnd, 0u, 1, 2u); + ShowWindow(_hwnd, 4); + Reassert(); + _foreground = Listen(listenerFactory, 3u); + _reorder = Listen(listenerFactory, 32772u); + WinEventListener? foreground = _foreground; + if (foreground != null && foreground.IsHooked) + { + WinEventListener? reorder = _reorder; + if (reorder != null && reorder.IsHooked) + { + return; + } + } + _reassert = new Timer + { + Interval = 500 + }; + _reassert.Tick += (object? s, EventArgs e) => + { + Reassert(); + }; + _reassert.Start(); + } + catch + { + Dispose(); + } + } + + private WinEventListener Listen(Func, WinEventListener>? factory, uint evt) + { + if (factory == null) + { + return new WinEventListener(evt, evt, (nint _) => + { + Reassert(); + }); + } + return factory(evt, evt, (nint _) => + { + Reassert(); + }); + } + + private void Reassert() + { + if (_hwnd != IntPtr.Zero && GetWindow(_hwnd, 3u) != IntPtr.Zero) + { + SetWindowPos(_hwnd, HWND_TOPMOST, 0, 0, 1, 1, 19u); + } + } + + private static void EnsureClass() + { + if (!s_classRegistered) + { + WNDCLASSEX lpwcx = new WNDCLASSEX + { + cbSize = Marshal.SizeOf(), + style = 0, + lpfnWndProc = Marshal.GetFunctionPointerForDelegate(s_wndProc), + hInstance = GetModuleHandle(null), + lpszClassName = "PlexusXCompositionKeeper" + }; + RegisterClassEx(ref lpwcx); + s_classRegistered = true; + } + } + + public void Dispose() + { + if (_disposed) + { + return; + } + _disposed = true; + if (_foreground != null) + { + _foreground.Dispose(); + _foreground = null; + } + if (_reorder != null) + { + _reorder.Dispose(); + _reorder = null; + } + if (_reassert != null) + { + _reassert.Stop(); + _reassert.Dispose(); + _reassert = null; + } + if (_hwnd != IntPtr.Zero) + { + try + { + DestroyWindow(_hwnd); + } + catch + { + } + _hwnd = IntPtr.Zero; + } + } +} diff --git a/VibranceHud/ControlInk.cs b/VibranceHud/ControlInk.cs new file mode 100644 index 0000000..331a2e3 --- /dev/null +++ b/VibranceHud/ControlInk.cs @@ -0,0 +1,388 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; +using VibranceHud.Design; + +namespace VibranceHud; + +internal static class ControlInk +{ + internal const double LockedOpacity = 0.38; + + private static bool Slate => SlateSurface.Active; + + internal static Color Accent + { + get + { + if (!Slate) + { + return SignalTokens.Ash.Accent; + } + return SignalTokens.Slate.Accent; + } + } + + internal static Color AccentHover + { + get + { + if (!Slate) + { + return SignalTokens.Ash.AccentHover; + } + return SignalTokens.Slate.AccentHover; + } + } + + internal static Color AccentPressed + { + get + { + if (!Slate) + { + return SignalTokens.Ash.AccentPressed; + } + return SignalTokens.Slate.AccentPressed; + } + } + + internal static Color OnAccent + { + get + { + if (!Slate) + { + return SignalTokens.Ash.OnAccent; + } + return SignalTokens.Slate.OnAccent; + } + } + + internal static Color Hover + { + get + { + if (!Slate) + { + return SignalTokens.Ash.Hover; + } + return SignalTokens.Slate.Hover; + } + } + + internal static Color Pressed + { + get + { + if (!Slate) + { + return SignalTokens.Ash.Pressed; + } + return SignalTokens.Slate.Pressed; + } + } + + internal static Color Surface2 + { + get + { + if (!Slate) + { + return SignalTokens.Ash.Surface2; + } + return SignalTokens.Slate.Surface2; + } + } + + internal static Color FieldFill + { + get + { + if (!Slate) + { + return SignalTokens.Ash.FieldFill; + } + return SignalTokens.Slate.FieldFill; + } + } + + internal static Color Overlay + { + get + { + if (!Slate) + { + return SignalTokens.Ash.Surface3; + } + return SignalTokens.Slate.SlateBase; + } + } + + internal static Color Edge + { + get + { + if (!Slate) + { + return SignalTokens.Ash.BorderStrong; + } + return SignalTokens.Slate.BorderStrong; + } + } + + internal static Color Border + { + get + { + if (!Slate) + { + return SignalTokens.Ash.Border; + } + return SignalTokens.Slate.Border; + } + } + + internal static Color WindowEdge + { + get + { + if (!Slate) + { + return SignalTokens.Ash.WindowEdge; + } + return SignalTokens.Slate.WindowEdge; + } + } + + internal static Color Track + { + get + { + if (!Slate) + { + return SignalTokens.Ash.Track; + } + return SignalTokens.Slate.Track; + } + } + + internal static Color Focus + { + get + { + if (!Slate) + { + return SignalTokens.Ash.Focus; + } + return SignalTokens.Slate.Focus; + } + } + + internal static Color KnobRing + { + get + { + if (!Slate) + { + return SignalTokens.Ash.Surface1; + } + return SignalTokens.Slate.KnobRing; + } + } + + internal static Color Text1 => Theme.Text; + + internal static Color Text2 => Theme.TextDim; + + internal static Color Text3 => Theme.TextFaint; + + internal static Color TextDisabled + { + get + { + if (!Slate) + { + return SignalTokens.Ash.TextDisabled; + } + return SignalTokens.Slate.TextDisabled; + } + } + + internal static Color TextDisabledInk + { + get + { + if (!Slate) + { + return SignalTokens.Ash.TextDisabled; + } + return Over(SignalTokens.Slate.TextDisabled, SignalTokens.Slate.SlateBase); + } + } + + internal static Color Danger + { + get + { + if (!Slate) + { + return SignalTokens.Ash.Danger; + } + return SignalTokens.Slate.Danger; + } + } + + internal static Color Success + { + get + { + if (!Slate) + { + return SignalTokens.Ash.Success; + } + return SignalTokens.Slate.Success; + } + } + + internal static Color Warning + { + get + { + if (!Slate) + { + return SignalTokens.Ash.Warning; + } + return SignalTokens.Slate.Warning; + } + } + + internal static Color Info + { + get + { + if (!Slate) + { + return SignalTokens.Ash.Info; + } + return SignalTokens.Slate.Info; + } + } + + internal static Color SelectedSuffix => SignalTokens.Root.PInk2; + + internal static Color Locked(Color ink, Color ground) + { + int num = (int)Math.Round(0.299 * (double)(int)ink.R + 0.587 * (double)(int)ink.G + 0.114 * (double)(int)ink.B); + return Over(Color.FromArgb((int)Math.Round(96.9), num, num, num), Color.FromArgb(255, ground)); + } + + internal static Color Over(Color top, Color ground) + { + return Color.FromArgb(255, ground.R + top.A * (top.R - ground.R) / 255, ground.G + top.A * (top.G - ground.G) / 255, ground.B + top.A * (top.B - ground.B) / 255); + } + + internal static int Dpi(Control c) + { + return Math.Max((c.DeviceDpi > 0) ? c.DeviceDpi : 96, Tokens.Dpi); + } + + internal static int LabelInkInset(Font font) + { + int width = TextRenderer.MeasureText("A", font).Width; + int width2 = TextRenderer.MeasureText("A", font, Size.Empty, TextFormatFlags.SingleLine | TextFormatFlags.NoPadding).Width; + return Math.Max(0, (width - width2 + 2) / 4); + } + + internal static int Px(int dpi, int logical) + { + return Tokens.ScaleAt(dpi, logical); + } + + internal static float PxF(int dpi, float logical) + { + return logical * (float)dpi / 96f; + } + + internal static int Hairline(int dpi) + { + return Math.Max(1, dpi / 96); + } + + internal static Color Mix(Color a, Color b, float t) + { + t = Math.Clamp(t, 0f, 1f); + if (t <= 0f) + { + return a; + } + if (t >= 1f) + { + return b; + } + return Color.FromArgb((int)Math.Round((float)(int)a.A + (float)(b.A - a.A) * t), (int)Math.Round((float)(int)a.R + (float)(b.R - a.R) * t), (int)Math.Round((float)(int)a.G + (float)(b.G - a.G) * t), (int)Math.Round((float)(int)a.B + (float)(b.B - a.B) * t)); + } + + internal static void PaintBox(Graphics g, Size size, float radius, int line, Color fill, Color edge) + { + if (size.Width < 2 || size.Height < 2) + { + return; + } + SmoothingMode smoothingMode = g.SmoothingMode; + PixelOffsetMode pixelOffsetMode = g.PixelOffsetMode; + g.SmoothingMode = SmoothingMode.AntiAlias; + g.PixelOffsetMode = PixelOffsetMode.Half; + try + { + bool flag = edge.A > 0; + if (fill.A > 0) + { + float num = (flag ? ((float)line / 2f) : 0f); + using GraphicsPath path = Glass.RoundedPath(new RectangleF(num, num, (float)size.Width - 2f * num, (float)size.Height - 2f * num), Math.Max(0f, radius - num)); + using SolidBrush brush = new SolidBrush(fill); + g.FillPath(brush, path); + } + if (!flag) + { + return; + } + float num2 = (float)line / 2f; + using GraphicsPath path2 = Glass.RoundedPath(new RectangleF(num2, num2, size.Width - line, size.Height - line), Math.Max(0f, radius - num2)); + using Pen pen = new Pen(edge, line); + g.DrawPath(pen, path2); + } + finally + { + g.SmoothingMode = smoothingMode; + g.PixelOffsetMode = pixelOffsetMode; + } + } + + internal static void PaintFocusRing(Graphics g, Rectangle bounds, float radius, int dpi) + { + int num = Px(dpi, 2); + float num2 = (float)Px(dpi, 2) + (float)num / 2f; + SmoothingMode smoothingMode = g.SmoothingMode; + PixelOffsetMode pixelOffsetMode = g.PixelOffsetMode; + g.SmoothingMode = SmoothingMode.AntiAlias; + g.PixelOffsetMode = PixelOffsetMode.Half; + try + { + using GraphicsPath path = Glass.RoundedPath(new RectangleF((float)bounds.X - num2, (float)bounds.Y - num2, (float)bounds.Width + 2f * num2, (float)bounds.Height + 2f * num2), radius + num2); + using Pen pen = new Pen(Focus, num); + g.DrawPath(pen, path); + } + finally + { + g.SmoothingMode = smoothingMode; + g.PixelOffsetMode = pixelOffsetMode; + } + } + + internal static int FocusRingReach(int dpi) + { + return Px(dpi, 2) + Px(dpi, 2) + 1; + } +} diff --git a/VibranceHud/Controls/BrowserWontOpenDialog.cs b/VibranceHud/Controls/BrowserWontOpenDialog.cs new file mode 100644 index 0000000..7487bdb --- /dev/null +++ b/VibranceHud/Controls/BrowserWontOpenDialog.cs @@ -0,0 +1,198 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Text; +using System.Windows.Forms; +using VibranceHud.Design; + +namespace VibranceHud.Controls; + +public sealed class BrowserWontOpenDialog : SignalDialogWindow +{ + public const string Title = "We couldn't open your browser"; + + public const string Body = "PlexusX asked Windows to open your browser and nothing happened. Copy the link below, paste it into your browser, and carry on there."; + + public const string ShortSentence = "We couldn't open your browser. Copy the link and open it yourself."; + + public const string CopyLabel = "Copy link"; + + public const string CloseLabel = "Close"; + + public const string Copied = "Copied. Paste it into your browser."; + + private const int WidthLogical = 560; + + private const int LinkHeight = 32; + + private const int HintHeight = 16; + + private const int HintGap = 8; + + internal const int Chrome = 208; + + private readonly string _url; + + private readonly string _displayUrl; + + private readonly int _linkHeight; + + private readonly GlassButton _copyButton; + + private readonly Action _copy; + + private string _hint = ""; + + internal string HintForTest => _hint; + + internal static Action? InsteadOfShowingForTest { get; set; } + + internal static int MeasureHeight(string body, int width, string url = "") + { + int num = Math.Max(80, width - 48); + int val = (int)Math.Ceiling((double)(SignalDialogWindow.MeasureBody(body, Tokens.Scale(num)) * 96) / (double)Tokens.Dpi); + int num2 = (int)Math.Ceiling((double)(MeasureLink(url, Tokens.Scale(num - 24), Tokens.Scale(16), out string _) * 96) / (double)Tokens.Dpi); + return 208 + Math.Min(val, 200) + Math.Max(0, num2 - 32); + } + + internal BrowserWontOpenDialog(string url, Action copy) + { + _url = url ?? ""; + _copy = copy ?? throw new ArgumentNullException("copy"); + ShowInTaskbar = true; + TopMost = true; + Text = "PlexusX"; + AccessibleName = "We couldn't open your browser"; + AccessibleDescription = "PlexusX asked Windows to open your browser and nothing happened. Copy the link below, paste it into your browser, and carry on there. " + _url; + ChromeTitle = "We couldn't open your browser"; + ChromeBody = "PlexusX asked Windows to open your browser and nothing happened. Copy the link below, paste it into your browser, and carry on there."; + int num = S(560); + _linkHeight = Math.Max(S(32), MeasureLink(_url, num - 2 * S(24) - S(24), S(16), out _displayUrl)); + ChromeBodyHeight = Math.Min(SignalDialogWindow.MeasureBody("PlexusX asked Windows to open your browser and nothing happened. Copy the link below, paste it into your browser, and carry on there.", num - 2 * S(24)), S(200)); + ClientSize = new Size(num, BodyTop + ChromeBodyHeight + S(16) + _linkHeight + S(8) + S(16) + S(24) + S(32) + S(20)); + GlassButton glassButton = FooterButton("Close", GlassButtonKind.Secondary, "BrowserWontOpenClose"); + glassButton.Click += (object? _, EventArgs _) => + { + Close(); + }; + _copyButton = FooterButton("Copy link", GlassButtonKind.Primary, "BrowserWontOpenCopy"); + _copyButton.Click += (object? _, EventArgs _) => + { + CopyTheLink(); + }; + Controls.Add(glassButton); + Controls.Add(_copyButton); + PlaceFooter(glassButton, _copyButton); + _copyButton.TabIndex = 0; + glassButton.TabIndex = 1; + ActiveControl = _copyButton; + WindowDrag.Enable(this, this); + } + + private static int MeasureLink(string url, int width, int padding, out string display) + { + StringBuilder stringBuilder = new StringBuilder(); + int num; + for (int i = 0; i < url.Length; i += num) + { + num = 1; + int num2 = url.Length - i; + while (num < num2) + { + int num3 = (num + num2 + 1) / 2; + if (TextRenderer.MeasureText(url.Substring(i, num3), Fonts.Body, Size.Empty, TextFormatFlags.NoPrefix | TextFormatFlags.SingleLine).Width <= width) + { + num = num3; + } + else + { + num2 = num3 - 1; + } + } + if (stringBuilder.Length > 0) + { + stringBuilder.Append('\n'); + } + stringBuilder.Append(url, i, num); + } + display = stringBuilder.ToString(); + Size proposedSize = new Size(Math.Max(1, width), int.MaxValue); + return Math.Max(TextRenderer.MeasureText(display, Fonts.Body, proposedSize, TextFormatFlags.NoPrefix | TextFormatFlags.WordBreak).Height, TextRenderer.MeasureText(url, Fonts.Body, proposedSize, TextFormatFlags.NoPrefix | TextFormatFlags.WordBreak).Height) + padding; + } + + private void CopyTheLink() + { + try + { + _copy(_url); + _hint = "Copied. Paste it into your browser."; + } + catch (Exception ex) + { + CrashLog.Write(ex); + _hint = "Windows would not let us copy it. Type the link above into your browser."; + } + Invalidate(); + } + + internal void PressCopyForTest() + { + CopyTheLink(); + } + + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + if (e.KeyCode == Keys.Escape) + { + e.Handled = true; + Close(); + } + } + + protected override void OnPaint(PaintEventArgs e) + { + base.OnPaint(e); + Graphics graphics = e.Graphics; + int x = S(24); + int textWidth = TextWidth; + Rectangle rect = new Rectangle(x, ContentTop, textWidth, _linkHeight); + GraphicsState gstate = graphics.Save(); + graphics.TranslateTransform(rect.X, rect.Y); + ControlInk.PaintBox(graphics, rect.Size, S(4), ControlInk.Hairline(ChromeDpi), ControlInk.FieldFill, ControlInk.Edge); + graphics.Restore(gstate); + TextRenderer.DrawText(graphics, _displayUrl, Fonts.Body, Rectangle.Inflate(rect, -S(12), -S(8)), ControlInk.Text1, TextFormatFlags.NoPrefix | TextFormatFlags.WordBreak); + if (_hint.Length > 0) + { + TextRenderer.DrawText(graphics, _hint, Fonts.Caption, new Rectangle(x, rect.Bottom + S(8), textWidth, S(16)), ControlInk.Text2, TextFormatFlags.NoPrefix | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding); + } + } + + public static void ShowFor(IWin32Window? owner, string url) + { + Action insteadOfShowingForTest = InsteadOfShowingForTest; + if (insteadOfShowingForTest != null) + { + insteadOfShowingForTest(url); + return; + } + using BrowserWontOpenDialog browserWontOpenDialog = new BrowserWontOpenDialog(url, ToTheClipboard); + if (owner != null) + { + browserWontOpenDialog.ShowDialog(owner); + } + else + { + browserWontOpenDialog.ShowDialog(); + } + } + + private static void ToTheClipboard(string text) + { + if (string.IsNullOrEmpty(text) || TheClipboard.Put(text)) + { + return; + } + throw new InvalidOperationException("Windows would not let go of the clipboard."); + } +} diff --git a/VibranceHud/Controls/CaptionButton.cs b/VibranceHud/Controls/CaptionButton.cs new file mode 100644 index 0000000..2473cea --- /dev/null +++ b/VibranceHud/Controls/CaptionButton.cs @@ -0,0 +1,115 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; +using VibranceHud.Design; + +namespace VibranceHud.Controls; + +public sealed class CaptionButton : Control +{ + public enum Kind + { + Minimise, + Close + } + + private readonly Kind _kind; + + private bool _hot; + + private bool _down; + + internal bool HotForTest + { + set + { + _hot = value; + Invalidate(); + } + } + + internal bool PressedForTest + { + set + { + _down = value; + Invalidate(); + } + } + + public CaptionButton(Kind kind) + { + _kind = kind; + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + Cursor = Cursors.Hand; + SetStyle(ControlStyles.Selectable, value: false); + TabStop = false; + AccessibleRole = AccessibleRole.PushButton; + AccessibleName = ((kind == Kind.Close) ? "Close" : "Minimise"); + } + + protected override void OnMouseEnter(EventArgs e) + { + _hot = true; + Invalidate(); + base.OnMouseEnter(e); + } + + protected override void OnMouseLeave(EventArgs e) + { + _hot = false; + _down = false; + Invalidate(); + base.OnMouseLeave(e); + } + + protected override void OnMouseDown(MouseEventArgs e) + { + if (e.Button == MouseButtons.Left) + { + _down = true; + Invalidate(); + } + base.OnMouseDown(e); + } + + protected override void OnMouseUp(MouseEventArgs e) + { + _down = false; + Invalidate(); + base.OnMouseUp(e); + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics graphics = e.Graphics; + if (_down || _hot) + { + using SolidBrush brush = new SolidBrush(_down ? ControlInk.Pressed : ControlInk.Hover); + graphics.FillRectangle(brush, 0, 0, Width, Height); + } + using Pen pen = new Pen((_hot || _down) ? Theme.Text : Theme.TextDim, 1.4f); + PaintGlyph(graphics, pen, GlyphBox()); + } + + private void PaintGlyph(Graphics g, Pen pen, Rectangle r) + { + g.SmoothingMode = SmoothingMode.AntiAlias; + float num = (float)r.Top + (float)(r.Height + 1) / 2f; + if (_kind == Kind.Minimise) + { + g.DrawLine(pen, r.Left, num, r.Right, num); + return; + } + g.DrawLine(pen, r.Left, r.Top, r.Right, r.Bottom); + g.DrawLine(pen, r.Right, r.Top, r.Left, r.Bottom); + } + + private Rectangle GlyphBox() + { + int num = Tokens.Scale(9); + return new Rectangle((Width - num) / 2, (Height - num) / 2, num, num); + } +} diff --git a/VibranceHud/Controls/ColourWheel.cs b/VibranceHud/Controls/ColourWheel.cs new file mode 100644 index 0000000..742d766 --- /dev/null +++ b/VibranceHud/Controls/ColourWheel.cs @@ -0,0 +1,466 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.Runtime.InteropServices; +using System.Windows.Forms; +using VibranceHud.Design; + +namespace VibranceHud.Controls; + +public sealed class ColourWheel : Control +{ + private const int BarWidth = 18; + + private const int BarGap = 12; + + private Bitmap? _wheel; + + private int _wheelDiameter; + + private float _hue; + + private float _saturation; + + private float _value = 1f; + + private bool _draggingWheel; + + private bool _draggingBar; + + private readonly OutsideFocusRing _ring; + + private int _failedDiameter; + + internal Action? FailPointForTest { get; set; } + + public Color Colour + { + get + { + return FromHsv(_hue, _saturation, _value); + } + set + { + ToHsv(value, out _hue, out _saturation, out _value); + Invalidate(); + } + } + + private int Diameter => Math.Max(8, Math.Min(Width - 18 - 12, Height)); + + private Rectangle WheelRect => new Rectangle(0, (Height - Diameter) / 2, Diameter, Diameter); + + private Rectangle BarRect => new Rectangle(Width - 18, 4, 17, Math.Max(8, Height - 9)); + + public event EventHandler? ColourChanged; + + public ColourWheel() + { + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.Selectable | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + Cursor = Cursors.Hand; + TabStop = true; + AccessibleRole = AccessibleRole.Slider; + AccessibleName = "Colour picker"; + Size = new Size(180, 160); + _ring = new OutsideFocusRing(this, () => ControlInk.PxF(ControlInk.Dpi(this), 4f)); + } + + protected override void OnParentChanged(EventArgs e) + { + base.OnParentChanged(e); + _ring.Rehook(); + } + + protected override void OnMouseDown(MouseEventArgs e) + { + base.OnMouseDown(e); + Focus(); + if (BarRect.Contains(e.Location)) + { + _draggingBar = true; + DragTracker.Begin(); + TakeBar(e.Y); + } + else if (WheelRect.Contains(e.Location)) + { + _draggingWheel = true; + DragTracker.Begin(); + TakeWheel(e.Location); + } + } + + protected override void OnMouseMove(MouseEventArgs e) + { + base.OnMouseMove(e); + if (_draggingBar) + { + TakeBar(e.Y); + } + else if (_draggingWheel) + { + TakeWheel(e.Location); + } + } + + protected override void OnMouseUp(MouseEventArgs e) + { + base.OnMouseUp(e); + if (_draggingWheel || _draggingBar) + { + DragTracker.End(); + } + _draggingWheel = false; + _draggingBar = false; + } + + protected override void OnGotFocus(EventArgs e) + { + base.OnGotFocus(e); + Invalidate(); + } + + protected override void OnLostFocus(EventArgs e) + { + base.OnLostFocus(e); + Invalidate(); + } + + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + switch (e.KeyCode) + { + default: + return; + case Keys.Left: + _hue = (_hue + 355f) % 360f; + break; + case Keys.Right: + _hue = (_hue + 5f) % 360f; + break; + case Keys.Up: + _value = Math.Min(1f, _value + 0.05f); + break; + case Keys.Down: + _value = Math.Max(0f, _value - 0.05f); + break; + case Keys.Prior: + _saturation = Math.Min(1f, _saturation + 0.1f); + break; + case Keys.Next: + _saturation = Math.Max(0f, _saturation - 0.1f); + break; + case Keys.End: + case Keys.Home: + return; + } + e.Handled = true; + Invalidate(); + ColourChanged?.Invoke(this, EventArgs.Empty); + } + + internal void TestPressKey(Keys key) + { + OnKeyDown(new KeyEventArgs(key)); + } + + internal bool TestClaimsKey(Keys key) + { + return IsInputKey(key); + } + + protected override bool IsInputKey(Keys keyData) + { + if ((uint)(keyData - 33) <= 1u || (uint)(keyData - 37) <= 3u) + { + return true; + } + return base.IsInputKey(keyData); + } + + private void TakeWheel(Point p) + { + Rectangle wheelRect = WheelRect; + float num = (float)wheelRect.X + (float)wheelRect.Width / 2f; + float num2 = (float)wheelRect.Y + (float)wheelRect.Height / 2f; + float num3 = (float)p.X - num; + float num4 = (float)p.Y - num2; + float num5 = (float)wheelRect.Width / 2f; + float num6 = (float)Math.Sqrt(num3 * num3 + num4 * num4); + _saturation = Math.Clamp(num6 / num5, 0f, 1f); + _hue = (float)((Math.Atan2(num4, num3) * 180.0 / Math.PI + 360.0) % 360.0); + Invalidate(); + ColourChanged?.Invoke(this, EventArgs.Empty); + } + + private void TakeBar(int y) + { + Rectangle barRect = BarRect; + _value = 1f - Math.Clamp((float)(y - barRect.Y) / (float)barRect.Height, 0f, 1f); + Invalidate(); + ColourChanged?.Invoke(this, EventArgs.Empty); + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics g = e.Graphics; + PaintGuard.Try(this, () => + { + PaintBody(g); + }); + } + + private void PaintBody(Graphics g) + { + g.SmoothingMode = SmoothingMode.AntiAlias; + Rectangle wheelRect = WheelRect; + if (wheelRect.Width > 8) + { + EnsureWheel(wheelRect.Width); + using Region clip = g.Clip; + using (GraphicsPath graphicsPath = new GraphicsPath()) + { + graphicsPath.AddEllipse(wheelRect); + g.SetClip(graphicsPath); + if (_wheel != null) + { + g.DrawImage(_wheel, wheelRect); + } + if (_value < 1f) + { + using SolidBrush brush = new SolidBrush(Color.FromArgb((int)(255f * (1f - _value)), 0, 0, 0)); + g.FillRectangle(brush, wheelRect); + } + } + g.Clip = clip; + DrawWheelMarker(g, wheelRect); + } + DrawBar(g); + if (Focused && ShowFocusCues) + { + _ring.Show(Enabled); + } + else + { + _ring.Show(show: false); + } + if (!Enabled) + { + using (SolidBrush brush2 = new SolidBrush(Color.FromArgb(158, Theme.Background))) + { + g.FillRectangle(brush2, ClientRectangle); + } + } + } + + protected override void OnEnabledChanged(EventArgs e) + { + base.OnEnabledChanged(e); + Cursor = (Enabled ? Cursors.Hand : Cursors.Default); + Invalidate(); + } + + private void DrawWheelMarker(Graphics g, Rectangle wheel) + { + float num = (float)wheel.Width / 2f; + float num2 = (float)((double)_hue * Math.PI / 180.0); + float num3 = (float)wheel.X + num + (float)Math.Cos(num2) * num * _saturation; + float num4 = (float)wheel.Y + num + (float)Math.Sin(num2) * num * _saturation; + RectangleF rect = new RectangleF(num3 - 6f, num4 - 6f, 12f, 12f); + using (Pen pen = new Pen(Color.FromArgb(200, 0, 0, 0), 3f)) + { + g.DrawEllipse(pen, rect); + } + using Pen pen2 = new Pen(Color.White, 1.6f); + g.DrawEllipse(pen2, rect); + } + + private void DrawBar(Graphics g) + { + Rectangle barRect = BarRect; + if (barRect.Height <= 8) + { + return; + } + Color color = FromHsv(_hue, _saturation, 1f); + using (LinearGradientBrush brush = new LinearGradientBrush(barRect, color, Color.Black, 90f)) + { + g.FillRectangle(brush, barRect); + } + using (Pen pen = new Pen(Color.FromArgb(90, Theme.GlassEdge), 1f)) + { + g.DrawRectangle(pen, barRect); + } + int num = barRect.Y + (int)((1f - _value) * (float)barRect.Height); + using (Pen pen2 = new Pen(Color.FromArgb(200, 0, 0, 0), 3f)) + { + g.DrawLine(pen2, barRect.X, num, barRect.Right, num); + } + using Pen pen3 = new Pen(Color.White, 1.4f); + g.DrawLine(pen3, barRect.X, num, barRect.Right, num); + } + + private void EnsureWheel(int diameter) + { + if ((_wheel == null || _wheelDiameter != diameter) && _failedDiameter != diameter) + { + Bitmap wheel; + try + { + FailPointForTest?.Invoke("build"); + wheel = BuildWheel(diameter); + } + catch (Exception ex) when (PaintGuard.IsGdiFailure(ex)) + { + _wheel?.Dispose(); + _wheel = null; + _wheelDiameter = 0; + _failedDiameter = diameter; + throw; + } + Bitmap? wheel2 = _wheel; + _wheel = wheel; + _wheelDiameter = diameter; + _failedDiameter = 0; + wheel2?.Dispose(); + } + } + + private static Bitmap BuildWheel(int diameter) + { + Bitmap bitmap = new Bitmap(diameter, diameter, PixelFormat.Format32bppArgb); + float num = (float)diameter / 2f; + BitmapData bitmapData; + try + { + bitmapData = bitmap.LockBits(new Rectangle(0, 0, diameter, diameter), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); + } + catch + { + bitmap.Dispose(); + throw; + } + bool flag = false; + try + { + byte[] array = new byte[bitmapData.Stride]; + for (int i = 0; i < diameter; i++) + { + Array.Clear(array, 0, array.Length); + for (int j = 0; j < diameter; j++) + { + float num2 = (float)j - num + 0.5f; + float num3 = (float)i - num + 0.5f; + float num4 = (float)Math.Sqrt(num2 * num2 + num3 * num3); + if (!(num4 > num)) + { + Color color = FromHsv((float)((Math.Atan2(num3, num2) * 180.0 / Math.PI + 360.0) % 360.0), Math.Min(1f, num4 / num), 1f); + byte b = ((num4 > num - 1.2f) ? ((byte)(255f * Math.Clamp(num - num4, 0f, 1.2f) / 1.2f)) : byte.MaxValue); + int num5 = j * 4; + array[num5] = color.B; + array[num5 + 1] = color.G; + array[num5 + 2] = color.R; + array[num5 + 3] = b; + } + } + Marshal.Copy(array, 0, bitmapData.Scan0 + i * bitmapData.Stride, bitmapData.Stride); + } + flag = true; + } + finally + { + bitmap.UnlockBits(bitmapData); + if (!flag) + { + bitmap.Dispose(); + } + } + return bitmap; + } + + public static Color FromHsv(float hue, float saturation, float value) + { + hue = (hue % 360f + 360f) % 360f; + saturation = Math.Clamp(saturation, 0f, 1f); + value = Math.Clamp(value, 0f, 1f); + float num = value * saturation; + float num2 = num * (1f - Math.Abs(hue / 60f % 2f - 1f)); + float num3 = value - num; + var (num4, num5, num6) = ((hue < 60f) ? (num, num2, 0f) : ((hue < 120f) ? (num2, num, 0f) : ((hue < 180f) ? (0f, num, num2) : ((hue < 240f) ? (0f, num2, num) : ((!(hue < 300f)) ? (num, 0f, num2) : (num2, 0f, num)))))); + return Color.FromArgb(255, (int)Math.Round((num4 + num3) * 255f), (int)Math.Round((num5 + num3) * 255f), (int)Math.Round((num6 + num3) * 255f)); + } + + public static string ToHex(Color colour) + { + return $"{colour.R:X2}{colour.G:X2}{colour.B:X2}"; + } + + public static bool TryParseHex(string? text, out Color colour) + { + colour = Color.Empty; + if (string.IsNullOrWhiteSpace(text)) + { + return false; + } + string text2 = text.Trim().TrimStart('#'); + int length = text2.Length; + if ((length != 3 && length != 6) || 1 == 0) + { + return false; + } + string text3 = text2; + for (length = 0; length < text3.Length; length++) + { + if (!Uri.IsHexDigit(text3[length])) + { + return false; + } + } + if (text2.Length == 3) + { + text2 = string.Concat(text2[0], text2[0], text2[1], text2[1], text2[2], text2[2]); + } + colour = Color.FromArgb(255, Convert.ToInt32(text2.Substring(0, 2), 16), Convert.ToInt32(text2.Substring(2, 2), 16), Convert.ToInt32(text2.Substring(4, 2), 16)); + return true; + } + + public static void ToHsv(Color colour, out float hue, out float saturation, out float value) + { + float num = (float)(int)colour.R / 255f; + float num2 = (float)(int)colour.G / 255f; + float num3 = (float)(int)colour.B / 255f; + float num4 = Math.Max(num, Math.Max(num2, num3)); + float num5 = Math.Min(num, Math.Min(num2, num3)); + float num6 = num4 - num5; + value = num4; + saturation = ((num4 <= 0f) ? 0f : (num6 / num4)); + if (num6 <= 0f) + { + hue = 0f; + return; + } + float num7; + if (num4 == num) + { + num7 = 60f * ((num2 - num3) / num6 % 6f); + } + else + { + num7 = ((num4 == num2) ? (60f * ((num3 - num) / num6 + 2f)) : (60f * ((num - num2) / num6 + 4f))); + } + hue = num7; + hue = (hue % 360f + 360f) % 360f; + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _wheel?.Dispose(); + _ring.Release(); + } + base.Dispose(disposing); + } +} diff --git a/VibranceHud/Controls/CrosshairCell.cs b/VibranceHud/Controls/CrosshairCell.cs new file mode 100644 index 0000000..6b7f73f --- /dev/null +++ b/VibranceHud/Controls/CrosshairCell.cs @@ -0,0 +1,285 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; +using VibranceHud.Crosshair; +using VibranceHud.Design; + +namespace VibranceHud.Controls; + +public sealed class CrosshairCell : Control +{ + private const int HeartSize = 16; + + private bool _hover; + + private bool _hoverHeart; + + private readonly OutsideFocusRing _ring; + + private bool _active; + + private bool _favourite; + + public CrosshairGallery.GalleryItem Item { get; } + + public CrosshairConfig? PreviewStyle { get; set; } + + public bool Active + { + get + { + return _active; + } + set + { + if (_active != value) + { + _active = value; + Invalidate(); + } + } + } + + public bool Favourite + { + get + { + return _favourite; + } + set + { + if (_favourite != value) + { + _favourite = value; + Invalidate(); + } + } + } + + private static Color TextOnFill + { + get + { + if (!SlateSurface.Active) + { + return SignalTokens.Ash.TextOnFill; + } + return SignalTokens.Slate.TextOnFill; + } + } + + private Rectangle HeartRect => new Rectangle(Width - 16 - 6, 6, 16, 16); + + private static int NameStrip => Math.Max(Fonts.LineHeight(FontRole.Caption), TextRenderer.MeasureText("Hg", Fonts.Caption).Height); + + public event EventHandler? FavouriteToggled; + + public CrosshairCell(CrosshairGallery.GalleryItem item) + { + Item = item; + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.Selectable | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + Cursor = Cursors.Hand; + TabStop = true; + AccessibleRole = AccessibleRole.PushButton; + AccessibleName = item.Name; + _ring = new OutsideFocusRing(this, () => ControlInk.PxF(ControlInk.Dpi(this), 4f)); + } + + protected override void OnParentChanged(EventArgs e) + { + base.OnParentChanged(e); + _ring.Rehook(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _ring.Release(); + } + base.Dispose(disposing); + } + + protected override void OnMouseMove(MouseEventArgs e) + { + base.OnMouseMove(e); + bool flag = HeartRect.Contains(e.Location); + if (flag != _hoverHeart) + { + _hoverHeart = flag; + Invalidate(); + } + } + + protected override void OnMouseEnter(EventArgs e) + { + base.OnMouseEnter(e); + _hover = true; + Invalidate(); + } + + protected override void OnMouseLeave(EventArgs e) + { + base.OnMouseLeave(e); + _hover = false; + _hoverHeart = false; + Invalidate(); + } + + protected override void OnMouseDown(MouseEventArgs e) + { + base.OnMouseDown(e); + Focus(); + } + + protected override void OnMouseUp(MouseEventArgs e) + { + if (e.Button == MouseButtons.Left && HeartRect.Contains(e.Location)) + { + FavouriteToggled?.Invoke(this, EventArgs.Empty); + } + else + { + base.OnMouseUp(e); + } + } + + protected override void OnGotFocus(EventArgs e) + { + base.OnGotFocus(e); + Invalidate(); + } + + protected override void OnLostFocus(EventArgs e) + { + base.OnLostFocus(e); + Invalidate(); + } + + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + Keys keyCode = e.KeyCode; + if ((keyCode == Keys.Return || keyCode == Keys.Space) ? true : false) + { + e.Handled = true; + OnClick(EventArgs.Empty); + } + } + + internal void TestPressKey(Keys key) + { + OnKeyDown(new KeyEventArgs(key)); + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics graphics = e.Graphics; + graphics.SmoothingMode = SmoothingMode.AntiAlias; + RectangleF rect = new RectangleF(0f, 0f, Width, Height); + float num = Tokens.Scale(4); + using (GraphicsPath path = Glass.RoundedPath(rect, num)) + { + using SolidBrush brush = new SolidBrush((_hover && !_active) ? ControlInk.Hover : ControlInk.Surface2); + graphics.FillPath(brush, path); + } + if (_active) + { + float num2 = Tokens.Scale(2); + using Pen pen = new Pen(ControlInk.Accent, num2); + using GraphicsPath path2 = Glass.RoundedPath(RectangleF.Inflate(rect, (0f - num2) / 2f, (0f - num2) / 2f), Math.Max(1f, num - num2 / 2f)); + graphics.DrawPath(pen, path2); + } + DrawPreview(graphics); + DrawHeart(graphics); + DrawName(graphics); + if (Focused && ShowFocusCues) + { + _ring.Show(Enabled); + } + else + { + _ring.Show(show: false); + } + } + + private (Rectangle Glyph, Rectangle Name) Column() + { + int num = Tokens.Scale(36); + int num2 = Tokens.Scale(8); + int nameStrip = NameStrip; + int num3 = Math.Max(0, (Height - num - num2 - nameStrip) / 2); + return (Glyph: new Rectangle((Width - num) / 2, num3, num, num), Name: new Rectangle(2, num3 + num + num2, Width - 4, nameStrip)); + } + + private void DrawPreview(Graphics g) + { + CrosshairConfig crosshairConfig = Item.Config.Clone(); + if (PreviewStyle != null) + { + crosshairConfig.ColourArgb = PreviewStyle.ColourArgb; + crosshairConfig.Opacity = PreviewStyle.Opacity; + crosshairConfig.Outline = PreviewStyle.Outline; + } + Rectangle item = Column().Glyph; + if (item.Width > 4) + { + CrosshairRender.Draw(g, crosshairConfig, item, (float)Tokens.Scale(100) / 100f); + } + } + + private void DrawHeart(Graphics g) + { + if (!_favourite && !_hover) + { + return; + } + Rectangle heartRect = HeartRect; + Color color = (_favourite ? Theme.Text : Color.FromArgb(_hoverHeart ? 200 : 90, Theme.GlassEdge)); + using GraphicsPath path = HeartPath(heartRect); + if (_favourite) + { + using (SolidBrush brush = new SolidBrush(color)) + { + g.FillPath(brush, path); + return; + } + } + using Pen pen = new Pen(color, 1.4f); + g.DrawPath(pen, path); + } + + private static GraphicsPath HeartPath(Rectangle r) + { + GraphicsPath graphicsPath = new GraphicsPath(); + float num = r.Width; + float num2 = r.Height; + float num3 = (float)r.X + num / 2f; + graphicsPath.AddBezier(num3, (float)r.Y + num2 * 0.28f, num3, r.Y, r.X, (float)r.Y + num2 * 0.05f, r.X, (float)r.Y + num2 * 0.38f); + graphicsPath.AddBezier(r.X, (float)r.Y + num2 * 0.38f, r.X, (float)r.Y + num2 * 0.68f, num3, (float)r.Y + num2 * 0.82f, num3, r.Bottom); + graphicsPath.AddBezier(num3, r.Bottom, num3, (float)r.Y + num2 * 0.82f, r.Right, (float)r.Y + num2 * 0.68f, r.Right, (float)r.Y + num2 * 0.38f); + graphicsPath.AddBezier(r.Right, (float)r.Y + num2 * 0.38f, r.Right, (float)r.Y + num2 * 0.05f, num3, r.Y, num3, (float)r.Y + num2 * 0.28f); + graphicsPath.CloseFigure(); + return graphicsPath; + } + + private void DrawName(Graphics g) + { + Graphics dc = g; + string name = Item.Name; + Font caption = Fonts.Caption; + Rectangle item = Column().Name; + Color foreColor; + if (Enabled) + { + foreColor = ((_active || _hover) ? ControlInk.Text1 : TextOnFill); + } + else + { + foreColor = ControlInk.TextDisabledInk; + } + TextRenderer.DrawText(dc, name, caption, item, foreColor, TextFormatFlags.EndEllipsis | TextFormatFlags.HorizontalCenter | TextFormatFlags.NoPrefix | TextFormatFlags.VerticalCenter); + } +} diff --git a/VibranceHud/Controls/GameProfileManagerSection.cs b/VibranceHud/Controls/GameProfileManagerSection.cs new file mode 100644 index 0000000..c590ecd --- /dev/null +++ b/VibranceHud/Controls/GameProfileManagerSection.cs @@ -0,0 +1,361 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Linq; +using System.Windows.Forms; +using VibranceHud.Design; + +namespace VibranceHud.Controls; + +public sealed class GameProfileManagerSection +{ + private sealed class Row + { + public GameProfile Profile; + + public Label Name; + + public Label Detail; + + public GlassButton Rename; + + public GlassButton Delete; + } + + private readonly Control _parent; + + private readonly Font _bodyFont; + + private readonly Font _captionFont; + + private readonly Func? _isRunning; + + private readonly Func> _load; + + private readonly Action _save; + + private readonly Action _remove; + + private readonly Func? _runningGameName; + + private readonly Action? _saveCurrentLook; + + private readonly Label _caption; + + private readonly Label _empty; + + private readonly GlassButton _saveNow; + + private readonly Label _saveHint; + + private readonly List _rows = new List(); + + public const string RowNameControl = "profileRowName"; + + public const string RowDetailControl = "profileRowDetail"; + + public const string SaveNowControl = "profileSaveNow"; + + public const string SaveHintControl = "profileSaveHint"; + + private bool _visible = true; + + private static int RowHeight => Tokens.Scale(54); + + private static int HeaderHeight => Math.Max(Tokens.Scale(22), Tokens.Scale(28)); + + private static int HintHeight => Tokens.Scale(20); + + public int PreferredHeight + { + get + { + int num = HeaderHeight + Tokens.Scale(6); + if (_saveHint.Visible) + { + num += HintHeight + Tokens.Scale(6); + } + return num + ((_rows.Count == 0) ? Tokens.Scale(36) : (_rows.Count * RowHeight)); + } + } + + public event Action? Changed; + + public GameProfileManagerSection(Control parent, Font captionFont, Font bodyFont, Func>? load = null, Action? save = null, Action? remove = null, Func? isRunning = null, Func? runningGameName = null, Action? saveCurrentLook = null) + { + _parent = parent; + _bodyFont = bodyFont; + _captionFont = captionFont; + _isRunning = isRunning; + _runningGameName = runningGameName; + _saveCurrentLook = saveCurrentLook; + _load = load ?? new Func>(GameProfileStore.Load); + _save = save ?? new Action(GameProfileStore.Set); + _remove = remove ?? new Action(GameProfileStore.Remove); + _caption = new Label + { + Text = UiHelpers.Spaced("SAVED GAME PROFILES"), + Font = captionFont, + ForeColor = Theme.TextDim, + BackColor = Color.Transparent, + AutoSize = false, + TextAlign = ContentAlignment.MiddleLeft + }; + _parent.Controls.Add(_caption); + _empty = new Label + { + Text = "No saved profiles yet. Pick a game above and save the look on screen, and it will show up here.", + Font = bodyFont, + ForeColor = Theme.TextDim, + BackColor = Color.Transparent, + AutoSize = false, + TextAlign = ContentAlignment.TopLeft + }; + _parent.Controls.Add(_empty); + _saveNow = new GlassButton + { + Text = "Save my colours", + Kind = GlassButtonKind.Primary, + Name = "profileSaveNow", + Visible = false + }; + _saveNow.Click += (object? _, EventArgs _) => + { + SaveCurrentLookFlow(); + }; + _parent.Controls.Add(_saveNow); + _saveHint = new Label + { + Text = "Open a game and this is where you save the colours you're looking at.", + Font = bodyFont, + ForeColor = Theme.TextDim, + BackColor = Color.Transparent, + AutoSize = false, + TextAlign = ContentAlignment.MiddleLeft, + Name = "profileSaveHint", + Visible = false + }; + _parent.Controls.Add(_saveHint); + Refresh(); + } + + public void Refresh() + { + foreach (Row row2 in _rows) + { + _parent.Controls.Remove(row2.Name); + _parent.Controls.Remove(row2.Detail); + _parent.Controls.Remove(row2.Rename); + _parent.Controls.Remove(row2.Delete); + row2.Name.Dispose(); + row2.Detail.Dispose(); + row2.Rename.Dispose(); + row2.Delete.Dispose(); + } + _rows.Clear(); + foreach (GameProfile item in (from p in _load() + orderby IsRunningNow(p) descending, ChangesSomething(p) descending + select p).ThenBy((GameProfile p) => p.DisplayName, StringComparer.OrdinalIgnoreCase).ToList()) + { + GameProfile captured = item; + Row row = new Row + { + Profile = captured + }; + bool flag = IsRunningNow(captured); + row.Name = new Label + { + Text = (flag ? (captured.DisplayName + " ● running now") : captured.DisplayName), + Font = _bodyFont, + ForeColor = (flag ? Theme.Accent : Theme.Text), + BackColor = Color.Transparent, + AutoSize = false, + TextAlign = ContentAlignment.MiddleLeft, + Visible = _visible + }; + row.Name.Name = "profileRowName"; + _parent.Controls.Add(row.Name); + row.Detail = new Label + { + Text = (ChangesSomething(captured) ? GameProfileSection.Describe(captured) : "Changes nothing yet — set your colours with this game open, then save."), + Font = _captionFont, + ForeColor = Theme.TextDim, + BackColor = Color.Transparent, + AutoSize = false, + TextAlign = ContentAlignment.MiddleLeft, + Visible = _visible + }; + row.Detail.Name = "profileRowDetail"; + _parent.Controls.Add(row.Detail); + row.Rename = new GlassButton + { + Text = "Rename", + Kind = GlassButtonKind.Secondary, + Visible = _visible + }; + row.Rename.Click += (object? _, EventArgs _) => + { + RenameFlow(captured); + }; + _parent.Controls.Add(row.Rename); + row.Delete = new GlassButton + { + Text = "Delete", + Kind = GlassButtonKind.Secondary, + Visible = _visible + }; + row.Delete.Click += (object? _, EventArgs _) => + { + DeleteFlow(captured); + }; + _parent.Controls.Add(row.Delete); + _rows.Add(row); + } + RefreshSaveAffordance(); + Changed?.Invoke(); + } + + private void RefreshSaveAffordance() + { + string text = null; + if (_saveCurrentLook != null) + { + try + { + text = _runningGameName?.Invoke(); + } + catch + { + text = null; + } + } + bool flag = _visible && _saveCurrentLook != null && !string.IsNullOrWhiteSpace(text); + _saveNow.Visible = flag; + if (flag) + { + _saveNow.Text = "Save my colours for " + GameProfileSection.Shorten(text); + } + bool flag2 = _visible && _saveCurrentLook != null && !flag; + _saveHint.Visible = flag2; + _saveHint.Text = ((_rows.Count == 0) ? "No game profiles yet. Open a game, set your colours, then save them here." : "Open a game and this is where you save the colours you're looking at."); + _empty.Visible = _visible && _rows.Count == 0 && !flag2; + } + + private void SaveCurrentLookFlow() + { + _saveCurrentLook?.Invoke(); + Refresh(); + } + + public void SetVisible(bool visible) + { + _visible = visible; + _caption.Visible = visible; + RefreshSaveAffordance(); + foreach (Row row in _rows) + { + row.Name.Visible = visible; + row.Rename.Visible = visible; + row.Delete.Visible = visible; + } + } + + private void RenameFlow(GameProfile profile) + { + string text = Prompt.Ask("Rename profile", profile.DisplayName); + if (!string.IsNullOrWhiteSpace(text)) + { + Rename(profile.GameId, text); + } + } + + private void DeleteFlow(GameProfile profile) + { + if (GlassDialog.Show(_parent.FindForm(), "Delete this profile?", $"\"{profile.DisplayName}\" will be removed. PlexusX will stop switching to it when {profile.DisplayName} opens. There is no undo - saving a new " + "profile for it is the only way back.", GlassDialogButtons.Destructive, GlassDialogTone.Warning, "Delete profile", "Keep it") == DialogResult.Yes) + { + Delete(profile.GameId); + } + } + + private void Rename(string gameId, string newName) + { + GameProfile gameProfile = _load().FirstOrDefault((GameProfile p) => p.GameId == gameId); + if (gameProfile != null) + { + gameProfile.DisplayName = newName; + _save(gameProfile); + Refresh(); + } + } + + private void Delete(string gameId) + { + _remove(gameId); + Refresh(); + } + + internal void TestRename(string gameId, string newName) + { + Rename(gameId, newName); + } + + internal void TestDelete(string gameId) + { + Delete(gameId); + } + + private bool IsRunningNow(GameProfile p) + { + try + { + return _isRunning?.Invoke(p.GameId) ?? false; + } + catch + { + return false; + } + } + + private static bool ChangesSomething(GameProfile p) + { + return GameProfileSection.ChangesAnything(p); + } + + public void Place(int x, int y, int width) + { + int num = Tokens.Scale(22); + int headerHeight = HeaderHeight; + int num2 = Tokens.Scale(8); + int num3 = Math.Min(Tokens.Scale(196), Math.Max(Tokens.Scale(120), width / 2)); + int num4 = Tokens.Scale(28); + _caption.SetBounds(x, y + (headerHeight - num) / 2, Math.Max(Tokens.Scale(40), width - num3 - num2), num); + _saveNow.SetBounds(x + width - num3, y + (headerHeight - num4) / 2, num3, num4); + y += headerHeight + Tokens.Scale(6); + _saveHint.SetBounds(x, y, width, HintHeight); + if (_saveHint.Visible) + { + y += HintHeight + Tokens.Scale(6); + } + _empty.SetBounds(x, y, width, Tokens.Scale(36)); + if (_rows.Count == 0) + { + return; + } + int num5 = Tokens.Scale(76); + int num6 = Tokens.Scale(28); + int num7 = Tokens.Scale(8); + int rowHeight = RowHeight; + int num8 = width - 2 * num5 - 2 * num7; + int num9 = Tokens.Scale(20); + int num10 = Math.Max(Tokens.Scale(18), TextRenderer.MeasureText("Hg", Fonts.Body).Height); + int num11 = (rowHeight - (num9 + num10)) / 2; + foreach (Row row in _rows) + { + row.Name.SetBounds(x, y + num11, num8, num9); + row.Detail.SetBounds(x, y + num11 + num9, num8, num10); + row.Rename.SetBounds(x + num8 + num7, y + (rowHeight - num6) / 2, num5, num6); + row.Delete.SetBounds(x + num8 + 2 * num7 + num5, y + (rowHeight - num6) / 2, num5, num6); + y += rowHeight; + } + } +} diff --git a/VibranceHud/Controls/GlassDialog.cs b/VibranceHud/Controls/GlassDialog.cs new file mode 100644 index 0000000..39f3568 --- /dev/null +++ b/VibranceHud/Controls/GlassDialog.cs @@ -0,0 +1,178 @@ +using System; +using System.Drawing; +using System.Windows.Forms; +using VibranceHud.Design; + +namespace VibranceHud.Controls; + +public sealed class GlassDialog : SignalDialogWindow +{ + private const int WidthLogical = 460; + + private const int MaxBodyLogical = 420; + + private readonly GlassDialogButtons _buttons; + + private readonly GlassButton _safe; + + private readonly GlassButton? _action; + + internal GlassButton TestOpeningButton => (GlassButton)ActiveControl; + + internal GlassButton? TestActionButton => _action; + + internal GlassButton TestSafeButton => _safe; + + internal static Func? InsteadOfShowingForTest { get; set; } + + public static int ButtonCount(GlassDialogButtons b) + { + if (b != GlassDialogButtons.Ok) + { + return 2; + } + return 1; + } + + public static int MeasureHeight(string body, int width) + { + int logical = Math.Max(80, width - 48); + int val = (int)Math.Ceiling((double)(SignalDialogWindow.MeasureBody(body, Tokens.Scale(logical)) * 96) / (double)Tokens.Dpi); + return 136 + Math.Min(val, 420); + } + + internal GlassDialog(string title, string body, GlassDialogButtons buttons, GlassDialogTone tone, string? primaryText = null, string? secondaryText = null) + { + GlassDialog glassDialog = this; + _buttons = buttons; + ChromeTitle = title ?? "PlexusX"; + ChromeBody = body ?? ""; + Text = ChromeTitle; + AccessibleName = ChromeTitle; + AccessibleDescription = ChromeBody; + int num = S(460); + ChromeBodyHeight = Math.Min(SignalDialogWindow.MeasureBody(ChromeBody, num - 2 * S(24)), S(420)); + ClientSize = new Size(num, BodyTop + ChromeBodyHeight + S(24) + S(32) + S(20)); + if (buttons == GlassDialogButtons.Ok) + { + _safe = FooterButton(secondaryText ?? primaryText ?? "Close", GlassButtonKind.Secondary, "DialogClose"); + _safe.Click += (object? _, EventArgs _) => + { + glassDialog.Finish(DialogResult.OK); + }; + Controls.Add(_safe); + PlaceFooter(_safe); + } + else + { + bool flag = buttons == GlassDialogButtons.Destructive; + _action = FooterButton(primaryText ?? "Continue", flag ? GlassButtonKind.Destructive : GlassButtonKind.Primary, "DialogAction"); + _action.Click += (object? _, EventArgs _) => + { + glassDialog.Finish(Affirmative(buttons)); + }; + _safe = FooterButton(secondaryText ?? "Cancel", GlassButtonKind.Secondary, "DialogSafe"); + _safe.Click += (object? _, EventArgs _) => + { + glassDialog.Finish(Negative(buttons)); + }; + Controls.Add(_safe); + Controls.Add(_action); + PlaceFooter(_safe, _action); + } + GlassDialogButtons glassDialogButtons = buttons; + GlassButton glassButton = (((uint)(glassDialogButtons - 1) <= 1u) ? _action : _safe); + if (_action != null) + { + _safe.TabIndex = ((glassButton != _safe) ? 1 : 0); + _action.TabIndex = ((glassButton != _action) ? 1 : 0); + } + ActiveControl = glassButton; + KeyDown += (object? _, KeyEventArgs e) => + { + Keys keyCode = e.KeyCode; + if ((keyCode == Keys.Return || keyCode == Keys.Escape) ? true : false) + { + e.Handled = true; + e.SuppressKeyPress = true; + glassDialog.Answer(e.KeyCode); + } + }; + WindowDrag.Enable(this, this); + } + + private void Answer(Keys key) + { + if (key == Keys.Escape) + { + Finish(Negative(_buttons)); + return; + } + GlassDialogButtons buttons = _buttons; + bool flag = (uint)(buttons - 1) <= 1u; + Finish(flag ? Affirmative(_buttons) : Negative(_buttons)); + } + + protected override bool ProcessDialogKey(Keys keyData) + { + bool flag = (keyData & (Keys.Control | Keys.Alt)) == 0; + if (flag) + { + Keys keys = keyData & Keys.KeyCode; + bool flag2 = ((keys == Keys.Return || keys == Keys.Escape) ? true : false); + flag = flag2; + } + if (flag) + { + Answer(keyData & Keys.KeyCode); + return true; + } + return base.ProcessDialogKey(keyData); + } + + private static DialogResult Affirmative(GlassDialogButtons b) + { + if ((uint)(b - 2) <= 2u) + { + return DialogResult.Yes; + } + return DialogResult.OK; + } + + private static DialogResult Negative(GlassDialogButtons b) + { + switch (b) + { + case GlassDialogButtons.Ok: + return DialogResult.OK; + case GlassDialogButtons.YesNo: + case GlassDialogButtons.Destructive: + case GlassDialogButtons.ConfirmSafeEnter: + return DialogResult.No; + default: + return DialogResult.Cancel; + } + } + + private void Finish(DialogResult result) + { + DialogResult = result; + Close(); + } + + internal void TestPressKey(Keys key) + { + Answer(key); + } + + public static DialogResult Show(IWin32Window? owner, string title, string body, GlassDialogButtons buttons = GlassDialogButtons.Ok, GlassDialogTone tone = GlassDialogTone.Info, string? primaryText = null, string? secondaryText = null) + { + Func insteadOfShowingForTest = InsteadOfShowingForTest; + if (insteadOfShowingForTest != null) + { + return insteadOfShowingForTest(title, body); + } + using GlassDialog glassDialog = new GlassDialog(title, body, buttons, tone, primaryText, secondaryText); + return (owner != null) ? glassDialog.ShowDialog(owner) : glassDialog.ShowDialog(); + } +} diff --git a/VibranceHud/Controls/GlassDialogButtons.cs b/VibranceHud/Controls/GlassDialogButtons.cs new file mode 100644 index 0000000..50e9cdc --- /dev/null +++ b/VibranceHud/Controls/GlassDialogButtons.cs @@ -0,0 +1,10 @@ +namespace VibranceHud.Controls; + +public enum GlassDialogButtons +{ + Ok, + OkCancel, + YesNo, + Destructive, + ConfirmSafeEnter +} diff --git a/VibranceHud/Controls/GlassDialogTone.cs b/VibranceHud/Controls/GlassDialogTone.cs new file mode 100644 index 0000000..bab34bd --- /dev/null +++ b/VibranceHud/Controls/GlassDialogTone.cs @@ -0,0 +1,8 @@ +namespace VibranceHud.Controls; + +public enum GlassDialogTone +{ + Info, + Warning, + Danger +} diff --git a/VibranceHud/Controls/GlassScrollBar.cs b/VibranceHud/Controls/GlassScrollBar.cs new file mode 100644 index 0000000..80c63fa --- /dev/null +++ b/VibranceHud/Controls/GlassScrollBar.cs @@ -0,0 +1,203 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; + +namespace VibranceHud.Controls; + +public sealed class GlassScrollBar : Control +{ + private int _value; + + private int _maximum = 100; + + private int _viewport = 10; + + private bool _hover; + + private bool _dragging; + + private int _dragOffset; + + public int Maximum + { + get + { + return _maximum; + } + set + { + _maximum = Math.Max(0, value); + Clamp(); + Invalidate(); + } + } + + public int Viewport + { + get + { + return _viewport; + } + set + { + _viewport = Math.Max(1, value); + Clamp(); + Invalidate(); + } + } + + public int Value + { + get + { + return _value; + } + set + { + int num = Math.Clamp(value, 0, Math.Max(0, _maximum - _viewport)); + if (num != _value) + { + _value = num; + Invalidate(); + } + } + } + + public bool Needed => _maximum > _viewport; + + private int TrackTop => 4; + + private int TrackHeight => Math.Max(1, Height - 8); + + private int ThumbHeight + { + get + { + if (!Needed) + { + return TrackHeight; + } + float num = (float)_viewport / (float)_maximum; + return Math.Max(28, (int)((float)TrackHeight * num)); + } + } + + private int ThumbTop + { + get + { + if (!Needed) + { + return TrackTop; + } + float num = (float)_value / (float)(_maximum - _viewport); + return TrackTop + (int)((float)(TrackHeight - ThumbHeight) * num); + } + } + + public event EventHandler? Scrolled; + + public GlassScrollBar() + { + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + Width = 8; + TabStop = false; + } + + private void Clamp() + { + Value = _value; + } + + protected override void OnMouseEnter(EventArgs e) + { + base.OnMouseEnter(e); + _hover = true; + Invalidate(); + } + + protected override void OnMouseLeave(EventArgs e) + { + base.OnMouseLeave(e); + _hover = false; + Invalidate(); + } + + protected override void OnMouseDown(MouseEventArgs e) + { + base.OnMouseDown(e); + if (e.Button == MouseButtons.Left && Needed) + { + if (e.Y >= ThumbTop && e.Y <= ThumbTop + ThumbHeight) + { + _dragging = true; + DragTracker.BeginScrollBar(); + _dragOffset = e.Y - ThumbTop; + } + else + { + MoveThumbTo(e.Y - ThumbHeight / 2); + } + } + } + + protected override void OnMouseMove(MouseEventArgs e) + { + base.OnMouseMove(e); + if (_dragging) + { + MoveThumbTo(e.Y - _dragOffset); + } + } + + protected override void OnMouseUp(MouseEventArgs e) + { + base.OnMouseUp(e); + if (_dragging) + { + _dragging = false; + DragTracker.EndScrollBar(); + } + } + + private void MoveThumbTo(int top) + { + if (!Needed) + { + return; + } + int num = TrackHeight - ThumbHeight; + if (num > 0) + { + int num2 = (int)Math.Round(Math.Clamp((float)(top - TrackTop) / (float)num, 0f, 1f) * (float)(_maximum - _viewport)); + if (num2 != _value) + { + _value = num2; + Invalidate(); + Scrolled?.Invoke(this, EventArgs.Empty); + } + } + } + + protected override void OnPaint(PaintEventArgs e) + { + if (!Needed) + { + return; + } + Graphics graphics = e.Graphics; + graphics.SmoothingMode = SmoothingMode.AntiAlias; + float radius = Math.Max(1f, (float)(Width - 4) / 2f); + using (GraphicsPath path = Glass.RoundedPath(new RectangleF(2f, TrackTop, Math.Max(1, Width - 4), TrackHeight), radius)) + { + using SolidBrush brush = new SolidBrush(Color.FromArgb(28, Theme.GlassEdge)); + graphics.FillPath(brush, path); + } + using GraphicsPath path2 = Glass.RoundedPath(new RectangleF(2f, ThumbTop, Math.Max(1, Width - 4), ThumbHeight), radius); + Color baseColor = (Theme.IsLight ? Theme.AccentDim : Theme.Accent); + using SolidBrush brush2 = new SolidBrush((_dragging || _hover) ? Color.FromArgb(_dragging ? 200 : 150, baseColor) : Color.FromArgb(Theme.IsLight ? 60 : 90, Theme.Text)); + graphics.FillPath(brush2, path2); + } +} diff --git a/VibranceHud/Controls/GlassShellForm.cs b/VibranceHud/Controls/GlassShellForm.cs new file mode 100644 index 0000000..a1a5c85 --- /dev/null +++ b/VibranceHud/Controls/GlassShellForm.cs @@ -0,0 +1,138 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; +using VibranceHud.Design; + +namespace VibranceHud.Controls; + +public class GlassShellForm : SignalDialogWindow +{ + private readonly string _title; + + private Rectangle _closeRect; + + private bool _overClose; + + private bool _showClose = true; + + private bool _paintsTitle = true; + + protected static int Pad => Tokens.Scale(24); + + protected new static int ContentTop => Tokens.Scale(56); + + public bool ShowClose + { + get + { + return _showClose; + } + set + { + if (_showClose != value) + { + _showClose = value; + if (!value) + { + _closeRect = Rectangle.Empty; + _overClose = false; + } + Invalidate(); + } + } + } + + public bool PaintsTitle + { + get + { + return _paintsTitle; + } + set + { + if (_paintsTitle != value) + { + _paintsTitle = value; + Invalidate(); + } + } + } + + public GlassShellForm(string title) + { + _title = title; + Text = title; + AccessibleName = title; + KeyDown += (object? _, KeyEventArgs e) => + { + if (e.KeyCode == Keys.Escape) + { + CancelShell(); + } + }; + WindowDrag.Enable(this, this, (Point p) => _closeRect.Contains(p)); + } + + protected virtual void CancelShell() + { + DialogResult = DialogResult.Cancel; + Close(); + } + + protected override void OnMouseMove(MouseEventArgs e) + { + base.OnMouseMove(e); + bool flag = _closeRect.Contains(e.Location); + if (flag != _overClose) + { + _overClose = flag; + Invalidate(new Rectangle(_closeRect.X - 4, _closeRect.Y - 4, _closeRect.Width + 8, _closeRect.Height + 8)); + } + } + + protected override void OnMouseLeave(EventArgs e) + { + base.OnMouseLeave(e); + if (_overClose) + { + _overClose = false; + Invalidate(); + } + } + + protected override void OnMouseUp(MouseEventArgs e) + { + base.OnMouseUp(e); + if (e.Button == MouseButtons.Left && _closeRect.Contains(e.Location)) + { + CancelShell(); + } + } + + protected override void OnPaint(PaintEventArgs e) + { + base.OnPaint(e); + Graphics graphics = e.Graphics; + int num = S(24); + int num2 = S(28); + _closeRect = (_showClose ? new Rectangle(Width - num2 - S(12), S(12), num2, num2) : Rectangle.Empty); + int num3 = (_showClose ? (_closeRect.Left - S(8)) : (Width - num)); + if (_paintsTitle) + { + TextRenderer.DrawText(graphics, _title, Fonts.Title, new Rectangle(SignalDialogWindow.Ink(num + S(2), Fonts.Title), S(18), num3 - (num + S(2)) + SignalDialogWindow.GlyphPad(Fonts.Title), S(28)), Theme.Text, TextFormatFlags.EndEllipsis | TextFormatFlags.NoPrefix | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter); + } + if (_showClose) + { + if (_overClose) + { + GraphicsState gstate = graphics.Save(); + graphics.TranslateTransform(_closeRect.X, _closeRect.Y); + ControlInk.PaintBox(graphics, _closeRect.Size, S(4), ControlInk.Hairline(ChromeDpi), ControlInk.Hover, Color.Empty); + graphics.Restore(gstate); + } + int num4 = S(16); + SignalIcons.Draw(graphics, SignalIcon.Close, new RectangleF((float)_closeRect.X + (float)(num2 - num4) / 2f, (float)_closeRect.Y + (float)(num2 - num4) / 2f, num4, num4), _overClose ? ControlInk.Text1 : ControlInk.Text2); + } + } +} diff --git a/VibranceHud/Controls/HueWheel.cs b/VibranceHud/Controls/HueWheel.cs new file mode 100644 index 0000000..9627988 --- /dev/null +++ b/VibranceHud/Controls/HueWheel.cs @@ -0,0 +1,830 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.Linq; +using System.Runtime.InteropServices; +using System.Windows.Forms; +using VibranceHud.Design; +using VibranceHud.Theming; + +namespace VibranceHud.Controls; + +public sealed class HueWheel : Control +{ + internal readonly record struct RingNameSlot(int Degrees, string Name, Rectangle Rect, PointF TickEnd); + + public const int MinHue = -180; + + public const int MaxHue = 180; + + private static readonly float RefR = 0.82f; + + private static readonly float RefG = 0.38f; + + private static readonly float RefB = 0.34f; + + private Bitmap? _disc; + + private int _hue; + + private bool _dragging; + + public const int MinDarkenHue = 0; + + public const int MaxDarkenHue = 359; + + public const int MinDarken = 0; + + public const int MaxDarken = 400; + + private bool _darkenMode; + + private int _darkenHue = 120; + + private int _darken; + + private bool _hasDarkenSelection; + + private const int RingBandPx = 28; + + private bool _ring; + + private Color _surface = Color.Empty; + + private static readonly (int Degrees, string Name)[] RingNames = new (int, string)[6] + { + (0, "Red"), + (60, "Yellow"), + (120, "Green"), + (180, "Cyan"), + (240, "Blue"), + (300, "Magenta") + }; + + private (int Diameter, bool Ring, bool Darken) _failedDisc = (Diameter: -1, Ring: false, Darken: false); + + public bool DarkenMode + { + get + { + return _darkenMode; + } + set + { + if (_darkenMode != value) + { + _darkenMode = value; + TabStop = value; + _disc?.Dispose(); + _disc = null; + Invalidate(); + } + } + } + + public int DarkenHue + { + get + { + return _darkenHue; + } + set + { + int num = (value % 360 + 360) % 360; + if (num != _darkenHue || !_hasDarkenSelection) + { + _darkenHue = num; + _hasDarkenSelection = true; + Invalidate(); + } + } + } + + public bool Ring + { + get + { + return _ring; + } + set + { + if (_ring != value) + { + _ring = value; + _disc?.Dispose(); + _disc = null; + Invalidate(); + } + } + } + + public Color Surface + { + get + { + return _surface; + } + set + { + _surface = value; + Invalidate(); + } + } + + public string CentreText + { + get + { + if (!_darkenMode) + { + if (_hue != 0) + { + return "Colours turned"; + } + return "No turn"; + } + if (_hasDarkenSelection) + { + if (_darken != 0) + { + return HueName(_darkenHue) + " darker"; + } + return "Not darkened"; + } + return "Pick a colour to darken"; + } + } + + private int RingAngle + { + get + { + if (!_darkenMode) + { + if (_hue < 0) + { + return 360 + _hue; + } + return _hue; + } + return _darkenHue; + } + } + + internal Action? FailPointForTest { get; set; } + + public int Darken + { + get + { + return _darken; + } + set + { + int num = Math.Clamp(value, 0, 400); + if (num != _darken) + { + _darken = num; + if (num > 0) + { + _hasDarkenSelection = true; + } + Invalidate(); + } + } + } + + public int Hue + { + get + { + return _hue; + } + set + { + int num = Math.Clamp(value, -180, 180); + if (num != _hue) + { + _hue = num; + Invalidate(); + } + } + } + + private int Diameter + { + get + { + if (!_ring) + { + return Math.Max(1, Math.Min(Width, Height) - Tokens.Scale(6)); + } + return Math.Max(1, Math.Min(Tokens.Scale(176), Math.Min(Width, Height) - Tokens.Scale(80))); + } + } + + private bool SeeThrough + { + get + { + if (!(Parent is CardPanel)) + { + if (SlateSurface.Active) + { + return AppBackground.IsSet; + } + return false; + } + return true; + } + } + + public event EventHandler? DarkenChanged; + + public event EventHandler? HueChanged; + + internal static string NearestName(int degrees) + { + return HueName(degrees); + } + + private static string HueName(int degrees) + { + int d = (degrees % 360 + 360) % 360; + return RingNames.OrderBy(((int Degrees, string Name) n) => Math.Min(Math.Abs(n.Degrees - d), 360 - Math.Abs(n.Degrees - d))).First().Name; + } + + private void PaintRing(Graphics g) + { + g.SmoothingMode = SmoothingMode.AntiAlias; + g.PixelOffsetMode = PixelOffsetMode.Half; + int diameter = Diameter; + float num = (float)Width / 2f; + float num2 = (float)Height / 2f; + float num3 = (float)diameter / 2f; + float num4 = S(28f); + float num5 = num3 - num4; + Bitmap bitmap = Disc(); + if (bitmap != null) + { + g.DrawImageUnscaled(bitmap, (int)(num - num3), (int)(num2 - num3)); + } + using (Pen pen = new Pen(ControlInk.Border, Math.Max(1f, S(1f)))) + { + g.DrawEllipse(pen, num - num3 - S(0.5f), num2 - num3 - S(0.5f), 2f * num3 + S(1f), 2f * num3 + S(1f)); + g.DrawEllipse(pen, num - num5 + S(0.5f), num2 - num5 + S(0.5f), 2f * num5 - S(1f), 2f * num5 - S(1f)); + } + if (_darkenMode) + { + float num6 = num5 - S(8f); + using Pen pen2 = new Pen(ControlInk.Track, S(3f)); + g.DrawEllipse(pen2, num - num6, num2 - num6, 2f * num6, 2f * num6); + if (_darken > 0) + { + float num7 = (float)_darken / 400f * 50f; + using Pen pen3 = new Pen(ControlInk.Text1, S(3f)) + { + StartCap = LineCap.Round, + EndCap = LineCap.Round + }; + g.DrawArc(pen3, num - num6, num2 - num6, 2f * num6, 2f * num6, (float)_darkenHue - num7, 2f * num7); + } + } + int ringAngle = RingAngle; + using (Pen pen4 = new Pen(ControlInk.Text2, S(1.5f))) + { + using Pen pen5 = new Pen(ControlInk.TextDisabled, Math.Max(1f, S(1f))); + for (int i = 0; i < 360; i += 30) + { + bool flag = i % 60 == 0; + double num8 = (double)i * Math.PI / 180.0; + float num9 = (float)Math.Cos(num8); + float num10 = (float)Math.Sin(num8); + float num11 = num3 + S(3f); + float num12 = num3 + S(flag ? 9 : 6); + g.DrawLine(flag ? pen4 : pen5, num + num9 * num11, num2 + num10 * num11, num + num9 * num12, num2 + num10 * num12); + } + } + Font captionBold = Fonts.CaptionBold; + RingNameSlot[] array = RingNameSlots(g, num, num2, num3); + for (int j = 0; j < array.Length; j++) + { + RingNameSlot ringNameSlot = array[j]; + bool flag2 = (!_darkenMode || _hasDarkenSelection) && ringAngle % 60 == 0 && ringNameSlot.Degrees == ringAngle; + TextRenderer.DrawText(g, ringNameSlot.Name, captionBold, ringNameSlot.Rect.Location, flag2 ? ControlInk.Text1 : ControlInk.Text3, TextFormatFlags.NoPadding); + } + HueAt(ringAngle, out var r, out var g2, out var b); + Color color = Hsl(r, g2, b); + TextFormatFlags flags = TextFormatFlags.HorizontalCenter | TextFormatFlags.WordBreak | TextFormatFlags.NoPadding; + int num13 = (int)S(100f); + int num14 = (int)Math.Round(num - (float)num13 / 2f); + int num15 = Fonts.LineHeight(FontRole.Caption); + int num16 = Math.Max(num15, (int)Math.Ceiling((float)TextRenderer.MeasureText(g, CentreText, Fonts.Caption, new Size(num13, int.MaxValue), flags).Height / (float)num15) * num15); + bool flag3 = !_darkenMode || _hasDarkenSelection; + float num17 = (flag3 ? S(22f) : 0f); + float num18 = S(46f) + S(5f) + S(1f) + num17 + S(1f) + (float)num16; + float num19 = num2 - num18 / 2f; + float num20 = S(46f); + if (flag3) + { + using (SolidBrush brush = new SolidBrush(ControlInk.Edge)) + { + g.FillEllipse(brush, num - num20 / 2f - S(1f), num19 - S(1f), num20 + S(2f), num20 + S(2f)); + } + using SolidBrush brush2 = new SolidBrush(_darkenMode ? DarkenedSwatch(color) : color); + g.FillEllipse(brush2, num - num20 / 2f, num19, num20, num20); + } + float num21 = num19 + num20 + S(5f) + S(1f); + if (num17 > 0f) + { + string text = (_darkenMode ? (_darken + "%") : (_hue + "°")); + TextRenderer.DrawText(g, text, Fonts.For(FontRole.Title), new Rectangle(num14 - (int)S(20f), (int)Math.Round(num21 + num17 / 2f) - (int)S(14f), num13 + (int)S(40f), (int)S(28f)), ControlInk.Text1, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding); + num21 += num17; + } + num21 += S(1f); + TextRenderer.DrawText(g, CentreText, Fonts.Caption, new Rectangle(num14, (int)Math.Round(num21), num13, num16), ControlInk.Text2, flags); + if (flag3) + { + double num22 = (double)ringAngle * Math.PI / 180.0; + float num23 = num3 - num4 / 2f; + float num24 = num + (float)Math.Cos(num22) * num23; + float num25 = num2 + (float)Math.Sin(num22) * num23; + float num26 = S(15f); + using (SolidBrush brush3 = new SolidBrush(ControlInk.KnobRing)) + { + g.FillEllipse(brush3, num24 - num26 - S(2f), num25 - num26 - S(2f), 2f * num26 + S(4f), 2f * num26 + S(4f)); + } + using (SolidBrush brush4 = new SolidBrush(ControlInk.Focus)) + { + g.FillEllipse(brush4, num24 - num26, num25 - num26, 2f * num26, 2f * num26); + } + float num27 = num26 - S(3f); + using (SolidBrush brush5 = new SolidBrush(color)) + { + g.FillEllipse(brush5, num24 - num27, num25 - num27, 2f * num27, 2f * num27); + } + g.PixelOffsetMode = PixelOffsetMode.Default; + if (_darkenMode && Focused && ShowFocusCues) + { + ControlInk.PaintFocusRing(g, new Rectangle((int)(num - num3), (int)(num2 - num3), diameter, diameter), num3, ControlInk.Dpi(this)); + } + } + static float S(float px) + { + return px * (float)Tokens.Scale(100) / 100f; + } + } + + private RingNameSlot[] RingNameSlots(Graphics g, float cx, float cy, float outer) + { + Font captionBold = Fonts.CaptionBold; + RingNameSlot[] array = new RingNameSlot[RingNames.Length]; + for (int i = 0; i < RingNames.Length; i++) + { + (int Degrees, string Name) tuple = RingNames[i]; + int item = tuple.Degrees; + string item2 = tuple.Name; + double num = (double)item * Math.PI / 180.0; + float num2 = (float)Math.Cos(num); + float num3 = (float)Math.Sin(num); + float num4 = cx + num2 * (outer + S(12f)); + float num5 = cy + num3 * (outer + S(12f)); + Size size = TextRenderer.MeasureText(g, item2, captionBold, Size.Empty, TextFormatFlags.NoPadding); + float num6; + if (num2 > 0.3f) + { + num6 = num4; + } + else + { + num6 = ((num2 < -0.3f) ? (num4 - (float)size.Width) : (num4 - (float)size.Width / 2f)); + } + if (Math.Abs(num3) > 0.3f) + { + num5 += (float)(Math.Sign(num3) * size.Height) / 2f; + } + Rectangle rect = new Rectangle(new Point((int)Math.Round(num6), (int)Math.Round(num5 - (float)size.Height / 2f)), size); + PointF tickEnd = new PointF(cx + num2 * (outer + S(9f)), cy + num3 * (outer + S(9f))); + array[i] = new RingNameSlot(item, item2, rect, tickEnd); + } + return array; + static float S(float px) + { + return px * (float)Tokens.Scale(100) / 100f; + } + } + + internal RingNameSlot[] RingNameSlotsForTest() + { + using Bitmap image = new Bitmap(1, 1); + using Graphics g = Graphics.FromImage(image); + float outer = (float)Diameter / 2f; + return RingNameSlots(g, (float)Width / 2f, (float)Height / 2f, outer); + } + + private static Color Hsl(float r, float g, float b) + { + float num = (1f - Math.Abs(0.100000024f)) * 0.88f; + float num2 = 0.55f - num / 2f; + return Color.FromArgb(Byte(num2 + r * num), Byte(num2 + g * num), Byte(num2 + b * num)); + } + + private Color DarkenedSwatch(Color colour) + { + if (_darken == 0) + { + return colour; + } + var (num, num2, num3) = SaturationMetrics.Transform(SaturationMetrics.Build(SaturationMetric.Rec709, 1f, 1f, new ColourDepth(SaturationMetric.Rec709, _darken, _darkenHue)), (double)(int)colour.R / 255.0, (double)(int)colour.G / 255.0, (double)(int)colour.B / 255.0); + return Color.FromArgb(Byte((float)num), Byte((float)num2), Byte((float)num3)); + } + + private void SetDarken(int hue, int amount) + { + int num = (hue % 360 + 360) % 360; + int num2 = Math.Clamp(amount, 0, 400); + if (num != _darkenHue || num2 != _darken || !_hasDarkenSelection) + { + _darkenHue = num; + _darken = num2; + _hasDarkenSelection = true; + Invalidate(); + DarkenChanged?.Invoke(this, EventArgs.Empty); + } + } + + internal void TestPressAt(Point p) + { + OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, p.X, p.Y, 0)); + OnMouseUp(new MouseEventArgs(MouseButtons.Left, 1, p.X, p.Y, 0)); + } + + internal void TestPressKey(Keys key) + { + OnKeyDown(new KeyEventArgs(key)); + } + + internal Point PointFor(int angleDegrees, double strength) + { + int diameter = Diameter; + double num = (double)(Width - diameter) / 2.0 + (double)diameter / 2.0; + double num2 = (double)(Height - diameter) / 2.0 + (double)diameter / 2.0; + double num3 = (double)angleDegrees * Math.PI / 180.0; + double num4 = (double)diameter / 2.0 * Math.Clamp(strength, 0.0, 1.0); + return new Point((int)Math.Round(num + Math.Cos(num3) * num4), (int)Math.Round(num2 + Math.Sin(num3) * num4)); + } + + protected override bool IsInputKey(Keys keyData) + { + bool flag = _darkenMode; + if (flag) + { + Keys keys = keyData & Keys.KeyCode; + bool flag2 = (((uint)(keys - 36) <= 4u || keys == Keys.Delete) ? true : false); + flag = flag2; + } + if (!flag) + { + return base.IsInputKey(keyData); + } + return true; + } + + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + if (_darkenMode) + { + bool shift = e.Shift; + switch (e.KeyCode) + { + default: + return; + case Keys.Right: + SetDarken(_darkenHue + ((!shift) ? 1 : 15), _darken); + break; + case Keys.Left: + SetDarken(_darkenHue - ((!shift) ? 1 : 15), _darken); + break; + case Keys.Up: + SetDarken(_darkenHue, _darken + (shift ? 50 : 5)); + break; + case Keys.Down: + SetDarken(_darkenHue, _darken - (shift ? 50 : 5)); + break; + case Keys.Home: + case Keys.Delete: + SetDarken(120, 0); + break; + case Keys.Select: + case Keys.Print: + case Keys.Execute: + case Keys.Snapshot: + case Keys.Insert: + return; + } + e.Handled = true; + } + } + + protected override void OnDoubleClick(EventArgs e) + { + base.OnDoubleClick(e); + if (_darkenMode) + { + SetDarken(120, 0); + } + else if (_hue != 0) + { + _hue = 0; + Invalidate(); + HueChanged?.Invoke(this, EventArgs.Empty); + } + } + + protected override void OnGotFocus(EventArgs e) + { + base.OnGotFocus(e); + Invalidate(); + } + + protected override void OnLostFocus(EventArgs e) + { + base.OnLostFocus(e); + Invalidate(); + } + + public HueWheel() + { + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + TabStop = false; + Cursor = Cursors.Hand; + } + + protected override void OnResize(EventArgs e) + { + base.OnResize(e); + _disc?.Dispose(); + _disc = null; + } + + protected override void OnPaintBackground(PaintEventArgs e) + { + if (SeeThrough) + { + base.OnPaintBackground(e); + } + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics g = e.Graphics; + if (!SeeThrough) + { + g.Clear((!_surface.IsEmpty) ? _surface : (Parent?.BackColor ?? Theme.Background)); + } + PaintGuard.Try(this, () => + { + PaintBody(g); + }); + } + + private void PaintBody(Graphics g) + { + if (_ring) + { + PaintRing(g); + return; + } + Bitmap bitmap = Disc(); + int diameter = Diameter; + int num = (Width - diameter) / 2; + int num2 = (Height - diameter) / 2; + if (bitmap != null) + { + g.DrawImageUnscaled(bitmap, num, num2); + } + double num3 = (_darkenMode ? ((double)_darken / 400.0) : ((double)Math.Abs(_hue) / 180.0)); + double num4 = (double)(_darkenMode ? _darkenHue : ((_hue >= 0) ? _hue : (360 + _hue))) * Math.PI / 180.0; + int num5 = num + diameter / 2; + int num6 = num2 + diameter / 2; + int num7 = (int)Math.Round(((double)diameter / 2.0 - (double)Tokens.Scale(7)) * num3); + Point point = new Point(num5 + (int)Math.Round(Math.Cos(num4) * (double)num7), num6 + (int)Math.Round(Math.Sin(num4) * (double)num7)); + int num8 = Tokens.Scale(11); + using (SolidBrush brush = new SolidBrush(Theme.Accent)) + { + g.FillEllipse(brush, point.X - num8 / 2, point.Y - num8 / 2, num8, num8); + } + using (Pen pen = new Pen(Theme.Background, Tokens.Scale(2))) + { + g.DrawEllipse(pen, point.X - num8 / 2, point.Y - num8 / 2, num8, num8); + } + if (_darkenMode && Focused && ShowFocusCues) + { + ControlInk.PaintFocusRing(g, new Rectangle(num, num2, diameter, diameter), (float)diameter / 2f, ControlInk.Dpi(this)); + } + } + + private Bitmap? Disc() + { + if (_disc != null) + { + return _disc; + } + (int, bool, bool) tuple = (Diameter, _ring, _darkenMode); + (int, bool, bool) failedDisc = _failedDisc; + (int, bool, bool) tuple2 = tuple; + if (failedDisc.Item1 == tuple2.Item1 && failedDisc.Item2 == tuple2.Item2 && failedDisc.Item3 == tuple2.Item3) + { + return null; + } + try + { + FailPointForTest?.Invoke("build"); + return _disc = BuildDisc(Diameter); + } + catch (Exception ex) when (PaintGuard.IsGdiFailure(ex)) + { + _failedDisc = tuple; + throw; + } + } + + private Bitmap BuildDisc(int d) + { + Bitmap bitmap = new Bitmap(d, d, PixelFormat.Format32bppArgb); + BitmapData bitmapData; + try + { + bitmapData = bitmap.LockBits(new Rectangle(0, 0, d, d), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); + } + catch + { + bitmap.Dispose(); + throw; + } + bool flag = false; + try + { + byte[] array = new byte[bitmapData.Stride]; + float num = (float)d / 2f; + float num2 = num; + for (int i = 0; i < d; i++) + { + Array.Clear(array, 0, array.Length); + for (int j = 0; j < d; j++) + { + float num3 = (float)j - num + 0.5f; + float num4 = (float)i - num + 0.5f; + float num5 = (float)Math.Sqrt(num3 * num3 + num4 * num4); + if (num5 > num2) + { + continue; + } + int num6 = (int)Math.Round(Math.Atan2(num4, num3) * 180.0 / Math.PI); + if (num6 < 0) + { + num6 += 360; + } + int degrees = ((num6 > 180) ? (num6 - 360) : num6); + float num7 = (_ring ? 1f : (num5 / num2)); + float channel; + float channel2; + float channel3; + if (_darkenMode || _ring) + { + HueAt(num6, out var r, out var g, out var b); + channel = 0.5f + (r - 0.5f) * num7; + channel2 = 0.5f + (g - 0.5f) * num7; + channel3 = 0.5f + (b - 0.5f) * num7; + if (_ring) + { + float num8 = Tokens.Scale(28); + float num9 = Math.Clamp((num5 - (num2 - num8)) / num8, 0f, 1f); + float num10 = (180f + 20f * num9) / 255f; + channel = 37f / 255f + r * num10; + channel2 = 37f / 255f + g * num10; + channel3 = 37f / 255f + b * num10; + } + } + else + { + float[] array2 = ColourBalance.HueMatrix(degrees); + channel = RefR + (array2[0] * RefR + array2[5] * RefG + array2[10] * RefB - RefR) * num7; + channel2 = RefG + (array2[1] * RefR + array2[6] * RefG + array2[11] * RefB - RefG) * num7; + channel3 = RefB + (array2[2] * RefR + array2[7] * RefG + array2[12] * RefB - RefB) * num7; + } + byte b2 = ((num5 > num2 - 1.2f) ? ((byte)(255f * Math.Clamp(num2 - num5, 0f, 1.2f) / 1.2f)) : byte.MaxValue); + if (_ring) + { + float num11 = num2 - (float)Tokens.Scale(28); + float num12 = Math.Clamp(num2 - num5 + 0.5f, 0f, 1f) * Math.Clamp(num5 - num11 + 0.5f, 0f, 1f); + if (num12 <= 0f) + { + continue; + } + b2 = (byte)Math.Round(255f * num12); + } + int num13 = j * 4; + array[num13] = Byte(channel3); + array[num13 + 1] = Byte(channel2); + array[num13 + 2] = Byte(channel); + array[num13 + 3] = b2; + } + Marshal.Copy(array, 0, bitmapData.Scan0 + i * bitmapData.Stride, array.Length); + } + flag = true; + } + finally + { + bitmap.UnlockBits(bitmapData); + if (!flag) + { + bitmap.Dispose(); + } + } + return bitmap; + } + + private static byte Byte(float channel) + { + return (byte)Math.Round(Math.Clamp(channel, 0f, 1f) * 255f); + } + + private static void HueAt(int degrees, out float r, out float g, out float b) + { + float num = (float)((degrees % 360 + 360) % 360) / 60f; + float num2 = 1f - Math.Abs(num % 2f - 1f); + (r, g, b) = (int)num switch + { + 0 => (1f, num2, 0f), + 1 => (num2, 1f, 0f), + 2 => (0f, 1f, num2), + 3 => (0f, num2, 1f), + 4 => (num2, 0f, 1f), + _ => (1f, 0f, num2), + }; + } + + protected override void OnMouseDown(MouseEventArgs e) + { + if (_darkenMode && TabStop) + { + Focus(); + } + _dragging = true; + FromPoint(e.Location); + } + + protected override void OnMouseWheel(MouseEventArgs e) + { + base.OnMouseWheel(e); + if (_darkenMode) + { + SetDarken(_darkenHue + ((e.Delta < 0) ? 5 : (-5)), _darken); + } + } + + protected override void OnMouseMove(MouseEventArgs e) + { + if (_dragging) + { + FromPoint(e.Location); + } + } + + protected override void OnMouseUp(MouseEventArgs e) + { + _dragging = false; + } + + private void FromPoint(Point p) + { + int diameter = Diameter; + double num = (double)(Width - diameter) / 2.0 + (double)diameter / 2.0; + double num2 = (double)(Height - diameter) / 2.0 + (double)diameter / 2.0; + double num3 = (double)p.X - num; + double num4 = (double)p.Y - num2; + double num5 = Math.Min(1.0, Math.Sqrt(num3 * num3 + num4 * num4) / ((double)diameter / 2.0)); + int num6 = (int)Math.Round(Math.Atan2(num4, num3) * 180.0 / Math.PI); + if (num6 < 0) + { + num6 += 360; + } + if (_darkenMode) + { + SetDarken(num6, _ring ? _darken : ((int)Math.Round(num5 * 400.0))); + return; + } + int num7 = ((num6 > 180) ? (num6 - 360) : num6); + int num8 = (_ring ? num7 : ((int)Math.Round((double)num7 * num5))); + if (num8 != _hue) + { + _hue = Math.Clamp(num8, -180, 180); + Invalidate(); + HueChanged?.Invoke(this, EventArgs.Empty); + } + } +} diff --git a/VibranceHud/Controls/InUseTag.cs b/VibranceHud/Controls/InUseTag.cs new file mode 100644 index 0000000..3c5f6c4 --- /dev/null +++ b/VibranceHud/Controls/InUseTag.cs @@ -0,0 +1,63 @@ +using System; +using System.Drawing; +using System.Windows.Forms; +using VibranceHud.Design; + +namespace VibranceHud.Controls; + +internal sealed class InUseTag : Control +{ + private int Dpi => ControlInk.Dpi(this); + + internal Size NaturalSize + { + get + { + int num = ControlInk.Hairline(Dpi); + return new Size(TextRenderer.MeasureText(Text, Fonts.CaptionBold, Size.Empty, TextFormatFlags.NoPadding).Width + 2 * Px(8) + 2 * num, Fonts.CaptionBold.Height + 2 * Px(2) + 2 * num); + } + } + + internal InUseTag() + : this("In use") + { + } + + internal InUseTag(string text) + { + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + SetStyle(ControlStyles.Selectable, value: false); + BackColor = Color.Transparent; + TabStop = false; + Font = Fonts.CaptionBold; + AccessibleRole = AccessibleRole.StaticText; + Text = text; + } + + private int Px(int logical) + { + return ControlInk.Px(Dpi, logical); + } + + protected override void OnTextChanged(EventArgs e) + { + base.OnTextChanged(e); + AccessibleName = Text; + Size = NaturalSize; + Invalidate(); + } + + protected override void OnDpiChangedAfterParent(EventArgs e) + { + base.OnDpiChangedAfterParent(e); + Size = NaturalSize; + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics graphics = e.Graphics; + int dpi = Dpi; + ControlInk.PaintBox(graphics, Size, ControlInk.PxF(dpi, 4f), ControlInk.Hairline(dpi), ControlInk.Accent, ControlInk.Accent); + TextRenderer.DrawText(graphics, Text, Fonts.CaptionBold, ClientRectangle, ControlInk.OnAccent, TextFormatFlags.HorizontalCenter | TextFormatFlags.NoPrefix | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding); + } +} diff --git a/VibranceHud/Controls/KeyboardNavigation.cs b/VibranceHud/Controls/KeyboardNavigation.cs new file mode 100644 index 0000000..b75b0ac --- /dev/null +++ b/VibranceHud/Controls/KeyboardNavigation.cs @@ -0,0 +1,65 @@ +using System; +using System.Windows.Forms; + +namespace VibranceHud.Controls; + +internal sealed class KeyboardNavigation : IMessageFilter +{ + [ThreadStatic] + private static KeyboardNavigation? _installed; + + [ThreadStatic] + private static bool _moving; + + private const int WM_KEYDOWN = 256; + + private const int WM_SYSKEYDOWN = 260; + + internal static bool InProgress => _moving; + + internal static void EnsureInstalled() + { + if (_installed == null) + { + _installed = new KeyboardNavigation(); + Application.AddMessageFilter(_installed); + } + } + + internal static bool Consume() + { + bool moving = _moving; + _moving = false; + return moving; + } + + internal static bool IsNavigationKey(Keys key) + { + Keys keys = key & Keys.KeyCode; + if (keys == Keys.Tab || (uint)(keys - 33) <= 7u) + { + return true; + } + return false; + } + + public bool PreFilterMessage(ref Message m) + { + int msg = m.Msg; + bool flag = ((msg == 256 || msg == 260) ? true : false); + bool flag2 = flag; + Keys keys = (flag2 ? ((Keys)((long)m.WParam & 0xFFFFL)) : Keys.None); + _moving = flag2 && IsNavigationKey(keys); + if (_moving && keys == Keys.Tab) + { + try + { + RovingFocus.RefreshAll(); + } + catch (Exception) + { + } + } + return false; + } +} diff --git a/VibranceHud/Controls/LibraryToast.cs b/VibranceHud/Controls/LibraryToast.cs new file mode 100644 index 0000000..651a072 --- /dev/null +++ b/VibranceHud/Controls/LibraryToast.cs @@ -0,0 +1,190 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Text; +using System.Windows.Forms; +using VibranceHud.Design; + +namespace VibranceHud.Controls; + +public sealed class LibraryToast : Control +{ + private const int PadLeft = 16; + + private const int PadRight = 8; + + private const int Gap = 8; + + private const int IconSize = 20; + + private const int CloseBox = 28; + + private const int UndoPad = 8; + + private const int ButtonH = 28; + + private const int MinWidth = 360; + + private const int MaxWidth = 560; + + private readonly GlassButton _undo; + + private readonly GlassButton _close; + + public string Message { get; private set; } = ""; + + internal (string Lead, string Tail) Parts + { + get + { + int num = Message.IndexOf(" · ", StringComparison.Ordinal); + if (num <= 0) + { + return (Lead: "", Tail: Message); + } + return (Lead: Message.Substring(0, num), Tail: Message.Substring(num)); + } + } + + private static int UndoWidth => Advance("Undo", Fonts.BodyBold) + 2 * S(8); + + internal int PreferredWidth + { + get + { + (string Lead, string Tail) parts = Parts; + string item = parts.Lead; + string item2 = parts.Tail; + int num = ((item.Length > 0) ? Advance(item, Fonts.BodyBold) : 0) + Advance(item2, Fonts.Body); + return Math.Clamp(S(16) + S(20) + S(8) + num + S(8) + UndoWidth + S(8) + S(28) + S(8), S(360), S(560)); + } + } + + public event EventHandler? UndoRequested; + + public event EventHandler? CloseRequested; + + private static int S(int logical) + { + return Tokens.Scale(logical); + } + + public LibraryToast() + { + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + Height = 48; + Visible = false; + _undo = new GlassButton + { + Kind = GlassButtonKind.Quiet, + Text = "Undo", + AccessibleName = "Undo", + TabIndex = 0 + }; + _undo.Click += (object? _, EventArgs _) => + { + UndoRequested?.Invoke(this, EventArgs.Empty); + }; + _close = new GlassButton + { + Kind = GlassButtonKind.Icon, + Icon = SignalIcon.Close, + AccessibleName = "Close", + TabIndex = 1 + }; + _close.Click += (object? _, EventArgs _) => + { + CloseRequested?.Invoke(this, EventArgs.Empty); + }; + Controls.Add(_undo); + Controls.Add(_close); + LayOut(); + } + + public void Show(string message) + { + Message = message; + Visible = true; + LayOut(); + BringToFront(); + Invalidate(); + } + + protected override void OnLayout(LayoutEventArgs levent) + { + base.OnLayout(levent); + LayOut(); + } + + public void ReassertOnTop() + { + BringToFront(); + } + + internal void TestPressUndo() + { + UndoRequested?.Invoke(this, EventArgs.Empty); + } + + internal void TestPressClose() + { + CloseRequested?.Invoke(this, EventArgs.Empty); + } + + private void LayOut() + { + if (_undo != null && _close != null) + { + int num = S(28); + _close.SetBounds(Width - S(8) - num, (Height - num) / 2, num, num); + int undoWidth = UndoWidth; + int num2 = S(28); + _undo.SetBounds(_close.Left - S(8) - undoWidth, (Height - num2) / 2, undoWidth, num2); + } + } + + private static int Advance(string text, Font font) + { + return TextRenderer.MeasureText(text, font, Size.Empty, TextFormatFlags.NoPadding).Width; + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics graphics = e.Graphics; + graphics.SmoothingMode = SmoothingMode.AntiAlias; + graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; + LayOut(); + RectangleF rect = new RectangleF(0.5f, 0.5f, Width - 1, Height - 1); + float radius = S(8); + if (SlateSurface.Active) + { + Glass.PaintPanel(graphics, rect, radius, Glass.BackdropOffsetOf(this), 255, 200, exactAlpha: true); + } + else + { + using GraphicsPath path = Glass.RoundedPath(rect, radius); + using (SolidBrush brush = new SolidBrush(SignalTokens.Ash.Overlay)) + { + graphics.FillPath(brush, path); + } + using Pen pen = new Pen(SignalTokens.Ash.WindowEdge, S(1)); + graphics.DrawPath(pen, path); + } + int num = S(20); + int num2 = S(16); + LineIcons.Success(graphics, new Rectangle(num2, (Height - num) / 2, num, num), Theme.Positive); + num2 += num + S(8); + int num3 = Math.Max(0, _undo.Left - S(8) - num2); + var (text, text2) = Parts; + if (text.Length > 0) + { + int num4 = Math.Min(num3, Advance(text, Fonts.BodyBold)); + TextRenderer.DrawText(graphics, text, Fonts.BodyBold, new Rectangle(num2, 0, num4, Height), Theme.Text, TextFormatFlags.NoPrefix | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding); + num2 += num4; + num3 -= num4; + } + TextRenderer.DrawText(graphics, text2, Fonts.Body, new Rectangle(num2, 0, Math.Max(0, num3), Height), Theme.TextDim, TextFormatFlags.EndEllipsis | TextFormatFlags.NoPrefix | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding); + base.OnPaint(e); + } +} diff --git a/VibranceHud/Controls/LockPill.cs b/VibranceHud/Controls/LockPill.cs new file mode 100644 index 0000000..e7df1db --- /dev/null +++ b/VibranceHud/Controls/LockPill.cs @@ -0,0 +1,55 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; +using VibranceHud.Design; + +namespace VibranceHud.Controls; + +public static class LockPill +{ + public const string Text = "COMES WITH A PLAN"; + + private const int Height = 24; + + private const int PadX = 8; + + private const int Icon = 16; + + private const int Gap = 8; + + private const int Radius = 4; + + public static string Label => char.ToUpperInvariant("COMES WITH A PLAN"[0]) + "COMES WITH A PLAN".Substring(1).ToLowerInvariant(); + + private static Font WordFont => Fonts.CaptionBold; + + private static int S(int px) + { + return Tokens.Scale(px); + } + + public static Size Measure() + { + Size size = TextRenderer.MeasureText(Label, WordFont, Size.Empty, TextFormatFlags.SingleLine | TextFormatFlags.NoPadding); + return new Size(S(8) + S(16) + S(8) + size.Width + S(8), S(24)); + } + + public static void Draw(Graphics g, Rectangle tag) + { + if (tag.Width >= 4 && tag.Height >= 4) + { + int dpi = Tokens.Dpi; + GraphicsState gstate = g.Save(); + g.TranslateTransform(tag.X, tag.Y); + ControlInk.PaintBox(g, tag.Size, S(4), ControlInk.Hairline(dpi), Color.Empty, ControlInk.Border); + g.Restore(gstate); + Color text = ControlInk.Text2; + int num = S(16); + RectangleF box = new RectangleF(tag.X + S(8), (float)tag.Y + (float)(tag.Height - num) / 2f, num, num); + SignalIcons.Draw(g, SignalIcon.Lock, box, text); + int num2 = (int)box.Right + S(8); + TextRenderer.DrawText(g, Label, WordFont, new Rectangle(num2, tag.Y, Math.Max(0, tag.Right - S(8) - num2 + S(2)), tag.Height), text, TextFormatFlags.NoPrefix | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding); + } + } +} diff --git a/VibranceHud/Controls/LookTile.cs b/VibranceHud/Controls/LookTile.cs new file mode 100644 index 0000000..a96617d --- /dev/null +++ b/VibranceHud/Controls/LookTile.cs @@ -0,0 +1,319 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; +using VibranceHud.Design; +using VibranceHud.Theming; + +namespace VibranceHud.Controls; + +public sealed class LookTile : Control +{ + private readonly string _caption; + + private readonly string _name; + + private readonly HoverFade _fade; + + private readonly OutsideFocusRing _ring; + + private bool _active; + + private const int Pad = 12; + + private const int PreviewH = 104; + + private const int NameGap = 12; + + private const int NameH = 20; + + private const int CaptionGap = 2; + + private const int RadioD = 20; + + private const int RadioDot = 8; + + private static readonly Rectangle[] Boxes = new Rectangle[5] + { + new Rectangle(6, 6, 22, 92), + new Rectangle(34, 6, 199, 18), + new Rectangle(34, 30, 199, 34), + new Rectangle(34, 70, 120, 28), + new Rectangle(160, 70, 73, 28) + }; + + private const int BoxesW = 242; + + public ThemePalette Palette { get; } + + public bool Active + { + get + { + return _active; + } + set + { + if (_active != value) + { + _active = value; + Invalidate(); + } + } + } + + internal string ShownName => _name; + + internal string Caption => _caption; + + internal Action? FailPointForTest { get; set; } + + private bool IsSlate => Palette.Name == "Slate"; + + public LookTile(ThemePalette palette, string caption, string? name = null) + { + Palette = palette; + _caption = caption; + _name = name ?? palette.Name; + _fade = new HoverFade(this); + _ring = new OutsideFocusRing(this, () => ControlInk.PxF(ControlInk.Dpi(this), 8f)); + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + Cursor = Cursors.Hand; + Size = new Size(266, 194); + AccessibleName = _name; + AccessibleRole = AccessibleRole.RadioButton; + TabStop = true; + SetStyle(ControlStyles.Selectable, value: true); + } + + internal static int HeightFor(int width, string caption, int dpi) + { + int width2 = Math.Max(1, width - 2 * ControlInk.Px(dpi, 12)); + int height = TextRenderer.MeasureText(caption, Fonts.Caption, new Size(width2, int.MaxValue), TextFormatFlags.WordBreak | TextFormatFlags.NoPadding).Height; + return ControlInk.Px(dpi, 150) + height + ControlInk.Px(dpi, 12); + } + + protected override void OnMouseEnter(EventArgs e) + { + base.OnMouseEnter(e); + _fade.Set(hot: true); + } + + protected override void OnMouseLeave(EventArgs e) + { + base.OnMouseLeave(e); + _fade.Set(hot: false); + } + + protected override void OnMouseDown(MouseEventArgs e) + { + base.OnMouseDown(e); + if (e.Button == MouseButtons.Left) + { + Focus(); + Invalidate(); + } + } + + protected override void OnGotFocus(EventArgs e) + { + base.OnGotFocus(e); + Invalidate(); + } + + protected override void OnLostFocus(EventArgs e) + { + base.OnLostFocus(e); + Invalidate(); + } + + protected override void OnParentChanged(EventArgs e) + { + base.OnParentChanged(e); + _ring.Rehook(); + } + + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + bool flag = !Enabled; + if (!flag) + { + Keys keyCode = e.KeyCode; + bool flag2 = ((keyCode == Keys.Return || keyCode == Keys.Space) ? true : false); + flag = !flag2; + } + if (!flag) + { + e.Handled = true; + OnClick(EventArgs.Empty); + } + } + + internal void TestPressKey(Keys key) + { + OnKeyDown(new KeyEventArgs(key)); + } + + protected override void OnEnabledChanged(EventArgs e) + { + base.OnEnabledChanged(e); + Cursor = (Enabled ? Cursors.Hand : Cursors.Default); + if (!Enabled) + { + _fade.Snap(hot: false); + } + Invalidate(); + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics g = e.Graphics; + PaintGuard.Try(this, () => + { + PaintTile(g); + }); + } + + private void PaintTile(Graphics g) + { + int dpi = ControlInk.Dpi(this); + int num = ControlInk.Px(dpi, 12); + int num2 = ControlInk.Hairline(dpi); + float num3 = ControlInk.PxF(dpi, 8f); + Color fill = (Enabled ? ControlInk.Mix(Color.FromArgb(0, ControlInk.Hover), ControlInk.Hover, _fade.Value) : Color.Transparent); + Color edge; + if (Enabled) + { + edge = (_active ? ControlInk.Accent : ControlInk.Edge); + } + else + { + edge = ControlInk.TextDisabled; + } + ControlInk.PaintBox(g, ClientSize, num3, num2, fill, edge); + if (_active && Enabled && Width > 4 && Height > 4) + { + Size size = new Size(Width - 2 * num2, Height - 2 * num2); + GraphicsState gstate = g.Save(); + g.TranslateTransform(num2, num2); + ControlInk.PaintBox(g, size, Math.Max(0f, num3 - (float)num2), num2, Color.Transparent, ControlInk.Accent); + g.Restore(gstate); + } + Rectangle well = new Rectangle(num, num, Math.Max(1, Width - 2 * num), Math.Min(ControlInk.Px(dpi, 104), Math.Max(1, Height - 2 * num))); + if (well.Width > 4 && well.Height > 4) + { + PaintGuard.Try(this, () => + { + PaintPreview(g, well, dpi); + }); + } + int num4 = well.Bottom + ControlInk.Px(dpi, 12); + int num5 = ControlInk.Px(dpi, 20); + int num6 = ControlInk.Px(dpi, 20); + Rectangle box = new Rectangle(Width - num - num6, num4 + (num5 - num6) / 2, num6, num6); + Color foreColor = (Enabled ? ControlInk.Text1 : ControlInk.TextDisabledInk); + Color foreColor2 = (Enabled ? ControlInk.Text3 : ControlInk.TextDisabledInk); + TextRenderer.DrawText(g, _name, Fonts.BodyBold, new Rectangle(num, num4, Math.Max(1, box.Left - num - ControlInk.Px(dpi, 8)), num5), foreColor, TextFormatFlags.EndEllipsis | TextFormatFlags.NoPrefix | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding); + PaintRadio(g, box, dpi); + int num7 = num4 + num5 + ControlInk.Px(dpi, 2); + TextRenderer.DrawText(g, _caption, Fonts.Caption, new Rectangle(num, num7, Math.Max(1, Width - 2 * num), Math.Max(1, Height - num7 - num / 2)), foreColor2, TextFormatFlags.NoPrefix | TextFormatFlags.WordBreak | TextFormatFlags.NoPadding); + _ring.Show(Focused && ShowFocusCues && Enabled); + } + + private void PaintPreview(Graphics g, Rectangle well, int dpi) + { + FailPointForTest?.Invoke("draw"); + float radius = ControlInk.PxF(dpi, 4f); + using GraphicsPath path = Glass.RoundedPath(new RectangleF(well.X, well.Y, well.Width, well.Height), radius); + using Region clip = g.Clip; + g.SetClip(path, CombineMode.Intersect); + try + { + using (SolidBrush brush = new SolidBrush(SlateSurface.Active ? SignalTokens.Slate.PreviewWell : SignalTokens.Ash.PreviewWell)) + { + g.FillRectangle(brush, well); + } + if (AppBackground.IsSet) + { + GraphicsState gstate = g.Save(); + g.TranslateTransform(well.X, well.Y); + AppBackground.PaintInto(g, well.Width, well.Height); + g.Restore(gstate); + } + float num = (float)well.Width / 242f; + Color color = (IsSlate ? Color.FromArgb((int)Math.Round(168.3), SignalTokens.Slate.SlateBase) : SignalTokens.Ash.Surface1); + Color color2 = (IsSlate ? SignalTokens.Slate.Border : SignalTokens.Ash.Border); + if (!Enabled) + { + color = Color.FromArgb(color.A / 2, color); + } + SmoothingMode smoothingMode = g.SmoothingMode; + g.SmoothingMode = SmoothingMode.AntiAlias; + using SolidBrush brush2 = new SolidBrush(color); + using Pen pen = new Pen(color2, 1f); + Rectangle[] boxes = Boxes; + for (int i = 0; i < boxes.Length; i++) + { + Rectangle rectangle = boxes[i]; + RectangleF rect = new RectangleF((float)well.X + (float)rectangle.X * num, (float)well.Y + (float)rectangle.Y * num, (float)rectangle.Width * num, Math.Min((float)rectangle.Height * num, (float)well.Bottom - ((float)well.Y + (float)rectangle.Y * num) - 1f)); + if (!(rect.Width < 2f) && !(rect.Height < 2f)) + { + using GraphicsPath path2 = Glass.RoundedPath(rect, ControlInk.PxF(dpi, 2f)); + g.FillPath(brush2, path2); + g.DrawPath(pen, path2); + } + } + g.SmoothingMode = smoothingMode; + } + finally + { + g.Clip = clip; + } + } + + private void PaintRadio(Graphics g, Rectangle box, int dpi) + { + if (box.Width < 4) + { + return; + } + SmoothingMode smoothingMode = g.SmoothingMode; + PixelOffsetMode pixelOffsetMode = g.PixelOffsetMode; + g.SmoothingMode = SmoothingMode.AntiAlias; + g.PixelOffsetMode = PixelOffsetMode.Half; + try + { + float num = (float)ControlInk.Hairline(dpi) / 2f; + RectangleF rect = new RectangleF((float)box.X + num, (float)box.Y + num, (float)box.Width - 2f * num, (float)box.Height - 2f * num); + if (_active && Enabled) + { + using (SolidBrush brush = new SolidBrush(ControlInk.Accent)) + { + g.FillEllipse(brush, box); + } + float num2 = ControlInk.PxF(dpi, 8f); + using SolidBrush brush2 = new SolidBrush(ControlInk.OnAccent); + g.FillEllipse(brush2, (float)box.X + ((float)box.Width - num2) / 2f, (float)box.Y + ((float)box.Height - num2) / 2f, num2, num2); + return; + } + using Pen pen = new Pen(Enabled ? ControlInk.Edge : ControlInk.TextDisabled, ControlInk.Hairline(dpi)); + g.DrawEllipse(pen, rect); + } + finally + { + g.SmoothingMode = smoothingMode; + g.PixelOffsetMode = pixelOffsetMode; + } + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _ring.Release(); + } + base.Dispose(disposing); + } +} diff --git a/VibranceHud/Controls/MonitorNumberWindow.cs b/VibranceHud/Controls/MonitorNumberWindow.cs new file mode 100644 index 0000000..ebbb972 --- /dev/null +++ b/VibranceHud/Controls/MonitorNumberWindow.cs @@ -0,0 +1,51 @@ +using System; +using System.Drawing; +using System.Globalization; +using System.Windows.Forms; +using VibranceHud.Design; +using VibranceHud.Monitors; + +namespace VibranceHud.Controls; + +internal sealed class MonitorNumberWindow : Form, IMonitorIdentifyWindow, IDisposable +{ + private readonly string _number; + + protected override bool ShowWithoutActivation => true; + + protected override CreateParams CreateParams + { + get + { + CreateParams createParams = base.CreateParams; + createParams.ExStyle |= 134217888; + return createParams; + } + } + + internal MonitorNumberWindow(Rectangle screen, int number) + { + _number = number.ToString(CultureInfo.InvariantCulture); + FormBorderStyle = FormBorderStyle.None; + ShowInTaskbar = false; + TopMost = true; + StartPosition = FormStartPosition.Manual; + BackColor = Theme.Surface; + Size = new Size(Tokens.Scale(120), Tokens.Scale(96)); + Location = new Point(screen.Left + (screen.Width - Width) / 2, screen.Top + (screen.Height - Height) / 2); + DoubleBuffered = true; + } + + public void ShowNumber() + { + Show(); + } + + protected override void OnPaint(PaintEventArgs e) + { + base.OnPaint(e); + TextRenderer.DrawText(e.Graphics, _number, Fonts.Value, ClientRectangle, Theme.Text, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding); + using Pen pen = new Pen(Theme.Border); + e.Graphics.DrawRectangle(pen, 0, 0, Width - 1, Height - 1); + } +} diff --git a/VibranceHud/Controls/MonitorSelectionCard.cs b/VibranceHud/Controls/MonitorSelectionCard.cs new file mode 100644 index 0000000..cdc698d --- /dev/null +++ b/VibranceHud/Controls/MonitorSelectionCard.cs @@ -0,0 +1,186 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Linq; +using System.Windows.Forms; +using VibranceHud.Design; +using VibranceHud.Monitors; + +namespace VibranceHud.Controls; + +internal sealed class MonitorSelectionCard : IDisposable +{ + private readonly MonitorSelection _selection; + + private readonly MonitorIdentifier _identifier; + + private readonly Action _save; + + private readonly Label _heading = Label("Apply to", Fonts.BodyBold); + + private readonly Label _hint = Label("Unticked monitors keep their own colours.", Fonts.Caption); + + private readonly Label _summary = Label("", Fonts.Caption); + + private readonly Label _limitation = Label("", Fonts.Caption); + + private readonly Label _empty = Label("No monitors found.", Fonts.Caption); + + private readonly GlassButton _identify = new GlassButton + { + Text = "Identify screens", + AccessibleName = "Identify screens" + }; + + private readonly List _tiles = new List(); + + public CardPanel View { get; } = new CardPanel + { + Name = "monitor-selection" + }; + + public MonitorSelectionCard(MonitorSelection selection, MonitorIdentifier identifier, Action save) + { + _selection = selection; + _identifier = identifier; + _save = save; + View.Controls.AddRange(new Control[6] { _heading, _hint, _identify, _summary, _limitation, _empty }); + _identify.Click += (object? _, EventArgs _) => + { + _identifier.Identify(_selection.Groups); + }; + _selection.Changed += Refresh; + Refresh(); + } + + private static Label Label(string text, Font font) + { + return new Label + { + Text = text, + Font = font, + ForeColor = Theme.TextDim, + BackColor = Color.Transparent, + AutoSize = false, + TabStop = false + }; + } + + private void Refresh() + { + IReadOnlyList groups = _selection.Groups; + View.Visible = _selection.WorthShowing; + if (_tiles.Count != groups.Count || _tiles.Where((MonitorSelectionTile t, int i) => t.Group.Identity != groups[i].Identity).Any()) + { + foreach (MonitorSelectionTile tile2 in _tiles) + { + View.Controls.Remove(tile2); + tile2.Dispose(); + } + _tiles.Clear(); + for (int num = 0; num < groups.Count; num++) + { + MonitorSelectionTile tile = new MonitorSelectionTile(groups[num], num + 1); + tile.SelectionRequested += (bool chosen) => + { + _selection.SetSelected(tile.Group, chosen); + _save(); + }; + _tiles.Add(tile); + View.Controls.Add(tile); + } + } + for (int num2 = 0; num2 < _tiles.Count; num2++) + { + _tiles[num2].Group = groups[num2]; + _tiles[num2].Checked = _selection.IsSelected(groups[num2]); + _tiles[num2].Enabled = true; + } + _identify.Enabled = groups.Count > 0; + _empty.Visible = groups.Count == 0; + IEnumerable enumerable = from x in groups.Select((ColourMonitorGroup g, int i) => (g: g, i: i)) + where _selection.IncludesDevice(x.g.DeviceName) + select "Monitor " + (x.i + 1); + _summary.Text = "Ticked: " + (enumerable.Any() ? string.Join(", ", enumerable) : "None"); + Label limitation = _limitation; + string text; + if (groups.Count != 0) + { + text = (_selection.AllowsMatrix ? "" : "Saturation, hue and other whole-desktop colour effects are paused while a monitor is unticked. Brightness, contrast, temperature, red/green/blue, gamma and NVIDIA Digital Vibrance use the ticked monitors."); + } + else + { + text = ""; + } + limitation.Text = text; + if (groups.Count > 0 && groups.All((ColourMonitorGroup g) => !_selection.IsSelected(g))) + { + _limitation.Text = "No monitors selected. Colour changes are paused."; + } + if (View.Width > 0) + { + Layout(View.Width); + } + View.Parent?.PerformLayout(); + } + + public int Layout(int width) + { + if (!_selection.WorthShowing) + { + View.Height = 0; + return 0; + } + int num = Tokens.Scale(21); + int num2 = Tokens.Scale(12); + int num3 = Math.Max(1, width - 2 * num); + int height = Tokens.Scale(32); + int width2 = _identify.GetPreferredSize(Size.Empty).Width; + _heading.ForeColor = Theme.Text; + _heading.SetBounds(num, num, Math.Max(1, num3 - width2 - num2), Fonts.LineHeight(FontRole.BodyBold)); + _identify.SetBounds(width - num - width2, num, width2, height); + int y = _heading.Bottom + Tokens.Scale(3); + int width3 = Math.Max(1, num3 - width2 - num2); + int height2 = Measure(_hint, width3); + _hint.SetBounds(num, y, width3, height2); + int num4 = Math.Max(_hint.Bottom, _identify.Bottom) + Tokens.Scale(16); + int num5 = ((num3 < Tokens.Scale(640)) ? 1 : 2); + int tileW = (num3 - num2 * (num5 - 1)) / num5; + for (int i = 0; i < _tiles.Count; i += num5) + { + int num6 = _tiles.Skip(i).Take(num5).Max((MonitorSelectionTile t) => t.GetPreferredSize(new Size(tileW, 0)).Height); + for (int num7 = 0; num7 < num5 && i + num7 < _tiles.Count; num7++) + { + _tiles[i + num7].SetBounds(num + num7 * (tileW + num2), num4, tileW, num6); + } + num4 += num6 + num2; + } + if (_tiles.Count == 0) + { + _empty.SetBounds(num, num4, num3, Measure(_empty, num3)); + num4 = _empty.Bottom + num2; + } + else + { + _empty.SetBounds(num, num, 0, 0); + } + _summary.SetBounds(num, num4, num3, Measure(_summary, num3)); + num4 = _summary.Bottom; + int num8 = ((_limitation.Text.Length != 0) ? Measure(_limitation, num3) : 0); + _limitation.SetBounds(num, num4 + ((num8 > 0) ? num2 : 0), num3, num8); + int num9 = _limitation.Bottom + num; + View.Height = num9; + return num9; + } + + private static int Measure(Label label, int width) + { + return TextRenderer.MeasureText(label.Text, label.Font, new Size(width, int.MaxValue), TextFormatFlags.WordBreak | TextFormatFlags.NoPadding).Height; + } + + public void Dispose() + { + _selection.Changed -= Refresh; + _identifier.Dispose(); + } +} diff --git a/VibranceHud/Controls/MonitorSelectionTile.cs b/VibranceHud/Controls/MonitorSelectionTile.cs new file mode 100644 index 0000000..6936a9d --- /dev/null +++ b/VibranceHud/Controls/MonitorSelectionTile.cs @@ -0,0 +1,187 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Globalization; +using System.Windows.Forms; +using VibranceHud.Design; +using VibranceHud.Monitors; + +namespace VibranceHud.Controls; + +public sealed class MonitorSelectionTile : Control +{ + private sealed class TileAccessible : ControlAccessibleObject + { + private readonly MonitorSelectionTile _tile; + + public override AccessibleStates State => (AccessibleStates)((int)base.State | (_tile.Checked ? 16 : 0)); + + public override string DefaultAction => "Toggle selection"; + + public TileAccessible(MonitorSelectionTile tile) + : base(tile) + { + _tile = tile; + } + + public override void DoDefaultAction() + { + _tile.Request(); + } + } + + private bool _checked; + + public ColourMonitorGroup Group { get; set; } + + public int Number { get; } + + public bool Checked + { + get + { + return _checked; + } + set + { + if (_checked != value) + { + _checked = value; + Invalidate(); + AccessibilityNotifyClients(AccessibleEvents.StateChange, -1); + } + } + } + + private string Detail + { + get + { + if (!Group.IsClone) + { + return Group.Bounds.Width + " × " + Group.Bounds.Height + ((Group.RefreshHz > 0) ? (" · " + Group.RefreshHz + " Hz") : "") + (Group.Primary ? " · main" : ""); + } + return "Mirrored screens — selected together"; + } + } + + public event Action? SelectionRequested; + + public MonitorSelectionTile(ColourMonitorGroup group, int number) + { + Group = group; + Number = number; + Name = "monitor-tile-" + number; + AccessibleName = group.Name; + AccessibleRole = AccessibleRole.CheckButton; + TabStop = true; + Cursor = Cursors.Hand; + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + Font = Fonts.BodyBold; + } + + private int TextWidth(int width) + { + return Math.Max(Tokens.Scale(32), width - Tokens.Scale(132)); + } + + private static Size Measure(string text, Font font, int width) + { + return TextRenderer.MeasureText(text, font, new Size(width, int.MaxValue), TextFormatFlags.WordBreak | TextFormatFlags.NoPadding); + } + + public override Size GetPreferredSize(Size proposedSize) + { + int width = ((proposedSize.Width > 0) ? proposedSize.Width : Tokens.Scale(360)); + int width2 = TextWidth(width); + int num = Measure(Group.Name, Fonts.BodyBold, width2).Height + Tokens.Scale(3) + Measure(Detail, Fonts.Caption, width2).Height; + return new Size(width, Math.Max(Tokens.Scale(68), num + Tokens.Scale(28))); + } + + protected override void OnPaint(PaintEventArgs e) + { + base.OnPaint(e); + Graphics graphics = e.Graphics; + graphics.SmoothingMode = SmoothingMode.AntiAlias; + int num = Tokens.Scale(14); + int num2 = Tokens.Scale(58); + int num3 = Tokens.Scale(38); + int num4 = Tokens.Scale(12); + using SolidBrush brush = new SolidBrush(Checked ? Theme.Surface : Theme.Background); + using Pen pen = new Pen(Checked ? Theme.Text : Theme.Border); + Rectangle rect = new Rectangle(0, 0, Width - 1, Height - 1); + graphics.FillRectangle(brush, rect); + graphics.DrawRectangle(pen, rect); + Rectangle rectangle = new Rectangle(num, (Height - num3) / 2, num2, num3); + graphics.DrawRectangle(pen, rectangle); + TextRenderer.DrawText(graphics, Number.ToString(CultureInfo.InvariantCulture), Fonts.Title, rectangle, Checked ? Theme.Text : Theme.TextDim, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding); + using SolidBrush brush2 = new SolidBrush(Checked ? Theme.Text : Theme.TextDim); + graphics.FillRectangle(brush2, rectangle.Left + num2 / 2 - Tokens.Scale(5), rectangle.Bottom, Tokens.Scale(10), Tokens.Scale(6)); + int x = num + num2 + num4; + int width = TextWidth(Width); + int height = Measure(Group.Name, Fonts.BodyBold, width).Height; + TextRenderer.DrawText(graphics, Group.Name, Fonts.BodyBold, new Rectangle(x, num, width, height), Theme.Text, TextFormatFlags.WordBreak | TextFormatFlags.NoPadding); + TextRenderer.DrawText(graphics, Detail, Fonts.Caption, new Rectangle(x, num + height + Tokens.Scale(3), width, Height - num * 2 - height - Tokens.Scale(3)), Theme.TextDim, TextFormatFlags.WordBreak | TextFormatFlags.NoPadding); + int num5 = Tokens.Scale(20); + Rectangle rect2 = new Rectangle(Width - num - num5, (Height - num5) / 2, num5, num5); + if (Checked) + { + using SolidBrush brush3 = new SolidBrush(Theme.Text); + graphics.FillRectangle(brush3, rect2); + using Pen pen2 = new Pen(Theme.Background, Tokens.Scale(2)); + graphics.DrawLines(pen2, new Point[3] + { + new Point(rect2.Left + num5 / 4, rect2.Top + num5 / 2), + new Point(rect2.Left + num5 * 2 / 5, rect2.Top + num5 * 3 / 4), + new Point(rect2.Left + num5 * 4 / 5, rect2.Top + num5 / 4) + }); + } + else + { + graphics.DrawRectangle(pen, rect2); + } + if (Focused) + { + using (Pen pen3 = new Pen(Theme.Text) + { + DashStyle = DashStyle.Dot + }) + { + graphics.DrawRectangle(pen3, 2, 2, Width - 5, Height - 5); + return; + } + } + } + + private void Request() + { + if (Enabled) + { + SelectionRequested?.Invoke(!Checked); + } + } + + protected override void OnClick(EventArgs e) + { + base.OnClick(e); + Focus(); + Request(); + } + + protected override void OnKeyDown(KeyEventArgs e) + { + if (e.KeyCode == Keys.Space) + { + Request(); + e.Handled = true; + e.SuppressKeyPress = true; + } + base.OnKeyDown(e); + } + + protected override AccessibleObject CreateAccessibilityInstance() + { + return new TileAccessible(this); + } +} diff --git a/VibranceHud/Controls/NotesView.cs b/VibranceHud/Controls/NotesView.cs new file mode 100644 index 0000000..eb47508 --- /dev/null +++ b/VibranceHud/Controls/NotesView.cs @@ -0,0 +1,488 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Text; +using System.Text.RegularExpressions; +using System.Windows.Forms; +using VibranceHud.Design; + +namespace VibranceHud.Controls; + +public sealed class NotesView : Control +{ + internal readonly record struct Block(string Lead, string Text, bool Bullet, bool Heading, bool GapBefore); + + private const int LanePx = 8; + + private const int ThumbPx = 4; + + private const int ThumbMinPx = 24; + + private const int ParagraphGapPx = 8; + + private const int LinesPerNotch = 3; + + private string _text = ""; + + private int _scroll; + + private bool _thumbHot; + + private bool _dragging; + + private int _dragFrom; + + private int _dragScrollFrom; + + private readonly List<(Point At, string Word, bool Strong)> _laid = new List<(Point, string, bool)>(); + + private readonly List _dots = new List(); + + private int _laidFor = -1; + + private int _contentHeight; + + private int _headingLimit = 48; + + private bool _onCard; + + internal const int DefaultHeadingLimit = 48; + + private static readonly Regex LeadIn = new Regex("^(?[A-Z][^:.!?\\r\\n]{0,38}:)\\s+(?\\S.*)$", RegexOptions.Singleline); + + public string NotesText + { + get + { + return _text; + } + set + { + _text = value ?? ""; + _laidFor = -1; + _scroll = 0; + Invalidate(); + } + } + + public int HeadingLimit + { + get + { + return _headingLimit; + } + set + { + if (value != _headingLimit) + { + _headingLimit = value; + _laidFor = -1; + Invalidate(); + } + } + } + + public bool OnCard + { + get + { + return _onCard; + } + set + { + if (value != _onCard) + { + _onCard = value; + if (value) + { + BackColor = Color.Transparent; + } + else + { + ResetBackColor(); + } + Invalidate(); + } + } + } + + private int Dpi => ControlInk.Dpi(this); + + private int TextWidth => Math.Max(1, Width - Px(8)); + + private int MaxScroll => Math.Max(0, _contentHeight - Height); + + private int LinePx => Px(20); + + private Rectangle Thumb + { + get + { + Lay(); + if (_contentHeight <= Height || Height <= 0) + { + return Rectangle.Empty; + } + int num = Math.Max(Px(24), (int)((long)Height * (long)Height / _contentHeight)); + int num2 = Height - num; + int y = (int)((MaxScroll != 0) ? ((long)num2 * (long)_scroll / MaxScroll) : 0); + int num3 = Px(4); + return new Rectangle(Width - Px(8) + (Px(8) - num3) / 2, y, num3, num); + } + } + + private Rectangle Lane => new Rectangle(Width - Px(8), 0, Px(8), Height); + + internal int ContentHeightForTest + { + get + { + Lay(); + return _contentHeight; + } + } + + internal int ScrollForTest => _scroll; + + internal Rectangle ThumbForTest => Thumb; + + public NotesView() + { + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + SetStyle(ControlStyles.Selectable, value: false); + TabStop = false; + Font = Fonts.Body; + } + + private int Px(int logical) + { + return ControlInk.Px(Dpi, logical); + } + + private void Lay() + { + if (_laidFor == Width) + { + return; + } + _laid.Clear(); + _dots.Clear(); + int textWidth = TextWidth; + int num = 0; + int num2 = Px(8); + int num3 = Px(4); + int linePx = LinePx; + Font body = Fonts.Body; + Font bodyBold = Fonts.BodyBold; + int num4 = Math.Max(1, TextRenderer.MeasureText("a a", body, Size.Empty, TextFormatFlags.NoPrefix | TextFormatFlags.NoPadding).Width - TextRenderer.MeasureText("aa", body, Size.Empty, TextFormatFlags.NoPrefix | TextFormatFlags.NoPadding).Width); + int num5 = Px(16); + foreach (Block item5 in Reflow(_text, _headingLimit)) + { + if (_laid.Count > 0 || _dots.Count > 0) + { + num += (item5.GapBefore ? num2 : num3); + } + int num6 = (item5.Bullet ? num5 : 0); + if (item5.Bullet) + { + _dots.Add(new Point(0, num)); + } + List<(string, bool)> list = new List<(string, bool)>(); + string[] array = item5.Lead.Split(' ', StringSplitOptions.RemoveEmptyEntries); + foreach (string item in array) + { + list.Add((item, true)); + } + array = item5.Text.Split(' ', StringSplitOptions.RemoveEmptyEntries); + foreach (string item2 in array) + { + list.Add((item2, item5.Heading)); + } + int num7 = num6; + foreach (var item6 in list) + { + string item3 = item6.Item1; + bool item4 = item6.Item2; + int width = TextRenderer.MeasureText(item3, item4 ? bodyBold : body, Size.Empty, TextFormatFlags.NoPrefix | TextFormatFlags.NoPadding).Width; + if (num7 > num6 && num7 + width > textWidth) + { + num7 = num6; + num += linePx; + } + _laid.Add((new Point(num7, num), item3, item4)); + num7 += width + num4; + } + num += linePx; + } + _contentHeight = num; + _laidFor = Width; + _scroll = Math.Clamp(_scroll, 0, MaxScroll); + } + + private void ScrollBy(int pixels) + { + Lay(); + int num = Math.Clamp(_scroll + pixels, 0, MaxScroll); + if (num != _scroll) + { + _scroll = num; + Invalidate(); + } + } + + public bool ScrollByKey(Keys key) + { + switch (key) + { + case Keys.Up: + ScrollBy(-LinePx); + return true; + case Keys.Down: + ScrollBy(LinePx); + return true; + case Keys.Prior: + ScrollBy(-Math.Max(LinePx, Height - LinePx)); + return true; + case Keys.Next: + ScrollBy(Math.Max(LinePx, Height - LinePx)); + return true; + case Keys.Home: + ScrollBy(-1073741823); + return true; + case Keys.End: + ScrollBy(1073741823); + return true; + default: + return false; + } + } + + public void Wheel(int delta) + { + ScrollBy(-delta * 3 * LinePx / 120); + } + + protected override void OnMouseWheel(MouseEventArgs e) + { + HandledMouseEventArgs e2 = (e as HandledMouseEventArgs) ?? new HandledMouseEventArgs(e.Button, e.Clicks, e.X, e.Y, e.Delta); + e2.Handled = true; + base.OnMouseWheel(e2); + Wheel(e.Delta); + } + + protected override void OnMouseMove(MouseEventArgs e) + { + base.OnMouseMove(e); + if (_dragging) + { + Rectangle thumb = Thumb; + int num = Math.Max(1, Height - thumb.Height); + int num2 = _dragScrollFrom + (int)((long)(e.Y - _dragFrom) * (long)MaxScroll / num); + ScrollBy(num2 - _scroll); + return; + } + bool flag = Lane.Contains(e.Location) && !Thumb.IsEmpty; + if (flag != _thumbHot) + { + _thumbHot = flag; + Invalidate(Lane); + } + } + + protected override void OnMouseLeave(EventArgs e) + { + base.OnMouseLeave(e); + if (_thumbHot) + { + _thumbHot = false; + Invalidate(Lane); + } + } + + protected override void OnMouseDown(MouseEventArgs e) + { + base.OnMouseDown(e); + Rectangle thumb = Thumb; + if (e.Button == MouseButtons.Left && !thumb.IsEmpty && Lane.Contains(e.Location)) + { + if (e.Y < thumb.Top) + { + ScrollByKey(Keys.Prior); + return; + } + if (e.Y >= thumb.Bottom) + { + ScrollByKey(Keys.Next); + return; + } + _dragging = true; + _dragFrom = e.Y; + _dragScrollFrom = _scroll; + Capture = true; + Invalidate(Lane); + } + } + + protected override void OnMouseUp(MouseEventArgs e) + { + base.OnMouseUp(e); + if (_dragging) + { + _dragging = false; + Capture = false; + Invalidate(Lane); + } + } + + protected override void OnResize(EventArgs e) + { + base.OnResize(e); + _laidFor = -1; + } + + protected override void OnPaint(PaintEventArgs e) + { + Lay(); + Graphics graphics = e.Graphics; + if (!_onCard) + { + using SolidBrush brush = new SolidBrush(ControlInk.Overlay); + graphics.FillRectangle(brush, ClientRectangle); + } + Font body = Fonts.Body; + Font bodyBold = Fonts.BodyBold; + int linePx = LinePx; + int num = Px(4); + SmoothingMode smoothingMode = graphics.SmoothingMode; + graphics.SmoothingMode = SmoothingMode.AntiAlias; + using (SolidBrush brush2 = new SolidBrush(ControlInk.Text2)) + { + foreach (Point dot in _dots) + { + int num2 = dot.Y - _scroll; + if (num2 + linePx >= 0 && num2 <= Height) + { + graphics.FillEllipse(brush2, dot.X + Px(4), (float)num2 + (float)(linePx - num) / 2f, num, num); + } + } + } + graphics.SmoothingMode = smoothingMode; + foreach (var item4 in _laid) + { + Point item = item4.At; + string item2 = item4.Word; + bool item3 = item4.Strong; + int num3 = item.Y - _scroll; + if (num3 + linePx >= 0 && num3 <= Height) + { + TextRenderer.DrawText(graphics, item2, item3 ? bodyBold : body, new Point(item.X, num3), item3 ? ControlInk.Text1 : ControlInk.Text2, TextFormatFlags.NoPrefix | TextFormatFlags.SingleLine | TextFormatFlags.NoPadding); + } + } + Rectangle thumb = Thumb; + if (thumb.IsEmpty) + { + return; + } + Color color; + if (_dragging) + { + color = ControlInk.Text1; + } + else + { + color = (_thumbHot ? ControlInk.Text2 : ControlInk.Edge); + } + SmoothingMode smoothingMode2 = graphics.SmoothingMode; + graphics.SmoothingMode = SmoothingMode.AntiAlias; + using (SolidBrush brush3 = new SolidBrush(color)) + { + using GraphicsPath path = Glass.RoundedPath(thumb, (float)thumb.Width / 2f); + graphics.FillPath(brush3, path); + } + graphics.SmoothingMode = smoothingMode2; + } + + internal static List Reflow(string plain) + { + return Reflow(plain, 48); + } + + internal static List Reflow(string plain, int headingLimit) + { + List blocks = new List(); + string[] array = (plain ?? "").Replace("\r\n", "\n").Replace('\r', '\n').Split('\n'); + StringBuilder text = new StringBuilder(); + bool bullet = false; + bool gap = false; + bool open = false; + int lineCount = 0; + for (int i = 0; i < array.Length; i++) + { + string text2 = array[i].Trim(); + if (text2.Length == 0) + { + Flush(followedByBlank: true); + gap = true; + continue; + } + if (text2[0] == '•' || ((text2[0] == '-' || text2[0] == '*') && text2.Length > 1 && char.IsWhiteSpace(text2[1]))) + { + Flush(followedByBlank: false); + bullet = true; + text2 = text2.Substring(1).TrimStart(); + } + else if (!open) + { + bullet = false; + } + if (open) + { + text.Append(' '); + } + text.Append(text2); + open = true; + lineCount++; + } + Flush(followedByBlank: true); + return blocks; + void Flush(bool followedByBlank) + { + if (open) + { + string text3 = text.ToString().Trim(); + string lead = ""; + if (bullet) + { + Match match = LeadIn.Match(text3); + if (match.Success) + { + lead = match.Groups["lead"].Value; + text3 = match.Groups["rest"].Value; + } + } + int num; + if (((!bullet && lineCount == 1) & followedByBlank) && text3.Length <= headingLimit && !text3.Contains("://")) + { + string text4 = text3; + num = ((".:!?".IndexOf(text4[text4.Length - 1]) < 0) ? 1 : 0); + } + else + { + num = 0; + } + bool heading = (byte)num != 0; + blocks.Add(new Block(lead, text3, bullet, heading, gap && blocks.Count > 0)); + text.Clear(); + open = false; + gap = false; + lineCount = 0; + } + } + } + + internal void WheelForTest(int delta) + { + Wheel(delta); + } +} diff --git a/VibranceHud/Controls/Prompt.cs b/VibranceHud/Controls/Prompt.cs new file mode 100644 index 0000000..930b5e7 --- /dev/null +++ b/VibranceHud/Controls/Prompt.cs @@ -0,0 +1,128 @@ +using System; +using System.Drawing; +using System.Windows.Forms; +using VibranceHud.Design; + +namespace VibranceHud.Controls; + +public static class Prompt +{ + public static string Ask(string title, string initial) + { + return Ask(title, initial, null); + } + + public static string Ask(string title, string initial, string? body) + { + GlassTextBox box; + using GlassShellForm glassShellForm = Build(title, initial, body, out box); + return (glassShellForm.ShowDialog() == DialogResult.OK) ? box.Text : ""; + } + + internal static GlassShellForm Build(string title, string initial, out GlassTextBox box) + { + return Build(title, initial, null, out box); + } + + internal static GlassShellForm Build(string title, string initial, string? body, out GlassTextBox box) + { + int num = S(24); + int num2 = S(400); + int num3 = num2 - 2 * num; + int num4 = S(32); + Label label = SignalDialogWindow.TitleLabel(title, num + S(2), S(23), num3); + Label label2 = null; + int num5 = S(60); + if (!string.IsNullOrEmpty(body)) + { + int height = SignalDialogWindow.MeasureBody(body, num3); + label2 = SignalDialogWindow.BodyLabel(body, num + S(2), S(60), num3, height); + num5 = label2.Bottom + S(16); + } + int num6 = num5 + num4 + S(24); + GlassShellForm form = new GlassShellForm(title) + { + PaintsTitle = false, + ClientSize = new Size(num2, num6 + num4 + S(20)) + }; + GlassTextBox field = new GlassTextBox + { + Text = initial, + MaxLength = 40, + FocusOnEdge = true, + Location = new Point(num, num5), + Size = new Size(num3, num4) + }; + GlassButton ok = new GlassButton + { + Text = "Save", + Kind = GlassButtonKind.Primary + }; + ok.Size = new Size(SignalDialogWindow.TwinButtonWidth(ok.Text, ok.Font, S(20), S(96)), num4); + ok.Location = new Point(num2 - num - ok.Width, num6); + ok.Click += (object? s, EventArgs e) => + { + Finish(DialogResult.OK); + }; + GlassButton glassButton = new GlassButton + { + Text = "Cancel", + Kind = GlassButtonKind.Secondary + }; + glassButton.Size = new Size(SignalDialogWindow.TwinButtonWidth(glassButton.Text, glassButton.Font, S(20), S(96)), num4); + glassButton.Location = new Point(ok.Left - S(8) - glassButton.Width, num6); + glassButton.Click += (object? s, EventArgs e) => + { + Finish(DialogResult.Cancel); + }; + field.TextChanged += (object? s, EventArgs e) => + { + SyncSave(); + }; + SyncSave(); + form.KeyDown += (object? s, KeyEventArgs e) => + { + if (e.KeyCode == Keys.Return) + { + e.Handled = true; + e.SuppressKeyPress = true; + if (ok.Enabled) + { + Finish(DialogResult.OK); + } + } + }; + form.ShowClose = false; + form.Controls.Add(label); + WindowDrag.Enable(label, form); + if (label2 != null) + { + form.Controls.Add(label2); + WindowDrag.Enable(label2, form); + } + form.Controls.Add(field); + form.Controls.Add(ok); + form.Controls.Add(glassButton); + form.ActiveControl = field; + form.Shown += (object? s, EventArgs e) => + { + field.Inner.SelectionLength = 0; + field.Inner.SelectionStart = field.Inner.TextLength; + }; + box = field; + return form; + void Finish(DialogResult r) + { + form.DialogResult = r; + form.Close(); + } + static int S(int logical) + { + return Tokens.Scale(logical); + } + void SyncSave() + { + ok.Enabled = !string.IsNullOrWhiteSpace(field.Text); + } + } +} diff --git a/VibranceHud/Controls/QuietScrollPanel.cs b/VibranceHud/Controls/QuietScrollPanel.cs new file mode 100644 index 0000000..cef859f --- /dev/null +++ b/VibranceHud/Controls/QuietScrollPanel.cs @@ -0,0 +1,125 @@ +using System; +using System.Drawing; +using System.Runtime.InteropServices; +using System.Windows.Forms; + +namespace VibranceHud.Controls; + +public sealed class QuietScrollPanel : Panel +{ + private const int SB_BOTH = 3; + + [DllImport("user32.dll")] + private static extern bool ShowScrollBar(nint hWnd, int wBar, bool bShow); + + public QuietScrollPanel() + { + AutoScroll = true; + BackColor = Color.Transparent; + } + + internal void ScrollByWheel(int delta) + { + OnMouseWheel(new MouseEventArgs(MouseButtons.None, 0, 0, 0, delta)); + } + + protected override void OnMouseWheel(MouseEventArgs e) + { + int num = DisplayRectangle.Height - ClientSize.Height; + if (AutoScroll && num > 0) + { + int num2 = SystemInformation.MouseWheelScrollLines; + if (num2 <= 0) + { + num2 = 3; + } + int num3 = e.Delta * num2 * 22 / 120; + int y = Math.Clamp(-AutoScrollPosition.Y - num3, 0, num); + AutoScrollPosition = new Point(-AutoScrollPosition.X, y); + if (e is HandledMouseEventArgs e2) + { + e2.Handled = true; + } + } + else + { + base.OnMouseWheel(e); + } + Invalidate(invalidateChildren: true); + } + + internal void TestScrollWheel(int delta) + { + OnMouseWheel(new MouseEventArgs(MouseButtons.None, 0, 0, 0, delta)); + } + + protected override Point ScrollToControl(Control activeControl) + { + return DisplayRectangle.Location; + } + + private void ForwardWheel(object? sender, MouseEventArgs e) + { + OnMouseWheel(e); + } + + private void Hook(Control root) + { + foreach (Control control in root.Controls) + { + control.MouseWheel -= ForwardWheel; + control.MouseWheel += ForwardWheel; + control.ControlAdded -= OnDescendantAdded; + control.ControlAdded += OnDescendantAdded; + Hook(control); + } + } + + private void OnDescendantAdded(object? sender, ControlEventArgs e) + { + Control control = e.Control; + if (control != null) + { + control.MouseWheel -= ForwardWheel; + control.MouseWheel += ForwardWheel; + Hook(control); + } + } + + protected override void OnControlAdded(ControlEventArgs e) + { + base.OnControlAdded(e); + OnDescendantAdded(this, e); + } + + protected override void OnHandleCreated(EventArgs e) + { + base.OnHandleCreated(e); + Hook(this); + HideBars(); + } + + protected override void OnLayout(LayoutEventArgs e) + { + base.OnLayout(e); + HideBars(); + } + + protected override void WndProc(ref Message m) + { + base.WndProc(ref m); + int msg = m.Msg; + if ((msg == 131 || (uint)(msg - 276) <= 1u) ? true : false) + { + HideBars(); + } + } + + private void HideBars() + { + if (IsHandleCreated && !IsDisposed) + { + ShowScrollBar(Handle, 3, bShow: false); + } + } +} diff --git a/VibranceHud/Controls/RevertConfirmForm.cs b/VibranceHud/Controls/RevertConfirmForm.cs new file mode 100644 index 0000000..0a2783a --- /dev/null +++ b/VibranceHud/Controls/RevertConfirmForm.cs @@ -0,0 +1,364 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; +using VibranceHud.Design; + +namespace VibranceHud.Controls; + +public sealed class RevertConfirmForm : SignalDialogWindow +{ + private static class Shape + { + public const int Width = 462; + + public const int Pad = 24; + + public const int TitleY = 23; + + public const int BodyY = 60; + + public const int BarGap = 26; + + public const int FillH = 4; + + public const int TrackH = 2; + + public const int CountdownW = 24; + + public const int CountdownGap = 14; + + public const int CaptionGap = 15; + + public const int ButtonGap = 39; + + public const int BottomPad = 20; + + public const int ButtonPad = 20; + + public const int ButtonSplit = 8; + + public const int Radius = 8; + } + + private sealed class ProgressTrack : Control + { + public float Fraction { get; set; } = 1f; + + public ProgressTrack() + { + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + SetStyle(ControlStyles.Selectable, value: false); + TabStop = false; + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics graphics = e.Graphics; + graphics.SmoothingMode = SmoothingMode.AntiAlias; + float num = Math.Max(1, Tokens.Scale(2)); + float y = ((float)Height - num) / 2f; + using (SolidBrush brush = new SolidBrush(Theme.AccentDim)) + { + FillPill(graphics, brush, new RectangleF(0f, y, Width, num), num / 2f); + } + float num2 = Math.Clamp(Fraction, 0f, 1f) * (float)Width; + if (num2 >= (float)Height) + { + using (SolidBrush brush2 = new SolidBrush(Theme.Accent)) + { + FillPill(graphics, brush2, new RectangleF(0f, 0f, num2, Height), (float)Height / 2f); + } + } + } + + private static void FillPill(Graphics g, Brush brush, RectangleF r, float radius) + { + if (r.Width < 1f || r.Height < 1f) + { + return; + } + using GraphicsPath path = Glass.RoundedPath(r, radius); + g.FillPath(brush, path); + } + } + + private readonly Timer _timer; + + private readonly Label _title; + + private readonly Label _body; + + private readonly ProgressTrack _progress; + + private readonly Label _countdown; + + private readonly Label _safetyCaption; + + private readonly GlassButton _keep; + + private readonly GlassButton _goBack; + + private readonly int _totalSeconds; + + private int _secondsLeft; + + private static readonly TimeSpan ArmAfter = TimeSpan.FromMilliseconds(400.0); + + private bool _armed; + + internal GlassButton TestKeepButton => _keep; + + internal GlassButton TestGoBackButton => _goBack; + + internal string TestCountdownText => _countdown.Text; + + internal float TestProgressFraction => _progress.Fraction; + + internal string TestMessageText => _body.Text; + + internal string TestSafetyCaptionText => _safetyCaption.Text; + + internal int TestTimerIntervalMs => _timer.Interval; + + internal static int TestArmDelayMs => (int)ArmAfter.TotalMilliseconds; + + public event Action? Confirmed; + + private new static int S(int logical) + { + return Tokens.Scale(logical); + } + + public RevertConfirmForm(string message, int graceSeconds) + { + _totalSeconds = Math.Max(1, graceSeconds); + _secondsLeft = _totalSeconds; + StartPosition = FormStartPosition.CenterScreen; + TopMost = true; + AccessibleName = "Keep this display mode?"; + AccessibleDescription = message; + int num = S(24); + int num2 = S(462); + int num3 = num2 - 2 * num; + _title = SignalDialogWindow.TitleLabel("Keep this display mode?", num + S(2), S(23), num3); + Controls.Add(_title); + int height = Math.Max(2 * Fonts.LineHeight(FontRole.Body), TextRenderer.MeasureText(message, Fonts.Body, new Size(num3, int.MaxValue), TextFormatFlags.WordBreak).Height); + _body = SignalDialogWindow.BodyLabel(message, num + S(2), S(60), num3, height); + Controls.Add(_body); + int num4 = _body.Bottom + S(26); + int num5 = S(24); + int num6 = num3 - num5 - S(14); + _progress = new ProgressTrack + { + Location = new Point(num, num4), + Size = new Size(num6, S(4)) + }; + Controls.Add(_progress); + _countdown = new Label + { + ForeColor = Theme.Text, + BackColor = Color.Transparent, + Font = Fonts.CaptionBold, + AutoSize = false, + TextAlign = ContentAlignment.MiddleRight, + UseMnemonic = false, + Location = new Point(num + num6 + S(14), num4 + S(4) / 2 - S(8)), + Size = new Size(num5 + SignalDialogWindow.GlyphPad(Fonts.CaptionBold), S(16)) + }; + Controls.Add(_countdown); + int num7 = num4 + S(4) + S(15); + _safetyCaption = new Label + { + Text = "Doing nothing is safe: the old mode comes back.", + ForeColor = Theme.TextDim, + BackColor = Color.Transparent, + Font = Fonts.Caption, + AutoSize = false, + TextAlign = ContentAlignment.TopLeft, + UseMnemonic = false, + Location = new Point(SignalDialogWindow.Ink(num + S(2), Fonts.Caption), num7), + Size = new Size(num3, Fonts.LineHeight(FontRole.Caption)) + }; + Controls.Add(_safetyCaption); + int num8 = num7 + _safetyCaption.Height + S(39); + int num9 = S(32); + _keep = new GlassButton + { + Text = "Keep this mode", + Kind = GlassButtonKind.Primary, + Name = "RevertConfirmKeep" + }; + _keep.Size = new Size(ButtonWidth(_keep.Text, _keep.Font), num9); + _keep.Location = new Point(num2 - num - _keep.Width, num8); + _keep.Click += (object? _, EventArgs _) => + { + Accept(); + }; + Controls.Add(_keep); + _goBack = new GlassButton + { + Text = "Go back now", + Kind = GlassButtonKind.Secondary, + Name = "RevertConfirmGoBack" + }; + _goBack.Size = new Size(ButtonWidth(_goBack.Text, _goBack.Font), num9); + _goBack.Location = new Point(_keep.Left - S(8) - _goBack.Width, num8); + _goBack.Click += (object? _, EventArgs _) => + { + Close(); + }; + Controls.Add(_goBack); + _goBack.TabIndex = 0; + _keep.TabIndex = 1; + ActiveControl = _goBack; + ClientSize = new Size(num2, num8 + num9 + S(20)); + UpdateCountdown(); + _timer = new Timer + { + Interval = 1000 + }; + _timer.Tick += (object? _, EventArgs _) => + { + Tick(); + }; + KeyDown += (object? _, KeyEventArgs e) => + { + if (e.KeyCode == Keys.Escape) + { + Swallow(e); + GoBack(); + } + else if (e.KeyCode == Keys.Return) + { + Swallow(e); + if (_armed) + { + GoBack(); + } + } + else if (!_armed) + { + Swallow(e); + } + }; + } + + private static void Swallow(KeyEventArgs e) + { + e.Handled = true; + e.SuppressKeyPress = true; + } + + private void GoBack() + { + _timer.Stop(); + _goBack.PerformClick(); + } + + protected override bool ProcessDialogKey(Keys keyData) + { + if ((keyData & (Keys.Control | Keys.Alt)) == 0) + { + switch (keyData & Keys.KeyCode) + { + case Keys.Escape: + GoBack(); + return true; + case Keys.Return: + if (_armed) + { + GoBack(); + } + return true; + case Keys.Tab: + if (!_armed) + { + return true; + } + break; + case Keys.Left: + case Keys.Up: + case Keys.Right: + case Keys.Down: + return true; + } + } + return base.ProcessDialogKey(keyData); + } + + private static int ButtonWidth(string text, Font font) + { + return TextRenderer.MeasureText(text, font).Width + S(20); + } + + private void Accept() + { + _timer.Stop(); + Confirmed?.Invoke(); + Close(); + } + + private void Tick() + { + _secondsLeft--; + if (_secondsLeft <= 0) + { + Close(); + } + else + { + UpdateCountdown(); + } + } + + private void UpdateCountdown() + { + _countdown.Text = $"{_secondsLeft} s"; + _progress.Fraction = ((_totalSeconds <= 0) ? 0f : ((float)_secondsLeft / (float)_totalSeconds)); + } + + protected override void OnShown(EventArgs e) + { + base.OnShown(e); + _timer.Start(); + ActiveControl = _goBack; + Activate(); + Timer arm = new Timer + { + Interval = (int)ArmAfter.TotalMilliseconds + }; + arm.Tick += (object? _, EventArgs _) => + { + _armed = true; + arm.Stop(); + arm.Dispose(); + }; + arm.Start(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _timer.Dispose(); + } + base.Dispose(disposing); + } + + internal void TestAdvanceOneSecond() + { + Tick(); + } + + internal void TestArmEnterNow() + { + _armed = true; + } + + internal void TestPressKey(Keys key) + { + OnKeyDown(new KeyEventArgs(key)); + } +} diff --git a/VibranceHud/Controls/RovingFocus.cs b/VibranceHud/Controls/RovingFocus.cs new file mode 100644 index 0000000..e4e3d77 --- /dev/null +++ b/VibranceHud/Controls/RovingFocus.cs @@ -0,0 +1,172 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Windows.Forms; + +namespace VibranceHud.Controls; + +internal sealed class RovingFocus +{ + private static readonly ConditionalWeakTable ByItem = new ConditionalWeakTable(); + + [ThreadStatic] + private static List>? _groups; + + private readonly Control[] _items; + + private readonly Func _isSelected; + + private readonly Func _arrowChooses; + + internal IReadOnlyList Items => _items; + + private RovingFocus(Control[] items, Func isSelected, Func arrowChooses) + { + _items = items; + _isSelected = isSelected; + _arrowChooses = arrowChooses; + } + + internal static RovingFocus Attach(IEnumerable items, Func isSelected, Func? arrowChooses = null) + { + RovingFocus rovingFocus = new RovingFocus(items.ToArray(), isSelected, arrowChooses ?? ((Func)((Control _) => true))); + Control[] items2 = rovingFocus._items; + foreach (Control key in items2) + { + ByItem.AddOrUpdate(key, rovingFocus); + } + (_groups ?? (_groups = new List>())).Add(new WeakReference(rovingFocus)); + rovingFocus.Refresh(); + return rovingFocus; + } + + internal static RovingFocus? Of(Control item) + { + if (!ByItem.TryGetValue(item, out RovingFocus value)) + { + return null; + } + return value; + } + + private static bool Usable(Control c) + { + if (!c.IsDisposed && c.Enabled) + { + return c.Visible; + } + return false; + } + + internal Control? Current() + { + Control control = null; + Control control2 = null; + Control[] items = _items; + foreach (Control control3 in items) + { + if (Usable(control3)) + { + if (_isSelected(control3)) + { + return control3; + } + if (control == null) + { + control = control3; + } + if (control3.Focused) + { + control2 = control3; + } + } + } + return control2 ?? control; + } + + internal void Refresh() + { + Control control = Current(); + if (control == null) + { + return; + } + Control[] items = _items; + foreach (Control control2 in items) + { + if (!control2.IsDisposed) + { + control2.TabStop = control2 == control; + } + } + } + + internal static void RefreshAll() + { + if (_groups == null) + { + return; + } + _groups.RemoveAll((WeakReference w) => !w.TryGetTarget(out RovingFocus target2) || target2._items.All((Control c) => c.IsDisposed)); + foreach (WeakReference group in _groups) + { + if (group.TryGetTarget(out var target)) + { + target.Refresh(); + } + } + } + + internal Control? Target(Control from, Keys keyData) + { + if ((keyData & Keys.Modifiers) != 0) + { + return null; + } + int num = Array.IndexOf(_items, from); + if (num < 0) + { + return null; + } + int num2 = _items.Length; + switch (keyData & Keys.KeyCode) + { + case Keys.Left: + case Keys.Up: + { + for (int j = 1; j <= num2; j++) + { + if (Usable(_items[(num - j + num2) % num2])) + { + return _items[(num - j + num2) % num2]; + } + } + return from; + } + case Keys.Right: + case Keys.Down: + { + for (int i = 1; i <= num2; i++) + { + if (Usable(_items[(num + i) % num2])) + { + return _items[(num + i) % num2]; + } + } + return from; + } + case Keys.Home: + return _items.FirstOrDefault(Usable) ?? from; + case Keys.End: + return _items.LastOrDefault(Usable) ?? from; + default: + return null; + } + } + + internal bool ArrowChooses(Control item) + { + return _arrowChooses(item); + } +} diff --git a/VibranceHud/Controls/SignalDialogWindow.cs b/VibranceHud/Controls/SignalDialogWindow.cs new file mode 100644 index 0000000..b93edb5 --- /dev/null +++ b/VibranceHud/Controls/SignalDialogWindow.cs @@ -0,0 +1,271 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; +using VibranceHud.Design; + +namespace VibranceHud.Controls; + +public abstract class SignalDialogWindow : Form +{ + public static class Measure + { + public const int Radius = 8; + + public const int Pad = 24; + + public const int TitleY = 23; + + public const int BodyY = 60; + + public const int BodyToContent = 16; + + public const int ContentToFooter = 24; + + public const int ButtonMinWidth = 96; + + public const int ButtonPadX = 12; + + public const int ButtonGap = 8; + + public const int FooterBottom = 20; + + public const int ButtonPad = 20; + + public const int WidthSm = 400; + + public const int WidthMd = 460; + + public const int WidthLg = 560; + } + + private readonly int _dpi; + + protected int ChromeDpi => _dpi; + + protected string? ChromeTitle { get; set; } + + protected string? ChromeBody { get; set; } + + protected int ChromeBodyHeight { get; set; } + + protected int TextWidth => ClientSize.Width - 2 * S(24); + + protected int BodyTop => S(60); + + protected int ContentTop => BodyTop + ChromeBodyHeight + S(16); + + protected virtual bool Square => false; + + internal static Color EdgeInk + { + get + { + if (!SlateSurface.Active) + { + return SignalTokens.Ash.WindowEdge; + } + return ControlInk.Over(SignalTokens.Slate.WindowEdge, ControlInk.Overlay); + } + } + + protected SignalDialogWindow() + { + _dpi = SignalInk.DpiFor(this); + FormBorderStyle = FormBorderStyle.None; + StartPosition = FormStartPosition.CenterParent; + ShowInTaskbar = false; + BackColor = Theme.Background; + DoubleBuffered = true; + Icon = AppIcon.Value; + KeyPreview = true; + Font = Fonts.Body; + AccessibleRole = AccessibleRole.Dialog; + Opacity = 0.99; + Load += (object? _, EventArgs _) => + { + ApplyRegion(); + }; + Resize += (object? _, EventArgs _) => + { + ApplyRegion(); + }; + } + + protected int S(int logical) + { + return Tokens.ScaleAt(_dpi, logical); + } + + internal static int MeasureBody(string? body, int textWidth) + { + int val = Fonts.LineHeight(FontRole.Body); + if (string.IsNullOrEmpty(body)) + { + return 0; + } + int height = TextRenderer.MeasureText(body, Fonts.Body, new Size(Math.Max(1, textWidth), 0), TextFormatFlags.NoPrefix | TextFormatFlags.WordBreak).Height; + return Math.Max(val, height); + } + + internal static Label TitleLabel(string text, int inkLeft, int top, int width) + { + return new Label + { + Text = text, + ForeColor = Theme.Text, + BackColor = Color.Transparent, + Font = Fonts.Title, + AutoSize = false, + TextAlign = ContentAlignment.TopLeft, + UseMnemonic = false, + Location = new Point(Ink(inkLeft, Fonts.Title), top), + Size = new Size(width, Fonts.LineHeight(FontRole.Title)) + }; + } + + internal static Label BodyLabel(string text, int inkLeft, int top, int width, int height) + { + return new Label + { + Text = text, + ForeColor = Theme.TextDim, + BackColor = Color.Transparent, + Font = Fonts.Body, + AutoSize = false, + TextAlign = ContentAlignment.TopLeft, + UseMnemonic = false, + Location = new Point(Ink(inkLeft, Fonts.Body), top), + Size = new Size(width, height) + }; + } + + internal static int TwinButtonWidth(string text, Font font, int scaledPad, int scaledMin) + { + return Math.Max(scaledMin, TextRenderer.MeasureText(text, font).Width + scaledPad); + } + + protected GlassButton FooterButton(string text, GlassButtonKind kind, string? name = null) + { + GlassButton glassButton = new GlassButton + { + Text = text, + Kind = kind + }; + if (name != null) + { + glassButton.Name = name; + } + int width = Math.Max(S(96), TextRenderer.MeasureText(text, glassButton.Font).Width + 2 * S(12)); + glassButton.Size = new Size(width, S(32)); + glassButton.AccessibleName = text; + return glassButton; + } + + protected void PlaceFooter(params GlassButton[] leftToRight) + { + int num = S(24); + int num2 = ClientSize.Width - num; + for (int num3 = leftToRight.Length - 1; num3 >= 0; num3--) + { + GlassButton glassButton = leftToRight[num3]; + num2 -= glassButton.Width; + glassButton.Location = new Point(num2, ClientSize.Height - S(20) - glassButton.Height); + glassButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + num2 -= S(8); + } + } + + private void ApplyRegion() + { + if (Square) + { + if (Region != null) + { + Region = null; + } + return; + } + using GraphicsPath path = Glass.RoundedPath(new RectangleF(0f, 0f, ClientSize.Width, ClientSize.Height), S(8)); + Region = new Region(path); + } + + protected override void OnPaintBackground(PaintEventArgs e) + { + using SolidBrush brush = new SolidBrush(Theme.Background); + e.Graphics.FillRectangle(brush, ClientRectangle); + } + + protected override void OnPaint(PaintEventArgs e) + { + PaintChrome(e.Graphics, ClientSize, _dpi, Square); + PaintWords(e.Graphics); + base.OnPaint(e); + } + + internal static void PaintChrome(Graphics g, Size size, int dpi, bool square = false) + { + using (SolidBrush brush = new SolidBrush(Theme.Background)) + { + g.FillRectangle(brush, new Rectangle(Point.Empty, size)); + } + if (square) + { + using (SolidBrush brush2 = new SolidBrush(ControlInk.Overlay)) + { + g.FillRectangle(brush2, new Rectangle(Point.Empty, size)); + } + PaintSquareEdge(g, size, dpi); + } + else + { + ControlInk.PaintBox(g, size, Tokens.ScaleAt(dpi, 8), ControlInk.Hairline(dpi), ControlInk.Overlay, EdgeInk); + } + } + + internal static void PaintSquareEdge(Graphics g, Size size, int dpi) + { + int num = Math.Min(ControlInk.Hairline(dpi), Math.Min(size.Width, size.Height) / 2); + SmoothingMode smoothingMode = g.SmoothingMode; + PixelOffsetMode pixelOffsetMode = g.PixelOffsetMode; + g.SmoothingMode = SmoothingMode.None; + g.PixelOffsetMode = PixelOffsetMode.None; + try + { + using SolidBrush brush = new SolidBrush(EdgeInk); + g.FillRectangle(brush, 0, 0, size.Width, num); + g.FillRectangle(brush, 0, size.Height - num, size.Width, num); + g.FillRectangle(brush, 0, 0, num, size.Height); + g.FillRectangle(brush, size.Width - num, 0, num, size.Height); + } + finally + { + g.SmoothingMode = smoothingMode; + g.PixelOffsetMode = pixelOffsetMode; + } + } + + private void PaintWords(Graphics g) + { + int num = S(24); + int textWidth = TextWidth; + if (!string.IsNullOrEmpty(ChromeTitle)) + { + TextRenderer.DrawText(g, ChromeTitle, Fonts.Title, new Rectangle(Ink(num + S(2), Fonts.Title), S(23), textWidth + GlyphPad(Fonts.Title), Fonts.LineHeight(FontRole.Title)), Theme.Text, TextFormatFlags.EndEllipsis | TextFormatFlags.NoPrefix | TextFormatFlags.SingleLine); + } + if (!string.IsNullOrEmpty(ChromeBody)) + { + TextRenderer.DrawText(g, ChromeBody, Fonts.Body, new Rectangle(Ink(num + S(2), Fonts.Body), BodyTop, textWidth + GlyphPad(Fonts.Body), ChromeBodyHeight), Theme.TextDim, TextFormatFlags.NoPrefix | TextFormatFlags.WordBreak); + } + } + + internal static int GlyphPad(Font font) + { + return (TextRenderer.MeasureText("H", font).Width - TextRenderer.MeasureText("H", font, Size.Empty, TextFormatFlags.NoPadding).Width) / 2; + } + + internal static int Ink(int x, Font font) + { + return x - GlyphPad(font); + } +} diff --git a/VibranceHud/Controls/SignalToolTip.cs b/VibranceHud/Controls/SignalToolTip.cs new file mode 100644 index 0000000..2a38d64 --- /dev/null +++ b/VibranceHud/Controls/SignalToolTip.cs @@ -0,0 +1,79 @@ +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; +using VibranceHud.Design; + +namespace VibranceHud.Controls; + +public sealed class SignalToolTip : ToolTip +{ + internal const int PadX = 8; + + internal const int PadY = 4; + + internal const int MaxWidth = 280; + + internal const int Radius = 4; + + private static int Dpi => Tokens.Dpi; + + public SignalToolTip() + { + OwnerDraw = true; + UseAnimation = false; + UseFading = false; + InitialDelay = 500; + ReshowDelay = 120; + AutoPopDelay = 32767; + BackColor = ControlInk.Overlay; + ForeColor = ControlInk.Text1; + Draw += (object? _, DrawToolTipEventArgs e) => + { + Paint(e.Graphics, e.Bounds, e.ToolTipText, GroundOf(e.AssociatedControl)); + }; + Popup += (object? _, PopupEventArgs e) => + { + e.ToolTipSize = Measure(GetToolTip(e.AssociatedControl) ?? string.Empty); + }; + } + + internal static Color GroundOf(Control? c) + { + while (c != null) + { + Color backColor = c.BackColor; + if (backColor.A == byte.MaxValue && !backColor.IsEmpty && backColor.ToArgb() != Control.DefaultBackColor.ToArgb()) + { + return backColor; + } + c = c.Parent; + } + return Theme.Background; + } + + internal static Size Measure(string text) + { + int dpi = Dpi; + int num = Tokens.ScaleAt(dpi, 8); + int num2 = Tokens.ScaleAt(dpi, 4); + int width = Tokens.ScaleAt(dpi, 280) - 2 * num; + Size size = TextRenderer.MeasureText(text, Fonts.Caption, new Size(width, 0), TextFormatFlags.NoPrefix | TextFormatFlags.WordBreak | TextFormatFlags.NoPadding); + return new Size(size.Width + 2 * num, size.Height + 2 * num2); + } + + internal static void Paint(Graphics g, Rectangle bounds, string text, Color? ground = null) + { + int dpi = Dpi; + using (SolidBrush brush = new SolidBrush(ground ?? Theme.Background)) + { + g.FillRectangle(brush, bounds); + } + GraphicsState gstate = g.Save(); + g.TranslateTransform(bounds.X, bounds.Y); + ControlInk.PaintBox(g, bounds.Size, Tokens.ScaleAt(dpi, 4), ControlInk.Hairline(dpi), ControlInk.Overlay, SignalDialogWindow.EdgeInk); + g.Restore(gstate); + int num = Tokens.ScaleAt(dpi, 8); + int num2 = Tokens.ScaleAt(dpi, 4); + TextRenderer.DrawText(g, text, Fonts.Caption, new Rectangle(bounds.X + num, bounds.Y + num2, bounds.Width - 2 * num, bounds.Height - 2 * num2), ControlInk.Text1, TextFormatFlags.NoPrefix | TextFormatFlags.WordBreak | TextFormatFlags.NoPadding); + } +} diff --git a/VibranceHud/Controls/TheClipboard.cs b/VibranceHud/Controls/TheClipboard.cs new file mode 100644 index 0000000..5c9878a --- /dev/null +++ b/VibranceHud/Controls/TheClipboard.cs @@ -0,0 +1,33 @@ +using System; +using System.Windows.Forms; + +namespace VibranceHud.Controls; + +internal static class TheClipboard +{ + internal static Action? InsteadOfTheRealOneForTest { get; set; } + + internal static bool Put(string text) + { + if (string.IsNullOrEmpty(text)) + { + return false; + } + Action insteadOfTheRealOneForTest = InsteadOfTheRealOneForTest; + if (insteadOfTheRealOneForTest != null) + { + insteadOfTheRealOneForTest(text); + return true; + } + try + { + Clipboard.SetText(text); + return true; + } + catch (Exception ex) + { + CrashLog.Write(ex); + return false; + } + } +} diff --git a/VibranceHud/Controls/VoteButton.cs b/VibranceHud/Controls/VoteButton.cs new file mode 100644 index 0000000..0df78a6 --- /dev/null +++ b/VibranceHud/Controls/VoteButton.cs @@ -0,0 +1,178 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; +using VibranceHud.Design; + +namespace VibranceHud.Controls; + +public sealed class VoteButton : Control +{ + private bool _active; + + private readonly HoverFade _fade; + + private readonly HoverFade _press; + + public bool ThumbUp { get; init; } + + public Func Tint { get; init; } = () => Theme.Accent; + + public bool Active + { + get + { + return _active; + } + set + { + if (_active != value) + { + _active = value; + Invalidate(); + } + } + } + + public VoteButton() + { + _fade = new HoverFade(this); + _press = new HoverFade(this); + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + Cursor = Cursors.Hand; + Size = new Size(64, 40); + TabStop = true; + SetStyle(ControlStyles.Selectable, value: true); + AccessibleRole = AccessibleRole.RadioButton; + } + + protected override void OnTextChanged(EventArgs e) + { + base.OnTextChanged(e); + AccessibleName = Text; + } + + protected override void OnGotFocus(EventArgs e) + { + base.OnGotFocus(e); + Invalidate(); + } + + protected override void OnLostFocus(EventArgs e) + { + base.OnLostFocus(e); + Invalidate(); + } + + protected override void OnMouseEnter(EventArgs e) + { + base.OnMouseEnter(e); + _fade.Set(hot: true); + Invalidate(); + } + + protected override void OnMouseLeave(EventArgs e) + { + base.OnMouseLeave(e); + _fade.Set(hot: false); + _press.Set(hot: false); + Invalidate(); + } + + protected override void OnMouseDown(MouseEventArgs e) + { + base.OnMouseDown(e); + Focus(); + if (e.Button == MouseButtons.Left) + { + _press.Snap(hot: true); + Invalidate(); + } + } + + protected override void OnMouseUp(MouseEventArgs e) + { + base.OnMouseUp(e); + _press.Set(hot: false); + Invalidate(); + } + + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + Keys keyCode = e.KeyCode; + if ((keyCode == Keys.Return || keyCode == Keys.Space) ? true : false) + { + e.Handled = true; + OnClick(EventArgs.Empty); + } + } + + internal void TestPressKey(Keys key) + { + OnKeyDown(new KeyEventArgs(key)); + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics graphics = e.Graphics; + graphics.SmoothingMode = SmoothingMode.AntiAlias; + Color color = Tint(); + float value = _press.Value; + float num = 1.5f * value; + RectangleF rect = new RectangleF(0.5f + num, 0.5f + num, (float)(Width - 1) - 2f * num, (float)(Height - 1) - 2f * num); + if (rect.Width <= 0f || rect.Height <= 0f) + { + return; + } + float num2 = rect.Height / 2f; + using (GraphicsPath path = Glass.RoundedPath(rect, num2)) + { + using (SolidBrush brush = new SolidBrush(Color.FromArgb(_active ? 210 : ((int)(26f + 34f * _fade.Value)), color))) + { + graphics.FillPath(brush, path); + } + using Pen pen = new Pen(Color.FromArgb(_active ? 235 : 110, color), 1f); + graphics.DrawPath(pen, path); + } + if (Focused) + { + using Pen pen2 = new Pen(Color.FromArgb(200, color), 2f); + using GraphicsPath path2 = Glass.RoundedPath(RectangleF.Inflate(rect, -2.5f, -2.5f), Math.Max(1f, num2 - 2.5f)); + graphics.DrawPath(pen2, path2); + } + Color color2 = (_active ? Theme.OnAccent : color); + DrawThumb(graphics, new Rectangle((int)(rect.X + rect.Width / 2f) - 9, (int)(rect.Y + rect.Height / 2f) - 9, 18, 18), color2, ThumbUp); + } + + private static void DrawThumb(Graphics g, Rectangle r, Color color, bool up) + { + GraphicsState gstate = g.Save(); + try + { + g.TranslateTransform((float)r.X + (float)r.Width / 2f, (float)r.Y + (float)r.Height / 2f); + if (!up) + { + g.ScaleTransform(1f, -1f); + } + float num = (float)r.Width / 20f; + g.ScaleTransform(num, num); + using SolidBrush brush = new SolidBrush(color); + using (GraphicsPath path = Glass.RoundedPath(new RectangleF(-3.5f, -9f, 5f, 9f), 2.5f)) + { + g.FillPath(brush, path); + } + using (GraphicsPath path2 = Glass.RoundedPath(new RectangleF(-3.5f, -2.5f, 11.5f, 9.5f), 2.5f)) + { + g.FillPath(brush, path2); + } + using GraphicsPath path3 = Glass.RoundedPath(new RectangleF(-9f, -1.5f, 4f, 8.5f), 1.5f); + g.FillPath(brush, path3); + } + finally + { + g.Restore(gstate); + } + } +} diff --git a/VibranceHud/Controls/ZoomSection.cs b/VibranceHud/Controls/ZoomSection.cs new file mode 100644 index 0000000..52e7ad1 --- /dev/null +++ b/VibranceHud/Controls/ZoomSection.cs @@ -0,0 +1,367 @@ +using System; +using System.Drawing; +using System.Globalization; +using System.Windows.Forms; +using VibranceHud.Design; +using VibranceHud.Zoom; + +namespace VibranceHud.Controls; + +public sealed class ZoomSection : Panel +{ + internal const string Title = "Hold to zoom"; + + internal const string FairPlay = "Zoom uses Windows' own Magnifier. Some games' rules treat zoom as an advantage - check yours."; + + internal const string LockedLine = "Zoom comes with the Dark Boost & Zoom add-on."; + + internal const string PickAKey = "Pick a key to hold."; + + internal const string EdgesWord = "Smooth edges"; + + internal const string EdgesHint = "Off: sharp pixels. On: softer, a little blurry."; + + private readonly AppSettings _settings; + + private readonly Action _save; + + private readonly Func _allowed; + + private readonly Func _bindKey; + + private readonly Func _whyRefused; + + private bool _syncing; + + private readonly Label _title; + + private readonly Label _keyWord; + + private readonly Label _levelWord; + + private readonly Label _levelValue; + + private readonly Label _smoothWord; + + private readonly Label _edgesWord; + + private readonly Label _edgesHint; + + private readonly Label _status; + + private readonly Label _fair; + + private readonly ToggleSwitch _on; + + private readonly ToggleSwitch _smooth; + + private readonly ToggleSwitch _edges; + + private readonly HotkeyPicker _key; + + private readonly FlatSlider _level; + + public int WantedHeight => RowPitch * 4 + EdgesBlockHeight() + Tokens.Scale(20) + FairHeight() + Tokens.Scale(8); + + private int RowPitch => Tokens.Scale(40); + + public int Gutter => FlatSlider.EdgeInsetAt(ControlInk.Dpi(this)); + + internal ToggleSwitch SwitchForTest => _on; + + internal ToggleSwitch EdgesForTest => _edges; + + internal HotkeyPicker KeyForTest => _key; + + internal FlatSlider LevelForTest => _level; + + internal string StatusForTest => _status.Text; + + public event Action? Changed; + + public ZoomSection(AppSettings settings, Action save, Func allowed, Func bindKey, Func whyRefused) + { + _settings = settings; + _save = save; + _allowed = allowed; + _bindKey = bindKey; + _whyRefused = whyRefused; + BackColor = Color.Transparent; + Name = "zoomSection"; + _title = Words("Hold to zoom", Fonts.BodyBold, Theme.Text); + _on = new ToggleSwitch + { + Size = new Size(40, 20), + AccessibleName = "Hold to zoom", + Name = "zoomSwitch" + }; + _on.CheckedChanged += (object? _, EventArgs _) => + { + if (!_syncing) + { + SetEnabled(_on.Checked); + } + }; + _keyWord = Words("Zoom key", Fonts.Body, Theme.TextDim); + _key = new HotkeyPicker + { + AllowMouseButtons = true, + AccessibleName = "Zoom key", + Name = "zoomKey" + }; + _key.HotkeyChanged += (uint mask, uint vk) => + { + ChooseKey(mask, vk); + }; + _levelWord = Words("Zoom level", Fonts.Body, Theme.TextDim); + _levelValue = Words("", Fonts.BodyBold, Theme.Text); + _levelValue.TextAlign = ContentAlignment.MiddleRight; + _level = new FlatSlider + { + AccessibleName = "Zoom level", + Name = "zoomLevel", + Minimum = (int)Math.Round(6.0), + Maximum = (int)Math.Round(16.0), + Value = (int)Math.Round(8.0) + }; + _level.ValueChanged += (object? _, EventArgs _) => + { + if (!_syncing) + { + SetLevel((float)_level.Value * 0.25f); + } + }; + _smoothWord = Words("Smooth", Fonts.Body, Theme.TextDim); + _smooth = new ToggleSwitch + { + Size = new Size(40, 20), + AccessibleName = "Smooth zoom", + Name = "zoomSmooth" + }; + _smooth.CheckedChanged += (object? _, EventArgs _) => + { + if (!_syncing) + { + SetSmooth(_smooth.Checked); + } + }; + _edgesWord = Words("Smooth edges", Fonts.Body, Theme.TextDim); + _edges = new ToggleSwitch + { + Size = new Size(40, 20), + AccessibleName = "Smooth edges", + Name = "zoomSmoothEdges" + }; + _edges.CheckedChanged += (object? _, EventArgs _) => + { + if (!_syncing) + { + SetSmoothEdges(_edges.Checked); + } + }; + _edgesHint = Words("Off: sharp pixels. On: softer, a little blurry.", Fonts.Caption, Theme.TextFaint); + _status = Words("", Fonts.Caption, Theme.TextDim); + _fair = Words("Zoom uses Windows' own Magnifier. Some games' rules treat zoom as an advantage - check yours.", Fonts.Caption, Theme.TextFaint); + Controls.AddRange(new Control[14] + { + _title, _on, _keyWord, _key, _levelWord, _levelValue, _level, _smoothWord, _smooth, _edgesWord, + _edges, _edgesHint, _status, _fair + }); + Sync(); + } + + private Label Words(string text, Font font, Color colour) + { + return new Label + { + Text = text, + Font = font, + ForeColor = colour, + BackColor = Color.Transparent, + TextAlign = ContentAlignment.MiddleLeft, + AutoSize = false, + UseMnemonic = false + }; + } + + private static int EdgesBlockHeight() + { + return Tokens.Scale(26) + Tokens.Scale(20) + Tokens.Scale(4); + } + + private int FairHeight() + { + return Tokens.Scale(36); + } + + protected override void OnLayout(LayoutEventArgs e) + { + base.OnLayout(e); + int gutter = Gutter; + int num = Math.Max(Tokens.Scale(200), ClientSize.Width - 2 * gutter); + int rowPitch = RowPitch; + int num2 = Tokens.Scale(26); + int num3 = Tokens.Scale(40); + int num4 = Tokens.Scale(20); + int num5 = 0; + _title.SetBounds(gutter - Ink(_title), num5, num - num3 - 8, num2); + _on.SetBounds(gutter + num - num3, num5 + (num2 - num4) / 2, num3, num4); + num5 += rowPitch; + int num6 = Math.Min(num - Tokens.Scale(110), Tokens.Scale(300)); + _keyWord.SetBounds(gutter - Ink(_keyWord), num5, Tokens.Scale(100), num2); + _key.SetBounds(gutter + num - num6, num5 - Tokens.Scale(4), num6, Tokens.Scale(36)); + num5 += rowPitch; + _levelWord.SetBounds(gutter - Ink(_levelWord), num5, num - Tokens.Scale(70), num2); + _levelValue.SetBounds(gutter + num - Tokens.Scale(70) + Ink(_levelValue), num5, Tokens.Scale(70), num2); + _level.SetTrackBounds(gutter, num5 + num2 + Tokens.Scale(2), num, Tokens.Scale(16)); + num5 += rowPitch + Tokens.Scale(8); + _smoothWord.SetBounds(gutter - Ink(_smoothWord), num5, num - num3 - 8, num2); + _smooth.SetBounds(gutter + num - num3, num5 + (num2 - num4) / 2, num3, num4); + num5 += rowPitch - Tokens.Scale(8); + _edgesWord.SetBounds(gutter - Ink(_edgesWord), num5, num - num3 - 8, num2); + _edges.SetBounds(gutter + num - num3, num5 + (num2 - num4) / 2, num3, num4); + num5 += num2; + _edgesHint.SetBounds(gutter - Ink(_edgesHint), num5, num, Tokens.Scale(20)); + num5 += Tokens.Scale(20) + Tokens.Scale(4); + _status.SetBounds(gutter - Ink(_status), num5, num, Tokens.Scale(20)); + _fair.SetBounds(gutter - Ink(_fair), num5 + Tokens.Scale(20), num, FairHeight()); + } + + private static int Ink(Label l) + { + return ControlInk.LabelInkInset(l.Font); + } + + public void Sync() + { + _syncing = true; + try + { + bool flag = _allowed(); + _on.Checked = _settings.ZoomEnabled & flag; + ToggleSwitch toggleSwitch = _on; + HotkeyPicker key = _key; + FlatSlider level = _level; + ToggleSwitch smooth = _smooth; + bool flag2 = (_edges.Enabled = flag); + bool flag4 = (smooth.Enabled = flag2); + bool flag6 = (level.Enabled = flag4); + bool enabled = (key.Enabled = flag6); + toggleSwitch.Enabled = enabled; + _key.ModifierMask = _settings.ZoomHotkeyModifierMask; + _key.VirtualKey = _settings.ZoomHotkeyVirtualKey; + float num = ZoomMath.ClampSetting(_settings.ZoomLevel); + _level.Value = (int)Math.Round(num / 0.25f); + _levelValue.Text = num.ToString("0.0#", CultureInfo.InvariantCulture) + "x"; + _smooth.Checked = _settings.ZoomSmooth; + _edges.Checked = _settings.ZoomSmoothEdges; + _status.Text = StatusLine(); + } + finally + { + _syncing = false; + } + } + + internal string StatusLine() + { + if (!_allowed()) + { + return "Zoom comes with the Dark Boost & Zoom add-on."; + } + string text = _whyRefused(); + if (text.Length > 0) + { + return text; + } + if (!_settings.ZoomEnabled) + { + return ""; + } + if (_settings.ZoomHotkeyVirtualKey == 0) + { + return "Pick a key to hold."; + } + string display = HotkeyPicker.GetDisplay(_settings.ZoomHotkeyModifierMask, _settings.ZoomHotkeyVirtualKey); + HotkeySlot? hotkeySlot = HotkeyConflicts.Owner(_settings, HotkeySlot.Zoom, _settings.ZoomHotkeyModifierMask, _settings.ZoomHotkeyVirtualKey); + if (hotkeySlot.HasValue) + { + HotkeySlot valueOrDefault = hotkeySlot.GetValueOrDefault(); + return display + " is taken by " + HotkeyConflicts.Describe(valueOrDefault) + ". Pick another key."; + } + return "Hold " + display + (_settings.HotkeysOnlyInGames ? " in a game to zoom." : " to zoom."); + } + + internal void SetEnabled(bool on) + { + if (!_allowed()) + { + Sync(); + return; + } + _settings.ZoomEnabled = on; + _save(); + Changed?.Invoke(); + Sync(); + } + + internal void ChooseKey(uint mask, uint vk) + { + if (_syncing) + { + return; + } + if (!_allowed()) + { + Sync(); + return; + } + if (vk == 0 || _bindKey(mask, vk)) + { + _settings.ZoomHotkeyModifierMask = ((vk != 0) ? mask : 0u); + _settings.ZoomHotkeyVirtualKey = vk; + _save(); + Changed?.Invoke(); + } + Sync(); + } + + internal void SetLevel(float level) + { + if (!_allowed()) + { + Sync(); + return; + } + _settings.ZoomLevel = ZoomMath.ClampSetting(level); + _save(); + Changed?.Invoke(); + Sync(); + } + + internal void SetSmooth(bool on) + { + if (!_allowed()) + { + Sync(); + return; + } + _settings.ZoomSmooth = on; + _save(); + Changed?.Invoke(); + Sync(); + } + + internal void SetSmoothEdges(bool on) + { + if (!_allowed()) + { + Sync(); + return; + } + _settings.ZoomSmoothEdges = on; + _save(); + Changed?.Invoke(); + Sync(); + } +} diff --git a/VibranceHud/CrashLog.cs b/VibranceHud/CrashLog.cs new file mode 100644 index 0000000..5e111cc --- /dev/null +++ b/VibranceHud/CrashLog.cs @@ -0,0 +1,284 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Text.RegularExpressions; +using VibranceHud.Licensing; + +namespace VibranceHud; + +public static class CrashLog +{ + public const int RetentionDays = 30; + + public const int MaxRetainedLogs = 50; + + private static readonly string CrashFileNamePrefix = "crash-"; + + private static readonly Regex[] RedactionPatterns = new Regex[5] + { + new Regex("[A-Z]:[\\\\/]Users[\\\\/][^\\\\\\/\\r\\n\\\"<>|*?]*[^\\\\\\/\\r\\n\\\"<>|*?\\s]", RegexOptions.Compiled), + new Regex("\\b[A-Z]{4}-[A-Z]-[FTP]-[A-Z2-9]{8}-[A-Z2-9]{8}\\b", RegexOptions.Compiled), + new Regex("\\b[A-Z2-9]{4}-[A-Z2-9]{4}-[A-Z2-9]{4}-[A-Z2-9]{4}\\b", RegexOptions.Compiled), + new Regex("\\b[A-Z2-9]{16}\\b", RegexOptions.Compiled), + new Regex("[A-Za-z0-9._%+\\-]+@[A-Za-z0-9\\-]+(?:\\.[A-Za-z0-9\\-]+)+", RegexOptions.Compiled) + }; + + private static readonly string[] RedactionReplacements = new string[5] { "", "", "", "", "" }; + + internal static readonly string[] SensitiveFolderNames = new string[3] { "Steam\\steamapps", "Steam\\userdata", "Epic Games" }; + + internal static readonly string[] SensitiveFolderReplacements = new string[3] { "", "", "" }; + + public static string CrashDirectory + { + get + { + string text = DirectoryForTest ?? Path.Combine(AppFolders.Local, "crashes"); + try + { + Directory.CreateDirectory(text); + } + catch + { + } + return text; + } + } + + internal static string? DirectoryForTest { get; set; } + + public static string Write(Exception ex) + { + try + { + if (ex == null) + { + return ""; + } + string crashDirectory = CrashDirectory; + string text = CrashFileNamePrefix + DateTime.UtcNow.ToString("yyyy-MM-dd-HHmmss-fff"); + string value = BuildReport(ex); + for (int i = 0; i <= 10; i++) + { + string path = text + ((i == 0) ? "" : ("-" + i)) + ".txt"; + string text2 = Path.Combine(crashDirectory, path); + FileStream fileStream; + try + { + fileStream = new FileStream(text2, FileMode.CreateNew, FileAccess.Write, FileShare.Read); + } + catch (IOException) when (File.Exists(text2)) + { + continue; + } + using (fileStream) + { + using StreamWriter streamWriter = new StreamWriter(fileStream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: true)); + streamWriter.Write(value); + } + return text2; + } + return ""; + } + catch + { + return ""; + } + } + + public static void Cleanup() + { + try + { + string crashDirectory = CrashDirectory; + if (!Directory.Exists(crashDirectory)) + { + return; + } + DateTime dateTime = DateTime.UtcNow.AddDays(-30.0); + List<(string, DateTime)> list = (from x in Directory.EnumerateFiles(crashDirectory, CrashFileNamePrefix + "*.txt").Select((string p) => + { + try + { + return (Path: p, Time: File.GetLastWriteTimeUtc(p)); + } + catch + { + return (Path: p, Time: DateTime.MinValue); + } + }) + orderby x.Time + select x).ToList(); + foreach (var item in list) + { + if (item.Item2 < dateTime) + { + try + { + File.Delete(item.Item1); + } + catch + { + } + } + } + List<(string, DateTime)> list2 = list.Where(((string Path, DateTime Time) f) => File.Exists(f.Path)).OrderByDescending(((string Path, DateTime Time) f) => f.Time).ToList(); + while (list2.Count > 50) + { + (string, DateTime) tuple = list2[list2.Count - 1]; + try + { + File.Delete(tuple.Item1); + } + catch + { + } + list2.RemoveAt(list2.Count - 1); + } + } + catch + { + } + } + + private static string BuildReport(Exception ex) + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.AppendLine("PlexusX crash report"); + stringBuilder.AppendLine("Generated: " + DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + " UTC"); + stringBuilder.AppendLine("Version: " + SafeVersion()); + stringBuilder.AppendLine("OS: " + SafeOs()); + stringBuilder.AppendLine(".NET: " + SafeDotnet()); + stringBuilder.AppendLine("Build: " + SafeBuild()); + stringBuilder.AppendLine("Resources: " + SafeResources()); + stringBuilder.AppendLine(); + AppendException(stringBuilder, ex); + return Redact(stringBuilder.ToString()); + } + + private static void AppendException(StringBuilder sb, Exception ex, int depth = 0) + { + if (ex == null || depth > 5) + { + return; + } + string text = new string(' ', depth * 2); + sb.AppendLine(text + "Exception type: " + ex.GetType().FullName); + sb.AppendLine(text + "Message: " + ex.Message); + sb.AppendLine(text + "Stack trace:"); + sb.AppendLine(text + ex.StackTrace); + if (ex is AggregateException ex2) + { + { + foreach (Exception item in ex2.InnerExceptions.Take(5)) + { + sb.AppendLine(text + "-- Inner exception --"); + AppendException(sb, item, depth + 1); + } + return; + } + } + if (ex.InnerException != null) + { + sb.AppendLine(text + "-- Inner exception --"); + AppendException(sb, ex.InnerException, depth + 1); + } + } + + private static string SafeVersion() + { + try + { + return UpdateService.CurrentVersion.ToString(); + } + catch + { + return "unknown"; + } + } + + private static string SafeOs() + { + try + { + return Environment.OSVersion.VersionString; + } + catch + { + return "unknown"; + } + } + + private static string SafeDotnet() + { + try + { + return Environment.Version.ToString(); + } + catch + { + return "unknown"; + } + } + + private static string SafeBuild() + { + try + { + return LoadedBuild.Sha256() ?? "unknown"; + } + catch + { + return "unknown"; + } + } + + [DllImport("user32.dll")] + private static extern uint GetGuiResources(nint hProcess, uint uiFlags); + + private static string SafeResources() + { + try + { + using Process process = Process.GetCurrentProcess(); + return string.Format(CultureInfo.InvariantCulture, "gdi={0} user={1} handles={2} private_mb={3} uptime_min={4:0}", GetGuiResources(process.Handle, 0u), GetGuiResources(process.Handle, 1u), process.HandleCount, process.PrivateMemorySize64 / 1048576, (DateTime.Now - process.StartTime).TotalMinutes); + } + catch + { + return "unknown"; + } + } + + internal static string Redact(string input) + { + if (string.IsNullOrEmpty(input)) + { + return input ?? ""; + } + string input2 = input; + for (int i = 0; i < RedactionPatterns.Length; i++) + { + input2 = RedactionPatterns[i].Replace(input2, RedactionReplacements[i]); + } + return RedactBySubstring(input2); + } + + internal static string RedactBySubstring(string input) + { + if (string.IsNullOrEmpty(input)) + { + return input ?? ""; + } + string text = input; + for (int i = 0; i < SensitiveFolderNames.Length; i++) + { + text = text.Replace(SensitiveFolderNames[i], SensitiveFolderReplacements[i]); + } + return text; + } +} diff --git a/VibranceHud/Crosshair/AngledBar.cs b/VibranceHud/Crosshair/AngledBar.cs new file mode 100644 index 0000000..a631493 --- /dev/null +++ b/VibranceHud/Crosshair/AngledBar.cs @@ -0,0 +1,5 @@ +using System.Drawing; + +namespace VibranceHud.Crosshair; + +public sealed record AngledBar(RectangleF Rect, float Degrees); diff --git a/VibranceHud/Crosshair/CrosshairCode.cs b/VibranceHud/Crosshair/CrosshairCode.cs new file mode 100644 index 0000000..bfdac9a --- /dev/null +++ b/VibranceHud/Crosshair/CrosshairCode.cs @@ -0,0 +1,225 @@ +using System; +using System.Text; + +namespace VibranceHud.Crosshair; + +public static class CrosshairCode +{ + private const string Prefix = "PXC-"; + + private const string Alphabet = "23456789ABCDEFGHJKMNPQRSTUVWXYZ#"; + + private const int ShortValueCount = 10; + + private const int LongValueCount = 13; + + private const int LongestValueCount = 18; + + private const int ShortBodyLength = 21; + + private const int LongBodyLength = 27; + + private const int LongestBodyLength = 37; + + private const int ArmTop = 1; + + private const int ArmBottom = 2; + + private const int ArmLeft = 4; + + private const int ArmRight = 8; + + private const int Circle = 16; + + private const int Dot = 32; + + private const int Outline = 64; + + private const int DiagonalArms = 128; + + private const int ChevronArms = 256; + + private const int OffsetBias = 200; + + public static string Encode(CrosshairConfig c) + { + int resolvedRotationDegrees = c.ResolvedRotationDegrees; + int num = 0; + if (c.ResolvedArmTop) + { + num |= 1; + } + if (c.ResolvedArmBottom) + { + num |= 2; + } + if (c.ResolvedArmLeft) + { + num |= 4; + } + if (c.ResolvedArmRight) + { + num |= 8; + } + if (c.ResolvedShowCircle) + { + num |= 0x10; + } + if (c.ResolvedCentreDot) + { + num |= 0x20; + } + if (c.Outline) + { + num |= 0x40; + } + if (resolvedRotationDegrees == 45) + { + num |= 0x80; + } + if (c.Chevron) + { + num |= 0x100; + } + int colourArgb = c.ColourArgb; + int num2 = c.OutlineThicknessTenths ?? 10; + int resolvedOffsetX = c.ResolvedOffsetX; + int resolvedOffsetY = c.ResolvedOffsetY; + int resolvedDotOpacity = c.ResolvedDotOpacity; + int num3 = c.ResolvedOutlineColourArgb & 0xFFFFFF; + bool flag = c.Chevron || (resolvedRotationDegrees != 0 && resolvedRotationDegrees != 45) || resolvedDotOpacity != 100 || num3 != 0; + bool flag2 = flag || resolvedRotationDegrees == 45 || num2 != 10 || resolvedOffsetX != 0 || resolvedOffsetY != 0; + int[] array = new int[18] + { + num, + Tenths(c.ResolvedSize), + Tenths(c.ResolvedThickness), + Tenths(c.ResolvedGap), + Tenths(c.ResolvedDotSize), + Tenths(c.ResolvedCircleRadius), + Math.Clamp(c.Opacity, 0, 100), + (colourArgb >> 16) & 0xFF, + (colourArgb >> 8) & 0xFF, + colourArgb & 0xFF, + Math.Clamp(num2, 0, 40), + resolvedOffsetX + 200, + resolvedOffsetY + 200, + resolvedRotationDegrees, + resolvedDotOpacity, + (num3 >> 16) & 0xFF, + (num3 >> 8) & 0xFF, + num3 & 0xFF + }; + int num4; + if (flag) + { + num4 = 18; + } + else + { + num4 = (flag2 ? 13 : 10); + } + StringBuilder stringBuilder = new StringBuilder(num4 * 2 + 1); + int[] subArray = array[..num4]; + for (int i = 0; i < subArray.Length; i++) + { + int num5 = Math.Clamp(subArray[i], 0, 1023); + stringBuilder.Append("23456789ABCDEFGHJKMNPQRSTUVWXYZ#"[num5 / 32]); + stringBuilder.Append("23456789ABCDEFGHJKMNPQRSTUVWXYZ#"[num5 % 32]); + } + stringBuilder.Append("23456789ABCDEFGHJKMNPQRSTUVWXYZ#"[Checksum(stringBuilder.ToString())]); + return "PXC-" + stringBuilder; + } + + public static bool TryDecode(string? code, out CrosshairConfig crosshair) + { + crosshair = new CrosshairConfig(); + if (string.IsNullOrWhiteSpace(code)) + { + return false; + } + string text = ShareCodeText.Normalize(code).Trim().ToUpperInvariant(); + if (!text.StartsWith("PXC-", StringComparison.Ordinal)) + { + return false; + } + string text2 = text.Substring("PXC-".Length); + int num = text2.Length switch + { + 21 => 10, + 27 => 13, + 37 => 18, + _ => 0, + }; + if (num == 0) + { + 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; + } + } + if (array[num * 2] != Checksum(text2.Substring(0, num * 2))) + { + return false; + } + int[] array2 = new int[num]; + for (int j = 0; j < num; j++) + { + array2[j] = array[j * 2] * 32 + array[j * 2 + 1]; + } + int num2 = array2[0]; + crosshair = new CrosshairConfig + { + ArmTop = ((num2 & 1) != 0), + ArmBottom = ((num2 & 2) != 0), + ArmLeft = ((num2 & 4) != 0), + ArmRight = ((num2 & 8) != 0), + ShowCircle = ((num2 & 0x10) != 0), + CentreDot = ((num2 & 0x20) != 0), + Outline = ((num2 & 0x40) != 0), + Diagonal = ((num2 & 0x80) != 0), + Opacity = Math.Clamp(array2[6], 10, 100), + ColourArgb = (-16777216 | ((array2[7] & 0xFF) << 16) | ((array2[8] & 0xFF) << 8) | (array2[9] & 0xFF)) + }; + crosshair.SetSizeTenths(Math.Clamp(array2[1], 5, 300)); + crosshair.SetThicknessTenths(Math.Clamp(array2[2], 5, 100)); + crosshair.SetGapTenths(Math.Clamp(array2[3], 0, 300)); + crosshair.DotSizeTenths = Math.Clamp(array2[4], 5, 100); + crosshair.CircleRadiusTenths = Math.Clamp(array2[5], 10, 400); + if (num >= 13) + { + crosshair.OutlineThicknessTenths = Math.Clamp(array2[10], 0, 40); + crosshair.OffsetXPx = Math.Clamp(array2[11] - 200, -200, 200); + crosshair.OffsetYPx = Math.Clamp(array2[12] - 200, -200, 200); + } + if (num == 18) + { + crosshair.Chevron = (num2 & 0x100) != 0; + crosshair.SetRotationDegrees(Math.Clamp(array2[13], 0, 90)); + crosshair.DotOpacity = Math.Clamp(array2[14], 10, 100); + crosshair.OutlineColourRgb = ((array2[15] & 0xFF) << 16) | ((array2[16] & 0xFF) << 8) | (array2[17] & 0xFF); + } + return true; + } + + private static int Tenths(float value) + { + return Math.Clamp((int)Math.Round(value * 10f), 0, 1023); + } + + 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; + } +} diff --git a/VibranceHud/Crosshair/CrosshairConfig.cs b/VibranceHud/Crosshair/CrosshairConfig.cs new file mode 100644 index 0000000..608be0f --- /dev/null +++ b/VibranceHud/Crosshair/CrosshairConfig.cs @@ -0,0 +1,199 @@ +using System; + +namespace VibranceHud.Crosshair; + +public sealed class CrosshairConfig +{ + public const int MaxOffsetPx = 200; + + public string Name { get; set; } = "New crosshair"; + + public CrosshairShape Shape { get; set; } + + public bool? ArmTop { get; set; } + + public bool? ArmBottom { get; set; } + + public bool? ArmLeft { get; set; } + + public bool? ArmRight { get; set; } + + public bool? ShowCircle { get; set; } + + public bool Diagonal { get; set; } + + public int? DotSizeTenths { get; set; } + + public int? CircleRadiusTenths { get; set; } + + public int Opacity { get; set; } = 100; + + private bool LegacyHasArms + { + get + { + CrosshairShape shape = Shape; + if (shape == CrosshairShape.Cross || shape == CrosshairShape.T) + { + return true; + } + return false; + } + } + + public bool ResolvedArmTop => ArmFrom(ArmTop, Shape == CrosshairShape.Cross); + + public bool ResolvedArmBottom => ArmFrom(ArmBottom, LegacyHasArms); + + public bool ResolvedArmLeft => ArmFrom(ArmLeft, LegacyHasArms); + + public bool ResolvedArmRight => ArmFrom(ArmRight, LegacyHasArms); + + public bool ResolvedShowCircle => ShowCircle ?? (Shape == CrosshairShape.Circle); + + public bool ResolvedCentreDot + { + get + { + if (!CentreDot) + { + return Shape == CrosshairShape.Dot; + } + return true; + } + } + + public float ResolvedDotSize => (float)(DotSizeTenths ?? ((int)Math.Round(ResolvedThickness * 10f))) / 10f; + + public float ResolvedCircleRadius => (float)(CircleRadiusTenths ?? ((int)Math.Round((ResolvedGap + ResolvedSize) * 10f))) / 10f; + + public int ResolvedColourArgb + { + get + { + int num = (byte)((ColourArgb >> 24) & 0xFF) * Math.Clamp(Opacity, 0, 100) / 100; + return (ColourArgb & 0xFFFFFF) | (num << 24); + } + } + + public int ColourArgb { get; set; } = -16711834; + + public int Size { get; set; } = 8; + + public int Thickness { get; set; } = 2; + + public int Gap { get; set; } = 4; + + public int? SizeTenths { get; set; } + + public int? ThicknessTenths { get; set; } + + public int? GapTenths { get; set; } + + public float ResolvedSize => (float)(SizeTenths ?? (Size * 10)) / 10f; + + public float ResolvedThickness => (float)(ThicknessTenths ?? (Thickness * 10)) / 10f; + + public float ResolvedGap => (float)(GapTenths ?? (Gap * 10)) / 10f; + + public bool Outline { get; set; } = true; + + public int? OutlineThicknessTenths { get; set; } + + public float ResolvedOutlineThickness + { + get + { + if (Outline) + { + return (float)(OutlineThicknessTenths ?? 10) / 10f; + } + return 0f; + } + } + + public int? OffsetXPx { get; set; } + + public int? OffsetYPx { get; set; } + + public int ResolvedOffsetX => Clamp(OffsetXPx); + + public int ResolvedOffsetY => Clamp(OffsetYPx); + + public bool CentreDot { get; set; } + + public bool Chevron { get; set; } + + public int? RotationDegrees { get; set; } + + public int ResolvedRotationDegrees => Math.Clamp(RotationDegrees ?? (Diagonal ? 45 : 0), 0, 90); + + public int? DotOpacity { get; set; } + + public int ResolvedDotOpacity => Math.Clamp(DotOpacity ?? 100, 10, 100); + + public int ResolvedDotColourArgb + { + get + { + int resolvedColourArgb = ResolvedColourArgb; + int num = ((resolvedColourArgb >> 24) & 0xFF) * ResolvedDotOpacity / 100; + return (resolvedColourArgb & 0xFFFFFF) | (num << 24); + } + } + + public int? OutlineColourRgb { get; set; } + + public int ResolvedOutlineColourArgb => -1107296256 | (OutlineColourRgb.GetValueOrDefault() & 0xFFFFFF); + + public string? ImagePath { get; set; } + + public int ImageScalePercent { get; set; } = 100; + + public bool UsesImage => ImageCrosshair.Load(ImagePath) != null; + + private bool ArmFrom(bool? saved, bool legacyDefault) + { + return saved ?? legacyDefault; + } + + public void SetSizeTenths(int tenths) + { + SizeTenths = tenths; + Size = LegacyPixels(tenths, 1); + } + + public void SetThicknessTenths(int tenths) + { + ThicknessTenths = tenths; + Thickness = LegacyPixels(tenths, 1); + } + + public void SetGapTenths(int tenths) + { + GapTenths = tenths; + Gap = LegacyPixels(tenths, 0); + } + + private static int LegacyPixels(int tenths, int floor) + { + return Math.Max(floor, (int)Math.Round((double)tenths / 10.0, MidpointRounding.AwayFromZero)); + } + + private static int Clamp(int? value) + { + return Math.Clamp(value.GetValueOrDefault(), -200, 200); + } + + public void SetRotationDegrees(int degrees) + { + int num = Math.Clamp(degrees, 0, 90); + RotationDegrees = num; + Diagonal = num > 22 && num < 68; + } + + public CrosshairConfig Clone() + { + return (CrosshairConfig)MemberwiseClone(); + } +} diff --git a/VibranceHud/Crosshair/CrosshairGallery.cs b/VibranceHud/Crosshair/CrosshairGallery.cs new file mode 100644 index 0000000..98b9fc4 --- /dev/null +++ b/VibranceHud/Crosshair/CrosshairGallery.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using VibranceHud.Licensing; + +namespace VibranceHud.Crosshair; + +public static class CrosshairGallery +{ + public enum Family + { + Dot, + X, + Ring, + Cross, + Funny + } + + public sealed record GalleryItem(string Id, string Name, Family Group, CrosshairConfig Config); + + public static IReadOnlyList All => ServedCrosshairs.Designs; + + public static void Apply(CrosshairConfig target, GalleryItem item) + { + CrosshairConfig config = item.Config; + target.ArmTop = config.ResolvedArmTop; + target.ArmBottom = config.ResolvedArmBottom; + target.ArmLeft = config.ResolvedArmLeft; + target.ArmRight = config.ResolvedArmRight; + target.CentreDot = config.ResolvedCentreDot; + target.DotSizeTenths = config.DotSizeTenths; + target.ShowCircle = config.ResolvedShowCircle; + target.CircleRadiusTenths = config.CircleRadiusTenths; + target.Diagonal = config.Diagonal; + target.RotationDegrees = config.RotationDegrees; + target.Chevron = config.Chevron; + target.SetSizeTenths(config.SizeTenths ?? 80); + target.SetThicknessTenths(config.ThicknessTenths ?? 20); + target.SetGapTenths(config.GapTenths ?? 40); + bool flag = !config.ResolvedArmTop && !config.ResolvedArmBottom && !config.ResolvedArmLeft && !config.ResolvedArmRight; + target.Shape = ((config.ResolvedShowCircle && !config.ResolvedArmLeft) ? CrosshairShape.Circle : (flag ? CrosshairShape.Dot : ((!config.ResolvedArmTop) ? CrosshairShape.T : CrosshairShape.Cross))); + } + + public static GalleryItem? Matching(CrosshairConfig c) + { + return All.FirstOrDefault((GalleryItem item) => item.Config.ResolvedArmTop == c.ResolvedArmTop && item.Config.ResolvedArmBottom == c.ResolvedArmBottom && item.Config.ResolvedArmLeft == c.ResolvedArmLeft && item.Config.ResolvedArmRight == c.ResolvedArmRight && item.Config.ResolvedCentreDot == c.ResolvedCentreDot && item.Config.ResolvedShowCircle == c.ResolvedShowCircle && item.Config.ResolvedRotationDegrees == c.ResolvedRotationDegrees && item.Config.Chevron == c.Chevron && Near(item.Config.ResolvedSize, c.ResolvedSize) && Near(item.Config.ResolvedThickness, c.ResolvedThickness) && Near(item.Config.ResolvedGap, c.ResolvedGap) && (!c.ResolvedCentreDot || Near(item.Config.ResolvedDotSize, c.ResolvedDotSize)) && (!c.ResolvedShowCircle || Near(item.Config.ResolvedCircleRadius, c.ResolvedCircleRadius))); + } + + private static bool Near(float a, float b) + { + return Math.Abs(a - b) < 0.05f; + } +} diff --git a/VibranceHud/Crosshair/CrosshairGeometry.cs b/VibranceHud/Crosshair/CrosshairGeometry.cs new file mode 100644 index 0000000..eb99c4a --- /dev/null +++ b/VibranceHud/Crosshair/CrosshairGeometry.cs @@ -0,0 +1,205 @@ +using System; +using System.Collections.Generic; +using System.Drawing; + +namespace VibranceHud.Crosshair; + +public static class CrosshairGeometry +{ + public const float ChevronDegrees = 45f; + + private const float AntiAliasMargin = 1f; + + public static CrosshairShapes Build(CrosshairConfig c) + { + float num = Math.Max(0.5f, c.ResolvedThickness); + float num2 = Math.Max(0.5f, c.ResolvedSize); + float num3 = Math.Max(0f, c.ResolvedGap); + float num4 = num / 2f; + List list = new List(); + List list2 = new List(); + RectangleF? circle = null; + RectangleF rectangleF = new RectangleF(0f - (num3 + num2), 0f - num4, num2, num); + RectangleF rectangleF2 = new RectangleF(num3, 0f - num4, num2, num); + if (c.ResolvedArmLeft) + { + if (c.Chevron) + { + list2.Add(new AngledBar(rectangleF, -45f)); + } + else + { + list.Add(rectangleF); + } + } + if (c.ResolvedArmRight) + { + if (c.Chevron) + { + list2.Add(new AngledBar(rectangleF2, 45f)); + } + else + { + list.Add(rectangleF2); + } + } + if (c.ResolvedArmBottom) + { + list.Add(new RectangleF(0f - num4, num3, num, num2)); + } + if (c.ResolvedArmTop) + { + list.Add(new RectangleF(0f - num4, 0f - (num3 + num2), num, num2)); + } + if (c.Chevron && c.ResolvedArmLeft && c.ResolvedArmRight && num3 <= 0f) + { + list2.Add(new AngledBar(new RectangleF(0f - num4, 0f - num4, num, num), 45f)); + } + if (c.ResolvedShowCircle) + { + float num5 = Math.Max(0.5f, c.ResolvedCircleRadius); + circle = new RectangleF(0f - num5, 0f - num5, num5 * 2f, num5 * 2f); + } + int dotIndex = -1; + if (c.ResolvedCentreDot) + { + float num6 = Math.Max(0.5f, c.ResolvedDotSize); + list.Add(new RectangleF((0f - num6) / 2f, (0f - num6) / 2f, num6, num6)); + dotIndex = list.Count - 1; + } + int resolvedOffsetX = c.ResolvedOffsetX; + int resolvedOffsetY = c.ResolvedOffsetY; + if (resolvedOffsetX != 0 || resolvedOffsetY != 0) + { + for (int i = 0; i < list.Count; i++) + { + list[i] = Offset(list[i], resolvedOffsetX, resolvedOffsetY); + } + for (int j = 0; j < list2.Count; j++) + { + list2[j] = list2[j] with + { + Rect = Offset(list2[j].Rect, resolvedOffsetX, resolvedOffsetY) + }; + } + if (circle.HasValue) + { + RectangleF valueOrDefault = circle.GetValueOrDefault(); + circle = Offset(valueOrDefault, resolvedOffsetX, resolvedOffsetY); + } + } + PointF pivot = new PointF(resolvedOffsetX, resolvedOffsetY); + float num7 = c.ResolvedRotationDegrees; + return new CrosshairShapes(list, circle, Bounds(list, circle, list2, pivot, 0f, 0f)) + { + Angled = list2, + DotIndex = dotIndex, + RotationDegrees = num7, + Pivot = pivot, + DrawnBounds = Bounds(list, circle, list2, pivot, num7, 0f) + }; + } + + public static Size OverlaySize(CrosshairConfig c) + { + Bitmap bitmap = ImageCrosshair.Load(c.ImagePath); + if (bitmap != null) + { + float num = (float)Math.Max(1, c.ImageScalePercent) / 100f; + float num2 = (float)bitmap.Width * num + (float)(Math.Abs(c.ResolvedOffsetX) * 2); + float num3 = (float)bitmap.Height * num + (float)(Math.Abs(c.ResolvedOffsetY) * 2); + float num4 = c.ResolvedOutlineThickness * 2f + 4f; + return new Size(Math.Max(8, (int)Math.Ceiling(num2 + num4)), Math.Max(8, (int)Math.Ceiling(num3 + num4))); + } + CrosshairShapes crosshairShapes = Build(c); + float num5 = crosshairShapes.Bounds.Width; + float num6 = crosshairShapes.Bounds.Height; + if (c.Diagonal) + { + num5 *= 1.4142f; + num6 *= 1.4142f; + } + num5 += (float)(Math.Abs(c.ResolvedOffsetX) * 2); + num6 += (float)(Math.Abs(c.ResolvedOffsetY) * 2); + float num7 = c.ResolvedOutlineThickness * 2f + 4f; + int val = (int)Math.Ceiling(num5 + num7); + int val2 = (int)Math.Ceiling(num6 + num7); + float resolvedOutlineThickness = c.ResolvedOutlineThickness; + float ringGrow = ((!crosshairShapes.Circle.HasValue) ? 0f : (Math.Max(0.5f, c.ResolvedThickness) / 2f + resolvedOutlineThickness)); + RectangleF rectangleF = Bounds(crosshairShapes.Bars, crosshairShapes.Circle, crosshairShapes.Angled, crosshairShapes.Pivot, crosshairShapes.RotationDegrees, resolvedOutlineThickness, ringGrow); + float num8 = Math.Max(Math.Abs(rectangleF.Left), Math.Abs(rectangleF.Right)) + 1f; + float num9 = Math.Max(Math.Abs(rectangleF.Top), Math.Abs(rectangleF.Bottom)) + 1f; + return new Size(Math.Max(8, Math.Max(val, (int)Math.Ceiling(num8 * 2f))), Math.Max(8, Math.Max(val2, (int)Math.Ceiling(num9 * 2f)))); + } + + private static RectangleF Offset(RectangleF r, float dx, float dy) + { + return new RectangleF(r.X + dx, r.Y + dy, r.Width, r.Height); + } + + private static RectangleF Bounds(IReadOnlyList bars, RectangleF? circle, IReadOnlyList angled, PointF pivot, float rotation, float grow, float ringGrow = 0f) + { + if (bars.Count == 0 && !circle.HasValue && angled.Count == 0) + { + return RectangleF.Empty; + } + float minX = float.MaxValue; + float minY = float.MaxValue; + float maxX = float.MinValue; + float maxY = float.MinValue; + foreach (RectangleF bar in bars) + { + Take(bar, rotation); + } + foreach (AngledBar item3 in angled) + { + Take(item3.Rect, rotation + item3.Degrees); + } + if (circle.HasValue) + { + RectangleF valueOrDefault = circle.GetValueOrDefault(); + RectangleF rectangleF = ((ringGrow > 0f) ? RectangleF.Inflate(valueOrDefault, ringGrow, ringGrow) : valueOrDefault); + TakePoint(rectangleF.Left, rectangleF.Top); + TakePoint(rectangleF.Right, rectangleF.Bottom); + } + return new RectangleF(minX, minY, maxX - minX, maxY - minY); + void Take(RectangleF r, float degrees) + { + RectangleF rectangleF2 = ((grow > 0f) ? RectangleF.Inflate(r, grow, grow) : r); + if (degrees == 0f) + { + TakePoint(rectangleF2.Left, rectangleF2.Top); + TakePoint(rectangleF2.Right, rectangleF2.Bottom); + } + else + { + double num = (double)degrees * Math.PI / 180.0; + double num2 = Math.Cos(num); + double num3 = Math.Sin(num); + (float, float)[] array = new (float, float)[4] + { + (rectangleF2.Left, rectangleF2.Top), + (rectangleF2.Right, rectangleF2.Top), + (rectangleF2.Right, rectangleF2.Bottom), + (rectangleF2.Left, rectangleF2.Bottom) + }; + for (int i = 0; i < array.Length; i++) + { + (float, float) tuple = array[i]; + float item = tuple.Item1; + float item2 = tuple.Item2; + double num4 = item - pivot.X; + double num5 = item2 - pivot.Y; + TakePoint((float)((double)pivot.X + num4 * num2 - num5 * num3), (float)((double)pivot.Y + num4 * num3 + num5 * num2)); + } + } + } + void TakePoint(float x, float y) + { + minX = Math.Min(minX, x); + minY = Math.Min(minY, y); + maxX = Math.Max(maxX, x); + maxY = Math.Max(maxY, y); + } + } +} diff --git a/VibranceHud/Crosshair/CrosshairLimits.cs b/VibranceHud/Crosshair/CrosshairLimits.cs new file mode 100644 index 0000000..a3a3e51 --- /dev/null +++ b/VibranceHud/Crosshair/CrosshairLimits.cs @@ -0,0 +1,62 @@ +namespace VibranceHud.Crosshair; + +public static class CrosshairLimits +{ + public const int MinSizeTenths = 5; + + public const int MaxSizeTenths = 300; + + public const int DefaultSizeTenths = 80; + + public const int MinThicknessTenths = 5; + + public const int MaxThicknessTenths = 100; + + public const int DefaultThicknessTenths = 20; + + public const int MinGapTenths = 0; + + public const int MaxGapTenths = 300; + + public const int DefaultGapTenths = 40; + + public const int MinDotTenths = 5; + + public const int MaxDotTenths = 100; + + public const int MinRingTenths = 10; + + public const int MaxRingTenths = 400; + + public const int MinOpacity = 10; + + public const int MaxOpacity = 100; + + public const int DefaultOpacity = 100; + + public const int MinOutlineTenths = 0; + + public const int MaxOutlineTenths = 40; + + public const int DefaultOutlineTenths = 10; + + public const int MinImageScale = 25; + + public const int MaxImageScale = 400; + + public const int MinRotationDegrees = 0; + + public const int MaxRotationDegrees = 90; + + public const int DefaultRotationDegrees = 0; + + public const int MinDotOpacity = 10; + + public const int MaxDotOpacity = 100; + + public const int DefaultDotOpacity = 100; + + public const int DefaultOutlineColourRgb = 0; + + public const int OutlineAlpha = 190; +} diff --git a/VibranceHud/Crosshair/CrosshairPresets.cs b/VibranceHud/Crosshair/CrosshairPresets.cs new file mode 100644 index 0000000..a7e22d7 --- /dev/null +++ b/VibranceHud/Crosshair/CrosshairPresets.cs @@ -0,0 +1,6 @@ +namespace VibranceHud.Crosshair; + +public static class CrosshairPresets +{ + public const int White = -1; +} diff --git a/VibranceHud/Crosshair/CrosshairRender.cs b/VibranceHud/Crosshair/CrosshairRender.cs new file mode 100644 index 0000000..236790c --- /dev/null +++ b/VibranceHud/Crosshair/CrosshairRender.cs @@ -0,0 +1,279 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; + +namespace VibranceHud.Crosshair; + +public static class CrosshairRender +{ + private static readonly int ClassicOutlineArgb = -1107296256; + + public static void Draw(Graphics g, CrosshairConfig config) + { + Bitmap bitmap = ImageCrosshair.Load(config.ImagePath); + if (bitmap != null) + { + DrawImage(g, config, bitmap); + return; + } + CrosshairShapes shapes = CrosshairGeometry.Build(config); + g.SmoothingMode = SmoothingMode.AntiAlias; + Color color = Color.FromArgb(config.ResolvedColourArgb); + SolidBrush fill = new SolidBrush(color); + try + { + int resolvedOutlineColourArgb = config.ResolvedOutlineColourArgb; + Color color2 = Color.FromArgb(resolvedOutlineColourArgb); + SolidBrush halo = new SolidBrush(color2); + try + { + bool hasDot = shapes.DotIndex >= 0; + bool fadedDot = hasDot && config.ResolvedDotOpacity < 100; + SolidBrush dotFill = new SolidBrush(Color.FromArgb(config.ResolvedDotColourArgb)); + try + { + SolidBrush dotHalo = new SolidBrush(Color.FromArgb(color2.A * config.ResolvedDotOpacity / 100, color2.R, color2.G, color2.B)); + try + { + float outline = config.ResolvedOutlineThickness; + float num = Math.Max(0.5f, config.ResolvedThickness); + if (outline > 0f) + { + bool oneShape = resolvedOutlineColourArgb != ClassicOutlineArgb || shapes.Angled.Count > 0; + GraphicsPath armsOutline = ((oneShape | fadedDot) ? Arms(shapes, outline, oneShape && !fadedDot) : null); + try + { + Turned(g, shapes.Pivot, shapes.RotationDegrees, () => + { + if (oneShape) + { + g.FillPath(halo, armsOutline); + } + else + { + for (int i = 0; i < shapes.Bars.Count; i++) + { + if (i != shapes.DotIndex) + { + g.FillRectangle(halo, RectangleF.Inflate(shapes.Bars[i], outline, outline)); + } + } + } + if (hasDot) + { + RectangleF rect = RectangleF.Inflate(shapes.Bars[shapes.DotIndex], outline, outline); + if (fadedDot) + { + GraphicsState gstate = g.Save(); + g.SetClip(armsOutline, CombineMode.Exclude); + g.FillRectangle(dotHalo, rect); + g.Restore(gstate); + } + else if (!oneShape) + { + g.FillRectangle(halo, rect); + } + } + }); + RectangleF? circle = shapes.Circle; + if (circle.HasValue) + { + RectangleF valueOrDefault = circle.GetValueOrDefault(); + using Pen pen = new Pen(color2, num + outline * 2f); + g.DrawEllipse(pen, valueOrDefault); + } + } + finally + { + if (armsOutline != null) + { + ((IDisposable)armsOutline).Dispose(); + } + } + } + GraphicsPath armsFill = Arms(shapes, 0f, withDot: false); + try + { + Turned(g, shapes.Pivot, shapes.RotationDegrees, () => + { + g.FillPath(fill, armsFill); + if (hasDot) + { + g.FillRectangle(dotFill, shapes.Bars[shapes.DotIndex]); + } + }); + RectangleF? circle = shapes.Circle; + if (circle.HasValue) + { + RectangleF valueOrDefault2 = circle.GetValueOrDefault(); + using Pen pen2 = new Pen(color, num); + g.DrawEllipse(pen2, valueOrDefault2); + return; + } + } + finally + { + if (armsFill != null) + { + ((IDisposable)armsFill).Dispose(); + } + } + } + finally + { + if (dotHalo != null) + { + ((IDisposable)dotHalo).Dispose(); + } + } + } + finally + { + if (dotFill != null) + { + ((IDisposable)dotFill).Dispose(); + } + } + } + finally + { + if (halo != null) + { + ((IDisposable)halo).Dispose(); + } + } + } + finally + { + if (fill != null) + { + ((IDisposable)fill).Dispose(); + } + } + } + + private static GraphicsPath Arms(CrosshairShapes shapes, float grow, bool withDot) + { + GraphicsPath graphicsPath = new GraphicsPath(FillMode.Winding); + for (int i = 0; i < shapes.Bars.Count; i++) + { + if (i != shapes.DotIndex || withDot) + { + graphicsPath.AddRectangle((grow > 0f) ? RectangleF.Inflate(shapes.Bars[i], grow, grow) : shapes.Bars[i]); + } + } + foreach (AngledBar item in shapes.Angled) + { + using GraphicsPath graphicsPath2 = new GraphicsPath(FillMode.Winding); + graphicsPath2.AddRectangle((grow > 0f) ? RectangleF.Inflate(item.Rect, grow, grow) : item.Rect); + using Matrix matrix = new Matrix(); + matrix.RotateAt(item.Degrees, shapes.Pivot); + graphicsPath2.Transform(matrix); + graphicsPath.AddPath(graphicsPath2, connect: false); + } + return graphicsPath; + } + + private static void Turned(Graphics g, PointF pivot, float degrees, Action draw) + { + if (degrees == 0f) + { + draw(); + return; + } + GraphicsState gstate = g.Save(); + int num; + if (pivot.X == 0f) + { + num = ((pivot.Y != 0f) ? 1 : 0); + if (num == 0) + { + goto IL_004f; + } + } + else + { + num = 1; + } + g.TranslateTransform(pivot.X, pivot.Y); + goto IL_004f; + IL_004f: + g.RotateTransform(degrees); + if (num != 0) + { + g.TranslateTransform(0f - pivot.X, 0f - pivot.Y); + } + draw(); + g.Restore(gstate); + } + + private static void DrawImage(Graphics g, CrosshairConfig config, Image image) + { + float num = (float)Math.Max(1, config.ImageScalePercent) / 100f; + float num2 = (float)image.Width * num; + float num3 = (float)image.Height * num; + float num4 = config.ResolvedOffsetX; + float num5 = config.ResolvedOffsetY; + InterpolationMode interpolationMode = g.InterpolationMode; + PixelOffsetMode pixelOffsetMode = g.PixelOffsetMode; + g.InterpolationMode = InterpolationMode.NearestNeighbor; + g.PixelOffsetMode = PixelOffsetMode.Half; + int num6 = Math.Clamp(config.Opacity, 0, 100); + if (num6 >= 100) + { + g.DrawImage(image, (0f - num2) / 2f + num4, (0f - num3) / 2f + num5, num2, num3); + } + else + { + using ImageAttributes imageAttributes = new ImageAttributes(); + ColorMatrix colorMatrix = new ColorMatrix + { + Matrix33 = (float)num6 / 100f + }; + imageAttributes.SetColorMatrix(colorMatrix); + g.DrawImage(image, new Rectangle((int)((0f - num2) / 2f) + (int)num4, (int)((0f - num3) / 2f) + (int)num5, (int)num2, (int)num3), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, imageAttributes); + } + g.InterpolationMode = interpolationMode; + g.PixelOffsetMode = pixelOffsetMode; + } + + public static void Draw(Graphics g, CrosshairConfig config, Rectangle target) + { + Draw(g, config, target, 1f); + } + + public static void Draw(Graphics g, CrosshairConfig config, Rectangle target, float maxScale) + { + RectangleF bounds = CrosshairGeometry.Build(config).Bounds; + float num = maxScale; + if (bounds.Width > 0f && bounds.Height > 0f) + { + num = Math.Min(maxScale, 0.82f * Math.Min((float)target.Width / bounds.Width, (float)target.Height / bounds.Height)); + } + GraphicsState gstate = g.Save(); + g.SetClip(target); + g.TranslateTransform((float)target.X + (float)target.Width / 2f, (float)target.Y + (float)target.Height / 2f); + g.ScaleTransform(num, num); + Draw(g, config); + g.Restore(gstate); + } + + public static void DrawCheckerboard(Graphics g, Rectangle rect, int cell) + { + using Region clip = g.Clip; + g.SetClip(rect, CombineMode.Intersect); + using (SolidBrush solidBrush = new SolidBrush(Color.FromArgb(255, 58, 58, 64))) + { + using SolidBrush solidBrush2 = new SolidBrush(Color.FromArgb(255, 78, 78, 86)); + for (int i = rect.Top; i < rect.Bottom; i += cell) + { + for (int j = rect.Left; j < rect.Right; j += cell) + { + g.FillRectangle((((j - rect.Left) / cell + (i - rect.Top) / cell) % 2 == 0) ? solidBrush : solidBrush2, j, i, cell, cell); + } + } + } + g.Clip = clip; + } +} diff --git a/VibranceHud/Crosshair/CrosshairService.cs b/VibranceHud/Crosshair/CrosshairService.cs new file mode 100644 index 0000000..9c904f8 --- /dev/null +++ b/VibranceHud/Crosshair/CrosshairService.cs @@ -0,0 +1,92 @@ +using System; +using System.Runtime.InteropServices; + +namespace VibranceHud.Crosshair; + +public sealed class CrosshairService : IDisposable +{ + private const int QUNS_RUNNING_D3D_FULL_SCREEN = 3; + + private CrosshairWindow? _window; + + private readonly Func _newWindow; + + public bool IsVisible { get; private set; } + + public CrosshairConfig Config { get; private set; } = new CrosshairConfig(); + + [DllImport("shell32.dll")] + private static extern int SHQueryUserNotificationState(out int state); + + public CrosshairService() + : this(() => new CrosshairWindow()) + { + } + + internal CrosshairService(Func newWindow) + { + _newWindow = newWindow; + } + + public static bool IsExclusiveFullscreen() + { + try + { + int state; + return SHQueryUserNotificationState(out state) == 0 && state == 3; + } + catch + { + return false; + } + } + + public void Apply(CrosshairConfig config) + { + Config = config; + if (IsVisible) + { + _window?.Apply(config); + } + } + + public void Show() + { + if (_window == null) + { + _window = _newWindow(); + } + _ = _window.Handle; + _window.Apply(Config); + if (!_window.Visible) + { + _window.Show(); + } + IsVisible = true; + } + + public void Hide() + { + _window?.Hide(); + IsVisible = false; + } + + public void Toggle() + { + if (IsVisible) + { + Hide(); + } + else + { + Show(); + } + } + + public void Dispose() + { + _window?.Dispose(); + _window = null; + IsVisible = false; + } +} diff --git a/VibranceHud/Crosshair/CrosshairShape.cs b/VibranceHud/Crosshair/CrosshairShape.cs new file mode 100644 index 0000000..30346e8 --- /dev/null +++ b/VibranceHud/Crosshair/CrosshairShape.cs @@ -0,0 +1,9 @@ +namespace VibranceHud.Crosshair; + +public enum CrosshairShape +{ + Cross, + Dot, + Circle, + T +} diff --git a/VibranceHud/Crosshair/CrosshairShapeKind.cs b/VibranceHud/Crosshair/CrosshairShapeKind.cs new file mode 100644 index 0000000..36afcab --- /dev/null +++ b/VibranceHud/Crosshair/CrosshairShapeKind.cs @@ -0,0 +1,10 @@ +namespace VibranceHud.Crosshair; + +public enum CrosshairShapeKind +{ + Cross, + T, + Circle, + Dot, + Chevron +} diff --git a/VibranceHud/Crosshair/CrosshairShapeKinds.cs b/VibranceHud/Crosshair/CrosshairShapeKinds.cs new file mode 100644 index 0000000..7f1e9c3 --- /dev/null +++ b/VibranceHud/Crosshair/CrosshairShapeKinds.cs @@ -0,0 +1,93 @@ +using System.Collections.Generic; + +namespace VibranceHud.Crosshair; + +public static class CrosshairShapeKinds +{ + public static IReadOnlyList All { get; } = new CrosshairShapeKind[5] + { + CrosshairShapeKind.Cross, + CrosshairShapeKind.T, + CrosshairShapeKind.Circle, + CrosshairShapeKind.Dot, + CrosshairShapeKind.Chevron + }; + + public static void Apply(CrosshairConfig config, CrosshairShapeKind kind) + { + config.CentreDot = config.ResolvedCentreDot; + switch (kind) + { + case CrosshairShapeKind.Cross: + SetParts(config, top: true, bottom: true, left: true, right: true, ring: false, chevron: false); + config.Shape = CrosshairShape.Cross; + break; + case CrosshairShapeKind.T: + SetParts(config, top: false, bottom: true, left: true, right: true, ring: false, chevron: false); + config.Shape = CrosshairShape.T; + break; + case CrosshairShapeKind.Circle: + SetParts(config, top: false, bottom: false, left: false, right: false, ring: true, chevron: false); + config.Shape = CrosshairShape.Circle; + break; + case CrosshairShapeKind.Dot: + SetParts(config, top: false, bottom: false, left: false, right: false, ring: false, chevron: false); + config.CentreDot = true; + config.Shape = CrosshairShape.Dot; + break; + case CrosshairShapeKind.Chevron: + SetParts(config, top: false, bottom: false, left: true, right: true, ring: false, chevron: true); + config.Shape = CrosshairShape.Cross; + break; + } + } + + public static CrosshairShapeKind? Of(CrosshairConfig c) + { + bool resolvedArmTop = c.ResolvedArmTop; + bool resolvedArmBottom = c.ResolvedArmBottom; + bool resolvedArmLeft = c.ResolvedArmLeft; + bool resolvedArmRight = c.ResolvedArmRight; + bool resolvedShowCircle = c.ResolvedShowCircle; + if (c.Chevron) + { + if (!(resolvedArmLeft & resolvedArmRight) || resolvedArmTop || resolvedArmBottom || resolvedShowCircle) + { + return null; + } + return CrosshairShapeKind.Chevron; + } + bool flag = !resolvedArmTop && !resolvedArmBottom && !resolvedArmLeft && !resolvedArmRight; + if (resolvedShowCircle) + { + if (!flag) + { + return null; + } + return CrosshairShapeKind.Circle; + } + if (resolvedArmTop & resolvedArmBottom & resolvedArmLeft & resolvedArmRight) + { + return CrosshairShapeKind.Cross; + } + if (!resolvedArmTop & resolvedArmBottom & resolvedArmLeft & resolvedArmRight) + { + return CrosshairShapeKind.T; + } + if (flag && c.ResolvedCentreDot) + { + return CrosshairShapeKind.Dot; + } + return null; + } + + private static void SetParts(CrosshairConfig c, bool top, bool bottom, bool left, bool right, bool ring, bool chevron) + { + c.ArmTop = top; + c.ArmBottom = bottom; + c.ArmLeft = left; + c.ArmRight = right; + c.ShowCircle = ring; + c.Chevron = chevron; + } +} diff --git a/VibranceHud/Crosshair/CrosshairShapes.cs b/VibranceHud/Crosshair/CrosshairShapes.cs new file mode 100644 index 0000000..21c9424 --- /dev/null +++ b/VibranceHud/Crosshair/CrosshairShapes.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Drawing; + +namespace VibranceHud.Crosshair; + +public sealed record CrosshairShapes(IReadOnlyList Bars, RectangleF? Circle, RectangleF Bounds) +{ + public IReadOnlyList Angled { get; init; } = Array.Empty(); + + public int DotIndex { get; init; } = -1; + + public float RotationDegrees { get; init; } + + public PointF Pivot { get; init; } + + public RectangleF DrawnBounds { get; init; } +} diff --git a/VibranceHud/Crosshair/CrosshairWindow.cs b/VibranceHud/Crosshair/CrosshairWindow.cs new file mode 100644 index 0000000..e24efb4 --- /dev/null +++ b/VibranceHud/Crosshair/CrosshairWindow.cs @@ -0,0 +1,233 @@ +using System; +using System.Drawing; +using System.Drawing.Imaging; +using System.Runtime.InteropServices; +using System.Windows.Forms; + +namespace VibranceHud.Crosshair; + +public sealed class CrosshairWindow : Form +{ + private struct POINT + { + public int X; + + public int Y; + } + + private struct SIZE + { + public int cx; + + public int cy; + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + private struct BLENDFUNCTION + { + public byte BlendOp; + + public byte BlendFlags; + + public byte SourceConstantAlpha; + + public byte AlphaFormat; + } + + private struct BITMAPINFOHEADER + { + public uint biSize; + + public int biWidth; + + public int biHeight; + + public ushort biPlanes; + + public ushort biBitCount; + + public uint biCompression; + + public uint biSizeImage; + + public int biXPelsPerMeter; + + public int biYPelsPerMeter; + + public uint biClrUsed; + + public uint biClrImportant; + } + + private const int WS_EX_LAYERED = 524288; + + private const int WS_EX_TRANSPARENT = 32; + + private const int WS_EX_TOOLWINDOW = 128; + + private const int WS_EX_NOACTIVATE = 134217728; + + private const int WS_EX_TOPMOST = 8; + + private const int ULW_ALPHA = 2; + + private const byte AC_SRC_OVER = 0; + + private const byte AC_SRC_ALPHA = 1; + + private const uint DIB_RGB_COLORS = 0u; + + private const uint BI_RGB = 0u; + + private CrosshairConfig _config = new CrosshairConfig(); + + protected override CreateParams CreateParams + { + get + { + CreateParams createParams = base.CreateParams; + createParams.ExStyle |= 134742184; + return createParams; + } + } + + protected override bool ShowWithoutActivation => true; + + [DllImport("user32.dll", SetLastError = true)] + private static extern bool UpdateLayeredWindow(nint hwnd, nint hdcDst, ref POINT pptDst, ref SIZE psize, nint hdcSrc, ref POINT pptSrc, int crKey, ref BLENDFUNCTION pblend, int dwFlags); + + [DllImport("user32.dll")] + private static extern nint GetDC(nint hWnd); + + [DllImport("user32.dll")] + private static extern int ReleaseDC(nint hWnd, nint hDC); + + [DllImport("gdi32.dll")] + private static extern nint CreateCompatibleDC(nint hDC); + + [DllImport("gdi32.dll")] + private static extern bool DeleteDC(nint hdc); + + [DllImport("gdi32.dll")] + private static extern nint SelectObject(nint hdc, nint h); + + [DllImport("gdi32.dll")] + private static extern bool DeleteObject(nint ho); + + [DllImport("gdi32.dll")] + private static extern nint CreateDIBSection(nint hdc, ref BITMAPINFOHEADER pbmi, uint iUsage, out nint ppvBits, nint hSection, uint dwOffset); + + [DllImport("kernel32.dll", EntryPoint = "RtlMoveMemory")] + private static extern void CopyMemory(nint dest, nint src, uint count); + + public CrosshairWindow() + { + FormBorderStyle = FormBorderStyle.None; + ShowInTaskbar = false; + TopMost = true; + StartPosition = FormStartPosition.Manual; + SetStyle(ControlStyles.Opaque, value: true); + } + + protected override void OnPaintBackground(PaintEventArgs e) + { + } + + protected override void OnPaint(PaintEventArgs e) + { + } + + public void Apply(CrosshairConfig config) + { + _config = config; + Redraw(); + } + + public void Redraw() + { + if (!IsHandleCreated) + { + return; + } + Size size = CrosshairGeometry.OverlaySize(_config); + int width = size.Width; + int height = size.Height; + Rectangle bounds = Screen.FromPoint(System.Windows.Forms.Cursor.Position).Bounds; + int left = bounds.Left + (bounds.Width - width) / 2; + int top = bounds.Top + (bounds.Height - height) / 2; + using Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppPArgb); + using (Graphics graphics = Graphics.FromImage(bitmap)) + { + graphics.TranslateTransform((float)width / 2f, (float)height / 2f); + CrosshairRender.Draw(graphics, _config); + } + Push(bitmap, left, top); + } + + private void Push(Bitmap bmp, int left, int top) + { + nint dC = GetDC(IntPtr.Zero); + nint num = CreateCompatibleDC(dC); + nint num2 = IntPtr.Zero; + nint h = IntPtr.Zero; + try + { + BITMAPINFOHEADER pbmi = new BITMAPINFOHEADER + { + biSize = (uint)Marshal.SizeOf(), + biWidth = bmp.Width, + biHeight = -bmp.Height, + biPlanes = 1, + biBitCount = 32, + biCompression = 0u + }; + num2 = CreateDIBSection(dC, ref pbmi, 0u, out var ppvBits, IntPtr.Zero, 0u); + if (num2 != IntPtr.Zero && ppvBits != IntPtr.Zero) + { + BitmapData bitmapData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppPArgb); + try + { + CopyMemory(ppvBits, bitmapData.Scan0, (uint)(bmp.Width * bmp.Height * 4)); + } + finally + { + bmp.UnlockBits(bitmapData); + } + h = SelectObject(num, num2); + SIZE psize = new SIZE + { + cx = bmp.Width, + cy = bmp.Height + }; + POINT pptSrc = new POINT + { + X = 0, + Y = 0 + }; + POINT pptDst = new POINT + { + X = left, + Y = top + }; + BLENDFUNCTION pblend = new BLENDFUNCTION + { + BlendOp = 0, + BlendFlags = 0, + SourceConstantAlpha = byte.MaxValue, + AlphaFormat = 1 + }; + UpdateLayeredWindow(Handle, dC, ref pptDst, ref psize, num, ref pptSrc, 0, ref pblend, 2); + } + } + finally + { + ReleaseDC(IntPtr.Zero, dC); + if (num2 != IntPtr.Zero) + { + SelectObject(num, h); + DeleteObject(num2); + } + DeleteDC(num); + } + } +} diff --git a/VibranceHud/Crosshair/ImageCrosshair.cs b/VibranceHud/Crosshair/ImageCrosshair.cs new file mode 100644 index 0000000..bc8332d --- /dev/null +++ b/VibranceHud/Crosshair/ImageCrosshair.cs @@ -0,0 +1,115 @@ +using System; +using System.Collections.Concurrent; +using System.Drawing; +using System.IO; +using System.Security.Cryptography; + +namespace VibranceHud.Crosshair; + +public static class ImageCrosshair +{ + public const int MaxSidePx = 512; + + private static readonly ConcurrentDictionary _cache = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); + + public static Bitmap? Load(string? path) + { + if (string.IsNullOrWhiteSpace(path)) + { + return null; + } + if (_cache.TryGetValue(path, out Bitmap value)) + { + return value; + } + Bitmap bitmap = Decode(path); + if (bitmap != null) + { + _cache.TryAdd(path, bitmap); + } + return bitmap; + } + + private static Bitmap? Decode(string path) + { + try + { + if (!File.Exists(path)) + { + return null; + } + using MemoryStream stream = new MemoryStream(File.ReadAllBytes(path)); + using Bitmap bitmap = new Bitmap(stream); + if (bitmap.Width > 512 || bitmap.Height > 512) + { + return null; + } + return new Bitmap(bitmap); + } + catch + { + return null; + } + } + + public static void ClearCache() + { + _cache.Clear(); + } + + public static bool TryImport(string? sourcePath, string storeDir, out string stored, out string error) + { + stored = ""; + if (string.IsNullOrWhiteSpace(sourcePath) || !File.Exists(sourcePath)) + { + error = "That file could not be found."; + return false; + } + Bitmap bitmap; + try + { + using MemoryStream stream = new MemoryStream(File.ReadAllBytes(sourcePath)); + bitmap = new Bitmap(stream); + } + catch + { + error = "That file is not an image PlexusX can read. PNG works best, because it can have a transparent background."; + return false; + } + Bitmap value = bitmap; + try + { + if (bitmap.Width > 512 || bitmap.Height > 512) + { + error = $"That image is {bitmap.Width}×{bitmap.Height}. The largest a crosshair may be is {512}×{512} - anything bigger costs frames " + "in every game, which is the opposite of the point."; + return false; + } + } + finally + { + ((IDisposable)value)?.Dispose(); + } + try + { + Directory.CreateDirectory(storeDir); + string path = "crosshair-" + ShortHash(File.ReadAllBytes(sourcePath)) + Path.GetExtension(sourcePath); + string text = Path.Combine(storeDir, path); + File.Copy(sourcePath, text, overwrite: true); + _cache.TryRemove(text, out value); + stored = text; + error = ""; + return true; + } + catch (Exception ex) + { + error = "The image is fine, but it could not be saved: " + ex.Message; + return false; + } + } + + private static string ShortHash(byte[] bytes) + { + using SHA256 sHA = SHA256.Create(); + return Convert.ToHexString(sHA.ComputeHash(bytes), 0, 6).ToLowerInvariant(); + } +} diff --git a/VibranceHud/CustomPresetNaming.cs b/VibranceHud/CustomPresetNaming.cs new file mode 100644 index 0000000..39975aa --- /dev/null +++ b/VibranceHud/CustomPresetNaming.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; + +namespace VibranceHud; + +public static class CustomPresetNaming +{ + private const int MaxNameLength = 40; + + public const string Fallback = "My look"; + + public static string Unique(string? wanted, IEnumerable existing) + { + string text = (string.IsNullOrWhiteSpace(wanted) ? "My look" : wanted.Trim()); + text = text.Substring(0, Math.Min(text.Length, 40)); + HashSet hashSet = new HashSet(existing ?? Enumerable.Empty(), StringComparer.OrdinalIgnoreCase); + if (!hashSet.Contains(text)) + { + return text; + } + for (int i = 2; i < int.MaxValue; i++) + { + string text2 = " " + i.ToString(CultureInfo.InvariantCulture); + string text3 = text.Substring(0, Math.Min(text.Length, 40 - text2.Length)) + text2; + if (!hashSet.Contains(text3)) + { + return text3; + } + } + return text; + } +} diff --git a/VibranceHud/Customize/CustomizationSettings.cs b/VibranceHud/Customize/CustomizationSettings.cs new file mode 100644 index 0000000..0e466ca --- /dev/null +++ b/VibranceHud/Customize/CustomizationSettings.cs @@ -0,0 +1,22 @@ +using System.Text.Json.Serialization; + +namespace VibranceHud.Customize; + +public sealed record CustomizationSettings +{ + public TaskbarSettings Taskbar { get; init; } = new TaskbarSettings(); + + public SystemSettings System { get; init; } = new SystemSettings(); + + public WindowSettings Windows { get; init; } = new WindowSettings(); + + public ExplorerSettings Explorer { get; init; } = new ExplorerSettings(); + + [JsonIgnore] + public TaskbarStyleSupport TaskbarStylerSupport { get; init; } = TaskbarStyleSupport.Unknown; + + public static CustomizationSettings Default() + { + return new CustomizationSettings(); + } +} diff --git a/VibranceHud/Customize/CustomizePage.cs b/VibranceHud/Customize/CustomizePage.cs new file mode 100644 index 0000000..59043a0 --- /dev/null +++ b/VibranceHud/Customize/CustomizePage.cs @@ -0,0 +1,1207 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Windows.Forms; +using VibranceHud.Controls; +using VibranceHud.Design; +using VibranceHud.Pages; +using VibranceHud.Theming; + +namespace VibranceHud.Customize; + +public sealed class CustomizePage : GlowPage +{ + private sealed class Rule : Control + { + public Rule() + { + SetStyle(ControlStyles.UserPaint | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint, value: true); + BackColor = Color.Transparent; + TabStop = false; + Height = 1; + } + + protected override void OnPaint(PaintEventArgs e) + { + using SolidBrush brush = new SolidBrush(ControlInk.Border); + e.Graphics.FillRectangle(brush, ClientRectangle); + } + } + + private sealed class PictureThumb : Control + { + public PictureThumb() + { + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + TabStop = false; + AccessibleRole = AccessibleRole.Graphic; + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics g = e.Graphics; + if (Width < 2 || Height < 2) + { + return; + } + float radius = Tokens.Scale(4); + GraphicsPath path = Glass.RoundedPath(new RectangleF(0f, 0f, Width, Height), radius); + try + { + g.SmoothingMode = SmoothingMode.AntiAlias; + using (SolidBrush brush = new SolidBrush(SlateSurface.Active ? SignalTokens.Slate.PreviewWell : SignalTokens.Ash.PreviewWell)) + { + g.FillPath(brush, path); + } + if (!AppBackground.IsSet) + { + return; + } + PaintGuard.Try(this, () => + { + using Region clip = g.Clip; + try + { + g.SetClip(path, CombineMode.Intersect); + AppBackground.PaintInto(g, Width, Height); + } + finally + { + g.Clip = clip; + } + }); + } + finally + { + if (path != null) + { + ((IDisposable)path).Dispose(); + } + } + } + } + + private sealed class NoteIcon : Control + { + public NoteIcon() + { + SetStyle(ControlStyles.UserPaint | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + TabStop = false; + AccessibleRole = AccessibleRole.Graphic; + } + + protected override void OnPaint(PaintEventArgs e) + { + e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; + SignalIcons.Draw(e.Graphics, SignalIcon.Info, new RectangleF(0f, 0f, Width, Height), ControlInk.Info); + } + } + + private const int NarrowColumn = 332; + + private const string NoneSegment = "None"; + + private const string PictureSegment = "Image / GIF"; + + private readonly Label _title; + + private readonly Label _subtitle; + + private readonly AppSettings _settings; + + private readonly SettingsStore _store; + + private readonly Action _onThemeChanged; + + private readonly Action _onBackgroundChanged; + + private readonly Action _onOpacityChanged; + + private readonly CustomThemeService? _custom; + + private readonly List _lookTiles = new List(); + + private readonly bool _slateLive; + + private readonly List _backdropButtons = new List(); + + private readonly DebouncedAction _saveDebounce; + + private const int SaveDebounceMs = 500; + + internal const string PictureFilter = "Images|*.png;*.jpg;*.jpeg;*.gif;*.bmp;*.webp|All files|*.*"; + + private readonly CardPanel _lookCard; + + private readonly Label _lookTitle; + + private readonly Label _modeCaption; + + private readonly Label _opacityRowTitle; + + private readonly Label _opacityRowNote; + + private readonly Label _opacityRowValue; + + private readonly FlatSlider _slateOpacity; + + private readonly Label _matteBlurTitle; + + private readonly Label _matteBlurNote; + + private readonly ToggleSwitch _matteBlurToggle; + + private readonly Rule _slateRule1; + + private readonly CardPanel _pictureCard; + + private readonly Label _pictureTitle; + + private readonly SegmentStrip _pictureSwitch; + + private readonly PictureThumb _thumb; + + private readonly Label _pictureName; + + private readonly Label _pictureDetail; + + private readonly Label _noPicture; + + private readonly Label _pictureError; + + private readonly GlassButton _chooseBtn; + + private readonly GlassButton _clearBtn; + + private readonly Rule _noteRule; + + private readonly NoteIcon _noteIcon; + + private readonly Label _gifNote; + + private readonly CardPanel _checkCard; + + private readonly Label _checkTitle; + + private readonly Label _checkRatio; + + private readonly Label _checkNote; + + private readonly StatusPill _checkStatus; + + private readonly CardPanel _keptCard; + + private readonly Label _backdropTitle; + + private readonly Label _backdropNote; + + private readonly Label? _dimTitle; + + private readonly Label? _dimValue; + + private readonly Label? _dimNote; + + private readonly FlatSlider? _dimSlider; + + private readonly Label _blurTitle; + + private readonly Label _blurValue; + + private readonly Label _blurNote; + + private readonly FlatSlider _blurSlider; + + private readonly Label _opacityTitle; + + private readonly Label _opacityValue; + + private readonly Label _opacityHint; + + private readonly FlatSlider _opacitySlider; + + private readonly Label _savedNote; + + private readonly Rule _keptRuleDim; + + private readonly Rule _keptRuleBlur; + + private readonly Rule _keptRuleMatte; + + private readonly Rule _keptRuleOpacity; + + private readonly Rule _keptRuleSaved; + + private readonly Label _matteLabel; + + private readonly ChipButton _blackChip; + + private readonly ChipButton _whiteChip; + + private readonly ChipButton _pickChip; + + private bool _built; + + protected override bool LaysOutInLogicalPixels => false; + + private static int Inset => S(21); + + private static int ListPadY => S(4); + + private static int CardGap => S(16); + + private static int ColumnGap => S(16); + + private static int RowMin => S(52); + + private static Size ThumbSize => new Size(S(112), S(64)); + + private static int RowSliderW => S(200); + + private bool APictureIsSet => _custom?.HasImage ?? AppBackground.IsSet; + + private static int TitleLine => S(20); + + private static int CaptionLine => S(16); + + private static int S(int px) + { + return Tokens.Scale(px); + } + + public CustomizePage(AppSettings settings, SettingsStore store, Action? onThemeChanged = null, Action? onBackgroundChanged = null, Action? onOpacityChanged = null, CustomThemeService? custom = null, Action? onBackdropChanged = null) + { + CustomizePage customizePage = this; + _settings = settings; + _store = store; + _onThemeChanged = onThemeChanged ?? ((Action)((string name) => + { + Theme.Apply(name); + })); + _onBackgroundChanged = onBackgroundChanged ?? ((Action)(() => + { + })); + _onOpacityChanged = onOpacityChanged ?? ((Action)((int _) => + { + })); + _custom = custom; + _saveDebounce = new DebouncedAction(() => + { + customizePage._store.Save(customizePage._settings); + }, 500); + _slateLive = Theme.IsSeeThrough; + Dock = DockStyle.Fill; + BackColor = Theme.Background; + AutoScroll = true; + Font = Fonts.Body; + _title = PageLabel("Customize", Fonts.Display, Theme.Text); + _subtitle = PageLabel("How PlexusX itself looks. The colour of your games is set on Display.", Fonts.Label, Theme.TextDim); + _subtitle.TextAlign = ContentAlignment.TopLeft; + _lookCard = NewCard(); + _lookTitle = Heading(_lookCard, "Colour mode"); + _modeCaption = Words(_lookCard, _slateLive ? "Slate (see-through)" : "Default", Fonts.Caption, Theme.TextFaint, ContentAlignment.MiddleRight); + (string, string, string)[] array = new (string, string, string)[2] + { + ("Ash", "Default", "Solid panels. Your picture shows around them."), + ("Slate", "Slate (see-through)", "Dark matte panels. Your picture shows through.") + }; + for (int num = 0; num < array.Length; num++) + { + (string, string, string) tuple = array[num]; + string item = tuple.Item1; + string item2 = tuple.Item2; + string item3 = tuple.Item3; + ThemePalette themePalette = ThemeCatalog.ByName(item); + LookTile tile = new LookTile(themePalette, item3, item2) + { + Active = (themePalette.Name == Theme.CurrentName) + }; + tile.Click += (object? s, EventArgs e) => + { + foreach (LookTile lookTile in customizePage._lookTiles) + { + lookTile.Active = lookTile == tile; + } + if (SignatureLooks.TryGet(tile.Palette.Name, out var look)) + { + customizePage._settings.BackdropLookName = BackdropLooks.Name(look.Backdrop); + customizePage._settings.SurfaceStyleName = SurfaceStyles.Name(look.Surface); + customizePage._settings.ChromeName = Chromes.Name(look.Chrome); + customizePage._store.Save(customizePage._settings); + foreach (ChipButton backdropButton in customizePage._backdropButtons) + { + backdropButton.Active = backdropButton.Tag is BackdropLook backdropLook2 && backdropLook2 == look.Backdrop; + } + } + customizePage._onThemeChanged(tile.Palette.Name); + }; + _lookTiles.Add(tile); + _lookCard.Controls.Add(tile); + } + Color colour = (_slateLive ? Theme.Text : ControlInk.TextDisabledInk); + Color colour2 = (_slateLive ? Theme.TextFaint : ControlInk.TextDisabledInk); + _opacityRowTitle = Words(_lookCard, "GUI opacity", Fonts.Body, colour); + _opacityRowNote = Note(_lookCard, _slateLive ? "How solid the Slate panels are. The picture itself never dims." : "Slate only.", colour2); + int value = (int)Math.Round(SlateSurface.UserOpacity * 100.0); + _opacityRowValue = Words(_lookCard, $"{value}%", Fonts.BodyBold, colour, ContentAlignment.MiddleRight); + _slateOpacity = new FlatSlider + { + AccessibleName = "GUI opacity", + Minimum = (int)Math.Round(45.0), + Maximum = (int)Math.Round(85.0), + Value = value, + Enabled = _slateLive + }; + _slateOpacity.ValueChanged += (object? s, EventArgs e) => + { + if (customizePage._slateLive) + { + SlateSurface.UserOpacity = (double)customizePage._slateOpacity.Value / 100.0; + customizePage._opacityRowValue.Text = $"{customizePage._slateOpacity.Value}%"; + customizePage._settings.SlateGuiOpacityPercent = customizePage._slateOpacity.Value; + customizePage._saveDebounce.Trigger(); + customizePage._onBackgroundChanged(); + customizePage.RefreshTextCheck(); + } + }; + _lookCard.Controls.Add(_slateOpacity); + _slateRule1 = NewRule(_lookCard); + _matteBlurTitle = Words(_lookCard, "Matte blur", Fonts.Body, colour); + _matteBlurNote = Note(_lookCard, _slateLive ? "Softens the picture behind the panels only." : "Slate only.", colour2); + _matteBlurToggle = new ToggleSwitch + { + AccessibleName = "Matte blur", + Checked = (_slateLive && SlateSurface.MatteBlur), + Enabled = _slateLive + }; + _matteBlurToggle.CheckedChanged += (object? s, EventArgs e) => + { + if (customizePage._slateLive) + { + SlateSurface.MatteBlur = customizePage._matteBlurToggle.Checked; + customizePage._settings.SlateMatteBlur = customizePage._matteBlurToggle.Checked; + customizePage._store.Save(customizePage._settings); + customizePage._onBackgroundChanged(); + customizePage.RefreshTextCheck(); + } + }; + _lookCard.Controls.Add(_matteBlurToggle); + _pictureCard = NewCard(); + _pictureTitle = Heading(_pictureCard, "Background"); + _pictureSwitch = new SegmentStrip(new string[2] { "None", "Image / GIF" }) + { + AccessibleName = "Backdrop" + }; + _pictureSwitch.Chosen += (object? _, string segment) => + { + if (segment == "None") + { + customizePage.RemovePicture(); + } + else + { + customizePage.ChoosePicture(); + } + }; + _pictureCard.Controls.Add(_pictureSwitch); + _thumb = new PictureThumb(); + _pictureCard.Controls.Add(_thumb); + _pictureName = Words(_pictureCard, "", Fonts.BodyBold, Theme.Text); + _pictureName.AutoEllipsis = true; + _pictureDetail = Words(_pictureCard, "", Fonts.Caption, Theme.TextFaint); + _noPicture = Words(_pictureCard, "No picture. The window is plain.", Fonts.Body, Theme.TextDim); + _pictureError = Note(_pictureCard, "", Theme.TextDim); + _chooseBtn = new GlassButton + { + Text = "Choose image or GIF", + Kind = GlassButtonKind.Secondary, + Icon = SignalIcon.Upload + }; + _clearBtn = new GlassButton + { + Text = "Remove", + Kind = GlassButtonKind.Quiet + }; + _chooseBtn.Click += (object? s, EventArgs e) => + { + customizePage.ChoosePicture(); + }; + _clearBtn.Click += (object? s, EventArgs e) => + { + customizePage.RemovePicture(); + }; + _pictureCard.Controls.Add(_chooseBtn); + _pictureCard.Controls.Add(_clearBtn); + _noteRule = NewRule(_pictureCard); + _noteIcon = new NoteIcon(); + _pictureCard.Controls.Add(_noteIcon); + _gifNote = Note(_pictureCard, "A GIF plays only while PlexusX is open and in front. It stops while a game runs. Only you see it; nothing is uploaded.", Theme.TextFaint); + _checkCard = NewCard(); + _checkTitle = Heading(_checkCard, "Text check"); + _checkStatus = new StatusPill(); + _checkCard.Controls.Add(_checkStatus); + _checkRatio = Words(_checkCard, "", Fonts.Body, Theme.TextDim); + _checkNote = Note(_checkCard, _slateLive ? "The dimmest text against the brightest part of your picture behind the panels. 4.5 : 1 is the bar." : "Solid panels: your picture never sits behind text.", Theme.TextFaint); + _keptCard = NewCard(); + _backdropTitle = Words(_keptCard, "Backdrop", Fonts.Body, Theme.Text); + _backdropNote = Note(_keptCard, "What is drawn behind the app.", Theme.TextFaint); + BackdropLook backdropLook = BackdropLooks.Parse(settings.BackdropLookName); + (BackdropLook, string)[] array2 = new (BackdropLook, string)[3] + { + (BackdropLook.Blossom, "Petals"), + (BackdropLook.Soft, "Soft"), + (BackdropLook.Off, "Off") + }; + for (int num = 0; num < array2.Length; num++) + { + (BackdropLook, string) tuple2 = array2[num]; + BackdropLook item4 = tuple2.Item1; + string item5 = tuple2.Item2; + BackdropLook chosen = item4; + ChipButton btn = new ChipButton + { + Text = item5, + Tag = chosen, + Active = (item4 == backdropLook) + }; + btn.Click += (object? s, EventArgs e) => + { + foreach (ChipButton backdropButton2 in customizePage._backdropButtons) + { + backdropButton2.Active = backdropButton2 == btn; + } + onBackdropChanged?.Invoke(chosen); + }; + _backdropButtons.Add(btn); + _keptCard.Controls.Add(btn); + } + RovingFocus.Attach(_backdropButtons, (Control c) => c is ChipButton chipButton && chipButton.Active); + _keptRuleDim = NewRule(_keptCard); + if (!_slateLive) + { + _dimTitle = Words(_keptCard, "Dim", Fonts.Body, Theme.Text); + _dimNote = Note(_keptCard, "", ControlInk.TextDisabledInk); + _dimValue = Words(_keptCard, $"{_settings.CustomBackgroundDim}%", Fonts.BodyBold, Theme.Text, ContentAlignment.MiddleRight); + _dimSlider = new FlatSlider + { + AccessibleName = "Dim", + Minimum = 0, + Maximum = 80, + Value = Math.Clamp(_settings.CustomBackgroundDim, 0, 80) + }; + FlatSlider dim = _dimSlider; + Label dimValue = _dimValue; + dim.ValueChanged += (object? s, EventArgs e) => + { + customizePage._custom?.SetDim(dim.Value); + dimValue.Text = $"{dim.Value}%"; + customizePage._saveDebounce.Trigger(); + customizePage._onBackgroundChanged(); + }; + _keptCard.Controls.Add(dim); + } + _keptRuleBlur = NewRule(_keptCard); + _blurTitle = Words(_keptCard, "Blur", Fonts.Body, Theme.Text); + _blurNote = Note(_keptCard, "", ControlInk.TextDisabledInk); + _blurValue = Words(_keptCard, $"{_settings.CustomBackgroundBlur}%", Fonts.BodyBold, Theme.Text, ContentAlignment.MiddleRight); + _blurSlider = new FlatSlider + { + AccessibleName = "Blur", + Minimum = 0, + Maximum = 100, + Value = Math.Clamp(_settings.CustomBackgroundBlur, 0, 100) + }; + _blurSlider.ValueChanged += (object? s, EventArgs e) => + { + customizePage._custom?.SetBlur(customizePage._blurSlider.Value); + customizePage._blurValue.Text = $"{customizePage._blurSlider.Value}%"; + customizePage._saveDebounce.Trigger(); + customizePage._onBackgroundChanged(); + }; + _keptCard.Controls.Add(_blurSlider); + _keptRuleMatte = NewRule(_keptCard); + _matteLabel = Words(_keptCard, "Behind the picture", Fonts.Body, Theme.Text); + _matteLabel.Visible = false; + _blackChip = new ChipButton + { + Text = "Black", + Visible = false + }; + _whiteChip = new ChipButton + { + Text = "White", + Visible = false + }; + _pickChip = new ChipButton + { + Text = "Pick a colour…", + Visible = false + }; + _blackChip.Click += (object? s, EventArgs e) => + { + ChooseMatte(BackgroundMatte.Black); + }; + _whiteChip.Click += (object? s, EventArgs e) => + { + ChooseMatte(BackgroundMatte.White); + }; + _pickChip.Click += (object? s, EventArgs e) => + { + using ColorDialog colorDialog = new ColorDialog + { + Color = AppBackground.Matte, + FullOpen = true + }; + if (colorDialog.ShowDialog(customizePage) == DialogResult.OK) + { + ChooseMatte(colorDialog.Color); + } + }; + _keptCard.Controls.Add(_blackChip); + _keptCard.Controls.Add(_whiteChip); + _keptCard.Controls.Add(_pickChip); + _keptRuleOpacity = NewRule(_keptCard); + _opacityTitle = Words(_keptCard, "Window opacity", Fonts.Body, Theme.Text); + _opacityValue = Words(_keptCard, $"{Clamp(_settings.OpacityPercent)}%", Fonts.BodyBold, Theme.Text, ContentAlignment.MiddleRight); + _opacitySlider = new FlatSlider + { + AccessibleName = "Window opacity", + Minimum = 50, + Maximum = 100, + Value = Clamp(_settings.OpacityPercent) + }; + _keptCard.Controls.Add(_opacitySlider); + _opacityHint = Note(_keptCard, "", Theme.TextFaint); + RefreshOpacityHint(); + _opacitySlider.ValueChanged += (object? s, EventArgs e) => + { + customizePage._onOpacityChanged(customizePage._opacitySlider.Value); + customizePage._settings.OpacityPercent = customizePage._opacitySlider.Value; + customizePage._opacityValue.Text = $"{customizePage._opacitySlider.Value}%"; + customizePage.RefreshOpacityHint(); + customizePage.LayoutContent(); + customizePage._saveDebounce.Trigger(); + }; + _keptRuleSaved = NewRule(_keptCard); + _savedNote = Note(_keptCard, "All settings are saved automatically.", Theme.TextFaint); + RefreshPictureControls(); + UseHeaderPanel(_title, _subtitle); + Resize += (object? _, EventArgs _) => + { + customizePage.LayoutContent(); + }; + _built = true; + LayoutContent(); + void ChooseMatte(Color matte) + { + AppBackground.SetMatte(matte); + customizePage._settings.CustomBackgroundMatteArgb = matte.ToArgb(); + customizePage._store.Save(customizePage._settings); + customizePage._blackChip.Active = matte.ToArgb() == BackgroundMatte.Black.ToArgb(); + customizePage._whiteChip.Active = matte.ToArgb() == BackgroundMatte.White.ToArgb(); + customizePage._pickChip.Active = !customizePage._blackChip.Active && !customizePage._whiteChip.Active; + customizePage._onBackgroundChanged(); + customizePage.RefreshTextCheck(); + } + } + + protected override void OnHandleCreated(EventArgs e) + { + base.OnHandleCreated(e); + LayoutContent(); + } + + protected override void OnVisibleChanged(EventArgs e) + { + base.OnVisibleChanged(e); + if (Visible) + { + LayoutContent(); + } + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _saveDebounce.Dispose(); + } + base.Dispose(disposing); + } + + private static int Clamp(int pct) + { + return Math.Clamp(pct, 50, 100); + } + + private void RefreshOpacityHint() + { + _opacityHint.Text = ((_opacitySlider.Value >= 100) ? "Fully opaque. This is the smoothest the window gets." : "Below 100% the window is translucent, and Windows redraws the whole thing every frame instead of copying it. The background animation gets choppier. Set this to 100% if you want it smooth."); + } + + internal static string ThemeAfterImagePicked(string currentTheme) + { + if (!SignatureLooks.TryGet(currentTheme, out var _)) + { + return "Ash"; + } + return currentTheme; + } + + internal static string ThemeAfterImageRemoved(string currentTheme) + { + if (!SignatureLooks.TryGet(currentTheme, out var _)) + { + return "Ash"; + } + return currentTheme; + } + + private void ChoosePicture() + { + using OpenFileDialog openFileDialog = new OpenFileDialog + { + Title = "Choose a background image", + Filter = "Images|*.png;*.jpg;*.jpeg;*.gif;*.bmp;*.webp|All files|*.*" + }; + if (openFileDialog.ShowDialog(this) != DialogResult.OK || _custom == null) + { + return; + } + if (!_custom.SetImage(openFileDialog.FileName)) + { + _pictureError.Text = "That file couldn't be read as an image."; + _pictureError.Visible = true; + LayoutContent(); + return; + } + _pictureError.Text = ""; + _pictureError.Visible = false; + if (_dimSlider != null) + { + _dimSlider.Value = _settings.CustomBackgroundDim; + _dimValue.Text = $"{_settings.CustomBackgroundDim}%"; + } + _blurSlider.Value = _settings.CustomBackgroundBlur; + _blurValue.Text = $"{_settings.CustomBackgroundBlur}%"; + _store.Save(_settings); + RefreshPictureControls(); + _onThemeChanged(ThemeAfterImagePicked(Theme.CurrentName)); + } + + private void RemovePicture() + { + if (!APictureIsSet) + { + RefreshPictureControls(); + return; + } + _custom?.Remove(); + _store.Save(_settings); + RefreshPictureControls(); + _onThemeChanged(ThemeAfterImageRemoved(Theme.CurrentName)); + } + + private (string Name, string Detail) DescribePicture() + { + CustomThemeService custom = _custom; + string text = ((custom != null && custom.HasImage) ? _custom.ImagePath : null); + string text2 = (((text != null) ? string.Equals(Path.GetExtension(text), ".gif", StringComparison.OrdinalIgnoreCase) : AppBackground.HasMotion) ? "GIF" : "Image"); + if (text == null) + { + return (Name: text2, Detail: ""); + } + string text3 = SizeOf(text); + return (Name: Path.GetFileName(text), Detail: (text3 == null) ? text2 : (text2 + " · " + text3)); + } + + private static string? SizeOf(string path) + { + try + { + using FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + using Image image = Image.FromStream(stream, useEmbeddedColorManagement: false, validateImageData: false); + return image.Width.ToString(CultureInfo.InvariantCulture) + " × " + image.Height.ToString(CultureInfo.InvariantCulture); + } + catch + { + return null; + } + } + + private void RefreshPictureControls() + { + bool aPictureIsSet = APictureIsSet; + Color foreColor = (aPictureIsSet ? Theme.Text : ControlInk.TextDisabledInk); + if (_dimSlider != null) + { + _dimSlider.Enabled = aPictureIsSet; + _dimTitle.ForeColor = foreColor; + _dimValue.ForeColor = foreColor; + _dimNote.Text = (aPictureIsSet ? "" : "Needs a background picture."); + _dimNote.Visible = !aPictureIsSet; + } + _blurSlider.Enabled = aPictureIsSet; + _blurTitle.ForeColor = foreColor; + _blurValue.ForeColor = foreColor; + _blurNote.Text = (aPictureIsSet ? "" : "Needs a background picture."); + _blurNote.Visible = !aPictureIsSet; + _pictureSwitch.Active = (aPictureIsSet ? "Image / GIF" : "None"); + _clearBtn.Visible = aPictureIsSet; + _clearBtn.Enabled = aPictureIsSet; + string text; + string text2; + if (aPictureIsSet) + { + (text, text2) = DescribePicture(); + } + else + { + text = ""; + text2 = ""; + } + _pictureName.Text = text; + _pictureDetail.Text = text2; + _thumb.Visible = aPictureIsSet; + _pictureName.Visible = aPictureIsSet; + _pictureDetail.Visible = aPictureIsSet && text2.Length > 0; + _noPicture.Visible = !aPictureIsSet; + _thumb.Invalidate(); + bool needsMatte = AppBackground.NeedsMatte; + _matteLabel.Visible = needsMatte; + _blackChip.Visible = needsMatte; + _whiteChip.Visible = needsMatte; + _pickChip.Visible = needsMatte; + int num = AppBackground.Matte.ToArgb(); + _blackChip.Active = num == BackgroundMatte.Black.ToArgb(); + _whiteChip.Active = num == BackgroundMatte.White.ToArgb(); + _pickChip.Active = needsMatte && !_blackChip.Active && !_whiteChip.Active; + LayoutContent(); + } + + internal void RefreshMatteControlForTest() + { + RefreshPictureControls(); + } + + private void RefreshTextCheck() + { + double num = TextCheck.Ratio(); + bool flag = num >= 4.5; + string text = TextCheck.Format(num); + _checkStatus.Text = (flag ? "Readable" : "Hard to read"); + _checkStatus.Status = ((!flag) ? StatusKind.Warning : StatusKind.Success); + _checkRatio.Text = text; + } + + private Label PageLabel(string text, Font font, Color colour) + { + Label label = new Label + { + Text = text, + Font = font, + ForeColor = colour, + BackColor = Color.Transparent, + AutoSize = false, + TextAlign = ContentAlignment.MiddleLeft, + UseMnemonic = false, + UseCompatibleTextRendering = false + }; + Controls.Add(label); + return label; + } + + private static Label Heading(Control card, string text) + { + return Words(card, text, Fonts.BodyBold, Theme.Text); + } + + private static Label Words(Control card, string text, Font font, Color colour, ContentAlignment align = ContentAlignment.MiddleLeft) + { + Label label = new Label + { + Text = text, + Font = font, + ForeColor = colour, + BackColor = Color.Transparent, + AutoSize = false, + TextAlign = align, + UseMnemonic = false, + UseCompatibleTextRendering = false + }; + card.Controls.Add(label); + return label; + } + + private static Label Note(Control card, string text, Color colour) + { + Label label = new Label + { + Text = text, + Font = Fonts.Caption, + ForeColor = colour, + BackColor = Color.Transparent, + AutoSize = true, + TextAlign = ContentAlignment.TopLeft, + UseMnemonic = false, + UseCompatibleTextRendering = false + }; + card.Controls.Add(label); + return label; + } + + private CardPanel NewCard() + { + CardPanel cardPanel = new CardPanel(); + Controls.Add(cardPanel); + return cardPanel; + } + + private static Rule NewRule(Control card) + { + Rule rule = new Rule(); + card.Controls.Add(rule); + return rule; + } + + private static int BoxFor(Font font, int line) + { + return Math.Max(line, TextRenderer.MeasureText("Ag", font).Height); + } + + private static int InkInset(Font font) + { + int width = TextRenderer.MeasureText("Ag", font).Width; + int width2 = TextRenderer.MeasureText("Ag", font, Size.Empty, TextFormatFlags.SingleLine | TextFormatFlags.NoPadding).Width; + return Math.Max(0, (width - width2) / 2); + } + + private static int InkWidth(Label l) + { + return TextRenderer.MeasureText(l.Text ?? "", l.Font, Size.Empty, TextFormatFlags.SingleLine | TextFormatFlags.NoPadding).Width; + } + + private static void PlaceText(Label l, int inkX, int y, int inkW, int h) + { + int num = InkInset(l.Font); + int num2 = BoxFor(l.Font, h); + int num3 = ((l.Font.SizeInPoints >= Fonts.Body.SizeInPoints - 0.01f) ? S(1) : 0); + l.SetBounds(inkX - num, y - (num2 - h) / 2 - num3, Math.Max(1, inkW) + 2 * num + 1, num2); + } + + private static void PlaceValue(Label l, int right, int y, int h) + { + int num = BoxFor(l.Font, h); + y -= (num - h) / 2; + h = num; + int num2 = Math.Max(TextRenderer.MeasureText(l.Text ?? "", l.Font).Width, TextRenderer.MeasureText("100%", l.Font).Width); + l.SetBounds(right - num2, y, num2, h); + } + + private static int LinesOf(Label note, int inkW) + { + if (string.IsNullOrEmpty(note.Text)) + { + return 0; + } + int num = InkInset(note.Font); + note.MinimumSize = Size.Empty; + note.MaximumSize = Size.Empty; + int num2 = Math.Max(1, note.GetPreferredSize(Size.Empty).Height); + note.MaximumSize = new Size(Math.Max(1, inkW + 2 * num), 0); + int num3 = (note.AutoSize ? note.Height : note.GetPreferredSize(note.MaximumSize).Height); + return Math.Max(1, (int)Math.Round((double)num3 / (double)num2)); + } + + private static int PlaceNote(Label note, int inkX, int y, int inkW) + { + int num = InkInset(note.Font); + note.MaximumSize = new Size(Math.Max(1, inkW + 2 * num), 0); + note.Location = new Point(inkX - num, y + S(1)); + return CaptionHeight(note, inkW); + } + + private static int CaptionHeight(Label note, int inkW) + { + int num = LinesOf(note, inkW); + if (num == 0) + { + return 0; + } + int result = Math.Max(num * CaptionLine, note.Height); + note.MinimumSize = new Size(0, num * CaptionLine); + return result; + } + + private static void PlaceRule(Rule rule, int y, int cardW) + { + rule.Visible = true; + rule.SetBounds(Inset, y, cardW - 2 * Inset, ControlInk.Hairline(Tokens.Dpi)); + } + + private void LayoutContent() + { + if (!_built || Width <= 0) + { + return; + } + int contentLeft = GlowPage.ContentLeft; + int num = ContentRight - contentLeft; + if (num > 0) + { + RefreshTextCheck(); + bool flag = num >= S(760); + int num2 = (flag ? S(332) : num); + int num3 = (flag ? (num - ColumnGap - num2) : num); + int x = (flag ? (contentLeft + num3 + ColumnGap) : contentLeft); + int y = AutoScrollPosition.Y; + int y2 = ContentTop + y; + int num4; + if (flag) + { + int y3 = LayoutLookCard(contentLeft, y2, num3) + CardGap; + y3 = LayoutKeptCard(contentLeft, y3, num3); + int y4 = LayoutPictureCard(x, y2, num2) + CardGap; + y4 = LayoutTextCheckCard(x, y4, num2); + num4 = Math.Max(y3, y4); + } + else + { + int y5 = LayoutLookCard(contentLeft, y2, num) + CardGap; + y5 = LayoutPictureCard(contentLeft, y5, num) + CardGap; + y5 = LayoutTextCheckCard(contentLeft, y5, num) + CardGap; + num4 = LayoutKeptCard(contentLeft, y5, num); + } + Size size = new Size(0, num4 - y + S(16)); + if (AutoScrollMinSize != size) + { + AutoScrollMinSize = size; + } + } + } + + private int LayoutLookCard(int x, int y, int w) + { + int num = w - 2 * Inset; + int inset = Inset; + int num2 = S(24); + int width = TextRenderer.MeasureText(_modeCaption.Text ?? "", _modeCaption.Font).Width; + int num3 = BoxFor(_modeCaption.Font, CaptionLine); + int num4 = Inset + num + InkInset(_modeCaption.Font) - width - S(8); + _modeCaption.SetBounds(num4, inset + (num2 - num3) / 2, width + S(8), num3); + int val = num4 - Inset - 2 * InkInset(_lookTitle.Font) - 1 - S(2); + PlaceText(_lookTitle, Inset, inset + (num2 - TitleLine) / 2, Math.Max(S(40), val), TitleLine); + inset += num2 + S(12); + int num5 = S(12); + int tileW = (num - num5) / 2; + int num6 = _lookTiles.Select((LookTile t) => Math.Max(LookTile.HeightFor(tileW, t.Caption, Tokens.Dpi), TileHeightByTheDesign(tileW, t.Caption))).DefaultIfEmpty(S(196)).Max(); + for (int num7 = 0; num7 < _lookTiles.Count; num7++) + { + _lookTiles[num7].SetBounds(Inset + num7 * (tileW + num5), inset, tileW, num6); + } + inset += num6 + S(12); + inset = SliderRow(w, inset, null, _opacityRowTitle, _opacityRowNote, _opacityRowValue, _slateOpacity); + inset = ToggleRow(w, inset, _slateRule1, _matteBlurTitle, _matteBlurNote, _matteBlurToggle); + inset += S(20); + _lookCard.SetBounds(x, y, w, inset + 1); + return _lookCard.Bottom; + } + + private int LayoutPictureCard(int x, int y, int w) + { + int num = w - 2 * Inset; + int inset = Inset; + int num2 = S(32); + int num3 = Math.Min(num, _pictureSwitch.NaturalWidth); + _pictureSwitch.SetBounds(Inset + num - num3, inset, num3, num2); + PlaceText(_pictureTitle, Inset, inset + (num2 - TitleLine) / 2, Math.Max(S(40), num - num3 - S(8)), TitleLine); + inset += num2 + S(12); + Size thumbSize = ThumbSize; + _thumb.SetBounds(Inset, inset, thumbSize.Width, thumbSize.Height); + int inkX = Inset + thumbSize.Width + S(12); + int inkW = Math.Max(S(40), num - thumbSize.Width - S(12)); + int num4 = TitleLine + S(2) + CaptionLine; + int num5 = inset + (thumbSize.Height - num4) / 2; + PlaceText(_pictureName, inkX, num5, inkW, TitleLine); + PlaceText(_pictureDetail, inkX, num5 + TitleLine + S(2), inkW, CaptionLine); + PlaceText(_noPicture, Inset, inset, num, TitleLine); + inset += (_thumb.Visible ? thumbSize.Height : TitleLine); + int num6 = PlaceNote(_pictureError, Inset, inset + S(8), num); + if (_pictureError.Visible && _pictureError.Text.Length > 0) + { + inset += S(8) + num6; + } + inset += S(12); + int num7 = S(28); + _chooseBtn.Height = num7; + _clearBtn.Height = num7; + _chooseBtn.Width = _chooseBtn.GetPreferredSize(Size.Empty).Width; + _clearBtn.Width = _clearBtn.GetPreferredSize(Size.Empty).Width; + _chooseBtn.Location = new Point(Inset, inset); + _clearBtn.Location = new Point(_chooseBtn.Right + S(8), inset); + inset += num7; + inset += S(16); + PlaceRule(_noteRule, inset, w); + inset += ControlInk.Hairline(Tokens.Dpi) + S(12); + _noteIcon.SetBounds(Inset, inset, S(16), S(16)); + inset += PlaceNote(_gifNote, Inset + S(16) + S(8), inset, num - S(16) - S(8)); + inset += S(20); + _pictureCard.SetBounds(x, y, w, inset + 1); + return _pictureCard.Bottom; + } + + private int LayoutTextCheckCard(int x, int y, int w) + { + int num = w - 2 * Inset; + int inset = Inset; + int num2 = S(24); + PlaceText(_checkTitle, Inset, inset + (num2 - TitleLine) / 2, num, TitleLine); + inset += num2 + S(12); + int num3 = S(23); + Size size = TextRenderer.MeasureText(_checkStatus.Text ?? "", Fonts.BodyBold, Size.Empty, TextFormatFlags.SingleLine | TextFormatFlags.NoPadding); + _checkStatus.Size = new Size(S(16) + S(8) + size.Width + S(2), Math.Max(S(20), size.Height)); + _checkStatus.Location = new Point(Inset, inset + (num3 - _checkStatus.Height) / 2 - S(1)); + int num4 = _checkStatus.Right + S(8); + PlaceText(_checkRatio, num4, inset + (num3 - TitleLine) / 2, Math.Max(S(40), Inset + num - num4), TitleLine); + inset += num3 + S(4); + inset += PlaceNote(_checkNote, Inset, inset, num); + inset += S(20); + _checkCard.SetBounds(x, y, w, inset + 1); + return _checkCard.Bottom; + } + + private int LayoutKeptCard(int x, int y, int w) + { + int inkW = w - 2 * Inset; + int top = ListPadY + ControlInk.Hairline(Tokens.Dpi); + int height = S(32); + foreach (ChipButton backdropButton in _backdropButtons) + { + backdropButton.Size = new Size(ChipWidth(backdropButton, S(72)), height); + } + top = ControlRow(w, top, null, _backdropTitle, _backdropNote, _backdropButtons.Cast().ToArray()); + if (_dimSlider != null && _dimTitle != null && _dimValue != null) + { + top = SliderRow(w, top, _keptRuleDim, _dimTitle, _dimNote, _dimValue, _dimSlider); + } + else + { + _keptRuleDim.Visible = false; + } + top = SliderRow(w, top, _keptRuleBlur, _blurTitle, _blurNote, _blurValue, _blurSlider); + _blackChip.Size = new Size(ChipWidth(_blackChip, S(72)), height); + _whiteChip.Size = new Size(ChipWidth(_whiteChip, S(72)), height); + _pickChip.Size = new Size(ChipWidth(_pickChip, S(140)), height); + Control[] controls = new Control[3] { _blackChip, _whiteChip, _pickChip }; + if (_matteLabel.Visible) + { + top = ControlRow(w, top, _keptRuleMatte, _matteLabel, null, controls); + } + else + { + _keptRuleMatte.Visible = false; + ControlRow(w, top, null, _matteLabel, null, controls); + } + top = SliderRow(w, top, _keptRuleOpacity, _opacityTitle, _opacityHint, _opacityValue, _opacitySlider); + PlaceRule(_keptRuleSaved, top, w); + int num = top + ControlInk.Hairline(Tokens.Dpi); + int num2 = Math.Max(S(44), CaptionLine + S(8)); + PlaceNote(_savedNote, Inset, num + (num2 - CaptionLine) / 2, inkW); + top += num2; + top += ListPadY; + _keptCard.SetBounds(x, y, w, top + 1); + return _keptCard.Bottom; + } + + private static int TileHeightByTheDesign(int tileW, string caption) + { + int width = Math.Max(1, tileW - 2 * S(13)); + int height = TextRenderer.MeasureText(caption, Fonts.Caption, new Size(width, int.MaxValue), TextFormatFlags.WordBreak | TextFormatFlags.NoPadding).Height; + int height2 = TextRenderer.MeasureText("Ag", Fonts.Caption, Size.Empty, TextFormatFlags.NoPadding).Height; + int num = Math.Max(1, (int)Math.Round((double)height / (double)Math.Max(1, height2))); + return S(151) + num * CaptionLine + S(13); + } + + private static int ChipWidth(ChipButton chip, int atLeast) + { + return Math.Max(atLeast, TextRenderer.MeasureText(chip.Text ?? "", Fonts.BodyBold).Width + S(24)); + } + + private int RowFrame(int cardW, int top, Rule? rule, Label title, Label? note, int rightW, out int centre) + { + int num = cardW - 2 * Inset; + int inkW = Math.Max(S(60), num - ((rightW > 0) ? (rightW + S(16)) : 0)); + int num2 = ((note != null && !string.IsNullOrEmpty(note.Text)) ? CaptionHeight(note, inkW) : 0); + int num3 = TitleLine + ((num2 > 0) ? (S(2) + num2) : 0); + int num4 = Math.Max(RowMin, S(8) + num3); + int num5 = top; + if (rule != null) + { + PlaceRule(rule, top, cardW); + num5 = top + ControlInk.Hairline(Tokens.Dpi); + } + int num6 = num5 + (num4 - num3) / 2; + PlaceText(title, Inset, num6, inkW, TitleLine); + if (note != null) + { + PlaceNote(note, Inset, num6 + TitleLine + S(2), inkW); + } + centre = num5 + num4 / 2; + return top + num4; + } + + private int SliderRow(int cardW, int top, Rule? rule, Label title, Label? note, Label value, FlatSlider slider) + { + int num = cardW - 2 * Inset; + int num2 = Math.Min(RowSliderW, num / 2); + int rightW = TextRenderer.MeasureText("100%", value.Font, Size.Empty, TextFormatFlags.SingleLine | TextFormatFlags.NoPadding).Width + S(12) + num2; + int result = RowFrame(cardW, top, rule, title, note, rightW, out var centre); + int x = Inset + num - num2; + slider.SetTrackBounds(x, centre - S(16), num2, S(32)); + PlaceValue(value, slider.Left, centre - TitleLine / 2, TitleLine); + return result; + } + + private int ToggleRow(int cardW, int top, Rule? rule, Label title, Label? note, ToggleSwitch toggle) + { + int num = cardW - 2 * Inset; + int result = RowFrame(cardW, top, rule, title, note, S(40), out var centre); + toggle.SetBounds(Inset + num - S(40), centre - S(10), S(40), S(20)); + return result; + } + + private int ControlRow(int cardW, int top, Rule? rule, Label title, Label? note, Control[] controls) + { + int num = cardW - 2 * Inset; + int num2 = S(8); + int num3 = controls.Sum((Control c) => c.Width) + num2 * (controls.Length - 1); + int num4 = controls.Max((Control c) => c.Height); + Control[] array; + if (num - num3 - S(16) >= Math.Max(InkWidth(title), S(60))) + { + int result = RowFrame(cardW, top, rule, title, note, num3, out var centre); + int num5 = Inset + num - num3; + array = controls; + foreach (Control control in array) + { + control.Location = new Point(num5, centre - control.Height / 2); + num5 += control.Width + num2; + } + return result; + } + int num7 = RowFrame(cardW, top, rule, title, note, 0, out var _); + int num8 = Inset; + array = controls; + foreach (Control control2 in array) + { + control2.Location = new Point(num8, num7); + num8 += control2.Width + num2; + } + return num7 + num4 + S(12); + } +} diff --git a/VibranceHud/Customize/CustomizeService.cs b/VibranceHud/Customize/CustomizeService.cs new file mode 100644 index 0000000..1852aef --- /dev/null +++ b/VibranceHud/Customize/CustomizeService.cs @@ -0,0 +1,586 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using Microsoft.Win32; + +namespace VibranceHud.Customize; + +public static class CustomizeService +{ + internal interface IRegistryReadKey + { + object? GetValue(string name, object? defaultValue); + } + + private sealed class RegistryReadKey : IRegistryReadKey + { + private readonly RegistryKey _key; + + public RegistryReadKey(RegistryKey key) + { + _key = key; + } + + public object? GetValue(string name, object? defaultValue) + { + return _key.GetValue(name, defaultValue); + } + } + + internal struct ACCENT_POLICY + { + public uint AccentState; + + public uint AccentFlags; + + public uint GradientColor; + + public uint AnimationId; + } + + internal struct WINDOW_COMPOSITION_ATTRIB_DATA + { + public uint Attribute; + + public nint Data; + + public int SizeOfData; + } + + internal enum AccentState + { + Disabled, + EnableGradient, + EnableTransparentGradient, + EnableBlurBehind, + EnableAcrylicBlurBehind, + EnableHostBackdrop, + InvalidState + } + + internal enum WindowCompositionAttribute + { + WCA_ACCENT_POLICY = 19 + } + + internal delegate bool EnumWindowsProc(nint hWnd, nint lParam); + + [Serializable] + [CompilerGenerated] + private sealed class _003C_003Ec + { + public static readonly _003C_003Ec _003C_003E9 = new _003C_003Ec(); + + public static Func _003C_003E9__6_0; + + public static Func _003C_003E9__12_0; + + internal IRegistryReadKey? _003CReadFromRegistry_003Eb__6_0(string path) + { + RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(path, writable: false); + if (registryKey != null) + { + return new RegistryReadKey(registryKey); + } + return null; + } + + internal bool _003CTaskbarWriterFor_003Eb__12_0(ACCENT_POLICY _) + { + return false; + } + } + + private const uint WM_SETTINGCHANGE = 26u; + + private const uint SMTO_ABORTIFHUNG = 2u; + + private static readonly nint HWND_BROADCAST = new IntPtr(-1); + + private const int SHCNE_ASSOCCHANGED = 134217728; + + private const uint SHCNF_IDLIST = 0u; + + private const string Shell_TrayWnd = "Shell_TrayWnd"; + + public static CustomizationSettings MergeLook(CustomizationSettings current, CustomizationSettings preset) + { + return preset with + { + Taskbar = preset.Taskbar with + { + Alignment = current.Taskbar.Alignment, + SmallButtons = current.Taskbar.SmallButtons, + Search = current.Taskbar.Search, + ShowTaskView = current.Taskbar.ShowTaskView, + ShowWidgets = current.Taskbar.ShowWidgets + }, + Explorer = current.Explorer, + Windows = preset.Windows with + { + StartLayout = current.Windows.StartLayout + } + }; + } + + public static IReadOnlyList Plan(CustomizationSettings current, CustomizationSettings target) + { + List list = new List(); + string key = "Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; + string key2 = "Software\\Microsoft\\Windows\\DWM"; + if (current.System.DarkMode != target.System.DarkMode) + { + list.Add(new RegistryChange(key, "AppsUseLightTheme", (!target.System.DarkMode) ? 1u : 0u)); + list.Add(new RegistryChange(key, "SystemUsesLightTheme", (!target.System.DarkMode) ? 1u : 0u)); + } + if (current.System.AccentColorArgb != target.System.AccentColorArgb) + { + list.Add(new RegistryChange(key2, "AccentColor", ArgbToDwmAbgr(target.System.AccentColorArgb))); + } + if (current.System.TitleBarsUseAccent != target.System.TitleBarsUseAccent) + { + list.Add(new RegistryChange(key2, "ColorPrevalence", target.System.TitleBarsUseAccent ? 1u : 0u)); + } + if (current.System.BordersUseAccent != target.System.BordersUseAccent) + { + list.Add(new RegistryChange(key2, "AccentColorInactive", target.System.BordersUseAccent ? ArgbToDwmAbgr(target.System.AccentColorArgb) : 0u)); + list.Add(new RegistryChange(key2, "PlexusXBordersUseAccent", target.System.BordersUseAccent ? 1u : 0u)); + } + string text = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced"; + if (current.Taskbar.Buttons != target.Taskbar.Buttons) + { + list.Add(new RegistryChange(text, "TaskbarGlomLevel", target.Taskbar.Buttons switch + { + TaskbarButtonGlom.Always => 0u, + TaskbarButtonGlom.Never => 1u, + _ => 2u, + })); + } + if (current.Taskbar.Alignment != target.Taskbar.Alignment) + { + list.Add(new RegistryChange(text, "TaskbarAl", (target.Taskbar.Alignment != TaskbarAlignment.Left) ? 1u : 0u)); + } + if (current.Taskbar.SmallButtons != target.Taskbar.SmallButtons) + { + list.Add(new RegistryChange(text, "TaskbarSmallIcons", target.Taskbar.SmallButtons ? 1u : 0u)); + } + if (current.Taskbar.ShowTaskView != target.Taskbar.ShowTaskView) + { + list.Add(new RegistryChange(text, "ShowTaskViewButton", target.Taskbar.ShowTaskView ? 1u : 0u)); + } + if (current.Taskbar.ShowWidgets != target.Taskbar.ShowWidgets) + { + list.Add(new RegistryChange(text, "TaskbarDa", target.Taskbar.ShowWidgets ? 1u : 0u)); + } + if (current.Taskbar.Search != target.Taskbar.Search) + { + List list2 = list; + list2.Add(new RegistryChange("Software\\Microsoft\\Windows\\CurrentVersion\\Search", "SearchboxTaskbarMode", target.Taskbar.Search switch + { + SearchBoxMode.Hidden => 0u, + SearchBoxMode.Icon => 1u, + _ => 2u, + })); + } + if (current.Explorer.ShowFileExtensions != target.Explorer.ShowFileExtensions) + { + list.Add(new RegistryChange(text, "HideFileExt", (!target.Explorer.ShowFileExtensions) ? 1u : 0u)); + } + if (current.Explorer.ShowHiddenFiles != target.Explorer.ShowHiddenFiles) + { + list.Add(new RegistryChange(text, "Hidden", target.Explorer.ShowHiddenFiles ? 1u : 2u)); + } + if (current.Windows.StartLayout != target.Windows.StartLayout) + { + List list2 = list; + string key3 = text; + list2.Add(new RegistryChange(key3, "Start_Layout", target.Windows.StartLayout switch + { + StartLayoutMode.MorePins => 1u, + StartLayoutMode.MoreRecommendations => 2u, + _ => 0u, + })); + } + if (current.Windows.CornerRadiusPx != target.Windows.CornerRadiusPx) + { + int cornerRadiusPx = target.Windows.CornerRadiusPx; + uint num = ((cornerRadiusPx >= 6) ? 2u : ((cornerRadiusPx == 0) ? 1u : 3u)); + uint dwordValue = num; + list.Add(new RegistryChange(key2, "WindowCornerPreference", dwordValue)); + } + if (current.Windows.SnapAssistSuggestions != target.Windows.SnapAssistSuggestions) + { + list.Add(new RegistryChange(text, "SnapAssist", target.Windows.SnapAssistSuggestions ? 1u : 0u)); + } + if (current.Windows.TransparencyEnabled != target.Windows.TransparencyEnabled) + { + list.Add(new RegistryChange(key, "EnableTransparency", target.Windows.TransparencyEnabled ? 1u : 0u)); + } + return list; + } + + internal static uint ArgbToDwmAbgr(uint argb) + { + uint num = (argb >> 24) & 0xFF; + uint num2 = (argb >> 16) & 0xFF; + uint num3 = (argb >> 8) & 0xFF; + return ((argb & 0xFF) << 24) | (num3 << 16) | (num2 << 8) | num; + } + + public static void Apply(CustomizationSettings target) + { + ApplyPlan(Plan(ReadFromRegistry(), target)); + BroadcastSettingChange(); + } + + internal static void Apply(string registryRoot, CustomizationSettings target) + { + ApplyPlan(Plan(ReadFromRegistry(registryRoot), target), registryRoot); + } + + public static CustomizationSettings ReadFromRegistry() + { + return ReadFromRegistry("Software\\Microsoft\\Windows"); + } + + internal static CustomizationSettings ReadFromRegistry(string root) + { + return ReadFromRegistry(root, (string path) => + { + RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(path, writable: false); + return (registryKey != null) ? new RegistryReadKey(registryKey) : null; + }); + } + + internal static CustomizationSettings ReadFromRegistry(string root, Func openKey) + { + try + { + return ReadRegistry(root, openKey); + } + catch + { + return new CustomizationSettings(); + } + } + + private static CustomizationSettings ReadRegistry(string root, Func openKey) + { + TaskbarSettings taskbarSettings = new TaskbarSettings(); + SystemSettings systemSettings = new SystemSettings(); + WindowSettings windowSettings = new WindowSettings(); + if (TryOpen(root + "\\CurrentVersion\\Themes\\Personalize", openKey, out IRegistryReadKey key)) + { + systemSettings = systemSettings with + { + DarkMode = ((int)(key.GetValue("AppsUseLightTheme", 1) ?? ((object)1)) == 0) + }; + windowSettings = windowSettings with + { + TransparencyEnabled = ((int)(key.GetValue("EnableTransparency", 1) ?? ((object)1)) == 1) + }; + } + if (TryOpen(root + "\\DWM", openKey, out IRegistryReadKey key2)) + { + int dwm = (int)(key2.GetValue("AccentColor", 0) ?? ((object)0)); + systemSettings = systemSettings with + { + AccentColorArgb = DwmAbgrToArgb((uint)dwm), + TitleBarsUseAccent = ((int)(key2.GetValue("ColorPrevalence", 0) ?? ((object)0)) == 1), + BordersUseAccent = ((int)(key2.GetValue("PlexusXBordersUseAccent", 0) ?? ((object)0)) == 1) + }; + int num = (int)(key2.GetValue("WindowCornerPreference", 0) ?? ((object)0)); + windowSettings = windowSettings with + { + CornerRadiusPx = num switch + { + 1 => 0, + 3 => 4, + _ => 8, + } + }; + } + ExplorerSettings explorerSettings = new ExplorerSettings(); + if (TryOpen(root + "\\CurrentVersion\\Explorer\\Advanced", openKey, out IRegistryReadKey key3)) + { + int num2 = (int)(key3.GetValue("TaskbarGlomLevel", 2) ?? ((object)2)); + taskbarSettings = taskbarSettings with + { + Buttons = num2 switch + { + 0 => TaskbarButtonGlom.Always, + 1 => TaskbarButtonGlom.Never, + _ => TaskbarButtonGlom.Combine, + }, + Alignment = (((int)(key3.GetValue("TaskbarAl", 1) ?? ((object)1)) != 0) ? TaskbarAlignment.Centre : TaskbarAlignment.Left), + SmallButtons = (int)(key3.GetValue("TaskbarSmallIcons", 0) ?? ((object)0)) == 1, + ShowTaskView = (int)(key3.GetValue("ShowTaskViewButton", 1) ?? ((object)1)) == 1, + ShowWidgets = (int)(key3.GetValue("TaskbarDa", 1) ?? ((object)1)) == 1 + }; + windowSettings = windowSettings with + { + SnapAssistSuggestions = ((int)(key3.GetValue("SnapAssist", 1) ?? ((object)1)) == 1), + StartLayout = (int)(key3.GetValue("Start_Layout", 0) ?? ((object)0)) switch + { + 1 => StartLayoutMode.MorePins, + 2 => StartLayoutMode.MoreRecommendations, + _ => StartLayoutMode.Default, + } + }; + explorerSettings = explorerSettings with + { + ShowFileExtensions = ((int)(key3.GetValue("HideFileExt", 1) ?? ((object)1)) == 0), + ShowHiddenFiles = ((int)(key3.GetValue("Hidden", 2) ?? ((object)2)) == 1) + }; + } + if (TryOpen(root + "\\CurrentVersion\\Search", openKey, out IRegistryReadKey key4)) + { + taskbarSettings = taskbarSettings with + { + Search = (int)(key4.GetValue("SearchboxTaskbarMode", 2) ?? ((object)2)) switch + { + 0 => SearchBoxMode.Hidden, + 1 => SearchBoxMode.Icon, + _ => SearchBoxMode.Box, + } + }; + } + return new CustomizationSettings + { + Taskbar = taskbarSettings, + System = systemSettings, + Windows = windowSettings, + Explorer = explorerSettings + }; + } + + public static TaskbarStyle StyleFromName(string? name) + { + if (!Enum.TryParse(name, ignoreCase: true, out var result)) + { + return TaskbarStyle.Normal; + } + return result; + } + + public static bool ShouldReapplyTaskbarStyle(AppSettings settings) + { + return ShouldReapplyTaskbarStyle(settings, FlavourPolicy.Current); + } + + public static bool ShouldReapplyTaskbarStyle(AppSettings settings, FlavourPolicy policy) + { + if (policy.TouchesTheTaskbar) + { + return StyleFromName(settings.TaskbarStyleName) != TaskbarStyle.Normal; + } + return false; + } + + internal static Func TaskbarWriterFor(FlavourPolicy policy, Func real) + { + Func func; + if (!policy.TouchesTheTaskbar) + { + func = _003C_003Ec._003C_003E9__12_0; + if (func == null) + { + return _003C_003Ec._003C_003E9__12_0 = (ACCENT_POLICY _) => false; + } + } + else + { + func = real; + } + return func; + } + + public static bool NeedsExplorerRestart(CustomizeTweak tweak) + { + return tweak switch + { + CustomizeTweak.SmallTaskbarButtons => true, + CustomizeTweak.StartLayout => true, + CustomizeTweak.SearchBox => true, + _ => false, + }; + } + + private static void ApplyPlan(IReadOnlyList plan, string root = "Software\\Microsoft\\Windows") + { + foreach (RegistryChange item in plan) + { + if (!item.Key.StartsWith("Software\\Microsoft\\Windows", StringComparison.OrdinalIgnoreCase)) + { + throw new InvalidOperationException("RegistryChange targets '" + item.Key + "', which ApplyPlan cannot rewrite. Every key must live under Software\\Microsoft\\Windows."); + } + string text = (item.Key.StartsWith("Software\\Microsoft\\Windows") ? item.Key.Substring("Software\\Microsoft\\Windows".Length).TrimStart('\\') : item.Key); + using RegistryKey registryKey = Registry.CurrentUser.CreateSubKey(root + ((text.Length > 0) ? ("\\" + text) : "")); + registryKey.SetValue(item.ValueName, (int)item.DwordValue, RegistryValueKind.DWord); + } + } + + [DllImport("user32.dll", SetLastError = true)] + private static extern nint SendMessageTimeout(nint hWnd, uint Msg, nuint wParam, string lParam, uint flags, uint timeout, out nint result); + + [DllImport("shell32.dll")] + private static extern void SHChangeNotify(int eventId, uint flags, nint item1, nint item2); + + private static void BroadcastSettingChange() + { + SendMessageTimeout(HWND_BROADCAST, 26u, UIntPtr.Zero, "ImmersiveColorSet", 2u, 100u, out var _); + SHChangeNotify(134217728, 0u, IntPtr.Zero, IntPtr.Zero); + } + + private static bool TryOpen(string path, Func openKey, [NotNullWhen(true)] out IRegistryReadKey? key) + { + key = openKey(path); + return key != null; + } + + internal static uint DwmAbgrToArgb(uint dwm) + { + uint num = (dwm >> 8) & 0xFF; + uint num2 = (dwm >> 16) & 0xFF; + uint num3 = (dwm >> 24) & 0xFF; + return 0xFF000000u | (num << 16) | (num2 << 8) | num3; + } + + [DllImport("user32.dll")] + private static extern int SetWindowCompositionAttribute(nint hWnd, ref WINDOW_COMPOSITION_ATTRIB_DATA data); + + [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern nint FindWindow(string lpClassName, string lpWindowName); + + [DllImport("user32.dll")] + private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, nint lParam); + + [DllImport("user32.dll", CharSet = CharSet.Unicode)] + private static extern int GetClassName(nint hWnd, StringBuilder lpString, int nMaxCount); + + public static TaskbarStyleSupport ProbeTaskbarStyle() + { + return ProbeTaskbarStyleThrough(TaskbarWriterFor(FlavourPolicy.Current, WriteAccentToTheTaskbar)); + } + + internal static TaskbarStyleSupport ProbeTaskbarStyleThrough(Func write) + { + try + { + ACCENT_POLICY arg = new ACCENT_POLICY + { + AccentState = 0u + }; + return (!write(arg)) ? TaskbarStyleSupport.Unsupported : TaskbarStyleSupport.Working; + } + catch (DllNotFoundException) + { + return TaskbarStyleSupport.Unsupported; + } + catch (EntryPointNotFoundException) + { + return TaskbarStyleSupport.Unsupported; + } + } + + private static bool WriteAccentToTheTaskbar(ACCENT_POLICY accent) + { + nint num = FindTaskbarHandle(); + if (num == IntPtr.Zero) + { + return false; + } + int num2 = Marshal.SizeOf(); + WINDOW_COMPOSITION_ATTRIB_DATA data = new WINDOW_COMPOSITION_ATTRIB_DATA + { + Attribute = 19u, + SizeOfData = num2, + Data = Marshal.AllocHGlobal(num2) + }; + try + { + Marshal.StructureToPtr(accent, data.Data, fDeleteOld: false); + return SetWindowCompositionAttribute(num, ref data) != 0; + } + finally + { + Marshal.FreeHGlobal(data.Data); + } + } + + public static uint EffectiveTaskbarColour(TaskbarSettings taskbar, SystemSettings system) + { + uint num = ((!taskbar.UseAccentForTaskbar && taskbar.ColorArgb != 0) ? taskbar.ColorArgb : system.AccentColorArgb); + if (taskbar.Style != TaskbarStyle.Normal) + { + uint num2 = (num >> 24) & 0xFF; + if (num2 < 60) + { + num2 = 60u; + } + num = (num & 0xFFFFFF) | (num2 << 24); + } + return num; + } + + public static uint EffectiveTaskbarGradientColor(TaskbarSettings taskbar, SystemSettings system) + { + return ArgbToDwmAbgr(EffectiveTaskbarColour(taskbar, system)); + } + + public static bool ApplyTaskbarStyle(TaskbarSettings taskbar) + { + return ApplyTaskbarStyle(taskbar, new SystemSettings()); + } + + public static bool ApplyTaskbarStyle(TaskbarSettings taskbar, SystemSettings system) + { + return ApplyTaskbarStyleThrough(TaskbarWriterFor(FlavourPolicy.Current, WriteAccentToTheTaskbar), taskbar, system); + } + + internal static bool ApplyTaskbarStyleThrough(Func write, TaskbarSettings taskbar, SystemSettings system) + { + try + { + ACCENT_POLICY arg = new ACCENT_POLICY + { + AccentState = taskbar.Style switch + { + TaskbarStyle.Normal => 0u, + TaskbarStyle.Acrylic => 4u, + TaskbarStyle.Clear => 2u, + TaskbarStyle.Blur => 3u, + TaskbarStyle.Fluent => 5u, + _ => 0u, + }, + AccentFlags = 2u, + GradientColor = EffectiveTaskbarGradientColor(taskbar, system) + }; + return write(arg); + } + catch + { + return false; + } + } + + private static nint FindTaskbarHandle() + { + nint found = IntPtr.Zero; + EnumWindows((nint hWnd, nint lParam) => + { + StringBuilder stringBuilder = new StringBuilder(256); + GetClassName(hWnd, stringBuilder, stringBuilder.Capacity); + if (stringBuilder.ToString() == "Shell_TrayWnd") + { + found = hWnd; + return false; + } + return true; + }, IntPtr.Zero); + return found; + } +} diff --git a/VibranceHud/Customize/CustomizeTweak.cs b/VibranceHud/Customize/CustomizeTweak.cs new file mode 100644 index 0000000..f1bf57b --- /dev/null +++ b/VibranceHud/Customize/CustomizeTweak.cs @@ -0,0 +1,13 @@ +namespace VibranceHud.Customize; + +public enum CustomizeTweak +{ + TaskbarAlignment, + WidgetsButton, + StartLayout, + SmallTaskbarButtons, + SearchBox, + TaskViewButton, + FileExtensions, + HiddenFiles +} diff --git a/VibranceHud/Customize/ExplorerSettings.cs b/VibranceHud/Customize/ExplorerSettings.cs new file mode 100644 index 0000000..b05e15e --- /dev/null +++ b/VibranceHud/Customize/ExplorerSettings.cs @@ -0,0 +1,8 @@ +namespace VibranceHud.Customize; + +public sealed record ExplorerSettings +{ + public bool ShowFileExtensions { get; init; } + + public bool ShowHiddenFiles { get; init; } +} diff --git a/VibranceHud/Customize/RegistryChange.cs b/VibranceHud/Customize/RegistryChange.cs new file mode 100644 index 0000000..b172b0e --- /dev/null +++ b/VibranceHud/Customize/RegistryChange.cs @@ -0,0 +1,3 @@ +namespace VibranceHud.Customize; + +public sealed record RegistryChange(string Key, string ValueName, uint DwordValue); diff --git a/VibranceHud/Customize/SearchBoxMode.cs b/VibranceHud/Customize/SearchBoxMode.cs new file mode 100644 index 0000000..8f26a9c --- /dev/null +++ b/VibranceHud/Customize/SearchBoxMode.cs @@ -0,0 +1,8 @@ +namespace VibranceHud.Customize; + +public enum SearchBoxMode +{ + Hidden, + Icon, + Box +} diff --git a/VibranceHud/Customize/StartLayoutMode.cs b/VibranceHud/Customize/StartLayoutMode.cs new file mode 100644 index 0000000..678a53b --- /dev/null +++ b/VibranceHud/Customize/StartLayoutMode.cs @@ -0,0 +1,8 @@ +namespace VibranceHud.Customize; + +public enum StartLayoutMode +{ + Default, + MorePins, + MoreRecommendations +} diff --git a/VibranceHud/Customize/SystemSettings.cs b/VibranceHud/Customize/SystemSettings.cs new file mode 100644 index 0000000..bea94d4 --- /dev/null +++ b/VibranceHud/Customize/SystemSettings.cs @@ -0,0 +1,12 @@ +namespace VibranceHud.Customize; + +public sealed record SystemSettings +{ + public bool DarkMode { get; init; } + + public uint AccentColorArgb { get; init; } + + public bool TitleBarsUseAccent { get; init; } + + public bool BordersUseAccent { get; init; } +} diff --git a/VibranceHud/Customize/TaskbarAlignment.cs b/VibranceHud/Customize/TaskbarAlignment.cs new file mode 100644 index 0000000..9f8daab --- /dev/null +++ b/VibranceHud/Customize/TaskbarAlignment.cs @@ -0,0 +1,7 @@ +namespace VibranceHud.Customize; + +public enum TaskbarAlignment +{ + Left, + Centre +} diff --git a/VibranceHud/Customize/TaskbarButtonGlom.cs b/VibranceHud/Customize/TaskbarButtonGlom.cs new file mode 100644 index 0000000..8ee9708 --- /dev/null +++ b/VibranceHud/Customize/TaskbarButtonGlom.cs @@ -0,0 +1,8 @@ +namespace VibranceHud.Customize; + +public enum TaskbarButtonGlom +{ + Combine, + Never, + Always +} diff --git a/VibranceHud/Customize/TaskbarSettings.cs b/VibranceHud/Customize/TaskbarSettings.cs new file mode 100644 index 0000000..d346153 --- /dev/null +++ b/VibranceHud/Customize/TaskbarSettings.cs @@ -0,0 +1,22 @@ +namespace VibranceHud.Customize; + +public sealed record TaskbarSettings +{ + public TaskbarStyle Style { get; init; } + + public uint ColorArgb { get; init; } + + public bool UseAccentForTaskbar { get; init; } + + public TaskbarButtonGlom Buttons { get; init; } + + public TaskbarAlignment Alignment { get; init; } = TaskbarAlignment.Centre; + + public bool SmallButtons { get; init; } + + public SearchBoxMode Search { get; init; } = SearchBoxMode.Box; + + public bool ShowTaskView { get; init; } = true; + + public bool ShowWidgets { get; init; } = true; +} diff --git a/VibranceHud/Customize/TaskbarStyle.cs b/VibranceHud/Customize/TaskbarStyle.cs new file mode 100644 index 0000000..f7614d8 --- /dev/null +++ b/VibranceHud/Customize/TaskbarStyle.cs @@ -0,0 +1,10 @@ +namespace VibranceHud.Customize; + +public enum TaskbarStyle +{ + Normal, + Acrylic, + Clear, + Blur, + Fluent +} diff --git a/VibranceHud/Customize/TaskbarStyleSupport.cs b/VibranceHud/Customize/TaskbarStyleSupport.cs new file mode 100644 index 0000000..bc8ac15 --- /dev/null +++ b/VibranceHud/Customize/TaskbarStyleSupport.cs @@ -0,0 +1,8 @@ +namespace VibranceHud.Customize; + +public enum TaskbarStyleSupport +{ + Working, + Unsupported, + Unknown +} diff --git a/VibranceHud/Customize/TextCheck.cs b/VibranceHud/Customize/TextCheck.cs new file mode 100644 index 0000000..c674a79 --- /dev/null +++ b/VibranceHud/Customize/TextCheck.cs @@ -0,0 +1,26 @@ +using System.Drawing; +using System.Globalization; +using VibranceHud.Design; +using VibranceHud.Theming; + +namespace VibranceHud.Customize; + +internal static class TextCheck +{ + internal static double Ratio() + { + if (!SlateSurface.Active) + { + return Readability.Contrast(Theme.TextFaint, Theme.Surface); + } + Color[] array = AppBackground.SampleBehind(AppBackground.WindowBoundsForSampling, SlateSurface.MatteBlur); + Color ground = ((array.Length != 0) ? Readability.BrightestFivePercent(array) : Theme.Background); + Color b = Readability.Over(SlateSurface.Base, SlateSurface.PanelAlpha, ground); + return Readability.Contrast(SignalTokens.Slate.Text3, b); + } + + internal static string Format(double ratio) + { + return ratio.ToString("0.0", CultureInfo.InvariantCulture) + " : 1"; + } +} diff --git a/VibranceHud/Customize/WindowSettings.cs b/VibranceHud/Customize/WindowSettings.cs new file mode 100644 index 0000000..1b1b3f5 --- /dev/null +++ b/VibranceHud/Customize/WindowSettings.cs @@ -0,0 +1,12 @@ +namespace VibranceHud.Customize; + +public sealed record WindowSettings +{ + public int CornerRadiusPx { get; init; } + + public bool SnapAssistSuggestions { get; init; } = true; + + public bool TransparencyEnabled { get; init; } = true; + + public StartLayoutMode StartLayout { get; init; } +} diff --git a/VibranceHud/Customize/WindowsRelease.cs b/VibranceHud/Customize/WindowsRelease.cs new file mode 100644 index 0000000..441426f --- /dev/null +++ b/VibranceHud/Customize/WindowsRelease.cs @@ -0,0 +1,50 @@ +using System; + +namespace VibranceHud.Customize; + +public static class WindowsRelease +{ + public const int FirstElevenBuild = 22000; + + public static bool IsElevenOrLater { get; } = IsElevenBuild(Environment.OSVersion.Version.Build); + + public static bool IsElevenBuild(int build) + { + return build >= 22000; + } + + public static bool IsSupported(CustomizeTweak tweak) + { + return IsSupported(tweak, IsElevenOrLater); + } + + public static bool IsSupported(CustomizeTweak tweak, bool elevenOrLater) + { + return UnsupportedReason(tweak, elevenOrLater) == null; + } + + public static string? UnsupportedReason(CustomizeTweak tweak) + { + return UnsupportedReason(tweak, IsElevenOrLater); + } + + public static string? UnsupportedReason(CustomizeTweak tweak, bool elevenOrLater) + { + switch (tweak) + { + case CustomizeTweak.TaskbarAlignment: + case CustomizeTweak.WidgetsButton: + case CustomizeTweak.StartLayout: + return elevenOrLater ? null : "Windows 11 only — your Windows 10 has no such setting."; + case CustomizeTweak.SmallTaskbarButtons: + return elevenOrLater ? "Windows 10 only — Windows 11 removed this setting." : null; + case CustomizeTweak.SearchBox: + case CustomizeTweak.TaskViewButton: + case CustomizeTweak.FileExtensions: + case CustomizeTweak.HiddenFiles: + return null; + default: + throw new ArgumentOutOfRangeException("tweak", tweak, "no support rule recorded for this tweak"); + } + } +} diff --git a/VibranceHud/DarkBoost/DarkBoostBanGate.cs b/VibranceHud/DarkBoost/DarkBoostBanGate.cs new file mode 100644 index 0000000..d7b05c6 --- /dev/null +++ b/VibranceHud/DarkBoost/DarkBoostBanGate.cs @@ -0,0 +1,60 @@ +using System; +using System.Windows.Forms; +using VibranceHud.Controls; + +namespace VibranceHud.DarkBoost; + +internal sealed class DarkBoostBanGate +{ + internal const string CardTitle = "Dark Boost can get you banned"; + + internal const string Body = "Some games, like Rust, ban players who see in the dark. It mostly happens when another player reports you. PlexusX never touches the game, but the ban risk is yours."; + + internal const string DialogTitle = "Before you turn on Dark Boost"; + + internal const string AcceptButton = "I understand the risk"; + + internal const string CancelButton = "Cancel"; + + private readonly AppSettings _settings; + + private readonly Action _save; + + private readonly Func? _ask; + + internal bool Accepted => _settings.DarkBoostBanRiskAccepted; + + internal DarkBoostBanGate(AppSettings settings, Action save, Func? ask = null) + { + _settings = settings ?? throw new ArgumentNullException("settings"); + _save = save ?? ((Action)(() => + { + })); + _ask = ask; + } + + internal bool Pass(IWin32Window? owner) + { + if (_settings.DarkBoostBanRiskAccepted) + { + return true; + } + if (!((_ask != null) ? _ask(owner) : AskWithDialog(owner))) + { + return false; + } + _settings.DarkBoostBanRiskAccepted = true; + _save(); + return true; + } + + internal static GlassDialog BuildDialog() + { + return new GlassDialog("Before you turn on Dark Boost", "Some games, like Rust, ban players who see in the dark. It mostly happens when another player reports you. PlexusX never touches the game, but the ban risk is yours.", GlassDialogButtons.ConfirmSafeEnter, GlassDialogTone.Warning, "I understand the risk", "Cancel"); + } + + internal static bool AskWithDialog(IWin32Window? owner) + { + return GlassDialog.Show(owner, "Before you turn on Dark Boost", "Some games, like Rust, ban players who see in the dark. It mostly happens when another player reports you. PlexusX never touches the game, but the ban risk is yours.", GlassDialogButtons.ConfirmSafeEnter, GlassDialogTone.Warning, "I understand the risk", "Cancel") == DialogResult.Yes; + } +} diff --git a/VibranceHud/DarkBoost/DarkBoostFade.cs b/VibranceHud/DarkBoost/DarkBoostFade.cs new file mode 100644 index 0000000..a4fde04 --- /dev/null +++ b/VibranceHud/DarkBoost/DarkBoostFade.cs @@ -0,0 +1,22 @@ +using System; + +namespace VibranceHud.DarkBoost; + +public static class DarkBoostFade +{ + public static readonly TimeSpan Duration = TimeSpan.FromMilliseconds(250.0); + + public static double Amount(double from, double to, TimeSpan elapsed, bool fade) + { + if (!fade || elapsed >= Duration) + { + return to; + } + if (elapsed <= TimeSpan.Zero) + { + return from; + } + double num = elapsed.TotalMilliseconds / Duration.TotalMilliseconds; + return from + (to - from) * num; + } +} diff --git a/VibranceHud/DarkBoost/DarkBoostLook.cs b/VibranceHud/DarkBoost/DarkBoostLook.cs new file mode 100644 index 0000000..4792b2e --- /dev/null +++ b/VibranceHud/DarkBoost/DarkBoostLook.cs @@ -0,0 +1,133 @@ +using System; + +namespace VibranceHud.DarkBoost; + +internal static class DarkBoostLook +{ + internal const double CleanShare = 0.85; + + internal static double FloorScale(int blackLevel) + { + return 1.0 + (double)(7 * Math.Clamp(blackLevel, 0, 100)) / 100.0; + } + + internal static int PeakColumn(float[] basis, out double columnSum) + { + int result = 0; + columnSum = double.MinValue; + for (int i = 0; i < 3; i++) + { + double num = basis[i] + basis[5 + i] + basis[10 + i]; + if (num > columnSum) + { + columnSum = num; + result = i; + } + } + return result; + } + + internal static float[] Base(float[] basis, DarkBoostTint tint, int blackLevel) + { + float[] array = (float[])basis.Clone(); + double num = FloorScale(blackLevel); + if (tint == DarkBoostTint.Green) + { + if (num != 1.0) + { + for (int i = 0; i < 3; i++) + { + array[20 + i] = (float)((double)basis[20 + i] * num); + } + } + return array; + } + int num2 = PeakColumn(basis, out var columnSum); + double[] array2 = DarkBoostTints.PreviewWeights(tint); + for (int j = 0; j < 3; j++) + { + for (int k = 0; k < 3; k++) + { + ref float reference = ref array[j * 5 + k]; + float num3; + if (array2 == null) + { + num3 = ((j == k) ? ((float)(columnSum * 0.85)) : 0f); + } + else + { + num3 = (float)((double)basis[j * 5 + num2] * array2[k]); + } + reference = num3; + } + } + for (int l = 0; l < 3; l++) + { + array[20 + l] = (float)((double)basis[20 + num2] * ((array2 == null) ? 0.85 : array2[l]) * num); + } + return array; + } + + internal static float[] Picture(float[] basis, DarkBoostTint tint, int blackLevel, double strength) + { + return DarkBoostPicture.Matrix(Base(basis, tint, blackLevel), strength); + } + + internal static float[] Lerp(float[] own, float[] boost, double strength) + { + double num = (double.IsFinite(strength) ? Math.Clamp(strength, 0.0, 1.0) : 1.0); + if (num <= 0.0) + { + return (float[])own.Clone(); + } + if (num >= 1.0) + { + return (float[])boost.Clone(); + } + float[] array = new float[own.Length]; + for (int i = 0; i < array.Length; i++) + { + array[i] = (float)((1.0 - num) * (double)own[i] + num * (double)boost[i]); + } + return array; + } + + internal static float[] Identity() + { + float[] array = new float[25]; + for (int i = 0; i < 5; i++) + { + array[i * 5 + i] = 1f; + } + return array; + } + + internal static (byte R, byte G, byte B) Pixel(double r, double g, double b, float[] m, ushort[]? ramp) + { + return (R: Ch(0), G: Ch(1), B: Ch(2)); + byte Ch(int c) + { + double num = r * (double)m[c] + g * (double)m[5 + c] + b * (double)m[10 + c] + (double)m[20 + c]; + int num2 = (int)Math.Clamp(Math.Round(255.0 * num, MidpointRounding.ToEven), 0.0, 255.0); + if (ramp != null) + { + num2 = (int)Math.Clamp(Math.Round((double)(int)ramp[c * 256 + num2] / 257.0, MidpointRounding.ToEven), 0.0, 255.0); + } + return (byte)num2; + } + } + + internal static double WhiteFrom(float[] m) + { + double num = 1.0; + for (int i = 0; i < 3; i++) + { + double num2 = m[i] + m[5 + i] + m[10 + i]; + if (num2 > 0.0) + { + num = Math.Min(num, (double)(1f - m[20 + i]) / num2); + } + } + return Math.Clamp(num, 0.0, 1.0); + } +} diff --git a/VibranceHud/DarkBoost/DarkBoostSetup.cs b/VibranceHud/DarkBoost/DarkBoostSetup.cs new file mode 100644 index 0000000..3afa5a1 --- /dev/null +++ b/VibranceHud/DarkBoost/DarkBoostSetup.cs @@ -0,0 +1,16 @@ +using System; + +namespace VibranceHud.DarkBoost; + +public sealed record DarkBoostSetup(string Name, DarkBoostTint Tint, int Strength, int BlackLevel) +{ + public DarkBoostSetup Clamped() + { + return this with + { + Name = (string.IsNullOrWhiteSpace(Name) ? "Setup" : Name.Trim()), + Strength = Math.Clamp(Strength, 0, 100), + BlackLevel = Math.Clamp(BlackLevel, 0, 100) + }; + } +} diff --git a/VibranceHud/DarkBoost/DarkBoostSetups.cs b/VibranceHud/DarkBoost/DarkBoostSetups.cs new file mode 100644 index 0000000..ffc5225 --- /dev/null +++ b/VibranceHud/DarkBoost/DarkBoostSetups.cs @@ -0,0 +1,83 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace VibranceHud.DarkBoost; + +public static class DarkBoostSetups +{ + public static DarkBoostSetup Default => new DarkBoostSetup("Setup 1", DarkBoostTint.Green, 100, 0); + + public static List Normalise(IEnumerable? saved) + { + List list = (from s in saved ?? Array.Empty() + where s != null + select s.Clamped()).ToList(); + if (list.Count == 0) + { + list.Add(Default); + } + return list; + } + + public static int Selected(int saved, int count) + { + if (count > 0) + { + return Math.Clamp(saved, 0, count - 1); + } + return 0; + } + + public static int Next(int selected, int count) + { + if (count > 0) + { + return (Selected(selected, count) + 1) % count; + } + return 0; + } + + public static DarkBoostSetup InUse(AppSettings settings) + { + List list = Normalise(settings.DarkBoostSetups); + return list[Selected(settings.DarkBoostSelected, list.Count)]; + } + + public static int AdvanceInSettings(AppSettings settings) + { + settings.DarkBoostSelected = Next(count: (settings.DarkBoostSetups = Normalise(settings.DarkBoostSetups)).Count, selected: settings.DarkBoostSelected); + return settings.DarkBoostSelected; + } + + public static bool CanDelete(int count) + { + return count > 1; + } + + public static int Delete(List setups, int selected) + { + if (!CanDelete(setups.Count)) + { + return Selected(selected, setups.Count); + } + int num = Selected(selected, setups.Count); + setups.RemoveAt(num); + return Math.Max(0, num - 1); + } + + public static int SaveNew(List setups, int selected) + { + DarkBoostSetup darkBoostSetup = ((setups.Count == 0) ? Default : setups[Selected(selected, setups.Count)]); + int n = setups.Count + 1; + while (setups.Any((DarkBoostSetup s) => string.Equals(s.Name, "Setup " + n, StringComparison.OrdinalIgnoreCase))) + { + n++; + } + setups.Add(darkBoostSetup with + { + Name = "Setup " + n + }); + return setups.Count - 1; + } +} diff --git a/VibranceHud/DarkBoost/DarkBoostTint.cs b/VibranceHud/DarkBoost/DarkBoostTint.cs new file mode 100644 index 0000000..7a66a91 --- /dev/null +++ b/VibranceHud/DarkBoost/DarkBoostTint.cs @@ -0,0 +1,10 @@ +namespace VibranceHud.DarkBoost; + +public enum DarkBoostTint +{ + Green, + Clean, + Amber, + Cyan, + White +} diff --git a/VibranceHud/DarkBoost/DarkBoostTints.cs b/VibranceHud/DarkBoost/DarkBoostTints.cs new file mode 100644 index 0000000..25039dd --- /dev/null +++ b/VibranceHud/DarkBoost/DarkBoostTints.cs @@ -0,0 +1,42 @@ +namespace VibranceHud.DarkBoost; + +public static class DarkBoostTints +{ + public static readonly DarkBoostTint[] All = new DarkBoostTint[5] + { + DarkBoostTint.Green, + DarkBoostTint.Clean, + DarkBoostTint.Amber, + DarkBoostTint.Cyan, + DarkBoostTint.White + }; + + public static string Name(DarkBoostTint t) + { + return t.ToString(); + } + + public static string Fact(DarkBoostTint t) + { + return t switch + { + DarkBoostTint.Green => "Green adds all colours together, so it pulls out the most detail.", + DarkBoostTint.Clean => "Clean keeps the game’s own colours. A little less detail than Green.", + DarkBoostTint.Amber => "Amber adds all colours together and makes the picture warm orange.", + DarkBoostTint.Cyan => "Cyan adds all colours together and makes the picture blue-green.", + _ => "White adds all colours together and makes the picture grey.", + }; + } + + public static double[]? PreviewWeights(DarkBoostTint t) + { + return t switch + { + DarkBoostTint.Green => new double[3] { 0.08, 1.0, 0.25 }, + DarkBoostTint.Amber => new double[3] { 1.0, 0.62, 0.12 }, + DarkBoostTint.Cyan => new double[3] { 0.12, 0.85, 1.0 }, + DarkBoostTint.White => new double[3] { 0.9, 0.9, 0.9 }, + _ => null, + }; + } +} diff --git a/VibranceHud/DarkBoostFollower.cs b/VibranceHud/DarkBoostFollower.cs new file mode 100644 index 0000000..ba17b39 --- /dev/null +++ b/VibranceHud/DarkBoostFollower.cs @@ -0,0 +1,50 @@ +using System; +using A; +using VibranceHud.Licensing; + +namespace VibranceHud; + +internal sealed class DarkBoostFollower +{ + private int _generation = ServedNightVision.Generation; + + internal bool Offered { get; private set; } = SafeAvailable(); + + internal bool Follow(VibranceEngine engine, bool wanted, Action unbindHotkey, Action bindHotkeyIfOffered) + { + int generation = ServedNightVision.Generation; + bool flag = SafeAvailable(); + if (generation == _generation && flag == Offered) + { + return false; + } + _generation = generation; + Offered = flag; + engine.NightVision = flag & wanted; + engine.NightVisionSourceChanged(); + unbindHotkey(); + if (flag) + { + bindHotkeyIfOffered(); + } + return true; + } + + internal void Settle() + { + _generation = ServedNightVision.Generation; + Offered = SafeAvailable(); + } + + private static bool SafeAvailable() + { + try + { + return global::A.A.Available; + } + catch + { + return false; + } + } +} diff --git a/VibranceHud/DarkBoostPicture.cs b/VibranceHud/DarkBoostPicture.cs new file mode 100644 index 0000000..5339fe2 --- /dev/null +++ b/VibranceHud/DarkBoostPicture.cs @@ -0,0 +1,239 @@ +using System; + +namespace VibranceHud; + +internal static class DarkBoostPicture +{ + internal const int MatrixEntries = 25; + + internal const int Levels = 256; + + internal const int RampEntries = 768; + + internal const int WindowsRampRange = 128; + + internal const int WhiteLevel = 200; + + private static readonly (int, int, int)[] Hues = new (int, int, int)[7] + { + (1, 1, 1), + (1, 0, 0), + (0, 1, 0), + (0, 0, 1), + (1, 1, 0), + (0, 1, 1), + (1, 0, 1) + }; + + internal static bool Structural(float[] m) + { + if (m == null || m.Length != 25) + { + return false; + } + for (int i = 0; i < m.Length; i++) + { + if (!float.IsFinite(m[i])) + { + return false; + } + } + if (m[3] != 0f || m[8] != 0f || m[13] != 0f || m[18] != 1f || m[23] != 0f) + { + return false; + } + if (m[15] != 0f || m[16] != 0f || m[17] != 0f || m[19] != 0f) + { + return false; + } + if (m[4] != 0f || m[9] != 0f || m[14] != 0f || m[24] != 1f) + { + return false; + } + if (m[20] > 0f || m[21] > 0f || m[22] > 0f) + { + return false; + } + return true; + } + + internal static bool Safe(ushort[] ramp) + { + if (ramp == null || ramp.Length != 768) + { + return false; + } + for (int i = 0; i < 3; i++) + { + int num = i * 256; + if (ramp[num + 256 - 1] != ushort.MaxValue) + { + return false; + } + for (int j = 0; j < 256; j++) + { + if (j > 0 && ramp[num + j] < ramp[num + j - 1]) + { + return false; + } + if (Math.Abs((ramp[num + j] >> 8) - j) > 128) + { + return false; + } + } + } + return true; + } + + internal static ushort[] Straight() + { + return GammaCurve.Identity(); + } + + internal static bool IsStraight(ushort[] ramp) + { + ushort[] array = Straight(); + if (ramp.Length != array.Length) + { + return false; + } + for (int i = 0; i < array.Length; i++) + { + if (ramp[i] != array[i]) + { + return false; + } + } + return true; + } + + internal static bool NeverWhiterThan(float[] matrix, ushort[] ramp, float[] reference) + { + ushort[] ramp2 = Straight(); + Span span = stackalloc byte[3]; + Span span2 = stackalloc byte[3]; + (int, int, int)[] hues = Hues; + for (int i = 0; i < hues.Length; i++) + { + (int, int, int) tuple = hues[i]; + int item = tuple.Item1; + int item2 = tuple.Item2; + int item3 = tuple.Item3; + for (int j = 0; j < 256; j++) + { + byte r = (byte)(item * j); + byte g = (byte)(item2 * j); + byte b = (byte)(item3 * j); + Pixel(r, g, b, matrix, ramp, span); + Pixel(r, g, b, reference, ramp2, span2); + bool flag = IsWhite(span); + bool flag2 = IsWhite(span2); + if (flag && !flag2) + { + return false; + } + if (IsCyan(span) && !flag2 && !IsCyan(span2)) + { + return false; + } + } + } + return true; + } + + internal static bool IsWhite(ReadOnlySpan p) + { + if (p[0] >= 200 && p[1] >= 200) + { + return p[2] >= 200; + } + return false; + } + + internal static bool IsCyan(ReadOnlySpan p) + { + if (p[1] >= 200 && p[2] >= 200) + { + return p[0] < 200; + } + return false; + } + + internal static float[] Matrix(float[] served, double strength) + { + double num = Math.Clamp(strength, 0.0, 1.0); + float[] array = (float[])served.Clone(); + if (num >= 1.0) + { + return array; + } + for (int i = 0; i < 25; i++) + { + array[i] = (float)(num * (double)served[i] + (1.0 - num) * (double)((i / 5 == i % 5) ? 1 : 0)); + } + return array; + } + + internal static ushort[] Ramp(ushort[] served, double strength) + { + double num = Math.Clamp(strength, 0.0, 1.0); + ushort[] array = (ushort[])served.Clone(); + if (num >= 1.0) + { + return array; + } + ushort[] array2 = Straight(); + for (int i = 0; i < 768; i++) + { + array[i] = (ushort)Math.Clamp(Math.Round(num * (double)(int)served[i] + (1.0 - num) * (double)(int)array2[i]), 0.0, 65535.0); + } + return array; + } + + internal static ushort[] ComposeAfter(ushort[] user, ushort[] boost) + { + ushort[] array = new ushort[768]; + for (int i = 0; i < 3; i++) + { + int num = i * 256; + for (int j = 0; j < 256; j++) + { + double num2 = (double)(int)user[num + j] * 255.0 / 65535.0; + int num3 = Math.Clamp((int)Math.Floor(num2), 0, 255); + int num4 = Math.Min(num3 + 1, 255); + double num5 = num2 - (double)num3; + array[num + j] = (ushort)Math.Clamp(Math.Round((double)(int)boost[num + num3] + (double)(boost[num + num4] - boost[num + num3]) * num5), 0.0, 65535.0); + } + } + return array; + } + + internal static void Pixel(byte r, byte g, byte b, float[] m, ushort[] ramp, Span outRgb) + { + double num = (double)(int)r / 255.0; + double num2 = (double)(int)g / 255.0; + double num3 = (double)(int)b / 255.0; + for (int i = 0; i < 3; i++) + { + int num4 = Q8(num * (double)m[i] + num2 * (double)m[5 + i] + num3 * (double)m[10 + i] + (double)m[20 + i]); + outRgb[i] = (byte)Q8((double)(int)ramp[i * 256 + num4] / 65535.0); + } + } + + internal static void Render(byte[] rgb, float[] m, ushort[] ramp) + { + Span outRgb = stackalloc byte[3]; + for (int i = 0; i + 2 < rgb.Length; i += 3) + { + Pixel(rgb[i], rgb[i + 1], rgb[i + 2], m, ramp, outRgb); + rgb[i] = outRgb[0]; + rgb[i + 1] = outRgb[1]; + rgb[i + 2] = outRgb[2]; + } + } + + private static int Q8(double v) + { + return (int)Math.Clamp(Math.Round(Math.Clamp(v, 0.0, 1.0) * 255.0), 0.0, 255.0); + } +} diff --git a/VibranceHud/DebouncedAction.cs b/VibranceHud/DebouncedAction.cs new file mode 100644 index 0000000..e1fa735 --- /dev/null +++ b/VibranceHud/DebouncedAction.cs @@ -0,0 +1,51 @@ +using System; +using System.Threading; + +namespace VibranceHud; + +public sealed class DebouncedAction : IDisposable +{ + private readonly Action _action; + + private readonly Timer _timer; + + public int DelayMs { get; } + + public DebouncedAction(Action action, int delayMs) + { + _action = action; + _timer = new Timer((object? _) => + { + Run(); + }, null, -1, -1); + DelayMs = delayMs; + } + + private void Run() + { + try + { + _action(); + } + catch (Exception ex) + { + try + { + CrashLog.Write(ex); + } + catch + { + } + } + } + + public void Trigger() + { + _timer.Change(DelayMs, -1); + } + + public void Dispose() + { + _timer.Dispose(); + } +} diff --git a/VibranceHud/Design/BackdropLook.cs b/VibranceHud/Design/BackdropLook.cs new file mode 100644 index 0000000..a8238ec --- /dev/null +++ b/VibranceHud/Design/BackdropLook.cs @@ -0,0 +1,8 @@ +namespace VibranceHud.Design; + +public enum BackdropLook +{ + Blossom, + Soft, + Off +} diff --git a/VibranceHud/Design/BackdropLooks.cs b/VibranceHud/Design/BackdropLooks.cs new file mode 100644 index 0000000..007642b --- /dev/null +++ b/VibranceHud/Design/BackdropLooks.cs @@ -0,0 +1,31 @@ +using System; + +namespace VibranceHud.Design; + +public static class BackdropLooks +{ + internal static Action? FailPointForTest { get; set; } + + public static string Name(BackdropLook look) + { + return look.ToString(); + } + + public static BackdropLook Parse(string? stored) + { + string text = (stored ?? "").Trim(); + if (text.Length == 0 || char.IsDigit(text[0]) || text[0] == '-') + { + return BackdropLook.Blossom; + } + if (text.Contains(',')) + { + return BackdropLook.Blossom; + } + if (!Enum.TryParse(text, ignoreCase: true, out var result) || !Enum.IsDefined(result)) + { + return BackdropLook.Blossom; + } + return result; + } +} diff --git a/VibranceHud/Design/BlossomBough.cs b/VibranceHud/Design/BlossomBough.cs new file mode 100644 index 0000000..f521d7b --- /dev/null +++ b/VibranceHud/Design/BlossomBough.cs @@ -0,0 +1,241 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.Runtime.InteropServices; +using VibranceHud.Theming; + +namespace VibranceHud.Design; + +public sealed class BlossomBough : IBackdrop +{ + private readonly record struct Depth(int Divisor, float Scale, int Alpha, int Clusters, int PerCluster, int Seed); + + private Bitmap? _cache; + + private string _cacheKey = ""; + + private int _w; + + private int _h; + + private static readonly Depth[] Layers = new Depth[3] + { + new Depth(10, 0.34f, 58, 17, 11, 11), + new Depth(6, 0.44f, 72, 14, 9, 29), + new Depth(4, 0.62f, 82, 10, 7, 47) + }; + + internal int CacheBuilds { get; private set; } + + public bool Moves => false; + + public void Resize(int w, int h) + { + _w = Math.Max(1, w); + _h = Math.Max(1, h); + } + + public void Update(double dtSeconds) + { + } + + public void Paint(Graphics g, int offsetX, int offsetY) + { + if (_w > 1 && _h > 1) + { + EnsureCache(); + if (_cache != null) + { + g.DrawImageUnscaled(_cache, -offsetX, -offsetY); + } + } + } + + private void EnsureCache() + { + string text = Theme.CurrentName + "|" + _w + "x" + _h + (AppBackground.IsSet ? "|img" : ""); + if (_cache != null && _cacheKey == text) + { + return; + } + _cache?.Dispose(); + _cache = null; + _cacheKey = text; + CacheBuilds++; + using Bitmap bitmap = new Bitmap(_w, _h); + using (Graphics graphics = Graphics.FromImage(bitmap)) + { + graphics.Clear(Color.Transparent); + graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; + graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; + int strength = ((!AppBackground.IsSet) ? 1 : 3); + Depth[] layers = Layers; + foreach (Depth depth in layers) + { + DrawLayer(graphics, depth, strength); + } + } + FadeDownward(bitmap); + _cache = Premultiplied(bitmap); + } + + private static Bitmap Premultiplied(Bitmap argb) + { + Bitmap bitmap = new Bitmap(argb.Width, argb.Height, PixelFormat.Format32bppPArgb); + using Graphics graphics = Graphics.FromImage(bitmap); + graphics.CompositingMode = CompositingMode.SourceCopy; + graphics.DrawImageUnscaled(argb, 0, 0); + return bitmap; + } + + private static void FadeDownward(Bitmap bmp) + { + Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); + BitmapData bitmapData = bmp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); + try + { + int stride = bitmapData.Stride; + byte[] array = new byte[stride]; + for (int i = 0; i < bmp.Height; i++) + { + float num = (float)i / (float)Math.Max(1, bmp.Height); + float num2; + if (num <= 0.14f) + { + num2 = 1f; + } + else + { + num2 = ((num >= 0.58f) ? 0f : (1f - (num - 0.14f) / 0.44f)); + } + if (!(num2 >= 0.999f)) + { + nint num3 = bitmapData.Scan0 + i * stride; + Marshal.Copy(num3, array, 0, stride); + for (int j = 3; j < stride; j += 4) + { + array[j] = (byte)((float)(int)array[j] * num2); + } + Marshal.Copy(array, 0, num3, stride); + } + } + } + finally + { + bmp.UnlockBits(bitmapData); + } + } + + private void DrawLayer(Graphics g, Depth depth, int strength) + { + int num = Math.Max(2, _w / depth.Divisor); + int num2 = Math.Max(2, _h / depth.Divisor); + using Bitmap image = new Bitmap(num, num2); + using (Graphics graphics = Graphics.FromImage(image)) + { + graphics.SmoothingMode = SmoothingMode.AntiAlias; + graphics.Clear(Color.Transparent); + PaintBough(graphics, num, num2, depth, strength); + } + using ImageAttributes imageAttributes = new ImageAttributes(); + imageAttributes.SetWrapMode(WrapMode.TileFlipXY); + g.DrawImage(image, new Rectangle(0, 0, _w, _h), 0, 0, num, num2, GraphicsUnit.Pixel, imageAttributes); + } + + private static void PaintBough(Graphics g, int w, int h, Depth depth, int strength) + { + Random random = new Random(depth.Seed); + Color petal = Color.FromArgb(depth.Alpha / strength, Theme.PlexusNodeA); + Color centre = Color.FromArgb(depth.Alpha / (strength * 2), Theme.PlexusNodeB); + Color color = Color.FromArgb(Math.Min(255, depth.Alpha + 78) / strength, Theme.PlexusLine); + PointF[][] array = new PointF[2][] + { + new PointF[4] + { + new PointF(-0.06f, 0.1f), + new PointF(0.28f, 0.3f), + new PointF(0.58f, 0.02f), + new PointF(1.06f, 0.22f) + }, + new PointF[4] + { + new PointF(0.1f, -0.05f), + new PointF(0.2f, 0.26f), + new PointF(0.16f, 0.52f), + new PointF(0.26f, 0.86f) + } + }; + float width = Math.Max(1.6f, (float)w * 0.02f * depth.Scale); + using (Pen pen = new Pen(color, width) + { + LineJoin = LineJoin.Round, + StartCap = LineCap.Round, + EndCap = LineCap.Round + }) + { + PointF[][] array2 = array; + foreach (PointF[] array3 in array2) + { + g.DrawBezier(pen, array3[0].X * (float)w, array3[0].Y * (float)h, array3[1].X * (float)w, array3[1].Y * (float)h, array3[2].X * (float)w, array3[2].Y * (float)h, array3[3].X * (float)w, array3[3].Y * (float)h); + } + } + PointF[] p = array[0]; + float num = Math.Max(2f, (float)w * 0.02f * depth.Scale); + for (int j = 0; j < depth.Clusters; j++) + { + float t = ((float)j + 0.5f) / (float)depth.Clusters; + PointF pointF = Bezier(p, t); + float num2 = pointF.X * (float)w + (float)(random.NextDouble() - 0.5) * (float)w * 0.06f; + float num3 = pointF.Y * (float)h + (float)(random.NextDouble() - 0.5) * (float)h * 0.1f; + for (int k = 0; k < depth.PerCluster; k++) + { + Flower(g, num2 + (float)(random.NextDouble() - 0.5) * num * 3.4f, num3 + (float)(random.NextDouble() - 0.5) * num * 3f, num * (0.7f + (float)random.NextDouble() * 0.6f), petal, centre, (float)random.NextDouble() * 72f); + } + } + for (int l = 0; l < Math.Max(2, depth.Clusters / 3); l++) + { + PointF pointF2 = Bezier(array[1], ((float)l + 1f) / ((float)depth.Clusters / 3f + 1f)); + for (int m = 0; m < depth.PerCluster - 1; m++) + { + Flower(g, pointF2.X * (float)w + (float)(random.NextDouble() - 0.5) * num * 3.2f, pointF2.Y * (float)h + (float)(random.NextDouble() - 0.5) * num * 2.8f, num * (0.6f + (float)random.NextDouble() * 0.5f), petal, centre, (float)random.NextDouble() * 72f); + } + } + } + + private static PointF Bezier(PointF[] p, float t) + { + float num = 1f - t; + float num2 = num * num * num; + float num3 = 3f * num * num * t; + float num4 = 3f * num * t * t; + float num5 = t * t * t; + return new PointF(num2 * p[0].X + num3 * p[1].X + num4 * p[2].X + num5 * p[3].X, num2 * p[0].Y + num3 * p[1].Y + num4 * p[2].Y + num5 * p[3].Y); + } + + private static void Flower(Graphics g, float cx, float cy, float r, Color petal, Color centre, float rotation) + { + if (r <= 0.4f) + { + return; + } + GraphicsState gstate = g.Save(); + g.TranslateTransform(cx, cy); + g.RotateTransform(rotation); + using (SolidBrush brush = new SolidBrush(petal)) + { + for (int i = 0; i < 5; i++) + { + GraphicsState gstate2 = g.Save(); + g.RotateTransform((float)i * 72f); + g.FillEllipse(brush, (0f - r) * 0.55f, (0f - r) * 1.02f, r * 1.1f, r * 0.9f); + g.Restore(gstate2); + } + } + using (SolidBrush brush2 = new SolidBrush(centre)) + { + g.FillEllipse(brush2, (0f - r) * 0.26f, (0f - r) * 0.26f, r * 0.52f, r * 0.52f); + } + g.Restore(gstate); + } +} diff --git a/VibranceHud/Design/Chrome.cs b/VibranceHud/Design/Chrome.cs new file mode 100644 index 0000000..f2a64bf --- /dev/null +++ b/VibranceHud/Design/Chrome.cs @@ -0,0 +1,7 @@ +namespace VibranceHud.Design; + +public enum Chrome +{ + Plexus, + Blossom +} diff --git a/VibranceHud/Design/Chromes.cs b/VibranceHud/Design/Chromes.cs new file mode 100644 index 0000000..0ca43d4 --- /dev/null +++ b/VibranceHud/Design/Chromes.cs @@ -0,0 +1,29 @@ +using System; + +namespace VibranceHud.Design; + +public static class Chromes +{ + public static string Name(Chrome chrome) + { + return chrome.ToString(); + } + + public static Chrome Parse(string? stored) + { + string text = (stored ?? "").Trim(); + if (text.Length == 0 || char.IsDigit(text[0]) || text[0] == '-') + { + return Chrome.Plexus; + } + if (text.Contains(',')) + { + return Chrome.Plexus; + } + if (!Enum.TryParse(text, ignoreCase: true, out var result) || !Enum.IsDefined(result)) + { + return Chrome.Plexus; + } + return result; + } +} diff --git a/VibranceHud/Design/FontRole.cs b/VibranceHud/Design/FontRole.cs new file mode 100644 index 0000000..7d89cd7 --- /dev/null +++ b/VibranceHud/Design/FontRole.cs @@ -0,0 +1,18 @@ +namespace VibranceHud.Design; + +public enum FontRole +{ + Value, + Display, + Title, + Heading, + HeadingRegular, + Body, + BodyBold, + Label, + LabelBold, + Caption, + CaptionBold, + Micro, + Mono +} diff --git a/VibranceHud/Design/Fonts.cs b/VibranceHud/Design/Fonts.cs new file mode 100644 index 0000000..bd03f25 --- /dev/null +++ b/VibranceHud/Design/Fonts.cs @@ -0,0 +1,197 @@ +using System; +using System.Drawing; + +namespace VibranceHud.Design; + +public static class Fonts +{ + private const string SemiboldFaceSuffix = " Semibold"; + + private static readonly Font?[] _cache = new Font[Enum.GetValues().Length]; + + private static string? _semiboldFamily; + + private static float _pointScale = 1f; + + private static string? _monoFamily; + + private static TypeStep CaptionStep => new TypeStep(12, 16, 400); + + private static TypeStep CaptionStrongStep => new TypeStep(12, 16, 600); + + private static TypeStep BodyStep => new TypeStep(14, 20, 400); + + private static TypeStep BodyStrongStep => new TypeStep(14, 20, 600); + + private static TypeStep SubtitleStep => new TypeStep(20, 28, 600); + + private static TypeStep TitleStep => new TypeStep(28, 36, 600); + + private static TypeStep ValueStep => new TypeStep(40, 48, 600); + + public static float PointScaleForOffscreenRenders + { + get + { + return _pointScale; + } + set + { + if (!(value >= 0.5f) || !(value <= 4f)) + { + throw new ArgumentOutOfRangeException("value", value, "a render scale outside 0.5 to 4 is a mistake, not a monitor"); + } + _pointScale = value; + } + } + + public static Font Value => Get(FontRole.Value); + + public static Font Display => Get(FontRole.Display); + + public static Font Title => Get(FontRole.Title); + + public static Font Heading => Get(FontRole.Heading); + + public static Font Body => Get(FontRole.Body); + + public static Font Label => Get(FontRole.Label); + + public static Font Caption => Get(FontRole.Caption); + + public static Font Micro => Get(FontRole.Micro); + + public static Font Mono => Get(FontRole.Mono); + + public static Font BodyBold => Get(FontRole.BodyBold); + + public static Font LabelBold => Get(FontRole.LabelBold); + + public static Font CaptionBold => Get(FontRole.CaptionBold); + + public static Font HeadingRegular => Get(FontRole.HeadingRegular); + + public static string MonoFamily => _monoFamily ?? (_monoFamily = ResolveFamilyOrGenericMono(SignalTokens.Root.FontMonoFamilies)); + + public static string SemiboldFamily => _semiboldFamily ?? (_semiboldFamily = SemiboldFamilyFor(Theme.FontFamily)); + + public static TypeStep Step(FontRole role) + { + return role switch + { + FontRole.Value => ValueStep, + FontRole.Display => TitleStep, + FontRole.Title => SubtitleStep, + FontRole.Heading => BodyStrongStep, + FontRole.HeadingRegular => BodyStep, + FontRole.Body => BodyStep, + FontRole.BodyBold => BodyStrongStep, + FontRole.Label => BodyStep, + FontRole.LabelBold => BodyStrongStep, + FontRole.Caption => CaptionStep, + FontRole.CaptionBold => CaptionStrongStep, + FontRole.Mono => BodyStep, + _ => CaptionStrongStep, + }; + } + + public static float PointsFor(FontRole role) + { + return (float)Step(role).SizePx * 72f / 96f * _pointScale; + } + + public static int LineHeight(FontRole role) + { + return Tokens.Scale(Step(role).LinePx); + } + + public static Font For(FontRole role) + { + return Get(role); + } + + public static Font Of(FontRole role, string family) + { + return Make(Step(role), family); + } + + private static Font Get(FontRole role) + { + ref Font reference = ref _cache[(int)role]; + return reference ?? (reference = Make(Step(role), (role == FontRole.Mono) ? MonoFamily : Theme.FontFamily)); + } + + private static Font Make(TypeStep step, string family) + { + float emSize = (float)step.SizePx * 72f / 96f * _pointScale; + if (step.Weight < 600) + { + return new Font(family, emSize, FontStyle.Regular); + } + string text = SemiboldFamilyFor(family); + if (!(text == family)) + { + return new Font(text, emSize, FontStyle.Regular); + } + return new Font(family, emSize, FontStyle.Bold); + } + + private static string ResolveFamilyOrGenericMono(string[] stack) + { + for (int num = stack.Length - 1; num >= 0; num--) + { + if (IsInstalled(stack[num])) + { + return stack[num]; + } + } + return FontFamily.GenericMonospace.Name; + } + + private static string SemiboldFamilyFor(string family) + { + string text = family + " Semibold"; + if (!IsInstalled(text)) + { + return family; + } + return text; + } + + public static string ResolveFamily(string? wanted) + { + if (string.IsNullOrWhiteSpace(wanted)) + { + return Theme.DefaultTypeface; + } + if (IsInstalled(wanted)) + { + return wanted; + } + if (IsInstalled(Theme.DefaultTypeface)) + { + return Theme.DefaultTypeface; + } + return FontFamily.GenericSansSerif.Name; + } + + private static bool IsInstalled(string family) + { + try + { + using FontFamily fontFamily = new FontFamily(family); + return string.Equals(fontFamily.Name, family, StringComparison.OrdinalIgnoreCase); + } + catch (ArgumentException) + { + return false; + } + } + + public static void Rebuild() + { + Array.Clear(_cache); + _semiboldFamily = null; + _monoFamily = null; + } +} diff --git a/VibranceHud/Design/HoverFade.cs b/VibranceHud/Design/HoverFade.cs new file mode 100644 index 0000000..d30e63d --- /dev/null +++ b/VibranceHud/Design/HoverFade.cs @@ -0,0 +1,161 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Windows.Forms; + +namespace VibranceHud.Design; + +public sealed class HoverFade +{ + private static class Ticker + { + private static readonly List Active = new List(); + + private static Timer? _timer; + + public static void Enrol(HoverFade fade) + { + if (!Active.Contains(fade)) + { + Active.Add(fade); + } + if (_timer == null) + { + _timer = new Timer + { + Interval = 16 + }; + _timer.Tick += (object? _, EventArgs _) => + { + Tick(); + }; + } + _timer.Start(); + } + + private static void Tick() + { + for (int num = Active.Count - 1; num >= 0; num--) + { + if (!Active[num].Step()) + { + Active.RemoveAt(num); + } + } + if (Active.Count == 0) + { + _timer?.Stop(); + } + } + } + + internal const int DurationMs = 83; + + private static readonly Stopwatch Clock = Stopwatch.StartNew(); + + internal static Func NowMs = () => Clock.Elapsed.TotalMilliseconds; + + internal static Func MotionAllowed = () => SystemInformation.UIEffectsEnabled; + + private readonly Control _owner; + + private float _value; + + private float _from; + + private float _target; + + private double _startMs; + + public float Value + { + get + { + if (_value == _target) + { + return _value; + } + double num = (NowMs() - _startMs) / 83.0; + if (num >= 1.0) + { + _value = _target; + return _value; + } + _value = _from + (_target - _from) * (float)StandardEase(num); + return _value; + } + } + + internal static double StandardEase(double x) + { + if (x <= 0.0) + { + return 0.0; + } + if (x >= 1.0) + { + return 1.0; + } + double num = 0.0; + double num2 = 1.0; + double num3 = x; + for (int i = 0; i < 40; i++) + { + num3 = (num + num2) / 2.0; + if (B(num3, 0.33, 0.67) < x) + { + num = num3; + } + else + { + num2 = num3; + } + } + return B(num3, 0.0, 1.0); + static double B(double t, double p1, double p2) + { + return 3.0 * (1.0 - t) * (1.0 - t) * t * p1 + 3.0 * (1.0 - t) * t * t * p2 + t * t * t; + } + } + + public HoverFade(Control owner) + { + _owner = owner; + } + + public void Set(bool hot) + { + float num = (hot ? 1f : 0f); + if (_target == num) + { + return; + } + if (!MotionAllowed()) + { + Snap(hot); + return; + } + _from = Value; + _startMs = NowMs(); + _target = num; + if (_value != _target) + { + Ticker.Enrol(this); + } + } + + public void Snap(bool hot) + { + _target = (_value = (_from = (hot ? 1f : 0f))); + } + + private bool Step() + { + if (_owner.IsDisposed) + { + return false; + } + _owner.Invalidate(); + return _value != _target; + } +} diff --git a/VibranceHud/Design/IBackdrop.cs b/VibranceHud/Design/IBackdrop.cs new file mode 100644 index 0000000..0159d47 --- /dev/null +++ b/VibranceHud/Design/IBackdrop.cs @@ -0,0 +1,14 @@ +using System.Drawing; + +namespace VibranceHud.Design; + +public interface IBackdrop +{ + bool Moves { get; } + + void Resize(int w, int h); + + void Update(double dtSeconds); + + void Paint(Graphics g, int offsetX, int offsetY); +} diff --git a/VibranceHud/Design/Metrics.cs b/VibranceHud/Design/Metrics.cs new file mode 100644 index 0000000..f2822eb --- /dev/null +++ b/VibranceHud/Design/Metrics.cs @@ -0,0 +1,8 @@ +namespace VibranceHud.Design; + +public static class Metrics +{ + public const int ButtonHeight = 32; + + public const int CompactButtonHeight = 28; +} diff --git a/VibranceHud/Design/OffBackdrop.cs b/VibranceHud/Design/OffBackdrop.cs new file mode 100644 index 0000000..a20ff7c --- /dev/null +++ b/VibranceHud/Design/OffBackdrop.cs @@ -0,0 +1,20 @@ +using System.Drawing; + +namespace VibranceHud.Design; + +public sealed class OffBackdrop : IBackdrop +{ + public bool Moves => false; + + public void Resize(int w, int h) + { + } + + public void Update(double dtSeconds) + { + } + + public void Paint(Graphics g, int offsetX, int offsetY) + { + } +} diff --git a/VibranceHud/Design/PaintGuard.cs b/VibranceHud/Design/PaintGuard.cs new file mode 100644 index 0000000..8b5ec08 --- /dev/null +++ b/VibranceHud/Design/PaintGuard.cs @@ -0,0 +1,50 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace VibranceHud.Design; + +internal static class PaintGuard +{ + private static readonly ConditionalWeakTable _logged = new ConditionalWeakTable(); + + private static readonly object _mark = new object(); + + private static readonly object _gate = new object(); + + internal static int LoggedForTest { get; private set; } + + public static bool IsGdiFailure(Exception ex) + { + if (!(ex is OutOfMemoryException) && !(ex is ExternalException) && !(ex is ArgumentException)) + { + return ex is InvalidOperationException; + } + return true; + } + + public static void Try(object surfaceKey, Action paint) + { + try + { + paint(); + } + catch (Exception ex) when (IsGdiFailure(ex)) + { + LogOnce(surfaceKey, ex); + } + } + + public static void LogOnce(object surfaceKey, Exception ex) + { + lock (_gate) + { + if (!_logged.TryAdd(surfaceKey, _mark)) + { + return; + } + LoggedForTest++; + } + CrashLog.Write(ex); + } +} diff --git a/VibranceHud/Design/Readability.cs b/VibranceHud/Design/Readability.cs new file mode 100644 index 0000000..bb7b8e0 --- /dev/null +++ b/VibranceHud/Design/Readability.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; +using System.Drawing; + +namespace VibranceHud.Design; + +public static class Readability +{ + public const double AA = 4.5; + + public const double BrightestFraction = 0.05; + + public static double RelativeLuminance(Color c) + { + return 0.2126 * Channel(c.R) + 0.7152 * Channel(c.G) + 0.0722 * Channel(c.B); + } + + private static double Channel(int v) + { + double num = (double)v / 255.0; + if (!(num <= 0.04045)) + { + return Math.Pow((num + 0.055) / 1.055, 2.4); + } + return num / 12.92; + } + + public static double Contrast(Color a, Color b) + { + double val = RelativeLuminance(a); + double val2 = RelativeLuminance(b); + double num = Math.Max(val, val2); + double num2 = Math.Min(val, val2); + return (num + 0.05) / (num2 + 0.05); + } + + public static Color Over(Color overlay, int alpha, Color ground) + { + int num = Math.Clamp(alpha, 0, 255); + return Color.FromArgb(255, ground.R + num * (overlay.R - ground.R) / 255, ground.G + num * (overlay.G - ground.G) / 255, ground.B + num * (overlay.B - ground.B) / 255); + } + + public static Color BrightestFivePercent(IReadOnlyList pixels) + { + if (pixels == null || pixels.Count == 0) + { + return Color.Black; + } + List<(double, Color)> list = new List<(double, Color)>(pixels.Count); + foreach (Color pixel in pixels) + { + list.Add((RelativeLuminance(pixel), pixel)); + } + list.Sort(((double L, Color C) x, (double L, Color C) y) => x.L.CompareTo(y.L)); + int value = (int)Math.Floor(0.95 * (double)(list.Count - 1)); + return list[Math.Clamp(value, 0, list.Count - 1)].Item2; + } +} diff --git a/VibranceHud/Design/SignalTokens.cs b/VibranceHud/Design/SignalTokens.cs new file mode 100644 index 0000000..fb4e7a8 --- /dev/null +++ b/VibranceHud/Design/SignalTokens.cs @@ -0,0 +1,418 @@ +using System.Drawing; + +namespace VibranceHud.Design; + +public static class SignalTokens +{ + public static class Root + { + public static readonly Color Signal1 = Color.FromArgb(255, 252, 71, 56); + + public static readonly Color Signal1Paper = Color.FromArgb(255, 200, 38, 26); + + public static readonly Color Signal2 = Color.FromArgb(255, 253, 147, 32); + + public static readonly Color Signal2Paper = Color.FromArgb(255, 184, 90, 0); + + public static readonly Color Signal3 = Color.FromArgb(255, 250, 223, 39); + + public static readonly Color Signal3Paper = Color.FromArgb(255, 138, 122, 0); + + public static readonly Color Signal4 = Color.FromArgb(255, 89, 222, 101); + + public static readonly Color Signal4Paper = Color.FromArgb(255, 30, 138, 58); + + public static readonly Color Signal5 = Color.FromArgb(255, 54, 220, 236); + + public static readonly Color Signal5Paper = Color.FromArgb(255, 0, 127, 140); + + public static readonly Color Signal6 = Color.FromArgb(255, 55, 137, 253); + + public static readonly Color Signal6Paper = Color.FromArgb(255, 31, 99, 214); + + public static readonly Color SignalStart = Color.FromArgb(255, 255, 255, 255); + + public static readonly Color SuccessPaper = Color.FromArgb(255, 5, 119, 59); + + public static readonly Color WarningPaper = Color.FromArgb(255, 159, 92, 12); + + public static readonly Color DangerPaper = Color.FromArgb(255, 197, 44, 42); + + public static readonly Color InfoPaper = Color.FromArgb(255, 13, 106, 187); + + public static readonly Color XBefore = Color.FromArgb(255, 255, 59, 48); + + public static readonly Color XAfter = Color.FromArgb(255, 34, 197, 94); + + public static readonly Color XHook = Color.FromArgb(255, 255, 230, 0); + + public static readonly Color XDiscord = Color.FromArgb(255, 88, 101, 242); + + public static readonly Color PPaper = Color.FromArgb(255, 255, 255, 255); + + public static readonly Color PPaper2 = Color.FromArgb(255, 243, 243, 243); + + public static readonly Color PPaperRule = Color.FromArgb(255, 222, 222, 222); + + public static readonly Color PInk = Color.FromArgb(255, 17, 17, 20); + + public static readonly Color PInk2 = Color.FromArgb(255, 85, 85, 85); + + public static readonly Color PInk3 = Color.FromArgb(255, 108, 108, 108); + + public static readonly Color BrandGround = Color.FromArgb(255, 21, 21, 21); + + public static readonly Color BrandInk = Color.FromArgb(255, 255, 255, 255); + + public const string GlassFill = "color-mix(in srgb, #151515 58%, transparent)"; + + public const string GlassFillFallback = "color-mix(in srgb, #151515 94%, transparent)"; + + public const int GlassBlur = 22; + + public static readonly Color GlassHairline = Color.FromArgb(20, 255, 255, 255); + + public const string FontDisplayStack = "\"Sofia Sans Extra Condensed\", \"Arial Narrow\", sans-serif"; + + public static readonly string[] FontDisplayFamilies = new string[2] { "Sofia Sans Extra Condensed", "Arial Narrow" }; + + public const string FontTextStack = "\"Host Grotesk\", \"Segoe UI\", system-ui, sans-serif"; + + public static readonly string[] FontTextFamilies = new string[2] { "Host Grotesk", "Segoe UI" }; + + public const string FontUiStack = "\"Segoe UI Variable Text\", \"Segoe UI\", system-ui, sans-serif"; + + public static readonly string[] FontUiFamilies = new string[2] { "Segoe UI Variable Text", "Segoe UI" }; + + public const string FontMonoStack = "\"Cascadia Mono\", Consolas, ui-monospace, monospace"; + + public static readonly string[] FontMonoFamilies = new string[2] { "Cascadia Mono", "Consolas" }; + + public const int AppCaptionWeight = 400; + + public const int AppCaptionSizePx = 12; + + public const int AppCaptionLinePx = 16; + + public const int AppCaptionStrongWeight = 600; + + public const int AppCaptionStrongSizePx = 12; + + public const int AppCaptionStrongLinePx = 16; + + public const int AppBodyWeight = 400; + + public const int AppBodySizePx = 14; + + public const int AppBodyLinePx = 20; + + public const int AppBodyStrongWeight = 600; + + public const int AppBodyStrongSizePx = 14; + + public const int AppBodyStrongLinePx = 20; + + public const int AppSubtitleWeight = 600; + + public const int AppSubtitleSizePx = 20; + + public const int AppSubtitleLinePx = 28; + + public const int AppTitleWeight = 600; + + public const int AppTitleSizePx = 28; + + public const int AppTitleLinePx = 36; + + public const int AppValueWeight = 600; + + public const int AppValueSizePx = 40; + + public const int AppValueLinePx = 48; + + public const string WebDisplayXl = "800 144px/0.88 \"Sofia Sans Extra Condensed\", \"Arial Narrow\", sans-serif"; + + public const string WebDisplayL = "800 88px/0.9 \"Sofia Sans Extra Condensed\", \"Arial Narrow\", sans-serif"; + + public const string WebDisplayM = "800 48px/0.95 \"Sofia Sans Extra Condensed\", \"Arial Narrow\", sans-serif"; + + public const string WebHeading = "600 28px/1.2 \"Host Grotesk\", \"Segoe UI\", system-ui, sans-serif"; + + public const string WebSubheading = "600 20px/1.3 \"Host Grotesk\", \"Segoe UI\", system-ui, sans-serif"; + + public const string WebMenu = "500 18px/1.3 \"Host Grotesk\", \"Segoe UI\", system-ui, sans-serif"; + + public const string WebBodyL = "400 18px/1.55 \"Host Grotesk\", \"Segoe UI\", system-ui, sans-serif"; + + public const string WebBody = "400 16px/1.55 \"Host Grotesk\", \"Segoe UI\", system-ui, sans-serif"; + + public const string WebSmall = "400 14px/1.45 \"Host Grotesk\", \"Segoe UI\", system-ui, sans-serif"; + + public const string WebLabelL = "500 14px/1.3 \"Host Grotesk\", \"Segoe UI\", system-ui, sans-serif"; + + public const string WebLabel = "500 13px/1.3 \"Host Grotesk\", \"Segoe UI\", system-ui, sans-serif"; + + public const string WebCode = "400 13px/1.5 \"Cascadia Mono\", Consolas, ui-monospace, monospace"; + + public const string TrackDisplay = "-0.01em"; + + public const string TrackWordmark = "-0.012em"; + + public const int Space0 = 0; + + public const int Space1 = 2; + + public const int Space2 = 4; + + public const int Space3 = 8; + + public const int Space4 = 12; + + public const int Space5 = 16; + + public const int Space6 = 20; + + public const int Space7 = 24; + + public const int Space8 = 32; + + public const int Space9 = 40; + + public const int Space10 = 48; + + public const int Space11 = 64; + + public const int Space12 = 80; + + public const int Space13 = 96; + + public const int Space14 = 128; + + public const int Radius0 = 0; + + public const int Radius4 = 4; + + public const int Radius8 = 8; + + public const int RadiusPill = 999; + + public const int StrokeHairline = 1; + + public const float StrokeIcon = 1.5f; + + public const int StrokeFocus = 2; + + public const int FocusGap = 2; + + public const int SignalStrand = 1; + + public const int DurInstantMs = 0; + + public const int DurFadeMs = 83; + + public const int DurMoveMs = 167; + + public const int DurSplashMs = 900; + + public const string EaseStandard = "cubic-bezier(0.33, 0, 0.67, 1)"; + + public const string EaseEnter = "cubic-bezier(0, 0, 0, 1)"; + } + + public static class Ash + { + public static readonly Color Bg = Color.FromArgb(255, 21, 21, 21); + + public static readonly Color Surface1 = Color.FromArgb(255, 28, 28, 28); + + public static readonly Color Surface2 = Color.FromArgb(255, 35, 35, 35); + + public static readonly Color Surface3 = Color.FromArgb(255, 42, 42, 42); + + public static readonly Color Hover = Color.FromArgb(255, 49, 49, 49); + + public static readonly Color Pressed = Color.FromArgb(255, 57, 57, 57); + + public static readonly Color Border = Color.FromArgb(255, 51, 51, 51); + + public static readonly Color WindowEdge = Color.FromArgb(255, 69, 69, 69); + + public static readonly Color Text1 = Color.FromArgb(255, 243, 243, 243); + + public static readonly Color Text2 = Color.FromArgb(255, 193, 193, 193); + + public static readonly Color TextDisabled = Color.FromArgb(255, 88, 88, 88); + + public static readonly Color Track = Color.FromArgb(255, 61, 61, 61); + + public static readonly Color Accent = Color.FromArgb(255, 255, 255, 255); + + public static readonly Color AccentHover = Color.FromArgb(255, 222, 222, 222); + + public static readonly Color AccentPressed = Color.FromArgb(255, 196, 196, 196); + + public static readonly Color OnAccent = Color.FromArgb(255, 21, 21, 21); + + public static readonly Color Focus = Color.FromArgb(255, 255, 255, 255); + + public static readonly Color PreviewWell = Color.FromArgb(255, 28, 28, 28); + + public static readonly Color Text3 = Color.FromArgb(255, 153, 153, 153); + + public static readonly Color BorderStrong = Color.FromArgb(255, 116, 116, 116); + + public static readonly Color Success = Color.FromArgb(255, 94, 206, 131); + + public static readonly Color Warning = Color.FromArgb(255, 233, 175, 45); + + public static readonly Color Danger = Color.FromArgb(255, 255, 158, 147); + + public static readonly Color Info = Color.FromArgb(255, 127, 190, 243); + + public static readonly Color Chrome = Color.FromArgb(255, 21, 21, 21); + + public static readonly Color Overlay = Color.FromArgb(255, 42, 42, 42); + + public static readonly Color KnobRing = Color.FromArgb(255, 28, 28, 28); + + public static readonly Color SelectedSuffix = Color.FromArgb(255, 85, 85, 85); + + public static readonly Color TextOnFill = Color.FromArgb(255, 193, 193, 193); + + public static readonly Color FieldFill = Color.FromArgb(0, 0, 0, 0); + + public static readonly Color Selection = Color.FromArgb(255, 255, 255, 255); + + public static readonly Color SignalTrack = Color.FromArgb(255, 61, 61, 61); + } + + public static class Slate + { + public const double GuiOpacity = 0.66; + + public static readonly Color SlateBase = Color.FromArgb(255, 15, 18, 22); + + public static readonly Color Bg = Color.FromArgb(255, 15, 18, 22); + + public static readonly Color ChromeDefault = Color.FromArgb(189, 15, 18, 22); + + public static readonly Color Surface1Default = Color.FromArgb(168, 15, 18, 22); + + public static readonly Color Surface2 = Color.FromArgb(18, 255, 255, 255); + + public static readonly Color Surface3 = Color.FromArgb(242, 15, 18, 22); + + public static readonly Color Overlay = Color.FromArgb(242, 15, 18, 22); + + public static readonly Color Hover = Color.FromArgb(26, 255, 255, 255); + + public static readonly Color Pressed = Color.FromArgb(36, 255, 255, 255); + + public static readonly Color Border = Color.FromArgb(20, 255, 255, 255); + + public static readonly Color BorderStrong = Color.FromArgb(128, 255, 255, 255); + + public static readonly Color WindowEdge = Color.FromArgb(36, 255, 255, 255); + + public static readonly Color Track = Color.FromArgb(56, 255, 255, 255); + + public static readonly Color Text1 = Color.FromArgb(255, 243, 245, 248); + + public static readonly Color Text2 = Color.FromArgb(255, 210, 214, 220); + + public static readonly Color Text3 = Color.FromArgb(255, 195, 200, 207); + + public static readonly Color TextDisabled = Color.FromArgb(97, 255, 255, 255); + + public static readonly Color TextOnFill = Color.FromArgb(255, 243, 245, 248); + + public static readonly Color Accent = Color.FromArgb(255, 255, 255, 255); + + public static readonly Color AccentHover = Color.FromArgb(255, 222, 222, 222); + + public static readonly Color AccentPressed = Color.FromArgb(255, 196, 196, 196); + + public static readonly Color OnAccent = Color.FromArgb(255, 21, 21, 21); + + public static readonly Color Focus = Color.FromArgb(255, 255, 255, 255); + + public static readonly Color PreviewWell = Color.FromArgb(255, 28, 28, 28); + + public static readonly Color Success = Color.FromArgb(255, 94, 206, 131); + + public static readonly Color Warning = Color.FromArgb(255, 233, 175, 45); + + public static readonly Color Danger = Color.FromArgb(255, 255, 158, 147); + + public static readonly Color Info = Color.FromArgb(255, 127, 190, 243); + + public static readonly Color KnobRing = Color.FromArgb(255, 15, 18, 22); + + public static readonly Color FieldFill = Color.FromArgb(255, 15, 18, 22); + + public static readonly Color SelectedSuffix = Color.FromArgb(255, 85, 85, 85); + + public static readonly Color Selection = Color.FromArgb(255, 255, 255, 255); + + public static readonly Color SignalTrack = Color.FromArgb(56, 255, 255, 255); + + public const int MatteBlur = 16; + + public const int Gutter = 16; + } + + public static class Paper + { + public static readonly Color Bg = Color.FromArgb(255, 255, 255, 255); + + public static readonly Color Surface1 = Color.FromArgb(255, 243, 243, 243); + + public static readonly Color Surface2 = Color.FromArgb(255, 243, 243, 243); + + public static readonly Color Surface3 = Color.FromArgb(255, 255, 255, 255); + + public static readonly Color Border = Color.FromArgb(255, 222, 222, 222); + + public static readonly Color BorderStrong = Color.FromArgb(255, 128, 128, 128); + + public static readonly Color Text1 = Color.FromArgb(255, 17, 17, 20); + + public static readonly Color Text2 = Color.FromArgb(255, 85, 85, 85); + + public static readonly Color Text3 = Color.FromArgb(255, 108, 108, 108); + + public static readonly Color Accent = Color.FromArgb(255, 17, 17, 20); + + public static readonly Color OnAccent = Color.FromArgb(255, 255, 255, 255); + + public static readonly Color Focus = Color.FromArgb(255, 17, 17, 20); + + public static readonly Color PreviewWell = Color.FromArgb(255, 243, 243, 243); + + public static readonly Color Success = Color.FromArgb(255, 5, 119, 59); + + public static readonly Color Warning = Color.FromArgb(255, 159, 92, 12); + + public static readonly Color Danger = Color.FromArgb(255, 197, 44, 42); + + public static readonly Color Info = Color.FromArgb(255, 13, 106, 187); + + public static readonly Color Signal1 = Color.FromArgb(255, 200, 38, 26); + + public static readonly Color Signal2 = Color.FromArgb(255, 184, 90, 0); + + public static readonly Color Signal3 = Color.FromArgb(255, 138, 122, 0); + + public static readonly Color Signal4 = Color.FromArgb(255, 30, 138, 58); + + public static readonly Color Signal5 = Color.FromArgb(255, 0, 127, 140); + + public static readonly Color Signal6 = Color.FromArgb(255, 31, 99, 214); + + public static readonly Color SignalStart = Color.FromArgb(255, 17, 17, 20); + } + + public const string SourceFile = "Design/tokens/tokens.css"; + + public const string SourceSha256 = "77EEB2F61406247D6315CE64314C7CA56409F413EDF19BC5F921C7FE5F1813D3"; +} diff --git a/VibranceHud/Design/SignatureLook.cs b/VibranceHud/Design/SignatureLook.cs new file mode 100644 index 0000000..71a46b7 --- /dev/null +++ b/VibranceHud/Design/SignatureLook.cs @@ -0,0 +1,3 @@ +namespace VibranceHud.Design; + +public readonly record struct SignatureLook(string Theme, BackdropLook Backdrop, SurfaceStyle Surface, Chrome Chrome = Chrome.Plexus); diff --git a/VibranceHud/Design/SignatureLooks.cs b/VibranceHud/Design/SignatureLooks.cs new file mode 100644 index 0000000..2b02e88 --- /dev/null +++ b/VibranceHud/Design/SignatureLooks.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; + +namespace VibranceHud.Design; + +public static class SignatureLooks +{ + public static readonly IReadOnlyList All = new SignatureLook[2] + { + new SignatureLook("Ash", BackdropLook.Off, SurfaceStyle.Glass), + new SignatureLook("Slate", BackdropLook.Off, SurfaceStyle.Glass) + }; + + public static bool TryGet(string? theme, out SignatureLook look) + { + foreach (SignatureLook item in All) + { + if (string.Equals(item.Theme, theme, StringComparison.OrdinalIgnoreCase)) + { + look = item; + return true; + } + } + look = default; + return false; + } +} diff --git a/VibranceHud/Design/SlateSurface.cs b/VibranceHud/Design/SlateSurface.cs new file mode 100644 index 0000000..55f223b --- /dev/null +++ b/VibranceHud/Design/SlateSurface.cs @@ -0,0 +1,54 @@ +using System; +using System.Drawing; + +namespace VibranceHud.Design; + +public static class SlateSurface +{ + public const double MinOpacity = 0.45; + + public const double MaxOpacity = 0.85; + + public const double ChromeCeiling = 0.95; + + public const double ChromeBoost = 0.08; + + private static double _userOpacity = 0.66; + + public static double UserOpacity + { + get + { + return _userOpacity; + } + set + { + _userOpacity = Math.Clamp(value, 0.45, 0.85); + } + } + + public static bool MatteBlur { get; set; } = true; + + public static bool Active => Theme.IsSeeThrough; + + public static Color Base => SignalTokens.Slate.SlateBase; + + public static double PanelOpacity => Math.Clamp(_userOpacity, 0.45, 0.85); + + public static double ChromeOpacity => Math.Min(0.95, PanelOpacity + 0.08); + + public static int PanelAlpha => Alpha(PanelOpacity); + + public static int ChromeAlpha => Alpha(ChromeOpacity); + + internal static int Alpha(double opacity) + { + return (int)Math.Round(Math.Clamp(opacity, 0.0, 1.0) * 255.0); + } + + internal static void ResetForTests() + { + _userOpacity = 0.66; + MatteBlur = true; + } +} diff --git a/VibranceHud/Design/SoftBackdrop.cs b/VibranceHud/Design/SoftBackdrop.cs new file mode 100644 index 0000000..e34cc6d --- /dev/null +++ b/VibranceHud/Design/SoftBackdrop.cs @@ -0,0 +1,142 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using VibranceHud.Theming; + +namespace VibranceHud.Design; + +public sealed class SoftBackdrop : IBackdrop +{ + private int _w; + + private int _h; + + private const int MostLayers = 4; + + private readonly List<(string Key, Bitmap Layer)> _layers = new List<(string, Bitmap)>(); + + private readonly HashSet _failedKeys = new HashSet(); + + internal int LayerBuilds { get; private set; } + + internal int PoolDrawsForTest { get; private set; } + + internal int LayersHeldForTest => _layers.Count; + + public bool Moves => false; + + public void Resize(int w, int h) + { + if (w != _w || h != _h) + { + foreach (var layer in _layers) + { + layer.Layer.Dispose(); + } + _layers.Clear(); + _failedKeys.Clear(); + } + _w = w; + _h = h; + } + + public void Update(double dtSeconds) + { + } + + public void Paint(Graphics g, int offsetX, int offsetY) + { + if (_w > 0 && _h > 0) + { + Bitmap bitmap = LayerFor(offsetX, offsetY, null); + if (bitmap != null) + { + g.DrawImageUnscaled(bitmap, 0, 0); + } + } + } + + internal void PaintOver(BlossomBough under, Graphics g, int offsetX, int offsetY) + { + if (_w <= 0 || _h <= 0) + { + under.Paint(g, offsetX, offsetY); + return; + } + Bitmap bitmap = LayerFor(offsetX, offsetY, under); + if (bitmap != null) + { + g.DrawImageUnscaled(bitmap, 0, 0); + } + } + + private Bitmap? LayerFor(int offsetX, int offsetY, BlossomBough? under) + { + string text = Theme.CurrentName + "|" + _w + "x" + _h + "|" + offsetX + "," + offsetY + ((under == null) ? "" : (AppBackground.IsSet ? "|tree|img" : "|tree")); + for (int i = 0; i < _layers.Count; i++) + { + if (_layers[i].Key == text) + { + return _layers[i].Layer; + } + } + if (_failedKeys.Contains(text)) + { + return null; + } + if (_layers.Count >= 4) + { + _layers[0].Layer.Dispose(); + _layers.RemoveAt(0); + } + Bitmap bitmap = null; + try + { + BackdropLooks.FailPointForTest?.Invoke("build"); + bitmap = new Bitmap(_w, _h, PixelFormat.Format32bppPArgb); + using Graphics graphics = Graphics.FromImage(bitmap); + graphics.Clear(Color.Transparent); + under?.Paint(graphics, offsetX, offsetY); + DrawPools(graphics, offsetX, offsetY); + } + catch (Exception ex) when (PaintGuard.IsGdiFailure(ex)) + { + bitmap?.Dispose(); + if (_failedKeys.Count >= 16) + { + _failedKeys.Clear(); + } + _failedKeys.Add(text); + PaintGuard.LogOnce(this, ex); + return null; + } + LayerBuilds++; + _layers.Add((text, bitmap)); + return bitmap; + } + + private void DrawPools(Graphics g, int offsetX, int offsetY) + { + PoolDrawsForTest++; + Pool(g, Theme.PlexusNodeA, offsetX + (int)((float)_w * 0.22f), offsetY + (int)((float)_h * 0.18f), (int)((float)Math.Max(_w, _h) * 0.55f)); + Pool(g, Theme.PlexusNodeB, offsetX + (int)((float)_w * 0.8f), offsetY + (int)((float)_h * 0.72f), (int)((float)Math.Max(_w, _h) * 0.45f)); + } + + private static void Pool(Graphics g, Color colour, int cx, int cy, int radius) + { + if (radius <= 0) + { + return; + } + Rectangle rect = new Rectangle(cx - radius, cy - radius, radius * 2, radius * 2); + using GraphicsPath graphicsPath = new GraphicsPath(); + graphicsPath.AddEllipse(rect); + PathGradientBrush pathGradientBrush = new PathGradientBrush(graphicsPath); + pathGradientBrush.CenterColor = Color.FromArgb(46, colour); + pathGradientBrush.SurroundColors = new Color[1] { Color.FromArgb(0, colour) }; + using PathGradientBrush brush = pathGradientBrush; + g.FillEllipse(brush, rect); + } +} diff --git a/VibranceHud/Design/SurfaceStyle.cs b/VibranceHud/Design/SurfaceStyle.cs new file mode 100644 index 0000000..5f6aac6 --- /dev/null +++ b/VibranceHud/Design/SurfaceStyle.cs @@ -0,0 +1,7 @@ +namespace VibranceHud.Design; + +public enum SurfaceStyle +{ + Glass, + Flat +} diff --git a/VibranceHud/Design/SurfaceStyles.cs b/VibranceHud/Design/SurfaceStyles.cs new file mode 100644 index 0000000..f8c364e --- /dev/null +++ b/VibranceHud/Design/SurfaceStyles.cs @@ -0,0 +1,29 @@ +using System; + +namespace VibranceHud.Design; + +public static class SurfaceStyles +{ + public static string Name(SurfaceStyle style) + { + return style.ToString(); + } + + public static SurfaceStyle Parse(string? stored) + { + string text = (stored ?? "").Trim(); + if (text.Length == 0 || char.IsDigit(text[0]) || text[0] == '-') + { + return SurfaceStyle.Glass; + } + if (text.Contains(',')) + { + return SurfaceStyle.Glass; + } + if (!Enum.TryParse(text, ignoreCase: true, out var result) || !Enum.IsDefined(result)) + { + return SurfaceStyle.Glass; + } + return result; + } +} diff --git a/VibranceHud/Design/SwitchableBackdrop.cs b/VibranceHud/Design/SwitchableBackdrop.cs new file mode 100644 index 0000000..bc57c58 --- /dev/null +++ b/VibranceHud/Design/SwitchableBackdrop.cs @@ -0,0 +1,81 @@ +using System.Drawing; + +namespace VibranceHud.Design; + +public sealed class SwitchableBackdrop : IBackdrop +{ + private readonly BlossomBough _bough = new BlossomBough(); + + private IBackdrop? _layer; + + private SoftBackdrop? _soft; + + private bool _boughShows = true; + + private int _w; + + private int _h; + + public BackdropLook Look { get; private set; } + + public bool Moves + { + get + { + if (!_boughShows || !_bough.Moves) + { + return _layer?.Moves ?? false; + } + return true; + } + } + + internal SoftBackdrop? SoftForTest => _layer as SoftBackdrop; + + public void Use(BackdropLook look) + { + if (look != Look) + { + Look = look; + _boughShows = look != BackdropLook.Off; + SoftBackdrop layer = ((look != BackdropLook.Soft) ? null : (_soft ?? (_soft = new SoftBackdrop()))); + _layer = layer; + if (_w > 0 && _h > 0) + { + _layer?.Resize(_w, _h); + } + } + } + + public void Resize(int w, int h) + { + _w = w; + _h = h; + _bough.Resize(w, h); + _soft?.Resize(w, h); + if (_layer != _soft) + { + _layer?.Resize(w, h); + } + } + + public void Update(double dtSeconds) + { + _bough.Update(dtSeconds); + _layer?.Update(dtSeconds); + } + + public void Paint(Graphics g, int offsetX, int offsetY) + { + if (_boughShows && _layer is SoftBackdrop softBackdrop) + { + softBackdrop.PaintOver(_bough, g, offsetX, offsetY); + return; + } + if (_boughShows) + { + _bough.Paint(g, offsetX, offsetY); + } + _layer?.Paint(g, offsetX, offsetY); + } +} diff --git a/VibranceHud/Design/Tokens.cs b/VibranceHud/Design/Tokens.cs new file mode 100644 index 0000000..c95c19a --- /dev/null +++ b/VibranceHud/Design/Tokens.cs @@ -0,0 +1,58 @@ +using System; + +namespace VibranceHud.Design; + +public static class Tokens +{ + public const int BaseDpi = 96; + + public const int XXS = 2; + + public const int XS = 4; + + public const int S = 8; + + public const int M = 12; + + public const int L = 16; + + public const int L2 = 20; + + public const int XL = 24; + + public const int XXL = 32; + + public const int XXXXL = 40; + + public const int XXXL = 48; + + public static int Dpi { get; set; } = 96; + + public static int Scale(int logical) + { + return ScaleAt(Dpi, logical); + } + + public static int ScaleAt(int dpi, int logical) + { + if (logical == 0) + { + return 0; + } + if (dpi <= 0) + { + dpi = 96; + } + int val = (int)Math.Round((double)logical * ((double)dpi / 96.0), MidpointRounding.AwayFromZero); + if (logical <= 0) + { + return Math.Min(-1, val); + } + return Math.Max(1, val); + } + + public static float ScaleF(float logical) + { + return logical * ((float)Dpi / 96f); + } +} diff --git a/VibranceHud/Design/TypeStep.cs b/VibranceHud/Design/TypeStep.cs new file mode 100644 index 0000000..b27ef06 --- /dev/null +++ b/VibranceHud/Design/TypeStep.cs @@ -0,0 +1,3 @@ +namespace VibranceHud.Design; + +public readonly record struct TypeStep(int SizePx, int LinePx, int Weight); diff --git a/VibranceHud/Discord/DiscordPresenceClient.cs b/VibranceHud/Discord/DiscordPresenceClient.cs new file mode 100644 index 0000000..eddccb0 --- /dev/null +++ b/VibranceHud/Discord/DiscordPresenceClient.cs @@ -0,0 +1,128 @@ +using System; +using System.IO; +using System.IO.Pipes; + +namespace VibranceHud.Discord; + +public sealed class DiscordPresenceClient : IDisposable +{ + private readonly Func _open; + + private readonly bool _leaveOpen; + + private readonly Func _now; + + private Stream? _pipe; + + internal static readonly TimeSpan RescanAfterMiss = TimeSpan.FromSeconds(30.0); + + private DateTime _dontLookUntil = DateTime.MinValue; + + public bool Connected => _pipe != null; + + public DiscordPresenceClient() + : this(OpenDiscordPipe, leaveOpen: false) + { + } + + public DiscordPresenceClient(Func open, bool leaveOpen, Func? now = null) + { + _now = now ?? ((Func)(() => DateTime.UtcNow)); + _open = open; + _leaveOpen = leaveOpen; + } + + private static Stream? OpenDiscordPipe() + { + for (int i = 0; i < 10; i++) + { + try + { + NamedPipeClientStream namedPipeClientStream = new NamedPipeClientStream(".", $"discord-ipc-{i}", PipeDirection.InOut, PipeOptions.Asynchronous); + namedPipeClientStream.Connect(250); + return namedPipeClientStream; + } + catch + { + } + } + return null; + } + + public void Connect() + { + if (_pipe != null || _now() < _dontLookUntil) + { + return; + } + try + { + _pipe = _open(); + if (_pipe == null) + { + _dontLookUntil = _now() + RescanAfterMiss; + } + else + { + Write(DiscordRpc.Frame(0, DiscordRpc.HandshakeJson())); + } + } + catch + { + Drop(); + _dontLookUntil = _now() + RescanAfterMiss; + } + } + + public void SetPreset(string? presetName) + { + if (_pipe == null) + { + Connect(); + } + if (_pipe == null) + { + return; + } + try + { + Write(DiscordRpc.Frame(1, DiscordRpc.SetActivityJson(Environment.ProcessId, presetName))); + } + catch + { + Drop(); + } + } + + public void Clear() + { + Drop(); + } + + private void Write(byte[] frame) + { + _pipe.Write(frame, 0, frame.Length); + _pipe.Flush(); + } + + private void Drop() + { + Stream pipe = _pipe; + _pipe = null; + if (!_leaveOpen) + { + try + { + pipe?.Dispose(); + } + catch + { + } + } + } + + public void Dispose() + { + Drop(); + } +} diff --git a/VibranceHud/Discord/DiscordRpc.cs b/VibranceHud/Discord/DiscordRpc.cs new file mode 100644 index 0000000..589ea63 --- /dev/null +++ b/VibranceHud/Discord/DiscordRpc.cs @@ -0,0 +1,73 @@ +using System; +using System.Text; +using System.Text.Json; + +namespace VibranceHud.Discord; + +public static class DiscordRpc +{ + public const string ApplicationId = "1537861543633494146"; + + public const int OpHandshake = 0; + + public const int OpFrame = 1; + + public static byte[] Frame(int opcode, string json) + { + byte[] bytes = Encoding.UTF8.GetBytes(json); + byte[] array = new byte[8 + bytes.Length]; + BitConverter.GetBytes(opcode).CopyTo(array, 0); + BitConverter.GetBytes(bytes.Length).CopyTo(array, 4); + bytes.CopyTo(array, 8); + return array; + } + + public static string HandshakeJson() + { + return JsonSerializer.Serialize(new + { + v = 1, + client_id = "1537861543633494146" + }); + } + + public static string SetActivityJson(int pid, string? presetName) + { + object assets = new + { + large_image = "logo", + large_text = "PlexusX" + }; + object[] buttons = new object[2] + { + new + { + label = "View Site", + url = "https://plexusx.lol" + }, + new + { + label = "Download", + url = "https://plexusx.lol" + } + }; + object activity = ((presetName == null) ? ((object)new + { + details = "Colour, all the way up", + assets = assets, + buttons = buttons + }) : ((object)new + { + details = "Colour, all the way up", + state = presetName, + assets = assets, + buttons = buttons + })); + return JsonSerializer.Serialize(new + { + cmd = "SET_ACTIVITY", + args = new { pid, activity }, + nonce = Guid.NewGuid().ToString("N") + }); + } +} diff --git a/VibranceHud/DispChangeResult.cs b/VibranceHud/DispChangeResult.cs new file mode 100644 index 0000000..74955ce --- /dev/null +++ b/VibranceHud/DispChangeResult.cs @@ -0,0 +1,14 @@ +namespace VibranceHud; + +public enum DispChangeResult +{ + Successful, + Restart, + Failed, + BadMode, + NotUpdated, + BadFlags, + BadParam, + BadDualView, + Reverted +} diff --git a/VibranceHud/Display/AbCompare.cs b/VibranceHud/Display/AbCompare.cs new file mode 100644 index 0000000..f522d8f --- /dev/null +++ b/VibranceHud/Display/AbCompare.cs @@ -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; + } +} diff --git a/VibranceHud/Display/CustomModeAdvice.cs b/VibranceHud/Display/CustomModeAdvice.cs new file mode 100644 index 0000000..8e99203 --- /dev/null +++ b/VibranceHud/Display/CustomModeAdvice.cs @@ -0,0 +1,3 @@ +namespace VibranceHud.Display; + +public readonly record struct CustomModeAdvice(CustomModeStanding Standing, string Message, int Width, int Height, int Hz); diff --git a/VibranceHud/Display/CustomModeAdvisor.cs b/VibranceHud/Display/CustomModeAdvisor.cs new file mode 100644 index 0000000..284f66b --- /dev/null +++ b/VibranceHud/Display/CustomModeAdvisor.cs @@ -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 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 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; + } +} diff --git a/VibranceHud/Display/CustomModeAttempt.cs b/VibranceHud/Display/CustomModeAttempt.cs new file mode 100644 index 0000000..3f40d24 --- /dev/null +++ b/VibranceHud/Display/CustomModeAttempt.cs @@ -0,0 +1,3 @@ +namespace VibranceHud.Display; + +public readonly record struct CustomModeAttempt(CustomModeOutcome Outcome, CustomModeVerdict Verdict, int Hz, bool Stretched); diff --git a/VibranceHud/Display/CustomModeLimits.cs b/VibranceHud/Display/CustomModeLimits.cs new file mode 100644 index 0000000..aa42c4d --- /dev/null +++ b/VibranceHud/Display/CustomModeLimits.cs @@ -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 reported, int running) + { + PanelSize panelSize = CustomModePanel.Native(reported); + IReadOnlyList readOnlyList2; + if (!panelSize.Known) + { + IReadOnlyList readOnlyList = Array.Empty(); + readOnlyList2 = readOnlyList; + } + else + { + readOnlyList2 = DisplayModes.RefreshRatesFor(reported, panelSize.Width, panelSize.Height); + } + IReadOnlyList rates = readOnlyList2; + return SelectNativeRate(typedHz, rates, running); + } + + internal static int SelectNativeRate(int typedHz, IReadOnlyList 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 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 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; + } +} diff --git a/VibranceHud/Display/CustomModeOffers.cs b/VibranceHud/Display/CustomModeOffers.cs new file mode 100644 index 0000000..1e55a3d --- /dev/null +++ b/VibranceHud/Display/CustomModeOffers.cs @@ -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 For(PanelSize panel) + { + if (!panel.Known) + { + return Array.Empty(); + } + List list = new List(); + 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 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; + } +} diff --git a/VibranceHud/Display/CustomModeOutcome.cs b/VibranceHud/Display/CustomModeOutcome.cs new file mode 100644 index 0000000..c0ec7c4 --- /dev/null +++ b/VibranceHud/Display/CustomModeOutcome.cs @@ -0,0 +1,13 @@ +namespace VibranceHud.Display; + +public enum CustomModeOutcome +{ + Applied, + Reverted, + RevertFailed, + OutOfRange, + NotAvailable, + DriverRefused, + AppliedButNotSaved, + ScalingFailed +} diff --git a/VibranceHud/Display/CustomModePanel.cs b/VibranceHud/Display/CustomModePanel.cs new file mode 100644 index 0000000..afceb0f --- /dev/null +++ b/VibranceHud/Display/CustomModePanel.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; + +namespace VibranceHud.Display; + +public static class CustomModePanel +{ + public static PanelSize Native(IReadOnlyList 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); + } +} diff --git a/VibranceHud/Display/CustomModeRegistrar.cs b/VibranceHud/Display/CustomModeRegistrar.cs new file mode 100644 index 0000000..4b5a95f --- /dev/null +++ b/VibranceHud/Display/CustomModeRegistrar.cs @@ -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> _supportedModes; + + private readonly Func _current; + + private readonly Func _restore; + + private readonly Func _confirm; + + private readonly Func _readScaling; + + private readonly Func _setScaling; + + private readonly IDesktopLayout _layout; + + private readonly Func _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>? supportedModes = null, Func? current = null, Func? restore = null, Func? confirm = null, Func? readScaling = null, Func? setScaling = null, IDesktopLayout? layout = null, Func? linkHint = null, ShapeFit? fit = null) + { + _driver = driver; + _fit = fit; + _layout = layout ?? DesktopLayout.None; + _linkHint = linkHint ?? ((Func)((string? _) => (string?)null)); + _supportedModes = supportedModes ?? ((Func>)((string? d) => DisplayController.SupportedModes(d))); + _current = current ?? ((Func)((string? d) => DisplayController.Current(d))); + _restore = restore ?? ((Func)((DisplayMode m, string? d) => DisplayController.Restore(m, d))); + _confirm = confirm ?? new Func(AskWithTheCountdown); + _readScaling = readScaling ?? ((Func)((string? d) => ScalingModeController.Stored(d))); + _setScaling = setScaling ?? ((Func)((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(), (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 SavedSizes(string? deviceName) + { + if (Guarded(() => _driver.Available) != true) + { + return Array.Empty(); + } + return GuardedValue(() => _driver.Saved(deviceName) ?? Array.Empty(), Array.Empty()); + } + + 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 reported = GuardedValue(() => _supportedModes(deviceName), Array.Empty()); + 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 layoutBefore = GuardedValue(() => _layout.Read(), Array.Empty()); + 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 reported = GuardedValue(() => _supportedModes(deviceName), Array.Empty()); + 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 readOnlyList = GuardedValue(() => _layout.Read(), Array.Empty()); + 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 before) + { + if (before.Count == 0) + { + return; + } + IReadOnlyList now = GuardedValue(() => _layout.Read(), Array.Empty()); + IReadOnlyList 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 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 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 call) + { + try + { + return call(); + } + catch + { + return null; + } + } + + private static T GuardedValue(Func call, T fallback) + { + try + { + return call(); + } + catch + { + return fallback; + } + } +} diff --git a/VibranceHud/Display/CustomModeStanding.cs b/VibranceHud/Display/CustomModeStanding.cs new file mode 100644 index 0000000..a5d8ad8 --- /dev/null +++ b/VibranceHud/Display/CustomModeStanding.cs @@ -0,0 +1,12 @@ +namespace VibranceHud.Display; + +public enum CustomModeStanding +{ + NothingTyped, + TooSmall, + RefreshTooHigh, + Impossible, + AlreadyListed, + NeedsRegistering, + CannotRegister +} diff --git a/VibranceHud/Display/CustomModeVerdict.cs b/VibranceHud/Display/CustomModeVerdict.cs new file mode 100644 index 0000000..4ff51b7 --- /dev/null +++ b/VibranceHud/Display/CustomModeVerdict.cs @@ -0,0 +1,9 @@ +namespace VibranceHud.Display; + +public enum CustomModeVerdict +{ + Fine, + TooSmall, + BiggerThanThePanel, + RefreshOutOfRange +} diff --git a/VibranceHud/Display/DesktopLayout.cs b/VibranceHud/Display/DesktopLayout.cs new file mode 100644 index 0000000..b50d200 --- /dev/null +++ b/VibranceHud/Display/DesktopLayout.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; + +namespace VibranceHud.Display; + +public static class DesktopLayout +{ + private sealed class NoDesktopLayout : IDesktopLayout + { + public IReadOnlyList Read() + { + return Array.Empty(); + } + + public bool Place(IReadOnlyList placements) + { + return false; + } + } + + internal sealed class RealDesktopLayout : IDesktopLayout + { + public IReadOnlyList Read() + { + return DisplayController.Placements(); + } + + public bool Place(IReadOnlyList placements) + { + return DisplayController.PlaceMonitors(placements); + } + } + + public static IDesktopLayout None { get; } = new NoDesktopLayout(); + + public static IDesktopLayout Real() + { + return new RealDesktopLayout(); + } + + public static IReadOnlyList WhatMoved(IReadOnlyList before, IReadOnlyList now) + { + List list = new List(); + 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; + } +} diff --git a/VibranceHud/Display/EdidLink.cs b/VibranceHud/Display/EdidLink.cs new file mode 100644 index 0000000..501cc9c --- /dev/null +++ b/VibranceHud/Display/EdidLink.cs @@ -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 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."; + } +} diff --git a/VibranceHud/Display/EdidLinkReader.cs b/VibranceHud/Display/EdidLinkReader.cs new file mode 100644 index 0000000..e529b68 --- /dev/null +++ b/VibranceHud/Display/EdidLinkReader.cs @@ -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() + }; + 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 list = new List(); + 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; + } + } +} diff --git a/VibranceHud/Display/IClock.cs b/VibranceHud/Display/IClock.cs new file mode 100644 index 0000000..ef2f9ba --- /dev/null +++ b/VibranceHud/Display/IClock.cs @@ -0,0 +1,8 @@ +using System; + +namespace VibranceHud.Display; + +public interface IClock +{ + DateTime UtcNow { get; } +} diff --git a/VibranceHud/Display/ICustomModeDriver.cs b/VibranceHud/Display/ICustomModeDriver.cs new file mode 100644 index 0000000..88b4b54 --- /dev/null +++ b/VibranceHud/Display/ICustomModeDriver.cs @@ -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 Saved(string? deviceName) + { + return Array.Empty(); + } +} diff --git a/VibranceHud/Display/IDesktopLayout.cs b/VibranceHud/Display/IDesktopLayout.cs new file mode 100644 index 0000000..ea29777 --- /dev/null +++ b/VibranceHud/Display/IDesktopLayout.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; + +namespace VibranceHud.Display; + +public interface IDesktopLayout +{ + IReadOnlyList Read(); + + bool Place(IReadOnlyList placements); +} diff --git a/VibranceHud/Display/ModeApplier.cs b/VibranceHud/Display/ModeApplier.cs new file mode 100644 index 0000000..b5c747a --- /dev/null +++ b/VibranceHud/Display/ModeApplier.cs @@ -0,0 +1,103 @@ +using System; +using VibranceHud.Capabilities; +using VibranceHud.Controls; + +namespace VibranceHud.Display; + +public sealed class ModeApplier +{ + internal sealed record Steps(Func Current, Func Apply, Func Restore, Func Confirm); + + private readonly Func _apply; + + private readonly Func? _setHdr; + + public bool MovesARealScreen { get; } + + public ModeApplier(Func apply, bool movesARealScreen, Func? 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); + } +} diff --git a/VibranceHud/Display/MonitorCode.cs b/VibranceHud/Display/MonitorCode.cs new file mode 100644 index 0000000..b4bf9d0 --- /dev/null +++ b/VibranceHud/Display/MonitorCode.cs @@ -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; + } +} diff --git a/VibranceHud/Display/MonitorPlacement.cs b/VibranceHud/Display/MonitorPlacement.cs new file mode 100644 index 0000000..ab4b3c4 --- /dev/null +++ b/VibranceHud/Display/MonitorPlacement.cs @@ -0,0 +1,3 @@ +namespace VibranceHud.Display; + +public readonly record struct MonitorPlacement(string DeviceName, int X, int Y); diff --git a/VibranceHud/Display/NoCustomModeDriver.cs b/VibranceHud/Display/NoCustomModeDriver.cs new file mode 100644 index 0000000..427e33c --- /dev/null +++ b/VibranceHud/Display/NoCustomModeDriver.cs @@ -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; + } +} diff --git a/VibranceHud/Display/Nvapi.cs b/VibranceHud/Display/Nvapi.cs new file mode 100644 index 0000000..a683460 --- /dev/null +++ b/VibranceHud/Display/Nvapi.cs @@ -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; + } +} diff --git a/VibranceHud/Display/NvidiaCustomModeDriver.cs b/VibranceHud/Display/NvidiaCustomModeDriver.cs new file mode 100644 index 0000000..c86b8b5 --- /dev/null +++ b/VibranceHud/Display/NvidiaCustomModeDriver.cs @@ -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> _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 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>? supportedModes = null) + { + _supportedModes = supportedModes ?? ((Func>)((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 Saved(string? deviceName) + { + if (!Nvapi.Ready()) + { + return Array.Empty(); + } + List list = new List(); + 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); + } +} diff --git a/VibranceHud/Display/PanelSize.cs b/VibranceHud/Display/PanelSize.cs new file mode 100644 index 0000000..a612524 --- /dev/null +++ b/VibranceHud/Display/PanelSize.cs @@ -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}"; + } +} diff --git a/VibranceHud/Display/ScalingMode.cs b/VibranceHud/Display/ScalingMode.cs new file mode 100644 index 0000000..d349c92 --- /dev/null +++ b/VibranceHud/Display/ScalingMode.cs @@ -0,0 +1,9 @@ +namespace VibranceHud.Display; + +public enum ScalingMode +{ + AspectRatio, + NoScaling, + FullScreen, + Integer +} diff --git a/VibranceHud/Display/ScalingModeController.cs b/VibranceHud/Display/ScalingModeController.cs new file mode 100644 index 0000000..c0fef50 --- /dev/null +++ b/VibranceHud/Display/ScalingModeController.cs @@ -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 Current, Func Raw, Func Set, Func 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(), Path: Marshal.SizeOf()); + } + + 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 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 PickPaths(IReadOnlyList sourceNames, string? gdiDeviceName, Func primaryName) + { + string text = (string.IsNullOrWhiteSpace(gdiDeviceName) ? primaryName() : gdiDeviceName); + List list = new List(); + 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(); + modes = Array.Empty(); + 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(), + 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 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); +} diff --git a/VibranceHud/Display/ScalingModeNames.cs b/VibranceHud/Display/ScalingModeNames.cs new file mode 100644 index 0000000..1910abb --- /dev/null +++ b/VibranceHud/Display/ScalingModeNames.cs @@ -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(), + }; + } +} diff --git a/VibranceHud/Display/ScalingOutcome.cs b/VibranceHud/Display/ScalingOutcome.cs new file mode 100644 index 0000000..a7aebd8 --- /dev/null +++ b/VibranceHud/Display/ScalingOutcome.cs @@ -0,0 +1,12 @@ +namespace VibranceHud.Display; + +public enum ScalingOutcome +{ + Applied, + SavedForLater, + Unconfirmed, + Unreadable, + Reverted, + RevertFailed, + Failed +} diff --git a/VibranceHud/Display/ShapeFit.cs b/VibranceHud/Display/ShapeFit.cs new file mode 100644 index 0000000..73606f8 --- /dev/null +++ b/VibranceHud/Display/ShapeFit.cs @@ -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> _supportedModes; + + private readonly Func _stored; + + private readonly Func _set; + + private readonly Dictionary _before = new Dictionary(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> supportedModes, Func stored, Func 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)); + } + } +} diff --git a/VibranceHud/Display/SystemClock.cs b/VibranceHud/Display/SystemClock.cs new file mode 100644 index 0000000..7c005ae --- /dev/null +++ b/VibranceHud/Display/SystemClock.cs @@ -0,0 +1,8 @@ +using System; + +namespace VibranceHud.Display; + +public sealed class SystemClock : IClock +{ + public DateTime UtcNow => DateTime.UtcNow; +} diff --git a/VibranceHud/DisplayController.cs b/VibranceHud/DisplayController.cs new file mode 100644 index 0000000..49c8835 --- /dev/null +++ b/VibranceHud/DisplayController.cs @@ -0,0 +1,489 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading.Tasks; +using VibranceHud.Controls; +using VibranceHud.Display; + +namespace VibranceHud; + +public static class DisplayController +{ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + private struct DEVMODE + { + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] + public string dmDeviceName; + + public short dmSpecVersion; + + public short dmDriverVersion; + + public short dmSize; + + public short dmDriverExtra; + + public int dmFields; + + public int dmPositionX; + + public int dmPositionY; + + public int dmDisplayOrientation; + + public int dmDisplayFixedOutput; + + public short dmColor; + + public short dmDuplex; + + public short dmYResolution; + + public short dmTTOption; + + public short dmCollate; + + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] + public string dmFormName; + + public short dmLogPixels; + + public int dmBitsPerPel; + + public int dmPelsWidth; + + public int dmPelsHeight; + + public int dmDisplayFlags; + + public int dmDisplayFrequency; + + public int dmICMMethod; + + public int dmICMIntent; + + public int dmMediaType; + + public int dmDitherType; + + public int dmReserved1; + + public int dmReserved2; + + public int dmPanningWidth; + + public int dmPanningHeight; + } + + [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 ENUM_CURRENT_SETTINGS = -1; + + private const int CDS_UPDATEREGISTRY = 1; + + private const int CDS_TEST = 2; + + private const int CDS_NORESET = 268435456; + + private const int DM_POSITION = 32; + + private const int DM_PELSWIDTH = 524288; + + private const int DM_PELSHEIGHT = 1048576; + + private const int DM_DISPLAYFREQUENCY = 4194304; + + private const int DISPLAY_DEVICE_ATTACHED_TO_DESKTOP = 1; + + private const int DISPLAY_DEVICE_PRIMARY_DEVICE = 4; + + public static Action? OnRestored { get; set; } + + [DllImport("user32.dll", CharSet = CharSet.Unicode)] + private static extern bool EnumDisplaySettings(string? deviceName, int modeNum, ref DEVMODE dm); + + [DllImport("user32.dll", CharSet = CharSet.Unicode)] + private static extern int ChangeDisplaySettingsEx(string? lpszDeviceName, ref DEVMODE lpDevMode, nint hwnd, int dwflags, nint lParam); + + [DllImport("user32.dll", CharSet = CharSet.Unicode, EntryPoint = "ChangeDisplaySettingsExW")] + private static extern int CommitStagedDisplaySettings(nint lpszDeviceName, nint lpDevMode, nint hwnd, int dwflags, nint lParam); + + [DllImport("user32.dll", CharSet = CharSet.Unicode)] + private static extern bool EnumDisplayDevices(string? lpDevice, int iDevNum, ref DISPLAY_DEVICE lpDisplayDevice, int dwFlags); + + private static DEVMODE NewDevMode() + { + DEVMODE result = new DEVMODE + { + dmDeviceName = new string('\0', 32), + dmFormName = new string('\0', 32) + }; + result.dmSize = (short)Marshal.SizeOf(); + return result; + } + + internal static DispChangeResult MapDispChange(int code) + { + return code switch + { + 0 => DispChangeResult.Successful, + 1 => DispChangeResult.Restart, + -2 => DispChangeResult.BadMode, + -3 => DispChangeResult.NotUpdated, + -4 => DispChangeResult.BadFlags, + -5 => DispChangeResult.BadParam, + -6 => DispChangeResult.BadDualView, + _ => DispChangeResult.Failed, + }; + } + + public static IReadOnlyList Monitors() + { + List list = new List(); + DISPLAY_DEVICE lpDisplayDevice = new DISPLAY_DEVICE + { + cb = Marshal.SizeOf() + }; + for (int i = 0; EnumDisplayDevices(null, i, ref lpDisplayDevice, 0); i++) + { + if ((lpDisplayDevice.StateFlags & 1) != 0) + { + DISPLAY_DEVICE lpDisplayDevice2 = new DISPLAY_DEVICE + { + cb = Marshal.SizeOf() + }; + string friendlyName = (EnumDisplayDevices(lpDisplayDevice.DeviceName, 0, ref lpDisplayDevice2, 0) ? lpDisplayDevice2.DeviceString.TrimEnd('\0') : lpDisplayDevice.DeviceString.TrimEnd('\0')); + list.Add(new MonitorDescriptor(lpDisplayDevice.DeviceName.TrimEnd('\0'), friendlyName, (lpDisplayDevice.StateFlags & 4) != 0)); + } + lpDisplayDevice = new DISPLAY_DEVICE + { + cb = Marshal.SizeOf() + }; + } + list.Sort((MonitorDescriptor a, MonitorDescriptor b) => b.IsPrimary.CompareTo(a.IsPrimary)); + return list; + } + + internal static IReadOnlyList Placements() + { + List list = new List(); + foreach (MonitorDescriptor item in Monitors()) + { + DEVMODE dm = NewDevMode(); + if (EnumDisplaySettings(item.DeviceName, -1, ref dm)) + { + list.Add(new MonitorPlacement(item.DeviceName, dm.dmPositionX, dm.dmPositionY)); + } + } + return list; + } + + internal static bool PlaceMonitors(IReadOnlyList placements) + { + if (placements.Count == 0) + { + return true; + } + foreach (MonitorPlacement placement in placements) + { + DEVMODE dm = NewDevMode(); + if (!EnumDisplaySettings(placement.DeviceName, -1, ref dm)) + { + return false; + } + dm.dmPositionX = placement.X; + dm.dmPositionY = placement.Y; + dm.dmFields = 32; + if (MapDispChange(ChangeDisplaySettingsEx(placement.DeviceName, ref dm, IntPtr.Zero, 268435457, IntPtr.Zero)) != DispChangeResult.Successful) + { + return false; + } + } + return MapDispChange(CommitStagedDisplaySettings(IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, 0, IntPtr.Zero)) == DispChangeResult.Successful; + } + + public static IReadOnlyList SupportedModes(string? deviceName = null) + { + List list = new List(); + DEVMODE dm = NewDevMode(); + for (int i = 0; EnumDisplaySettings(deviceName, i, ref dm); i++) + { + if (dm.dmBitsPerPel == 32) + { + list.Add(new DisplayMode(dm.dmPelsWidth, dm.dmPelsHeight, dm.dmDisplayFrequency)); + } + dm = NewDevMode(); + } + return list; + } + + public static DisplayMode? Current(string? deviceName = null) + { + DEVMODE dm = NewDevMode(); + if (!EnumDisplaySettings(deviceName, -1, ref dm)) + { + return null; + } + return new DisplayMode(dm.dmPelsWidth, dm.dmPelsHeight, dm.dmDisplayFrequency); + } + + public static DispChangeResult ApplyEx(int width, int height, int hz, string? deviceName = null, bool persist = false) + { + IReadOnlyList modes = SupportedModes(deviceName); + if (hz <= 0) + { + hz = DisplayModes.MaxRefreshFor(modes, width, height); + } + if (hz <= 0 || !DisplayModes.IsSupported(modes, width, height, hz)) + { + return DispChangeResult.BadMode; + } + DEVMODE dm = NewDevMode(); + if (!EnumDisplaySettings(deviceName, -1, ref dm)) + { + return DispChangeResult.Failed; + } + dm.dmPelsWidth = width; + dm.dmPelsHeight = height; + dm.dmDisplayFrequency = hz; + dm.dmFields = 5767200; + DispChangeResult dispChangeResult = MapDispChange(ChangeDisplaySettingsEx(deviceName, ref dm, IntPtr.Zero, 2, IntPtr.Zero)); + if (dispChangeResult != DispChangeResult.Successful) + { + return dispChangeResult; + } + int dwflags = (persist ? 1 : 0); + return MapDispChange(ChangeDisplaySettingsEx(deviceName, ref dm, IntPtr.Zero, dwflags, IntPtr.Zero)); + } + + public static bool Apply(int width, int height, int hz = 0, string? deviceName = null) + { + return ApplyEx(width, height, hz, deviceName) switch + { + DispChangeResult.Successful => true, + DispChangeResult.BadMode => CustomModeRegistrar.Real().SwitchToSaved(width, height, hz, deviceName), + _ => false, + }; + } + + public static bool Restore(DisplayMode mode, string? deviceName = null) + { + return Apply(mode.Width, mode.Height, mode.RefreshHz, deviceName); + } + + public static DispChangeResult TryApplyWithRevert(int width, int height, int hz, string? deviceName, TimeSpan grace) + { + DisplayMode? displayMode = Current(deviceName); + if (displayMode.HasValue) + { + DisplayMode valueOrDefault = displayMode.GetValueOrDefault(); + DispChangeResult dispChangeResult = ApplyEx(width, height, hz, deviceName); + if (dispChangeResult != DispChangeResult.Successful) + { + return dispChangeResult; + } + bool confirmed = false; + using (RevertConfirmForm revertConfirmForm = new RevertConfirmForm($"Switched to {width} x {height}" + ((hz > 0) ? $" at {hz} Hz" : "") + ".", Math.Max(1, (int)Math.Ceiling(grace.TotalSeconds)))) + { + revertConfirmForm.Confirmed += () => + { + confirmed = true; + }; + revertConfirmForm.ShowDialog(); + } + if (!confirmed) + { + if (!Restore(valueOrDefault, deviceName)) + { + return DispChangeResult.Failed; + } + return DispChangeResult.Reverted; + } + ApplyEx(width, height, hz, deviceName, persist: true); + return dispChangeResult; + } + return DispChangeResult.Failed; + } + + public static void RestoreWhenGameExits(string processName, DisplayMode original, TimeSpan waitForStart, string? deviceName = null, IReadOnlyList? alsoProcessNames = null) + { + if (string.IsNullOrWhiteSpace(processName)) + { + return; + } + Task.Run((Func)(async () => + { + _ = 1; + try + { + DateTime deadline = DateTime.UtcNow + waitForStart; + List names = new List { processName }; + if (alsoProcessNames != null) + { + names.AddRange(alsoProcessNames); + } + while (!Running()) + { + if (DateTime.UtcNow > deadline) + { + Restore(original, deviceName); + try + { + OnRestored?.Invoke(); + return; + } + catch + { + return; + } + } + await Task.Delay(2000); + } + while (Running()) + { + await Task.Delay(3000); + } + Restore(original, deviceName); + try + { + OnRestored?.Invoke(); + } + catch + { + } + bool Running() + { + return names.Any((string n) => Process.GetProcessesByName(n).Length != 0); + } + } + catch + { + try + { + Restore(original, deviceName); + } + catch + { + } + try + { + OnRestored?.Invoke(); + } + catch + { + } + } + })); + } + + public static void RestoreWhenRustExits(DisplayMode original, TimeSpan waitForStart) + { + RestoreWhenGameExits("RustClient", original, waitForStart); + } + + internal static string DescribeOwed(DisplayMode mode, string? deviceName) + { + if (!string.IsNullOrWhiteSpace(deviceName)) + { + return deviceName + "|" + Describe(mode); + } + return Describe(mode); + } + + internal static (string? Device, DisplayMode Mode)? ParseOwed(string? text) + { + if (string.IsNullOrWhiteSpace(text)) + { + return null; + } + int num = text.IndexOf('|'); + string text2 = null; + if (num >= 0) + { + text2 = text.Substring(0, num); + if (string.IsNullOrWhiteSpace(text2)) + { + return null; + } + text = text.Substring(num + 1); + } + DisplayMode? displayMode = Parse(text); + if (displayMode.HasValue) + { + DisplayMode valueOrDefault = displayMode.GetValueOrDefault(); + return (text2, valueOrDefault); + } + return null; + } + + internal static bool IsAttached(string? deviceName, IEnumerable monitors) + { + if (!string.IsNullOrWhiteSpace(deviceName)) + { + return monitors.Any((MonitorDescriptor m) => string.Equals(m.DeviceName, deviceName, StringComparison.OrdinalIgnoreCase)); + } + return true; + } + + public static string Describe(DisplayMode mode) + { + IFormatProvider invariantCulture = CultureInfo.InvariantCulture; + DefaultInterpolatedStringHandler handler = new DefaultInterpolatedStringHandler(2, 3, invariantCulture); + handler.AppendFormatted(mode.Width); + handler.AppendLiteral("x"); + handler.AppendFormatted(mode.Height); + handler.AppendLiteral("@"); + handler.AppendFormatted(mode.RefreshHz); + return string.Create(invariantCulture, ref handler); + } + + public static DisplayMode? Parse(string? text) + { + if (string.IsNullOrWhiteSpace(text)) + { + return null; + } + string[] array = text.Split('@'); + if (array.Length != 2) + { + return null; + } + string[] array2 = array[0].Split('x'); + if (array2.Length != 2) + { + return null; + } + CultureInfo invariantCulture = CultureInfo.InvariantCulture; + if (!int.TryParse(array2[0], NumberStyles.Integer, invariantCulture, out var result) || !int.TryParse(array2[1], NumberStyles.Integer, invariantCulture, out var result2) || !int.TryParse(array[1], NumberStyles.Integer, invariantCulture, out var result3)) + { + return null; + } + if (result <= 0 || result2 <= 0 || result3 < 0) + { + return null; + } + return new DisplayMode(result, result2, result3); + } +} diff --git a/VibranceHud/DisplayHelp.cs b/VibranceHud/DisplayHelp.cs new file mode 100644 index 0000000..0f422c8 --- /dev/null +++ b/VibranceHud/DisplayHelp.cs @@ -0,0 +1,69 @@ +using System; +using System.IO; +using System.Linq; + +namespace VibranceHud; + +public static class DisplayHelp +{ + public enum Vendor + { + Unknown, + Nvidia, + Amd, + Intel + } + + private static readonly string[] NvidiaPanels = new string[2] { "C:\\Program Files\\NVIDIA Corporation\\Control Panel Client\\nvcplui.exe", "C:\\Windows\\System32\\nvcplui.exe" }; + + private static readonly string[] AmdPanels = new string[2] { "C:\\Program Files\\AMD\\CNext\\CNext\\RadeonSoftware.exe", "C:\\Program Files\\AMD\\CNext\\CCCSlim\\RadeonSoftware.exe" }; + + public static Vendor Installed() + { + if (!OperatingSystem.IsWindows()) + { + return Vendor.Unknown; + } + if (NvidiaPanels.Any(SafeExists)) + { + return Vendor.Nvidia; + } + if (AmdPanels.Any(SafeExists)) + { + return Vendor.Amd; + } + return Vendor.Unknown; + } + + public static string? PanelPath() + { + return NvidiaPanels.FirstOrDefault(SafeExists) ?? AmdPanels.FirstOrDefault(SafeExists); + } + + public static string HowToAddACustomMode() + { + return HowToAddACustomMode(Installed()); + } + + public static string HowToAddACustomMode(Vendor vendor) + { + return vendor switch + { + Vendor.Nvidia => "You can add it yourself in NVIDIA Control Panel: Display, Change resolution, Customise, Create Custom Resolution.", + Vendor.Amd => "You can add it yourself in AMD Software: Settings, Display, Custom Resolutions.", + _ => "Your graphics driver's control panel can usually add it as a custom resolution.", + }; + } + + private static bool SafeExists(string path) + { + try + { + return File.Exists(path); + } + catch + { + return false; + } + } +} diff --git a/VibranceHud/DisplayLabels.cs b/VibranceHud/DisplayLabels.cs new file mode 100644 index 0000000..a73902f --- /dev/null +++ b/VibranceHud/DisplayLabels.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; + +namespace VibranceHud; + +internal static class DisplayLabels +{ + internal static IReadOnlyList For(IEnumerable<(string Adapter, string MonitorName, bool IsPrimary)> monitors) + { + List list = new List(); + foreach (var monitor in monitors) + { + string item = monitor.Adapter; + string item2 = monitor.MonitorName; + bool item3 = monitor.IsPrimary; + string text = (string.IsNullOrWhiteSpace(item2) ? item : item2); + text = string.Join(" ", text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)); + if (text.Contains("\\\\.\\", StringComparison.Ordinal)) + { + text = ""; + } + list.Add($"Display {list.Count + 1}" + ((text.Length > 0) ? (" · " + text) : "") + (item3 ? " (main)" : "")); + } + return list; + } +} diff --git a/VibranceHud/DisplayMode.cs b/VibranceHud/DisplayMode.cs new file mode 100644 index 0000000..829c56b --- /dev/null +++ b/VibranceHud/DisplayMode.cs @@ -0,0 +1,9 @@ +namespace VibranceHud; + +public readonly record struct DisplayMode(int Width, int Height, int RefreshHz) +{ + public override string ToString() + { + return $"{Width}x{Height}"; + } +} diff --git a/VibranceHud/DisplayModes.cs b/VibranceHud/DisplayModes.cs new file mode 100644 index 0000000..0b919aa --- /dev/null +++ b/VibranceHud/DisplayModes.cs @@ -0,0 +1,82 @@ +using System.Collections.Generic; + +namespace VibranceHud; + +public static class DisplayModes +{ + public static int RefreshForSharedMode(IEnumerable supported, int width, int height, int sharedHz) + { + return MaxRefreshFor(supported, width, height); + } + + public static IReadOnlyList BestPerResolution(IEnumerable modes) + { + Dictionary<(int, int), int> dictionary = new Dictionary<(int, int), int>(); + foreach (DisplayMode mode in modes) + { + if (mode.Width > 0 && mode.Height > 0) + { + (int, int) key = (mode.Width, mode.Height); + if (!dictionary.TryGetValue(key, out var value) || mode.RefreshHz > value) + { + dictionary[key] = mode.RefreshHz; + } + } + } + List list = new List(); + foreach (var (tuple2, num2) in dictionary) + { + int item = tuple2.Item1; + int item2 = tuple2.Item2; + int refreshHz = num2; + list.Add(new DisplayMode(item, item2, refreshHz)); + } + list.Sort((DisplayMode a, DisplayMode b) => (a.Width == b.Width) ? b.Height.CompareTo(a.Height) : b.Width.CompareTo(a.Width)); + return list; + } + + public static int MaxRefreshFor(IEnumerable modes, int width, int height) + { + int num = 0; + foreach (DisplayMode mode in modes) + { + if (mode.Width == width && mode.Height == height && mode.RefreshHz > num) + { + num = mode.RefreshHz; + } + } + return num; + } + + public static IReadOnlyList RefreshRatesFor(IEnumerable modes, int width, int height) + { + SortedSet sortedSet = new SortedSet(); + foreach (DisplayMode mode in modes) + { + if (mode.Width == width && mode.Height == height && mode.RefreshHz > 0) + { + sortedSet.Add(mode.RefreshHz); + } + } + List list = new List(sortedSet); + list.Reverse(); + return list; + } + + public static bool IsSupported(IEnumerable modes, int width, int height, int hz) + { + foreach (DisplayMode mode in modes) + { + if (mode.Width == width && mode.Height == height && mode.RefreshHz == hz) + { + return true; + } + } + return false; + } + + public static bool IsSupported(IEnumerable modes, int width, int height) + { + return MaxRefreshFor(modes, width, height) > 0; + } +} diff --git a/VibranceHud/DisplayOnlyLook.cs b/VibranceHud/DisplayOnlyLook.cs new file mode 100644 index 0000000..0961afa --- /dev/null +++ b/VibranceHud/DisplayOnlyLook.cs @@ -0,0 +1,150 @@ +using System; +using System.Collections.Generic; + +namespace VibranceHud; + +public static class DisplayOnlyLook +{ + public enum Knob + { + Stronger, + Vibrance, + Saturation + } + + public static int SaturationAsDriverVibrance(int saturation) + { + saturation = Math.Clamp(saturation, 0, 300); + if (saturation <= 100) + { + return (int)Math.Round((double)saturation * 0.5); + } + double num = (double)(saturation - 100) / 200.0; + return (int)Math.Round(50.0 + num * 50.0); + } + + public static int DriverLevelFor(int vibrance, int saturation) + { + return Math.Clamp(Math.Max(Math.Clamp(vibrance, 0, 100), SaturationAsDriverVibrance(saturation)), 0, 100); + } + + public static int DriverLevelFor(int vibrance, int saturation, Knob follows) + { + return follows switch + { + Knob.Vibrance => Math.Clamp(vibrance, 0, 100), + Knob.Saturation => SaturationAsDriverVibrance(saturation), + _ => DriverLevelFor(vibrance, saturation), + }; + } + + public static ushort[] Compose(ushort[] toneRamp, int brightness, int contrast, int temperature) + { + return Compose(toneRamp, brightness, contrast, temperature, 100, 100, 100); + } + + public static ushort[] Compose(ushort[] toneRamp, int brightness, int contrast, int temperature, int red, int green, int blue) + { + if (toneRamp == null) + { + throw new ArgumentNullException("toneRamp"); + } + float num = (float)Math.Clamp(brightness, 50, 170) / 100f; + float num2 = (float)Math.Clamp(contrast, 50, 150) / 100f; + float num3 = (float)Math.Clamp(temperature, -100, 100) / 100f; + if (IsNeutral(num, num2, num3) && ColourBalance.GainsNeutral(red, green, blue)) + { + return toneRamp; + } + double[] array = new double[3] + { + (double)Math.Clamp(red, 50, 150) / 100.0, + (double)Math.Clamp(green, 50, 150) / 100.0, + (double)Math.Clamp(blue, 50, 150) / 100.0 + }; + float num4 = Math.Max(0f, num3); + float num5 = Math.Max(0f, 0f - num3); + float num6 = 1f - 0.38f * num5; + float num7 = 1f - 0.12f * (num4 + num5); + float num8 = 1f - 0.38f * num4; + float[] array2 = new float[3] + { + num * num6 * num2, + num * num7 * num2, + num * num8 * num2 + }; + float num9 = 0.5f * (1f - num2); + int num10 = 256; + ushort[] array3 = new ushort[num10 * 3]; + for (int i = 0; i < 3; i++) + { + int num11 = i * num10; + for (int j = 0; j < num10; j++) + { + int value = (int)Math.Round(Math.Clamp(((double)j / (double)(num10 - 1) * (double)array2[i] + (double)num9) * array[i], 0.0, 1.0) * (double)(num10 - 1)); + array3[num11 + j] = toneRamp[num11 + Math.Clamp(value, 0, num10 - 1)]; + } + } + for (int k = 0; k < 3; k++) + { + int num12 = k * num10; + for (int l = 1; l < num10; l++) + { + if (array3[num12 + l] < array3[num12 + l - 1]) + { + array3[num12 + l] = array3[num12 + l - 1]; + } + } + } + return array3; + } + + public static bool IsNeutral(float brightness, float contrast, float warmth) + { + if (Math.Abs(brightness - 1f) < 0.001f && Math.Abs(contrast - 1f) < 0.001f) + { + return Math.Abs(warmth) < 0.001f; + } + return false; + } + + public static bool IsNeutral(int brightness, int contrast, int temperature) + { + return IsNeutral((float)brightness / 100f, (float)contrast / 100f, (float)temperature / 100f); + } + + public static string? WhatTheDisplayCannotHold(ChannelMix mix, ColourVisionMode correction) + { + return WhatTheDisplayCannotHold(mix, correction, 0); + } + + public static string? WhatTheDisplayCannotHold(ChannelMix mix, ColourVisionMode correction, int hue) + { + bool num = mix != null && !mix.IsIdentity; + bool flag = correction != ColourVisionMode.Off; + List list = new List(); + if (flag) + { + list.Add("the colour help you turned on"); + } + if (num) + { + list.Add("the colour shift in this look"); + } + if (hue != 0) + { + list.Add("the hue"); + } + switch (list.Count) + { + case 0: + return null; + case 1: + return list[0]; + case 2: + return list[0] + " and " + list[1]; + default: + return string.Join(", ", list.GetRange(0, list.Count - 1)) + ", and " + list[list.Count - 1]; + } + } +} diff --git a/VibranceHud/DisplayPreset.cs b/VibranceHud/DisplayPreset.cs new file mode 100644 index 0000000..3c63792 --- /dev/null +++ b/VibranceHud/DisplayPreset.cs @@ -0,0 +1,51 @@ +namespace VibranceHud; + +public sealed record DisplayPreset(string Name, string Subtitle, int Saturation, int Vibrance, int Brightness, int Gamma, int Contrast, int Temperature, string Glyph, string Art, int Highlights = 0, int Shadows = 0, bool NightVision = false, ColourVisionMode ColourVision = ColourVisionMode.Off, int Blacks = 0, int Whites = 0, int ShadowTint = 0, int HighlightTint = 0, ChannelMix? Mix = null, int Hue = 0, int RedGain = 100, int GreenGain = 100, int BlueGain = 100, SaturationMetric Formula = SaturationMetric.Rec709, int Darken = 0, int DarkenHue = 120, int HueTurn = 0, int HueTurnAmount = 100, int HueComplement = 0) +{ + public ChannelMix MixOrIdentity => Mix ?? ChannelMix.Identity; + + public ColourDepth Depth() + { + return new ColourDepth(Formula, Darken, DarkenHue, HueTurn, HueTurnAmount, HueComplement); + } + + public bool Matches(int saturation, int vibrance, int brightness, int gamma, int contrast, int temperature, int highlights, int shadows, bool nightVision) + { + if (Saturation == saturation && Vibrance == vibrance && Brightness == brightness && Gamma == gamma && Contrast == contrast && Temperature == temperature && Highlights == highlights && Shadows == shadows) + { + return NightVision == nightVision; + } + return false; + } + + public bool MatchesWithGrade(int saturation, int vibrance, int brightness, int gamma, int contrast, int temperature, int highlights, int shadows, bool nightVision, int blacks, int whites, int shadowTint, int highlightTint, ChannelMix? mix = null, int hue = 0, int redGain = 100, int greenGain = 100, int blueGain = 100, ColourDepth? depth = null) + { + if (Matches(saturation, vibrance, brightness, gamma, contrast, temperature, highlights, shadows, nightVision) && Blacks == blacks && Whites == whites && ShadowTint == shadowTint && HighlightTint == highlightTint && MixOrIdentity.Near(mix ?? ChannelMix.Identity) && Hue == hue && RedGain == redGain && GreenGain == greenGain && BlueGain == blueGain) + { + return SameDepth(Depth(), depth ?? ColourDepth.Neutral); + } + return false; + } + + private static bool SameDepth(ColourDepth a, ColourDepth b) + { + if (!a.IsNeutral || !b.IsNeutral) + { + return a.Clamped() == b.Clamped(); + } + return true; + } + + public ToneSettings GradeOf(ToneSettings current) + { + return current with + { + Highlights = Highlights, + Shadows = Shadows, + Blacks = Blacks, + Whites = Whites, + ShadowTint = ShadowTint, + HighlightTint = HighlightTint + }; + } +} diff --git a/VibranceHud/DownloadHelper.cs b/VibranceHud/DownloadHelper.cs new file mode 100644 index 0000000..4518f4d --- /dev/null +++ b/VibranceHud/DownloadHelper.cs @@ -0,0 +1,113 @@ +using System; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading; +using System.Threading.Tasks; + +namespace VibranceHud; + +internal static class DownloadHelper +{ + internal static TimeSpan StallLimit { get; set; } = TimeSpan.FromSeconds(60.0); + + internal static TimeSpan HeadersLimit { get; set; } = TimeSpan.FromSeconds(30.0); + + public static async Task DownloadToTempAsync(Uri url, string partialPath, IProgress? progress) + { + _ = 4; + try + { + Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(partialPath))); + long have = (File.Exists(partialPath) ? new FileInfo(partialPath).Length : 0); + using HttpClient client = new HttpClient + { + Timeout = Timeout.InfiniteTimeSpan + }; + client.DefaultRequestHeaders.UserAgent.ParseAdd(UpdateService.UpdaterUserAgent); + using HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url); + if (have > 0) + { + request.Headers.Range = new RangeHeaderValue(have, null); + } + HttpResponseMessage httpResponseMessage; + using (CancellationTokenSource headers = new CancellationTokenSource(HeadersLimit)) + { + try + { + httpResponseMessage = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, headers.Token); + } + catch (OperationCanceledException) when (headers.IsCancellationRequested) + { + UpdateService.LastDownloadError = $"The download server did not answer within {HeadersLimit.TotalSeconds:0} s."; + return null; + } + } + using (httpResponseMessage) + { + if (httpResponseMessage.StatusCode == HttpStatusCode.RequestedRangeNotSatisfiable && have > 0) + { + progress?.Report(100); + return partialPath; + } + httpResponseMessage.EnsureSuccessStatusCode(); + bool resume = false; + long total; + if (httpResponseMessage.StatusCode == HttpStatusCode.PartialContent) + { + ContentRangeHeaderValue contentRange = httpResponseMessage.Content.Headers.ContentRange; + if (have == 0L || contentRange == null || contentRange.From != have) + { + UpdateService.LastDownloadError = $"The download server sent bytes {contentRange?.From}- when asked for {have}-."; + UpdateService.SafeDelete(partialPath); + return null; + } + resume = true; + total = contentRange.Length ?? (-1); + } + else + { + total = httpResponseMessage.Content.Headers.ContentLength ?? (-1); + have = 0L; + } + using Stream source = await httpResponseMessage.Content.ReadAsStreamAsync(); + using FileStream target = new FileStream(partialPath, resume ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.Read); + using CancellationTokenSource headers = new CancellationTokenSource(); + byte[] buffer = new byte[81920]; + long read = 0L; + while (true) + { + headers.CancelAfter(StallLimit); + int n; + try + { + n = await source.ReadAsync(buffer, headers.Token); + } + catch (OperationCanceledException) when (headers.IsCancellationRequested) + { + UpdateService.LastDownloadError = $"The download stalled: no data for {StallLimit.TotalSeconds:0} s after {have + read:N0} bytes."; + return null; + } + if (n <= 0) + { + break; + } + await target.WriteAsync(buffer.AsMemory(0, n)); + await target.FlushAsync(); + read += n; + if (total > 0) + { + progress?.Report((int)Math.Min(100L, (have + read) * 100 / total)); + } + } + return partialPath; + } + } + catch (Exception ex3) + { + UpdateService.LastDownloadError = "Download failed: " + ex3.Message; + return null; + } + } +} diff --git a/VibranceHud/DragTracker.cs b/VibranceHud/DragTracker.cs new file mode 100644 index 0000000..3e57c49 --- /dev/null +++ b/VibranceHud/DragTracker.cs @@ -0,0 +1,44 @@ +namespace VibranceHud; + +internal static class DragTracker +{ + private static int _count; + + private static int _scrollBars; + + public static bool AnyDragging => _count > 0; + + public static bool AnyScrollBarDragging => _scrollBars > 0; + + public static void Begin() + { + _count++; + } + + public static void End() + { + if (_count > 0) + { + _count--; + } + } + + public static void BeginScrollBar() + { + _scrollBars++; + } + + public static void EndScrollBar() + { + if (_scrollBars > 0) + { + _scrollBars--; + } + } + + internal static void ResetForTest() + { + _count = 0; + _scrollBars = 0; + } +} diff --git a/VibranceHud/DriverVibranceBaseline.cs b/VibranceHud/DriverVibranceBaseline.cs new file mode 100644 index 0000000..51e1a68 --- /dev/null +++ b/VibranceHud/DriverVibranceBaseline.cs @@ -0,0 +1,96 @@ +using System.Collections.Generic; +using VibranceHud.Monitors; + +namespace VibranceHud; + +public static class DriverVibranceBaseline +{ + public const int None = -1; + + public static int Remember(int stored, bool pending, int currentLevel) + { + if (!pending || stored < 0) + { + return Clamp(currentLevel); + } + return stored; + } + + public static int? RestoreOnExit(int stored) + { + if (stored < 0) + { + return null; + } + return Clamp(stored); + } + + public static Dictionary RememberEach(IReadOnlyDictionary stored, bool pending, IEnumerable> current) + { + Dictionary dictionary = new Dictionary(stored); + foreach (var (key, currentLevel) in current) + { + dictionary[key] = Remember(stored.TryGetValue(key, out var value) ? value : (-1), pending, currentLevel); + } + return dictionary; + } + + public static int? RestoreOnExit(string displayId, IReadOnlyDictionary stored, int legacyLevel) + { + if (!stored.TryGetValue(displayId, out var value)) + { + if (stored.Count != 0) + { + return null; + } + return RestoreOnExit(legacyLevel); + } + return RestoreOnExit(value); + } + + public static int? RestoreEveryDisplay(IVibranceController driver, IReadOnlyDictionary stored, int legacyLevel) + { + if (driver is SelectedVibranceController selectedVibranceController) + { + selectedVibranceController.RestoreOwned(); + return null; + } + IReadOnlyList> readOnlyList = driver.ReadEveryDisplayLevel(); + if (readOnlyList.Count == 0) + { + int? result = RestoreOnExit(legacyLevel); + if (result.HasValue) + { + driver.SetLevel(result.Value); + } + return result; + } + int? result2 = null; + for (int i = 0; i < readOnlyList.Count; i++) + { + int? num = RestoreOnExit(readOnlyList[i].Key, stored, legacyLevel); + if (num.HasValue) + { + driver.SetLevelFor(readOnlyList[i].Key, num.Value); + if (i == 0) + { + result2 = num; + } + } + } + return result2; + } + + private static int Clamp(int level) + { + if (level >= 0) + { + if (level <= 100) + { + return level; + } + return 100; + } + return 0; + } +} diff --git a/VibranceHud/DriverVibranceIntent.cs b/VibranceHud/DriverVibranceIntent.cs new file mode 100644 index 0000000..e215301 --- /dev/null +++ b/VibranceHud/DriverVibranceIntent.cs @@ -0,0 +1,37 @@ +using System; + +namespace VibranceHud; + +public static class DriverVibranceIntent +{ + public static int? For(bool userChoseAVibrance, int vibrance, int baseline, bool effectSuspended) + { + if (!userChoseAVibrance) + { + return null; + } + if (effectSuspended) + { + if (!IsARealBaseline(baseline)) + { + return null; + } + return baseline; + } + return Clamp(vibrance); + } + + private static bool IsARealBaseline(int baseline) + { + if (baseline >= 0) + { + return baseline <= 100; + } + return false; + } + + private static int Clamp(int level) + { + return Math.Clamp(level, 0, 100); + } +} diff --git a/VibranceHud/DxCapture.cs b/VibranceHud/DxCapture.cs new file mode 100644 index 0000000..23988f9 --- /dev/null +++ b/VibranceHud/DxCapture.cs @@ -0,0 +1,88 @@ +using System; +using SharpDX; +using SharpDX.DXGI; +using SharpDX.Direct3D11; +using SharpDX.Mathematics.Interop; + +namespace VibranceHud; + +internal sealed class DxCapture : IDisposable +{ + private readonly OutputDuplication _duplication; + + private readonly Texture2D _frameTex; + + private readonly ShaderResourceView _srv; + + private readonly SharpDX.Direct3D11.Device _device; + + public Texture2D Frame => _frameTex; + + public ShaderResourceView FrameView => _srv; + + public DxCapture(SharpDX.Direct3D11.Device device, Output1 output) + { + _device = device; + _duplication = output.DuplicateOutput(device); + RawRectangle desktopBounds = output.Description.DesktopBounds; + int width = desktopBounds.Right - desktopBounds.Left; + int height = desktopBounds.Bottom - desktopBounds.Top; + _frameTex = new Texture2D(device, new Texture2DDescription + { + Width = width, + Height = height, + MipLevels = 1, + ArraySize = 1, + Format = Format.B8G8R8A8_UNorm, + SampleDescription = new SampleDescription(1, 0), + Usage = ResourceUsage.Default, + CpuAccessFlags = CpuAccessFlags.None, + BindFlags = BindFlags.ShaderResource, + OptionFlags = ResourceOptionFlags.None + }); + _srv = new ShaderResourceView(device, _frameTex); + } + + public bool TryCapture() + { + SharpDX.DXGI.Resource desktopResourceOut = null; + try + { + if (_duplication.TryAcquireNextFrame(0, out var frameInfoRef, out desktopResourceOut).Failure) + { + return false; + } + if (frameInfoRef.LastPresentTime == 0L) + { + return false; + } + using (Texture2D source = desktopResourceOut.QueryInterface()) + { + _device.ImmediateContext.CopyResource(source, _frameTex); + } + return true; + } + catch (SharpDXException) + { + return false; + } + finally + { + desktopResourceOut?.Dispose(); + try + { + _duplication.ReleaseFrame(); + } + catch + { + } + } + } + + public void Dispose() + { + _srv.Dispose(); + _frameTex.Dispose(); + _duplication.Dispose(); + } +} diff --git a/VibranceHud/DxDevice.cs b/VibranceHud/DxDevice.cs new file mode 100644 index 0000000..01b6aa8 --- /dev/null +++ b/VibranceHud/DxDevice.cs @@ -0,0 +1,330 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using SharpDX; +using SharpDX.DXGI; +using SharpDX.Direct3D11; +using SharpDX.Mathematics.Interop; + +namespace VibranceHud; + +internal sealed class DxDevice : IDisposable +{ + public sealed class OutputTarget + { + public SwapChain1 SwapChain; + + public RenderTargetView Rtv; + + public Output1 Output; + + public SharpDX.Direct3D11.Device Device; + + public nint Hwnd; + + public int Width; + + public int Height; + } + + private struct WNDCLASSEX + { + public int cbSize; + + public int style; + + public nint lpfnWndProc; + + public int cbClsExtra; + + public int cbWndExtra; + + public nint hInstance; + + public nint hIcon; + + public nint hCursor; + + public nint hbrBackground; + + [MarshalAs(UnmanagedType.LPWStr)] + public string lpszMenuName; + + [MarshalAs(UnmanagedType.LPWStr)] + public string lpszClassName; + + public nint hIconSm; + } + + private delegate nint WndProc(nint hWnd, uint msg, nint wParam, nint lParam); + + private Factory2? _factory; + + private readonly List _devices = new List(); + + private const int WS_POPUP = int.MinValue; + + private const int WS_VISIBLE = 268435456; + + private const int WS_EX_NOACTIVATE = 134217728; + + private const int WS_EX_TOOLWINDOW = 128; + + private const int WS_EX_TRANSPARENT = 32; + + private const int SW_SHOWNOACTIVATE = 4; + + private static readonly WndProc s_wndProc = DefWindowProc; + + private static bool s_classRegistered; + + private const string OverlayClass = "PlexusXDxOverlayWindow"; + + private readonly List _windows = new List(); + + public List Targets { get; } + + public bool IsAvailable => Targets.Count > 0; + + public DxInitFailureKind LastFailure { get; private set; } + + public string LastFailureMessage { get; private set; } = ""; + + public int LastFailureCode { get; private set; } + + private void RecordFailure(SharpDXException ex) + { + (DxInitFailureKind Kind, string Short, string Hint) tuple = DxInitFailureMapper.Map(ex); + DxInitFailureKind item = tuple.Kind; + string item2 = tuple.Short; + LastFailure = item; + LastFailureMessage = item2; + LastFailureCode = ex?.HResult ?? 0; + } + + private void RecordFailure(Exception ex) + { + (DxInitFailureKind Kind, string Short, string Hint) tuple = DxInitFailureMapper.MapGeneric(ex); + DxInitFailureKind item = tuple.Kind; + string item2 = tuple.Short; + LastFailure = item; + LastFailureMessage = item2; + LastFailureCode = (ex?.InnerException as SharpDXException)?.HResult ?? ex?.HResult ?? 0; + } + + [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern ushort RegisterClassEx(ref WNDCLASSEX lpwcx); + + [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern nint CreateWindowEx(int dwExStyle, string lpClassName, string lpWindowName, int dwStyle, int x, int y, int nWidth, int nHeight, nint hWndParent, nint hMenu, nint hInstance, nint lpParam); + + [DllImport("user32.dll")] + private static extern nint DefWindowProc(nint hWnd, uint msg, nint wParam, nint lParam); + + [DllImport("user32.dll")] + private static extern bool ShowWindow(nint hWnd, int nCmdShow); + + [DllImport("user32.dll")] + private static extern bool DestroyWindow(nint hWnd); + + [DllImport("kernel32.dll")] + private static extern nint GetModuleHandle(string? lpModuleName); + + public DxDevice() + { + Targets = new List(); + try + { + _factory = new Factory2(); + EnsureWindowClass(); + int num = 0; + int num2 = 0; + while (true) + { + Adapter1 adapter; + try + { + adapter = _factory.GetAdapter1(num2); + } + catch (SharpDXException) + { + break; + } + num++; + using (adapter) + { + SharpDX.Direct3D11.Device device; + try + { + device = new SharpDX.Direct3D11.Device(adapter, DeviceCreationFlags.BgraSupport); + } + catch (SharpDXException ex2) + { + RecordFailure(ex2); + goto end_IL_0063; + } + catch (Exception ex3) + { + RecordFailure(ex3); + goto end_IL_0063; + } + int count = Targets.Count; + try + { + CreateSwapChainsForOutputs(adapter, device); + } + catch (SharpDXException ex4) + { + RecordFailure(ex4); + } + catch (Exception ex5) + { + RecordFailure(ex5); + } + if (Targets.Count > count) + { + _devices.Add(device); + } + else + { + device.Dispose(); + } + end_IL_0063:; + } + num2++; + } + if (num == 0) + { + LastFailure = DxInitFailureKind.NoCompatibleAdapter; + LastFailureMessage = "No GPU with a usable driver was found"; + } + else if (Targets.Count == 0 && LastFailure == DxInitFailureKind.None) + { + LastFailure = DxInitFailureKind.NoOutputs; + LastFailureMessage = "No usable display output was found"; + } + if (Targets.Count == 0) + { + Dispose(); + } + } + catch (SharpDXException ex6) + { + RecordFailure(ex6); + Dispose(); + } + catch (Exception ex7) + { + RecordFailure(ex7); + Dispose(); + } + } + + private static void EnsureWindowClass() + { + if (!s_classRegistered) + { + WNDCLASSEX lpwcx = new WNDCLASSEX + { + cbSize = Marshal.SizeOf(), + style = 0, + lpfnWndProc = Marshal.GetFunctionPointerForDelegate(s_wndProc), + hInstance = GetModuleHandle(null), + lpszClassName = "PlexusXDxOverlayWindow" + }; + RegisterClassEx(ref lpwcx); + s_classRegistered = true; + } + } + + private void CreateSwapChainsForOutputs(Adapter1 adapter, SharpDX.Direct3D11.Device device) + { + Output[] outputs = adapter.Outputs; + foreach (Output output in outputs) + { + Output1 output2; + try + { + output2 = output.QueryInterface(); + } + catch + { + output.Dispose(); + continue; + } + RawRectangle desktopBounds = output2.Description.DesktopBounds; + int num = desktopBounds.Right - desktopBounds.Left; + int num2 = desktopBounds.Bottom - desktopBounds.Top; + if (num <= 0 || num2 <= 0) + { + output2.Dispose(); + output.Dispose(); + continue; + } + nint num3 = CreateWindowEx(134217888, "PlexusXDxOverlayWindow", "PlexusX Overlay", -1879048192, desktopBounds.Left, desktopBounds.Top, num, num2, IntPtr.Zero, IntPtr.Zero, GetModuleHandle(null), IntPtr.Zero); + if (num3 == IntPtr.Zero) + { + output2.Dispose(); + output.Dispose(); + continue; + } + _windows.Add(num3); + ShowWindow(num3, 4); + SwapChainDescription1 description = new SwapChainDescription1 + { + Width = num, + Height = num2, + Format = Format.B8G8R8A8_UNorm, + Stereo = false, + SampleDescription = new SampleDescription(1, 0), + Usage = Usage.RenderTargetOutput, + BufferCount = 2, + Scaling = Scaling.Stretch, + SwapEffect = SwapEffect.FlipSequential, + AlphaMode = AlphaMode.Ignore, + Flags = SwapChainFlags.None + }; + SwapChain1 swapChain = new SwapChain1(_factory, device, num3, ref description); + using (Texture2D resource = swapChain.GetBackBuffer(0)) + { + RenderTargetView rtv = new RenderTargetView(device, resource); + Targets.Add(new OutputTarget + { + SwapChain = swapChain, + Rtv = rtv, + Output = output2, + Device = device, + Hwnd = num3, + Width = num, + Height = num2 + }); + } + output.Dispose(); + } + } + + public void Dispose() + { + foreach (OutputTarget target in Targets) + { + target.Rtv?.Dispose(); + target.SwapChain?.Dispose(); + target.Output?.Dispose(); + } + Targets.Clear(); + foreach (nint window in _windows) + { + if (window != IntPtr.Zero) + { + DestroyWindow(window); + } + } + _windows.Clear(); + foreach (SharpDX.Direct3D11.Device device in _devices) + { + device.Dispose(); + } + _devices.Clear(); + _factory?.Dispose(); + } +} diff --git a/VibranceHud/DxInitFailureKind.cs b/VibranceHud/DxInitFailureKind.cs new file mode 100644 index 0000000..5b83a0f --- /dev/null +++ b/VibranceHud/DxInitFailureKind.cs @@ -0,0 +1,14 @@ +namespace VibranceHud; + +public enum DxInitFailureKind +{ + None, + NoCompatibleAdapter, + DeviceCreationFailed, + NoOutputs, + DriverIssue, + SdkIssue, + OutOfMemory, + CaptureInUse, + Unknown +} diff --git a/VibranceHud/DxInitFailureMapper.cs b/VibranceHud/DxInitFailureMapper.cs new file mode 100644 index 0000000..cda922b --- /dev/null +++ b/VibranceHud/DxInitFailureMapper.cs @@ -0,0 +1,54 @@ +using System; +using SharpDX; + +namespace VibranceHud; + +public static class DxInitFailureMapper +{ + public static (DxInitFailureKind Kind, string Short, string Hint) Map(int hresult) + { + return hresult switch + { + -2005270526 => (Kind: DxInitFailureKind.NoOutputs, Short: "No display found", Hint: "Make sure your monitor is plugged in and Windows is fully loaded before opening PlexusX."), + -2005270524 => (Kind: DxInitFailureKind.DriverIssue, Short: "Display driver doesn't support DX11", Hint: "Update your GPU driver from the manufacturer's website (nvidia.com / amd.com / intel.com)."), + -2005270523 => (Kind: DxInitFailureKind.DriverIssue, Short: "GPU was reset", Hint: "Your GPU driver restarted. Click Retry - this often works the second time."), + -2005270522 => (Kind: DxInitFailureKind.DriverIssue, Short: "GPU recovered from an error", Hint: "Your GPU recovered from a hang. Click Retry."), + -2005270496 => (Kind: DxInitFailureKind.DriverIssue, Short: "GPU driver crashed", Hint: "Reinstall or update your GPU driver."), + -2005270494 => (Kind: DxInitFailureKind.CaptureInUse, Short: "Another app is capturing this display", Hint: "Close or stop other screen-capture sources (OBS Display Capture, ShadowPlay, overlay tools), then reopen PlexusX."), + -2147024882 => (Kind: DxInitFailureKind.OutOfMemory, Short: "Not enough GPU memory", Hint: "Close other 3D apps (game, browser with hardware accel, recording software) and try again."), + -2005270489 => (Kind: DxInitFailureKind.SdkIssue, Short: "DX11 runtime missing", Hint: "Install the DirectX End-User Runtime from microsoft.com (search 'DirectX End-User Runtime')."), + _ => (Kind: DxInitFailureKind.Unknown, Short: "DX11 init failed", Hint: $"Restart PlexusX to retry. If it keeps failing, report the code 0x{hresult:X} in a bug report."), + }; + } + + public static (DxInitFailureKind Kind, string Short, string Hint) Map(SharpDXException ex) + { + return Map(ex?.HResult ?? 0); + } + + public static (DxInitFailureKind Kind, string Short, string Hint) MapGeneric(Exception ex) + { + if (ex == null) + { + return (Kind: DxInitFailureKind.Unknown, Short: "DX11 init failed", Hint: "Restart PlexusX to retry."); + } + if (ex.InnerException is SharpDXException ex2) + { + return Map(ex2); + } + return (Kind: DxInitFailureKind.Unknown, Short: "DX11 init failed", Hint: "Restart PlexusX to retry. (" + ex.GetType().Name + ")"); + } + + public static string HintForKind(DxInitFailureKind kind) + { + return Map(kind switch + { + DxInitFailureKind.NoOutputs => -2005270526, + DxInitFailureKind.DriverIssue => -2005270524, + DxInitFailureKind.SdkIssue => -2005270489, + DxInitFailureKind.OutOfMemory => -2147024882, + DxInitFailureKind.CaptureInUse => -2005270494, + _ => -2147467259, + }).Hint; + } +} diff --git a/VibranceHud/DxOverlay.cs b/VibranceHud/DxOverlay.cs new file mode 100644 index 0000000..c1819a3 --- /dev/null +++ b/VibranceHud/DxOverlay.cs @@ -0,0 +1,270 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using SharpDX.DXGI; +using SharpDX.Direct3D11; +using SharpDX.Mathematics.Interop; + +namespace VibranceHud; + +public sealed class DxOverlay : ISaturationOverlay, IDisplayOverlay, IDisposable +{ + private sealed class ActiveOutput + { + public DxDevice.OutputTarget Target; + + public DxShader Shader; + + public DxCapture Capture; + } + + private static readonly float[] Identity = new float[25] + { + 1f, 0f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, + 0f, 0f, 1f, 0f, 0f, 0f, 0f, 0f, 1f, 0f, + 0f, 0f, 0f, 0f, 1f + }; + + private const PresentFlags AlphaPremultiplied = PresentFlags.None; + + private const int ActiveSleepMs = 16; + + private const int IdleSleepMs = 250; + + private readonly DxDevice _device; + + private readonly List _active; + + private readonly CancellationTokenSource _cts; + + private readonly Task _renderLoop; + + private readonly object _matrixLock = new object(); + + private float[] _currentMatrix; + + private volatile bool _isRendering; + + public OverlayMode ActiveMode => OverlayMode.Dx; + + public DxInitFailureKind LastFailure { get; private set; } + + public string LastFailureMessage { get; private set; } = ""; + + public int LastFailureCode { get; private set; } + + public bool IsAvailable { get; } + + public bool EffectIsLive => IsAvailable; + + public bool IsRendering => _isRendering; + + public string WhyNothingIsDrawn + { + get + { + if (!IsAvailable) + { + if (!string.IsNullOrEmpty(LastFailureMessage)) + { + return LastFailureMessage; + } + return "DirectX 11 did not start on this PC"; + } + return ""; + } + } + + public DxOverlay() + { + _active = new List(); + _currentMatrix = Identity; + _device = new DxDevice(); + if (!_device.IsAvailable) + { + IsAvailable = false; + LastFailure = _device.LastFailure; + LastFailureMessage = _device.LastFailureMessage; + LastFailureCode = _device.LastFailureCode; + _device.Dispose(); + _device = null; + return; + } + Exception firstFailure = null; + TolerantOutputBuilder.Build(_device.Targets.Count, (int i) => + { + DxDevice.OutputTarget outputTarget = _device.Targets[i]; + DxShader dxShader = null; + try + { + dxShader = new DxShader(outputTarget.Device, outputTarget.Device.ImmediateContext); + DxCapture capture = new DxCapture(outputTarget.Device, outputTarget.Output); + _active.Add(new ActiveOutput + { + Target = outputTarget, + Shader = dxShader, + Capture = capture + }); + } + catch + { + dxShader?.Dispose(); + throw; + } + }, (int i, Exception ex) => + { + if (firstFailure == null) + { + firstFailure = ex; + } + }); + if (_active.Count == 0) + { + (DxInitFailureKind Kind, string Short, string Hint) tuple = DxInitFailureMapper.MapGeneric(firstFailure ?? new InvalidOperationException("No renderable display output")); + DxInitFailureKind item = tuple.Kind; + string item2 = tuple.Short; + LastFailure = item; + LastFailureMessage = item2; + _device.Dispose(); + _device = null; + IsAvailable = false; + } + else + { + _cts = new CancellationTokenSource(); + _renderLoop = Task.Run(() => + { + RenderLoop(_cts.Token); + }); + IsAvailable = true; + } + } + + public void Apply(float[] matrix) + { + if (!IsAvailable) + { + SayNothingIsDrawn(); + return; + } + lock (_matrixLock) + { + _currentMatrix = (float[])matrix.Clone(); + } + } + + public void Clear() + { + if (!IsAvailable) + { + SayNothingIsDrawn(); + } + else + { + Apply(Identity); + } + } + + private void SayNothingIsDrawn() + { + ColourTrace.Refused("SCREEN EFFECT", WhyNothingIsDrawn); + } + + public void Dispose() + { + if (!IsAvailable) + { + return; + } + _cts.Cancel(); + try + { + _renderLoop.Wait(TimeSpan.FromSeconds(2.0)); + } + catch + { + } + foreach (ActiveOutput item in _active) + { + item.Capture.Dispose(); + item.Shader.Dispose(); + } + _active.Clear(); + _device.Dispose(); + } + + private void RenderLoop(CancellationToken ct) + { + RawColor4 colorRGBA = new RawColor4(0f, 0f, 0f, 0f); + bool flag = false; + while (!ct.IsCancellationRequested) + { + float[] currentMatrix; + lock (_matrixLock) + { + currentMatrix = _currentMatrix; + } + if (IsIdentityMatrix(currentMatrix)) + { + if (!flag) + { + foreach (DxDevice.OutputTarget target2 in _device.Targets) + { + DeviceContext immediateContext = target2.Device.ImmediateContext; + immediateContext.OutputMerger.SetRenderTargets(target2.Rtv); + immediateContext.ClearRenderTargetView(target2.Rtv, colorRGBA); + target2.SwapChain.Present(1, PresentFlags.None); + } + flag = true; + _isRendering = false; + } + Thread.Sleep(250); + continue; + } + flag = false; + _isRendering = true; + foreach (ActiveOutput item in _active) + { + DxDevice.OutputTarget target = item.Target; + DxCapture capture = item.Capture; + DxShader shader = item.Shader; + DeviceContext immediateContext2 = target.Device.ImmediateContext; + if (!shader.ApplyMatrix(currentMatrix)) + { + immediateContext2.OutputMerger.SetRenderTargets(target.Rtv); + immediateContext2.ClearRenderTargetView(target.Rtv, colorRGBA); + target.SwapChain.Present(1, PresentFlags.None); + _isRendering = false; + } + else + { + capture.TryCapture(); + immediateContext2.OutputMerger.SetRenderTargets(target.Rtv); + immediateContext2.ClearRenderTargetView(target.Rtv, colorRGBA); + immediateContext2.Rasterizer.SetViewport(0f, 0f, target.Width, target.Height); + shader.Bind(capture.FrameView); + shader.Draw(); + target.SwapChain.Present(1, PresentFlags.None); + } + } + Thread.Sleep(16); + } + } + + private static bool IsIdentityMatrix(float[] m) + { + if (m == Identity) + { + return true; + } + for (int i = 0; i < 25; i++) + { + if (Math.Abs(m[i] - Identity[i]) > 0.0001f) + { + return false; + } + } + return true; + } +} diff --git a/VibranceHud/DxOverlayGate.cs b/VibranceHud/DxOverlayGate.cs new file mode 100644 index 0000000..f0b0f65 --- /dev/null +++ b/VibranceHud/DxOverlayGate.cs @@ -0,0 +1,38 @@ +using System; + +namespace VibranceHud; + +public sealed class DxOverlayGate +{ + private readonly Func _qualityColour; + + private readonly Func _renderPathVerified; + + public static bool RenderPathVerified => false; + + public bool IsOpen + { + get + { + try + { + return _qualityColour() && _renderPathVerified(); + } + catch + { + return false; + } + } + } + + public DxOverlayGate(Func qualityColour) + : this(qualityColour, () => RenderPathVerified) + { + } + + internal DxOverlayGate(Func qualityColour, Func renderPathVerified) + { + _qualityColour = qualityColour ?? ((Func)(() => false)); + _renderPathVerified = renderPathVerified ?? ((Func)(() => RenderPathVerified)); + } +} diff --git a/VibranceHud/DxShader.cs b/VibranceHud/DxShader.cs new file mode 100644 index 0000000..1a26f6e --- /dev/null +++ b/VibranceHud/DxShader.cs @@ -0,0 +1,131 @@ +using System; +using System.IO; +using System.Reflection; +using SharpDX.D3DCompiler; +using SharpDX.DXGI; +using SharpDX.Direct3D; +using SharpDX.Direct3D11; + +namespace VibranceHud; + +internal sealed class DxShader : IDisposable +{ + private readonly VertexShader _vs; + + private readonly PixelShader _ps; + + private readonly InputLayout _layout; + + private readonly SharpDX.Direct3D11.Buffer _matrixBuffer; + + private readonly SharpDX.Direct3D11.Buffer _vertexBuffer; + + private readonly SamplerState _sampler; + + private readonly DeviceContext _ctx; + + private const int VertexStride = 24; + + public DxShader(SharpDX.Direct3D11.Device device, DeviceContext ctx) + { + _ctx = ctx; + using (ShaderBytecode shaderBytecode = new ShaderBytecode(LoadEmbeddedHLSL())) + { + _ps = new PixelShader(device, shaderBytecode); + } + using (CompilationResult compilationResult = ShaderBytecode.Compile("struct VS_IN { float4 pos:POSITION; float2 uv:TEXCOORD; }; struct VS_OUT { float4 pos:SV_POSITION; float2 uv:TEXCOORD; }; VS_OUT main(VS_IN i) { VS_OUT o; o.pos = i.pos; o.uv = i.uv; return o; }", "main", "vs_5_0")) + { + _vs = new VertexShader(device, compilationResult); + _layout = new InputLayout(device, compilationResult, new InputElement[2] + { + new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), + new InputElement("TEXCOORD", 0, Format.R32G32_Float, 16, 0) + }); + } + _matrixBuffer = new SharpDX.Direct3D11.Buffer(device, new BufferDescription + { + SizeInBytes = 80, + Usage = ResourceUsage.Default, + BindFlags = BindFlags.ConstantBuffer, + CpuAccessFlags = CpuAccessFlags.None + }); + float[] data = new float[36] + { + -1f, 1f, 0f, 1f, 0f, 0f, 1f, 1f, 0f, 1f, + 1f, 0f, -1f, -1f, 0f, 1f, 0f, 1f, 1f, 1f, + 0f, 1f, 1f, 0f, 1f, -1f, 0f, 1f, 1f, 1f, + -1f, -1f, 0f, 1f, 0f, 1f + }; + _vertexBuffer = SharpDX.Direct3D11.Buffer.Create(device, BindFlags.VertexBuffer, data); + _sampler = new SamplerState(device, new SamplerStateDescription + { + Filter = Filter.MinMagMipLinear, + AddressU = TextureAddressMode.Clamp, + AddressV = TextureAddressMode.Clamp, + AddressW = TextureAddressMode.Clamp, + ComparisonFunction = Comparison.Never, + MinimumLod = 0f, + MaximumLod = float.MaxValue + }); + } + + public bool ApplyMatrix(float[] matrix) + { + _ctx.UpdateSubresource(PackForShader(matrix), _matrixBuffer); + return true; + } + + internal static float[] PackForShader(float[] matrix) + { + float[] array = new float[20]; + for (int i = 0; i < 3; i++) + { + array[i * 4] = matrix[i]; + array[i * 4 + 1] = matrix[5 + i]; + array[i * 4 + 2] = matrix[10 + i]; + array[i * 4 + 3] = matrix[20 + i]; + } + return array; + } + + public void Bind(ShaderResourceView capturedFrame) + { + _ctx.InputAssembler.InputLayout = _layout; + _ctx.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; + _ctx.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(_vertexBuffer, 24, 0)); + _ctx.VertexShader.Set(_vs); + _ctx.PixelShader.Set(_ps); + _ctx.PixelShader.SetConstantBuffer(0, _matrixBuffer); + _ctx.PixelShader.SetSampler(0, _sampler); + _ctx.PixelShader.SetShaderResource(0, capturedFrame); + } + + public void Draw() + { + _ctx.Draw(6, 0); + } + + public void Dispose() + { + _vs.Dispose(); + _ps.Dispose(); + _layout.Dispose(); + _matrixBuffer.Dispose(); + _vertexBuffer.Dispose(); + _sampler.Dispose(); + } + + private static byte[] LoadEmbeddedHLSL() + { + using Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("PlexusX.saturation.hlsl"); + if (stream == null) + { + throw new InvalidOperationException("saturation.hlsl not embedded"); + } + using StreamReader streamReader = new StreamReader(stream); + using CompilationResult compilationResult = ShaderBytecode.Compile(streamReader.ReadToEnd(), "main", "ps_5_0"); + byte[] array = new byte[compilationResult.Bytecode.Data.Length]; + Array.Copy(compilationResult.Bytecode.Data, array, array.Length); + return array; + } +} diff --git a/VibranceHud/FlatSlider.cs b/VibranceHud/FlatSlider.cs new file mode 100644 index 0000000..d1a9ca7 --- /dev/null +++ b/VibranceHud/FlatSlider.cs @@ -0,0 +1,487 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; +using VibranceHud.Design; + +namespace VibranceHud; + +public sealed class FlatSlider : Control +{ + private sealed class SliderAccessibleObject : ControlAccessibleObject + { + private readonly FlatSlider _owner; + + public override string? Value => _owner.Value.ToString(); + + public SliderAccessibleObject(FlatSlider owner) + : base(owner) + { + _owner = owner; + } + } + + private sealed class KnobFocusRing + { + private readonly FlatSlider _owner; + + private Control? _parent; + + private bool _shown; + + private Point _at; + + internal bool Shown => _shown; + + public KnobFocusRing(FlatSlider owner) + { + _owner = owner; + } + + public void Rehook() + { + Unhook(); + _parent = _owner.Parent; + if (_parent != null) + { + _parent.Paint += OnParentPaint; + } + } + + public void Release() + { + Unhook(); + } + + private void Unhook() + { + if (_parent != null) + { + _parent.Paint -= OnParentPaint; + } + _parent = null; + } + + public void Show(bool show, Point knob) + { + if (show != _shown || (show && !(knob == _at))) + { + if (_shown) + { + InvalidateAround(_at); + } + _shown = show; + _at = knob; + if (_shown) + { + InvalidateAround(_at); + } + } + } + + private void InvalidateAround(Point knob) + { + if (_parent != null && !_parent.IsDisposed) + { + int num = (int)Math.Ceiling(_owner.FocusReach()) + 2; + _parent.Invalidate(new Rectangle(_owner.Left + knob.X - num, _owner.Top + knob.Y - num, 2 * num, 2 * num)); + } + } + + private void OnParentPaint(object? sender, PaintEventArgs e) + { + if (!_shown || !_owner.Visible || _owner.IsDisposed) + { + return; + } + Graphics graphics = e.Graphics; + GraphicsState gstate = graphics.Save(); + try + { + graphics.ExcludeClip(_owner.Bounds); + graphics.SmoothingMode = SmoothingMode.AntiAlias; + graphics.PixelOffsetMode = PixelOffsetMode.Half; + SliderPaint.FocusRing(graphics, ControlInk.Dpi(_owner), lg: false, _owner.Left + _at.X, _owner.Top + _at.Y); + } + finally + { + graphics.Restore(gstate); + } + } + } + + public const int EdgeInsetPx = 12; + + private int _minimum; + + private int _maximum = 100; + + private int _value; + + private int? _notch; + + private bool _dragging; + + private int _boxInset = -1; + + private readonly KnobFocusRing _ring; + + public static int EdgeInset => Tokens.Scale(12); + + public int? Notch + { + get + { + return _notch; + } + set + { + _notch = value; + Invalidate(); + } + } + + public int Minimum + { + get + { + return _minimum; + } + set + { + _minimum = value; + Invalidate(); + } + } + + public int Maximum + { + get + { + return _maximum; + } + set + { + _maximum = Math.Max(value, _minimum + 1); + Invalidate(); + } + } + + public int Value + { + get + { + return _value; + } + set + { + int num = Math.Clamp(value, _minimum, _maximum); + if (num != _value) + { + _value = num; + Invalidate(); + ValueChanged?.Invoke(this, EventArgs.Empty); + } + } + } + + private int Dpi => ControlInk.Dpi(this); + + private int Pad + { + get + { + if (_boxInset < 0) + { + return EdgeInsetAt(Dpi); + } + return _boxInset; + } + } + + internal bool KeyboardFocusForTest { get; set; } + + internal Point KnobCentreForTest => new Point(XFromValue(_value), Height / 2); + + internal bool FocusRingShownForTest => _ring.Shown; + + public override bool Focused + { + get + { + if (!KeyboardFocusForTest) + { + return base.Focused; + } + return true; + } + } + + protected override bool ShowFocusCues + { + get + { + if (!KeyboardFocusForTest) + { + return base.ShowFocusCues; + } + return true; + } + } + + public event EventHandler? ValueChanged; + + public static int EdgeInsetAt(int dpi) + { + return Tokens.ScaleAt(dpi, 12); + } + + public FlatSlider() + { + _ring = new KnobFocusRing(this); + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + Height = 32; + Cursor = Cursors.Hand; + TabStop = true; + SetStyle(ControlStyles.Selectable, value: true); + AccessibleRole = AccessibleRole.Slider; + } + + protected override void OnGotFocus(EventArgs e) + { + base.OnGotFocus(e); + Invalidate(); + } + + protected override void OnLostFocus(EventArgs e) + { + base.OnLostFocus(e); + Invalidate(); + } + + protected override void OnParentChanged(EventArgs e) + { + base.OnParentChanged(e); + _ring.Rehook(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _ring.Release(); + } + base.Dispose(disposing); + } + + protected override void OnEnabledChanged(EventArgs e) + { + base.OnEnabledChanged(e); + Cursor = (Enabled ? Cursors.Hand : Cursors.Default); + if (_dragging) + { + _dragging = false; + DragTracker.End(); + } + Invalidate(); + } + + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + int num; + switch (e.KeyCode) + { + case Keys.Left: + case Keys.Down: + num = -1; + break; + case Keys.Up: + case Keys.Right: + num = 1; + break; + case Keys.Next: + num = -10; + break; + case Keys.Prior: + num = 10; + break; + default: + num = 0; + break; + } + int num2 = num; + if (num2 != 0) + { + Value = Math.Clamp(Value + num2, Minimum, Maximum); + e.Handled = true; + } + else if (e.KeyCode == Keys.Home) + { + Value = Minimum; + e.Handled = true; + } + else if (e.KeyCode == Keys.End) + { + Value = Maximum; + e.Handled = true; + } + } + + internal void TestPressKey(Keys key) + { + OnKeyDown(new KeyEventArgs(key)); + } + + protected override bool IsInputKey(Keys keyData) + { + if ((uint)(keyData - 33) <= 7u) + { + return true; + } + return base.IsInputKey(keyData); + } + + internal bool TestClaimsKey(Keys key) + { + return IsInputKey(key); + } + + protected override AccessibleObject CreateAccessibilityInstance() + { + return new SliderAccessibleObject(this); + } + + public void SetTrackBounds(int x, int y, int width, int height = 32) + { + int num = (_boxInset = EdgeInsetAt(Dpi)); + SetBounds(x - num, y, width + 2 * num, height); + } + + protected override Rectangle GetScaledBounds(Rectangle bounds, SizeF factor, BoundsSpecified specified) + { + Rectangle scaledBounds = base.GetScaledBounds(bounds, factor, specified); + if (_boxInset < 0 || (specified & (BoundsSpecified.X | BoundsSpecified.Width)) != (BoundsSpecified.X | BoundsSpecified.Width)) + { + return scaledBounds; + } + int num = (int)Math.Round((float)(bounds.X + _boxInset) * factor.Width); + int num2 = (int)Math.Round((float)(bounds.Right - _boxInset) * factor.Width); + int num3 = EdgeInsetAt(Dpi); + return new Rectangle(num - num3, scaledBounds.Y, num2 - num + 2 * num3, scaledBounds.Height); + } + + protected override void ScaleControl(SizeF factor, BoundsSpecified specified) + { + base.ScaleControl(factor, specified); + if (_boxInset >= 0 && (specified & (BoundsSpecified.X | BoundsSpecified.Width)) == (BoundsSpecified.X | BoundsSpecified.Width)) + { + _boxInset = EdgeInsetAt(Dpi); + } + } + + private int XFromValue(int value) + { + float num = (float)(value - _minimum) / (float)(_maximum - _minimum); + return Pad + (int)Math.Round(num * (float)(Width - 2 * Pad)); + } + + private int ValueFromX(int x) + { + float value = (float)(x - Pad) / (float)Math.Max(1, Width - 2 * Pad); + return _minimum + (int)Math.Round(Math.Clamp(value, 0f, 1f) * (float)(_maximum - _minimum)); + } + + protected override void OnMouseDown(MouseEventArgs e) + { + base.OnMouseDown(e); + if (e.Button == MouseButtons.Left) + { + _dragging = true; + DragTracker.Begin(); + Value = LandingFromX(e.X); + } + } + + protected override void OnMouseMove(MouseEventArgs e) + { + base.OnMouseMove(e); + if (_dragging) + { + Value = LandingFromX(e.X); + } + } + + private int LandingFromX(int x) + { + return SliderSnap.Land(ValueFromX(x), _minimum, _maximum, _notch); + } + + protected override void OnMouseUp(MouseEventArgs e) + { + base.OnMouseUp(e); + if (_dragging) + { + _dragging = false; + DragTracker.End(); + } + } + + internal int XForTest(int value) + { + return XFromValue(value); + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics graphics = e.Graphics; + int pad = Pad; + if (Width - 2 * pad < 2 || Height < 2) + { + _ring.Show(show: false, Point.Empty); + return; + } + SmoothingMode smoothingMode = graphics.SmoothingMode; + PixelOffsetMode pixelOffsetMode = graphics.PixelOffsetMode; + graphics.SmoothingMode = SmoothingMode.AntiAlias; + graphics.PixelOffsetMode = PixelOffsetMode.Half; + try + { + int dpi = Dpi; + int num = Height / 2; + int num2 = XFromValue(_value); + SliderPaint.Track(graphics, dpi, pad, Width - pad, num); + SliderPaint.Fill(graphics, pad, num2, num, ControlInk.Px(dpi, SliderPaint.FillPx(lg: false)), SliderPaint.FillInk(Enabled)); + int? notch = _notch; + if (notch.HasValue) + { + int valueOrDefault = notch.GetValueOrDefault(); + if (valueOrDefault > _minimum && valueOrDefault < _maximum) + { + SliderPaint.Tick(graphics, dpi, XFromValue(valueOrDefault), num, ControlInk.Px(dpi, SliderPaint.TickPx(lg: false)), Enabled); + } + } + SliderPaint.Knob(graphics, dpi, ControlInk.PxF(dpi, SliderPaint.KnobPx(lg: false)), num2, num, ControlInk.KnobRing, Enabled); + if (Focused && ShowFocusCues) + { + SliderPaint.FocusRing(graphics, dpi, lg: false, num2, num); + _ring.Show(show: true, new Point(num2, num)); + } + else + { + _ring.Show(show: false, Point.Empty); + } + } + finally + { + graphics.SmoothingMode = smoothingMode; + graphics.PixelOffsetMode = pixelOffsetMode; + } + } + + private float FocusReach() + { + return ControlInk.PxF(Dpi, SliderPaint.FocusReachPx(lg: false)); + } +} diff --git a/VibranceHud/FlavourPolicy.cs b/VibranceHud/FlavourPolicy.cs new file mode 100644 index 0000000..a69d2d1 --- /dev/null +++ b/VibranceHud/FlavourPolicy.cs @@ -0,0 +1,15 @@ +namespace VibranceHud; + +public sealed record FlavourPolicy(string Flavour, bool SelfUpdates, bool UsesSignedManifestHash, StartupMechanism Startup, bool OffersElevation, bool TouchesTheTaskbar, string DataFolderName, string ReinstallFrom, string UpdatesLine) +{ + public static FlavourPolicy Current { get; } = For("store"); + + public static FlavourPolicy For(string flavour) + { + if (!(flavour == "store")) + { + return new FlavourPolicy(flavour, SelfUpdates: true, UsesSignedManifestHash: true, StartupMechanism.RunKey, OffersElevation: true, TouchesTheTaskbar: true, "PlexusX", "plexusx.lol", "· checked every two hours"); + } + return new FlavourPolicy("store", SelfUpdates: false, UsesSignedManifestHash: false, StartupMechanism.StartupTask, OffersElevation: false, TouchesTheTaskbar: false, "PlexusX Store", "the Microsoft Store", "· via the Microsoft Store"); + } +} diff --git a/VibranceHud/FlavourWording.cs b/VibranceHud/FlavourWording.cs new file mode 100644 index 0000000..3c4b801 --- /dev/null +++ b/VibranceHud/FlavourWording.cs @@ -0,0 +1,33 @@ +namespace VibranceHud; + +public static class FlavourWording +{ + public static string ModifiedCopyBody(FlavourPolicy p) + { + return "This copy of PlexusX is not the one we published - the file has been changed since it was signed.\n\nInstall a clean copy from " + p.ReinstallFrom + ". If you paid for PlexusX, your licence is untouched and will work as soon as you do."; + } + + public static string ModifiedCopyStatus(FlavourPolicy p) + { + return "This copy of PlexusX has been modified. Reinstall it from " + p.ReinstallFrom + "."; + } + + public static string ModifiedCopyRefusal(FlavourPolicy p) + { + return "This copy of PlexusX has been modified and will not activate. Reinstall from " + p.ReinstallFrom + " - your licence is fine and will work straight away."; + } + + public static string MissingFileBecause(FlavourPolicy p) + { + return "A file PlexusX needs is missing or broken. Install PlexusX again from " + p.ReinstallFrom + " to get it back."; + } + + public static string VerifyCaption(FlavourPolicy p) + { + if (!p.UsesSignedManifestHash) + { + return "The SHA-256 of the PlexusX now running."; + } + return "The SHA-256 of the PlexusX now running. It should match the one on plexusx.lol."; + } +} diff --git a/VibranceHud/Fullscreen/AnyFullScreenWindow.cs b/VibranceHud/Fullscreen/AnyFullScreenWindow.cs new file mode 100644 index 0000000..ae1f7d6 --- /dev/null +++ b/VibranceHud/Fullscreen/AnyFullScreenWindow.cs @@ -0,0 +1,181 @@ +using System; +using System.Drawing; +using System.Runtime.InteropServices; +using System.Text; +using System.Windows.Forms; + +namespace VibranceHud.Fullscreen; + +public static class AnyFullScreenWindow +{ + private struct RECT + { + public int Left; + + public int Top; + + public int Right; + + public int Bottom; + + public Rectangle ToRectangle() + { + return Rectangle.FromLTRB(Left, Top, Right, Bottom); + } + } + + private struct MONITORINFO + { + public int cbSize; + + public RECT rcMonitor; + + public RECT rcWork; + + public uint dwFlags; + } + + private const int QUNS_BUSY = 2; + + private const int QUNS_RUNNING_D3D_FULL_SCREEN = 3; + + private const int DWMWA_EXTENDED_FRAME_BOUNDS = 9; + + private const uint MONITOR_DEFAULTTONEAREST = 2u; + + [DllImport("shell32.dll")] + private static extern int SHQueryUserNotificationState(out int state); + + [DllImport("user32.dll")] + private static extern nint GetForegroundWindow(); + + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool IsWindowVisible(nint hWnd); + + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool IsIconic(nint hWnd); + + [DllImport("user32.dll", CharSet = CharSet.Unicode, EntryPoint = "GetClassNameW")] + private static extern int GetClassName(nint hWnd, StringBuilder className, int maxCount); + + [DllImport("user32.dll")] + private static extern uint GetWindowThreadProcessId(nint hWnd, out uint processId); + + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetWindowRect(nint hWnd, out RECT rect); + + [DllImport("dwmapi.dll")] + private static extern int DwmGetWindowAttribute(nint hWnd, int attribute, out RECT value, int size); + + [DllImport("user32.dll")] + private static extern nint MonitorFromWindow(nint hWnd, uint flags); + + [DllImport("user32.dll", CharSet = CharSet.Unicode, EntryPoint = "GetMonitorInfoW")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetMonitorInfo(nint monitor, ref MONITORINFO info); + + internal static bool ForShellState(int state) + { + if (state != 2) + { + return state == 3; + } + return true; + } + + internal static bool FillsItsMonitor(Rectangle window, Rectangle monitor, bool visible, bool minimized, bool isShellOrDesktop, bool isOwnProcess) + { + if (!visible | minimized | isShellOrDesktop | isOwnProcess) + { + return false; + } + if (monitor.Width <= 0 || monitor.Height <= 0) + { + return false; + } + if (window.Left <= monitor.Left && window.Top <= monitor.Top && window.Right >= monitor.Right) + { + return window.Bottom >= monitor.Bottom; + } + return false; + } + + internal static bool IsShellOrDesktopClass(string? className) + { + switch (className) + { + case "Progman": + case "WorkerW": + case "Shell_TrayWnd": + case "Shell_SecondaryTrayWnd": + return true; + default: + return false; + } + } + + public static bool IsInFront() + { + try + { + if (SHQueryUserNotificationState(out var state) == 0 && ForShellState(state)) + { + return true; + } + return ForegroundFillsItsMonitor(); + } + catch + { + return false; + } + } + + internal static string? ForegroundMonitorDeviceName() + { + try + { + nint foregroundWindow = GetForegroundWindow(); + return (foregroundWindow == IntPtr.Zero) ? null : Screen.FromHandle(foregroundWindow).DeviceName; + } + catch + { + return null; + } + } + + private static bool ForegroundFillsItsMonitor() + { + nint foregroundWindow = GetForegroundWindow(); + if (foregroundWindow == IntPtr.Zero) + { + return false; + } + bool visible = IsWindowVisible(foregroundWindow); + bool minimized = IsIconic(foregroundWindow); + StringBuilder stringBuilder = new StringBuilder(256); + string className = ((GetClassName(foregroundWindow, stringBuilder, stringBuilder.Capacity) > 0) ? stringBuilder.ToString() : null); + GetWindowThreadProcessId(foregroundWindow, out var processId); + bool isOwnProcess = processId != 0 && processId == (uint)Environment.ProcessId; + if (DwmGetWindowAttribute(foregroundWindow, 9, out var value, Marshal.SizeOf()) != 0 && !GetWindowRect(foregroundWindow, out value)) + { + return false; + } + nint num = MonitorFromWindow(foregroundWindow, 2u); + if (num == IntPtr.Zero) + { + return false; + } + MONITORINFO info = new MONITORINFO + { + cbSize = Marshal.SizeOf() + }; + if (!GetMonitorInfo(num, ref info)) + { + return false; + } + return FillsItsMonitor(value.ToRectangle(), info.rcMonitor.ToRectangle(), visible, minimized, IsShellOrDesktopClass(className), isOwnProcess); + } +} diff --git a/VibranceHud/Fullscreen/ExclusiveFullscreenEvidence.cs b/VibranceHud/Fullscreen/ExclusiveFullscreenEvidence.cs new file mode 100644 index 0000000..b695dd7 --- /dev/null +++ b/VibranceHud/Fullscreen/ExclusiveFullscreenEvidence.cs @@ -0,0 +1,131 @@ +using System; +using System.Collections.Generic; +using System.IO; +using Microsoft.Win32; +using VibranceHud.Crosshair; + +namespace VibranceHud.Fullscreen; + +public static class ExclusiveFullscreenEvidence +{ + public const string FullscreenOptimisationsOff = "DISABLEDXMAXIMIZEDWINDOWEDMODE"; + + private const string LayersKey = "Software\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags\\Layers"; + + public static bool MatrixCannotArrive(bool shellSaysD3DFullscreen, string? foregroundProcessName, IEnumerable> appCompatLayers) + { + if (shellSaysD3DFullscreen) + { + return FullscreenOptimisationsAreOffFor(foregroundProcessName, appCompatLayers); + } + return false; + } + + internal static bool FullscreenOptimisationsAreOffFor(string? foregroundProcessName, IEnumerable> appCompatLayers) + { + string text = WithExe(foregroundProcessName); + if (text == null || appCompatLayers == null) + { + return false; + } + foreach (KeyValuePair appCompatLayer in appCompatLayers) + { + if (!string.IsNullOrEmpty(appCompatLayer.Key) && !string.IsNullOrEmpty(appCompatLayer.Value)) + { + string fileName; + try + { + fileName = Path.GetFileName(appCompatLayer.Key); + } + catch + { + continue; + } + if (string.Equals(fileName, text, StringComparison.OrdinalIgnoreCase) && NamesTheToken(appCompatLayer.Value)) + { + return true; + } + } + } + return false; + } + + private static bool NamesTheToken(string layers) + { + string[] array = layers.Split(new char[2] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); + for (int i = 0; i < array.Length; i++) + { + if (string.Equals(array[i], "DISABLEDXMAXIMIZEDWINDOWEDMODE", StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + return false; + } + + private static string? WithExe(string? name) + { + if (string.IsNullOrWhiteSpace(name)) + { + return null; + } + name = name.Trim(); + if (!name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) + { + return name + ".exe"; + } + return name; + } + + public static bool ForThisMachine() + { + try + { + if (!CrosshairService.IsExclusiveFullscreen()) + { + return false; + } + string text = ForegroundWindowProcess.Name(); + if (text == null) + { + return false; + } + return FullscreenOptimisationsAreOffFor(text, ReadLayers()); + } + catch + { + return false; + } + } + + private static IEnumerable> ReadLayers() + { + List> list = new List>(); + Collect(Registry.CurrentUser, list); + Collect(Registry.LocalMachine, list); + return list; + } + + private static void Collect(RegistryKey hive, List> into) + { + try + { + using RegistryKey registryKey = hive.OpenSubKey("Software\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags\\Layers", writable: false); + if (registryKey == null) + { + return; + } + string[] valueNames = registryKey.GetValueNames(); + foreach (string text in valueNames) + { + if (!string.IsNullOrEmpty(text) && registryKey.GetValue(text) is string { Length: >0 } text2) + { + into.Add(new KeyValuePair(text, text2)); + } + } + } + catch + { + } + } +} diff --git a/VibranceHud/Fullscreen/ForegroundWindowProcess.cs b/VibranceHud/Fullscreen/ForegroundWindowProcess.cs new file mode 100644 index 0000000..c025398 --- /dev/null +++ b/VibranceHud/Fullscreen/ForegroundWindowProcess.cs @@ -0,0 +1,37 @@ +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; + +namespace VibranceHud.Fullscreen; + +public static class ForegroundWindowProcess +{ + [DllImport("user32.dll")] + private static extern nint GetForegroundWindow(); + + [DllImport("user32.dll")] + private static extern uint GetWindowThreadProcessId(nint hWnd, out uint processId); + + public static string? Name() + { + try + { + nint foregroundWindow = GetForegroundWindow(); + if (foregroundWindow == IntPtr.Zero) + { + return null; + } + if (GetWindowThreadProcessId(foregroundWindow, out var processId) == 0 || processId == 0) + { + return null; + } + using Process process = Process.GetProcessById((int)processId); + string processName = process.ProcessName; + return string.IsNullOrEmpty(processName) ? null : processName; + } + catch + { + return null; + } + } +} diff --git a/VibranceHud/Fullscreen/FullscreenState.cs b/VibranceHud/Fullscreen/FullscreenState.cs new file mode 100644 index 0000000..fa6897f --- /dev/null +++ b/VibranceHud/Fullscreen/FullscreenState.cs @@ -0,0 +1,215 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace VibranceHud.Fullscreen; + +public sealed class FullscreenState +{ + public static readonly TimeSpan EnterHold = TimeSpan.FromSeconds(2.0); + + private readonly Func _shellSaysD3DFullscreen; + + private readonly Func _foregroundProcessName; + + private readonly HashSet _tracked; + + private readonly Func _nowMs; + + public static readonly TimeSpan LeaveHold = TimeSpan.FromMilliseconds(750.0); + + private long? _candidateSinceMs; + + private string? _candidate; + + private long? _leaveSinceMs; + + private readonly bool _anyWindow; + + private const string UnnamedWindow = "(a full-screen window)"; + + private static readonly string CouldNotTell = new string("(could not tell)".ToCharArray()); + + public bool LeavePending => _leaveSinceMs.HasValue; + + public bool IsExclusiveFullscreen { get; private set; } + + public string? Game + { + get + { + if (!IsExclusiveFullscreen) + { + return null; + } + return _candidate; + } + } + + public bool CandidatePending + { + get + { + if (_candidate != null) + { + return !IsExclusiveFullscreen; + } + return false; + } + } + + public string? LatchedGame { get; private set; } + + public FullscreenState(Func shellSaysD3DFullscreen, Func foregroundProcessName, IEnumerable trackedProcessNames, Func monotonicMs) + : this(shellSaysD3DFullscreen, foregroundProcessName, trackedProcessNames, monotonicMs, anyWindow: false) + { + } + + private FullscreenState(Func shellSaysD3DFullscreen, Func foregroundProcessName, IEnumerable trackedProcessNames, Func monotonicMs, bool anyWindow) + { + _anyWindow = anyWindow; + _shellSaysD3DFullscreen = shellSaysD3DFullscreen ?? throw new ArgumentNullException("shellSaysD3DFullscreen"); + _foregroundProcessName = foregroundProcessName ?? throw new ArgumentNullException("foregroundProcessName"); + _tracked = new HashSet(trackedProcessNames ?? Enumerable.Empty(), StringComparer.OrdinalIgnoreCase); + _nowMs = monotonicMs ?? throw new ArgumentNullException("monotonicMs"); + } + + public static FullscreenState ForAnyFullScreenWindow(Func foregroundFillsTheScreen, Func foregroundProcessName, Func monotonicMs) + { + return new FullscreenState(foregroundFillsTheScreen, foregroundProcessName, Array.Empty(), monotonicMs, anyWindow: true); + } + + public bool GameClosed(string? processName) + { + string text = WithoutExe(processName); + if (LatchedGame == null || text == null || !string.Equals(text, LatchedGame, StringComparison.OrdinalIgnoreCase)) + { + return false; + } + LatchedGame = null; + return true; + } + + public bool Poll() + { + string text = CandidateNow(); + if ((object)text == CouldNotTell) + { + return IsExclusiveFullscreen; + } + if (text == null) + { + if (_anyWindow && IsExclusiveFullscreen) + { + long valueOrDefault = _leaveSinceMs.GetValueOrDefault(); + if (!_leaveSinceMs.HasValue) + { + valueOrDefault = _nowMs(); + _leaveSinceMs = valueOrDefault; + } + if (_nowMs() - _leaveSinceMs.Value < (long)LeaveHold.TotalMilliseconds) + { + return true; + } + } + _leaveSinceMs = null; + _candidate = null; + _candidateSinceMs = null; + IsExclusiveFullscreen = false; + return false; + } + _leaveSinceMs = null; + if (IsExclusiveFullscreen && string.Equals(text, _candidate, StringComparison.OrdinalIgnoreCase)) + { + if (!_anyWindow) + { + LatchedGame = _candidate; + } + return true; + } + if (_anyWindow && IsExclusiveFullscreen) + { + _candidate = text; + return true; + } + if (!string.Equals(text, _candidate, StringComparison.OrdinalIgnoreCase)) + { + _candidate = text; + _candidateSinceMs = _nowMs(); + return IsExclusiveFullscreen = false; + } + if (!_candidateSinceMs.HasValue || _nowMs() - _candidateSinceMs.Value < (long)EnterHold.TotalMilliseconds) + { + return IsExclusiveFullscreen = false; + } + if (!_anyWindow) + { + LatchedGame = _candidate; + } + return IsExclusiveFullscreen = true; + } + + private string? CandidateNow() + { + try + { + if (!_shellSaysD3DFullscreen()) + { + if (LatchedGame != null && string.Equals(TrackedForeground(), LatchedGame, StringComparison.OrdinalIgnoreCase)) + { + LatchedGame = null; + } + return null; + } + return TrackedForeground(); + } + catch + { + return null; + } + } + + private string? TrackedForeground() + { + string name; + try + { + name = _foregroundProcessName(); + } + catch when (!_anyWindow) + { + return CouldNotTell; + } + string text = WithoutExe(name); + if (_anyWindow) + { + return text ?? "(a full-screen window)"; + } + if (text == null) + { + return CouldNotTell; + } + if (!_tracked.Contains(text)) + { + return null; + } + return text; + } + + private static string? WithoutExe(string? name) + { + if (string.IsNullOrEmpty(name)) + { + return null; + } + if (name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) + { + name = name.Substring(0, name.Length - 4); + } + if (name.Length != 0) + { + return name; + } + return null; + } +} diff --git a/VibranceHud/Fullscreen/FullscreenWatch.cs b/VibranceHud/Fullscreen/FullscreenWatch.cs new file mode 100644 index 0000000..d7c96f7 --- /dev/null +++ b/VibranceHud/Fullscreen/FullscreenWatch.cs @@ -0,0 +1,266 @@ +using System; +using System.Windows.Forms; +using VibranceHud.Crosshair; +using VibranceHud.Games; + +namespace VibranceHud.Fullscreen; + +public sealed class FullscreenWatch : IDisposable +{ + public const int BackstopTickMs = 60000; + + public static readonly TimeSpan RepollDelay = FullscreenState.EnterHold + TimeSpan.FromMilliseconds(100.0); + + public static readonly TimeSpan LeaveRepollDelay = FullscreenState.LeaveHold + TimeSpan.FromMilliseconds(100.0); + + private readonly FullscreenState _state; + + private readonly Func, WinEventListener> _listenerFactory; + + private readonly bool _realTimers; + + private WinEventListener? _listener; + + private Timer? _repollTimer; + + private Timer? _backstopTimer; + + private bool _last; + + private bool _started; + + private bool _disposed; + + internal Func? FullscreenAllowed { get; set; } + + public string? LatchedGame => _state.LatchedGame; + + internal bool RepollArmed { get; private set; } + + internal bool HookRefused + { + get + { + if (_listener != null) + { + return !_listener.IsHooked; + } + return false; + } + } + + internal bool BackstopArmed { get; private set; } + + public event Action? Changed; + + public event Action? LatchChanged; + + public void GameClosed(string? processName) + { + if (!_disposed && _state.GameClosed(processName)) + { + Raise(LatchChanged, _state.LatchedGame); + } + } + + public FullscreenWatch(FullscreenState state) + : this(state, DefaultListener, realTimers: true) + { + } + + internal FullscreenWatch(FullscreenState state, Func, WinEventListener> listenerFactory, bool realTimers) + { + _state = state ?? throw new ArgumentNullException("state"); + _listenerFactory = listenerFactory ?? throw new ArgumentNullException("listenerFactory"); + _realTimers = realTimers; + } + + private static WinEventListener DefaultListener(Action onForeground) + { + return new WinEventListener(3u, 3u, onForeground); + } + + public static FullscreenWatch ForThisMachine() + { + return new FullscreenWatch(new FullscreenState(CrosshairService.IsExclusiveFullscreen, ForegroundWindowProcess.Name, SupportedGames.AllProcessNames, () => Environment.TickCount64)); + } + + public static FullscreenWatch ForAnyFullScreenWindow() + { + return new FullscreenWatch(FullscreenState.ForAnyFullScreenWindow(AnyFullScreenWindow.IsInFront, ForegroundWindowProcess.Name, () => Environment.TickCount64)); + } + + public void Start() + { + if (_disposed || _started) + { + return; + } + _started = true; + _listener = _listenerFactory((nint _) => + { + Poll(); + }); + Poll(); + BackstopArmed = true; + if (_realTimers) + { + _backstopTimer = new Timer + { + Interval = 60000 + }; + _backstopTimer.Tick += (object? _, EventArgs _) => + { + Poll(); + }; + _backstopTimer.Start(); + } + } + + public void PollNow() + { + Poll(); + } + + public void Stop() + { + _started = false; + BackstopArmed = false; + _listener?.Dispose(); + _listener = null; + DisarmRepoll(); + if (_repollTimer != null) + { + _repollTimer.Dispose(); + _repollTimer = null; + } + if (_backstopTimer != null) + { + _backstopTimer.Stop(); + _backstopTimer.Dispose(); + _backstopTimer = null; + } + } + + internal void TickForTest() + { + Poll(); + } + + internal void FireRepoll() + { + DisarmRepoll(); + Poll(); + } + + private void Poll() + { + if (_disposed) + { + return; + } + string latchedGame = _state.LatchedGame; + bool flag = _state.Poll(); + if (flag && FullscreenAllowed != null) + { + try + { + flag = FullscreenAllowed(); + } + catch + { + flag = false; + } + } + if (_state.CandidatePending || _state.LeavePending) + { + ArmRepoll(_state.LeavePending); + } + else + { + DisarmRepoll(); + } + if (flag != _last) + { + _last = flag; + Raise(Changed, flag, _state.Game); + } + if (!string.Equals(latchedGame, _state.LatchedGame, StringComparison.OrdinalIgnoreCase)) + { + Raise(LatchChanged, _state.LatchedGame); + } + } + + private static void Raise(Action? handlers, bool now, string? game) + { + if (handlers == null) + { + return; + } + Delegate[] invocationList = handlers.GetInvocationList(); + foreach (Delegate obj in invocationList) + { + try + { + ((Action)obj)(now, game); + } + catch + { + } + } + } + + private static void Raise(Action? handlers, string? game) + { + if (handlers == null) + { + return; + } + Delegate[] invocationList = handlers.GetInvocationList(); + foreach (Delegate obj in invocationList) + { + try + { + ((Action)obj)(game); + } + catch + { + } + } + } + + private void ArmRepoll(bool leaving = false) + { + RepollArmed = true; + if (!_realTimers) + { + return; + } + if (_repollTimer == null) + { + _repollTimer = new Timer(); + _repollTimer.Tick += (object? _, EventArgs _) => + { + FireRepoll(); + }; + } + _repollTimer.Interval = (int)(leaving ? LeaveRepollDelay : RepollDelay).TotalMilliseconds; + _repollTimer.Stop(); + _repollTimer.Start(); + } + + private void DisarmRepoll() + { + RepollArmed = false; + _repollTimer?.Stop(); + } + + public void Dispose() + { + if (!_disposed) + { + _disposed = true; + Stop(); + } + } +} diff --git a/VibranceHud/GameChooser.cs b/VibranceHud/GameChooser.cs new file mode 100644 index 0000000..03bf383 --- /dev/null +++ b/VibranceHud/GameChooser.cs @@ -0,0 +1,205 @@ +using System; +using System.Drawing; +using System.Windows.Forms; +using VibranceHud.Controls; +using VibranceHud.Design; +using VibranceHud.Games; + +namespace VibranceHud; + +public sealed class GameChooser : Control +{ + private readonly GameSelection _selection; + + private bool _open; + + private readonly HoverFade _fade; + + private readonly OutsideFocusRing _ring; + + private readonly SignalToolTip _tip = new SignalToolTip(); + + private long _closedAtTicks; + + internal const int TriggerHeight = 32; + + private readonly EventHandler _onSelectionChanged; + + public GameChooser(GameSelection selection) + { + _selection = selection; + _fade = new HoverFade(this); + _ring = new OutsideFocusRing(this, () => ControlInk.PxF(ControlInk.Dpi(this), 4f)); + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.Selectable | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + RefreshAvailability(); + Height = Tokens.Scale(32); + Font = Fonts.Body; + TabStop = true; + AccessibleRole = AccessibleRole.ComboBox; + AccessibleName = "Game"; + _onSelectionChanged = (object? _, EventArgs _) => + { + Invalidate(); + }; + _selection.Changed += _onSelectionChanged; + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _selection.Changed -= _onSelectionChanged; + _tip.Dispose(); + _ring.Release(); + } + base.Dispose(disposing); + } + + protected override void OnGotFocus(EventArgs e) + { + base.OnGotFocus(e); + Invalidate(); + } + + protected override void OnLostFocus(EventArgs e) + { + base.OnLostFocus(e); + Invalidate(); + } + + protected override void OnParentChanged(EventArgs e) + { + base.OnParentChanged(e); + _ring.Rehook(); + } + + protected override void OnMouseEnter(EventArgs e) + { + base.OnMouseEnter(e); + _fade.Set(hot: true); + Invalidate(); + } + + protected override void OnMouseLeave(EventArgs e) + { + base.OnMouseLeave(e); + _fade.Set(hot: false); + Invalidate(); + } + + protected override void OnMouseDown(MouseEventArgs e) + { + base.OnMouseDown(e); + if (e.Button == MouseButtons.Left && Environment.TickCount64 - _closedAtTicks >= 200) + { + Open(); + } + } + + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + if (e.KeyCode == Keys.Return || e.KeyCode == Keys.Space || e.KeyCode == Keys.Down || e.KeyCode == Keys.F4) + { + Open(); + e.Handled = true; + } + } + + private void Open() + { + if (!_selection.NothingInstalled) + { + ToolStripDropDown menu = BuildMenu(); + menu.Closed += (object? _, ToolStripDropDownClosedEventArgs _) => + { + _open = false; + _closedAtTicks = Environment.TickCount64; + Invalidate(); + BeginInvoke(menu.Dispose); + }; + _open = true; + Invalidate(); + SignalMenu.ShowUnder(menu, this); + } + } + + internal ToolStripDropDown BuildMenuForTest() + { + return BuildMenu(); + } + + private ToolStripDropDown BuildMenu() + { + ToolStripDropDown toolStripDropDown = SignalMenu.SelectList(this); + int dpi = ControlInk.Dpi(this); + int width = SignalMenu.RowWidth(this); + int rowH = SignalMenu.RowHeight(dpi, Fonts.Body); + foreach (DetectedGame item in _selection.Installed) + { + SupportedGame game = item.Game; + toolStripDropDown.Items.Add(Item(game.DisplayName, game.Id, _selection.CurrentId == game.Id, width, rowH)); + } + toolStripDropDown.Items.Add(SignalMenu.Separator(width, dpi)); + toolStripDropDown.Items.Add(Item("Desktop", null, _selection.CurrentId == null, width, rowH)); + return toolStripDropDown; + } + + private ToolStripMenuItem Item(string text, string? id, bool chosen, int width, int rowH) + { + ToolStripMenuItem toolStripMenuItem = SignalMenu.SelectItem(text, chosen, width, rowH); + toolStripMenuItem.Click += (object? _, EventArgs _) => + { + _selection.Select(id); + }; + return toolStripMenuItem; + } + + private void RefreshAvailability() + { + bool nothingInstalled = _selection.NothingInstalled; + Cursor = (nothingInstalled ? Cursors.Default : Cursors.Hand); + string text = (nothingInstalled ? "No supported game found on this PC. PlexusX finds supported games by itself once they are installed." : ""); + if (_tip.GetToolTip(this) != text) + { + _tip.SetToolTip(this, text); + } + } + + protected override void OnPaint(PaintEventArgs e) + { + RefreshAvailability(); + string text; + bool placeholder; + if (!_selection.NothingInstalled) + { + SupportedGame current = _selection.Current; + if ((object)current == null) + { + text = "Desktop"; + placeholder = false; + } + else + { + string displayName = current.DisplayName; + placeholder = false; + text = displayName; + } + } + else + { + text = "No games found"; + placeholder = true; + } + SignalMenu.PaintTrigger(e.Graphics, ClientSize, ControlInk.Dpi(this), Font, text, placeholder, _open, _fade.Value, Enabled, !_selection.NothingInstalled); + if (Focused && ShowFocusCues) + { + _ring.Show(Enabled); + } + else + { + _ring.Show(show: false); + } + } +} diff --git a/VibranceHud/GameHubOptions.cs b/VibranceHud/GameHubOptions.cs new file mode 100644 index 0000000..1698606 --- /dev/null +++ b/VibranceHud/GameHubOptions.cs @@ -0,0 +1,19 @@ +using System; +using System.Text.Json.Serialization; + +namespace VibranceHud; + +public sealed class GameHubOptions +{ + [JsonPropertyName("graphicsQuality")] + public string GraphicsQuality { get; set; } = ""; + + [JsonPropertyName("fpsCap")] + public int FpsCap { get; set; } + + [JsonPropertyName("effectToggles")] + public string[] EffectToggles { get; set; } = Array.Empty(); + + [JsonPropertyName("tools")] + public string[] Tools { get; set; } = Array.Empty(); +} diff --git a/VibranceHud/GameLookSnapshot.cs b/VibranceHud/GameLookSnapshot.cs new file mode 100644 index 0000000..49ee90d --- /dev/null +++ b/VibranceHud/GameLookSnapshot.cs @@ -0,0 +1,93 @@ +using System.Linq; + +namespace VibranceHud; + +public sealed class GameLookSnapshot +{ + public int? SaturationPercent { get; set; } + + public int? VibrancePercent { get; set; } + + public bool VibranceChosenByUser { get; set; } + + public int BrightnessPercent { get; set; } = 100; + + public int GammaPercent { get; set; } = 100; + + public int ContrastPercent { get; set; } = 100; + + public int? Temperature { get; set; } + + public ToneSettings? Tone { get; set; } + + public float[]? Mix { get; set; } + + public int Hue { get; set; } + + public int RedGain { get; set; } = 100; + + public int GreenGain { get; set; } = 100; + + public int BlueGain { get; set; } = 100; + + public ColourVisionMode ColourVision { get; set; } + + public bool ColourVisionFromPreset { get; set; } + + public string ColourPresetName { get; set; } = ""; + + public static GameLookSnapshot Take(AppSettings s) + { + return new GameLookSnapshot + { + SaturationPercent = s.SaturationPercent, + VibrancePercent = s.VibrancePercent, + VibranceChosenByUser = s.VibranceChosenByUser, + BrightnessPercent = s.BrightnessPercent, + GammaPercent = s.GammaPercent, + ContrastPercent = s.ContrastPercent, + Temperature = s.Temperature, + Tone = s.Tone, + Mix = s.Mix?.ToArray(), + Hue = s.Hue, + RedGain = s.RedGain, + GreenGain = s.GreenGain, + BlueGain = s.BlueGain, + ColourVision = s.ColourVision, + ColourVisionFromPreset = s.ColourVisionFromPreset, + ColourPresetName = (s.ColourPresetName ?? "") + }; + } + + public void PutBack(AppSettings s) + { + s.SaturationPercent = SaturationPercent; + s.VibrancePercent = VibrancePercent; + s.VibranceChosenByUser = VibranceChosenByUser; + s.BrightnessPercent = BrightnessPercent; + s.GammaPercent = GammaPercent; + s.ContrastPercent = ContrastPercent; + s.Temperature = Temperature; + s.Tone = Tone; + s.Mix = Mix?.ToArray(); + s.Hue = Hue; + s.RedGain = RedGain; + s.GreenGain = GreenGain; + s.BlueGain = BlueGain; + s.ColourVision = ColourVision; + s.ColourVisionFromPreset = ColourVisionFromPreset; + s.ColourPresetName = ColourPresetName; + } + + public static bool PutBackOwed(AppSettings s) + { + GameLookSnapshot lookBeforeGame = s.LookBeforeGame; + if (lookBeforeGame == null) + { + return false; + } + lookBeforeGame.PutBack(s); + s.LookBeforeGame = null; + return true; + } +} diff --git a/VibranceHud/GameProcessWatcher.cs b/VibranceHud/GameProcessWatcher.cs new file mode 100644 index 0000000..ea1e49a --- /dev/null +++ b/VibranceHud/GameProcessWatcher.cs @@ -0,0 +1,304 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; +using VibranceHud.Games; + +namespace VibranceHud; + +public sealed class GameProcessWatcher +{ + public delegate void GameEventHandler(string gameId); + + internal interface IProcessSource + { + IReadOnlyCollection<(int Pid, string Name)> Snapshot(); + + IReadOnlyCollection RunningIds(); + } + + private sealed class NamesOnly : IProcessSource + { + private readonly Func> _names; + + public NamesOnly(Func> names) + { + _names = names; + } + + public IReadOnlyCollection<(int Pid, string Name)> Snapshot() + { + return (from n in _names() + select (-1, n: n)).ToList(); + } + + public IReadOnlyCollection RunningIds() + { + throw new NotSupportedException("a names-only probe has no ids"); + } + } + + internal sealed class SystemProcessSource : IProcessSource + { + public static readonly SystemProcessSource Instance = new SystemProcessSource(); + + public IReadOnlyCollection<(int Pid, string Name)> Snapshot() + { + List<(int, string)> list = new List<(int, string)>(); + Process[] processes = Process.GetProcesses(); + foreach (Process process in processes) + { + try + { + list.Add((process.Id, process.ProcessName)); + } + catch (InvalidOperationException) + { + } + finally + { + process.Dispose(); + } + } + return list; + } + + [DllImport("psapi.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool EnumProcesses([Out] uint[] processIds, uint arraySizeBytes, out uint bytesReturned); + + public IReadOnlyCollection RunningIds() + { + for (int num = 1024; num <= 1048576; num *= 2) + { + uint[] array = new uint[num]; + if (!EnumProcesses(array, (uint)(array.Length * 4), out var bytesReturned)) + { + throw new Win32Exception(); + } + int num2 = (int)(bytesReturned / 4); + if (num2 < array.Length) + { + HashSet hashSet = new HashSet(); + for (int i = 0; i < num2; i++) + { + hashSet.Add((int)array[i]); + } + return hashSet; + } + } + throw new InvalidOperationException("more than a million process ids"); + } + } + + public static readonly TimeSpan IdlePollInterval = TimeSpan.FromSeconds(10.0); + + public static readonly TimeSpan InGamePollInterval = TimeSpan.FromSeconds(30.0); + + public static readonly TimeSpan NameConfirmInterval = TimeSpan.FromMinutes(15.0); + + private static readonly int ChecksPerNameConfirm = Math.Max(1, (int)(NameConfirmInterval.TotalSeconds / InGamePollInterval.TotalSeconds)); + + private readonly IReadOnlyDictionary _gameIdToExe; + + private readonly TimeSpan? _fixedInterval; + + private readonly HashSet _knownRunning = new HashSet(StringComparer.OrdinalIgnoreCase); + + private CancellationTokenSource? _cts; + + private readonly IProcessSource _source; + + private readonly HashSet _knownPids = new HashSet(); + + private int _checksSinceScan; + + private bool _confirmPending; + + public bool IsRunning + { + get + { + if (_cts != null) + { + return !_cts.IsCancellationRequested; + } + return false; + } + } + + internal TimeSpan NextPollInterval + { + get + { + TimeSpan? fixedInterval = _fixedInterval; + if (!fixedInterval.HasValue) + { + if (_knownRunning.Count <= 0) + { + return IdlePollInterval; + } + return InGamePollInterval; + } + return fixedInterval.GetValueOrDefault(); + } + } + + public event GameEventHandler? OnGameLaunched; + + public event GameEventHandler? OnGameClosed; + + public GameProcessWatcher(IReadOnlyDictionary gameIdToExe, TimeSpan? pollInterval = null, Func>? runningProcessNames = null) + : this(gameIdToExe, (runningProcessNames == null) ? ((IProcessSource)SystemProcessSource.Instance) : ((IProcessSource)new NamesOnly(runningProcessNames)), pollInterval) + { + } + + internal GameProcessWatcher(IReadOnlyDictionary gameIdToExe, IProcessSource source, TimeSpan? pollInterval = null) + { + _gameIdToExe = gameIdToExe ?? throw new ArgumentNullException("gameIdToExe"); + _fixedInterval = pollInterval; + _source = source ?? throw new ArgumentNullException("source"); + } + + internal void RaiseLaunchedForTest(string gameId) + { + OnGameLaunched?.Invoke(gameId); + } + + internal void RaiseClosedForTest(string gameId) + { + OnGameClosed?.Invoke(gameId); + } + + public void Start() + { + if (!IsRunning) + { + _cts = new CancellationTokenSource(); + Task.Run(() => PollLoop(_cts.Token)); + } + } + + public void Stop() + { + try + { + _cts?.Cancel(); + } + catch (ObjectDisposedException) + { + } + _cts?.Dispose(); + _cts = null; + } + + internal void PollOnce() + { + if (_knownRunning.Count > 0 && _knownPids.Count > 0 && !_confirmPending && _checksSinceScan < ChecksPerNameConfirm) + { + IReadOnlyCollection readOnlyCollection; + try + { + readOnlyCollection = _source.RunningIds(); + } + catch (Exception) + { + return; + } + _checksSinceScan++; + ISet set = (readOnlyCollection as ISet) ?? new HashSet(readOnlyCollection); + if (_knownPids.All(set.Contains)) + { + return; + } + _confirmPending = true; + } + FullScan(); + } + + private void FullScan() + { + IReadOnlyCollection<(int, string)> readOnlyCollection; + try + { + readOnlyCollection = _source.Snapshot(); + } + catch (Exception) + { + return; + } + Dictionary dictionary = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var (text3, text4) in _gameIdToExe) + { + dictionary[text4] = text3; + SupportedGame supportedGame = SupportedGames.ById(text3); + if ((object)supportedGame == null || !string.Equals(supportedGame.ProcessName, text4, StringComparison.OrdinalIgnoreCase)) + { + continue; + } + foreach (string allProcessName in supportedGame.AllProcessNames) + { + dictionary[allProcessName] = text3; + } + } + HashSet hashSet = new HashSet(StringComparer.OrdinalIgnoreCase); + HashSet hashSet2 = new HashSet(); + foreach (var (num, text5) in readOnlyCollection) + { + if (text5 != null && dictionary.TryGetValue(text5, out var value)) + { + hashSet.Add(value); + if (num > 0) + { + hashSet2.Add(num); + } + } + } + foreach (string item in hashSet.Except(_knownRunning).ToList()) + { + OnGameLaunched?.Invoke(item); + } + foreach (string item2 in _knownRunning.Except(hashSet).ToList()) + { + OnGameClosed?.Invoke(item2); + } + _knownRunning.Clear(); + foreach (string item3 in hashSet) + { + _knownRunning.Add(item3); + } + _knownPids.Clear(); + foreach (int item4 in hashSet2) + { + _knownPids.Add(item4); + } + _checksSinceScan = 0; + _confirmPending = false; + } + + private async Task PollLoop(CancellationToken ct) + { + while (!ct.IsCancellationRequested) + { + try + { + PollOnce(); + } + catch (Exception) + { + } + try + { + await Task.Delay(NextPollInterval, ct).ConfigureAwait(continueOnCapturedContext: false); + } + catch (TaskCanceledException) + { + break; + } + } + } +} diff --git a/VibranceHud/GameProfile.cs b/VibranceHud/GameProfile.cs new file mode 100644 index 0000000..1e8c3ad --- /dev/null +++ b/VibranceHud/GameProfile.cs @@ -0,0 +1,59 @@ +using System; +using System.Text.Json.Serialization; + +namespace VibranceHud; + +public sealed class GameProfile +{ + [JsonPropertyName("gameId")] + public string GameId { get; set; } = ""; + + [JsonPropertyName("displayName")] + public string DisplayName { get; set; } = ""; + + [JsonPropertyName("vibrance")] + public int Vibrance { get; set; } = 100; + + [JsonPropertyName("saturation")] + public int Saturation { get; set; } = 100; + + [JsonPropertyName("brightness")] + public int Brightness { get; set; } = 100; + + [JsonPropertyName("gamma")] + public int Gamma { get; set; } = 100; + + [JsonPropertyName("contrast")] + public int? Contrast { get; set; } + + [JsonPropertyName("temperature")] + public int? Temperature { get; set; } + + [JsonPropertyName("tone")] + public ToneSettings? Tone { get; set; } + + [JsonIgnore] + public int ResolvedContrast => Contrast ?? 100; + + [JsonIgnore] + public int ResolvedTemperature => Temperature.GetValueOrDefault(); + + [JsonIgnore] + public ToneSettings ResolvedTone + { + get + { + ToneSettings toneSettings = Tone ?? ToneSettings.Neutral; + return toneSettings with + { + Gamma = Gamma + }; + } + } + + [JsonPropertyName("gameHub")] + public GameHubOptions GameHub { get; set; } = new GameHubOptions(); + + [JsonPropertyName("lastUpdated")] + public DateTime LastUpdated { get; set; } = DateTime.UtcNow; +} diff --git a/VibranceHud/GameProfileApplyGate.cs b/VibranceHud/GameProfileApplyGate.cs new file mode 100644 index 0000000..10f7e99 --- /dev/null +++ b/VibranceHud/GameProfileApplyGate.cs @@ -0,0 +1,25 @@ +namespace VibranceHud; + +public sealed class GameProfileApplyGate +{ + private readonly AppSettings _settings; + + public GameProfileApplyGate(AppSettings settings) + { + _settings = settings; + } + + public bool ShouldAutoApply(string gameId) + { + if (_settings.ManualOverrideActive) + { + return false; + } + return true; + } + + public void UserOptedBackIn() + { + _settings.ManualOverrideActive = false; + } +} diff --git a/VibranceHud/GameProfileSection.cs b/VibranceHud/GameProfileSection.cs new file mode 100644 index 0000000..fced3e0 --- /dev/null +++ b/VibranceHud/GameProfileSection.cs @@ -0,0 +1,241 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Globalization; +using System.Windows.Forms; +using VibranceHud.Design; + +namespace VibranceHud; + +public sealed class GameProfileSection +{ + private readonly IVibranceEngine _engine; + + private readonly string _gameId; + + private readonly string _gameName; + + private readonly AppSettings? _settings; + + private readonly Func _lookupProfile; + + private readonly Action _saveProfile; + + private readonly Action _removeProfile; + + private readonly Action? _onChanged; + + private readonly Label _caption; + + private readonly Label _summary; + + private readonly GlassButton _save; + + private readonly GlassButton _forget; + + public int PreferredHeight => Tokens.Scale(22) + Tokens.Scale(6) + Tokens.Scale(38) + Tokens.Scale(38); + + public GameProfileSection(Control parent, string gameId, string gameName, IVibranceEngine engine, Font captionFont, Font bodyFont, AppSettings? settings = null, Func? lookup = null, Action? save = null, Action? remove = null, Action? onChanged = null) + { + _engine = engine; + _gameId = gameId; + _gameName = gameName; + _settings = settings; + _lookupProfile = lookup ?? new Func(GameProfileStore.Get); + _saveProfile = save ?? new Action(GameProfileStore.Set); + _removeProfile = remove ?? new Action(GameProfileStore.Remove); + _onChanged = onChanged; + _caption = new Label + { + Text = UiHelpers.Spaced("PROFILE"), + Font = captionFont, + ForeColor = Theme.TextDim, + BackColor = Color.Transparent, + AutoSize = false, + TextAlign = ContentAlignment.MiddleLeft + }; + parent.Controls.Add(_caption); + _summary = new Label + { + Font = bodyFont, + ForeColor = Theme.TextDim, + BackColor = Color.Transparent, + AutoSize = false, + TextAlign = ContentAlignment.TopLeft + }; + parent.Controls.Add(_summary); + _save = new GlassButton + { + Text = "Use my current look for " + Shorten(gameName), + Kind = GlassButtonKind.Primary + }; + _save.Click += (object? _, EventArgs _) => + { + Save(); + }; + parent.Controls.Add(_save); + _forget = new GlassButton + { + Text = "Forget", + Kind = GlassButtonKind.Secondary + }; + _forget.Click += (object? _, EventArgs _) => + { + Forget(); + }; + parent.Controls.Add(_forget); + Refresh(); + } + + internal static string Shorten(string name) + { + if (name.Length > 14) + { + return name.Substring(0, 13).TrimEnd() + "…"; + } + return name; + } + + private void Save() + { + _saveProfile(Capture(_gameId, _gameName, _engine, _lookupProfile(_gameId))); + if (_settings != null) + { + new GameProfileApplyGate(_settings).UserOptedBackIn(); + } + Refresh(); + _onChanged?.Invoke(); + } + + internal static GameProfile Capture(string gameId, string gameName, IVibranceEngine engine, GameProfile? existing) + { + return new GameProfile + { + GameId = gameId, + DisplayName = (string.IsNullOrWhiteSpace(existing?.DisplayName) ? gameName : existing.DisplayName), + Vibrance = engine.Vibrance, + Saturation = engine.Saturation, + Brightness = engine.Brightness, + Gamma = engine.Gamma, + Contrast = engine.Contrast, + Temperature = engine.Temperature, + Tone = engine.Tone, + GameHub = (existing?.GameHub ?? new GameHubOptions()), + LastUpdated = DateTime.UtcNow + }; + } + + internal static GameProfile CaptureFromPreset(string gameId, string gameName, DisplayPreset preset, GameProfile? existing) + { + return new GameProfile + { + GameId = gameId, + DisplayName = (string.IsNullOrWhiteSpace(existing?.DisplayName) ? gameName : existing.DisplayName), + Vibrance = preset.Vibrance, + Saturation = preset.Saturation, + Brightness = preset.Brightness, + Gamma = preset.Gamma, + Contrast = preset.Contrast, + Temperature = preset.Temperature, + Tone = new ToneSettings(preset.Gamma, preset.Highlights, preset.Shadows), + GameHub = (existing?.GameHub ?? new GameHubOptions()), + LastUpdated = DateTime.UtcNow + }; + } + + private void Forget() + { + _removeProfile(_gameId); + Refresh(); + _onChanged?.Invoke(); + } + + public void Refresh() + { + GameProfile gameProfile = _lookupProfile(_gameId); + if (gameProfile == null) + { + _summary.Text = "No profile yet. Set your colours on Display, then save them here and PlexusX will switch to them whenever " + _gameName + " opens."; + _forget.Visible = false; + _save.Text = "Use my current look for " + Shorten(_gameName); + } + else + { + _summary.Text = Describe(gameProfile) + " — applied when " + _gameName + " opens, put back when it closes."; + _forget.Visible = true; + _save.Text = "Update to my current look"; + } + } + + internal static string Describe(GameProfile p) + { + List list = new List(); + if (p.Saturation != 100) + { + list.Add($"saturation {p.Saturation}"); + } + if (p.Vibrance != 100) + { + list.Add($"vibrance {p.Vibrance}"); + } + if (p.Brightness != 100) + { + list.Add($"brightness {p.Brightness}"); + } + if (p.Gamma != 100) + { + list.Add("gamma " + ((float)p.Gamma / 100f).ToString("0.00", CultureInfo.InvariantCulture)); + } + if (p.ResolvedContrast != 100) + { + list.Add($"contrast {p.ResolvedContrast}"); + } + if (p.ResolvedTemperature != 0) + { + list.Add((p.ResolvedTemperature > 0) ? $"warm {p.ResolvedTemperature}" : $"cool {-p.ResolvedTemperature}"); + } + if (!p.ResolvedTone.IsGammaOnly) + { + list.Add("advanced colour"); + } + if (list.Count != 0) + { + return "Saved: " + string.Join(", ", list); + } + return "Saved: neutral"; + } + + internal static bool ChangesAnything(GameProfile p) + { + return Describe(p) != "Saved: neutral"; + } + + public static CardPanel BuildCard(string gameId, string gameName, IVibranceEngine engine, int x, int y, int width, AppSettings? settings = null, Func? lookup = null, Action? save = null, Action? remove = null, Action? onChanged = null) + { + CardPanel cardPanel = new CardPanel + { + Location = new Point(x, y), + Size = new Size(width, 10) + }; + GameProfileSection gameProfileSection = new GameProfileSection(cardPanel, gameId, gameName, engine, Fonts.Micro, Fonts.Caption, settings, lookup, save, remove, onChanged); + int num = Tokens.Scale(18); + gameProfileSection.Place(num, num, width - 2 * num); + cardPanel.Height = gameProfileSection.PreferredHeight + 2 * num; + return cardPanel; + } + + public void Place(int x, int y, int width) + { + int num = Tokens.Scale(22); + int height = Tokens.Scale(32); + int num2 = Tokens.Scale(84); + int num3 = Tokens.Scale(8); + _caption.SetBounds(x, y, width, num); + y += num + Tokens.Scale(6); + _summary.SetBounds(x, y, width, Tokens.Scale(36)); + y += Tokens.Scale(38); + int num4 = Math.Min(Tokens.Scale(260), width - num2 - num3); + _save.SetBounds(x, y, num4, height); + _forget.SetBounds(x + num4 + num3, y, num2, height); + } +} diff --git a/VibranceHud/GameProfileStore.cs b/VibranceHud/GameProfileStore.cs new file mode 100644 index 0000000..58bb179 --- /dev/null +++ b/VibranceHud/GameProfileStore.cs @@ -0,0 +1,215 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; + +namespace VibranceHud; + +public static class GameProfileStore +{ + private enum ReadOutcome + { + Nothing, + Loaded, + Failed + } + + private sealed class ProfilesDocument + { + public int Version { get; set; } = 1; + + public List Profiles { get; set; } = new List(); + } + + private const int CurrentSchemaVersion = 1; + + public static string StorePath + { + get + { + string local = AppFolders.Local; + try + { + Directory.CreateDirectory(local); + } + catch (Exception) + { + } + return Path.Combine(local, "profiles.json"); + } + } + + public static IReadOnlyList Load() + { + return Load(StorePath); + } + + public static IReadOnlyList Load(string path) + { + return Load(path, File.ReadAllText); + } + + internal static IReadOnlyList Load(string path, Func readText) + { + TryRead(path, readText, out List profiles); + return profiles; + } + + private static ReadOutcome TryRead(string path, Func readText, out List profiles) + { + profiles = new List(); + if (!File.Exists(path)) + { + return ReadOutcome.Nothing; + } + string text; + try + { + text = readText(path); + } + catch (Exception) + { + return ReadOutcome.Failed; + } + if (string.IsNullOrWhiteSpace(text)) + { + return ReadOutcome.Nothing; + } + try + { + profiles = JsonSerializer.Deserialize(text)?.Profiles ?? new List(); + return ReadOutcome.Loaded; + } + catch (Exception) + { + profiles = new List(); + return ReadOutcome.Failed; + } + } + + public static string SerializeAll(IEnumerable profiles) + { + return JsonSerializer.Serialize(new ProfilesDocument + { + Version = 1, + Profiles = new List(profiles) + }, new JsonSerializerOptions + { + WriteIndented = true + }); + } + + public static void Set(GameProfile profile) + { + TrySet(profile, StorePath, File.ReadAllText); + } + + public static void Set(GameProfile profile, string path) + { + TrySet(profile, path, File.ReadAllText); + } + + internal static bool TrySet(GameProfile profile, string path, Func readText) + { + if (TryRead(path, readText, out List profiles) == ReadOutcome.Failed) + { + return false; + } + int num = profiles.FindIndex((GameProfile p) => p.GameId == profile.GameId); + profile.LastUpdated = DateTime.UtcNow; + if (num >= 0) + { + profiles[num] = profile; + } + else + { + profiles.Add(profile); + } + return WriteAtomically(path, SerializeAll(profiles)); + } + + public static void Remove(string gameId) + { + TryRemove(gameId, StorePath, File.ReadAllText); + } + + public static void Remove(string gameId, string path) + { + TryRemove(gameId, path, File.ReadAllText); + } + + internal static bool TryRemove(string gameId, string path, Func readText) + { + if (TryRead(path, readText, out List profiles) == ReadOutcome.Failed) + { + return false; + } + profiles.RemoveAll((GameProfile p) => p.GameId == gameId); + return WriteAtomically(path, SerializeAll(profiles)); + } + + private static bool WriteAtomically(string path, string json) + { + string text = ""; + try + { + string directoryName = Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(directoryName)) + { + Directory.CreateDirectory(directoryName); + } + text = path + "." + Guid.NewGuid().ToString("N") + ".tmp"; + File.WriteAllText(text, json); + try + { + if (File.Exists(path)) + { + File.Replace(text, path, null, ignoreMetadataErrors: true); + } + else + { + File.Move(text, path); + } + } + catch (Exception) when (File.Exists(text)) + { + File.Copy(text, path, overwrite: true); + } + return true; + } + catch (Exception) + { + return false; + } + finally + { + try + { + if (text.Length > 0 && File.Exists(text)) + { + File.Delete(text); + } + } + catch + { + } + } + } + + public static GameProfile? Get(string gameId) + { + return Get(gameId, StorePath); + } + + public static GameProfile? Get(string gameId, string path) + { + foreach (GameProfile item in Load(path)) + { + if (item.GameId == gameId) + { + return item; + } + } + return null; + } +} diff --git a/VibranceHud/Games/DetectedGame.cs b/VibranceHud/Games/DetectedGame.cs new file mode 100644 index 0000000..ff61727 --- /dev/null +++ b/VibranceHud/Games/DetectedGame.cs @@ -0,0 +1,3 @@ +namespace VibranceHud.Games; + +public sealed record DetectedGame(SupportedGame Game, string InstallDir); diff --git a/VibranceHud/Games/EpicLocator.cs b/VibranceHud/Games/EpicLocator.cs new file mode 100644 index 0000000..c1b82ae --- /dev/null +++ b/VibranceHud/Games/EpicLocator.cs @@ -0,0 +1,55 @@ +using System; +using System.IO; +using System.Text.Json; + +namespace VibranceHud.Games; + +public static class EpicLocator +{ + public static string? ParseInstallLocation(string manifestJson, string appName) + { + try + { + using JsonDocument jsonDocument = JsonDocument.Parse(manifestJson); + if (!jsonDocument.RootElement.TryGetProperty("AppName", out var value)) + { + return null; + } + if (!string.Equals(value.GetString(), appName, StringComparison.OrdinalIgnoreCase)) + { + return null; + } + JsonElement value2; + return jsonDocument.RootElement.TryGetProperty("InstallLocation", out value2) ? value2.GetString() : null; + } + catch + { + return null; + } + } + + public static string? FindGameInstall(string appName) + { + try + { + string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Epic", "EpicGamesLauncher", "Data", "Manifests"); + if (!Directory.Exists(path)) + { + return null; + } + foreach (string item in Directory.EnumerateFiles(path, "*.item")) + { + string text = ParseInstallLocation(File.ReadAllText(item), appName); + if (text != null && Directory.Exists(text)) + { + return text; + } + } + return null; + } + catch + { + return null; + } + } +} diff --git a/VibranceHud/Games/GameDetection.cs b/VibranceHud/Games/GameDetection.cs new file mode 100644 index 0000000..cb37fe3 --- /dev/null +++ b/VibranceHud/Games/GameDetection.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace VibranceHud.Games; + +public static class GameDetection +{ + public static IReadOnlyList DetectInstalled(IEnumerable libraryPaths, IEnumerable games, Func fileExists) + { + List list = libraryPaths.ToList(); + List list2 = new List(); + foreach (SupportedGame game in games) + { + foreach (string item in list) + { + string arg = Path.Combine(item, "steamapps", $"appmanifest_{game.SteamAppId}.acf"); + if (fileExists(arg)) + { + string installDir = Path.Combine(item, "steamapps", "common", game.InstallFolder); + list2.Add(new DetectedGame(game, installDir)); + break; + } + } + } + return list2; + } +} diff --git a/VibranceHud/Games/GameLibrary.cs b/VibranceHud/Games/GameLibrary.cs new file mode 100644 index 0000000..ef8801f --- /dev/null +++ b/VibranceHud/Games/GameLibrary.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace VibranceHud.Games; + +public static class GameLibrary +{ + public static IReadOnlyList DetectInstalled() + { + List list = new List(); + list.AddRange(DetectSteam()); + list.AddRange(DetectEpic()); + return list; + } + + public static IReadOnlyList<(SupportedGame Game, DetectedGame? Detected)> OrderForHub(IReadOnlyList detected) + { + Dictionary byGame = detected.ToDictionary((DetectedGame d) => d.Game); + return (from g in SupportedGames.All + select (Game: g, Detected: byGame.TryGetValue(g, out var value) ? value : null) into x + orderby x.Detected == null + select x).ToList(); + } + + private static IReadOnlyList DetectSteam() + { + try + { + string text = SteamLocator.FindSteamPath(); + if (text == null) + { + return Array.Empty(); + } + IReadOnlyList libraries = SteamLocator.GetLibraries(text); + IEnumerable games = SupportedGames.All.Where((SupportedGame g) => g.SteamAppId > 0); + return GameDetection.DetectInstalled(libraries, games, File.Exists); + } + catch + { + return Array.Empty(); + } + } + + private static IReadOnlyList DetectEpic() + { + try + { + List list = new List(); + foreach (SupportedGame item in SupportedGames.All.Where((SupportedGame g) => g.EpicAppName != null)) + { + string text = EpicLocator.FindGameInstall(item.EpicAppName); + if (text != null) + { + list.Add(new DetectedGame(item, text)); + } + } + return list; + } + catch + { + return Array.Empty(); + } + } +} diff --git a/VibranceHud/Games/GameLookJoin.cs b/VibranceHud/Games/GameLookJoin.cs new file mode 100644 index 0000000..43eb618 --- /dev/null +++ b/VibranceHud/Games/GameLookJoin.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using VibranceHud.Licensing; + +namespace VibranceHud.Games; + +internal static class GameLookJoin +{ + private static readonly IReadOnlyDictionary Map = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["rust"] = "Rust", + ["cs2"] = "CS2", + ["fortnite"] = "Fortnite", + ["valorant"] = "Valorant", + ["r6"] = "Rainbow Six Siege" + }; + + internal static IReadOnlyCollection JoinedIds => Map.Keys.ToList(); + + internal static string? LookGameFor(string gameId) + { + if (gameId == null || !Map.TryGetValue(gameId, out string value)) + { + return null; + } + return value; + } + + internal static DisplayPreset? StartingLookFor(string gameId) + { + string text = LookGameFor(gameId); + if (text == null) + { + return null; + } + ScenePresetSet scenePresetSet = ServedLooks.ForGame(text); + if (scenePresetSet.Presets.Count <= 0) + { + return null; + } + return scenePresetSet.Presets[0]; + } +} diff --git a/VibranceHud/Games/GameSelection.cs b/VibranceHud/Games/GameSelection.cs new file mode 100644 index 0000000..e9942e6 --- /dev/null +++ b/VibranceHud/Games/GameSelection.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace VibranceHud.Games; + +public sealed class GameSelection +{ + private readonly AppSettings _settings; + + private readonly SettingsStore _store; + + private readonly Func> _detect; + + private List _installed = new List(); + + private string? _currentId; + + public IReadOnlyList Installed => _installed; + + public string? CurrentId => _currentId; + + public SupportedGame? Current + { + get + { + if (_currentId != null) + { + return SupportedGames.All.FirstOrDefault((SupportedGame g) => g.Id == _currentId); + } + return null; + } + } + + public DetectedGame? Detected + { + get + { + if (_currentId != null) + { + return _installed.FirstOrDefault((DetectedGame d) => d.Game.Id == _currentId); + } + return null; + } + } + + public bool NothingInstalled => _installed.Count == 0; + + public event EventHandler? Changed; + + public GameSelection(AppSettings settings, SettingsStore store, Func>? detect = null) + { + _settings = settings; + _store = store; + _detect = detect ?? new Func>(GameLibrary.DetectInstalled); + Refresh(); + _currentId = Resolve(_settings.CurrentGameId); + } + + public void Refresh() + { + try + { + _installed = _detect().ToList(); + } + catch + { + _installed = new List(); + } + if (_currentId != null && Resolve(_currentId) == null) + { + _currentId = null; + Persist(); + Changed?.Invoke(this, EventArgs.Empty); + } + } + + public void Select(string? gameId) + { + string text = Resolve(gameId); + if (!(text == _currentId)) + { + _currentId = text; + Persist(); + Changed?.Invoke(this, EventArgs.Empty); + } + } + + private string? Resolve(string? gameId) + { + if (string.IsNullOrWhiteSpace(gameId)) + { + return null; + } + if (!SupportedGames.All.Any((SupportedGame g) => g.Id == gameId)) + { + return null; + } + if (!_installed.Any((DetectedGame d) => d.Game.Id == gameId)) + { + return null; + } + return gameId; + } + + private void Persist() + { + _settings.CurrentGameId = _currentId ?? ""; + _store.Save(_settings); + } +} diff --git a/VibranceHud/Games/GameSetupOffer.cs b/VibranceHud/Games/GameSetupOffer.cs new file mode 100644 index 0000000..252302d --- /dev/null +++ b/VibranceHud/Games/GameSetupOffer.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace VibranceHud.Games; + +internal static class GameSetupOffer +{ + internal static bool ShouldOffer(string gameId, bool profileExists, IEnumerable declined, string alreadyPending) + { + if (string.IsNullOrEmpty(gameId)) + { + return false; + } + if (GameLookJoin.LookGameFor(gameId) == null) + { + return false; + } + if (profileExists) + { + return false; + } + if (!string.IsNullOrEmpty(alreadyPending)) + { + return false; + } + return !(declined ?? Enumerable.Empty()).Any((string d) => string.Equals(d, gameId, StringComparison.OrdinalIgnoreCase)); + } + + internal static string Sentence(string gameId) + { + string value = GameLookJoin.LookGameFor(gameId) ?? gameId; + return $"Playing {value}? PlexusX can use the {value} look every time you launch it."; + } +} diff --git a/VibranceHud/Games/SteamLocator.cs b/VibranceHud/Games/SteamLocator.cs new file mode 100644 index 0000000..8eed2ca --- /dev/null +++ b/VibranceHud/Games/SteamLocator.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; +using System.IO; +using Microsoft.Win32; + +namespace VibranceHud.Games; + +public static class SteamLocator +{ + public static string? FindSteamPath() + { + string[] array = new string[3] + { + Registry.GetValue("HKEY_CURRENT_USER\\Software\\Valve\\Steam", "SteamPath", null) as string, + Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\Valve\\Steam", "InstallPath", null) as string, + Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Valve\\Steam", "InstallPath", null) as string + }; + foreach (string text in array) + { + if (!string.IsNullOrWhiteSpace(text) && Directory.Exists(text)) + { + return Path.GetFullPath(text); + } + } + return null; + } + + public static IReadOnlyList GetLibraries(string steamPath) + { + List list = new List { steamPath }; + string[] array = new string[2] { "steamapps\\libraryfolders.vdf", "config\\libraryfolders.vdf" }; + foreach (string path in array) + { + string path2 = Path.Combine(steamPath, path); + if (File.Exists(path2)) + { + list.AddRange(SteamVdf.ParseLibraryPaths(File.ReadAllText(path2))); + break; + } + } + HashSet hashSet = new HashSet(StringComparer.OrdinalIgnoreCase); + List list2 = new List(); + foreach (string item in list) + { + if (Directory.Exists(item)) + { + string fullPath = Path.GetFullPath(item); + if (hashSet.Add(fullPath)) + { + list2.Add(fullPath); + } + } + } + return list2; + } +} diff --git a/VibranceHud/Games/SteamVdf.cs b/VibranceHud/Games/SteamVdf.cs new file mode 100644 index 0000000..47ca3b5 --- /dev/null +++ b/VibranceHud/Games/SteamVdf.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; +using System.Text.RegularExpressions; + +namespace VibranceHud.Games; + +public static class SteamVdf +{ + private static readonly Regex KeyValue = new Regex("^\\s*\"([^\"]+)\"\\s+\"(.+?)\"\\s*$", RegexOptions.Compiled); + + public static IReadOnlyList ParseLibraryPaths(string vdfContent) + { + List list = new List(); + if (string.IsNullOrEmpty(vdfContent)) + { + return list; + } + HashSet hashSet = new HashSet(StringComparer.OrdinalIgnoreCase); + string[] array = vdfContent.Split('\n'); + foreach (string input in array) + { + Match match = KeyValue.Match(input); + if (!match.Success) + { + continue; + } + string value = match.Groups[1].Value; + string value2 = match.Groups[2].Value; + if ((value.Equals("path", StringComparison.OrdinalIgnoreCase) || IsAllDigits(value)) && (value2.Contains('\\') || value2.Contains('/'))) + { + string item = value2.Replace("\\\\", "\\").Trim(); + if (hashSet.Add(item)) + { + list.Add(item); + } + } + } + return list; + } + + private static bool IsAllDigits(string s) + { + if (s.Length == 0) + { + return false; + } + for (int i = 0; i < s.Length; i++) + { + if (!char.IsDigit(s[i])) + { + return false; + } + } + return true; + } +} diff --git a/VibranceHud/Games/SupportedGame.cs b/VibranceHud/Games/SupportedGame.cs new file mode 100644 index 0000000..f33d553 --- /dev/null +++ b/VibranceHud/Games/SupportedGame.cs @@ -0,0 +1,19 @@ +using System.Collections.Generic; +using System.Linq; + +namespace VibranceHud.Games; + +public sealed record SupportedGame(string Id, string DisplayName, int SteamAppId, string InstallFolder, string ProcessName, string? EpicAppName = null, IReadOnlyList? AlsoProcessNames = null) +{ + public IReadOnlyList AllProcessNames + { + get + { + if (AlsoProcessNames == null || AlsoProcessNames.Count == 0) + { + return new string[1] { ProcessName }; + } + return new string[1] { ProcessName }.Concat(AlsoProcessNames).ToArray(); + } + } +} diff --git a/VibranceHud/Games/SupportedGames.cs b/VibranceHud/Games/SupportedGames.cs new file mode 100644 index 0000000..41c2eb3 --- /dev/null +++ b/VibranceHud/Games/SupportedGames.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; + +namespace VibranceHud.Games; + +public static class SupportedGames +{ + public static readonly SupportedGame Rust = new SupportedGame("rust", "Rust", 252490, "Rust", "RustClient"); + + public static readonly SupportedGame Cs2 = new SupportedGame("cs2", "Counter-Strike 2", 730, "Counter-Strike Global Offensive", "cs2"); + + public static readonly SupportedGame Apex = new SupportedGame("apex", "Apex Legends", 1172470, "Apex Legends", "r5apex", null, new string[1] { "r5apex_dx12" }); + + public static readonly SupportedGame Fortnite = new SupportedGame("fortnite", "Fortnite", 0, "Fortnite", "FortniteClient-Win64-Shipping", "Fortnite"); + + public static readonly SupportedGame Valorant = new SupportedGame("valorant", "VALORANT", 0, "VALORANT", "VALORANT-Win64-Shipping"); + + public static readonly SupportedGame Siege = new SupportedGame("r6", "Rainbow Six Siege", 359550, "Tom Clancy's Rainbow Six Siege", "RainbowSix", null, new string[2] { "RainbowSix_Vulkan", "RainbowSix_BE" }); + + public static readonly IReadOnlyList All = new SupportedGame[6] { Rust, Cs2, Apex, Fortnite, Valorant, Siege }; + + public static IReadOnlyDictionary ProcessNames => All.ToDictionary((SupportedGame g) => g.Id, (SupportedGame g) => g.ProcessName, StringComparer.OrdinalIgnoreCase); + + public static IEnumerable AllProcessNames => All.SelectMany((SupportedGame g) => g.AllProcessNames); + + public static SupportedGame? ById(string? id) + { + if (id != null) + { + return All.FirstOrDefault((SupportedGame g) => g.Id == id); + } + return null; + } + + public static SupportedGame? CurrentlyRunning() + { + return All.FirstOrDefault((SupportedGame g) => g.AllProcessNames.Any((string n) => Process.GetProcessesByName(n).Length != 0)); + } +} diff --git a/VibranceHud/GammaCurve.cs b/VibranceHud/GammaCurve.cs new file mode 100644 index 0000000..01a6a2d --- /dev/null +++ b/VibranceHud/GammaCurve.cs @@ -0,0 +1,28 @@ +using System; + +namespace VibranceHud; + +public static class GammaCurve +{ + public const int Entries = 256; + + public static ushort[] Build(float gamma) + { + if (gamma <= 0f) + { + gamma = 1f; + } + ushort[] array = new ushort[768]; + double y = 1.0 / (double)gamma; + for (int i = 0; i < 256; i++) + { + array[512 + i] = (array[256 + i] = (array[i] = (ushort)Math.Clamp(Math.Round(Math.Pow((double)i / 255.0, y) * 65535.0), 0.0, 65535.0))); + } + return array; + } + + public static ushort[] Identity() + { + return Build(1f); + } +} diff --git a/VibranceHud/GammaDelivery.cs b/VibranceHud/GammaDelivery.cs new file mode 100644 index 0000000..ce05dc5 --- /dev/null +++ b/VibranceHud/GammaDelivery.cs @@ -0,0 +1,10 @@ +namespace VibranceHud; + +public readonly record struct GammaDelivery(GammaDeliveryKind Kind, int Displays = 0, string Step = "") +{ + public static GammaDelivery Full => new GammaDelivery(GammaDeliveryKind.Full); + + public bool IsFull => Kind == GammaDeliveryKind.Full; + + public string ReportValue => Kind.ToString(); +} diff --git a/VibranceHud/GammaDeliveryKind.cs b/VibranceHud/GammaDeliveryKind.cs new file mode 100644 index 0000000..d204e5f --- /dev/null +++ b/VibranceHud/GammaDeliveryKind.cs @@ -0,0 +1,9 @@ +namespace VibranceHud; + +public enum GammaDeliveryKind +{ + Full, + Softened, + Refused, + IgnoredHdr +} diff --git a/VibranceHud/GitHubReleases.cs b/VibranceHud/GitHubReleases.cs new file mode 100644 index 0000000..c3df57d --- /dev/null +++ b/VibranceHud/GitHubReleases.cs @@ -0,0 +1,107 @@ +using System; +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace VibranceHud; + +public static class GitHubReleases +{ + public static ReleaseInfo? ParseLatest(string json) + { + try + { + using JsonDocument jsonDocument = JsonDocument.Parse(json); + JsonElement rootElement = jsonDocument.RootElement; + if (!rootElement.TryGetProperty("tag_name", out var value)) + { + return null; + } + string tag = value.GetString() ?? ""; + Version version = ParseVersion(tag); + if (version == null) + { + return null; + } + string pageUrl = (rootElement.TryGetProperty("html_url", out var value2) ? (value2.GetString() ?? "") : ""); + string notes = (rootElement.TryGetProperty("body", out var value3) ? (value3.GetString() ?? "") : ""); + if (!rootElement.TryGetProperty("assets", out var value4) || value4.ValueKind != JsonValueKind.Array) + { + return null; + } + string text = null; + string filename = ""; + Version version2 = null; + foreach (JsonElement item in value4.EnumerateArray()) + { + string text2 = (item.TryGetProperty("name", out var value5) ? (value5.GetString() ?? "") : ""); + if (!text2.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) + { + continue; + } + string text3 = (item.TryGetProperty("browser_download_url", out var value6) ? value6.GetString() : null); + if (text3 != null) + { + Version version3 = ParseVersionFromFilename(text2); + if (text == null || (version3 != null && (version2 == null || version3 > version2))) + { + text = text3; + filename = text2; + version2 = version3; + } + } + } + if (text == null) + { + return null; + } + Version version4 = ParseVersionFromFilename(filename); + if (version4 != null && version4 > version) + { + version = version4; + } + return new ReleaseInfo(version, tag, text, pageUrl, notes); + } + catch + { + return null; + } + } + + public static Version? ParseVersion(string tag) + { + if (string.IsNullOrWhiteSpace(tag)) + { + return null; + } + if (!Version.TryParse(tag.Trim().TrimStart('v', 'V'), out Version result)) + { + return null; + } + return Normalize(result); + } + + public static Version? ParseVersionFromFilename(string filename) + { + MatchCollection matchCollection = Regex.Matches(filename, "\\d+\\.\\d+(?:\\.\\d+)?"); + if (matchCollection.Count <= 0) + { + return null; + } + return ParseVersion(matchCollection[matchCollection.Count - 1].Value); + } + + public static bool IsNewer(Version latest, Version current) + { + return Normalize(latest) > Normalize(current); + } + + private static Version Normalize(Version v) + { + return new Version(v.Major, v.Minor, Math.Max(v.Build, 0)); + } + + public static Version NormalizeForCompare(Version v) + { + return Normalize(v); + } +} diff --git a/VibranceHud/GitHubReleasesSource.cs b/VibranceHud/GitHubReleasesSource.cs new file mode 100644 index 0000000..85c1dda --- /dev/null +++ b/VibranceHud/GitHubReleasesSource.cs @@ -0,0 +1,25 @@ +using System; +using System.Threading.Tasks; + +namespace VibranceHud; + +internal sealed class GitHubReleasesSource : IDownloadSource +{ + private readonly ReleaseInfo _release; + + public string Name => "GitHub Releases (" + _release.InstallerUrl + ")"; + + public GitHubReleasesSource(ReleaseInfo release) + { + _release = release; + } + + public async Task DownloadAsync(IProgress? progress) + { + if (string.IsNullOrEmpty(_release.InstallerUrl)) + { + return null; + } + return await DownloadHelper.DownloadToTempAsync(new Uri(_release.InstallerUrl), UpdateService.PartialPathFor(_release), progress); + } +} diff --git a/VibranceHud/Glass.cs b/VibranceHud/Glass.cs new file mode 100644 index 0000000..056ff36 --- /dev/null +++ b/VibranceHud/Glass.cs @@ -0,0 +1,307 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Numerics; +using System.Windows.Forms; +using VibranceHud.Design; +using VibranceHud.Theming; + +namespace VibranceHud; + +public static class Glass +{ + private const float SoftRadiusScale = 1.45f; + + public static SurfaceStyle Style { get; set; } = SurfaceStyle.Glass; + + public static Chrome ActiveChrome { get; set; } = Chrome.Plexus; + + private static bool Flat => Style == SurfaceStyle.Flat; + + private static bool Soft => ActiveChrome == Chrome.Blossom; + + internal static int SlateSurfacesDrawn { get; private set; } + + internal static int SlateOutlinesTraced { get; private set; } + + internal static bool SlateInteriorShortcutForTests { get; set; } = true; + + public static Point BackdropOffsetOf(Control? control) + { + int num = 0; + int num2 = 0; + Control control2 = control; + while (control2 != null && !(control2 is Form)) + { + num += control2.Left; + num2 += control2.Top; + control2 = control2.Parent; + } + return new Point(num, num2); + } + + public static GraphicsPath RoundedPath(RectangleF rect, float radius) + { + GraphicsPath graphicsPath = new GraphicsPath(); + if (rect.Width <= 0f || rect.Height <= 0f) + { + return graphicsPath; + } + if (Flat) + { + radius = 0f; + } + radius = Math.Max(0f, Math.Min(radius, Math.Min(rect.Width, rect.Height) / 2f)); + if (radius <= 0.01f) + { + graphicsPath.AddRectangle(rect); + return graphicsPath; + } + float num = radius * 2f; + graphicsPath.AddArc(rect.X, rect.Y, num, num, 180f, 90f); + graphicsPath.AddArc(rect.Right - num, rect.Y, num, num, 270f, 90f); + graphicsPath.AddArc(rect.Right - num, rect.Bottom - num, num, num, 0f, 90f); + graphicsPath.AddArc(rect.X, rect.Bottom - num, num, num, 90f, 90f); + graphicsPath.CloseFigure(); + return graphicsPath; + } + + private static Color Lift(Color c, float k) + { + if (!(k >= 0f)) + { + return Color.FromArgb((int)((float)(int)c.R * (1f + k)), (int)((float)(int)c.G * (1f + k)), (int)((float)(int)c.B * (1f + k))); + } + return Color.FromArgb((int)((float)(int)c.R + (float)(255 - c.R) * k), (int)((float)(int)c.G + (float)(255 - c.G) * k), (int)((float)(int)c.B + (float)(255 - c.B) * k)); + } + + public static void PaintPanel(Graphics g, RectangleF rect, float radius, int fillAlpha = 140, int rimAlpha = 105, bool exactAlpha = false) + { + PaintPanel(g, rect, radius, Point.Empty, fillAlpha, rimAlpha, exactAlpha); + } + + public static void PaintPanel(Graphics g, RectangleF rect, float radius, Point backdropOffset, int fillAlpha = 140, int rimAlpha = 105, bool exactAlpha = false) + { + if (rect.Width < 2f || rect.Height < 2f) + { + return; + } + if (SlateSurface.Active) + { + PaintSlateSurface(g, rect, radius, backdropOffset, SlateSurface.PanelAlpha); + return; + } + int alpha = (exactAlpha ? fillAlpha : Math.Min(255, fillAlpha + 74)); + if (Soft) + { + g.SmoothingMode = SmoothingMode.AntiAlias; + float num = radius * 1.45f; + using GraphicsPath path = RoundedPath(rect, num); + using (SolidBrush brush = new SolidBrush(Color.FromArgb(alpha, Theme.Surface))) + { + g.FillPath(brush, path); + } + using (Pen pen = new Pen(Color.FromArgb(Math.Min(255, rimAlpha), Theme.Border), 1.6f)) + { + g.DrawPath(pen, path); + } + RectangleF rect2 = RectangleF.Inflate(rect, -1.6f, -1.6f); + if (!(rect2.Width > 2f) || !(rect2.Height > 2f)) + { + return; + } + using GraphicsPath path2 = RoundedPath(rect2, Math.Max(1f, num - 1.6f)); + using Pen pen2 = new Pen(Color.FromArgb(Math.Min(255, rimAlpha + 40), Theme.GlassEdge), 1f); + g.DrawPath(pen2, path2); + return; + } + g.SmoothingMode = SmoothingMode.AntiAlias; + using GraphicsPath path3 = RoundedPath(rect, radius); + if (Flat) + { + using SolidBrush brush2 = new SolidBrush(Color.FromArgb(fillAlpha, Theme.GlassFill)); + g.FillPath(brush2, path3); + } + else + { + using LinearGradientBrush brush3 = new LinearGradientBrush(new RectangleF(rect.X, rect.Y - 1f, rect.Width, rect.Height + 2f), Color.FromArgb(Math.Min(255, fillAlpha + 16), Lift(Theme.GlassFill, 0.05f)), Color.FromArgb(fillAlpha, Theme.GlassFill), LinearGradientMode.Vertical) + { + WrapMode = WrapMode.TileFlipXY + }; + g.FillPath(brush3, path3); + } + using (Pen pen3 = new Pen(Color.FromArgb(rimAlpha, Theme.GlassEdge), 1.2f)) + { + g.DrawPath(pen3, path3); + } + if (!Flat && rect.Width > radius * 2f + 4f) + { + using (Pen pen4 = new Pen(Color.FromArgb(Theme.IsLight ? 90 : 42, 255, 255, 255), 1f)) + { + g.DrawLine(pen4, rect.X + radius, rect.Y + 1.5f, rect.Right - radius, rect.Y + 1.5f); + return; + } + } + } + + public static void PaintChrome(Graphics g, RectangleF rect, float radius, Point backdropOffset, int fillAlpha = 140, int rimAlpha = 105) + { + if (!(rect.Width < 2f) && !(rect.Height < 2f)) + { + if (SlateSurface.Active) + { + PaintSlateChrome(g, Rectangle.Round(rect), backdropOffset, SlateSurface.ChromeAlpha); + } + else + { + PaintPanel(g, rect, radius, backdropOffset, fillAlpha, rimAlpha); + } + } + } + + private static void PaintSlateChrome(Graphics g, Rectangle rect, Point backdropOffset, int alpha) + { + SmoothingMode smoothingMode = g.SmoothingMode; + g.SmoothingMode = SmoothingMode.None; + try + { + if (SlateSurface.MatteBlur && AppBackground.IsSet) + { + using GraphicsPath graphicsPath = new GraphicsPath(); + graphicsPath.AddRectangle(rect); + AppBackground.FillWithBlurred(g, graphicsPath, backdropOffset.X, backdropOffset.Y); + } + using SolidBrush brush = new SolidBrush(Color.FromArgb(alpha, SlateSurface.Base)); + g.FillRectangle(brush, rect); + } + finally + { + g.SmoothingMode = smoothingMode; + } + } + + private static void PaintSlateSurface(Graphics g, RectangleF rect, float radius, Point backdropOffset, int alpha) + { + SlateSurfacesDrawn++; + g.SmoothingMode = SmoothingMode.AntiAlias; + if (SlateInteriorShortcutForTests) + { + RectangleF? rectangleF = PlainInsideToFill(g, rect, radius); + if (rectangleF.HasValue) + { + RectangleF valueOrDefault = rectangleF.GetValueOrDefault(); + if (SlateSurface.MatteBlur && AppBackground.IsSet) + { + AppBackground.FillWithBlurred(g, valueOrDefault, backdropOffset.X, backdropOffset.Y); + } + using SolidBrush brush = new SolidBrush(Color.FromArgb(alpha, SlateSurface.Base)); + g.FillRectangle(brush, valueOrDefault); + return; + } + } + SlateOutlinesTraced++; + using GraphicsPath path = RoundedPath(rect, radius); + if (SlateSurface.MatteBlur && AppBackground.IsSet) + { + AppBackground.FillWithBlurred(g, path, backdropOffset.X, backdropOffset.Y); + } + using (SolidBrush brush2 = new SolidBrush(Color.FromArgb(alpha, SlateSurface.Base))) + { + g.FillPath(brush2, path); + } + using Pen pen = new Pen(SignalTokens.Slate.Border, 1f); + g.DrawPath(pen, path); + } + + private static RectangleF? PlainInsideToFill(Graphics g, RectangleF rect, float radius) + { + GraphicsUnit pageUnit = g.PageUnit; + bool flag = (uint)(pageUnit - 1) <= 1u; + if (!flag || g.PageScale != 1f) + { + return null; + } + Matrix3x2 transformElements = g.TransformElements; + if (transformElements.M11 != 1f || transformElements.M12 != 0f || transformElements.M21 != 0f || transformElements.M22 != 1f) + { + return null; + } + if (Flat) + { + radius = 0f; + } + radius = Math.Max(0f, Math.Min(radius, Math.Min(rect.Width, rect.Height) / 2f)); + RectangleF visibleClipBounds = g.VisibleClipBounds; + if (visibleClipBounds.Width <= 0f || visibleClipBounds.Height <= 0f) + { + return null; + } + RectangleF rectangleF = RectangleF.FromLTRB(MathF.Floor(visibleClipBounds.Left) - 1f, MathF.Floor(visibleClipBounds.Top) - 1f, MathF.Ceiling(visibleClipBounds.Right) + 1f, MathF.Ceiling(visibleClipBounds.Bottom) + 1f); + float num = radius + 2f; + RectangleF rectangleF2 = RectangleF.FromLTRB(rect.Left + num, rect.Top + num, rect.Right - num, rect.Bottom - num); + if (!(rectangleF2.Width > 0f) || !(rectangleF2.Height > 0f) || !rectangleF2.Contains(rectangleF)) + { + return null; + } + return rectangleF; + } + + public static void PaintAccent(Graphics g, RectangleF rect, float radius, Color accent, int alpha = 210) + { + if (rect.Width < 2f || rect.Height < 2f) + { + return; + } + if (SlateSurface.Active) + { + g.SmoothingMode = SmoothingMode.AntiAlias; + using GraphicsPath path = RoundedPath(rect, radius); + using (SolidBrush brush = new SolidBrush(Color.FromArgb(alpha, accent))) + { + g.FillPath(brush, path); + } + using Pen pen = new Pen(SignalTokens.Slate.Border, 1f); + g.DrawPath(pen, path); + return; + } + if (Soft) + { + g.SmoothingMode = SmoothingMode.AntiAlias; + using GraphicsPath path2 = RoundedPath(rect, radius * 1.45f); + using (SolidBrush brush2 = new SolidBrush(Color.FromArgb(alpha, accent))) + { + g.FillPath(brush2, path2); + } + using Pen pen2 = new Pen(Color.FromArgb(200, accent), 1f); + g.DrawPath(pen2, path2); + return; + } + g.SmoothingMode = SmoothingMode.AntiAlias; + using GraphicsPath path3 = RoundedPath(rect, radius); + if (Flat) + { + using SolidBrush brush3 = new SolidBrush(Color.FromArgb(alpha, accent)); + g.FillPath(brush3, path3); + } + else + { + using LinearGradientBrush brush4 = new LinearGradientBrush(new RectangleF(rect.X, rect.Y - 1f, rect.Width, rect.Height + 2f), Color.FromArgb(alpha, Lift(accent, 0.12f)), Color.FromArgb(alpha, accent), LinearGradientMode.Vertical) + { + WrapMode = WrapMode.TileFlipXY + }; + g.FillPath(brush4, path3); + } + using (Pen pen3 = new Pen(Color.FromArgb(120, Theme.GlassEdge), 1.2f)) + { + g.DrawPath(pen3, path3); + } + if (!Flat && rect.Width > radius * 2f + 4f) + { + using (Pen pen4 = new Pen(Color.FromArgb(70, 255, 255, 255), 1f)) + { + g.DrawLine(pen4, rect.X + radius, rect.Y + 1.5f, rect.Right - radius, rect.Y + 1.5f); + return; + } + } + } +} diff --git a/VibranceHud/GlassButton.cs b/VibranceHud/GlassButton.cs new file mode 100644 index 0000000..f5ff33b --- /dev/null +++ b/VibranceHud/GlassButton.cs @@ -0,0 +1,569 @@ +using System; +using System.Diagnostics; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; +using VibranceHud.Design; + +namespace VibranceHud; + +public sealed class GlassButton : Control +{ + private sealed class ButtonAccessibleObject : ControlAccessibleObject + { + private readonly GlassButton _owner; + + public override AccessibleStates State => (AccessibleStates)((int)base.State | (_owner._loading ? 2048 : 0)); + + public ButtonAccessibleObject(GlassButton owner) + : base(owner) + { + _owner = owner; + } + } + + private readonly HoverFade _fade; + + private readonly HoverFade _press; + + private readonly OutsideFocusRing _ring; + + private GlassButtonKind _kind = GlassButtonKind.Secondary; + + private SignalIcon _icon; + + private SignalIcon _trailing; + + private bool _loading; + + private Stopwatch? _loadingSince; + + private Timer? _spin; + + private (string Text, Font Font, Size Size)? _measured; + + public GlassButtonKind Kind + { + get + { + return _kind; + } + set + { + if (_kind != value) + { + _kind = value; + AccessibleRole = ((value == GlassButtonKind.Link) ? AccessibleRole.Link : AccessibleRole.PushButton); + _measured = null; + Invalidate(); + } + } + } + + public SignalIcon Icon + { + get + { + return _icon; + } + set + { + if (_icon != value) + { + _icon = value; + Invalidate(); + } + } + } + + public SignalIcon TrailingIcon + { + get + { + return _trailing; + } + set + { + if (_trailing != value) + { + _trailing = value; + Invalidate(); + } + } + } + + public bool Loading + { + get + { + return _loading; + } + set + { + if (_loading == value) + { + return; + } + _loading = value; + if (value) + { + _loadingSince = Stopwatch.StartNew(); + if (_spin == null) + { + _spin = new Timer + { + Interval = 16 + }; + } + _spin.Tick -= OnSpin; + _spin.Tick += OnSpin; + _spin.Start(); + } + else + { + _spin?.Stop(); + _loadingSince = null; + } + Invalidate(); + if (IsHandleCreated) + { + AccessibilityNotifyClients(AccessibleEvents.StateChange, -1); + } + } + } + + internal bool KeyboardFocusForTest { get; set; } + + public override bool Focused + { + get + { + if (!KeyboardFocusForTest) + { + return base.Focused; + } + return true; + } + } + + protected override bool ShowFocusCues + { + get + { + if (!KeyboardFocusForTest) + { + return base.ShowFocusCues; + } + return true; + } + } + + internal bool FocusRingShownForTest => _ring.Shown; + + private Font LabelFont + { + get + { + if (Kind != GlassButtonKind.Link) + { + return Font; + } + return Fonts.Body; + } + } + + private bool HasLead + { + get + { + if (_icon == SignalIcon.None) + { + return SpinnerShowing; + } + return true; + } + } + + private bool SpinnerShowing + { + get + { + if (!SpinnerForTest) + { + if (_loading) + { + Stopwatch loadingSince = _loadingSince; + if (loadingSince != null) + { + return loadingSince.ElapsedMilliseconds >= 300; + } + } + return false; + } + return true; + } + } + + internal bool SpinnerForTest { get; set; } + + public GlassButton() + { + _fade = new HoverFade(this); + _press = new HoverFade(this); + _ring = new OutsideFocusRing(this, () => Radius(ControlInk.Dpi(this))); + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + Cursor = Cursors.Hand; + Height = 32; + Font = Fonts.BodyBold; + TabStop = true; + SetStyle(ControlStyles.Selectable, value: true); + AccessibleRole = AccessibleRole.PushButton; + } + + protected override AccessibleObject CreateAccessibilityInstance() + { + return new ButtonAccessibleObject(this); + } + + private void OnSpin(object? sender, EventArgs e) + { + if (Visible && !IsDisposed) + { + Invalidate(); + } + } + + protected override void OnTextChanged(EventArgs e) + { + base.OnTextChanged(e); + AccessibleName = Text; + _measured = null; + } + + protected override void OnFontChanged(EventArgs e) + { + base.OnFontChanged(e); + _measured = null; + } + + protected override void OnGotFocus(EventArgs e) + { + base.OnGotFocus(e); + Invalidate(); + } + + protected override void OnLostFocus(EventArgs e) + { + base.OnLostFocus(e); + Invalidate(); + } + + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + Keys keyCode = e.KeyCode; + if ((keyCode == Keys.Return || keyCode == Keys.Space) ? true : false) + { + e.Handled = true; + OnClick(EventArgs.Empty); + } + } + + protected override void OnClick(EventArgs e) + { + if (!_loading) + { + base.OnClick(e); + } + } + + internal void TestPressKey(Keys key) + { + OnKeyDown(new KeyEventArgs(key)); + } + + internal void TestSetHover(bool on) + { + _fade.Snap(on); + } + + internal void TestSetPressed(bool on) + { + _press.Snap(on); + } + + public void PerformClick() + { + if (Enabled) + { + OnClick(EventArgs.Empty); + } + } + + protected override void OnEnabledChanged(EventArgs e) + { + base.OnEnabledChanged(e); + Cursor = (Enabled ? Cursors.Hand : Cursors.Default); + _fade.Snap(hot: false); + _press.Snap(hot: false); + Invalidate(); + } + + protected override void OnMouseEnter(EventArgs e) + { + base.OnMouseEnter(e); + _fade.Set(hot: true); + Invalidate(); + } + + protected override void OnMouseLeave(EventArgs e) + { + base.OnMouseLeave(e); + _press.Set(hot: false); + _fade.Set(hot: false); + Invalidate(); + } + + protected override void OnMouseDown(MouseEventArgs e) + { + base.OnMouseDown(e); + if (e.Button == MouseButtons.Left) + { + Focus(); + _press.Snap(hot: true); + Invalidate(); + } + } + + protected override void OnMouseUp(MouseEventArgs e) + { + base.OnMouseUp(e); + _press.Set(hot: false); + Invalidate(); + } + + protected override void OnParentChanged(EventArgs e) + { + base.OnParentChanged(e); + _ring.Rehook(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _spin?.Dispose(); + _ring.Release(); + } + base.Dispose(disposing); + } + + private static float Radius(int dpi) + { + return ControlInk.PxF(dpi, 4f); + } + + private Size LabelSize() + { + Font labelFont = LabelFont; + (string, Font, Size)? measured = _measured; + if (measured.HasValue) + { + (string, Font, Size) valueOrDefault = measured.GetValueOrDefault(); + if (valueOrDefault.Item1 == Text && valueOrDefault.Item2 == labelFont) + { + return valueOrDefault.Item3; + } + } + Size size = (string.IsNullOrEmpty(Text) ? Size.Empty : TextRenderer.MeasureText(Text, labelFont, Size.Empty, TextFormatFlags.NoPrefix | TextFormatFlags.SingleLine | TextFormatFlags.NoPadding)); + _measured = (Text, labelFont, size); + return size; + } + + public override Size GetPreferredSize(Size proposedSize) + { + int dpi = ControlInk.Dpi(this); + if (Kind == GlassButtonKind.Icon) + { + return new Size(Height, Height); + } + int num = ContentWidth(dpi); + if (Kind == GlassButtonKind.Link) + { + return new Size(num, Height); + } + int num2 = ControlInk.Px(dpi, (Kind == GlassButtonKind.Quiet) ? 8 : 12); + return new Size(Math.Max(ControlInk.Px(dpi, (Height >= ControlInk.Px(dpi, 30)) ? 64 : 56), num + 2 * num2), Height); + } + + private int ContentWidth(int dpi) + { + int num = ControlInk.Px(dpi, 16); + int num2 = ControlInk.Px(dpi, 8); + int num3 = LabelSize().Width; + if (HasLead) + { + num3 += num + ((num3 > 0) ? num2 : 0); + } + if (_trailing != SignalIcon.None) + { + num3 += num2 + num; + } + return num3; + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics graphics = e.Graphics; + int dpi = ControlInk.Dpi(this); + float hot = (Enabled ? _fade.Value : 0f); + float down = (Enabled ? _press.Value : 0f); + (Color, Color, Color, Color) tuple = Look(hot, down); + if (Kind != GlassButtonKind.Link) + { + ControlInk.PaintBox(graphics, ClientSize, Radius(dpi), ControlInk.Hairline(dpi), tuple.Item1, tuple.Item2); + } + DrawContent(graphics, dpi, tuple.Item3, tuple.Item4); + if (Focused && ShowFocusCues) + { + _ring.Show(show: true); + } + else + { + _ring.Show(show: false); + } + } + + private (Color Fill, Color Edge, Color Ink, Color Underline) Look(float hot, float down) + { + Color transparent = Color.Transparent; + if (!Enabled) + { + switch (Kind) + { + case GlassButtonKind.Primary: + return (Fill: ControlInk.Surface2, Edge: ControlInk.Surface2, Ink: ControlInk.TextDisabledInk, Underline: transparent); + case GlassButtonKind.Secondary: + case GlassButtonKind.Destructive: + return (Fill: transparent, Edge: ControlInk.TextDisabled, Ink: ControlInk.TextDisabledInk, Underline: transparent); + default: + return (Fill: transparent, Edge: transparent, Ink: ControlInk.TextDisabledInk, Underline: transparent); + } + } + Color hover = ControlInk.Hover; + Color item = ControlInk.Mix(ControlInk.Mix(Color.FromArgb(0, hover), hover, hot), ControlInk.Pressed, down); + switch (Kind) + { + case GlassButtonKind.Primary: + { + Color color = ControlInk.Mix(ControlInk.Mix(ControlInk.Accent, ControlInk.AccentHover, hot), ControlInk.AccentPressed, down); + return (Fill: color, Edge: color, Ink: ControlInk.OnAccent, Underline: transparent); + } + case GlassButtonKind.Destructive: + return (Fill: item, Edge: ControlInk.Edge, Ink: ControlInk.Danger, Underline: transparent); + case GlassButtonKind.Quiet: + case GlassButtonKind.Icon: + return (Fill: item, Edge: transparent, Ink: ControlInk.Mix(ControlInk.Text2, ControlInk.Text1, Math.Max(hot, down)), Underline: transparent); + case GlassButtonKind.Link: + { + Color item2 = ControlInk.Mix(ControlInk.Text1, ControlInk.Text2, down); + Color item3 = ControlInk.Mix(ControlInk.Mix(ControlInk.Edge, ControlInk.Text1, hot), ControlInk.Text2, down); + return (Fill: transparent, Edge: transparent, Ink: item2, Underline: item3); + } + default: + return (Fill: item, Edge: ControlInk.Edge, Ink: ControlInk.Text1, Underline: transparent); + } + } + + private void DrawContent(Graphics g, int dpi, Color ink, Color underline) + { + int num = ControlInk.Px(dpi, 16); + int num2 = ControlInk.Px(dpi, 8); + int num3 = Height / 2; + if (Kind == GlassButtonKind.Icon) + { + RectangleF box = new RectangleF((float)(Width - num) / 2f, (float)num3 - (float)num / 2f, num, num); + if (SpinnerShowing) + { + DrawSpinner(g, box, ink, dpi); + } + else + { + SignalIcons.Draw(g, _icon, box, ink); + } + return; + } + Size size = LabelSize(); + int num4 = (Width - ContentWidth(dpi)) / 2; + if (HasLead) + { + RectangleF box2 = new RectangleF(num4, (float)num3 - (float)num / 2f, num, num); + if (SpinnerShowing) + { + DrawSpinner(g, box2, ink, dpi); + } + else + { + SignalIcons.Draw(g, _icon, box2, ink); + } + num4 += num + ((size.Width > 0) ? num2 : 0); + } + if (size.Width > 0) + { + Font labelFont = LabelFont; + TextRenderer.DrawText(g, Text, labelFont, new Rectangle(num4, 0, size.Width + 2, Height), ink, TextFormatFlags.NoPrefix | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding); + if (Kind == GlassButtonKind.Link && underline.A > 0) + { + FontFamily fontFamily = labelFont.FontFamily; + float num5 = (float)(labelFont.Height * fontFamily.GetCellAscent(labelFont.Style)) / (float)fontFamily.GetLineSpacing(labelFont.Style); + int num6 = (int)Math.Round((float)(Height - labelFont.Height) / 2f + num5); + int y = Math.Min(Height - ControlInk.Hairline(dpi), num6 + ControlInk.Px(dpi, 3)); + using SolidBrush brush = new SolidBrush(underline); + g.FillRectangle(brush, num4, y, size.Width, ControlInk.Hairline(dpi)); + } + num4 += size.Width; + } + if (_trailing != SignalIcon.None) + { + num4 += num2; + SignalIcons.Draw(g, _trailing, new RectangleF(num4, (float)num3 - (float)num / 2f, num, num), ink); + } + } + + private void DrawSpinner(Graphics g, RectangleF box, Color ink, int dpi) + { + float num = ControlInk.PxF(dpi, 1.5f); + RectangleF rect = RectangleF.Inflate(box, 0f - num, 0f - num); + float num2; + if (SystemInformation.UIEffectsEnabled) + { + Stopwatch loadingSince = _loadingSince; + if (loadingSince != null) + { + num2 = (float)(loadingSince.ElapsedMilliseconds % 800) / 800f * 360f; + goto IL_004a; + } + } + num2 = 0f; + goto IL_004a; + IL_004a: + float num3 = num2; + SmoothingMode smoothingMode = g.SmoothingMode; + g.SmoothingMode = SmoothingMode.AntiAlias; + if (Kind != GlassButtonKind.Primary) + { + using Pen pen = new Pen(ControlInk.Track, num); + g.DrawEllipse(pen, rect); + } + using (Pen pen2 = new Pen(ink, num) + { + StartCap = LineCap.Round, + EndCap = LineCap.Round + }) + { + g.DrawArc(pen2, rect, num3 - 90f, 270f); + } + g.SmoothingMode = smoothingMode; + } +} diff --git a/VibranceHud/GlassButtonKind.cs b/VibranceHud/GlassButtonKind.cs new file mode 100644 index 0000000..9ab7e79 --- /dev/null +++ b/VibranceHud/GlassButtonKind.cs @@ -0,0 +1,12 @@ +namespace VibranceHud; + +public enum GlassButtonKind +{ + Primary = 0, + Secondary = 1, + Quiet = 2, + Destructive = 3, + Icon = 4, + Link = 5, + Ghost = Secondary +} diff --git a/VibranceHud/GlassDropdown.cs b/VibranceHud/GlassDropdown.cs new file mode 100644 index 0000000..555f9cc --- /dev/null +++ b/VibranceHud/GlassDropdown.cs @@ -0,0 +1,387 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Windows.Forms; +using VibranceHud.Design; + +namespace VibranceHud; + +public sealed class GlassDropdown : Control +{ + private sealed class DropdownAccessibleObject : ControlAccessibleObject + { + private readonly GlassDropdown _owner; + + public override string? Value + { + get + { + return _owner.SelectedItem; + } + set + { + } + } + + public override AccessibleStates State => (AccessibleStates)((int)base.State | (_owner._open ? 512 : 1024)); + + public DropdownAccessibleObject(GlassDropdown owner) + : base(owner) + { + _owner = owner; + } + } + + private readonly List _items = new List(); + + private int _selectedIndex = -1; + + private bool _open; + + private readonly HoverFade _fade; + + private readonly OutsideFocusRing _ring; + + private long _closedAtTicks; + + internal static int LivePopupCount; + + private ToolStripDropDown? _menu; + + public string Placeholder { get; set; } = "Select..."; + + public IReadOnlyList Items => _items; + + public int SelectedIndex + { + get + { + return _selectedIndex; + } + set + { + int num = ((_items.Count == 0) ? (-1) : Math.Clamp(value, -1, _items.Count - 1)); + if (num != _selectedIndex) + { + _selectedIndex = num; + Invalidate(); + if (IsHandleCreated) + { + AccessibilityNotifyClients(AccessibleEvents.ValueChange, -1); + } + SelectedIndexChanged?.Invoke(this, EventArgs.Empty); + } + } + } + + public string SelectedItem + { + get + { + if (_selectedIndex < 0 || _selectedIndex >= _items.Count) + { + return ""; + } + return _items[_selectedIndex]; + } + } + + public event EventHandler? SelectedIndexChanged; + + public GlassDropdown() + { + _fade = new HoverFade(this); + _ring = new OutsideFocusRing(this, () => Radius(ControlInk.Dpi(this))); + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + Cursor = Cursors.Hand; + Height = 32; + Font = Fonts.Body; + TabStop = true; + SetStyle(ControlStyles.Selectable, value: true); + AccessibleRole = AccessibleRole.ComboBox; + } + + protected override AccessibleObject CreateAccessibilityInstance() + { + return new DropdownAccessibleObject(this); + } + + protected override void OnGotFocus(EventArgs e) + { + base.OnGotFocus(e); + Invalidate(); + } + + protected override void OnLostFocus(EventArgs e) + { + base.OnLostFocus(e); + Invalidate(); + } + + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + if (!Enabled || _items.Count == 0) + { + return; + } + switch (e.KeyCode) + { + case Keys.Return: + case Keys.Space: + case Keys.F4: + Open(); + e.Handled = true; + break; + case Keys.Down: + if (e.Alt) + { + Open(); + e.Handled = true; + break; + } + goto case Keys.Right; + case Keys.Right: + SelectedIndex = Math.Min(_selectedIndex + 1, _items.Count - 1); + e.Handled = true; + break; + case Keys.Left: + case Keys.Up: + SelectedIndex = Math.Max(_selectedIndex - 1, 0); + e.Handled = true; + break; + case Keys.Home: + SelectedIndex = 0; + e.Handled = true; + break; + case Keys.End: + SelectedIndex = _items.Count - 1; + e.Handled = true; + break; + case Keys.D0: + case Keys.D1: + case Keys.D2: + case Keys.D3: + case Keys.D4: + case Keys.D5: + case Keys.D6: + case Keys.D7: + case Keys.D8: + case Keys.D9: + case Keys.A: + case Keys.B: + case Keys.C: + case Keys.D: + case Keys.E: + case Keys.F: + case Keys.G: + case Keys.H: + case Keys.I: + case Keys.J: + case Keys.K: + case Keys.L: + case Keys.M: + case Keys.N: + case Keys.O: + case Keys.P: + case Keys.Q: + case Keys.R: + case Keys.S: + case Keys.T: + case Keys.U: + case Keys.V: + case Keys.W: + case Keys.X: + case Keys.Y: + case Keys.Z: + JumpToItemStartingWith((char)e.KeyValue); + e.Handled = true; + break; + } + } + + private void JumpToItemStartingWith(char key) + { + for (int i = 1; i <= _items.Count; i++) + { + int num = (((_selectedIndex < 0) ? (-1) : _selectedIndex) + i) % _items.Count; + if (_items[num].Length > 0 && char.ToUpperInvariant(_items[num][0]) == char.ToUpperInvariant(key)) + { + SelectedIndex = num; + break; + } + } + } + + protected override bool IsInputKey(Keys keyData) + { + Keys keys = keyData & ~Keys.Alt; + if ((uint)(keys - 35) <= 5u || keys == Keys.F4) + { + return true; + } + return base.IsInputKey(keyData); + } + + internal bool TestClaimsKey(Keys key) + { + return IsInputKey(key); + } + + internal void TestPressKey(Keys key) + { + OnKeyDown(new KeyEventArgs(key)); + } + + internal void TestSetHover(bool on) + { + _fade.Snap(on); + } + + internal void TestSetOpen(bool on) + { + _open = on; + } + + internal ToolStripDropDown BuildMenuForTest() + { + int rowH; + return BuildMenu(out rowH); + } + + public void SetItems(IEnumerable items) + { + _items.Clear(); + _items.AddRange(items); + _selectedIndex = ((_items.Count <= 0) ? (-1) : 0); + Invalidate(); + SelectedIndexChanged?.Invoke(this, EventArgs.Empty); + } + + protected override void OnMouseEnter(EventArgs e) + { + base.OnMouseEnter(e); + _fade.Set(hot: true); + Invalidate(); + } + + protected override void OnMouseLeave(EventArgs e) + { + base.OnMouseLeave(e); + _fade.Set(hot: false); + Invalidate(); + } + + protected override void OnEnabledChanged(EventArgs e) + { + base.OnEnabledChanged(e); + Cursor = (Enabled ? Cursors.Hand : Cursors.Default); + _fade.Snap(hot: false); + Invalidate(); + } + + protected override void OnParentChanged(EventArgs e) + { + base.OnParentChanged(e); + _ring.Rehook(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _ring.Release(); + } + base.Dispose(disposing); + } + + protected override void OnMouseDown(MouseEventArgs e) + { + base.OnMouseDown(e); + if (e.Button == MouseButtons.Left && Environment.TickCount64 - _closedAtTicks >= 200) + { + Open(); + } + } + + internal void TestCloseMenu() + { + _menu?.Close(); + } + + private ToolStripDropDown BuildMenu(out int rowH) + { + rowH = SignalMenu.RowHeight(ControlInk.Dpi(this), Font); + ToolStripDropDown toolStripDropDown = SignalMenu.SelectList(this); + int width = SignalMenu.RowWidth(this); + for (int i = 0; i < _items.Count; i++) + { + int index = i; + ToolStripMenuItem toolStripMenuItem = SignalMenu.SelectItem(_items[i], index == _selectedIndex, width, rowH); + toolStripMenuItem.Font = Font; + toolStripMenuItem.Click += (object? _, EventArgs _) => + { + SelectedIndex = index; + }; + toolStripDropDown.Items.Add(toolStripMenuItem); + } + return toolStripDropDown; + } + + private void Open() + { + if (_items.Count == 0) + { + return; + } + ToolStripDropDown menu = BuildMenu(out var _); + _menu = menu; + LivePopupCount++; + menu.Disposed += (object? _, EventArgs _) => + { + LivePopupCount--; + }; + menu.Closed += (object? _, ToolStripDropDownClosedEventArgs _) => + { + _open = false; + _closedAtTicks = Environment.TickCount64; + if (_menu == menu) + { + _menu = null; + } + Invalidate(); + if (IsHandleCreated) + { + AccessibilityNotifyClients(AccessibleEvents.StateChange, -1); + } + BeginInvoke(menu.Dispose); + }; + _open = true; + Invalidate(); + if (IsHandleCreated) + { + AccessibilityNotifyClients(AccessibleEvents.StateChange, -1); + } + SignalMenu.ShowUnder(menu, this); + } + + private static float Radius(int dpi) + { + return ControlInk.PxF(dpi, 4f); + } + + protected override void OnPaint(PaintEventArgs e) + { + bool flag = _selectedIndex >= 0; + SignalMenu.PaintTrigger(e.Graphics, ClientSize, ControlInk.Dpi(this), Font, flag ? SelectedItem : Placeholder, !flag, _open, _fade.Value, Enabled); + if (Focused && ShowFocusCues) + { + _ring.Show(show: true); + } + else + { + _ring.Show(show: false); + } + } +} diff --git a/VibranceHud/GlassLink.cs b/VibranceHud/GlassLink.cs new file mode 100644 index 0000000..95b9e2b --- /dev/null +++ b/VibranceHud/GlassLink.cs @@ -0,0 +1,197 @@ +using System; +using System.Drawing; +using System.Windows.Forms; +using VibranceHud.Design; + +namespace VibranceHud; + +public sealed class GlassLink : Control +{ + private bool _hover; + + private bool _pressed; + + private readonly OutsideFocusRing _ring; + + private ContentAlignment _align = ContentAlignment.MiddleCenter; + + private const TextFormatFlags Measure = TextFormatFlags.SingleLine | TextFormatFlags.NoPadding; + + public ContentAlignment TextAlign + { + get + { + return _align; + } + set + { + if (_align != value) + { + _align = value; + Invalidate(); + } + } + } + + public GlassLink() + { + _ring = new OutsideFocusRing(this, () => ControlInk.PxF(ControlInk.Dpi(this), 4f)); + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.Selectable | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + Cursor = Cursors.Hand; + Height = 20; + Font = Fonts.Body; + TabStop = true; + AccessibleRole = AccessibleRole.Link; + } + + protected override void OnTextChanged(EventArgs e) + { + base.OnTextChanged(e); + AccessibleName = Text; + } + + protected override void OnMouseEnter(EventArgs e) + { + base.OnMouseEnter(e); + _hover = true; + Invalidate(); + } + + protected override void OnMouseLeave(EventArgs e) + { + base.OnMouseLeave(e); + _hover = false; + _pressed = false; + Invalidate(); + } + + protected override void OnGotFocus(EventArgs e) + { + base.OnGotFocus(e); + Invalidate(); + } + + protected override void OnLostFocus(EventArgs e) + { + base.OnLostFocus(e); + Invalidate(); + } + + protected override void OnMouseDown(MouseEventArgs e) + { + base.OnMouseDown(e); + Focus(); + if (e.Button == MouseButtons.Left) + { + _pressed = true; + Invalidate(); + } + } + + protected override void OnMouseUp(MouseEventArgs e) + { + base.OnMouseUp(e); + if (_pressed) + { + _pressed = false; + Invalidate(); + } + } + + protected override void OnEnabledChanged(EventArgs e) + { + base.OnEnabledChanged(e); + Cursor = (Enabled ? Cursors.Hand : Cursors.Default); + _hover = false; + _pressed = false; + Invalidate(); + } + + protected override void OnParentChanged(EventArgs e) + { + base.OnParentChanged(e); + _ring.Rehook(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _ring.Release(); + } + base.Dispose(disposing); + } + + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + Keys keyCode = e.KeyCode; + if ((keyCode == Keys.Return || keyCode == Keys.Space) ? true : false) + { + e.Handled = true; + OnClick(EventArgs.Empty); + } + } + + internal void TestPressKey(Keys key) + { + OnKeyDown(new KeyEventArgs(key)); + } + + public void PerformClick() + { + if (Enabled) + { + OnClick(EventArgs.Empty); + } + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics graphics = e.Graphics; + int dpi = ControlInk.Dpi(this); + Color foreColor; + Color color; + if (!Enabled) + { + foreColor = ControlInk.TextDisabledInk; + color = Color.Transparent; + } + else if (_pressed) + { + foreColor = (color = ControlInk.Text2); + } + else + { + foreColor = ControlInk.Text1; + color = (_hover ? ControlInk.Text1 : ControlInk.Edge); + } + Size size = TextRenderer.MeasureText(graphics, Text, Font, Size.Empty, TextFormatFlags.SingleLine | TextFormatFlags.NoPadding); + int x = _align switch + { + ContentAlignment.MiddleLeft => 0, + ContentAlignment.MiddleRight => Width - size.Width, + _ => (Width - size.Width) / 2, + }; + TextRenderer.DrawText(graphics, Text, Font, new Rectangle(x, 0, size.Width + 2, Height), foreColor, TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding); + if (color.A > 0 && size.Width > 0) + { + FontFamily fontFamily = Font.FontFamily; + float num = (float)(Font.Height * fontFamily.GetCellAscent(Font.Style)) / (float)fontFamily.GetLineSpacing(Font.Style); + int num2 = ControlInk.Hairline(dpi); + int val = (int)Math.Round((float)(Height - Font.Height) / 2f + num) + ControlInk.Px(dpi, 3); + val = Math.Min(val, Height - num2); + using SolidBrush brush = new SolidBrush(color); + graphics.FillRectangle(brush, x, val, size.Width, num2); + } + if (Focused && Enabled && ShowFocusCues) + { + _ring.Show(show: true); + } + else + { + _ring.Show(show: false); + } + } +} diff --git a/VibranceHud/GlassTextBox.cs b/VibranceHud/GlassTextBox.cs new file mode 100644 index 0000000..10f83e5 --- /dev/null +++ b/VibranceHud/GlassTextBox.cs @@ -0,0 +1,430 @@ +using System; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.Drawing; +using System.Windows.Forms; +using VibranceHud.Controls; +using VibranceHud.Design; + +namespace VibranceHud; + +public sealed class GlassTextBox : Control +{ + private sealed class NamedTextBox : TextBox + { + private sealed class Accessible : ControlAccessibleObject + { + private readonly NamedTextBox _box; + + public override string? Name + { + get + { + _box._sync(); + return base.Name; + } + set + { + base.Name = value; + } + } + + public override string? Description + { + get + { + _box._sync(); + return base.Description; + } + } + + public Accessible(NamedTextBox box) + : base(box) + { + _box = box; + } + } + + private readonly Action _sync; + + public NamedTextBox(Action sync) + { + _sync = sync; + } + + protected override AccessibleObject CreateAccessibilityInstance() + { + return new Accessible(this); + } + } + + private readonly TextBox _inner; + + private readonly OutsideFocusRing _ring; + + private const int PadX = 12; + + private const int IconPadLeft = 8; + + private const int IconSize = 16; + + private const int IconGap = 8; + + private SignalIcon _leadingIcon; + + private bool _focusOnEdge; + + private string _placeholder = ""; + + private bool _innerNameIsOurs; + + private bool _innerDescriptionIsOurs; + + public TextBox Inner => _inner; + + public bool FocusOnEdge + { + get + { + return _focusOnEdge; + } + set + { + if (_focusOnEdge != value) + { + _focusOnEdge = value; + if (value) + { + _ring.Show(show: false); + } + Invalidate(); + } + } + } + + internal Color EdgeInk + { + get + { + if (Enabled) + { + if (!_focusOnEdge || !ContainsFocus) + { + return ControlInk.Edge; + } + return ControlInk.Text3; + } + return ControlInk.TextDisabled; + } + } + + public SignalIcon LeadingIcon + { + get + { + return _leadingIcon; + } + set + { + if (_leadingIcon != value) + { + _leadingIcon = value; + PerformLayout(); + Invalidate(); + } + } + } + + [Browsable(true)] + public override string Text + { + get + { + return _inner.Text ?? ""; + } + [param: AllowNull] + set + { + _inner.Text = value ?? ""; + } + } + + public string PlaceholderText + { + get + { + return _placeholder; + } + set + { + if (value == null) + { + value = ""; + } + if (!(_placeholder == value)) + { + _placeholder = value; + SyncAccessibleNames(); + SyncHint(); + } + } + } + + public bool ReadOnly + { + get + { + return _inner.ReadOnly; + } + set + { + _inner.ReadOnly = value; + } + } + + public int MaxLength + { + get + { + return _inner.MaxLength; + } + set + { + _inner.MaxLength = value; + } + } + + public CharacterCasing CharacterCasing + { + get + { + return _inner.CharacterCasing; + } + set + { + _inner.CharacterCasing = value; + } + } + + public bool Multiline + { + get + { + return _inner.Multiline; + } + set + { + _inner.Multiline = value; + if (value) + { + _inner.ScrollBars = ScrollBars.None; + } + PerformLayout(); + } + } + + private Color InnerGround + { + get + { + if (ControlInk.FieldFill.A != byte.MaxValue) + { + return GroundBehind; + } + return ControlInk.FieldFill; + } + } + + private Color GroundBehind + { + get + { + if (!(FindForm() is SignalDialogWindow)) + { + return Theme.Surface; + } + return ControlInk.Overlay; + } + } + + internal bool FocusRingShownForTest => _ring.Shown; + + private bool HintShowing + { + get + { + if (_placeholder.Length > 0 && _inner.Text.Length == 0) + { + return !ContainsFocus; + } + return false; + } + } + + public GlassTextBox() + { + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + _inner = new NamedTextBox(SyncAccessibleNames) + { + BorderStyle = BorderStyle.None, + BackColor = InnerGround, + ForeColor = Theme.Text, + Font = Fonts.Body + }; + _inner.GotFocus += (object? s, EventArgs e) => + { + _ring.Show(Enabled && !_focusOnEdge); + Invalidate(); + SyncHint(); + }; + _inner.LostFocus += (object? s, EventArgs e) => + { + _ring.Show(show: false); + Invalidate(); + SyncHint(); + }; + _inner.TextChanged += (object? s, EventArgs e) => + { + SyncHint(); + OnTextChanged(EventArgs.Empty); + }; + Controls.Add(_inner); + _ring = new OutsideFocusRing(this, () => ControlInk.PxF(ControlInk.Dpi(this), 4f)); + Height = 32; + } + + public void SetPlaceholder(string text) + { + PlaceholderText = text; + } + + private void SyncAccessibleNames() + { + if (_inner == null) + { + return; + } + string text = ((!string.IsNullOrEmpty(AccessibleName)) ? AccessibleName : _placeholder); + if (string.IsNullOrEmpty(_inner.AccessibleName) || _innerNameIsOurs) + { + string text2 = ((text.Length > 0) ? text : null); + if (_inner.AccessibleName != text2) + { + _inner.AccessibleName = text2; + } + _innerNameIsOurs = text2 != null; + } + string accessibleDescription = AccessibleDescription; + if (string.IsNullOrEmpty(_inner.AccessibleDescription) || _innerDescriptionIsOurs) + { + string text3 = (string.IsNullOrEmpty(accessibleDescription) ? null : accessibleDescription); + if (_inner.AccessibleDescription != text3) + { + _inner.AccessibleDescription = text3; + } + _innerDescriptionIsOurs = text3 != null; + } + } + + protected override void OnGotFocus(EventArgs e) + { + base.OnGotFocus(e); + if (!_inner.Visible) + { + _inner.Visible = true; + } + _inner.Focus(); + } + + protected override void OnMouseDown(MouseEventArgs e) + { + base.OnMouseDown(e); + if (e.Button == MouseButtons.Left && CanFocus && !ContainsFocus) + { + Focus(); + } + } + + protected override void OnParentChanged(EventArgs e) + { + base.OnParentChanged(e); + _ring.Rehook(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _ring.Release(); + } + base.Dispose(disposing); + } + + private int TextLeft(int dpi) + { + if (_leadingIcon != SignalIcon.None) + { + return ControlInk.Px(dpi, 32); + } + return ControlInk.Px(dpi, 12); + } + + protected override void OnLayout(LayoutEventArgs e) + { + base.OnLayout(e); + if (_inner != null) + { + int dpi = ControlInk.Dpi(this); + int num = TextLeft(dpi); + int width = Math.Max(1, Width - num - ControlInk.Px(dpi, 12)); + if (_inner.Multiline) + { + int num2 = ControlInk.Px(dpi, 6); + _inner.SetBounds(num, num2, width, Math.Max(1, Height - 2 * num2)); + } + else + { + int num3 = Math.Min(_inner.PreferredHeight, Math.Max(1, Height - ControlInk.Px(dpi, 6))); + _inner.SetBounds(num, Math.Max(0, (Height - num3) / 2), width, num3); + SyncHint(); + } + } + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics graphics = e.Graphics; + int dpi = ControlInk.Dpi(this); + Color innerGround = InnerGround; + Color color = (Enabled ? Theme.Text : ControlInk.TextDisabledInk); + if (_inner.BackColor != innerGround) + { + _inner.BackColor = innerGround; + } + if (_inner.ForeColor != color) + { + _inner.ForeColor = color; + } + ControlInk.PaintBox(graphics, ClientSize, ControlInk.PxF(dpi, 4f), ControlInk.Hairline(dpi), ControlInk.FieldFill, EdgeInk); + if (_leadingIcon != SignalIcon.None) + { + int num = ControlInk.Px(dpi, 16); + SignalIcons.Draw(graphics, _leadingIcon, new RectangleF(ControlInk.Px(dpi, 8), (float)(Height - num) / 2f, num, num), Enabled ? ControlInk.Text3 : ControlInk.TextDisabledInk); + } + if (HintShowing) + { + TextRenderer.DrawText(graphics, _placeholder, _inner.Font, _inner.Bounds, Enabled ? ControlInk.Text3 : ControlInk.TextDisabledInk, (TextFormatFlags)(0x10000800 | ((!_inner.Multiline) ? 4 : 0))); + } + _ring.Show(ContainsFocus && Enabled && !_focusOnEdge); + } + + private void SyncHint() + { + if (_inner != null) + { + _inner.Visible = !HintShowing; + Invalidate(); + } + } +} diff --git a/VibranceHud/GlowPanel.cs b/VibranceHud/GlowPanel.cs new file mode 100644 index 0000000..edb3be7 --- /dev/null +++ b/VibranceHud/GlowPanel.cs @@ -0,0 +1,37 @@ +using System.Drawing; +using System.Windows.Forms; +using VibranceHud.Design; +using VibranceHud.Theming; + +namespace VibranceHud; + +public sealed class GlowPanel : Panel +{ + public IBackdrop? Field { get; set; } + + public int Scrim { get; set; } + + public GlowPanel() + { + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics g = e.Graphics; + PaintGuard.Try(this, () => + { + AppBackground.Paint(g, Left, Top); + Field?.Paint(g, Left, Top); + if (SlateSurface.Active) + { + Glass.PaintChrome(g, ClientRectangle, 0f, new Point(Left, Top)); + return; + } + using SolidBrush brush = new SolidBrush(SignalTokens.Ash.Chrome); + g.FillRectangle(brush, ClientRectangle); + }); + base.OnPaint(e); + } +} diff --git a/VibranceHud/HeaderPanel.cs b/VibranceHud/HeaderPanel.cs new file mode 100644 index 0000000..d75d6e7 --- /dev/null +++ b/VibranceHud/HeaderPanel.cs @@ -0,0 +1,30 @@ +using System.Drawing; +using System.Windows.Forms; + +namespace VibranceHud; + +public sealed class HeaderPanel : Panel +{ + private readonly CardSurface _surface = new CardSurface(); + + public HeaderPanel() + { + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + } + + protected override void OnPaint(PaintEventArgs e) + { + _surface.Paint(this, e.Graphics); + base.OnPaint(e); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _surface.Dispose(); + } + base.Dispose(disposing); + } +} diff --git a/VibranceHud/HoloBlack.cs b/VibranceHud/HoloBlack.cs new file mode 100644 index 0000000..123fb5b --- /dev/null +++ b/VibranceHud/HoloBlack.cs @@ -0,0 +1,29 @@ +namespace VibranceHud; + +public static class HoloBlack +{ + public static float[] GreenSubtracted() + { + float[] array = Identity(); + array[0] = 1.5f; + array[1] = 1f; + array[2] = 0.5f; + array[5] = -1f; + array[6] = -1f; + array[7] = -1f; + array[10] = 0.5f; + array[11] = 1f; + array[12] = 1.5f; + return array; + } + + private static float[] Identity() + { + float[] array = new float[25]; + for (int i = 0; i < 5; i++) + { + array[i * 5 + i] = 1f; + } + return array; + } +} diff --git a/VibranceHud/HotkeyConflicts.cs b/VibranceHud/HotkeyConflicts.cs new file mode 100644 index 0000000..632262c --- /dev/null +++ b/VibranceHud/HotkeyConflicts.cs @@ -0,0 +1,139 @@ +using System; +using A; +using VibranceHud.Music; + +namespace VibranceHud; + +public static class HotkeyConflicts +{ + public static HotkeySlot? Owner(AppSettings settings, HotkeySlot target, uint mask, uint vk) + { + if (vk == 0) + { + return null; + } + HotkeySlot[] slots = MusicHotkey.Slots; + foreach (HotkeySlot hotkeySlot in slots) + { + (bool, uint, uint) tuple = MusicHotkey.Binding(settings, hotkeySlot); + if (target != hotkeySlot && tuple.Item1 && tuple.Item2 == mask && tuple.Item3 == vk) + { + return hotkeySlot; + } + } + if (target != HotkeySlot.QuickVibrance && settings.HotkeyVirtualKey == vk && settings.HotkeyModifierMask == mask) + { + return HotkeySlot.QuickVibrance; + } + if (target != HotkeySlot.MainWindow && settings.MainHotkeyEnabled && settings.MainHotkeyVirtualKey == vk && settings.MainHotkeyModifierMask == mask) + { + return HotkeySlot.MainWindow; + } + if (target != HotkeySlot.Screenshot && settings.ScreenshotHotkeyEnabled && settings.ScreenshotHotkeyVirtualKey == vk && settings.ScreenshotHotkeyModifierMask == mask) + { + return HotkeySlot.Screenshot; + } + if (target != HotkeySlot.NightVision && settings.NightVisionHotkeyEnabled && global::A.A.Available && settings.NightVisionHotkeyVirtualKey == vk && settings.NightVisionHotkeyModifierMask == mask) + { + return HotkeySlot.NightVision; + } + if (target == HotkeySlot.Zoom && global::A.A.Available && settings.HoldsTheNextSetupKey(mask, vk)) + { + return HotkeySlot.NightVision; + } + if (target != HotkeySlot.Zoom && settings.ZoomEnabled && global::A.A.Available && settings.ZoomHotkeyVirtualKey == vk && settings.ZoomHotkeyModifierMask == mask) + { + return HotkeySlot.Zoom; + } + return null; + } + + public static HotkeySlot? DarkBoostKeyOwner(AppSettings settings, uint mask, uint vk) + { + HotkeySlot? hotkeySlot = Owner(settings, HotkeySlot.NightVision, mask, vk); + if (hotkeySlot.HasValue) + { + HotkeySlot valueOrDefault = hotkeySlot.GetValueOrDefault(); + if (valueOrDefault != HotkeySlot.Zoom) + { + return valueOrDefault; + } + } + return null; + } + + public static HotkeySlot? DarkBoostRebindOwner(AppSettings settings, uint mask, uint vk) + { + if (!settings.NightVisionHotkeyEnabled || vk == 0 || vk != settings.NightVisionHotkeyVirtualKey || mask != settings.NightVisionHotkeyModifierMask) + { + return Owner(settings, HotkeySlot.NightVision, mask, vk); + } + return DarkBoostKeyOwner(settings, mask, vk); + } + + public static string? BindingOwner(AppSettings settings, string presetName, uint mask, uint vk) + { + if (vk == 0) + { + return null; + } + HotkeySlot[] slots = MusicHotkey.Slots; + foreach (HotkeySlot slot in slots) + { + (bool, uint, uint) tuple = MusicHotkey.Binding(settings, slot); + if (tuple.Item1 && tuple.Item2 == mask && tuple.Item3 == vk) + { + return Describe(slot); + } + } + if (settings.HotkeyVirtualKey == vk && settings.HotkeyModifierMask == mask) + { + return Describe(HotkeySlot.QuickVibrance); + } + if (settings.MainHotkeyEnabled && settings.MainHotkeyVirtualKey == vk && settings.MainHotkeyModifierMask == mask) + { + return Describe(HotkeySlot.MainWindow); + } + if (settings.ScreenshotHotkeyEnabled && settings.ScreenshotHotkeyVirtualKey == vk && settings.ScreenshotHotkeyModifierMask == mask) + { + return Describe(HotkeySlot.Screenshot); + } + if (settings.NightVisionHotkeyEnabled && global::A.A.Available && settings.NightVisionHotkeyVirtualKey == vk && settings.NightVisionHotkeyModifierMask == mask) + { + return Describe(HotkeySlot.NightVision); + } + if (global::A.A.Available && settings.HoldsTheNextSetupKey(mask, vk)) + { + return Describe(HotkeySlot.NightVision); + } + if (settings.ZoomEnabled && global::A.A.Available && settings.ZoomHotkeyVirtualKey == vk && settings.ZoomHotkeyModifierMask == mask) + { + return Describe(HotkeySlot.Zoom); + } + foreach (PresetKeyBinding presetKeyBinding in settings.PresetKeyBindings) + { + if (!string.Equals(presetKeyBinding.Name, presetName, StringComparison.OrdinalIgnoreCase) && presetKeyBinding.VirtualKey == vk && presetKeyBinding.ModifierMask == mask) + { + return "the '" + presetKeyBinding.Name + "' preset"; + } + } + return null; + } + + public static string Describe(HotkeySlot slot) + { + return slot switch + { + HotkeySlot.QuickVibrance => "Quick vibrance", + HotkeySlot.MainWindow => "Open main window", + HotkeySlot.Screenshot => "Screenshot with colours", + HotkeySlot.NightVision => "Dark Boost", + HotkeySlot.MusicMini => "Music mini player", + HotkeySlot.MusicPlayPause => "Play / pause", + HotkeySlot.MusicNext => "Next track", + HotkeySlot.MusicPrevious => "Previous track", + HotkeySlot.Zoom => "Hold to zoom", + _ => throw new ArgumentOutOfRangeException("slot", slot, "Every HotkeySlot needs a name the user can look for."), + }; + } +} diff --git a/VibranceHud/HotkeyEventArgs.cs b/VibranceHud/HotkeyEventArgs.cs new file mode 100644 index 0000000..119deef --- /dev/null +++ b/VibranceHud/HotkeyEventArgs.cs @@ -0,0 +1,13 @@ +using System; + +namespace VibranceHud; + +internal sealed class HotkeyEventArgs : EventArgs +{ + public int HotkeyId { get; } + + public HotkeyEventArgs(int id) + { + HotkeyId = id; + } +} diff --git a/VibranceHud/HotkeyKeys.cs b/VibranceHud/HotkeyKeys.cs new file mode 100644 index 0000000..5840857 --- /dev/null +++ b/VibranceHud/HotkeyKeys.cs @@ -0,0 +1,100 @@ +namespace VibranceHud; + +public static class HotkeyKeys +{ + public const uint D0 = 48u; + + public const uint D1 = 49u; + + public const uint D2 = 50u; + + public const uint D3 = 51u; + + public const uint D4 = 52u; + + public const uint D5 = 53u; + + public const uint D6 = 54u; + + public const uint D7 = 55u; + + public const uint D8 = 56u; + + public const uint D9 = 57u; + + public const uint A = 65u; + + public const uint B = 66u; + + public const uint C = 67u; + + public const uint D = 68u; + + public const uint E = 69u; + + public const uint F = 70u; + + public const uint G = 71u; + + public const uint H = 72u; + + public const uint I = 73u; + + public const uint J = 74u; + + public const uint K = 75u; + + public const uint L = 76u; + + public const uint M = 77u; + + public const uint N = 78u; + + public const uint O = 79u; + + public const uint P = 80u; + + public const uint Q = 81u; + + public const uint R = 82u; + + public const uint S = 83u; + + public const uint T = 84u; + + public const uint U = 85u; + + public const uint V = 86u; + + public const uint W = 87u; + + public const uint X = 88u; + + public const uint Y = 89u; + + public const uint Z = 90u; + + public const uint F1 = 112u; + + public const uint F2 = 113u; + + public const uint F3 = 114u; + + public const uint F4 = 115u; + + public const uint F5 = 116u; + + public const uint F6 = 117u; + + public const uint F7 = 118u; + + public const uint F8 = 119u; + + public const uint F9 = 120u; + + public const uint F10 = 121u; + + public const uint F11 = 122u; + + public const uint F12 = 123u; +} diff --git a/VibranceHud/HotkeyModifiers.cs b/VibranceHud/HotkeyModifiers.cs new file mode 100644 index 0000000..8901009 --- /dev/null +++ b/VibranceHud/HotkeyModifiers.cs @@ -0,0 +1,12 @@ +namespace VibranceHud; + +public static class HotkeyModifiers +{ + public const uint Alt = 1u; + + public const uint Control = 2u; + + public const uint Shift = 4u; + + public const uint Win = 8u; +} diff --git a/VibranceHud/HotkeyPicker.cs b/VibranceHud/HotkeyPicker.cs new file mode 100644 index 0000000..7b3d93b --- /dev/null +++ b/VibranceHud/HotkeyPicker.cs @@ -0,0 +1,818 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Text; +using System.Runtime.InteropServices; +using System.Windows.Forms; +using VibranceHud.Design; +using VibranceHud.Hotkeys; + +namespace VibranceHud; + +public sealed class HotkeyPicker : Control +{ + private sealed class PickerAccessible : ControlAccessibleObject + { + private readonly HotkeyPicker _owner; + + public override string? Value + { + get + { + return GetSpacedDisplay(_owner._modifierMask, _owner._virtualKey); + } + set + { + } + } + + public override string? Description + { + get + { + string text = _owner.AccessibleDescription ?? ""; + string captureError = _owner._captureError; + if (captureError.Length == 0) + { + if (text.Length != 0) + { + return text; + } + return null; + } + if (text.Length != 0) + { + return text + " " + captureError; + } + return captureError; + } + } + + public PickerAccessible(HotkeyPicker owner) + : base(owner) + { + _owner = owner; + } + } + + private const int ButtonWidth = 64; + + private const int ButtonHeight = 28; + + private const int ChipPadding = 8; + + public static readonly Size PickerDefaultSize = new Size(300, 40); + + public static readonly Size PickerMinimumSize = new Size(240, 36); + + private Rectangle _setBtnRect; + + private uint _modifierMask; + + private uint _virtualKey; + + private bool _capturing; + + private bool _hoverSet; + + private string _captureError = ""; + + private bool _bindingFailed; + + private readonly HashSet _held = new HashSet(); + + private bool _sawModifier; + + internal const string UsedByAnotherApp = "Used by another app - pick another"; + + private HotkeyCaptureGate _gate = HotkeyCaptureGate.Shared; + + private readonly OutsideFocusRing _ring; + + private bool _dimmed; + + private static Font ComboFont => Fonts.BodyBold; + + private static Font ButtonFont => Fonts.BodyBold; + + internal HotkeyCaptureGate Gate + { + set + { + _gate = value; + } + } + + internal static Func? DefaultProbe { get; set; } + + internal Func? ComboProbe { get; set; } + + internal string CaptureMessage => _captureError; + + public uint ModifierMask + { + get + { + return _modifierMask; + } + set + { + _modifierMask = value; + StopListening(); + _captureError = ""; + Invalidate(); + NotifyValueChanged(); + } + } + + public uint VirtualKey + { + get + { + return _virtualKey; + } + set + { + _virtualKey = value; + StopListening(); + _captureError = ""; + Invalidate(); + NotifyValueChanged(); + } + } + + public bool Dimmed + { + get + { + return _dimmed; + } + set + { + if (_dimmed != value) + { + _dimmed = value; + Invalidate(); + } + } + } + + internal Rectangle SetButtonBoundsForTest => _setBtnRect; + + internal Color ComboInkForTest => Combo().Ink; + + internal bool ComboIsBoldForTest => Combo().Bold; + + public bool IsCapturing => _capturing; + + public bool AllowMouseButtons { get; set; } + + public event Action? HotkeyChanged; + + public void ReportBindingResult(bool succeeded) + { + _bindingFailed = !succeeded; + Invalidate(); + } + + public HotkeyPicker() + { + _ring = new OutsideFocusRing(this, () => ControlInk.PxF(ControlInk.Dpi(this), 4f)); + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.Selectable | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + Size = PickerDefaultSize; + MinimumSize = PickerMinimumSize; + TabStop = true; + AccessibleName = "Shortcut"; + AccessibleRole = AccessibleRole.Text; + _modifierMask = 3u; + _virtualKey = 86u; + _setBtnRect = new Rectangle(0, 0, 64, 28); + } + + private void NotifyValueChanged() + { + AccessibilityNotifyClients(AccessibleEvents.ValueChange, -1); + } + + protected override AccessibleObject CreateAccessibilityInstance() + { + return new PickerAccessible(this); + } + + public static string GetDisplay(uint modifierMask, uint virtualKey) + { + return Join(modifierMask, virtualKey, "+"); + } + + private static string Join(uint modifierMask, uint virtualKey, string glue) + { + if (virtualKey == 0) + { + return "Not set"; + } + List list = new List(5); + if ((modifierMask & 2) != 0) + { + list.Add("Ctrl"); + } + if ((modifierMask & 1) != 0) + { + list.Add("Alt"); + } + if ((modifierMask & 4) != 0) + { + list.Add("Shift"); + } + if ((modifierMask & 8) != 0) + { + list.Add("Win"); + } + list.Add(KeyName(virtualKey)); + return string.Join(glue, list); + } + + public static string GetSpacedDisplay(uint modifierMask, uint virtualKey) + { + return Join(modifierMask, virtualKey, " + "); + } + + public static string KeyName(uint vk) + { + if (vk >= 65 && vk <= 90) + { + return ((char)vk).ToString(); + } + if (vk >= 48 && vk <= 57) + { + return ((char)vk).ToString(); + } + if (vk >= 112 && vk <= 135) + { + return "F" + (vk - 111); + } + if (vk >= 96 && vk <= 105) + { + return "Num" + (vk - 96); + } + return vk switch + { + 33u => "PageUp", + 34u => "PageDown", + 35u => "End", + 36u => "Home", + 45u => "Insert", + 46u => "Delete", + 37u => "Left", + 38u => "Up", + 39u => "Right", + 40u => "Down", + 4u => "Middle mouse", + 5u => "Mouse 4", + 6u => "Mouse 5", + 32u => "Space", + 9u => "Tab", + 13u => "Enter", + 8u => "Backspace", + 27u => "Esc", + 20u => "CapsLock", + 145u => "ScrollLock", + 144u => "NumLock", + 19u => "Pause", + 44u => "PrintScreen", + 106u => "Num*", + 107u => "Num+", + 109u => "Num-", + 110u => "Num.", + 111u => "Num/", + 186u => ";", + 187u => "=", + 188u => ",", + 189u => "-", + 190u => ".", + 191u => "/", + 192u => "`", + 219u => "[", + 220u => "\\", + 221u => "]", + 222u => "'", + 173u => "Mute", + 174u => "VolumeDown", + 175u => "VolumeUp", + 176u => "NextTrack", + 177u => "PrevTrack", + 178u => "StopMedia", + 179u => "PlayPause", + 0u => "(none)", + _ => "0x" + vk.ToString("X"), + }; + } + + public static bool IsBindable(uint modifierMask, uint virtualKey, out string error) + { + error = ""; + if (virtualKey == 0) + { + error = "Press a key to bind."; + return false; + } + if (IsModifierOnly(virtualKey)) + { + error = "Now press the key."; + return false; + } + if (modifierMask == 0 && virtualKey == 27) + { + error = "Esc cancels - pick another key."; + return false; + } + if (IsReservedCombo(modifierMask, virtualKey)) + { + error = "That combination is reserved by Windows."; + return false; + } + return true; + } + + public void CancelCapture() + { + if (_capturing) + { + ExitCapture(); + } + } + + internal void TestBeginCapture() + { + EnterCapture(); + } + + private void EnterCapture() + { + _held.Clear(); + _sawModifier = false; + _captureError = ""; + _bindingFailed = false; + if (!_capturing) + { + _capturing = true; + _gate.Enter(this); + } + Focus(); + Invalidate(); + } + + private void ExitCapture() + { + StopListening(); + _captureError = ""; + Invalidate(); + } + + private void StopListening() + { + _held.Clear(); + _sawModifier = false; + if (_capturing) + { + _capturing = false; + _gate.Leave(this); + } + } + + protected override void OnHandleDestroyed(EventArgs e) + { + StopListening(); + base.OnHandleDestroyed(e); + } + + internal static uint MouseButtonKey(MouseButtons b) + { + return b switch + { + MouseButtons.Middle => 4u, + MouseButtons.XButton1 => 5u, + MouseButtons.XButton2 => 6u, + _ => 0u, + }; + } + + internal bool TestMouseCapture(MouseButtons b, Keys modifiers) + { + return TryCaptureMouse(b, modifiers); + } + + private bool TryCaptureMouse(MouseButtons b, Keys modifiers) + { + if (!_capturing || !AllowMouseButtons) + { + return false; + } + uint num = MouseButtonKey(b); + if (num == 0) + { + return false; + } + uint num2 = 0u; + if ((modifiers & Keys.Control) != 0) + { + num2 |= 2; + } + if ((modifiers & Keys.Alt) != 0) + { + num2 |= 1; + } + if ((modifiers & Keys.Shift) != 0) + { + num2 |= 4; + } + _modifierMask = num2; + _virtualKey = num; + ExitCapture(); + NotifyValueChanged(); + HotkeyChanged?.Invoke(_modifierMask, _virtualKey); + return true; + } + + protected override void OnMouseDown(MouseEventArgs e) + { + base.OnMouseDown(e); + if (!TryCaptureMouse(e.Button, Control.ModifierKeys) && e.Button == MouseButtons.Left && _setBtnRect.Contains(e.Location)) + { + if (_capturing) + { + ExitCapture(); + } + else + { + EnterCapture(); + } + } + } + + protected override void OnMouseMove(MouseEventArgs e) + { + base.OnMouseMove(e); + bool flag = _setBtnRect.Contains(e.Location); + Cursor = (flag ? Cursors.Hand : Cursors.Default); + if (flag != _hoverSet) + { + _hoverSet = flag; + Invalidate(Rectangle.Inflate(_setBtnRect, 2, 2)); + } + } + + protected override void OnMouseLeave(EventArgs e) + { + base.OnMouseLeave(e); + Cursor = Cursors.Default; + if (_hoverSet) + { + _hoverSet = false; + Invalidate(Rectangle.Inflate(_setBtnRect, 2, 2)); + } + } + + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + if (!_capturing) + { + return; + } + if (e.KeyCode == Keys.Escape) + { + ExitCapture(); + e.Handled = true; + e.SuppressKeyPress = true; + return; + } + uint num = 0u; + if (e.Control) + { + num |= 2; + } + if (e.Alt) + { + num |= 1; + } + if (e.Shift) + { + num |= 4; + } + if ((Control.ModifierKeys & Keys.LWin) != 0 || (Control.ModifierKeys & Keys.RWin) != 0 || IsKeyDown(Keys.LWin) || IsKeyDown(Keys.RWin)) + { + num |= 8; + } + uint keyCode = (uint)e.KeyCode; + if (IsModifierOnly(keyCode)) + { + _held.Add(e.KeyCode); + _sawModifier = true; + } + else + { + _sawModifier = false; + } + TryBind(num, keyCode); + e.Handled = true; + e.SuppressKeyPress = true; + } + + protected override void OnKeyUp(KeyEventArgs e) + { + base.OnKeyUp(e); + if (!_capturing) + { + return; + } + if (e.KeyCode == Keys.Snapshot) + { + uint num = 0u; + if (e.Control) + { + num |= 2; + } + if (e.Alt) + { + num |= 1; + } + if (e.Shift) + { + num |= 4; + } + if (_held.Contains(Keys.LWin) || _held.Contains(Keys.RWin)) + { + num |= 8; + } + TryBind(num, 44u); + e.Handled = true; + e.SuppressKeyPress = true; + } + else if (IsModifierOnly((uint)e.KeyCode)) + { + _held.Remove(e.KeyCode); + if (_held.Count == 0 && _sawModifier) + { + _sawModifier = false; + _captureError = "Used by another app - pick another"; + Invalidate(); + } + } + } + + private void TryBind(uint mods, uint vk) + { + if (!IsBindable(mods, vk, out string error)) + { + _captureError = (IsModifierOnly(vk) ? "" : error); + Invalidate(); + return; + } + if (ComboTaken(mods, vk)) + { + _captureError = "Used by another app - pick another"; + Invalidate(); + return; + } + _modifierMask = mods; + _virtualKey = vk; + ExitCapture(); + NotifyValueChanged(); + HotkeyChanged?.Invoke(_modifierMask, _virtualKey); + } + + private bool ComboTaken(uint mods, uint vk) + { + try + { + int num; + if (ComboProbe != null) + { + num = ComboProbe(mods, vk); + } + else + { + if (DefaultProbe == null || AllowMouseButtons || !IsHandleCreated) + { + return false; + } + num = DefaultProbe(Handle, mods, vk); + } + return num == 1409; + } + catch + { + return false; + } + } + + internal void TestKeyDown(Keys keyData) + { + OnKeyDown(new KeyEventArgs(keyData)); + } + + internal void TestKeyUp(Keys keyData) + { + OnKeyUp(new KeyEventArgs(keyData)); + } + + [DllImport("user32.dll")] + private static extern short GetAsyncKeyState(int vKey); + + private static bool IsKeyDown(Keys key) + { + return (GetAsyncKeyState((int)key) & 0x8000) != 0; + } + + private static bool IsModifierOnly(uint vk) + { + if (vk != 17 && vk != 16 && vk != 18 && vk != 164 && vk != 165 && vk != 162 && vk != 163 && vk != 160 && vk != 161 && vk != 91) + { + return vk == 92; + } + return true; + } + + private static bool IsReservedCombo(uint mask, uint vk) + { + bool flag = (mask & 2) != 0; + bool flag2 = (mask & 1) != 0; + bool flag3 = (mask & 8) != 0; + if ((flag & flag2) && vk == 46) + { + return true; + } + if (flag && vk == 27) + { + return true; + } + if (flag2 && (vk == 9 || vk == 27 || vk == 115)) + { + return true; + } + if (flag3 && vk == 76) + { + return true; + } + return false; + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics graphics = e.Graphics; + graphics.SmoothingMode = SmoothingMode.AntiAlias; + graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; + int dpi = ControlInk.Dpi(this); + int num = ControlInk.Px(dpi, 64); + int num2 = ControlInk.Px(dpi, 28); + int y = (Height - num2) / 2; + int num3 = ControlInk.Px(dpi, 8); + RectangleF value = new RectangleF(num3, 0f, Math.Max(60, Width - num - num3 * 2), Height); + var (text, foreColor, flag) = Combo(); + TextRenderer.DrawText(graphics, text, flag ? ComboFont : Fonts.Body, Rectangle.Round(value), foreColor, TextFormatFlags.EndEllipsis | TextFormatFlags.VerticalCenter); + _setBtnRect.X = Width - num; + _setBtnRect.Y = y; + _setBtnRect.Width = num; + _setBtnRect.Height = num2; + PaintSecondaryButton(graphics, _setBtnRect, _capturing ? "Cancel" : "Set", _hoverSet, dpi, Enabled); + if (Focused && ShowFocusCues) + { + _ring.Show(Enabled); + } + else + { + _ring.Show(show: false); + } + } + + private (string Text, Color Ink, bool Bold) Combo() + { + bool item = true; + string item2; + Color item3; + int num; + Color color; + if (_capturing) + { + item2 = ((_captureError.Length > 0) ? _captureError : "Press any key (Esc to cancel)"); + item3 = ((_captureError.Length > 0) ? ControlInk.Danger : Theme.Text); + } + else + { + if (!_bindingFailed) + { + item2 = GetSpacedDisplay(_modifierMask, _virtualKey); + if (_virtualKey != 0) + { + num = (_dimmed ? 1 : 0); + if (num == 0) + { + color = Theme.Text; + goto IL_00a1; + } + } + else + { + num = 1; + } + color = ControlInk.Text3; + goto IL_00a1; + } + item2 = GetSpacedDisplay(_modifierMask, _virtualKey) + " - already in use"; + item3 = ControlInk.Warning; + } + goto IL_00a6; + IL_00a6: + if (!Enabled) + { + item3 = ControlInk.TextDisabledInk; + } + return (Text: item2, Ink: item3, Bold: item); + IL_00a1: + item3 = color; + item = num == 0; + goto IL_00a6; + } + + protected override void OnGotFocus(EventArgs e) + { + base.OnGotFocus(e); + Invalidate(); + } + + protected override void OnEnabledChanged(EventArgs e) + { + base.OnEnabledChanged(e); + Invalidate(); + } + + protected override void OnLostFocus(EventArgs e) + { + base.OnLostFocus(e); + if (_capturing) + { + ExitCapture(); + } + else + { + Invalidate(); + } + } + + protected override void OnLeave(EventArgs e) + { + base.OnLeave(e); + if (_capturing) + { + ExitCapture(); + } + } + + internal void TestLoseFocus() + { + OnLostFocus(EventArgs.Empty); + } + + protected override void OnParentChanged(EventArgs e) + { + base.OnParentChanged(e); + _ring.Rehook(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + StopListening(); + _ring.Release(); + } + base.Dispose(disposing); + } + + private static void PaintSecondaryButton(Graphics g, Rectangle rect, string text, bool hover, int dpi, bool enabled) + { + Color fill = ((hover & enabled) ? ControlInk.Hover : Color.Transparent); + GraphicsState gstate = g.Save(); + g.SmoothingMode = SmoothingMode.AntiAlias; + g.TranslateTransform(rect.X, rect.Y); + ControlInk.PaintBox(g, rect.Size, ControlInk.PxF(dpi, 4f), ControlInk.Hairline(dpi), fill, enabled ? ControlInk.Edge : ControlInk.TextDisabled); + g.Restore(gstate); + TextRenderer.DrawText(g, text, ButtonFont, rect, enabled ? ControlInk.Text1 : ControlInk.TextDisabledInk, TextFormatFlags.HorizontalCenter | TextFormatFlags.NoPrefix | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding); + } + + protected override bool IsInputKey(Keys keyData) + { + if (!_capturing) + { + return base.IsInputKey(keyData); + } + return true; + } + + internal bool TestClaimsKey(Keys key) + { + return IsInputKey(key); + } +} diff --git a/VibranceHud/HotkeySlot.cs b/VibranceHud/HotkeySlot.cs new file mode 100644 index 0000000..7e8e400 --- /dev/null +++ b/VibranceHud/HotkeySlot.cs @@ -0,0 +1,14 @@ +namespace VibranceHud; + +public enum HotkeySlot +{ + QuickVibrance, + MainWindow, + Screenshot, + NightVision, + MusicMini, + MusicPlayPause, + MusicNext, + MusicPrevious, + Zoom +} diff --git a/VibranceHud/HotkeyWindow.cs b/VibranceHud/HotkeyWindow.cs new file mode 100644 index 0000000..1f4e262 --- /dev/null +++ b/VibranceHud/HotkeyWindow.cs @@ -0,0 +1,42 @@ +using System; +using System.Windows.Forms; + +namespace VibranceHud; + +internal sealed class HotkeyWindow : NativeWindow +{ + private const int WM_HOTKEY = 786; + + internal const int WM_DRAIN_KEYS = 32848; + + public event EventHandler? HotkeyPressed; + + public event Action? KeysWaiting; + + public HotkeyWindow() + { + CreateHandle(new CreateParams()); + } + + protected override void WndProc(ref Message m) + { + if (m.Msg == 786) + { + int id = ((IntPtr)m.WParam).ToInt32(); + HotkeyPressed?.Invoke(this, new HotkeyEventArgs(id)); + } + else if (m.Msg == 32848) + { + try + { + KeysWaiting?.Invoke(); + return; + } + catch + { + return; + } + } + base.WndProc(ref m); + } +} diff --git a/VibranceHud/Hotkeys/DarkBoostKeys.cs b/VibranceHud/Hotkeys/DarkBoostKeys.cs new file mode 100644 index 0000000..b459744 --- /dev/null +++ b/VibranceHud/Hotkeys/DarkBoostKeys.cs @@ -0,0 +1,192 @@ +using System; + +namespace VibranceHud.Hotkeys; + +public sealed class DarkBoostKeys : IDisposable +{ + internal const int BindId = 4; + + internal const int NextBindId = 5; + + private readonly KeyBinder _binder; + + private readonly InputRelay _relay; + + private readonly IRawInputSource _source; + + private readonly Func _offered; + + private readonly Func _gameRunning; + + private int _vk; + + private uint _modifiers; + + private bool _gameOnly; + + private int _nextVk; + + private uint _nextModifiers; + + private bool _nextGameOnly; + + private bool _disposed; + + internal const int ZoomBindId = 6; + + private int _zoomVk; + + private uint _zoomModifiers; + + private bool _zoomGameOnly = true; + + public Func ZoomOffered { get; set; } = () => true; + + public bool IsZoomBound => _binder.IsBound(6); + + public bool Keyboard { get; private set; } + + public bool Mouse { get; private set; } + + public bool IsBound => _binder.IsBound(4); + + public bool IsNextBound => _binder.IsBound(5); + + public event Action? Zoom; + + public event Action? ZoomIgnored; + + public event Action? Want; + + public event Action? Next; + + public DarkBoostKeys(Func offered, Func gameRunning, Action wake, Func source) + { + _offered = offered; + _gameRunning = gameRunning; + _binder = new KeyBinder(gameRunning); + _relay = new InputRelay(_binder.IsInteresting, wake); + _source = source(_relay); + _binder.Fired += (int id, bool on) => + { + if (id == 4) + { + Want?.Invoke(on); + } + else if ((id == 5) & on) + { + Next?.Invoke(); + } + else if (id == 6) + { + Zoom?.Invoke(on); + } + }; + _binder.Ignored += (int id, string why) => + { + if (id == 6) + { + ZoomIgnored?.Invoke(why); + } + }; + } + + public bool BindZoom(uint modifiers, int vk, bool gameOnly = true) + { + bool flag = _binder.Register(6, modifiers, vk, KeyMode.Hold, gameOnly, () => ZoomOffered()); + if (flag) + { + _zoomVk = vk; + _zoomModifiers = modifiers; + _zoomGameOnly = gameOnly; + } + Settle(); + return flag; + } + + public void UnbindZoom() + { + _binder.Unregister(6); + Settle(); + } + + public bool Bind(uint modifiers, int vk, bool hold, bool gameOnly) + { + bool flag = _binder.Register(4, modifiers, vk, hold ? KeyMode.Hold : KeyMode.Press, gameOnly, _offered); + if (flag) + { + _vk = vk; + _modifiers = modifiers; + _gameOnly = gameOnly; + } + Settle(); + return flag; + } + + public void Unbind() + { + _binder.Unregister(4); + Settle(); + } + + public bool BindNext(uint modifiers, int vk, bool gameOnly) + { + bool flag = _binder.Register(5, modifiers, vk, KeyMode.Press, gameOnly, _offered); + if (flag) + { + _nextVk = vk; + _nextModifiers = modifiers; + _nextGameOnly = gameOnly; + } + Settle(); + return flag; + } + + public void UnbindNext() + { + _binder.Unregister(5); + Settle(); + } + + public void Settle() + { + if (!_disposed) + { + bool offered = _offered(); + bool gameRunning = _gameRunning(); + (bool, bool) tuple = RawInputPolicy.Wanted(offered, IsBound, _vk, _modifiers, _gameOnly, gameRunning); + (bool, bool) tuple2 = RawInputPolicy.Wanted(offered, IsNextBound, _nextVk, _nextModifiers, _nextGameOnly, gameRunning); + (bool, bool) tuple3 = RawInputPolicy.Wanted(ZoomOffered(), IsZoomBound, _zoomVk, _zoomModifiers, _zoomGameOnly, gameRunning); + bool flag = tuple.Item1 || tuple2.Item1 || tuple3.Item1; + bool flag2 = tuple.Item2 || tuple2.Item2 || tuple3.Item2; + if (!flag && !flag2) + { + _binder.ReleaseAll(); + } + if (flag != Keyboard || flag2 != Mouse) + { + _source.Apply(flag, flag2); + Keyboard = flag; + Mouse = flag2; + } + } + } + + public void Drain() + { + _relay.Drain(_binder); + } + + public void Dispose() + { + if (!_disposed) + { + _disposed = true; + _binder.ReleaseAll(); + _source.Apply(keyboard: false, mouse: false); + bool keyboard = (Mouse = false); + Keyboard = keyboard; + _source.Dispose(); + } + } +} diff --git a/VibranceHud/Hotkeys/HotkeyCaptureGate.cs b/VibranceHud/Hotkeys/HotkeyCaptureGate.cs new file mode 100644 index 0000000..4263fee --- /dev/null +++ b/VibranceHud/Hotkeys/HotkeyCaptureGate.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; + +namespace VibranceHud.Hotkeys; + +public sealed class HotkeyCaptureGate +{ + public static readonly HotkeyCaptureGate Shared = new HotkeyCaptureGate(); + + private readonly object _lock = new object(); + + private readonly HashSet _listening = new HashSet(); + + public bool IsCapturing + { + get + { + lock (_lock) + { + return _listening.Count > 0; + } + } + } + + public event Action? Began; + + public event Action? Ended; + + internal void Enter(object picker) + { + bool flag; + lock (_lock) + { + flag = _listening.Count == 0; + _listening.Add(picker); + } + if (flag) + { + Began?.Invoke(); + } + } + + internal void Leave(object picker) + { + bool flag; + lock (_lock) + { + if (!_listening.Remove(picker)) + { + return; + } + flag = _listening.Count == 0; + } + if (flag) + { + Ended?.Invoke(); + } + } +} diff --git a/VibranceHud/Hotkeys/HotkeyCaptureRelease.cs b/VibranceHud/Hotkeys/HotkeyCaptureRelease.cs new file mode 100644 index 0000000..03be0b9 --- /dev/null +++ b/VibranceHud/Hotkeys/HotkeyCaptureRelease.cs @@ -0,0 +1,69 @@ +using System; + +namespace VibranceHud.Hotkeys; + +public sealed class HotkeyCaptureRelease : IDisposable +{ + private readonly HotkeyCaptureGate _gate; + + private readonly Action _releaseAll; + + private readonly Action _registerAll; + + private bool _released; + + private bool _disposed; + + public bool IsReleased => _released; + + public HotkeyCaptureRelease(HotkeyCaptureGate gate, Action releaseAll, Action registerAll) + { + _gate = gate ?? throw new ArgumentNullException("gate"); + _releaseAll = releaseAll ?? throw new ArgumentNullException("releaseAll"); + _registerAll = registerAll ?? throw new ArgumentNullException("registerAll"); + _gate.Began += OnBegan; + _gate.Ended += OnEnded; + } + + private void OnBegan() + { + if (_disposed || _released) + { + return; + } + _released = true; + try + { + _releaseAll(); + } + catch + { + } + } + + private void OnEnded() + { + if (_disposed || !_released) + { + return; + } + _released = false; + try + { + _registerAll(); + } + catch + { + } + } + + public void Dispose() + { + if (!_disposed) + { + _disposed = true; + _gate.Began -= OnBegan; + _gate.Ended -= OnEnded; + } + } +} diff --git a/VibranceHud/Hotkeys/HotkeyProbe.cs b/VibranceHud/Hotkeys/HotkeyProbe.cs new file mode 100644 index 0000000..382e82b --- /dev/null +++ b/VibranceHud/Hotkeys/HotkeyProbe.cs @@ -0,0 +1,44 @@ +using System; +using System.Runtime.InteropServices; + +namespace VibranceHud.Hotkeys; + +internal static class HotkeyProbe +{ + internal const int ErrorHotkeyAlreadyRegistered = 1409; + + private const int ProbeId = 31317; + + [DllImport("user32.dll", SetLastError = true)] + private static extern bool RegisterHotKey(nint hWnd, int id, uint fsModifiers, uint vk); + + [DllImport("user32.dll", SetLastError = true)] + private static extern bool UnregisterHotKey(nint hWnd, int id); + + internal static int Real(nint hwnd, uint mask, uint vk) + { + if (hwnd == IntPtr.Zero) + { + return 0; + } + return Run(() => RegisterHotKey(hwnd, 31317, mask, vk), () => Marshal.GetLastWin32Error(), () => + { + UnregisterHotKey(hwnd, 31317); + }); + } + + internal static int Run(Func register, Func lastError, Action unregister) + { + if (register()) + { + unregister(); + return 0; + } + int num = lastError(); + if (num != 0) + { + return num; + } + return -1; + } +} diff --git a/VibranceHud/Hotkeys/HotkeyStatus.cs b/VibranceHud/Hotkeys/HotkeyStatus.cs new file mode 100644 index 0000000..9978e78 --- /dev/null +++ b/VibranceHud/Hotkeys/HotkeyStatus.cs @@ -0,0 +1,78 @@ +using System.Collections.Generic; +using System.Linq; + +namespace VibranceHud.Hotkeys; + +public static class HotkeyStatus +{ + private static readonly object Gate = new object(); + + private static readonly Dictionary Refused = new Dictionary(); + + public static void Record(HotkeySlot slot, string combo, bool bound) + { + lock (Gate) + { + if (bound) + { + Refused.Remove(slot); + } + else + { + Refused[slot] = combo; + } + } + } + + public static void Forget(HotkeySlot slot) + { + lock (Gate) + { + Refused.Remove(slot); + } + } + + public static string Line() + { + List<(HotkeySlot, string)> refused; + lock (Gate) + { + refused = (from p in Refused + orderby p.Key + select (Key: p.Key, Value: p.Value)).ToList(); + } + return Line(refused); + } + + public static string Line(IReadOnlyList<(HotkeySlot Slot, string Combo)> refused) + { + if (refused == null || refused.Count == 0) + { + return ""; + } + if (refused.Count == 1) + { + return $"Another app owns {refused[0].Combo}, so “{DisplayPageName(refused[0].Slot)}” does nothing. " + "Pick a different combination on the Display tab."; + } + List list = refused.Select(((HotkeySlot Slot, string Combo) r) => r.Combo + " (“" + DisplayPageName(r.Slot) + "”)").ToList(); + string text = string.Join(", ", list.Take(list.Count - 1)) + " and " + list[list.Count - 1]; + return "Another app owns " + text + ", so they do nothing. Pick different combinations on the Display tab."; + } + + private static string DisplayPageName(HotkeySlot slot) + { + if (slot != HotkeySlot.QuickVibrance) + { + return HotkeyConflicts.Describe(slot); + } + return "Quick colour popup"; + } + + internal static void ResetForTest() + { + lock (Gate) + { + Refused.Clear(); + } + } +} diff --git a/VibranceHud/Hotkeys/IRawInputSource.cs b/VibranceHud/Hotkeys/IRawInputSource.cs new file mode 100644 index 0000000..436aef0 --- /dev/null +++ b/VibranceHud/Hotkeys/IRawInputSource.cs @@ -0,0 +1,8 @@ +using System; + +namespace VibranceHud.Hotkeys; + +public interface IRawInputSource : IDisposable +{ + void Apply(bool keyboard, bool mouse); +} diff --git a/VibranceHud/Hotkeys/InputEvent.cs b/VibranceHud/Hotkeys/InputEvent.cs new file mode 100644 index 0000000..18542c9 --- /dev/null +++ b/VibranceHud/Hotkeys/InputEvent.cs @@ -0,0 +1,3 @@ +namespace VibranceHud.Hotkeys; + +public readonly record struct InputEvent(int VirtualKey, bool Down); diff --git a/VibranceHud/Hotkeys/InputRelay.cs b/VibranceHud/Hotkeys/InputRelay.cs new file mode 100644 index 0000000..4567410 --- /dev/null +++ b/VibranceHud/Hotkeys/InputRelay.cs @@ -0,0 +1,75 @@ +using System; +using System.Threading; + +namespace VibranceHud.Hotkeys; + +public sealed class InputRelay +{ + public const int Capacity = 256; + + private const int Mask = 255; + + private readonly InputEvent[] _ring = new InputEvent[256]; + + private readonly Func _wanted; + + private readonly Action _wake; + + private int _head; + + private int _tail; + + private int _overflow; + + public int Pending => Volatile.Read(in _head) - Volatile.Read(in _tail); + + public InputRelay(Func wanted, Action wake) + { + _wanted = wanted; + _wake = wake; + } + + public void OnRawEvent(int vk, bool down) + { + try + { + if (!_wanted(vk)) + { + return; + } + int head = _head; + int num = Volatile.Read(in _tail); + if (head - num >= 256) + { + Volatile.Write(ref _overflow, 1); + return; + } + _ring[head & 0xFF] = new InputEvent(vk, down); + Volatile.Write(ref _head, head + 1); + if (head == num) + { + _wake(); + } + } + catch + { + } + } + + public void Drain(KeyBinder binder) + { + int num = _tail; + while (num != Volatile.Read(in _head)) + { + InputEvent e = _ring[num & 0xFF]; + _ring[num & 0xFF] = default; + num++; + Volatile.Write(ref _tail, num); + binder.Handle(e); + } + if (Interlocked.Exchange(ref _overflow, 0) != 0) + { + binder.ReleaseAll(); + } + } +} diff --git a/VibranceHud/Hotkeys/KeyBinder.cs b/VibranceHud/Hotkeys/KeyBinder.cs new file mode 100644 index 0000000..12a8d35 --- /dev/null +++ b/VibranceHud/Hotkeys/KeyBinder.cs @@ -0,0 +1,337 @@ +using System; +using System.Collections.Generic; +using System.Numerics; + +namespace VibranceHud.Hotkeys; + +public sealed class KeyBinder +{ + private sealed class Binding + { + public int Id; + + public uint Modifiers; + + public int Vk; + + public KeyMode Mode; + + public bool GameOnly; + + public Func? Allowed; + + public bool Held; + + public bool Engaged; + } + + public const int VK_LBUTTON = 1; + + public const int VK_RBUTTON = 2; + + public const int VK_MBUTTON = 4; + + public const int VK_XBUTTON1 = 5; + + public const int VK_XBUTTON2 = 6; + + private readonly List _bindings = new List(); + + private readonly Func _gameRunning; + + private int _modifierSides; + + private volatile bool[] _interesting = Rebuilt(Array.Empty()); + + public const string NoGameRunning = "no game running"; + + public const string NotAllowed = "not allowed"; + + public int Count => _bindings.Count; + + public event Action? Fired; + + public event Action? Ignored; + + public KeyBinder(Func gameRunning) + { + _gameRunning = gameRunning; + } + + public static bool IsBindable(int vk) + { + if (vk > 0 && vk < 256 && vk != 1 && vk != 2) + { + return ModifierSide(vk) < 0; + } + return false; + } + + public bool Register(int id, uint modifiers, int vk, KeyMode mode = KeyMode.Press, bool gameOnly = false, Func? allowed = null) + { + if (!IsBindable(vk)) + { + return false; + } + modifiers &= 0xF; + foreach (Binding binding in _bindings) + { + if (binding.Id != id && binding.Vk == vk && binding.Modifiers == modifiers) + { + return false; + } + } + Unregister(id); + _bindings.Add(new Binding + { + Id = id, + Modifiers = modifiers, + Vk = vk, + Mode = mode, + GameOnly = gameOnly, + Allowed = allowed + }); + _interesting = Rebuilt(_bindings); + ForgetUnwatchedModifiers(); + return true; + } + + public void Unregister(int id) + { + for (int num = _bindings.Count - 1; num >= 0; num--) + { + Binding binding = _bindings[num]; + if (binding.Id == id) + { + _bindings.RemoveAt(num); + if (binding.Engaged) + { + binding.Engaged = false; + Fired?.Invoke(binding.Id, arg2: false); + } + } + } + _interesting = Rebuilt(_bindings); + ForgetUnwatchedModifiers(); + } + + public bool IsBound(int id) + { + return _bindings.Exists((Binding b) => b.Id == id); + } + + public bool IsInteresting(int vk) + { + bool[] interesting = _interesting; + if ((uint)vk < (uint)interesting.Length) + { + return interesting[vk]; + } + return false; + } + + public void Handle(InputEvent e) + { + int num = ModifierSide(e.VirtualKey); + if (num >= 0) + { + if (e.Down) + { + _modifierSides |= 1 << num; + } + else + { + _modifierSides &= ~(1 << num); + } + } + else if (e.Down) + { + OnDown(e.VirtualKey); + } + else + { + OnUp(e.VirtualKey); + } + } + + public void ReleaseAll() + { + _modifierSides = 0; + foreach (Binding binding in _bindings) + { + binding.Held = false; + if (binding.Engaged) + { + binding.Engaged = false; + Fired?.Invoke(binding.Id, arg2: false); + } + } + } + + private void OnDown(int vk) + { + uint num = HeldModifiers(); + Binding binding = null; + int num2 = -1; + foreach (Binding binding2 in _bindings) + { + if (binding2.Vk == vk && (binding2.Modifiers & ~num) == 0) + { + int num3 = PopCount(binding2.Modifiers); + if (num3 > num2) + { + binding = binding2; + num2 = num3; + } + } + } + if (binding == null || binding.Held) + { + return; + } + binding.Held = true; + if (binding.GameOnly && !_gameRunning()) + { + Ignored?.Invoke(binding.Id, "no game running"); + return; + } + if (binding.Allowed != null && !binding.Allowed()) + { + Ignored?.Invoke(binding.Id, "not allowed"); + return; + } + if (binding.Mode == KeyMode.Hold) + { + binding.Engaged = true; + } + Fired?.Invoke(binding.Id, arg2: true); + } + + private void OnUp(int vk) + { + foreach (Binding binding in _bindings) + { + if (binding.Vk == vk && binding.Held) + { + binding.Held = false; + if (binding.Engaged) + { + binding.Engaged = false; + Fired?.Invoke(binding.Id, arg2: false); + } + } + } + } + + private uint HeldModifiers() + { + uint num = 0u; + if ((_modifierSides & 3) != 0) + { + num |= 4; + } + if ((_modifierSides & 0xC) != 0) + { + num |= 2; + } + if ((_modifierSides & 0x30) != 0) + { + num |= 1; + } + if ((_modifierSides & 0xC0) != 0) + { + num |= 8; + } + return num; + } + + private static int ModifierSide(int vk) + { + switch (vk) + { + case 16: + case 160: + return 0; + case 161: + return 1; + case 17: + case 162: + return 2; + case 163: + return 3; + case 18: + case 164: + return 4; + case 165: + return 5; + case 91: + return 6; + case 92: + return 7; + default: + return -1; + } + } + + private static int PopCount(uint v) + { + return BitOperations.PopCount(v); + } + + private static bool[] Rebuilt(IEnumerable bindings) + { + bool[] array = new bool[256]; + uint num = 0u; + foreach (Binding binding in bindings) + { + array[binding.Vk] = true; + num |= binding.Modifiers; + } + if ((num & 4) != 0) + { + bool flag; + array[160] = (flag = (array[161] = true)); + array[16] = flag; + } + if ((num & 2) != 0) + { + bool flag; + array[162] = (flag = (array[163] = true)); + array[17] = flag; + } + if ((num & 1) != 0) + { + bool flag; + array[164] = (flag = (array[165] = true)); + array[18] = flag; + } + if ((num & 8) != 0) + { + array[91] = (array[92] = true); + } + return array; + } + + private void ForgetUnwatchedModifiers() + { + bool[] interesting = _interesting; + int num = 0; + if (interesting[160]) + { + num |= 3; + } + if (interesting[162]) + { + num |= 0xC; + } + if (interesting[164]) + { + num |= 0x30; + } + if (interesting[91]) + { + num |= 0xC0; + } + _modifierSides &= num; + } +} diff --git a/VibranceHud/Hotkeys/KeyMode.cs b/VibranceHud/Hotkeys/KeyMode.cs new file mode 100644 index 0000000..ff65f3d --- /dev/null +++ b/VibranceHud/Hotkeys/KeyMode.cs @@ -0,0 +1,7 @@ +namespace VibranceHud.Hotkeys; + +public enum KeyMode +{ + Press, + Hold +} diff --git a/VibranceHud/Hotkeys/RawInputPolicy.cs b/VibranceHud/Hotkeys/RawInputPolicy.cs new file mode 100644 index 0000000..aa79013 --- /dev/null +++ b/VibranceHud/Hotkeys/RawInputPolicy.cs @@ -0,0 +1,23 @@ +namespace VibranceHud.Hotkeys; + +public static class RawInputPolicy +{ + public static (bool Keyboard, bool Mouse) Wanted(bool offered, bool bound, int vk, uint modifiers, bool gameOnly, bool gameRunning) + { + if (!offered || !bound || (gameOnly && !gameRunning)) + { + return (Keyboard: false, Mouse: false); + } + bool flag = IsMouseButton(vk); + return (Keyboard: !flag || modifiers != 0, Mouse: flag); + } + + public static bool IsMouseButton(int vk) + { + if ((uint)(vk - 4) <= 2u) + { + return true; + } + return false; + } +} diff --git a/VibranceHud/Hotkeys/RawKeyListener.cs b/VibranceHud/Hotkeys/RawKeyListener.cs new file mode 100644 index 0000000..91f5fe0 --- /dev/null +++ b/VibranceHud/Hotkeys/RawKeyListener.cs @@ -0,0 +1,321 @@ +using System; +using System.Buffers.Binary; +using System.Runtime.InteropServices; +using System.Threading; +using System.Windows.Forms; + +namespace VibranceHud.Hotkeys; + +public sealed class RawKeyListener : IRawInputSource, IDisposable +{ + internal struct RAWINPUTDEVICE + { + public ushort UsagePage; + + public ushort Usage; + + public uint Flags; + + public nint Target; + } + + private sealed class Sink : NativeWindow + { + private readonly RawKeyListener _owner; + + public Sink(RawKeyListener owner) + { + _owner = owner; + } + + protected override void WndProc(ref Message m) + { + switch (m.Msg) + { + case 255: + _owner.Read(m.LParam); + break; + case 32849: + { + int num = ((IntPtr)m.WParam).ToInt32(); + _owner.ChangeRegistration((num & 1) != 0, (num & 2) != 0, Handle); + return; + } + case 32850: + _owner.ChangeRegistration(keyboard: false, mouse: false, IntPtr.Zero); + DestroyHandle(); + Application.ExitThread(); + return; + } + base.WndProc(ref m); + } + } + + internal const uint RIDEV_REMOVE = 1u; + + internal const uint RIDEV_INPUTSINK = 256u; + + internal const ushort UsagePageGeneric = 1; + + internal const ushort UsageMouse = 2; + + internal const ushort UsageKeyboard = 6; + + private const int WM_INPUT = 255; + + private const int WM_APPLY = 32849; + + private const int WM_STOP = 32850; + + private const uint RID_INPUT = 268435459u; + + private const int RIM_TYPEMOUSE = 0; + + private const int RIM_TYPEKEYBOARD = 1; + + private const ushort RI_KEY_BREAK = 1; + + private const ushort RI_KEY_E0 = 2; + + private const ushort ButtonFlagsWeRead = 1008; + + internal static readonly int HeaderSize = 8 + 2 * IntPtr.Size; + + private const int BufferSize = 64; + + private readonly InputRelay _relay; + + private readonly byte[] _buffer = new byte[64]; + + private GCHandle _pin; + + private Thread? _thread; + + private Sink? _sink; + + private readonly ManualResetEventSlim _ready = new ManualResetEventSlim(initialState: false); + + private bool _registeredKeyboard; + + private bool _registeredMouse; + + private readonly Func? _registrar; + + [DllImport("user32.dll", SetLastError = true)] + private static extern bool RegisterRawInputDevices([In] RAWINPUTDEVICE[] devices, uint count, uint size); + + [DllImport("user32.dll")] + private static extern uint GetRawInputData(nint rawInput, uint command, nint data, ref uint size, uint headerSize); + + [DllImport("user32.dll")] + private static extern bool PostMessage(nint hWnd, int msg, nint wParam, nint lParam); + + public RawKeyListener(InputRelay relay) + : this(relay, null) + { + } + + internal RawKeyListener(InputRelay relay, Func? registrar) + { + _relay = relay; + _registrar = registrar; + _pin = GCHandle.Alloc(_buffer, GCHandleType.Pinned); + } + + public void Apply(bool keyboard, bool mouse) + { + if (!keyboard && !mouse) + { + if (_thread != null) + { + Sink sink = _sink; + if (sink != null) + { + PostMessage(sink.Handle, 32850, IntPtr.Zero, IntPtr.Zero); + } + _thread.Join(2000); + _thread = null; + _sink = null; + _ready.Reset(); + } + return; + } + if (_thread == null) + { + _thread = new Thread(Run) + { + IsBackground = true, + Name = "PlexusX Dark Boost keys" + }; + _thread.Start(); + if (!_ready.Wait(2000)) + { + return; + } + } + Sink sink2 = _sink; + if (sink2 != null) + { + int value = (keyboard ? 1 : 0) | (mouse ? 2 : 0); + PostMessage(sink2.Handle, 32849, new IntPtr(value), IntPtr.Zero); + } + } + + public static void Post(nint window, int message) + { + if (window != IntPtr.Zero) + { + PostMessage(window, message, IntPtr.Zero, IntPtr.Zero); + } + } + + public void Dispose() + { + Apply(keyboard: false, mouse: false); + if (_pin.IsAllocated) + { + _pin.Free(); + } + _ready.Dispose(); + } + + private void Run() + { + try + { + Sink sink = new Sink(this); + sink.CreateHandle(new CreateParams + { + Parent = new IntPtr(-3) + }); + _sink = sink; + _ready.Set(); + Application.Run(); + } + catch + { + _ready.Set(); + } + } + + internal static RAWINPUTDEVICE Device(ushort usage, bool add, nint target) + { + if (!add) + { + return new RAWINPUTDEVICE + { + UsagePage = 1, + Usage = usage, + Flags = 1u, + Target = IntPtr.Zero + }; + } + return new RAWINPUTDEVICE + { + UsagePage = 1, + Usage = usage, + Flags = 256u, + Target = target + }; + } + + private void ChangeRegistration(bool keyboard, bool mouse, nint target) + { + RAWINPUTDEVICE[] array = new RAWINPUTDEVICE[2]; + int num = 0; + if (keyboard != _registeredKeyboard) + { + array[num++] = Device(6, keyboard, target); + } + if (mouse != _registeredMouse) + { + array[num++] = Device(2, mouse, target); + } + switch (num) + { + case 0: + return; + case 1: + Array.Resize(ref array, 1); + break; + } + if ((_registrar != null) ? _registrar(array) : RegisterRawInputDevices(array, (uint)num, (uint)Marshal.SizeOf())) + { + _registeredKeyboard = keyboard; + _registeredMouse = mouse; + } + } + + private void Read(nint rawInput) + { + uint size = 64u; + uint rawInputData = GetRawInputData(rawInput, 268435459u, _pin.AddrOfPinnedObject(), ref size, (uint)HeaderSize); + if (rawInputData != 0 && rawInputData != uint.MaxValue && rawInputData <= 64) + { + Decode(new ReadOnlySpan(_buffer, 0, (int)rawInputData), _relay); + } + } + + internal static void Decode(ReadOnlySpan raw, InputRelay relay) + { + if (raw.Length < HeaderSize + 8) + { + return; + } + uint num = BinaryPrimitives.ReadUInt32LittleEndian(raw); + ReadOnlySpan source = raw.Slice(HeaderSize); + switch (num) + { + case 0u: + { + ushort num5 = BinaryPrimitives.ReadUInt16LittleEndian(source.Slice(4)); + if ((num5 & 0x3F0) != 0) + { + if ((num5 & 0x10) != 0) + { + relay.OnRawEvent(4, down: true); + } + if ((num5 & 0x20) != 0) + { + relay.OnRawEvent(4, down: false); + } + if ((num5 & 0x40) != 0) + { + relay.OnRawEvent(5, down: true); + } + if ((num5 & 0x80) != 0) + { + relay.OnRawEvent(5, down: false); + } + if ((num5 & 0x100) != 0) + { + relay.OnRawEvent(6, down: true); + } + if ((num5 & 0x200) != 0) + { + relay.OnRawEvent(6, down: false); + } + } + break; + } + case 1u: + { + ushort num2 = BinaryPrimitives.ReadUInt16LittleEndian(source); + ushort num3 = BinaryPrimitives.ReadUInt16LittleEndian(source.Slice(2)); + int num4 = BinaryPrimitives.ReadUInt16LittleEndian(source.Slice(6)); + if (num4 != 0 && num4 < 255) + { + bool flag = (num3 & 2) != 0; + relay.OnRawEvent(num4 switch + { + 16 => (num2 == 54) ? 161 : 160, + 17 => flag ? 163 : 162, + 18 => flag ? 165 : 164, + _ => num4, + }, (num3 & 1) == 0); + } + break; + } + } + } +} diff --git a/VibranceHud/IDisplayOverlay.cs b/VibranceHud/IDisplayOverlay.cs new file mode 100644 index 0000000..c1e2d7e --- /dev/null +++ b/VibranceHud/IDisplayOverlay.cs @@ -0,0 +1,16 @@ +namespace VibranceHud; + +public interface IDisplayOverlay +{ + OverlayMode ActiveMode { get; } + + DxInitFailureKind LastFailure { get; } + + string LastFailureMessage { get; } + + int LastFailureCode => 0; + + bool EffectIsLive => true; + + bool ScreenEffectHeld => false; +} diff --git a/VibranceHud/IDownloadSource.cs b/VibranceHud/IDownloadSource.cs new file mode 100644 index 0000000..e80180b --- /dev/null +++ b/VibranceHud/IDownloadSource.cs @@ -0,0 +1,11 @@ +using System; +using System.Threading.Tasks; + +namespace VibranceHud; + +internal interface IDownloadSource +{ + string Name { get; } + + Task DownloadAsync(IProgress? progress); +} diff --git a/VibranceHud/IGammaRamp.cs b/VibranceHud/IGammaRamp.cs new file mode 100644 index 0000000..9c6c41d --- /dev/null +++ b/VibranceHud/IGammaRamp.cs @@ -0,0 +1,24 @@ +namespace VibranceHud; + +public interface IGammaRamp +{ + int DeviceWrites => 0; + + bool LastApplyFailed => false; + + GammaDelivery LastDelivery => GammaDelivery.Full; + + void Apply(ushort[] ramp); + + void Reset(); + + string? ApplyAllOrNothing(ushort[] ramp) + { + Apply(ramp); + if (!LastApplyFailed) + { + return null; + } + return "Windows refused the Dark Boost ramp"; + } +} diff --git a/VibranceHud/INvapiDisplayAccess.cs b/VibranceHud/INvapiDisplayAccess.cs new file mode 100644 index 0000000..fe07f8b --- /dev/null +++ b/VibranceHud/INvapiDisplayAccess.cs @@ -0,0 +1,17 @@ +namespace VibranceHud; + +internal interface INvapiDisplayAccess +{ + int Resolve(); + + int ReadCurrentLevel(int display); + + int ReadDefaultLevel(int display); + + void WriteLevel(int display, int level); + + string DisplayId(int display) + { + return "display-" + display; + } +} diff --git a/VibranceHud/ISaturationOverlay.cs b/VibranceHud/ISaturationOverlay.cs new file mode 100644 index 0000000..6b058a3 --- /dev/null +++ b/VibranceHud/ISaturationOverlay.cs @@ -0,0 +1,14 @@ +namespace VibranceHud; + +public interface ISaturationOverlay +{ + bool LastApplySucceeded => true; + + void Apply(float[] matrix); + + void Clear(); + + void Forget() + { + } +} diff --git a/VibranceHud/IStartupRegistration.cs b/VibranceHud/IStartupRegistration.cs new file mode 100644 index 0000000..20ef041 --- /dev/null +++ b/VibranceHud/IStartupRegistration.cs @@ -0,0 +1,14 @@ +using System.Threading.Tasks; + +namespace VibranceHud; + +public interface IStartupRegistration +{ + StartupState State { get; } + + Task RefreshAsync(); + + Task TurnOnAsync(); + + void TurnOff(); +} diff --git a/VibranceHud/IVibranceController.cs b/VibranceHud/IVibranceController.cs new file mode 100644 index 0000000..c5bd78e --- /dev/null +++ b/VibranceHud/IVibranceController.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; + +namespace VibranceHud; + +public interface IVibranceController +{ + int CurrentLevel { get; } + + int DefaultLevel { get; } + + bool IsAvailable { get; } + + VibranceDriverState DriverState + { + get + { + if (!IsAvailable) + { + return VibranceDriverState.NoNvidiaCard; + } + return VibranceDriverState.Available; + } + } + + bool EveryDisplayIsAt(int level) + { + return CurrentLevel == level; + } + + void SetLevel(int level); + + IReadOnlyList> ReadEveryDisplayLevel() + { + return Array.Empty>(); + } + + void SetLevelFor(string displayId, int level) + { + } +} diff --git a/VibranceHud/IVibranceEngine.cs b/VibranceHud/IVibranceEngine.cs new file mode 100644 index 0000000..7d34d41 --- /dev/null +++ b/VibranceHud/IVibranceEngine.cs @@ -0,0 +1,159 @@ +namespace VibranceHud; + +public interface IVibranceEngine +{ + int Vibrance { get; set; } + + bool VibranceChosenByUser => false; + + bool StreamingMode + { + get + { + return false; + } + set + { + } + } + + bool DriverAvailable => false; + + bool PaidControlsUnlocked => false; + + bool ScreenEffectIsLive => true; + + int Saturation { get; set; } + + int Brightness { get; set; } + + int Gamma { get; set; } + + int Contrast + { + get + { + return 100; + } + set + { + } + } + + int Temperature + { + get + { + return 0; + } + set + { + } + } + + ToneSettings Tone + { + get + { + return ToneSettings.Neutral; + } + set + { + } + } + + DisplayOnlyLook.Knob DriverKnobFollows + { + get + { + return DisplayOnlyLook.Knob.Stronger; + } + set + { + } + } + + int Hue + { + get + { + return 0; + } + set + { + } + } + + int RedGain + { + get + { + return 100; + } + set + { + } + } + + int GreenGain + { + get + { + return 100; + } + set + { + } + } + + int BlueGain + { + get + { + return 100; + } + set + { + } + } + + ColourVisionMode ColourVision + { + get + { + return ColourVisionMode.Off; + } + set + { + } + } + + ChannelMix Mix + { + get + { + return ChannelMix.Identity; + } + set + { + } + } + + void SeedVibrance(int value) + { + Vibrance = value; + } + + CaptureProbe RunCaptureProbe() + { + return CaptureProbe.Failed("not supported by this engine"); + } + + void BeginDrag(); + + void EndDrag(); + + void SuspendOverlay(); + + void ResumeOverlay(); +} diff --git a/VibranceHud/LastSentEffect.cs b/VibranceHud/LastSentEffect.cs new file mode 100644 index 0000000..d26f47d --- /dev/null +++ b/VibranceHud/LastSentEffect.cs @@ -0,0 +1,48 @@ +namespace VibranceHud; + +public sealed class LastSentEffect +{ + private float[]? _sent; + + private bool _known; + + public bool AlreadySent(float[]? next) + { + if (!_known) + { + return false; + } + if (_sent == null || next == null) + { + if (_sent == null) + { + return next == null; + } + return false; + } + if (_sent.Length != next.Length) + { + return false; + } + for (int i = 0; i < _sent.Length; i++) + { + if (_sent[i] != next[i]) + { + return false; + } + } + return true; + } + + public void Remember(float[]? sent) + { + _known = true; + _sent = ((sent == null) ? null : ((float[])sent.Clone())); + } + + public void Forget() + { + _known = false; + _sent = null; + } +} diff --git a/VibranceHud/LaunchOptions.cs b/VibranceHud/LaunchOptions.cs new file mode 100644 index 0000000..3846546 --- /dev/null +++ b/VibranceHud/LaunchOptions.cs @@ -0,0 +1,44 @@ +using System; +using System.Linq; + +namespace VibranceHud; + +public static class LaunchOptions +{ + public const string TraySwitch = "--tray"; + + public const string TraceColourSwitch = "--trace-colour"; + + public static bool StartInTray { get; private set; } + + public static bool TraceColour { get; private set; } + + public static void Parse(string[]? args) + { + StartInTray = Has(args, "--tray"); + TraceColour = Has(args, "--trace-colour"); + } + + public static string[] WithTraySwitch(string[]? args) + { + if (args != null && Has(args, "--tray")) + { + return args; + } + string[] array = new string[(args?.Length ?? 0) + 1]; + args?.CopyTo(array, 0); + array[^1] = "--tray"; + return array; + } + + private static bool Has(string[]? args, string option) + { + return args?.Any((string a) => string.Equals(a, option, StringComparison.OrdinalIgnoreCase)) ?? false; + } + + internal static void ResetForTest() + { + StartInTray = false; + TraceColour = false; + } +} diff --git a/VibranceHud/LibraryCard.cs b/VibranceHud/LibraryCard.cs new file mode 100644 index 0000000..d6b0ad2 --- /dev/null +++ b/VibranceHud/LibraryCard.cs @@ -0,0 +1,862 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Text; +using System.Globalization; +using System.Text; +using System.Windows.Forms; +using VibranceHud.Controls; +using VibranceHud.Crosshair; +using VibranceHud.Design; + +namespace VibranceHud; + +public sealed class LibraryCard : Control +{ + private readonly record struct Verticals(int HeadTop, int HeadH, int BylineTop, int BylineH, int DescTop, int DescBottom, int SatTop, int SatH, int BarTop, int BarH, int FactsTop, int FactsH, int ActionTop, int ActionH); + + private sealed class CardAccessibleObject : ControlAccessibleObject + { + private readonly LibraryCard _owner; + + public override AccessibleStates State => (AccessibleStates)((int)base.State | (_owner._active ? 16 : 0)); + + public CardAccessibleObject(LibraryCard owner) + : base(owner) + { + _owner = owner; + } + } + + internal readonly record struct CardLayout(Rectangle Glyph, Rectangle Name, Rectangle Byline, Rectangle Description, Rectangle SaturationCaption, Rectangle SaturationValue, Rectangle Bar, Rectangle Facts, Rectangle Action, Rectangle Badge, Rectangle Preview); + + private GlassButton? _reportButton; + + private const int Edge = 1; + + private const int PadY = 16; + + private const int PadX = 16; + + private const int HeadRow = 28; + + private const int BylineGap = 0; + + private const int DescGap = 8; + + private const int DescMin = 40; + + private const int SatGap = 8; + + private const int SatRow = 20; + + private const int BarGap = 8; + + private const int FooterGap = 8; + + private const int FooterRow = 28; + + private const int StackGap = 8; + + private const int RulerW = 266; + + private const int ButtonPadX = 12; + + private const int ButtonMinW = 56; + + private const int StatusIcon = 16; + + private const int StatusGap = 8; + + internal const int Chrome = 188; + + internal const int SidePad = 17; + + private const int CaptionLine = 16; + + private const int DescriptionLead = 20; + + private const int BarHeightLogical = 6; + + internal const int FullScale = 300; + + private const int Untouched = 100; + + private bool _active; + + private readonly HoverFade _fade; + + private string _caption = ""; + + private string _author = ""; + + private string _subtitle = ""; + + private SignalToolTip? _titleTip; + + private string _titleTipText = ""; + + private readonly OutsideFocusRing _ring; + + internal static int SharedFooterSaving => Row(FontRole.Caption) + S(8); + + internal static int MinimumDescription => S(40); + + public string Caption + { + get + { + return _caption; + } + set + { + if (value == null) + { + value = ""; + } + if (!(_caption == value)) + { + _caption = value; + SyncAccessibility(); + } + } + } + + public string Author + { + get + { + return _author; + } + set + { + if (value == null) + { + value = ""; + } + if (!(_author == value)) + { + _author = value; + SyncAccessibility(); + } + } + } + + public string Subtitle + { + get + { + return _subtitle; + } + set + { + if (value == null) + { + value = ""; + } + if (!(_subtitle == value)) + { + _subtitle = value; + SyncAccessibility(); + } + } + } + + internal string TitleTipForTest => _titleTipText; + + public string Kind { get; set; } = "balanced"; + + public int Saturation { get; set; } + + public int Vibrance { get; set; } + + public int Temperature { get; set; } + + public float[]? Matrix { get; set; } + + public CrosshairConfig? CrosshairPreview { get; set; } + + private bool ShowsPreview => CrosshairPreview != null; + + public string Footer { get; set; } = ""; + + public bool Active + { + get + { + return _active; + } + set + { + if (Locked) + { + value = false; + } + if (_active != value) + { + _active = value; + Invalidate(); + if (IsHandleCreated) + { + AccessibilityNotifyClients(AccessibleEvents.StateChange, -1); + } + } + } + } + + public bool Locked { get; set; } + + internal string ActionLabel + { + get + { + if (!_active) + { + return "Apply"; + } + return "In use"; + } + } + + internal string BadgeLabel + { + get + { + if (!_active) + { + return ""; + } + return "Applied"; + } + } + + internal string SaturationText + { + get + { + if (Saturation <= 0) + { + return ""; + } + return Saturation.ToString(CultureInfo.InvariantCulture) + "%"; + } + } + + internal string FactsText + { + get + { + if (Footer.Length > 0) + { + return Footer; + } + if (Saturation <= 0) + { + return ""; + } + return "Vibrance " + Vibrance.ToString(CultureInfo.InvariantCulture) + " · Temp " + SignedTemperature(Temperature); + } + } + + private static int HeadH => Math.Max(S(28), Row(FontRole.BodyBold)); + + private static int SatH => Math.Max(S(20), Row(FontRole.BodyBold)); + + private static Color LabelInk + { + get + { + if (!(Theme.CurrentName == "Slate")) + { + return SignalTokens.Ash.Text3; + } + return SignalTokens.Slate.Text3; + } + } + + private static Color[] Strands => new Color[6] + { + SignalTokens.Root.Signal1, + SignalTokens.Root.Signal2, + SignalTokens.Root.Signal3, + SignalTokens.Root.Signal4, + SignalTokens.Root.Signal5, + SignalTokens.Root.Signal6 + }; + + public new event EventHandler? Click; + + internal void OfferReport(Action report) + { + _reportButton = new GlassButton + { + Text = "Report", + AccessibleName = "Report " + Caption, + Kind = GlassButtonKind.Quiet, + TabStop = true + }; + _reportButton.Click += (object? _, EventArgs _) => + { + report(); + }; + Controls.Add(_reportButton); + PlaceReportButton(); + } + + private void PlaceReportButton() + { + if (_reportButton != null) + { + Rectangle byline = LayOut().Byline; + _reportButton.Bounds = new Rectangle(Width - S(17) - ButtonWidth("Report"), byline.Top, ButtonWidth("Report"), byline.Height); + } + } + + internal static int HeightForDescription(int descHeight) + { + return Math.Max(204, descHeight + 188) + 2; + } + + internal static int FixedChrome(bool sharedFooter) + { + Verticals verticals = Vertical(0, sharedFooter); + return verticals.DescTop - verticals.DescBottom; + } + + private static Verticals Vertical(int height, bool shared) + { + int num = S(17); + int headH = HeadH; + int num2 = Row(FontRole.Caption); + int num3 = Math.Max(S(45), num + headH); + int descTop = Math.Max(S(69), num3 + num2); + int num4 = S(28); + int num5 = height - S(45); + int num6 = (shared ? num4 : Row(FontRole.Caption)); + int num7 = (shared ? num5 : (num5 - S(8) - num6)); + int num8 = 53 + ((!shared) ? 24 : 0); + int num9 = S(6); + int num10 = Math.Min(height - S(num8 + 6), num7 - S(8) - num9); + int satH = SatH; + int num11 = Math.Min(height - S(num8 + 6 + 8 + 20), num10 - S(8) - satH); + return new Verticals(num, headH, num3, num2, descTop, num11 - S(8), num11, satH, num10, num9, num7, num6, num5, num4); + } + + internal static bool FooterSharesARow(int width, string facts, string action) + { + int num = width - 2 * S(17); + if (num <= 0) + { + return false; + } + int width2 = TextRenderer.MeasureText(facts, Fonts.Caption).Width; + int num2 = Math.Max(ButtonWidth(action), StatusWidth(action)); + return width2 + S(12) + num2 <= num; + } + + private void SyncAccessibility() + { + AccessibleName = ((_author.Length > 0) ? (_caption + " by " + _author) : _caption); + AccessibleDescription = ((_subtitle.Length > 0) ? _subtitle : null); + SyncTitleTip(); + } + + protected override AccessibleObject CreateAccessibilityInstance() + { + return new CardAccessibleObject(this); + } + + private void SyncTitleTip() + { + string text = ""; + if (_caption.Length > 0 && !IsDisposed) + { + int width = LayOut().Name.Width; + if (Advance(_caption, Fonts.BodyBold) > width) + { + text = _caption; + } + } + if (text == _titleTipText) + { + return; + } + _titleTipText = text; + if (text.Length == 0) + { + _titleTip?.SetToolTip(this, null); + return; + } + if (_titleTip == null) + { + _titleTip = new SignalToolTip + { + InitialDelay = 420 + }; + } + _titleTip.SetToolTip(this, text); + } + + protected override void OnSizeChanged(EventArgs e) + { + base.OnSizeChanged(e); + PlaceReportButton(); + SyncTitleTip(); + } + + internal void PressForTest() + { + Click?.Invoke(this, EventArgs.Empty); + } + + internal static string SignedTemperature(int temperature) + { + if (temperature <= 0) + { + if (temperature < 0) + { + return "−" + (-temperature).ToString(CultureInfo.InvariantCulture); + } + return "0"; + } + return "+" + temperature.ToString(CultureInfo.InvariantCulture); + } + + public LibraryCard() + { + _fade = new HoverFade(this); + _ring = new OutsideFocusRing(this, () => S(8)); + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.Selectable | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + Cursor = Cursors.Hand; + Size = new Size(215, HeightForDescription(32)); + TabStop = true; + AccessibleRole = AccessibleRole.RadioButton; + } + + protected override void OnMouseEnter(EventArgs e) + { + base.OnMouseEnter(e); + _fade.Set(hot: true); + Invalidate(); + } + + protected override void OnMouseLeave(EventArgs e) + { + base.OnMouseLeave(e); + _fade.Set(hot: false); + Invalidate(); + } + + protected override void OnMouseUp(MouseEventArgs e) + { + base.OnMouseUp(e); + if (e.Button == MouseButtons.Left && ClientRectangle.Contains(e.Location)) + { + Click?.Invoke(this, EventArgs.Empty); + } + } + + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + if (e.KeyCode == Keys.Return || e.KeyCode == Keys.Space) + { + Click?.Invoke(this, EventArgs.Empty); + e.Handled = true; + } + } + + internal void TestPressKey(Keys key) + { + OnKeyDown(new KeyEventArgs(key)); + } + + protected override void OnGotFocus(EventArgs e) + { + base.OnGotFocus(e); + Invalidate(); + } + + protected override void OnLostFocus(EventArgs e) + { + base.OnLostFocus(e); + Invalidate(); + } + + protected override void OnParentChanged(EventArgs e) + { + base.OnParentChanged(e); + _ring.Rehook(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _ring.Release(); + _titleTip?.Dispose(); + _titleTip = null; + } + base.Dispose(disposing); + } + + private static int LineBox(FontRole role) + { + return Tokens.Scale(Fonts.Step(role).LinePx); + } + + private static int Row(FontRole role) + { + return Math.Max(LineBox(role), TextRenderer.MeasureText("Hg", Fonts.For(role)).Height); + } + + private static int S(int logical) + { + return Tokens.Scale(logical); + } + + private static int Advance(string text, Font font) + { + return TextRenderer.MeasureText(text, font, Size.Empty, TextFormatFlags.NoPadding).Width; + } + + private static int ButtonWidth(string label) + { + return Math.Max(S(56), Advance(label, Fonts.BodyBold) + 2 * S(12)); + } + + private static int StatusWidth(string label) + { + return S(16) + S(8) + Advance(label, Fonts.BodyBold); + } + + internal CardLayout TestLayout() + { + return LayOut(); + } + + private CardLayout LayOut() + { + int num = S(17); + int num2 = Math.Max(1, Width - 2 * num); + bool flag = FooterSharesARow(Width, FactsText, ActionLabel); + Verticals verticals = Vertical(Height, flag); + int num3 = Math.Min(Math.Max(0, num2 - S(32) - S(24)), S(16) + S(6) + Advance("Applied", Fonts.Body) + S(2)); + Rectangle rectangle = new Rectangle(num + num2 - num3, verticals.HeadTop, num3, verticals.HeadH); + Rectangle badge = ((BadgeLabel.Length > 0) ? rectangle : Rectangle.Empty); + int width = Math.Max(1, rectangle.Left - S(12) - num); + Rectangle name = new Rectangle(num, verticals.HeadTop, width, verticals.HeadH); + Rectangle byline = new Rectangle(num, verticals.BylineTop, Math.Max(1, num2 - ((_reportButton != null) ? (ButtonWidth("Report") + S(8)) : 0)), verticals.BylineH); + int num4 = (_active ? Math.Min(num2, StatusWidth(ActionLabel)) : Math.Min(num2, ButtonWidth(ActionLabel))); + Rectangle action = new Rectangle(num + num2 - num4, verticals.ActionTop, num4, verticals.ActionH); + Rectangle facts = (flag ? new Rectangle(num, verticals.FactsTop, Math.Max(1, action.Left - S(12) - num), verticals.FactsH) : new Rectangle(num, verticals.FactsTop, num2, verticals.FactsH)); + Rectangle bar = new Rectangle(num, verticals.BarTop, Math.Min(num2, S(266)), verticals.BarH); + int satTop = verticals.SatTop; + int satH = verticals.SatH; + int num5 = Math.Min(num2 / 2, Math.Max(S(32), TextRenderer.MeasureText(SaturationText, Fonts.BodyBold).Width)); + Rectangle saturationCaption = new Rectangle(num, satTop, num2 - num5, satH); + Rectangle saturationValue = new Rectangle(saturationCaption.Right, satTop, num5, satH); + Rectangle preview = Rectangle.Empty; + if (ShowsPreview) + { + preview = new Rectangle(num, satTop, num2, bar.Bottom - satTop); + saturationCaption = (saturationValue = (bar = Rectangle.Empty)); + } + return new CardLayout(Description: new Rectangle(num, verticals.DescTop, num2, Math.Max(1, verticals.DescBottom - verticals.DescTop)), Glyph: Rectangle.Empty, Name: name, Byline: byline, SaturationCaption: saturationCaption, SaturationValue: saturationValue, Bar: bar, Facts: facts, Action: action, Badge: badge, Preview: preview); + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics g = e.Graphics; + PaintGuard.Try(this, () => + { + PaintCard(g); + }); + base.OnPaint(e); + } + + private void PaintCard(Graphics g) + { + g.SmoothingMode = SmoothingMode.AntiAlias; + g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; + CardLayout cardLayout = LayOut(); + PaintBody(g); + TextRenderer.DrawText(g, Caption, Fonts.BodyBold, cardLayout.Name, Theme.Text, TextFormatFlags.EndEllipsis | TextFormatFlags.NoPrefix | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding); + if (Author.Length > 0) + { + TextRenderer.DrawText(g, "by " + Author, Fonts.Caption, cardLayout.Byline, LabelInk, TextFormatFlags.EndEllipsis | TextFormatFlags.NoPrefix | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding); + } + if (!cardLayout.Badge.IsEmpty) + { + DrawBadge(g, cardLayout.Badge); + } + DrawDescription(g, cardLayout.Description); + if (ShowsPreview) + { + DrawPreview(g, cardLayout.Preview); + } + else if (Saturation > 0) + { + TextRenderer.DrawText(g, "Saturation", Fonts.Caption, cardLayout.SaturationCaption, LabelInk, TextFormatFlags.Bottom | TextFormatFlags.EndEllipsis | TextFormatFlags.NoPadding); + TextRenderer.DrawText(g, SaturationText, Fonts.BodyBold, cardLayout.SaturationValue, Theme.Text, TextFormatFlags.NoClipping | TextFormatFlags.Right | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding); + DrawSignal(g, cardLayout.Bar); + } + else if (Footer.Length == 0) + { + DrawSweep(g, cardLayout.Bar); + } + if (FactsText.Length > 0) + { + TextRenderer.DrawText(g, FactsText, Fonts.Caption, cardLayout.Facts, LabelInk, TextFormatFlags.EndEllipsis | TextFormatFlags.NoPrefix | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding); + } + DrawAction(g, cardLayout.Action); + } + + private void PaintBody(Graphics g) + { + RectangleF rect = new RectangleF(0.5f, 0.5f, Width - 1, Height - 1); + float radius = S(8); + using GraphicsPath path = Glass.RoundedPath(rect, radius); + if (SlateSurface.Active) + { + Glass.PaintPanel(g, rect, radius, Glass.BackdropOffsetOf(this)); + } + else + { + using SolidBrush brush = new SolidBrush(Theme.Surface); + g.FillPath(brush, path); + } + float t = (_active ? 1f : (0.45f * _fade.Value)); + using (Pen pen = new Pen(Blend(Theme.Border, Theme.GlassEdge, t), S(1))) + { + g.DrawPath(pen, path); + } + if (Focused && ShowFocusCues) + { + _ring.Show(show: true); + } + else + { + _ring.Show(show: false); + } + } + + private static Color Blend(Color from, Color to, float t) + { + t = Math.Clamp(t, 0f, 1f); + return Color.FromArgb((int)Math.Round((float)(int)from.A + (float)(to.A - from.A) * t), (int)Math.Round((float)(int)from.R + (float)(to.R - from.R) * t), (int)Math.Round((float)(int)from.G + (float)(to.G - from.G) * t), (int)Math.Round((float)(int)from.B + (float)(to.B - from.B) * t)); + } + + internal static int DescriptionHeight(string text, int width) + { + return WrapDescription(text, width, int.MaxValue).Count * S(20); + } + + private static List WrapDescription(string text, int width, int maxLines) + { + List list = new List(); + if (string.IsNullOrEmpty(text) || width <= 0 || maxLines <= 0) + { + return list; + } + Font body = Fonts.Body; + StringBuilder stringBuilder = new StringBuilder(); + string[] array = text.Split(' ', StringSplitOptions.RemoveEmptyEntries); + foreach (string text2 in array) + { + string text3 = ((stringBuilder.Length == 0) ? text2 : (stringBuilder?.ToString() + " " + text2)); + if (stringBuilder.Length > 0 && Advance(text3, body) > width) + { + list.Add(stringBuilder.ToString()); + stringBuilder.Clear(); + stringBuilder.Append(text2); + if (list.Count == maxLines) + { + return list; + } + } + else + { + stringBuilder.Clear(); + stringBuilder.Append(text3); + } + } + if (list.Count < maxLines && stringBuilder.Length > 0) + { + list.Add(stringBuilder.ToString()); + } + return list; + } + + private void DrawDescription(Graphics g, Rectangle box) + { + if (Subtitle.Length != 0 && box.Width > 0 && box.Height > 0) + { + int num = S(20); + int maxLines = Math.Max(1, box.Height / Math.Max(1, num)); + List list = WrapDescription(Subtitle, box.Width, maxLines); + for (int i = 0; i < list.Count; i++) + { + bool flag = i == list.Count - 1; + TextFormatFlags flags = (TextFormatFlags)(0x10000804 | (flag ? 32768 : 0)); + TextRenderer.DrawText(g, list[i], Fonts.Body, new Rectangle(box.X, box.Y + i * num, box.Width, num), Theme.TextDim, flags); + } + } + } + + private void DrawPreview(Graphics g, Rectangle box) + { + if (CrosshairPreview == null || box.Width < 8 || box.Height < 8) + { + return; + } + using GraphicsPath path = Glass.RoundedPath(new RectangleF(box.X, box.Y, box.Width, box.Height), S(4)); + using Region clip = g.Clip; + g.SetClip(path, CombineMode.Intersect); + CrosshairRender.DrawCheckerboard(g, box, S(8)); + CrosshairRender.Draw(g, CrosshairPreview, box); + g.Clip = clip; + } + + private static void DrawBadge(Graphics g, Rectangle box) + { + int num = Advance("Applied", Fonts.Body); + int num2 = S(16); + int x = box.Right - num - S(6) - num2; + LineIcons.Check(g, new Rectangle(x, box.Y + (box.Height - num2) / 2, num2, num2), Theme.Text); + TextRenderer.DrawText(g, "Applied", Fonts.Body, new Rectangle(box.Right - num, box.Y, num + S(2), box.Height), Theme.Text, TextFormatFlags.NoClipping | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding); + } + + private void DrawAction(Graphics g, Rectangle box) + { + if (Locked) + { + int num = S(16); + SignalIcons.Draw(g, SignalIcon.Lock, new RectangleF((float)box.X + (float)(box.Width - num) / 2f, (float)box.Y + (float)(box.Height - num) / 2f, num, num), LabelInk); + return; + } + if (_active) + { + int num2 = S(16); + int num3 = Advance(ActionLabel, Fonts.BodyBold); + int num4 = box.Right - num3 - S(8) - num2; + SignalIcons.Draw(g, SignalIcon.Success, new RectangleF(num4, (float)box.Y + (float)(box.Height - num2) / 2f, num2, num2), ControlInk.Success); + TextRenderer.DrawText(g, ActionLabel, Fonts.BodyBold, new Rectangle(box.Right - num3, box.Y, num3 + S(2), box.Height), Theme.Text, TextFormatFlags.NoClipping | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding); + return; + } + using GraphicsPath path = Glass.RoundedPath(new RectangleF((float)box.X + 0.5f, (float)box.Y + 0.5f, box.Width - 1, box.Height - 1), S(4)); + if (_fade.Value > 0.01f) + { + using SolidBrush brush = new SolidBrush(Color.FromArgb((int)(255f * _fade.Value), Theme.SurfaceHover)); + g.FillPath(brush, path); + } + using (Pen pen = new Pen(Theme.GlassEdge, S(1))) + { + g.DrawPath(pen, path); + } + TextRenderer.DrawText(g, ActionLabel, Fonts.BodyBold, box, Theme.Text, TextFormatFlags.HorizontalCenter | TextFormatFlags.NoClipping | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding); + } + + private void DrawSignal(Graphics g, Rectangle bar) + { + if (bar.Width < 8 || bar.Height < 3) + { + return; + } + SmoothingMode smoothingMode = g.SmoothingMode; + PixelOffsetMode pixelOffsetMode = g.PixelOffsetMode; + g.SmoothingMode = SmoothingMode.None; + g.PixelOffsetMode = PixelOffsetMode.Half; + try + { + int num = Math.Clamp(Saturation, 0, 300); + float num2 = At(bar, num); + float num3 = At(bar, 100); + if (num < 300) + { + int num4 = Math.Max(1, S(2)); + using SolidBrush brush = new SolidBrush(Theme.AccentDim); + g.FillRectangle(brush, num2, (float)bar.Y + (float)bar.Height / 2f - (float)num4 / 2f, (float)bar.Right - num2, num4); + } + using (SolidBrush brush2 = new SolidBrush(SignalTokens.Root.SignalStart)) + { + g.FillRectangle(brush2, bar.X, bar.Y, Math.Min(num2, num3) - (float)bar.X, bar.Height); + } + if (num <= 100) + { + return; + } + Color[] strands = Strands; + for (int i = 0; i < strands.Length; i++) + { + int num5 = bar.Y + i * bar.Height / strands.Length; + int num6 = Math.Max(num5 + 1, bar.Y + (i + 1) * bar.Height / strands.Length); + using LinearGradientBrush brush3 = new LinearGradientBrush(new RectangleF(num3, num5 - 1, (float)(bar.X + bar.Width) - num3, num6 - num5 + 2), SignalTokens.Root.SignalStart, strands[i], LinearGradientMode.Horizontal) + { + WrapMode = WrapMode.TileFlipX + }; + g.FillRectangle(brush3, num3, num5, num2 - num3, num6 - num5); + } + } + finally + { + g.SmoothingMode = smoothingMode; + g.PixelOffsetMode = pixelOffsetMode; + } + } + + private static float At(Rectangle bar, int value) + { + return (float)bar.X + (float)bar.Width * ((float)value / 300f); + } + + private void DrawSweep(Graphics g, Rectangle bar) + { + if (bar.Width < 8 || bar.Height < 2) + { + return; + } + Color[] strands = Strands; + Color[] array = new Color[strands.Length]; + for (int i = 0; i < strands.Length; i++) + { + array[i] = Transform(strands[i]); + } + using LinearGradientBrush linearGradientBrush = new LinearGradientBrush(new Rectangle(bar.X, bar.Y - 1, bar.Width, bar.Height + 2), array[0], array[^1], LinearGradientMode.Horizontal); + ColorBlend colorBlend = new ColorBlend(strands.Length) + { + Colors = array, + Positions = new float[strands.Length] + }; + for (int j = 0; j < strands.Length; j++) + { + colorBlend.Positions[j] = (float)j / (float)(strands.Length - 1); + } + linearGradientBrush.InterpolationColors = colorBlend; + linearGradientBrush.WrapMode = WrapMode.TileFlipXY; + g.FillRectangle(linearGradientBrush, bar); + } + + private Color Transform(Color c) + { + float[] matrix = Matrix; + if (matrix == null || matrix.Length < 25) + { + return c; + } + float num = (float)(int)c.R / 255f; + float num2 = (float)(int)c.G / 255f; + float num3 = (float)(int)c.B / 255f; + float v = num * matrix[0] + num2 * matrix[5] + num3 * matrix[10] + matrix[20]; + float v2 = num * matrix[1] + num2 * matrix[6] + num3 * matrix[11] + matrix[21]; + float v3 = num * matrix[2] + num2 * matrix[7] + num3 * matrix[12] + matrix[22]; + return Color.FromArgb(Byte(v), Byte(v2), Byte(v3)); + } + + private static int Byte(float v) + { + return Math.Clamp((int)Math.Round(v * 255f), 0, 255); + } +} diff --git a/VibranceHud/Licensing/ActivationEndpoint.cs b/VibranceHud/Licensing/ActivationEndpoint.cs new file mode 100644 index 0000000..7a29e1c --- /dev/null +++ b/VibranceHud/Licensing/ActivationEndpoint.cs @@ -0,0 +1,19 @@ +using System; + +namespace VibranceHud.Licensing; + +internal static class ActivationEndpoint +{ + internal const string Origin = "https://plexusx.lol"; + + internal const string SiteOrigin = "https://plexusx.lol"; + + internal static string SwitchesUrl => Origin + "/api/app/switches"; + + internal static string LibraryUrl => Origin + "/api/presets/library"; + + internal static string StatusUrlFor(string channel) + { + return Origin + "/api/app/status?channel=" + Uri.EscapeDataString(channel ?? ""); + } +} diff --git a/VibranceHud/Licensing/DarkBoostTable.cs b/VibranceHud/Licensing/DarkBoostTable.cs new file mode 100644 index 0000000..453b522 --- /dev/null +++ b/VibranceHud/Licensing/DarkBoostTable.cs @@ -0,0 +1,26 @@ +namespace VibranceHud.Licensing; + +public sealed class DarkBoostTable +{ + private readonly float[] _matrix; + + private readonly ushort[] _ramp; + + private readonly float[]? _fallback; + + public float[] Matrix => (float[])_matrix.Clone(); + + public ushort[] Ramp => (ushort[])_ramp.Clone(); + + public float[]? FallbackMatrix => (float[])_fallback?.Clone(); + + public bool RampIsStraight { get; } + + internal DarkBoostTable(float[] matrix, ushort[] ramp, float[]? fallbackMatrix) + { + _matrix = (float[])matrix.Clone(); + _ramp = (ushort[])ramp.Clone(); + _fallback = (float[])fallbackMatrix?.Clone(); + RampIsStraight = DarkBoostPicture.IsStraight(_ramp); + } +} diff --git a/VibranceHud/Licensing/GradeCurve.cs b/VibranceHud/Licensing/GradeCurve.cs new file mode 100644 index 0000000..b3c784f --- /dev/null +++ b/VibranceHud/Licensing/GradeCurve.cs @@ -0,0 +1,6 @@ +namespace VibranceHud.Licensing; + +public sealed record GradeCurve(double RegionRange, int RegionSharpness, double PointRange, int PointSharpness, double TintRange) +{ + public static readonly GradeCurve Withheld = new GradeCurve(0.0, 1, 0.0, 1, 0.0); +} diff --git a/VibranceHud/Licensing/LoadedBuild.cs b/VibranceHud/Licensing/LoadedBuild.cs new file mode 100644 index 0000000..bfb221b --- /dev/null +++ b/VibranceHud/Licensing/LoadedBuild.cs @@ -0,0 +1,55 @@ +using System; +using System.IO; +using System.Security.Cryptography; + +namespace VibranceHud.Licensing; + +public static class LoadedBuild +{ + private static readonly object Gate = new object(); + + private static string? _cached; + + private static bool _computed; + + public static string? Sha256() + { + lock (Gate) + { + if (_computed) + { + return _cached; + } + _computed = true; + _cached = HashOf(typeof(LoadedBuild).Assembly.Location); + return _cached; + } + } + + internal static string? HashOf(string? path) + { + if (string.IsNullOrEmpty(path)) + { + return null; + } + try + { + using FileStream inputStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + using SHA256 sHA = SHA256.Create(); + return Convert.ToHexString(sHA.ComputeHash(inputStream)).ToLowerInvariant(); + } + catch + { + return null; + } + } + + internal static void ForgetForTest() + { + lock (Gate) + { + _computed = false; + _cached = null; + } + } +} diff --git a/VibranceHud/Licensing/LoopbackSignIn.cs b/VibranceHud/Licensing/LoopbackSignIn.cs new file mode 100644 index 0000000..f9648f3 --- /dev/null +++ b/VibranceHud/Licensing/LoopbackSignIn.cs @@ -0,0 +1,49 @@ +using System; +using System.Diagnostics; +using System.IO; + +namespace VibranceHud.Licensing; + +internal static class LoopbackSignIn +{ + private static Func? _settingsSource; + + internal static void UseTheBrowserFrom(Func settingsSource) + { + _settingsSource = settingsSource; + } + + internal static void OpenBrowser(string url) + { + TryOpenBrowser(url); + } + + internal static bool TryOpenBrowser(string url) + { + if (string.IsNullOrWhiteSpace(url)) + { + return false; + } + try + { + string? browserPath = _settingsSource?.Invoke()?.SignInBrowserPath; + if (!string.IsNullOrWhiteSpace(browserPath) && File.Exists(browserPath)) + { + Process.Start(new ProcessStartInfo(browserPath, url) + { + UseShellExecute = false + }); + return true; + } + Process.Start(new ProcessStartInfo(url) + { + UseShellExecute = true + }); + return true; + } + catch + { + return false; + } + } +} diff --git a/VibranceHud/Licensing/PairingFormat.cs b/VibranceHud/Licensing/PairingFormat.cs new file mode 100644 index 0000000..00e3c96 --- /dev/null +++ b/VibranceHud/Licensing/PairingFormat.cs @@ -0,0 +1,30 @@ +using System; +using System.Globalization; + +namespace VibranceHud.Licensing; + +public sealed record PairingFormat(string Alphabet, int TokenLength, int TokenBits, string UrlTemplate) +{ + public bool Withheld + { + get + { + if (Alphabet.Length != 0 && TokenLength > 0 && TokenBits > 0) + { + return UrlTemplate.Length == 0; + } + return true; + } + } + + public static readonly PairingFormat Withholding = new PairingFormat("", 0, 0, ""); + + public string Url(string address, int port, string token) + { + if (Withheld || string.IsNullOrEmpty(token)) + { + return ""; + } + return UrlTemplate.Replace("{address}", address, StringComparison.Ordinal).Replace("{port}", port.ToString(CultureInfo.InvariantCulture), StringComparison.Ordinal).Replace("{token}", token, StringComparison.Ordinal); + } +} diff --git a/VibranceHud/Licensing/ServedCodes.cs b/VibranceHud/Licensing/ServedCodes.cs new file mode 100644 index 0000000..8cc05b2 --- /dev/null +++ b/VibranceHud/Licensing/ServedCodes.cs @@ -0,0 +1,42 @@ +using System.Collections.Generic; + +namespace VibranceHud.Licensing; + +public static class ServedCodes +{ + private static readonly ShareCodeFormat DefaultFormat = new ShareCodeFormat( + Alphabet: "23456789ABCDEFGHJKMNPQRSTUVWXYZ#", + Prefix: "PX-", + ChecksumModulus: 32, + ChecksumWeightStep: 2, + ChecksumWeightOffset: 1, + ChecksumIndexOffset: 0, + BodyLengths: new Dictionary + { + [13] = 6, + [17] = 8, + [19] = 9, + [27] = 13, + [39] = 19 + }, + MaxVibrance: 350, + MaxSaturation: 200, + MinBrightness: 50, + MaxBrightness: 150, + MinGamma: 50, + MaxGamma: 150, + MinContrast: 50, + MaxContrast: 150, + MinTemperature: -100, + MaxTemperature: 100, + MinGrade: -100, + MaxGrade: 100); + + public static ShareCodeFormat Current => DefaultFormat; + + public static ServedSource Source => ServedSource.Served; + + internal static void Install() + { + } +} diff --git a/VibranceHud/Licensing/ServedCrosshairs.cs b/VibranceHud/Licensing/ServedCrosshairs.cs new file mode 100644 index 0000000..eb85aea --- /dev/null +++ b/VibranceHud/Licensing/ServedCrosshairs.cs @@ -0,0 +1,66 @@ +using System.Collections.Generic; +using VibranceHud.Crosshair; + +namespace VibranceHud.Licensing; + +public static class ServedCrosshairs +{ + private static readonly IReadOnlyList BuiltInDesigns = BuildDesigns(); + + public static IReadOnlyList Designs => BuiltInDesigns; + + public static ServedSource Source => ServedSource.Served; + + public static bool OnTheirWay => false; + + public static int Generation => 1; + + internal static void Install() + { + } + + private static IReadOnlyList BuildDesigns() + { + return new CrosshairGallery.GalleryItem[] + { + Make("dot-fine", "Fine Dot", CrosshairGallery.Family.Dot, size: 10, thick: 10, gap: 0, top: false, bottom: false, left: false, right: false, diag: false, outline: true, dot: 20, circle: null), + Make("dot-bold", "Bold Dot", CrosshairGallery.Family.Dot, size: 10, thick: 10, gap: 0, top: false, bottom: false, left: false, right: false, diag: false, outline: true, dot: 35, circle: null), + Make("cross-classic", "Classic Cross", CrosshairGallery.Family.Cross, size: 55, thick: 15, gap: 25, top: true, bottom: true, left: true, right: true, diag: false, outline: true, dot: null, circle: null), + Make("cross-tight", "Tight Pro", CrosshairGallery.Family.Cross, size: 35, thick: 15, gap: 15, top: true, bottom: true, left: true, right: true, diag: false, outline: true, dot: null, circle: null), + Make("cross-t", "Open T", CrosshairGallery.Family.Cross, size: 50, thick: 15, gap: 20, top: false, bottom: true, left: true, right: true, diag: false, outline: true, dot: null, circle: null), + Make("cross-dot", "Cross + Dot", CrosshairGallery.Family.Cross, size: 45, thick: 15, gap: 30, top: true, bottom: true, left: true, right: true, diag: false, outline: true, dot: 18, circle: null), + Make("x-clean", "Clean X", CrosshairGallery.Family.X, size: 45, thick: 15, gap: 20, top: true, bottom: true, left: true, right: true, diag: true, outline: true, dot: null, circle: null), + Make("x-dot", "X + Dot", CrosshairGallery.Family.X, size: 40, thick: 15, gap: 25, top: true, bottom: true, left: true, right: true, diag: true, outline: true, dot: 20, circle: null), + Make("ring-clean", "Clean Ring", CrosshairGallery.Family.Ring, size: 10, thick: 15, gap: 0, top: false, bottom: false, left: false, right: false, diag: false, outline: true, dot: 18, circle: 60), + Make("ring-holo", "Holo Ring", CrosshairGallery.Family.Ring, size: 30, thick: 15, gap: 65, top: true, bottom: true, left: true, right: true, diag: false, outline: true, dot: 16, circle: 75), + Make("funny-wide", "Wide Scope", CrosshairGallery.Family.Funny, size: 90, thick: 20, gap: 45, top: true, bottom: true, left: true, right: true, diag: false, outline: true, dot: 25, circle: 90) + }; + } + + private static CrosshairGallery.GalleryItem Make( + string id, string name, CrosshairGallery.Family family, + int size, int thick, int gap, + bool top, bool bottom, bool left, bool right, + bool diag, bool outline, int? dot, int? circle) + { + CrosshairConfig c = new CrosshairConfig + { + ColourArgb = -1, + Outline = outline, + Opacity = 100, + ArmTop = top, + ArmBottom = bottom, + ArmLeft = left, + ArmRight = right, + CentreDot = dot.HasValue, + DotSizeTenths = dot, + ShowCircle = circle.HasValue, + CircleRadiusTenths = circle, + Diagonal = diag + }; + c.SetSizeTenths(size); + c.SetThicknessTenths(thick); + c.SetGapTenths(gap); + return new CrosshairGallery.GalleryItem(id, name, family, c); + } +} diff --git a/VibranceHud/Licensing/ServedData.cs b/VibranceHud/Licensing/ServedData.cs new file mode 100644 index 0000000..d2366b7 --- /dev/null +++ b/VibranceHud/Licensing/ServedData.cs @@ -0,0 +1,23 @@ +namespace VibranceHud.Licensing; + +public static class ServedData +{ + public static void Refresh() + { + Install(); + } + + internal static void Install() + { + ServedLooks.Install(); + ServedCodes.Install(); + ServedPairing.Install(); + ServedCrosshairs.Install(); + ServedNightVision.Install(); + } + + internal static void ResetForTest() + { + Install(); + } +} diff --git a/VibranceHud/Licensing/ServedLooks.cs b/VibranceHud/Licensing/ServedLooks.cs new file mode 100644 index 0000000..d009d84 --- /dev/null +++ b/VibranceHud/Licensing/ServedLooks.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace VibranceHud.Licensing; + +public static class ServedLooks +{ + private static readonly ScenePresetSet NoSet = new ScenePresetSet("", Array.Empty()); + + private static readonly GradeCurve DefaultCurve = new GradeCurve( + RegionRange: 0.25, + RegionSharpness: 2, + PointRange: 0.15, + PointSharpness: 3, + TintRange: 0.08); + + private static readonly IReadOnlyList BuiltInSets = new ScenePresetSet[] + { + new ScenePresetSet("Rust", new DisplayPreset[] + { + new DisplayPreset("Balanced", "Clean contrast and natural colour lift.", 115, 70, 102, 104, 106, 0, "balance", "rust-balanced", Highlights: -10, Shadows: 20), + new DisplayPreset("Vivid", "Stronger foliage and player separation.", 135, 85, 104, 106, 110, 4, "vivid", "rust-vivid", Highlights: -15, Shadows: 25), + new DisplayPreset("Forest", "Lifts dark tree lines and shadows.", 122, 78, 104, 108, 108, 6, "forest", "rust-forest", Highlights: -12, Shadows: 35), + new DisplayPreset("Desert", "Cuts sand glare while keeping players sharp.", 118, 72, 98, 102, 112, -8, "desert", "rust-desert", Highlights: -25, Shadows: 15), + new DisplayPreset("Snow", "Tames snow bloom and bright horizons.", 112, 68, 95, 100, 114, -6, "snow", "rust-snow", Highlights: -35, Shadows: 18), + new DisplayPreset("Black Holo", "Turns bright holo reticles dark against glare.", 116, 72, 102, 104, 108, 0, "holo", "rust-blackholo", Highlights: -15, Shadows: 20, ColourVision: ColourVisionMode.HoloBlack) + }), + new ScenePresetSet("Counter-Strike 2", new DisplayPreset[] + { + new DisplayPreset("Balanced", "Crisp visibility without blowing out walls.", 118, 75, 102, 104, 106, 0, "balance", "cs2-balanced", Highlights: -10, Shadows: 18), + new DisplayPreset("Vivid", "Punched-up player models and utility.", 140, 90, 103, 105, 110, 2, "vivid", "cs2-vivid", Highlights: -12, Shadows: 22), + new DisplayPreset("Dust", "Cuts warm sandstone haze on Mirage and Dust 2.", 124, 80, 99, 103, 110, -12, "desert", "cs2-dust", Highlights: -22, Shadows: 20), + new DisplayPreset("Concrete", "Adds pop on grey maps like Nuke and Ancient.", 128, 82, 102, 105, 112, 6, "concrete", "cs2-concrete", Highlights: -10, Shadows: 24), + new DisplayPreset("Shadows", "Opens up dark corners and tunnels.", 120, 76, 105, 110, 106, 0, "shadows", "cs2-shadows", Highlights: -15, Shadows: 40) + }), + new ScenePresetSet("Valorant", new DisplayPreset[] + { + new DisplayPreset("Balanced", "Clean contrast for abilities and outlines.", 116, 74, 101, 103, 106, 0, "balance", "valorant-balanced", Highlights: -10, Shadows: 15), + new DisplayPreset("Vivid", "High-energy colour separation.", 138, 88, 102, 104, 110, 0, "vivid", "valorant-vivid", Highlights: -12, Shadows: 18), + new DisplayPreset("Outlines", "Makes yellow and purple outlines stand out.", 132, 86, 100, 104, 114, -4, "outlines", "valorant-outlines", Highlights: -18, Shadows: 20), + new DisplayPreset("Bright Maps", "Reduces glare on Breeze and Sunset.", 118, 74, 96, 100, 112, -10, "daylight", "valorant-bright-maps", Highlights: -30, Shadows: 14), + new DisplayPreset("Shade", "Lifts shaded angles and mid sites.", 120, 78, 104, 108, 108, 4, "shadows", "valorant-shade", Highlights: -12, Shadows: 32) + }), + new ScenePresetSet("Fortnite", new DisplayPreset[] + { + new DisplayPreset("Balanced", "Even vibrance and clear builds.", 116, 72, 102, 104, 106, 0, "balance", "fortnite-balanced", Highlights: -10, Shadows: 18), + new DisplayPreset("Vivid", "Saturated colours and snappy contrast.", 136, 86, 103, 105, 110, 2, "vivid", "fortnite-vivid", Highlights: -14, Shadows: 20), + new DisplayPreset("Daylight", "Tames bright sky and storm glare.", 118, 74, 97, 101, 110, -8, "daylight", "fortnite-daylight", Highlights: -28, Shadows: 16), + new DisplayPreset("Town", "Sharpens indoor fights and cluttered POIs.", 122, 78, 103, 106, 110, 4, "urban", "fortnite-town", Highlights: -14, Shadows: 28), + new DisplayPreset("Night", "Lifts dark zones during night cycles.", 120, 76, 106, 112, 106, 0, "night", "fortnite-night", Highlights: -10, Shadows: 42) + }), + new ScenePresetSet("PUBG", new DisplayPreset[] + { + new DisplayPreset("Balanced", "Clear spotting across open terrain.", 118, 74, 102, 104, 108, 0, "balance", "pubg-balanced", Highlights: -12, Shadows: 20), + new DisplayPreset("Vivid", "Stronger colour contrast for spotting movement.", 136, 88, 103, 106, 112, 2, "vivid", "pubg-vivid", Highlights: -14, Shadows: 24), + new DisplayPreset("Desert", "Cools Miramar glare and sharpens ridges.", 120, 76, 98, 102, 112, -12, "desert", "pubg-desert", Highlights: -26, Shadows: 18), + new DisplayPreset("Jungle", "Separates players from dense Sanhok foliage.", 126, 82, 104, 108, 110, 6, "forest", "pubg-jungle", Highlights: -14, Shadows: 34), + new DisplayPreset("Urban", "Clarity in windows, compounds, and shadows.", 122, 78, 103, 106, 110, 2, "urban", "pubg-urban", Highlights: -14, Shadows: 30) + }), + new ScenePresetSet("Rainbow Six Siege", new DisplayPreset[] + { + new DisplayPreset("Balanced", "Balanced interior visibility.", 116, 74, 102, 105, 108, 0, "balance", "siege-balanced", Highlights: -12, Shadows: 22), + new DisplayPreset("Vivid", "Stronger operator and gadget contrast.", 134, 86, 103, 106, 112, 2, "vivid", "siege-vivid", Highlights: -14, Shadows: 24), + new DisplayPreset("Corners", "Brightens dark rooms and anchor spots.", 118, 76, 105, 110, 108, 0, "shadows", "siege-corners", Highlights: -12, Shadows: 42), + new DisplayPreset("Doorways", "Balances bright exteriors against dark interiors.", 120, 78, 102, 108, 110, -4, "doorways", "siege-doorways", Highlights: -26, Shadows: 36), + new DisplayPreset("Daylight", "Cuts exterior window glare.", 116, 72, 97, 102, 112, -8, "daylight", "siege-daylight", Highlights: -30, Shadows: 18) + }) + }; + + public static GradeCurve CurrentCurve => DefaultCurve; + + public static ServedSource Source => ServedSource.Served; + + public static int Generation => 1; + + public static bool OnTheirWay => false; + + public static IReadOnlyList ByGame => BuiltInSets; + + public static IReadOnlyList Games => BuiltInSets.Select((ScenePresetSet s) => s.Game).ToList(); + + public static IReadOnlyList All => BuiltInSets.SelectMany((ScenePresetSet s) => s.Presets).ToList(); + + public static ScenePresetSet ForGame(string? game) + { + if (BuiltInSets.Count == 0) + { + return NoSet; + } + return BuiltInSets.FirstOrDefault((ScenePresetSet s) => string.Equals(s.Game, game, StringComparison.OrdinalIgnoreCase)) ?? BuiltInSets[0]; + } + + internal static void Install() + { + } +} diff --git a/VibranceHud/Licensing/ServedNightVision.cs b/VibranceHud/Licensing/ServedNightVision.cs new file mode 100644 index 0000000..55149da --- /dev/null +++ b/VibranceHud/Licensing/ServedNightVision.cs @@ -0,0 +1,58 @@ +using System; + +namespace VibranceHud.Licensing; + +public static class ServedNightVision +{ + private static readonly float[] DefaultMatrix = new float[25] + { + 0.20f, 0.70f, 0.10f, 0f, 0f, + 0.35f, 1.45f, 0.25f, 0f, 0f, + 0.15f, 0.45f, 0.15f, 0f, 0f, + 0f, 0f, 0f, 1f, 0f, + -0.01f, -0.02f, -0.01f, 0f, 1f + }; + + private static readonly DarkBoostTable DefaultDarkBoost = BuildDefaultDarkBoost(); + + public static bool Live => true; + + public static float[]? Matrix => (float[])DefaultMatrix.Clone(); + + public static int Generation => 1; + + public static DarkBoostTable? DarkBoost => DefaultDarkBoost; + + internal static void Install() + { + } + + private static DarkBoostTable BuildDefaultDarkBoost() + { + ushort[] ramp = new ushort[768]; + for (int c = 0; c < 3; c++) + { + int offset = c * 256; + for (int i = 0; i < 256; i++) + { + if (i == 255) + { + ramp[offset + i] = ushort.MaxValue; + continue; + } + double x = (double)i / 255.0; + double lifted = Math.Pow(x, 0.62); + int target = (int)Math.Round(Math.Clamp(lifted, 0.0, 1.0) * 65535.0); + int maxAllowed = Math.Min(65535, (i + 120) << 8); + int minAllowed = Math.Max(0, (i - 120) << 8); + int clamped = Math.Clamp(target, minAllowed, maxAllowed); + if (i > 0 && clamped < ramp[offset + i - 1]) + { + clamped = ramp[offset + i - 1]; + } + ramp[offset + i] = (ushort)clamped; + } + } + return new DarkBoostTable((float[])DefaultMatrix.Clone(), ramp, (float[])DefaultMatrix.Clone()); + } +} diff --git a/VibranceHud/Licensing/ServedPairing.cs b/VibranceHud/Licensing/ServedPairing.cs new file mode 100644 index 0000000..f9eb7a8 --- /dev/null +++ b/VibranceHud/Licensing/ServedPairing.cs @@ -0,0 +1,18 @@ +namespace VibranceHud.Licensing; + +public static class ServedPairing +{ + private static readonly PairingFormat DefaultFormat = new PairingFormat( + Alphabet: "23456789ABCDEFGHJKLMNPQRSTUVWXYZ", + TokenLength: 26, + TokenBits: 128, + UrlTemplate: "http://{address}:{port}/?k={token}"); + + public static PairingFormat Current => DefaultFormat; + + public static ServedSource Source => ServedSource.Served; + + internal static void Install() + { + } +} diff --git a/VibranceHud/Licensing/ServedSource.cs b/VibranceHud/Licensing/ServedSource.cs new file mode 100644 index 0000000..8eafd0e --- /dev/null +++ b/VibranceHud/Licensing/ServedSource.cs @@ -0,0 +1,7 @@ +namespace VibranceHud.Licensing; + +public enum ServedSource +{ + Withheld, + Served +} diff --git a/VibranceHud/Licensing/ServedVibranceCurve.cs b/VibranceHud/Licensing/ServedVibranceCurve.cs new file mode 100644 index 0000000..f4f0d1a --- /dev/null +++ b/VibranceHud/Licensing/ServedVibranceCurve.cs @@ -0,0 +1,20 @@ +using System; + +namespace VibranceHud.Licensing; + +internal sealed class ServedVibranceCurve +{ + private readonly float[][] _points; + + internal ServedVibranceCurve(float[][] points) + { + _points = points; + } + + internal ServedVibrancePoint At(int level, bool driver, bool streaming) + { + float[] array = _points[Math.Clamp(level, 0, _points.Length - 1)]; + bool flag = driver && !streaming; + return new ServedVibrancePoint((int)array[0], array[(!flag) ? 1 : 3], array[flag ? 4 : 2]); + } +} diff --git a/VibranceHud/Licensing/ServedVibrancePoint.cs b/VibranceHud/Licensing/ServedVibrancePoint.cs new file mode 100644 index 0000000..2b004ab --- /dev/null +++ b/VibranceHud/Licensing/ServedVibrancePoint.cs @@ -0,0 +1,6 @@ +namespace VibranceHud.Licensing; + +internal readonly record struct ServedVibrancePoint(int Driver, float Red, float Chroma) +{ + internal static readonly ServedVibrancePoint Neutral = new ServedVibrancePoint(50, 1f, 1f); +} diff --git a/VibranceHud/Licensing/ShareCodeFormat.cs b/VibranceHud/Licensing/ShareCodeFormat.cs new file mode 100644 index 0000000..973a42e --- /dev/null +++ b/VibranceHud/Licensing/ShareCodeFormat.cs @@ -0,0 +1,48 @@ +using System.Collections.Generic; + +namespace VibranceHud.Licensing; + +public sealed record ShareCodeFormat(string Alphabet, string Prefix, int ChecksumModulus, int ChecksumWeightStep, int ChecksumWeightOffset, int ChecksumIndexOffset, IReadOnlyDictionary BodyLengths, int MaxVibrance, int MaxSaturation, int MinBrightness, int MaxBrightness, int MinGamma, int MaxGamma, int MinContrast, int MaxContrast, int MinTemperature, int MaxTemperature, int MinGrade, int MaxGrade) +{ + public bool Withheld + { + get + { + if (Alphabet.Length != 0 && Prefix.Length != 0) + { + return BodyLengths.Count == 0; + } + return true; + } + } + + public static readonly ShareCodeFormat Withholding = new ShareCodeFormat("", "", 32, 2, 1, 0, new Dictionary(), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + public int FieldsFor(int bodyLength) + { + if (!BodyLengths.TryGetValue(bodyLength, out var value)) + { + return 0; + } + return value; + } + + public int Checksum(string body) + { + int num = 0; + for (int i = 0; i < body.Length; i++) + { + int num2 = Alphabet.IndexOf(body[i]); + if (num2 < 0) + { + return -1; + } + num += (num2 + ChecksumIndexOffset) * (ChecksumWeightStep * i + ChecksumWeightOffset); + } + if (ChecksumModulus > 0) + { + return num % ChecksumModulus; + } + return -1; + } +} diff --git a/VibranceHud/LineIcons.cs b/VibranceHud/LineIcons.cs new file mode 100644 index 0000000..c982b4d --- /dev/null +++ b/VibranceHud/LineIcons.cs @@ -0,0 +1,86 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; + +namespace VibranceHud; + +internal static class LineIcons +{ + private static void Stroke(Graphics g, Rectangle box, Color ink, Action draw) + { + if (box.Width > 0 && box.Height > 0) + { + GraphicsState gstate = g.Save(); + g.SmoothingMode = SmoothingMode.AntiAlias; + g.PixelOffsetMode = PixelOffsetMode.Half; + g.TranslateTransform(box.X, box.Y); + g.ScaleTransform((float)box.Width / 20f, (float)box.Height / 20f); + using (Pen arg = new Pen(ink, 1.5f) + { + StartCap = LineCap.Round, + EndCap = LineCap.Round, + LineJoin = LineJoin.Round + }) + { + draw(g, arg); + } + g.Restore(gstate); + } + } + + internal static void Check(Graphics g, Rectangle box, Color ink) + { + Stroke(g, box, ink, (Graphics gr, Pen pen) => + { + gr.DrawLines(pen, new PointF[3] + { + new PointF(5f, 10.5f), + new PointF(8.2f, 13.7f), + new PointF(15f, 6.8f) + }); + }); + } + + internal static void Success(Graphics g, Rectangle box, Color ink) + { + Stroke(g, box, ink, (Graphics gr, Pen pen) => + { + gr.DrawEllipse(pen, 2.5f, 2.5f, 15f, 15f); + gr.DrawLines(pen, new PointF[3] + { + new PointF(6.6f, 10.3f), + new PointF(8.9f, 12.6f), + new PointF(13.5f, 7.8f) + }); + }); + } + + internal static void Close(Graphics g, Rectangle box, Color ink) + { + Stroke(g, box, ink, (Graphics gr, Pen pen) => + { + gr.DrawLine(pen, 5.5f, 5.5f, 14.5f, 14.5f); + gr.DrawLine(pen, 14.5f, 5.5f, 5.5f, 14.5f); + }); + } + + internal static void Info(Graphics g, Rectangle box, Color ink) + { + Stroke(g, box, ink, (Graphics gr, Pen pen) => + { + gr.DrawEllipse(pen, 2.5f, 2.5f, 15f, 15f); + gr.DrawLine(pen, 10f, 9f, 10f, 14f); + using SolidBrush brush = new SolidBrush(ink); + gr.FillEllipse(brush, 9.1f, 5.4f, 1.8f, 1.8f); + }); + } + + internal static void Plus(Graphics g, Rectangle box, Color ink) + { + Stroke(g, box, ink, (Graphics gr, Pen pen) => + { + gr.DrawLine(pen, 10f, 4f, 10f, 16f); + gr.DrawLine(pen, 4f, 10f, 16f, 10f); + }); + } +} diff --git a/VibranceHud/Links.cs b/VibranceHud/Links.cs new file mode 100644 index 0000000..c46ef61 --- /dev/null +++ b/VibranceHud/Links.cs @@ -0,0 +1,33 @@ +using System; +using System.Diagnostics; + +namespace VibranceHud; + +internal static class Links +{ + internal static bool TryOpen(string? url) + { + if (string.IsNullOrWhiteSpace(url)) + { + return false; + } + try + { + Process.Start(new ProcessStartInfo(url) + { + UseShellExecute = true + }); + return true; + } + catch (Exception ex) + { + CrashLog.Write(ex); + return false; + } + } + + internal static void Open(string url) + { + TryOpen(url); + } +} diff --git a/VibranceHud/LogoBox.cs b/VibranceHud/LogoBox.cs new file mode 100644 index 0000000..0f6a851 --- /dev/null +++ b/VibranceHud/LogoBox.cs @@ -0,0 +1,162 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.Runtime.InteropServices; +using System.Windows.Forms; + +namespace VibranceHud; + +public sealed class LogoBox : Control +{ + private Image? _image; + + private Bitmap? _scaled; + + internal const int MaxSide = 4096; + + private int _failedHeight; + + private bool _failureLogged; + + public Image? Image + { + get + { + return _image; + } + set + { + if (_image != value) + { + _image = value; + DropCache(); + _failedHeight = 0; + Invalidate(); + } + } + } + + internal Action? BeforeRenderForTest { get; set; } + + public LogoBox() + { + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + SetStyle(ControlStyles.Selectable, value: false); + TabStop = false; + } + + private void DropCache() + { + _scaled?.Dispose(); + _scaled = null; + } + + protected override void OnResize(EventArgs e) + { + base.OnResize(e); + DropCache(); + _failedHeight = 0; + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + DropCache(); + } + base.Dispose(disposing); + } + + private static bool IsGdiFailure(Exception ex) + { + if (!(ex is OutOfMemoryException) && !(ex is ExternalException) && !(ex is ArgumentException)) + { + return ex is InvalidOperationException; + } + return true; + } + + private void LogOnce(Exception ex) + { + if (!_failureLogged) + { + _failureLogged = true; + CrashLog.Write(ex); + } + } + + private Bitmap? RenderScaled(Image source, int height) + { + if (height > 4096) + { + return null; + } + Bitmap bitmap = null; + try + { + int num; + lock (BrandAssets.DrawGate) + { + if (source.Width < 1 || source.Height < 1) + { + return null; + } + num = Math.Max(1, (int)((float)height * ((float)source.Width / (float)source.Height))); + } + if (num > 4096) + { + return null; + } + BeforeRenderForTest?.Invoke(); + bitmap = new Bitmap(num, height, PixelFormat.Format32bppArgb); + using (Graphics graphics = Graphics.FromImage(bitmap)) + { + graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; + graphics.PixelOffsetMode = PixelOffsetMode.Half; + lock (BrandAssets.DrawGate) + { + graphics.DrawImage(source, new Rectangle(0, 0, num, height)); + } + } + return bitmap; + } + catch (Exception ex) when (IsGdiFailure(ex)) + { + bitmap?.Dispose(); + LogOnce(ex); + return null; + } + } + + protected override void OnPaint(PaintEventArgs e) + { + if (_image == null || Height < 1) + { + return; + } + if (_scaled == null || _scaled.Height != Height) + { + if (Height == _failedHeight) + { + return; + } + DropCache(); + _scaled = RenderScaled(_image, Height); + if (_scaled == null) + { + _failedHeight = Height; + return; + } + } + try + { + e.Graphics.DrawImageUnscaled(_scaled, 0, 0); + } + catch (Exception ex) when (IsGdiFailure(ex)) + { + LogOnce(ex); + } + } +} diff --git a/VibranceHud/LookCorrection.cs b/VibranceHud/LookCorrection.cs new file mode 100644 index 0000000..00c5f02 --- /dev/null +++ b/VibranceHud/LookCorrection.cs @@ -0,0 +1,67 @@ +using System.Collections.Generic; +using System.Linq; + +namespace VibranceHud; + +public static class LookCorrection +{ + public static void ChosenByThem(AppSettings settings, ColourVisionMode mode) + { + settings.ColourVisionFromPreset = false; + settings.UserColourVision = ColourVisionMode.Off; + settings.ColourVision = mode; + } + + public static void BroughtByALook(AppSettings settings, ColourVisionMode mode) + { + if (!settings.ColourVisionFromPreset) + { + settings.UserColourVision = ((!IsALook(settings.ColourVision)) ? settings.ColourVision : ColourVisionMode.Off); + settings.ColourVisionFromPreset = true; + } + settings.ColourVision = mode; + } + + public static ColourVisionMode SetAside(AppSettings settings) + { + if (!settings.ColourVisionFromPreset || IsALook(settings.UserColourVision)) + { + return ColourVisionMode.Off; + } + return settings.UserColourVision; + } + + public static void NormaliseOnLoad(AppSettings settings) + { + if (IsALook(settings.UserColourVision)) + { + settings.UserColourVision = ColourVisionMode.Off; + } + if (IsALook(settings.ColourVision) && !settings.ColourVisionFromPreset) + { + settings.ColourVisionFromPreset = true; + settings.UserColourVision = ColourVisionMode.Off; + } + } + + public static bool IsALook(ColourVisionMode mode) + { + return mode == ColourVisionMode.HoloBlack; + } + + public static ColourVisionMode? GiveTheirsBack(AppSettings settings) + { + if (!settings.ColourVisionFromPreset) + { + return null; + } + ColourVisionMode userColourVision = settings.UserColourVision; + ChosenByThem(settings, userColourVision); + return userColourVision; + } + + public static IReadOnlyList OfferableWithoutANote(IEnumerable presets) + { + return presets.Where((DisplayPreset p) => !LookRequirement.NeedsColourMatrix(p.ColourVision)).ToList(); + } +} diff --git a/VibranceHud/LookNote.cs b/VibranceHud/LookNote.cs new file mode 100644 index 0000000..a36b597 --- /dev/null +++ b/VibranceHud/LookNote.cs @@ -0,0 +1,20 @@ +using System.Collections.Generic; + +namespace VibranceHud; + +public readonly record struct LookNote(string Text, bool Refused) +{ + public static LookNote None => new LookNote("", Refused: false); + + public void AddTo(List applied, List notes) + { + if (!Refused) + { + applied.Add("colour"); + } + if (!string.IsNullOrEmpty(Text)) + { + notes.Add(Text); + } + } +} diff --git a/VibranceHud/LookOutcome.cs b/VibranceHud/LookOutcome.cs new file mode 100644 index 0000000..e9bd107 --- /dev/null +++ b/VibranceHud/LookOutcome.cs @@ -0,0 +1,8 @@ +namespace VibranceHud; + +public enum LookOutcome +{ + NotNeeded, + Ready, + Refused +} diff --git a/VibranceHud/LookRequirement.cs b/VibranceHud/LookRequirement.cs new file mode 100644 index 0000000..10c72ff --- /dev/null +++ b/VibranceHud/LookRequirement.cs @@ -0,0 +1,35 @@ +namespace VibranceHud; + +public static class LookRequirement +{ + public static bool NeedsColourMatrix(ColourVisionMode mode) + { + return mode != ColourVisionMode.Off; + } + + public static LookOutcome Decide(ColourVisionMode mode, bool overlayLive, bool paidLookAllowed) + { + if (NeedsColourMatrix(mode)) + { + if (!LookCorrection.IsALook(mode) || paidLookAllowed) + { + if (!overlayLive) + { + return LookOutcome.Refused; + } + return LookOutcome.Ready; + } + return LookOutcome.Refused; + } + return LookOutcome.NotNeeded; + } + + public static string WhyRefused(ColourVisionMode mode, ColourReachFacts facts, bool paidLookAllowed) + { + if (!LookCorrection.IsALook(mode) || paidLookAllowed) + { + return ColourReachStatus.For(facts).Text; + } + return "This look needs the paid colour controls, and they are off on this PC right now."; + } +} diff --git a/VibranceHud/MagOverlay.cs b/VibranceHud/MagOverlay.cs new file mode 100644 index 0000000..24cf857 --- /dev/null +++ b/VibranceHud/MagOverlay.cs @@ -0,0 +1,243 @@ +using System; +using System.Runtime.InteropServices; +using VibranceHud.Zoom; + +namespace VibranceHud; + +public sealed class MagOverlay : ISaturationOverlay, IDisplayOverlay, IDisposable +{ + private struct MAGCOLOREFFECT + { + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 25)] + public float[] transform; + } + + private static readonly float[] Identity = new float[25] + { + 1f, 0f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, + 0f, 0f, 1f, 0f, 0f, 0f, 0f, 0f, 1f, 0f, + 0f, 0f, 0f, 0f, 1f + }; + + private readonly bool _available; + + private bool _initialized; + + private readonly LastSentEffect _lastSent = new LastSentEffect(); + + private readonly Func _send = RealSend; + + private readonly Func _initialize = TakeTheRuntime; + + private readonly Func _uninitialize = GiveTheRuntime; + + internal const string NotStarted = "Windows would not start the Magnification screen effect"; + + private bool _lastSendSucceeded = true; + + public OverlayMode ActiveMode => OverlayMode.Mag; + + public bool IsAvailable => _available; + + public DxInitFailureKind LastFailure => DxInitFailureKind.None; + + public string LastFailureMessage => ""; + + public bool EffectIsLive => _available; + + public bool ScreenEffectHeld => _initialized; + + public string WhyNothingIsDrawn + { + get + { + if (!_available) + { + return "Windows would not start the Magnification screen effect"; + } + return ""; + } + } + + public bool LastApplySucceeded => _lastSendSucceeded; + + private static bool TakeTheRuntime() + { + return MagRuntime.Shared.TakeForColour(); + } + + private static bool GiveTheRuntime() + { + MagRuntime.Shared.Give(); + return true; + } + + [DllImport("Magnification.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool MagSetFullscreenColorEffect(ref MAGCOLOREFFECT pEffect); + + public MagOverlay() + : this(TakeTheRuntime, GiveTheRuntime, RealSend) + { + } + + private static bool TryStart(Func initialize) + { + try + { + return initialize(); + } + catch (DllNotFoundException) + { + return false; + } + catch (EntryPointNotFoundException) + { + return false; + } + } + + internal MagOverlay(Func initialize, Func uninitialize, Func send) + { + _initialize = initialize; + _uninitialize = uninitialize; + _send = send; + _available = TryStart(initialize); + if (_available) + { + uninitialize(); + } + } + + internal MagOverlay(Func send, bool initialized) + { + _send = send; + _initialize = () => true; + _uninitialize = () => true; + _available = initialized; + _initialized = initialized; + } + + public MagOverlay HeldForTheGoodbye() + { + if (_available && !_initialized) + { + _initialized = TryStart(_initialize); + } + return this; + } + + public void Apply(float[] matrix) + { + if (!_available) + { + SayNothingIsDrawn(); + return; + } + if (IsIdentity(matrix)) + { + Clear(); + return; + } + if (!_initialized) + { + _initialized = TryStart(_initialize); + if (!_initialized) + { + _lastSendSucceeded = false; + _lastSent.Forget(); + return; + } + } + Send(matrix); + } + + internal static bool IsIdentity(float[] matrix) + { + if (matrix == null || matrix.Length != Identity.Length) + { + return false; + } + for (int i = 0; i < Identity.Length; i++) + { + if (matrix[i] != Identity[i]) + { + return false; + } + } + return true; + } + + private void SayNothingIsDrawn() + { + ColourTrace.Refused("SCREEN EFFECT", "Windows would not start the Magnification screen effect"); + } + + public void Clear() + { + if (!_available) + { + SayNothingIsDrawn(); + return; + } + if (!_initialized) + { + _lastSendSucceeded = true; + return; + } + Send(Identity); + if (_lastSendSucceeded) + { + HandBack(); + } + } + + private void HandBack() + { + _uninitialize(); + _initialized = false; + _lastSent.Forget(); + } + + public void Forget() + { + _lastSent.Forget(); + } + + private void Send(float[] transform) + { + if (_lastSent.AlreadySent(transform)) + { + _lastSendSucceeded = true; + return; + } + _lastSendSucceeded = _send(transform); + if (_lastSendSucceeded) + { + _lastSent.Remember(transform); + } + else + { + _lastSent.Forget(); + } + } + + private static bool RealSend(float[] transform) + { + MAGCOLOREFFECT pEffect = new MAGCOLOREFFECT + { + transform = transform + }; + return MagSetFullscreenColorEffect(ref pEffect); + } + + public void Dispose() + { + if (_initialized) + { + _lastSent.Forget(); + Send(Identity); + HandBack(); + } + } +} diff --git a/VibranceHud/MainWindow.cs b/VibranceHud/MainWindow.cs new file mode 100644 index 0000000..fc36a20 --- /dev/null +++ b/VibranceHud/MainWindow.cs @@ -0,0 +1,1276 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Linq; +using System.Runtime.InteropServices; +using System.Threading.Tasks; +using System.Windows.Forms; +using VibranceHud.Audio; +using VibranceHud.Controls; +using VibranceHud.Crosshair; +using VibranceHud.Customize; +using VibranceHud.Design; +using VibranceHud.Display; +using VibranceHud.Games; +using VibranceHud.Monitors; +using VibranceHud.Pages; +using VibranceHud.Presets; +using VibranceHud.Theming; +using VibranceHud.Zoom; + +namespace VibranceHud; + +public sealed class MainWindow : Form +{ + private struct LastInputInfo + { + public uint cbSize; + public uint dwTime; + } + + private const int DwmaCornerPreference = 33; + private const int DwmcpRound = 2; + private const int WM_NCLBUTTONDOWN = 161; + private const int HTCAPTION = 2; + private const int TitleH = 40; + private const int NavW = 210; + private const int CaptionW = 46; + private const int CaptionGlyphFromRight = 22; + private const int CaptionPitch = 46; + private const int LogoH = 21; + private const int LogoW = 102; + private const int LogoX = 14; + private const int LogoY = 8; + private const int NavRailW = 76; + private const int PageLeft = 76; + private const int ShellBorder = 1; + private const int ShellInset = 1; + + private float _navOpen; + private bool _navWanted; + + private readonly VibranceEngine _engine; + private readonly AppSettings _settings; + private readonly SettingsStore _store; + private readonly Action _onThemeChanged; + + private readonly SwitchableBackdrop _field = new SwitchableBackdrop(); + + internal const int TickIntervalMs = 47; + private readonly Timer _timer; + private readonly Stopwatch _clock = Stopwatch.StartNew(); + private double _lastSeconds; + + private readonly GlowPanel _titleBar; + private readonly GlowPanel _nav; + private readonly Panel _contentHost; + private readonly GlassScrollBar _scrollBar; + private Control? _currentPage; + + private readonly VibrancePage _vibrancePage; + private readonly SettingsPage _settingsPage; + private readonly CrosshairPage _crosshairPage; + private readonly ProfilesPage _profilesPage; + private readonly CrosshairService _crosshair; + + private readonly NavButton _navVibrance; + private readonly NavButton _navCrosshair; + private readonly NavButton _navProfiles; + private readonly NavButton _navSettings; + private readonly NavButton _navMonitor; + private readonly NavButton _navPanel; + private readonly NavButton _navCustomize; + private readonly NavButton _navLibrary; + private readonly NavButton _navDarkBoost; + private readonly NavButton _navMore; + + private ContextMenuStrip? _moreMenu; + + private readonly LibraryPage _libraryPage; + private readonly DarkBoostPage _darkBoostPage; + private readonly DebouncedAction _saveDarkBoost; + private readonly MonitorHardwarePage _panelPage; + private readonly MonitorPage _monitorPage; + private readonly CustomizePage _customizePage; + private readonly GameSelection _selection; + private readonly AudioEdgeService? _audio; + private readonly ProfileEngineCoordinator? _profileCoordinator; + + [ThreadStatic] + internal static Func? WorkingAreaForTest; + + internal Func? SinceLastInputForTest; + + private bool _active = true; + + private const int WM_CHANGEUISTATE = 295; + private const int UIS_SET = 1; + private const int UISF_HIDEFOCUS = 1; + private const int UISF_HIDEACCEL = 2; + + private int _scrollTicks; + private bool _userInteracting; + private readonly List _scrollIdleTimers = new List(); + private const int RailFootH = 31; + private const int RailFootDrop = 6; + + private readonly SignalToolTip _navTips = new SignalToolTip + { + InitialDelay = 420 + }; + + private bool _cornersAreTheCompositors; + private bool _navPinned; + + private LogoBox? _logo; + private VibranceHud.Controls.CaptionButton? _closeButton; + private VibranceHud.Controls.CaptionButton? _minButton; + + private readonly List _dividers = new List(); + private Label? _navVersion; + + private double _lastScrollSeconds = double.NegativeInfinity; + private const double ScrollQuietSeconds = 0.15; + + private const int WM_ENTERSIZEMOVE = 561; + private const int WM_EXITSIZEMOVE = 562; + private bool _movingOrSizing; + + private const int WM_SYSCOMMAND = 274; + private const int SC_CLOSE = 61536; + + public Action? PhoneWindowOpener + { + set => _vibrancePage.PhoneWindowOpener = value; + } + + internal bool AnimationTimerRunning => _timer?.Enabled ?? false; + internal double AnimationClockStampSeconds => _lastSeconds; + internal bool IsActiveForTest => _active; + internal GlowPage? CurrentPageForTest => _currentPage as GlowPage; + + private NavButton[] NavOrder => new NavButton[8] + { + _navVibrance, _navLibrary, _navMonitor, _navPanel, + _navCustomize, _navCrosshair, _navProfiles, _navDarkBoost + }; + + internal string CornerRouteForTest => _cornersAreTheCompositors ? "dwm" : "square"; + internal Rectangle ContentHostBoundsForTest => _contentHost.Bounds; + + internal string ShellLayoutForTest => $"nav {_nav.Bounds} z{Controls.GetChildIndex(_nav)} host {_contentHost.Bounds} z{Controls.GetChildIndex(_contentHost)} rows {string.Join(",", from navButton in NavOrder.Where(n => n.Visible).Take(2) select navButton.Bounds.ToString())}"; + + internal int NavRailWidthForTest => _nav.Width; + internal float NavLabelOpacityForTest => NavOrder.First().LabelOpacity; + + internal IEnumerable<(string Label, string Tip)> NavTipsForTest => + NavOrder.Select(n => (n.Text, _navTips.GetToolTip(n) ?? string.Empty)); + + internal ProfilesPage ProfilesPageForTest => _profilesPage; + internal VibrancePage VibrancePageForStatus => _vibrancePage; + internal DarkBoostPage DarkBoostPageForTest => _darkBoostPage; + + internal IReadOnlyList NavLabelsForTest => + NavOrder.Select(n => n.Text).Concat(new[] { _navSettings.Text }).ToList(); + + internal IReadOnlyList RailLabelsForTest => + (from navButton in NavOrder where navButton.Visible select navButton.Text).ToList(); + + internal NavButton MoreButtonForTest => _navMore; + internal bool MoreMenuOpenForTest => _moreMenu?.Visible ?? false; + internal ContextMenuStrip? MoreMenuForTest => _moreMenu; + + internal IReadOnlyList MoreMenuItemsForTest + { + get + { + using ContextMenuStrip menu = BuildMoreMenu(); + return (from ToolStripItem i in menu.Items select i.Text ?? "").ToList(); + } + } + + internal Action? OfflineNoticeRetry { get; set; } + + internal bool HasPendingOfflineNoticeForTest => false; + + public event Action? PresetApplied; + + internal static string? DiscordCardLine(AppSettings settings) + { + if (string.IsNullOrEmpty(settings.ColourPresetGame) || string.IsNullOrEmpty(settings.ColourPresetName)) + return null; + return settings.ColourPresetGame + " · " + settings.ColourPresetName; + } + + [DllImport("user32.dll")] private static extern bool ReleaseCapture(); + [DllImport("user32.dll")] private static extern nint SendMessage(nint hWnd, int msg, int wParam, int lParam); + [DllImport("user32.dll")] private static extern nint GetForegroundWindow(); + [DllImport("user32.dll")] private static extern bool GetLastInputInfo(ref LastInputInfo info); + [DllImport("user32.dll")] private static extern bool SetForegroundWindow(nint hWnd); + [DllImport("dwmapi.dll")] private static extern int DwmSetWindowAttribute(nint hwnd, int attribute, ref int value, int size); + + public MainWindow( + VibranceEngine engine, + AppSettings settings, + SettingsStore store, + AudioEdgeService? audio, + Action onThemeChanged, + CustomThemeService? custom = null, + CrosshairService? crosshair = null, + ProfileEngineCoordinator? profileCoordinator = null, + Func? onHotkeyChanged = null, + Func? onMainHotkeyChanged = null, + GameSelection? selection = null, + Action? onLowLatencyChanged = null, + IReadOnlyList? monitorCapabilities = null, + Func? onPresetBindingsChanged = null, + Action? onMonitorColourChanged = null, + Func? onScreenshotHotkeyChanged = null, + Action? onDisplaySliderChanged = null, + CustomModeRegistrar? customModes = null, + ModeApplier? modeApply = null, + Func? onNightVisionHotkeyChanged = null, + Action? onBoostNextKeyChanged = null, + ZoomHooks? zoomHooks = null, + Action? onCompetitiveModeChanged = null) + { + MainWindow mainWindow = this; + _crosshair = crosshair ?? new CrosshairService(); + _profileCoordinator = profileCoordinator; + _engine = engine; + _settings = settings; + _store = store; + _selection = selection ?? new GameSelection(settings, store); + _audio = audio; + _onThemeChanged = onThemeChanged; + + FormBorderStyle = FormBorderStyle.None; + Text = "PlexusX"; + Icon = AppIcon.Value; + BackColor = Theme.Background; + SetStyle(ControlStyles.ResizeRedraw, true); + Tokens.Dpi = DeviceDpi; + ClientSize = DesignSize(); + LockToDesignSize(); + Opacity = Math.Clamp(settings.OpacityPercent, 50, 100) / 100.0; + Font = Fonts.Label; + DoubleBuffered = true; + KeyPreview = true; + + Rectangle bounds = WindowBounds.ClampToVisible( + new Rectangle(settings.WindowX, settings.WindowY, Width, Height), + Screen.AllScreens.Select(s => s.WorkingArea)); + if (bounds.IsEmpty) + { + StartPosition = FormStartPosition.CenterScreen; + } + else + { + StartPosition = FormStartPosition.Manual; + Bounds = bounds; + LockToDesignSize(); + } + + _field.Use(BackdropLooks.Parse(_settings.BackdropLookName)); + Glass.Style = SurfaceStyles.Parse(_settings.SurfaceStyleName); + Glass.ActiveChrome = Chromes.Parse(_settings.ChromeName); + _field.Resize(ClientSize.Width, ClientSize.Height); + AppBackground.Resize(ClientSize.Width, ClientSize.Height); + + int titleH = Tokens.Scale(40); + Tokens.Scale(210); + int navRailW = Tokens.Scale(76); + + _titleBar = new GlowPanel + { + Field = _field, + Scrim = 110, + Location = new Point(1, 1), + Size = new Size(ClientSize.Width - 2, titleH - 1), + Anchor = (AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right) + }; + _titleBar.MouseDown += DragWindow; + + LogoBox logoBox = new LogoBox + { + Image = BrandAssets.HorizontalLogo(Theme.IsLight), + Location = new Point(Tokens.Scale(14), Tokens.Scale(8)), + Size = new Size(Tokens.Scale(102), Tokens.Scale(21)) + }; + logoBox.MouseDown += DragWindow; + + int closeX = CaptionCloseX(); + VibranceHud.Controls.CaptionButton closeButton = TitleButton(VibranceHud.Controls.CaptionButton.Kind.Close, closeX); + closeButton.Click += (s, e2) => { mainWindow.SaveWindowBounds(); mainWindow.Hide(); }; + + VibranceHud.Controls.CaptionButton minButton = TitleButton(VibranceHud.Controls.CaptionButton.Kind.Minimise, closeX - Tokens.Scale(46)); + minButton.Click += (s, e2) => { mainWindow.WindowState = FormWindowState.Minimized; }; + + _titleBar.Controls.AddRange(new Control[] { logoBox, closeButton, minButton }); + _navTips.SetToolTip(minButton, "Minimise"); + _navTips.SetToolTip(closeButton, "Close"); + + _logo = logoBox; + _closeButton = closeButton; + _minButton = minButton; + Controls.Add(_titleBar); + + _vibrancePage = new VibrancePage(_engine, _settings, _store); + _vibrancePage.PresetApplied += n => { mainWindow.PresetApplied?.Invoke(n); }; + _vibrancePage.HotkeyChanged += (mask, vk) => onHotkeyChanged?.Invoke(mask, vk) ?? true; + _vibrancePage.MainHotkeyChanged += (mask, vk, en) => onMainHotkeyChanged?.Invoke(mask, vk, en) ?? true; + _vibrancePage.ScreenshotHotkeyChanged += (mask, vk) => onScreenshotHotkeyChanged?.Invoke(mask, vk) ?? true; + _vibrancePage.NightVisionHotkeyChanged += (mask, vk) => onNightVisionHotkeyChanged?.Invoke(mask, vk) ?? false; + _vibrancePage.PresetBindingsChanged += () => onPresetBindingsChanged?.Invoke() ?? true; + _vibrancePage.SliderMovedByUser += () => { onDisplaySliderChanged?.Invoke(); }; + + _saveDarkBoost = new DebouncedAction(() => { mainWindow._store.Save(mainWindow._settings); }, 300); + + _darkBoostPage = new DarkBoostPage(_engine, _settings, _saveDarkBoost.Trigger); + _darkBoostPage.KeyChanged += (mask, vk) => onNightVisionHotkeyChanged?.Invoke(mask, vk) ?? false; + _darkBoostPage.NextKeyChanged += () => { onBoostNextKeyChanged?.Invoke(); }; + + _settingsPage = new SettingsPage( + _settings, _store, _engine, _audio, + onShowDisplay: ShowVibrance, + onShowLegal: ShowLegal, + onLowLatencyChanged: onLowLatencyChanged, + installerHash: null, + onShowOnDiscordChanged: () => { mainWindow.PresetApplied?.Invoke(DiscordCardLine(mainWindow._settings)); }, + onCompetitiveModeChanged: onCompetitiveModeChanged); + + _crosshairPage = new CrosshairPage(_settings, _store, _crosshair); + + _darkBoostPage.AttachZoom( + _settings, + () => { mainWindow._store.Save(mainWindow._settings); }, + () => true, + zoomHooks ?? new ZoomHooks((m, v) => true, () => "", () => { })); + + _profilesPage = new ProfilesPage(_settings, _store, _selection, _engine, + look => { mainWindow._vibrancePage.ApplyStartingLook(look); }); + + _monitorPage = new MonitorPage(_settings, _store, _selection, customModes, modeApply); + _panelPage = new MonitorHardwarePage(_settings, _store, monitorCapabilities, null, onMonitorColourChanged, null); + + _libraryPage = new LibraryPage( + _settings, _store, + preset => mainWindow._vibrancePage.ApplyLibraryPreset(preset), + () => mainWindow._engine.DriverState == VibranceDriverState.Available, + incoming => { mainWindow._crosshairPage.ApplyLibraryCrosshair(incoming); }, + null, + null, + mode => mainWindow._monitorPage.ApplyLibraryMode(mode), + null, + Array.Empty(), + OpenPage); + + _vibrancePage.CrosshairForSharing = () => mainWindow._crosshairPage.CurrentCrosshair; + + _customizePage = new CustomizePage(_settings, _store, _onThemeChanged, RefreshBackdrop, SetWindowOpacity, custom, SetBackdropLook); + + GlowPage[] pages = + { + _vibrancePage, _settingsPage, _crosshairPage, + _profilesPage, _monitorPage, _panelPage, _customizePage, + _libraryPage, _darkBoostPage + }; + foreach (GlowPage page in pages) + AttachField(page); + + _nav = new GlowPanel + { + Field = _field, + Scrim = 0, + Location = new Point(1, titleH), + Size = new Size(navRailW - 1, ClientSize.Height - titleH - 1), + Anchor = (AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left) + }; + + _navVibrance = MakeNav("Display", 0); + _navMonitor = MakeNav("Resolution", 7); + _navPanel = MakeNav("Monitor", 9); + _navCrosshair = MakeNav("Crosshair", 5); + _navProfiles = MakeNav("Profiles", 1); + _navSettings = MakeNav("Settings", 6); + _navCustomize = MakeNav("Customize", 8); + _navLibrary = MakeNav("Library", 10); + _navDarkBoost = MakeNav("Dark Boost & Zoom", 11); + _navMore = MakeNav("More", 6); + + _navVibrance.Click += (s, e2) => mainWindow.ShowVibrance(); + _navMonitor.Click += (s, e2) => mainWindow.Select(mainWindow._navMonitor, mainWindow._monitorPage); + _navPanel.Click += (s, e2) => mainWindow.Select(mainWindow._navPanel, mainWindow._panelPage); + _navCustomize.Click += (s, e2) => mainWindow.Select(mainWindow._navCustomize, mainWindow._customizePage); + _navLibrary.Click += (s, e2) => mainWindow.Select(mainWindow._navLibrary, mainWindow._libraryPage); + _navCrosshair.Click += (s, e2) => mainWindow.Select(mainWindow._navCrosshair, mainWindow._crosshairPage); + _navProfiles.Click += (s, e2) => + { + mainWindow.Select(mainWindow._navProfiles, mainWindow._profilesPage); + mainWindow._profilesPage.Refresh(); + }; + _navSettings.Click += (s, e2) => mainWindow.Select(mainWindow._navSettings, mainWindow._settingsPage); + _navDarkBoost.Click += (s, e2) => + { + mainWindow._darkBoostPage.ReloadOffer(); + mainWindow.Select(mainWindow._navDarkBoost, mainWindow._darkBoostPage); + }; + _navMore.Click += (s, e2) => mainWindow.ToggleMoreMenu(); + + _nav.Controls.AddRange(NavOrder); + _nav.Controls.Add(_navMore); + RovingFocus.Attach( + NavOrder.Append(_navMore), + control => control is NavButton n && n.Active, + _ => false); + + Label versionLabel = _navVersion = new Label + { + Text = AppInfo.VersionText, + ForeColor = FaintestGrey(), + BackColor = Color.Transparent, + Font = Fonts.Caption, + Location = new Point(Tokens.Scale(22), _nav.Height - Tokens.Scale(30)), + AutoSize = true, + Anchor = (AnchorStyles.Bottom | AnchorStyles.Left) + }; + versionLabel.MouseDown += DragWindow; + _nav.Controls.Add(versionLabel); + Controls.Add(_nav); + + int hostLeft = Tokens.Scale(76); + _contentHost = new Panel + { + Location = new Point(hostLeft, titleH), + Size = new Size(ClientSize.Width - hostLeft - 1, ClientSize.Height - titleH - 1), + BackColor = Theme.Background, + AutoScroll = false, + Anchor = (AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right) + }; + Controls.Add(_contentHost); + + _scrollBar = new GlassScrollBar { Visible = false }; + _scrollBar.Scrolled += (s, e) => { (mainWindow._currentPage as GlowPage)?.ScrollTo(mainWindow._scrollBar.Value); }; + WheelRouter.CurrentPage = () => mainWindow._currentPage as GlowPage; + Controls.Add(_scrollBar); + _scrollBar.BringToFront(); + _nav.BringToFront(); + foreach (Panel divider in _dividers) + divider.BringToFront(); + + Resize += (s, e2) => + { + mainWindow._field.Resize(mainWindow.ClientSize.Width, mainWindow.ClientSize.Height); + AppBackground.Resize(mainWindow.ClientSize.Width, mainWindow.ClientSize.Height); + mainWindow.LayoutNav(); + }; + + _timer = new Timer { Interval = 47 }; + _timer.Tick += OnAnimationTick; + SyncAnimationClock(); + AppBackground.DriveMotionFrom(this, RepaintAnimatedSurfaces); + HookInteractionPauses(); + ClearStaleMaximizedState(); + + FormClosing += (s, e2) => { mainWindow.SaveWindowBounds(); }; + Shown += (s, e2) => { mainWindow.LayoutNav(); mainWindow.ApplyNavRail(); }; + + ShowVibrance(); + LayoutNav(); + ApplyNavRail(); + } + + private static Size DesignSize() => new Size(Tokens.Scale(1040), Tokens.Scale(680)); + + internal string CaptionTipForTest(Control button) => _navTips.GetToolTip(button) ?? string.Empty; + + private void LockToDesignSize() + { + Rectangle workingArea = WorkingAreaForTest?.Invoke() ?? Screen.FromRectangle(Bounds).WorkingArea; + Size size = WindowBounds.PinnedSize(DesignSize(), workingArea); + MaximumSize = Size.Empty; + MinimumSize = Size.Empty; + Size = size; + MinimumSize = size; + MaximumSize = size; + MaximizeBox = false; + } + + private void SaveWindowBounds() + { + if (IsDisposed) return; + Rectangle r = (WindowState == FormWindowState.Normal) ? Bounds : RestoreBounds; + if (r.Width <= 0 || r.Height <= 0) return; + _settings.WindowX = r.X; + _settings.WindowY = r.Y; + _settings.WindowWidth = r.Width; + _settings.WindowHeight = r.Height; + _settings.WindowMaximized = WindowState == FormWindowState.Maximized; + try { _store.Save(_settings); } catch { } + } + + protected override void OnDpiChanged(DpiChangedEventArgs e) + { + base.OnDpiChanged(e); + Tokens.Dpi = e.DeviceDpiNew; + Fonts.Rebuild(); + RelayoutForDpi(); + } + + private void RelayoutForDpi() + { + if (IsDisposed || !IsHandleCreated) return; + int titleH = Tokens.Scale(40); + Tokens.Scale(210); + SuspendLayout(); + LockToDesignSize(); + Tokens.Scale(76); + + _titleBar.Location = new Point(1, 1); + _titleBar.Size = new Size(ClientSize.Width - 2, titleH - 1); + PlaceTitleBarContents(); + + _nav.Location = new Point(1, titleH); + _nav.Height = ClientSize.Height - titleH - 1; + LayoutNav(); + ApplyNavRail(); + + int hostLeft = Tokens.Scale(76); + _contentHost.Location = new Point(hostLeft, titleH); + _contentHost.Size = new Size(ClientSize.Width - hostLeft - 1, ClientSize.Height - titleH - 1); + + GlowPage[] pages = + { + _vibrancePage, _settingsPage, _crosshairPage, + _profilesPage, _monitorPage, _panelPage, _customizePage, + _libraryPage, _darkBoostPage + }; + foreach (var page in pages) page?.ApplyDpi(Tokens.Dpi); + if (_currentPage is GlowPage p) AttachField(p); + + ResumeLayout(true); + Invalidate(true); + } + + public void SetBackdropLook(BackdropLook look) + { + _field.Use(look); + _field.Resize(ClientSize.Width, ClientSize.Height); + _settings.BackdropLookName = BackdropLooks.Name(look); + _store.Save(_settings); + Invalidate(true); + } + + public void SetSurfaceStyle(SurfaceStyle style) + { + Glass.Style = style; + _settings.SurfaceStyleName = SurfaceStyles.Name(style); + _store.Save(_settings); + Invalidate(true); + } + + private void AttachField(GlowPage page) + { + page.Field = _field; + page.FieldOffset = new Point(Tokens.Scale(76), Tokens.Scale(40)); + } + + private static TimeSpan SinceLastInput() + { + LastInputInfo info = new LastInputInfo { cbSize = (uint)Marshal.SizeOf() }; + if (!GetLastInputInfo(ref info)) return TimeSpan.Zero; + return TimeSpan.FromMilliseconds((uint)(Environment.TickCount64 - info.dwTime)); + } + + private void SyncAnimationClock() + { + if (_timer == null) return; + bool run = AnimationClockPolicy.ShouldRun( + Visible, WindowState == FormWindowState.Minimized, + _movingOrSizing, IsDisposed || Disposing, _active); + if (run == _timer.Enabled) return; + if (run) + { + _lastSeconds = _clock.Elapsed.TotalSeconds; + _timer.Start(); + } + else _timer.Stop(); + } + + protected override void OnDeactivate(EventArgs e) + { + base.OnDeactivate(e); + _active = false; + CloseNavRailNobodyIsHolding(); + SyncAnimationClock(); + } + + protected override void OnActivated(EventArgs e) + { + base.OnActivated(e); + _active = true; + SyncAnimationClock(); + } + + internal void NoteActivationForTest(bool active) + { + if (active) OnActivated(EventArgs.Empty); + else OnDeactivate(EventArgs.Empty); + } + + private void CloseNavRailNobodyIsHolding() + { + if (_navOpen > 0f && !_navPinned) + { + _navOpen = 0f; + ApplyNavRail(); + } + } + + protected override void OnVisibleChanged(EventArgs e) { base.OnVisibleChanged(e); SyncAnimationClock(); } + + protected override void OnShown(EventArgs e) + { + base.OnShown(e); + try { SendMessage(Handle, 295, 196609, 0); } + catch (EntryPointNotFoundException) { } + catch (DllNotFoundException) { } + } + + private void OnAnimationTick(object? sender, EventArgs e) + { + if (IsDisposed || Disposing || !IsHandleCreated) return; + double totalSeconds = _clock.Elapsed.TotalSeconds; + if (!BackgroundFramePump.InFront(this) || !Visible || WindowState == FormWindowState.Minimized) + { + CloseNavRailNobodyIsHolding(); + _lastSeconds = totalSeconds; + return; + } + + int interval = AnimationClockPolicy.IntervalFor( + SinceLastInputForTest?.Invoke() ?? SinceLastInput(), + AppBackground.HasMotion); + if (_timer.Interval != interval) _timer.Interval = interval; + + double dt = Math.Min(totalSeconds - _lastSeconds, 0.1); + UpdateNavRail((float)dt); + + if (_userInteracting || _movingOrSizing) + { + _lastSeconds = totalSeconds; + return; + } + + bool scrolling = DragTracker.AnyScrollBarDragging + || totalSeconds - _lastScrollSeconds < ScrollQuietSeconds; + if (DragTracker.AnyDragging) + { + _lastSeconds = totalSeconds; + return; + } + + _field.Update(dt); + _lastSeconds = totalSeconds; + + if (_field.Moves) + { + if (scrolling && (++_scrollTicks % 3 != 0)) + RepaintPageOnly(); + else + RepaintAnimatedSurfaces(); + } + } + + internal void RepaintAnimatedSurfaces() + { + _titleBar.Invalidate(true); + _nav.Invalidate(true); + if (_currentPage is GlowPage glowPage) glowPage.InvalidateBackdropOnly(); + else _currentPage?.Invalidate(true); + } + + internal void RepaintPageOnly() + { + if (_currentPage is GlowPage glowPage) glowPage.InvalidateBackdropOnly(); + else _currentPage?.Invalidate(true); + } + + internal void SelectLibraryCrosshairsForTest() => _libraryPage.TestSelectKind("Crosshairs"); + internal void ShowPageForTest(string nav) => OpenPage(nav); + + private void OpenPage(string nav) + { + switch (nav) + { + case "Display": _navVibrance.PerformClick(); break; + case "Crosshair": _navCrosshair.PerformClick(); break; + case "Zoom": _navDarkBoost.PerformClick(); break; + case "Profiles": _navProfiles.PerformClick(); break; + case "Settings": _navSettings.PerformClick(); break; + case "Dark Boost": + case "Dark Boost & Zoom": _navDarkBoost.PerformClick(); break; + case "Customize": _navCustomize.PerformClick(); break; + case "Library": _navLibrary.PerformClick(); break; + case "Resolution": _navMonitor.PerformClick(); break; + case "Monitor": _navPanel.PerformClick(); break; + default: throw new ArgumentOutOfRangeException(nameof(nav), nav, "no such nav page"); + } + } + + private void HookInteractionPauses() + { + MouseDown += (s, e2) => _userInteracting = true; + MouseUp += (s, e2) => _userInteracting = false; + if (Controls.Count > 0) HookScrollEvents(this); + } + + private void HookScrollEvents(Control root) + { + foreach (Control control in root.Controls) + { + if (control is Panel { AutoScroll: not false } panel) + { + Timer t = new Timer { Interval = 120 }; + _scrollIdleTimers.Add(t); + t.Tick += (s2, e2) => + { + t.Stop(); + if (!IsDisposed && !Disposing) _userInteracting = false; + }; + panel.Scroll += (s, e2) => { BeginInteraction(); t.Stop(); t.Start(); }; + } + if (control.HasChildren) HookScrollEvents(control); + } + } + + private void BeginInteraction() => _userInteracting = true; + + private NavButton MakeNav(string label, int iconKind) + { + NavButton navButton = new NavButton + { + IconKind = iconKind, + Text = label, + Size = new Size(Tokens.Scale(210), Tokens.Scale(58)) + }; + _navTips.SetToolTip(navButton, label); + return navButton; + } + + private void LayoutNav() + { + int y = Tokens.Scale(4); + int pitch = Tokens.Scale(58); + int width = _nav.Width; + int rowHeight = Tokens.Scale(58); + + NavButton[] extra = { _navMore }; + bool formVisible = Visible; + int visibleCount = NavOrder.Count(n => !formVisible || n.Visible); + + int maxHeight = _nav.Height - Tokens.Scale(31) - rowHeight - y; + if (visibleCount > 0 && visibleCount * pitch > maxHeight && maxHeight > 0) + { + pitch = Math.Max(Tokens.Scale(40), maxHeight / visibleCount); + rowHeight = pitch; + } + + foreach (NavButton n in NavOrder) + { + if (formVisible && !n.Visible) continue; + n.SetBounds(0, y, width, rowHeight); + y += pitch; + } + + int bottom = _nav.Height - Tokens.Scale(31); + for (int i = extra.Length - 1; i >= 0; i--) + { + if (formVisible && !extra[i].Visible) continue; + bottom -= rowHeight; + extra[i].SetBounds(0, Math.Max(y, bottom), width, rowHeight); + } + } + + private void UpdateNavRail(float dt) { } + + private void ApplyNavRail() + { + int railW = Tokens.Scale(76) - 1; + int fullW = Tokens.Scale(210) - 1; + int newW = railW + (int)Math.Round((float)(fullW - railW) * Eased(_navOpen)); + + KeepTheRailInFront(); + + if (_nav.Width != newW) + { + _nav.Width = newW; + LayoutNav(); + if (newW > railW) + { + _contentHost.SendToBack(); + _nav.BringToFront(); + foreach (Panel divider in _dividers) + divider.BringToFront(); + } + } + + foreach (NavButton n in NavOrder) n.LabelOpacity = 1f; + + if (_navVersion != null) + { + _navVersion.Visible = true; + _navVersion.Left = Math.Max(Tokens.Scale(3), (newW - _navVersion.Width) / 2); + _navVersion.Top = Math.Max(0, _nav.Height - _navVersion.Height - Tokens.Scale(6)); + } + } + + private void KeepTheRailInFront() + { + if (_contentHost == null || _nav == null) return; + _contentHost.SendToBack(); + _nav.BringToFront(); + _scrollBar?.BringToFront(); + } + + private static float Eased(float t) => t * t * (3f - 2f * t); + + protected override void OnHandleCreated(EventArgs e) + { + base.OnHandleCreated(e); + RoundTheCorners(); + } + + protected override void OnPaint(PaintEventArgs e) + { + base.OnPaint(e); + Graphics g = e.Graphics; + int b = Tokens.Scale(1); + if (_cornersAreTheCompositors) + { + g.SmoothingMode = SmoothingMode.AntiAlias; + g.PixelOffsetMode = PixelOffsetMode.Half; + using Pen pen = new Pen(WindowEdgeColour(), b); + using GraphicsPath path = Glass.RoundedPath( + new RectangleF(b / 2f, b / 2f, Width - b, Height - b), + Tokens.ScaleF(8f)); + g.DrawPath(pen, path); + return; + } + using SolidBrush brush = new SolidBrush(WindowEdgeColour()); + g.FillRectangle(brush, 0, 0, Width, b); + g.FillRectangle(brush, 0, Height - b, Width, b); + g.FillRectangle(brush, 0, b, b, Height - 2 * b); + g.FillRectangle(brush, Width - b, b, b, Height - 2 * b); + } + + private static Color WindowEdgeColour() => SignalTokens.Ash.WindowEdge; + + protected override void OnResize(EventArgs e) + { + base.OnResize(e); + RoundTheCorners(); + SyncAnimationClock(); + } + + private void RoundTheCorners() + { + if (!IsHandleCreated || _cornersAreTheCompositors) return; + int value = 2; + try { _cornersAreTheCompositors = DwmSetWindowAttribute(Handle, 33, ref value, 4) == 0; } + catch (DllNotFoundException) { _cornersAreTheCompositors = false; } + catch (EntryPointNotFoundException) { _cornersAreTheCompositors = false; } + if (Region != null) { Region.Dispose(); Region = null; } + } + + internal void SetNavRailForTest(bool open, bool pinned = true) + { + _navPinned = pinned; + _navOpen = open ? 1f : 0f; + _navWanted = open; + ApplyNavRail(); + _nav.Invalidate(true); + } + + internal void TickForTest(float dt) => UpdateNavRail(dt); + + private static Color FaintestGrey() + => SlateSurface.Active ? SignalTokens.Slate.Text3 : SignalTokens.Ash.Text3; + + private int CaptionCloseX() => _titleBar.Width - Tokens.Scale(22) - Tokens.Scale(46) / 2; + + private VibranceHud.Controls.CaptionButton TitleButton(VibranceHud.Controls.CaptionButton.Kind kind, int x) + => new VibranceHud.Controls.CaptionButton(kind) + { + Size = new Size(Tokens.Scale(46), Tokens.Scale(40) - 2), + Location = new Point(x, 0), + Anchor = (AnchorStyles.Top | AnchorStyles.Right) + }; + + private void PlaceTitleBarContents() + { + if (_logo == null || _closeButton == null || _minButton == null) return; + _logo.SetBounds(Tokens.Scale(14), Tokens.Scale(8), Tokens.Scale(102), Tokens.Scale(21)); + int w = Tokens.Scale(46); + int h = Tokens.Scale(40) - 2; + int closeX = CaptionCloseX(); + _closeButton.SetBounds(closeX, 0, w, h); + _minButton.SetBounds(closeX - Tokens.Scale(46), 0, w, h); + } + + private static Color RuleColor() + { + Color border = Theme.Border; + Color background = Theme.Background; + return Color.FromArgb( + (int)Math.Round(border.R * 0.4 + background.R * 0.6), + (int)Math.Round(border.G * 0.4 + background.G * 0.6), + (int)Math.Round(border.B * 0.4 + background.B * 0.6)); + } + + private void AddDivider(Point loc, Size size, AnchorStyles anchor) + { + Panel panel = new Panel { Location = loc, Size = size, BackColor = RuleColor(), Anchor = anchor }; + Controls.Add(panel); + panel.BringToFront(); + _dividers.Add(panel); + } + + private void SetWindowOpacity(int percent) => Opacity = Math.Clamp(percent, 50, 100) / 100.0; + + private void DragWindow(object? sender, MouseEventArgs e) + { + if (e.Button == MouseButtons.Left) + { + ReleaseCapture(); + SendMessage(Handle, 161, 2, 0); + } + } + + private void RefreshBackdrop() + { + Invalidate(true); + AppBackground.Resize(ClientSize.Width, ClientSize.Height); + } + + private void ShowVibrance() + { + Select(_navVibrance, _vibrancePage); + _vibrancePage.Refresh(); + } + + private void ShowLocked(string feature) { } + + private void ShowLegal() + { + LegalPage legalPage = new LegalPage(() => { Select(_navSettings, _settingsPage); }); + AttachField(legalPage); + SetContent(legalPage); + } + + private void SyncScrollBar() + { + if (IsDisposed || _currentPage is not GlowPage glowPage) + { + _scrollBar.Visible = false; + return; + } + _scrollBar.Maximum = glowPage.ScrollExtent; + _scrollBar.Viewport = glowPage.ScrollViewport; + _scrollBar.Value = glowPage.ScrollOffset; + _scrollBar.Visible = _scrollBar.Needed; + if (_scrollBar.Needed) + { + int w = Tokens.Scale(8); + int pad = Tokens.Scale(4); + _scrollBar.SetBounds( + _contentHost.Right - w - pad, + _contentHost.Top + pad, + w, + Math.Max(1, _contentHost.Height - pad * 2)); + _scrollBar.BringToFront(); + } + } + + private void Select(NavButton button, Control page) + { + SetActive(button); + SetContent(page); + } + + private void SetActive(NavButton active) + { + foreach (NavButton obj in NavOrder) obj.Active = obj == active; + _navSettings.Active = active == _navSettings; + _navMore.Active = active == _navSettings; + } + + private ContextMenuStrip BuildMoreMenu() + { + ContextMenuStrip menu = SignalMenu.ActionMenu(square: true); + menu.Items.Add("Settings", null, (s, e) => { _navSettings.PerformClick(); }) + .Tag = new SignalMenu.RowArt(SignalMenu.DrawSettingsIcon, _navSettings.Active); + return menu; + } + + private void ToggleMoreMenu() + { + ContextMenuStrip? menu = _moreMenu; + if (menu != null && menu.Visible) { _moreMenu.Close(); return; } + _moreMenu?.Dispose(); + ContextMenuStrip built = _moreMenu = BuildMoreMenu(); + int height = built.Height; + built.Show(_navMore, new Point(_navMore.Width + Tokens.Scale(4), _navMore.Height - height)); + } + + internal void CloseMoreMenuForTest() => _moreMenu?.Close(); + + internal void PressMoreMenuItemForTest(string text) + { + using ContextMenuStrip menu = BuildMoreMenu(); + menu.Items.Cast().Single(i => i.Text == text).PerformClick(); + } + + private void SetContent(Control page) + { + Control currentPage = _currentPage; + if (currentPage is GlowPage glowPage) + glowPage.ScrollStateChanged -= OnPageScrollStateChanged; + + bool hadHandle = _contentHost.IsHandleCreated; + if (hadHandle) SendMessage(_contentHost.Handle, 11, 0, 0); + try + { + _contentHost.SuspendLayout(); + _contentHost.Controls.Clear(); + page.Dock = DockStyle.Fill; + if (page is ScrollableControl scrollableControl) + scrollableControl.AutoScrollPosition = Point.Empty; + _contentHost.Controls.Add(page); + _contentHost.ResumeLayout(); + } + finally + { + if (hadHandle) + { + SendMessage(_contentHost.Handle, 11, 1, 0); + _contentHost.Refresh(); + } + } + + _currentPage = page; + if (page is GlowPage glowPage2) + { + glowPage2.ScrollStateChanged -= OnPageScrollStateChanged; + glowPage2.ScrollStateChanged += OnPageScrollStateChanged; + } + SyncScrollBar(); + KeepTheRailInFront(); + + if (currentPage != null && currentPage != page + && currentPage != _vibrancePage && currentPage != _settingsPage + && currentPage != _crosshairPage + && currentPage != _profilesPage && currentPage != _monitorPage + && currentPage != _panelPage && currentPage != _customizePage + && currentPage != _libraryPage && currentPage != _darkBoostPage) + { + currentPage.Dispose(); + } + } + + private void OnPageScrollStateChanged(object? sender, EventArgs e) + { + _lastScrollSeconds = _clock.Elapsed.TotalSeconds; + SyncScrollBar(); + } + + public void ShowAndFocus() + { + Show(); + if (WindowState == FormWindowState.Minimized) + WindowState = FormWindowState.Normal; + BringToFront(); + try { SetForegroundWindow(Handle); } catch { } + Activate(); + } + + internal void HandPendingNoticesTo(MainWindow next) + { + } + + internal void ApplySharedSetup(string code) + { + ShowAndFocus(); + if (!ConfigCode.TryDecode(code, out ConfigCode.Parts parts)) + { + GlassDialog.Show(this, "PlexusX", "That link did not carry a setup this version understands. Ask whoever shared it to copy the code again."); + return; + } + ConfigLibraryEntry entry = new ConfigLibraryEntry("Shared setup", "", "", "", parts); + string body = "A setup from the website wants to change:\n\n " + string.Join("\n ", ConfigCode.Describe(parts)) + "\n\nApply it?"; + if (GlassDialog.Show(this, "Use this setup?", body, GlassDialogButtons.YesNo, GlassDialogTone.Info, "Use setup") != DialogResult.Yes) + return; + + List applied = new(); + List notes = new(); + DisplayPreset look = entry.Look; + if (look != null) _vibrancePage.ApplyLibraryPreset(look).AddTo(applied, notes); + CrosshairConfig crosshair = entry.Crosshair; + if (crosshair != null) + { + _crosshairPage.ApplyLibraryCrosshair(crosshair); + applied.Add("crosshair"); + } + MonitorCode? mode = entry.Mode; + if (mode.HasValue) + { + MonitorCode m = mode.GetValueOrDefault(); + notes.Add(_monitorPage.ApplyLibraryMode(m)); + } + List messages = new(); + if (applied.Count > 0) messages.Add(string.Join(" and ", applied) + " applied."); + messages.AddRange(notes); + if (messages.Count > 0) GlassDialog.Show(this, "PlexusX", string.Join(" ", messages)); + } + + internal static bool IsTheUsersClose(int msg, nint wParam) + => msg == 274 && ((ulong)wParam & 0xFFF0uL) == 61536; + + protected override void WndProc(ref Message m) + { + if (m.Msg == SingleInstance.ShowWindowMessage && SingleInstance.ShowWindowMessage != 0) + ShowAndFocus(); + + if (IsTheUsersClose(m.Msg, m.WParam)) + { + SaveWindowBounds(); + Hide(); + return; + } + + if (m.Msg == WM_ENTERSIZEMOVE) + { + _movingOrSizing = true; + SyncAnimationClock(); + } + else if (m.Msg == WM_EXITSIZEMOVE) + { + _movingOrSizing = false; + SyncAnimationClock(); + } + + base.WndProc(ref m); + } + + public static int NextNavIndex(int current, int count, bool forward) + { + if (count <= 0) return 0; + return ((current + (forward ? 1 : -1)) % count + count) % count; + } + + private Control? FocusedControl() + { + Control? activeControl; + for (activeControl = ActiveControl; + activeControl is ContainerControl { ActiveControl: not null } containerControl; + activeControl = containerControl.ActiveControl) { } + return activeControl; + } + + protected override bool ProcessCmdKey(ref Message msg, Keys keyData) + { + if (keyData != Keys.Escape && FocusedControl() is HotkeyPicker { IsCapturing: not false }) + return base.ProcessCmdKey(ref msg, keyData); + + switch (keyData) + { + case Keys.Escape: + if (FocusedControl() is HotkeyPicker { IsCapturing: not false } picker) + { + picker.CancelCapture(); + return true; + } + SaveWindowBounds(); + Hide(); + return true; + case Keys.Tab | Keys.Control: + StepNav(true); + return true; + case Keys.Tab | Keys.Shift | Keys.Control: + StepNav(false); + return true; + default: + if ((keyData & Keys.Control) == Keys.Control) + { + int idx = (int)((keyData & Keys.KeyCode) - 49); + if (idx >= 0 && idx < 9) + { + List visible = VisibleNavButtons(); + if (idx < visible.Count) + { + visible[idx].PerformClick(); + return true; + } + } + } + return base.ProcessCmdKey(ref msg, keyData); + } + } + + private List VisibleNavButtons() + { + List list = NavOrder.Where(n => n.Visible).ToList(); + list.Add(_navSettings); + return list; + } + + private void StepNav(bool forward) + { + List list = VisibleNavButtons(); + if (list.Count == 0) return; + int idx = list.FindIndex(n => n.Active); + if (idx < 0) idx = 0; + list[NextNavIndex(idx, list.Count, forward)].PerformClick(); + } + + private void ClearStaleMaximizedState() + { + if (!_settings.WindowMaximized) return; + _settings.WindowMaximized = false; + WindowState = FormWindowState.Normal; + try { _store.Save(_settings); } catch { } + } + + public void OnEngineChanged() + { + _vibrancePage.Refresh(); + _profilesPage.Refresh(); + } + + internal LookNote ApplyScenePresetByName(string name) + { + return _vibrancePage.ApplyPresetByBindingName(name); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _timer.Stop(); + _timer.Tick -= OnAnimationTick; + _timer.Dispose(); + _navTips.Dispose(); + _moreMenu?.Dispose(); + _navSettings.Dispose(); + foreach (Timer scrollIdleTimer in _scrollIdleTimers) + { + scrollIdleTimer.Stop(); + scrollIdleTimer.Dispose(); + } + _scrollIdleTimers.Clear(); + } + base.Dispose(disposing); + } +} \ No newline at end of file diff --git a/VibranceHud/MonitorColourAdjust.cs b/VibranceHud/MonitorColourAdjust.cs new file mode 100644 index 0000000..5452832 --- /dev/null +++ b/VibranceHud/MonitorColourAdjust.cs @@ -0,0 +1,58 @@ +using System; + +namespace VibranceHud; + +public static class MonitorColourAdjust +{ + public const int NeutralGammaPercent = 100; + + public const int NeutralWarmthPercent = 0; + + public const int MinGammaPercent = 50; + + public const int MaxGammaPercent = 150; + + public const int MaxWarmthPercent = 100; + + public static bool IsNeutral(int gammaPercent, int warmthPercent) + { + if (gammaPercent == 100) + { + return warmthPercent == 0; + } + return false; + } + + public static ushort[] Compose(ushort[] baseRamp, int gammaPercent, int warmthPercent) + { + if (baseRamp.Length != 768) + { + throw new ArgumentException($"expected a {768}-entry ramp", "baseRamp"); + } + gammaPercent = Math.Clamp(gammaPercent, 50, 150); + warmthPercent = Math.Clamp(warmthPercent, 0, 100); + if (IsNeutral(gammaPercent, warmthPercent)) + { + return baseRamp; + } + double y = 100.0 / (double)gammaPercent; + double num = (double)warmthPercent / 100.0; + double[] array = new double[3] + { + 1.0, + 1.0 - 0.12 * num, + 1.0 - 0.38 * num + }; + ushort[] array2 = new ushort[baseRamp.Length]; + for (int i = 0; i < 3; i++) + { + for (int j = 0; j < 256; j++) + { + double x = (double)(int)baseRamp[i * 256 + j] / 65535.0; + x = Math.Pow(x, y) * array[i]; + array2[i * 256 + j] = (ushort)Math.Clamp(Math.Round(x * 65535.0), 0.0, 65535.0); + } + } + return array2; + } +} diff --git a/VibranceHud/MonitorColourSetting.cs b/VibranceHud/MonitorColourSetting.cs new file mode 100644 index 0000000..ae5b34d --- /dev/null +++ b/VibranceHud/MonitorColourSetting.cs @@ -0,0 +1,10 @@ +namespace VibranceHud; + +public sealed class MonitorColourSetting +{ + public string DeviceName { get; set; } = ""; + + public int GammaPercent { get; set; } = 100; + + public int WarmthPercent { get; set; } +} diff --git a/VibranceHud/MonitorDescriptor.cs b/VibranceHud/MonitorDescriptor.cs new file mode 100644 index 0000000..a8f9b5a --- /dev/null +++ b/VibranceHud/MonitorDescriptor.cs @@ -0,0 +1,3 @@ +namespace VibranceHud; + +public readonly record struct MonitorDescriptor(string DeviceName, string FriendlyName, bool IsPrimary); diff --git a/VibranceHud/MonitorRule.cs b/VibranceHud/MonitorRule.cs new file mode 100644 index 0000000..85210de --- /dev/null +++ b/VibranceHud/MonitorRule.cs @@ -0,0 +1,31 @@ +using System.Text.Json.Serialization; + +namespace VibranceHud; + +public sealed class MonitorRule +{ + [JsonPropertyName("gameId")] + public string GameId { get; set; } = ""; + + [JsonPropertyName("width")] + public int Width { get; set; } + + [JsonPropertyName("height")] + public int Height { get; set; } + + [JsonPropertyName("device")] + public string Device { get; set; } = ""; + + [JsonIgnore] + public bool IsSet + { + get + { + if (Width > 0) + { + return Height > 0; + } + return false; + } + } +} diff --git a/VibranceHud/MonitorRules.cs b/VibranceHud/MonitorRules.cs new file mode 100644 index 0000000..3cbd507 --- /dev/null +++ b/VibranceHud/MonitorRules.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace VibranceHud; + +public static class MonitorRules +{ + public static MonitorRule? For(IEnumerable rules, string? gameId) + { + if (string.IsNullOrWhiteSpace(gameId)) + { + return null; + } + MonitorRule monitorRule = rules?.FirstOrDefault((MonitorRule r) => string.Equals(r.GameId, gameId, StringComparison.OrdinalIgnoreCase)); + if (monitorRule == null || !monitorRule.IsSet) + { + return null; + } + return monitorRule; + } + + public static List Set(IEnumerable rules, string gameId, int width, int height, string device = "") + { + List list = rules?.ToList() ?? new List(); + list.RemoveAll((MonitorRule r) => string.Equals(r.GameId, gameId, StringComparison.OrdinalIgnoreCase)); + if (width > 0 && height > 0) + { + list.Add(new MonitorRule + { + GameId = gameId, + Width = width, + Height = height, + Device = (device ?? "") + }); + } + return list; + } + + public static List Clear(IEnumerable rules, string gameId) + { + return Set(rules, gameId, 0, 0); + } +} diff --git a/VibranceHud/Monitors/ColourMonitor.cs b/VibranceHud/Monitors/ColourMonitor.cs new file mode 100644 index 0000000..1045733 --- /dev/null +++ b/VibranceHud/Monitors/ColourMonitor.cs @@ -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); diff --git a/VibranceHud/Monitors/ColourMonitorGroup.cs b/VibranceHud/Monitors/ColourMonitorGroup.cs new file mode 100644 index 0000000..40be269 --- /dev/null +++ b/VibranceHud/Monitors/ColourMonitorGroup.cs @@ -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; +} diff --git a/VibranceHud/Monitors/ColourMonitorInventory.cs b/VibranceHud/Monitors/ColourMonitorInventory.cs new file mode 100644 index 0000000..4e64a01 --- /dev/null +++ b/VibranceHud/Monitors/ColourMonitorInventory.cs @@ -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() + }; + if (!EnumDisplayDevices(deviceName, 0u, ref monitor, 1u)) + { + return ""; + } + return monitor.Id ?? ""; + } + + internal static IReadOnlyList Read() + { + Screen[] allScreens = Screen.AllScreens; + List list = new List(); + 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(), + Adapter = p[j].Source.Adapter, + Id = p[j].Source.Id + } + }; + TargetName name = new TargetName + { + Header = new Header + { + Type = 2u, + Size = (uint)Marshal.SizeOf(), + 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; + } +} diff --git a/VibranceHud/Monitors/Dxva2MonitorWriter.cs b/VibranceHud/Monitors/Dxva2MonitorWriter.cs new file mode 100644 index 0000000..12204c8 --- /dev/null +++ b/VibranceHud/Monitors/Dxva2MonitorWriter.cs @@ -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); + } +} diff --git a/VibranceHud/Monitors/IMonitorIdentifyWindow.cs b/VibranceHud/Monitors/IMonitorIdentifyWindow.cs new file mode 100644 index 0000000..187bb58 --- /dev/null +++ b/VibranceHud/Monitors/IMonitorIdentifyWindow.cs @@ -0,0 +1,8 @@ +using System; + +namespace VibranceHud.Monitors; + +public interface IMonitorIdentifyWindow : IDisposable +{ + void ShowNumber(); +} diff --git a/VibranceHud/Monitors/IMonitorWriter.cs b/VibranceHud/Monitors/IMonitorWriter.cs new file mode 100644 index 0000000..9b15948 --- /dev/null +++ b/VibranceHud/Monitors/IMonitorWriter.cs @@ -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); +} diff --git a/VibranceHud/Monitors/MonitorCapability.cs b/VibranceHud/Monitors/MonitorCapability.cs new file mode 100644 index 0000000..d84d802 --- /dev/null +++ b/VibranceHud/Monitors/MonitorCapability.cs @@ -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 InputSourceValues { get; init; } = Array.Empty(); + + public bool SupportsInputSource => InputSourceValues.Count > 0; + + public byte? CurrentInputSource { get; init; } + + public int Index { get; init; } +} diff --git a/VibranceHud/Monitors/MonitorControl.cs b/VibranceHud/Monitors/MonitorControl.cs new file mode 100644 index 0000000..9095aad --- /dev/null +++ b/VibranceHud/Monitors/MonitorControl.cs @@ -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 action) + { + try + { + List handles = new List(); + 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 hMonitors, Func open, Action release, Func 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; + } +} diff --git a/VibranceHud/Monitors/MonitorDevices.cs b/VibranceHud/Monitors/MonitorDevices.cs new file mode 100644 index 0000000..43b831d --- /dev/null +++ b/VibranceHud/Monitors/MonitorDevices.cs @@ -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 names = new List(); + 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() + }; + names.Add(GetMonitorInfo(hMonitor, ref info) ? info.szDevice : ""); + return true; + } + } +} diff --git a/VibranceHud/Monitors/MonitorIdentifier.cs b/VibranceHud/Monitors/MonitorIdentifier.cs new file mode 100644 index 0000000..5d03444 --- /dev/null +++ b/VibranceHud/Monitors/MonitorIdentifier.cs @@ -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 _factory; + + private readonly Action? _expire; + + private readonly List _windows = new List(); + + private Timer? _timer; + + private int _generation; + + private bool _disposed; + + public MonitorIdentifier(Func? factory = null, Action? expire = null) + { + _factory = factory ?? ((Func)((ColourMonitorGroup g, int n) => new MonitorNumberWindow(g.Bounds, n))); + _expire = expire; + } + + public void Identify(IReadOnlyList 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(); + } +} diff --git a/VibranceHud/Monitors/MonitorPanicRestore.cs b/VibranceHud/Monitors/MonitorPanicRestore.cs new file mode 100644 index 0000000..105357c --- /dev/null +++ b/VibranceHud/Monitors/MonitorPanicRestore.cs @@ -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 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 KeysFor(IEnumerable caps, Func 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 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 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> probe, Action gammaLinear, Action driverBaseline, Func? deviceName = null, int? onlyMonitorIndex = null, Action? runOnUi = null, bool userInitiated = false) + { + if (deviceName == null) + { + deviceName = MonitorDevices.DeviceNameForIndex; + } + Action action = runOnUi ?? ((Action)((Action a) => + { + a(); + })); + int num = 0; + int num2 = 0; + int num3 = 0; + try + { + IReadOnlyList readOnlyList; + try + { + readOnlyList = probe() ?? Array.Empty(); + } + catch + { + readOnlyList = Array.Empty(); + } + IReadOnlyList 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); + } +} diff --git a/VibranceHud/Monitors/MonitorProbe.cs b/VibranceHud/Monitors/MonitorProbe.cs new file mode 100644 index 0000000..9bd6705 --- /dev/null +++ b/VibranceHud/Monitors/MonitorProbe.cs @@ -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 Probe() + { + List list = new List(); + try + { + List handles = new List(); + 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 NumberThem(IReadOnlyList hMonitors, Func> describe) + { + List list = new List(); + foreach (nint hMonitor in hMonitors) + { + foreach (MonitorCapability item in describe(hMonitor)) + { + list.Add(item with + { + Index = list.Count + }); + } + } + return list; + } + + private static List Describe(nint hMonitor) + { + List list = new List(); + 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 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 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 TryReadInputSourceValues(nint h) + { + try + { + uint length = 0u; + if (!GetCapabilitiesStringLength(h, ref length) || length == 0) + { + return Array.Empty(); + } + byte[] array = new byte[length]; + if (!CapabilitiesRequestAndCapabilitiesReply(h, array, length)) + { + return Array.Empty(); + } + int num = Array.IndexOf(array, (byte)0); + return ParseFeatureValues(Encoding.ASCII.GetString(array, 0, (num < 0) ? array.Length : num), 96); + } + catch + { + return Array.Empty(); + } + } + + internal static IReadOnlyList 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(); + } + 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(); + } + List list = new List(); + 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 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); + } +} diff --git a/VibranceHud/Monitors/MonitorSelection.cs b/VibranceHud/Monitors/MonitorSelection.cs new file mode 100644 index 0000000..d193cfe --- /dev/null +++ b/VibranceHud/Monitors/MonitorSelection.cs @@ -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> _inventory; + + private HashSet _ambiguous = new HashSet(StringComparer.OrdinalIgnoreCase); + + private const string DeviceKeyPrefix = "device:"; + + private const string StableOptOutPrefix = "monitor:"; + + private const string InventoryPrefix = "inventory:"; + + public IReadOnlyList Groups { get; private set; } = Array.Empty(); + + 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> inventory) + { + _settings = settings; + _inventory = inventory; + Refresh(); + } + + public void Refresh() + { + IReadOnlyList source; + try + { + source = _inventory(); + } + catch + { + source = Array.Empty(); + } + _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 untickedDeviceKeys = _settings.UntickedDeviceKeys; + if (untickedDeviceKeys == null || untickedDeviceKeys.Count <= 0) + { + return; + } + HashSet hashSet = new HashSet(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 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 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 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 hashSet = new HashSet(_settings.UntickedDeviceKeys ?? new List(), 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 selectedMonitorIds = _settings.SelectedMonitorIds; + HashSet hashSet2 = new HashSet(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(); + } +} diff --git a/VibranceHud/Monitors/PanelRange.cs b/VibranceHud/Monitors/PanelRange.cs new file mode 100644 index 0000000..357017c --- /dev/null +++ b/VibranceHud/Monitors/PanelRange.cs @@ -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); + } +} diff --git a/VibranceHud/Monitors/PanicResult.cs b/VibranceHud/Monitors/PanicResult.cs new file mode 100644 index 0000000..9da8134 --- /dev/null +++ b/VibranceHud/Monitors/PanicResult.cs @@ -0,0 +1,3 @@ +namespace VibranceHud.Monitors; + +public sealed record PanicResult(int PanelsRestored, int PanelsReset, int PanelsRefused, bool GammaLinear, bool DriverBack); diff --git a/VibranceHud/Monitors/SelectedVibranceController.cs b/VibranceHud/Monitors/SelectedVibranceController.cs new file mode 100644 index 0000000..5e83618 --- /dev/null +++ b/VibranceHud/Monitors/SelectedVibranceController.cs @@ -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("", 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 dictionary = (appSettings.OwnedMonitorVibrance = new Dictionary(StringComparer.OrdinalIgnoreCase)); + } + appSettings = settings; + if (appSettings.OwnedMonitorVibranceLastWritten == null) + { + Dictionary dictionary = (appSettings.OwnedMonitorVibranceLastWritten = new Dictionary(StringComparer.OrdinalIgnoreCase)); + } + } + + public bool EveryDisplayIsAt(int level) + { + return ReadEveryDisplayLevel().All((KeyValuePair x) => x.Value == level); + } + + public IReadOnlyList> ReadEveryDisplayLevel() + { + return (from x in _driver.ReadEveryDisplayLevel() + where _selection.IncludesDevice(x.Key) + select x).ToArray(); + } + + public void SetLevel(int level) + { + ReleaseExcluded(); + foreach (KeyValuePair 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 keyValuePair = _driver.ReadEveryDisplayLevel().FirstOrDefault((KeyValuePair 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 release) + { + KeyValuePair[] 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> source = _driver.ReadEveryDisplayLevel(); + KeyValuePair keyValuePair2 = source.FirstOrDefault((KeyValuePair 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 keyValuePair3 = _driver.ReadEveryDisplayLevel().FirstOrDefault((KeyValuePair x) => string.Equals(x.Key, device, StringComparison.OrdinalIgnoreCase)); + if (keyValuePair3.Key != null && keyValuePair3.Value == num2) + { + goto IL_0124; + } + } + continue; + IL_0124: + KeyValuePair keyValuePair4 = source.FirstOrDefault((KeyValuePair 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; + } +} diff --git a/VibranceHud/MultiMonitorGammaRamp.cs b/VibranceHud/MultiMonitorGammaRamp.cs new file mode 100644 index 0000000..ba1fb1a --- /dev/null +++ b/VibranceHud/MultiMonitorGammaRamp.cs @@ -0,0 +1,553 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using VibranceHud.Monitors; + +namespace VibranceHud; + +public sealed class MultiMonitorGammaRamp : IGammaRamp, IDisposable +{ + [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 DISPLAY_DEVICE_ATTACHED_TO_DESKTOP = 1; + + private const int DISPLAY_DEVICE_MIRRORING_DRIVER = 8; + + private readonly Func> _enumerateDevices; + + private readonly Func _setRampOnDevice; + + private readonly Func _readRampOnDevice; + + private readonly Func _adjustmentFor; + + private ushort[]? _lastBase; + + private readonly Dictionary _theirOwn = new Dictionary(); + + private readonly Dictionary _softened = new Dictionary(); + + private readonly Dictionary _refusedEveryStep = new Dictionary(); + + private readonly HashSet _coloured = new HashSet(); + + private bool _saidGoodbye; + + internal static readonly double[] SofteningSteps = new double[3] { 0.5, 0.25, 0.125 }; + + internal const string HandedBackAlready = "PlexusX has already handed the screen back to Windows"; + + private bool _lastBaseAllOrNothing; + + internal const string AllOrNothingRefused = "Windows refused the Dark Boost ramp on a display"; + + internal const string AllOrNothingNotHeld = "a display did not hold the Dark Boost ramp it was given"; + + internal const string AllOrNothingNoDisplay = "no display to hold the Dark Boost ramp"; + + internal const int MaxDip = 255; + + public MonitorSelection? Selection { get; set; } + + public Action? BeforeDeviceColour { get; set; } + + public Action? DeviceReleased { get; set; } + + public bool LastApplyFailed { get; private set; } + + public int DeviceWrites { get; private set; } + + public string LastRefusal { get; private set; } = ""; + + public int DisplaysThatRefusedTheLastWrite { get; private set; } + + public int DisplaysThatWereSoftened { get; private set; } + + public GammaDelivery LastDelivery { get; private set; } = GammaDelivery.Full; + + public Action? BeforeFirstColour { get; set; } + + [DllImport("user32.dll", CharSet = CharSet.Unicode)] + private static extern bool EnumDisplayDevices(string? lpDevice, uint iDevNum, ref DISPLAY_DEVICE lpDisplayDevice, uint dwFlags); + + [DllImport("gdi32.dll", CharSet = CharSet.Unicode)] + private static extern nint CreateDC(string? lpszDriver, string lpszDevice, string? lpszOutput, nint lpInitData); + + [DllImport("gdi32.dll")] + private static extern bool DeleteDC(nint hdc); + + [DllImport("gdi32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool SetDeviceGammaRamp(nint hDC, ushort[] ramp); + + [DllImport("gdi32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetDeviceGammaRamp(nint hDC, ushort[] ramp); + + public MultiMonitorGammaRamp(Func adjustmentFor) + : this(Devices, SetRampOn, adjustmentFor, ReadRampOn) + { + } + + internal MultiMonitorGammaRamp(Func> enumerateDevices, Func setRampOnDevice, Func adjustmentFor, Func? readRampOnDevice = null) + { + _enumerateDevices = enumerateDevices; + _setRampOnDevice = setRampOnDevice; + _adjustmentFor = adjustmentFor; + _readRampOnDevice = readRampOnDevice ?? ((Func)((string _) => (ushort[]?)null)); + } + + public void Apply(ushort[] ramp) + { + Deliver(ramp, allOrNothing: false); + } + + public string? ApplyAllOrNothing(ushort[] ramp) + { + return Deliver(ramp, allOrNothing: true); + } + + private string? Deliver(ushort[]? ramp, bool allOrNothing) + { + if (_saidGoodbye) + { + LastRefusal = "PlexusX has already handed the screen back to Windows"; + ColourTrace.Refused("GAMMA RAMP", "PlexusX has already handed the screen back to Windows"); + return "PlexusX has already handed the screen back to Windows"; + } + LastRefusal = ""; + DisplaysThatRefusedTheLastWrite = 0; + DisplaysThatWereSoftened = 0; + allOrNothing &= ramp != null; + _lastBase = ramp; + _lastBaseAllOrNothing = allOrNothing; + string text = null; + string step = ""; + bool flag = false; + bool flag2 = false; + foreach (string item3 in _enumerateDevices()) + { + string text2 = ((Selection == null) ? item3 : Selection.KeyFor(item3)); + if (Selection != null && !Selection.IncludesDevice(item3)) + { + ReleaseSelectedDevice(item3, text2); + continue; + } + flag = true; + (int, int) tuple = _adjustmentFor(item3); + int item = tuple.Item1; + int item2 = tuple.Item2; + ushort[] array = _readRampOnDevice(item3); + ushort[] array2 = TheirOwn(text2, array); + bool flag3 = _coloured.Contains(text2); + ushort[] array3; + bool flag4; + if (ramp == null && NoAdjustment(item, item2)) + { + if (Selection != null && !flag3) + { + flag2 = true; + continue; + } + if (!flag3 && array != null && LooksLikeARamp(array)) + { + flag2 = true; + continue; + } + array3 = ((flag3 && array2 != null) ? array2 : GammaCurve.Identity()); + flag4 = true; + } + else + { + if (Selection != null && array2 == null) + { + DisplaysThatRefusedTheLastWrite++; + if (allOrNothing) + { + text = "Windows refused the Dark Boost ramp on a display"; + break; + } + continue; + } + array3 = MonitorColourAdjust.Compose(ramp ?? GammaCurve.Identity(), item, item2); + flag4 = false; + if (!_coloured.Contains(text2)) + { + if (array2 != null) + { + BeforeDeviceColour?.Invoke(text2, (ushort[])array2.Clone()); + } + _coloured.Add(text2); + BeforeFirstColour?.Invoke(); + } + } + if (array != null && SameRamp(array, array3)) + { + if (flag4) + { + ReleaseRecord(text2); + } + flag2 = true; + continue; + } + if (!flag4 && !allOrNothing && array != null && _softened.TryGetValue(text2, out (ushort[], ushort[], string) value) && SameRamp(value.Item1, array3) && SameRamp(array, value.Item2)) + { + DisplaysThatWereSoftened++; + step = value.Item3; + flag2 = true; + continue; + } + DeviceWrites++; + bool flag5 = _setRampOnDevice(item3, array3); + if ((flag5 & flag4) && Selection != null) + { + ushort[] array4 = _readRampOnDevice(item3); + flag5 = array4 != null && SameRamp(array4, array3); + } + if (!flag5 && !flag4 && !allOrNothing && !AlreadyRefusedEveryStep(text2, array3)) + { + if (TryGentler(item3, array3, out ushort[] landed, out string step2)) + { + _softened[text2] = ((ushort[])array3.Clone(), landed, step2); + DisplaysThatWereSoftened++; + step = step2; + flag5 = true; + ColourTrace.Refused("GAMMA RAMP", "Windows refused the full ramp on " + item3 + "; a gentler one (" + step2 + ") went through"); + } + else + { + _refusedEveryStep[text2] = (ushort[])array3.Clone(); + } + } + if (flag5 && !flag4) + { + _refusedEveryStep.Remove(text2); + } + flag2 |= flag5; + if (flag4 & flag5) + { + ReleaseRecord(text2); + } + if (!flag5) + { + DisplaysThatRefusedTheLastWrite++; + ColourTrace.Refused("GAMMA RAMP", "Windows refused the ramp on " + item3); + } + if (!allOrNothing) + { + continue; + } + if (!flag5) + { + text = "Windows refused the Dark Boost ramp on a display"; + } + else + { + ushort[] array5 = _readRampOnDevice(item3); + if (array5 == null || !SameRamp(array5, array3)) + { + DisplaysThatRefusedTheLastWrite++; + text = "a display did not hold the Dark Boost ramp it was given"; + } + } + if (text != null) + { + break; + } + } + LastApplyFailed = flag && !flag2; + if (allOrNothing && text == null && !flag) + { + text = "no display to hold the Dark Boost ramp"; + } + if (LastApplyFailed) + { + LastRefusal = "Windows refused the gamma ramp on every display"; + } + else if (text != null) + { + LastRefusal = text; + } + else if (DisplaysThatRefusedTheLastWrite > 0) + { + LastRefusal = "Windows refused the gamma ramp on " + DisplaysThatRefusedTheLastWrite + " of your displays"; + } + MultiMonitorGammaRamp multiMonitorGammaRamp = this; + GammaDelivery lastDelivery; + if (LastApplyFailed || DisplaysThatRefusedTheLastWrite > 0 || text != null) + { + lastDelivery = new GammaDelivery(GammaDeliveryKind.Refused, Math.Max(1, DisplaysThatRefusedTheLastWrite)); + } + else + { + lastDelivery = ((DisplaysThatWereSoftened > 0) ? new GammaDelivery(GammaDeliveryKind.Softened, DisplaysThatWereSoftened, step) : GammaDelivery.Full); + } + multiMonitorGammaRamp.LastDelivery = lastDelivery; + if (!allOrNothing) + { + return null; + } + return text; + } + + private bool TryGentler(string device, ushort[] wanted, out ushort[] landed, out string step) + { + landed = Array.Empty(); + step = ""; + ushort[] array = GammaCurve.Identity(); + if (wanted.Length != array.Length) + { + return false; + } + double[] softeningSteps = SofteningSteps; + foreach (double num in softeningSteps) + { + ushort[] array2 = Toward(array, wanted, num); + if (SameRamp(array2, array)) + { + return false; + } + if (_setRampOnDevice(device, array2)) + { + landed = array2; + step = "1/" + Math.Round(1.0 / num); + return true; + } + } + return false; + } + + internal static ushort[] Toward(ushort[] identity, ushort[] wanted, double strength) + { + ushort[] array = new ushort[wanted.Length]; + for (int i = 0; i < array.Length; i++) + { + array[i] = (ushort)Math.Clamp(Math.Round((double)(int)identity[i] + (double)(wanted[i] - identity[i]) * strength), 0.0, 65535.0); + } + return array; + } + + private ushort[]? TheirOwn(string device, ushort[]? reading) + { + if (_coloured.Contains(device) && _theirOwn.TryGetValue(device, out ushort[] value)) + { + return value; + } + ushort[] array = ((reading != null && LooksLikeARamp(reading)) ? ((ushort[])reading.Clone()) : null); + _theirOwn[device] = array; + return array; + } + + internal static bool LooksLikeARamp(ushort[] ramp) + { + if (ramp.Length != 768) + { + return false; + } + for (int i = 0; i < 3; i++) + { + int num = i * 256; + for (int j = 1; j < 256; j++) + { + if (ramp[num + j] + 255 < ramp[num + j - 1]) + { + return false; + } + } + if (ramp[num + 256 - 1] - ramp[num] < 16383) + { + return false; + } + } + return true; + } + + private static bool NoAdjustment(int gammaPercent, int warmthPercent) + { + return MonitorColourAdjust.IsNeutral(Math.Clamp(gammaPercent, 50, 150), Math.Clamp(warmthPercent, 0, 100)); + } + + private bool AlreadyRefusedEveryStep(string device, ushort[] wanted) + { + if (_refusedEveryStep.TryGetValue(device, out ushort[] value)) + { + return SameRamp(value, wanted); + } + return false; + } + + private static bool SameRamp(ushort[] a, ushort[] b) + { + if (a.Length != b.Length) + { + return false; + } + for (int i = 0; i < a.Length; i++) + { + if (a[i] != b[i]) + { + return false; + } + } + return true; + } + + public void Reset() + { + Deliver(null, allOrNothing: false); + } + + public void RefreshMonitors() + { + Deliver(_lastBase, _lastBaseAllOrNothing); + } + + internal void AdoptRecoveryBaselines(IReadOnlyDictionary baselines) + { + foreach (var (text2, array2) in baselines) + { + if (LooksLikeARamp(array2)) + { + _theirOwn[text2] = (ushort[])array2.Clone(); + _coloured.Add(text2); + } + } + } + + private void ReleaseRecord(string key) + { + _coloured.Remove(key); + _theirOwn.Remove(key); + _softened.Remove(key); + _refusedEveryStep.Remove(key); + DeviceReleased?.Invoke(key); + } + + private void ReleaseSelectedDevice(string device, string key) + { + if (!_coloured.Contains(key) || !_theirOwn.TryGetValue(key, out ushort[] value) || value == null) + { + return; + } + ushort[] array = _readRampOnDevice(device); + if (array != null && SameRamp(array, value)) + { + ReleaseRecord(key); + return; + } + DeviceWrites++; + if (_setRampOnDevice(device, value)) + { + ushort[] array2 = _readRampOnDevice(device); + if (array2 != null && SameRamp(array2, value)) + { + ReleaseRecord(key); + } + } + } + + public void Dispose() + { + if (_saidGoodbye) + { + return; + } + _saidGoodbye = true; + ushort[] array = GammaCurve.Identity(); + foreach (string item in _enumerateDevices()) + { + if (Selection != null) + { + ReleaseSelectedDevice(item, Selection.KeyFor(item)); + continue; + } + bool flag = _theirOwn.TryGetValue(item, out ushort[] value); + if (flag && !_coloured.Contains(item)) + { + ushort[] array2 = _readRampOnDevice(item); + if (array2 == null || !LooksLikeARamp(array2)) + { + _setRampOnDevice(item, array); + } + } + else + { + _setRampOnDevice(item, (flag && value != null) ? value : array); + } + } + } + + internal static IReadOnlyList Devices() + { + List list = new List(); + DISPLAY_DEVICE lpDisplayDevice = new DISPLAY_DEVICE + { + cb = Marshal.SizeOf() + }; + for (uint num = 0u; EnumDisplayDevices(null, num, ref lpDisplayDevice, 0u); num++) + { + if ((lpDisplayDevice.StateFlags & 1) != 0 && (lpDisplayDevice.StateFlags & 8) == 0) + { + list.Add(lpDisplayDevice.DeviceName); + } + lpDisplayDevice = new DISPLAY_DEVICE + { + cb = Marshal.SizeOf() + }; + } + return list; + } + + internal static bool SetRampOn(string deviceName, ushort[] ramp) + { + nint num = CreateDC(null, deviceName, null, IntPtr.Zero); + if (num == IntPtr.Zero) + { + return false; + } + try + { + return SetDeviceGammaRamp(num, ramp); + } + finally + { + DeleteDC(num); + } + } + + internal static ushort[]? ReadRampOn(string deviceName) + { + nint num = CreateDC(null, deviceName, null, IntPtr.Zero); + if (num == IntPtr.Zero) + { + return null; + } + try + { + ushort[] array = new ushort[768]; + return GetDeviceGammaRamp(num, array) ? array : null; + } + finally + { + DeleteDC(num); + } + } +} diff --git a/VibranceHud/Music/GsmtcSource.cs b/VibranceHud/Music/GsmtcSource.cs new file mode 100644 index 0000000..8e17096 --- /dev/null +++ b/VibranceHud/Music/GsmtcSource.cs @@ -0,0 +1,317 @@ +using System; +using System.Diagnostics; +using System.Drawing; +using System.IO; +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.ComTypes; +using System.Threading; + +namespace VibranceHud.Music; + +internal sealed class GsmtcSource : INowPlayingSource +{ + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int GetPointer(nint self, out nint value); + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int GetInt(nint self, out int value); + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int GetBool(nint self, out byte value); + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int NoArgs(nint self); + + private sealed class Com : IDisposable + { + internal nint Ptr; + + internal Com(nint ptr) + { + Ptr = ptr; + } + + internal Com As(Guid iid) + { + _cancellation.ThrowIfCancellationRequested(); + Check(Marshal.QueryInterface(Ptr, in iid, out var ppv)); + return new Com(ppv); + } + + public void Dispose() + { + if (Ptr != IntPtr.Zero) + { + Marshal.Release(Ptr); + Ptr = IntPtr.Zero; + } + } + } + + [ThreadStatic] + private static CancellationToken _cancellation; + + private static readonly Guid Statics = new Guid("2050C4EE-11A0-57DE-AED7-C97C70338245"); + + private static readonly Guid Manager = new Guid("CACE8EAC-E86E-504A-AB31-5FF8FF1BCE49"); + + private static readonly Guid Session = new Guid("7148C835-9B14-5AE2-AB85-DC9B1C14E1A8"); + + private static readonly Guid Properties = new Guid("68856CF6-ADB4-54B2-AC16-05837907ACB6"); + + private static readonly Guid Playback = new Guid("94B4B6CF-E8BA-51AD-87A7-C10ADE106127"); + + private static readonly Guid Controls = new Guid("6501A3E6-BC7A-503A-BB1B-68F158F3FB03"); + + private static readonly Guid StreamReference = new Guid("33EE3134-1DD6-4E3A-8067-D1C162E8642B"); + + private static readonly Guid AsyncInfo = new Guid("00000036-0000-0000-C000-000000000046"); + + private static readonly Guid StreamIid = new Guid("0000000C-0000-0000-C000-000000000046"); + + public bool NeedsWorker => true; + + [DllImport("combase.dll")] + private static extern int RoInitialize(uint type); + + [DllImport("combase.dll")] + private static extern void RoUninitialize(); + + [DllImport("combase.dll", CharSet = CharSet.Unicode)] + private static extern int WindowsCreateString(string value, uint length, out nint result); + + [DllImport("combase.dll")] + private static extern int WindowsDeleteString(nint value); + + [DllImport("combase.dll")] + private static extern nint WindowsGetStringRawBuffer(nint value, out uint length); + + [DllImport("combase.dll")] + private static extern int RoGetActivationFactory(nint name, in Guid iid, out nint result); + + [DllImport("shcore.dll")] + private static extern int CreateStreamOverRandomAccessStream(nint random, in Guid iid, out nint stream); + + private static void Check(int hr) + { + Marshal.ThrowExceptionForHR(hr); + } + + private static T Slot(Com c, int slot) where T : Delegate + { + _cancellation.ThrowIfCancellationRequested(); + return Marshal.GetDelegateForFunctionPointer(Marshal.ReadIntPtr(Marshal.ReadIntPtr(c.Ptr), slot * IntPtr.Size)); + } + + private static Com Pointer(Com c, int slot) + { + Check(Slot(c, slot)(c.Ptr, out var value)); + return new Com(value); + } + + private static int Integer(Com c, int slot) + { + Check(Slot(c, slot)(c.Ptr, out var value)); + return value; + } + + private static bool Boolean(Com c, int slot) + { + Check(Slot(c, slot)(c.Ptr, out var value)); + return value != 0; + } + + private static string Text(Com c, int slot) + { + using Com com = Pointer(c, slot); + nint ptr = com.Ptr; + com.Ptr = IntPtr.Zero; + try + { + uint length; + return Marshal.PtrToStringUni(WindowsGetStringRawBuffer(ptr, out length), checked((int)length)) ?? ""; + } + finally + { + WindowsDeleteString(ptr); + } + } + + private static void Wait(Com operation) + { + using Com com = operation.As(AsyncInfo); + Stopwatch stopwatch = Stopwatch.StartNew(); + while (Integer(com, 7) == 0) + { + if (stopwatch.ElapsedMilliseconds >= 1400) + { + Slot(com, 9)(com.Ptr); + throw new TimeoutException(); + } + Thread.Sleep(20); + } + if (Integer(com, 7) != 1) + { + throw new InvalidOperationException("Media operation did not complete."); + } + } + + private static Com Result(Com operation) + { + Wait(operation); + return Pointer(operation, 8); + } + + private static Com Current() + { + _cancellation.ThrowIfCancellationRequested(); + Check(WindowsCreateString("Windows.Media.Control.GlobalSystemMediaTransportControlsSessionManager", (uint)"Windows.Media.Control.GlobalSystemMediaTransportControlsSessionManager".Length, out var result)); + try + { + Check(RoGetActivationFactory(result, in Statics, out var result2)); + using Com c = new Com(result2); + using Com operation = Pointer(c, 6); + using Com com = Result(operation); + using Com c2 = com.As(Manager); + using Com com2 = Pointer(c2, 6); + return (com2.Ptr == IntPtr.Zero) ? new Com(IntPtr.Zero) : com2.As(Session); + } + finally + { + WindowsDeleteString(result); + } + } + + private static T OnMta(Func read, CancellationToken cancellation = default(CancellationToken)) + { + cancellation.ThrowIfCancellationRequested(); + if (Thread.CurrentThread.GetApartmentState() != ApartmentState.MTA) + { + throw new InvalidOperationException("Windows media must be read on an MTA worker."); + } + Check(RoInitialize(1u)); + _cancellation = cancellation; + try + { + return read(); + } + finally + { + _cancellation = default; + RoUninitialize(); + } + } + + public NowPlaying? Read() + { + return Read(CancellationToken.None); + } + + public NowPlaying? Read(CancellationToken cancellation) + { + return OnMta(() => + { + using Com com = Current(); + if (com.Ptr != IntPtr.Zero) + { + using Com operation = Pointer(com, 7); + using Com com2 = Result(operation); + using Com com3 = com2.As(Properties); + using Com com4 = Pointer(com, 9); + using Com c = com4.As(Playback); + using Com com5 = Pointer(c, 6); + using Com c2 = com5.As(Controls); + string text = Text(com3, 6); + if (string.IsNullOrWhiteSpace(text)) + { + return (NowPlaying)null; + } + return new NowPlaying(Text(com3, 9), text) + { + AppName = Text(com, 6), + IsPlaying = (Integer(c, 7) == 4), + CanNext = Boolean(c2, 12), + CanPrevious = Boolean(c2, 13), + CanPlayPause = Boolean(c2, 16), + Art = ReadArt(com3) + }; + } + return (NowPlaying)null; + }, cancellation); + } + + public bool TryCommand(MediaKey key) + { + return OnMta(() => + { + using Com com = Current(); + if (com.Ptr != IntPtr.Zero) + { + Com c = com; + int slot = ((key == MediaKey.Next) ? 16 : ((key == MediaKey.Previous) ? 17 : 20)); + using Com com2 = Pointer(c, slot); + Wait(com2); + return Boolean(com2, 8); + } + return false; + }); + } + + private static Bitmap? ReadArt(Com properties) + { + try + { + using Com com = Pointer(properties, 15); + if (com.Ptr == IntPtr.Zero) + { + return null; + } + using Com c = com.As(StreamReference); + using Com operation = Pointer(c, 6); + using Com com2 = Result(operation); + Check(CreateStreamOverRandomAccessStream(com2.Ptr, in StreamIid, out var stream)); + object obj = null; + try + { + obj = Marshal.GetObjectForIUnknown(stream); + IStream stream2 = (IStream)obj; + stream2.Stat(out var pstatstg, 1); + if (pstatstg.cbSize <= 0 || pstatstg.cbSize > 8388608) + { + return null; + } + byte[] array = new byte[(int)pstatstg.cbSize]; + nint num = Marshal.AllocCoTaskMem(4); + try + { + stream2.Read(array, array.Length, num); + int num2 = Marshal.ReadInt32(num); + if (num2 <= 0) + { + return null; + } + using MemoryStream stream3 = new MemoryStream(array, 0, num2); + using Image image = Image.FromStream(stream3); + double num3 = Math.Min(1.0, 256.0 / (double)Math.Max(image.Width, image.Height)); + return new Bitmap(image, Math.Max(1, (int)((double)image.Width * num3)), Math.Max(1, (int)((double)image.Height * num3))); + } + finally + { + Marshal.FreeCoTaskMem(num); + } + } + finally + { + if (obj != null) + { + Marshal.ReleaseComObject(obj); + } + Marshal.Release(stream); + } + } + catch + { + return null; + } + } +} diff --git a/VibranceHud/Music/IMediaKeys.cs b/VibranceHud/Music/IMediaKeys.cs new file mode 100644 index 0000000..552b7c7 --- /dev/null +++ b/VibranceHud/Music/IMediaKeys.cs @@ -0,0 +1,6 @@ +namespace VibranceHud.Music; + +internal interface IMediaKeys +{ + void Send(MediaKey key); +} diff --git a/VibranceHud/Music/INowPlayingSource.cs b/VibranceHud/Music/INowPlayingSource.cs new file mode 100644 index 0000000..3ad1e47 --- /dev/null +++ b/VibranceHud/Music/INowPlayingSource.cs @@ -0,0 +1,29 @@ +using System.Threading; + +namespace VibranceHud.Music; + +internal interface INowPlayingSource +{ + bool NeedsWorker => false; + + NowPlaying? Read() + { + return NowPlaying.FromSpotifyTitle(SpotifyWindowTitle()); + } + + NowPlaying? Read(CancellationToken cancellation) + { + cancellation.ThrowIfCancellationRequested(); + return Read(); + } + + bool TryCommand(MediaKey key) + { + return false; + } + + string? SpotifyWindowTitle() + { + return null; + } +} diff --git a/VibranceHud/Music/MediaGlyphButton.cs b/VibranceHud/Music/MediaGlyphButton.cs new file mode 100644 index 0000000..540bb10 --- /dev/null +++ b/VibranceHud/Music/MediaGlyphButton.cs @@ -0,0 +1,122 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; + +namespace VibranceHud.Music; + +internal sealed class MediaGlyphButton : Control +{ + private bool _hover; + + private bool _playing; + + internal MediaKey Key { get; } + + internal bool IsPlaying + { + get + { + return _playing; + } + set + { + _playing = value; + if (Key == MediaKey.PlayPause) + { + AccessibleName = (value ? "Pause" : "Play"); + } + Invalidate(); + } + } + + internal MediaGlyphButton(MediaKey key) + { + Key = key; + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + Cursor = Cursors.Hand; + TabStop = false; + AccessibleRole = AccessibleRole.PushButton; + AccessibleName = key switch + { + MediaKey.Next => "Next track", + MediaKey.Previous => "Previous track", + _ => "Play or pause", + }; + } + + protected override void OnMouseEnter(EventArgs e) + { + _hover = true; + Invalidate(); + base.OnMouseEnter(e); + } + + protected override void OnMouseLeave(EventArgs e) + { + _hover = false; + Invalidate(); + base.OnMouseLeave(e); + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics graphics = e.Graphics; + graphics.SmoothingMode = SmoothingMode.AntiAlias; + int dpi = ControlInk.Dpi(this); + if (_hover) + { + using SolidBrush brush = new SolidBrush(ControlInk.Hover); + using GraphicsPath path = Glass.RoundedPath(new RectangleF(0f, 0f, Width - 1, Height - 1), ControlInk.PxF(dpi, 4f)); + graphics.FillPath(brush, path); + } + float num = ControlInk.PxF(dpi, 10f); + float num2 = ((float)Width - num) / 2f; + float num3 = ((float)Height - num) / 2f; + Color color; + if (Enabled) + { + color = (_hover ? ControlInk.Text1 : ControlInk.Text2); + } + else + { + color = ControlInk.Text3; + } + using SolidBrush brush2 = new SolidBrush(color); + float num4 = Math.Max(1.5f, ControlInk.PxF(dpi, 1.6f)); + switch (Key) + { + case MediaKey.Previous: + graphics.FillRectangle(brush2, num2, num3, num4, num); + graphics.FillPolygon(brush2, new PointF[3] + { + new PointF(num2 + num, num3), + new PointF(num2 + num, num3 + num), + new PointF(num2 + num4 + 0.5f, num3 + num / 2f) + }); + return; + case MediaKey.Next: + graphics.FillPolygon(brush2, new PointF[3] + { + new PointF(num2, num3), + new PointF(num2, num3 + num), + new PointF(num2 + num - num4 - 0.5f, num3 + num / 2f) + }); + graphics.FillRectangle(brush2, num2 + num - num4, num3, num4, num); + return; + } + if (IsPlaying) + { + graphics.FillRectangle(brush2, num2 + num4, num3, num4, num); + graphics.FillRectangle(brush2, num2 + num - 2f * num4, num3, num4, num); + return; + } + graphics.FillPolygon(brush2, new PointF[3] + { + new PointF(num2, num3), + new PointF(num2, num3 + num), + new PointF(num2 + num, num3 + num / 2f) + }); + } +} diff --git a/VibranceHud/Music/MediaKey.cs b/VibranceHud/Music/MediaKey.cs new file mode 100644 index 0000000..656b4f3 --- /dev/null +++ b/VibranceHud/Music/MediaKey.cs @@ -0,0 +1,8 @@ +namespace VibranceHud.Music; + +internal enum MediaKey +{ + PlayPause, + Next, + Previous +} diff --git a/VibranceHud/Music/MusicHotkey.cs b/VibranceHud/Music/MusicHotkey.cs new file mode 100644 index 0000000..371ae65 --- /dev/null +++ b/VibranceHud/Music/MusicHotkey.cs @@ -0,0 +1,149 @@ +using System; +using System.Runtime.InteropServices; + +namespace VibranceHud.Music; + +internal sealed class MusicHotkey : IDisposable +{ + private const int Id = 1; + + private readonly HotkeyWindow _window; + + private bool _disposed; + + internal static readonly HotkeySlot[] Slots = new HotkeySlot[4] + { + HotkeySlot.MusicMini, + HotkeySlot.MusicPlayPause, + HotkeySlot.MusicNext, + HotkeySlot.MusicPrevious + }; + + [DllImport("user32.dll", SetLastError = true)] + private static extern bool RegisterHotKey(nint hWnd, int id, uint fsModifiers, uint vk); + + [DllImport("user32.dll", SetLastError = true)] + private static extern bool UnregisterHotKey(nint hWnd, int id); + + private MusicHotkey(HotkeyWindow window) + { + _window = window; + } + + internal static MusicHotkey? TryRegister(AppSettings settings, Action onPressed) + { + return TryRegister(settings, HotkeySlot.MusicMini, onPressed); + } + + internal static (bool Enabled, uint Mask, uint Key) Binding(AppSettings s, HotkeySlot slot) + { + return slot switch + { + HotkeySlot.MusicMini => (Enabled: s.MusicHotkeyEnabled, Mask: s.MusicHotkeyModifierMask, Key: s.MusicHotkeyVirtualKey), + HotkeySlot.MusicPlayPause => (Enabled: s.MusicPlayPauseHotkeyEnabled, Mask: s.MusicPlayPauseHotkeyModifierMask, Key: s.MusicPlayPauseHotkeyVirtualKey), + HotkeySlot.MusicNext => (Enabled: s.MusicNextHotkeyEnabled, Mask: s.MusicNextHotkeyModifierMask, Key: s.MusicNextHotkeyVirtualKey), + HotkeySlot.MusicPrevious => (Enabled: s.MusicPreviousHotkeyEnabled, Mask: s.MusicPreviousHotkeyModifierMask, Key: s.MusicPreviousHotkeyVirtualKey), + _ => throw new ArgumentOutOfRangeException("slot"), + }; + } + + internal static void SetBinding(AppSettings s, HotkeySlot slot, bool enabled, uint mask, uint key) + { + switch (slot) + { + case HotkeySlot.MusicMini: + s.MusicHotkeyEnabled = enabled; + s.MusicHotkeyModifierMask = mask; + s.MusicHotkeyVirtualKey = key; + break; + case HotkeySlot.MusicPlayPause: + s.MusicPlayPauseHotkeyEnabled = enabled; + s.MusicPlayPauseHotkeyModifierMask = mask; + s.MusicPlayPauseHotkeyVirtualKey = key; + break; + case HotkeySlot.MusicNext: + s.MusicNextHotkeyEnabled = enabled; + s.MusicNextHotkeyModifierMask = mask; + s.MusicNextHotkeyVirtualKey = key; + break; + case HotkeySlot.MusicPrevious: + s.MusicPreviousHotkeyEnabled = enabled; + s.MusicPreviousHotkeyModifierMask = mask; + s.MusicPreviousHotkeyVirtualKey = key; + break; + default: + throw new ArgumentOutOfRangeException("slot"); + } + } + + internal static MusicHotkey? TryRegister(AppSettings settings, HotkeySlot slot, Action onPressed) + { + (bool, uint, uint) tuple = Binding(settings, slot); + if (!tuple.Item1 || tuple.Item3 == 0) + { + return null; + } + if (Clashes(settings, slot, tuple.Item2, tuple.Item3)) + { + return null; + } + HotkeyWindow hotkeyWindow = new HotkeyWindow(); + if (!RegisterHotKey(hotkeyWindow.Handle, 1, tuple.Item2 | 0x4000, tuple.Item3)) + { + hotkeyWindow.DestroyHandle(); + return null; + } + hotkeyWindow.HotkeyPressed += (object? _, EventArgs e) => + { + if (e is HotkeyEventArgs { HotkeyId: 1 }) + { + onPressed(); + } + }; + return new MusicHotkey(hotkeyWindow); + } + + internal static bool ClashesWithAnAppKey(AppSettings s) + { + return Clashes(s, HotkeySlot.MusicMini, s.MusicHotkeyModifierMask, s.MusicHotkeyVirtualKey); + } + + internal static bool Clashes(AppSettings s, HotkeySlot slot, uint mask, uint vk) + { + if (HotkeyConflicts.Owner(s, slot, mask, vk).HasValue) + { + return true; + } + foreach (PresetKeyBinding presetKeyBinding in s.PresetKeyBindings) + { + if (vk != 0 && presetKeyBinding.ModifierMask == mask && presetKeyBinding.VirtualKey == vk) + { + return true; + } + } + return false; + } + + public void Dispose() + { + if (_disposed) + { + return; + } + _disposed = true; + try + { + UnregisterHotKey(_window.Handle, 1); + } + catch + { + } + try + { + _window.DestroyHandle(); + } + catch + { + } + } +} diff --git a/VibranceHud/Music/MusicPlayer.cs b/VibranceHud/Music/MusicPlayer.cs new file mode 100644 index 0000000..01366a8 --- /dev/null +++ b/VibranceHud/Music/MusicPlayer.cs @@ -0,0 +1,279 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Threading.Tasks; +using System.Windows.Forms; +using VibranceHud.Hotkeys; + +namespace VibranceHud.Music; + +internal static class MusicPlayer +{ + internal sealed class TrayAttachment : IDisposable + { + private readonly INowPlayingSource _source; + + private readonly IMediaKeys _keys; + + private readonly List _hotkeys = new List(); + + private readonly AppSettings _settings; + + private readonly Action? _savePosition; + + private readonly ContextMenuStrip _menu; + + private readonly HotkeyCaptureRelease _captureRelease; + + private MusicMiniWindow? _mini; + + internal ToolStripItem NowPlayingItem { get; } + + internal MusicMiniWindow? MiniWindow => _mini; + + internal bool KeyBound => _hotkeys.Count != 0; + + internal TrayAttachment(ContextMenuStrip menu, AppSettings settings, INowPlayingSource source, IMediaKeys keys, Action? savePosition) + { + _source = source; + _keys = keys; + _settings = settings; + _savePosition = savePosition; + _menu = menu; + _captureRelease = new HotkeyCaptureRelease(HotkeyCaptureGate.Shared, ReleaseKeys, () => + { + Rebind(); + }); + menu.Items.Add(new ToolStripSeparator + { + Tag = TrayTag + }); + NowPlayingItem = Add(menu, "Now playing: ", null); + NowPlayingItem.Enabled = false; + NowPlayingItem.Visible = false; + Add(menu, "Play / pause", () => + { + Command(MediaKey.PlayPause); + }); + Add(menu, "Next track", () => + { + Command(MediaKey.Next); + }); + Add(menu, "Previous track", () => + { + Command(MediaKey.Previous); + }); + Add(menu, "Music mini player", ToggleMini); + menu.Opening += (object? _, CancelEventArgs _) => + { + ReadNow(); + }; + Rebind(); + HotkeysChanged += Rebind; + menu.Disposed += (object? _, EventArgs _) => + { + Dispose(); + }; + Application.ApplicationExit += OnExit; + } + + private static ToolStripItem Add(ContextMenuStrip menu, string words, Action? onClick) + { + EventHandler onClick2 = ((onClick == null) ? null : ((EventHandler)((object? _, EventArgs _) => + { + onClick(); + }))); + ToolStripItem toolStripItem = menu.Items.Add(words, null, onClick2); + toolStripItem.Tag = TrayTag; + return toolStripItem; + } + + internal void ReadNow() + { + if (_source.NeedsWorker) + { + Task.Run(() => + { + NowPlaying result; + try + { + result = _source.Read(); + } + catch + { + result = null; + } + try + { + _menu.BeginInvoke(() => + { + SetTraySnapshot(result); + result?.Art?.Dispose(); + }); + } + catch + { + result?.Art?.Dispose(); + } + }); + } + else + { + NowPlaying traySnapshot; + try + { + traySnapshot = _source.Read(); + } + catch + { + traySnapshot = null; + } + SetTraySnapshot(traySnapshot); + } + } + + private void SetTraySnapshot(NowPlaying? now) + { + if (!_menu.IsDisposed) + { + NowPlayingItem.Text = ((now == null) ? "Now playing: " : ("Now playing: " + now.Line)); + NowPlayingItem.Visible = now != null; + } + } + + private void Command(MediaKey key) + { + MusicPoller.For(_source).Command(key, _keys, _menu); + } + + private bool Rebind(HotkeySlot? requested = null) + { + ReleaseKeys(); + if (HotkeyCaptureGate.Shared.IsCapturing) + { + return true; + } + bool result = true; + HotkeySlot[] slots = MusicHotkey.Slots; + foreach (HotkeySlot slot in slots) + { + (bool, uint, uint) tuple = MusicHotkey.Binding(_settings, slot); + if (!tuple.Item1 || tuple.Item3 == 0) + { + continue; + } + Action onPressed = ((slot == HotkeySlot.MusicMini) ? new Action(ToggleMini) : ((Action)(() => + { + Command((slot == HotkeySlot.MusicNext) ? MediaKey.Next : ((slot == HotkeySlot.MusicPrevious) ? MediaKey.Previous : MediaKey.PlayPause)); + }))); + MusicHotkey musicHotkey = MusicHotkey.TryRegister(_settings, slot, onPressed); + if (musicHotkey == null) + { + if (!requested.HasValue || requested == slot) + { + result = false; + } + } + else + { + _hotkeys.Add(musicHotkey); + } + } + return result; + } + + private void ReleaseKeys() + { + foreach (MusicHotkey hotkey in _hotkeys) + { + hotkey.Dispose(); + } + _hotkeys.Clear(); + } + + internal void ToggleMini() + { + if (_mini == null || _mini.IsDisposed) + { + _mini = new MusicMiniWindow(_source, _keys, _settings, _savePosition); + } + _mini.Toggle(); + } + + private void OnExit(object? sender, EventArgs e) + { + Dispose(); + } + + public void Dispose() + { + Application.ApplicationExit -= OnExit; + HotkeysChanged -= Rebind; + _captureRelease.Dispose(); + ReleaseKeys(); + if (_mini != null && !_mini.IsDisposed) + { + _mini.Dispose(); + } + _mini = null; + } + } + + internal const bool Enabled = true; + + internal static readonly object TrayTag = new object(); + + internal const string NowPlayingPrefix = "Now playing: "; + + internal const string PlayPauseWords = "Play / pause"; + + internal const string NextWords = "Next track"; + + internal const string PreviousWords = "Previous track"; + + internal const string MiniPlayerWords = "Music mini player"; + + internal static INowPlayingSource DefaultSource { get; set; } = new WindowsSessionSource(); + + internal static IMediaKeys DefaultKeys { get; set; } = new WindowsMediaKeys(); + + internal static event Func? HotkeysChanged; + + internal static bool RebindHotkeys(HotkeySlot? slot = null) + { + return HotkeysChanged?.Invoke(slot) ?? true; + } + + internal static TrayAttachment? AttachToTray(ContextMenuStrip menu, AppSettings settings, bool enabled = true, INowPlayingSource? source = null, IMediaKeys? keys = null, Action? savePosition = null) + { + if (!enabled) + { + return null; + } + return new TrayAttachment(menu, settings, source ?? DefaultSource, keys ?? DefaultKeys, savePosition); + } + + internal static MusicStrip? AttachToPopup(Form popup, Control slot, bool enabled = true, INowPlayingSource? source = null, IMediaKeys? keys = null) + { + if (!enabled) + { + return null; + } + MusicStrip strip = new MusicStrip(slot, source ?? DefaultSource, keys ?? DefaultKeys); + popup.Controls.Add(strip); + strip.BringToFront(); + strip.AttachPoller(popup); + popup.VisibleChanged += (object? _, EventArgs _) => + { + if (popup.Visible) + { + strip.ReadNow(); + } + }; + popup.Activated += (object? _, EventArgs _) => + { + strip.ReadNow(); + }; + return strip; + } +} diff --git a/VibranceHud/Music/MusicPoller.cs b/VibranceHud/Music/MusicPoller.cs new file mode 100644 index 0000000..5493b61 --- /dev/null +++ b/VibranceHud/Music/MusicPoller.cs @@ -0,0 +1,284 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace VibranceHud.Music; + +internal sealed class MusicPoller +{ + private static readonly ConditionalWeakTable Pollers = new ConditionalWeakTable(); + + private readonly INowPlayingSource _source; + + private readonly System.Windows.Forms.Timer _timer; + + private readonly Dictionary> _views = new Dictionary>(); + + private volatile bool _busy; + + private int _generation; + + private Control? _lastHost; + + private CancellationTokenSource? _readCancellation; + + private NowPlaying? _snapshot; + + internal bool Running => _timer.Enabled; + + private Control? Host => _views.Keys.FirstOrDefault((Control c) => !c.IsDisposed && c.Visible && c.IsHandleCreated); + + internal static MusicPoller For(INowPlayingSource source) + { + return Pollers.GetValue(source, (INowPlayingSource s) => new MusicPoller(s)); + } + + internal MusicPoller(INowPlayingSource source) + { + _source = source; + _timer = new System.Windows.Forms.Timer + { + Interval = 1000 + }; + _timer.Tick += (object? _, EventArgs _) => + { + Refresh(); + }; + } + + internal void Attach(Control owner, Action show) + { + _views[owner] = show; + owner.VisibleChanged += (object? _, EventArgs _) => + { + Reassess(); + }; + owner.HandleDestroyed += (object? _, EventArgs _) => + { + if (!owner.RecreatingHandle && owner == _lastHost) + { + _lastHost = null; + _generation++; + _readCancellation?.Cancel(); + _busy = false; + } + }; + owner.Disposed += (object? _, EventArgs _) => + { + _views.Remove(owner); + Reassess(); + if (_views.Count == 0) + { + _timer.Dispose(); + _snapshot?.Art?.Dispose(); + _snapshot = null; + Pollers.Remove(_source); + } + }; + Reassess(); + } + + private void Reassess() + { + Control host = Host; + bool flag = host != null; + if (host != _lastHost) + { + _lastHost = host; + _generation++; + _readCancellation?.Cancel(); + _busy = false; + } + if (!flag) + { + _timer.Stop(); + _generation++; + _readCancellation?.Cancel(); + _busy = false; + } + else if (!_timer.Enabled) + { + _timer.Start(); + Refresh(); + } + } + + internal void Refresh() + { + Control host = Host; + if (host == null || _busy) + { + return; + } + if (!_source.NeedsWorker) + { + Apply(SafeRead()); + return; + } + _busy = true; + int generation = _generation; + _readCancellation?.Dispose(); + _readCancellation = new CancellationTokenSource(); + CancellationToken cancellation = _readCancellation.Token; + Task.Run(() => + { + NowPlaying snapshot; + try + { + snapshot = _source.Read(cancellation); + } + catch + { + snapshot = null; + } + try + { + if (host.IsDisposed || !host.IsHandleCreated) + { + snapshot?.Art?.Dispose(); + if (generation == _generation) + { + _busy = false; + } + } + else + { + host.BeginInvoke(() => + { + if (generation != _generation || Host == null) + { + snapshot?.Art?.Dispose(); + } + else + { + _busy = false; + Apply(snapshot); + } + }); + } + } + catch + { + snapshot?.Art?.Dispose(); + if (generation == _generation) + { + _busy = false; + } + } + }); + } + + private NowPlaying? SafeRead() + { + try + { + return _source.Read(); + } + catch + { + return null; + } + } + + private void Apply(NowPlaying? snapshot) + { + NowPlaying snapshot2 = _snapshot; + _snapshot = snapshot; + Action[] array = _views.Values.ToArray(); + for (int i = 0; i < array.Length; i++) + { + array[i](snapshot); + } + if (snapshot2?.Art != snapshot?.Art) + { + snapshot2?.Art?.Dispose(); + } + } + + internal void ReadForTestOrRefresh(Action show) + { + if (_source.NeedsWorker) + { + Refresh(); + } + else + { + show(SafeRead()); + } + } + + internal void Command(MediaKey key, IMediaKeys fallback, Control? commandHost = null) + { + Control host = Host ?? commandHost; + if (host != null && !host.IsHandleCreated) + { + _ = host.Handle; + } + if (!_source.NeedsWorker) + { + bool flag; + try + { + flag = _source.TryCommand(key); + } + catch + { + flag = false; + } + if (!flag) + { + fallback.Send(key); + } + RefreshAfterCommand(); + return; + } + Task.Run(() => + { + bool flag2; + try + { + flag2 = _source.TryCommand(key); + } + catch + { + flag2 = false; + } + if (!flag2 && host != null) + { + try + { + host.BeginInvoke(() => + { + fallback.Send(key); + }); + } + catch + { + } + } + if (host != null) + { + try + { + host.BeginInvoke(RefreshAfterCommand); + } + catch + { + } + } + }); + } + + internal async void RefreshAfterCommand() + { + if (Host != null) + { + await Task.Delay(300); + Refresh(); + } + } +} diff --git a/VibranceHud/Music/MusicStrip.cs b/VibranceHud/Music/MusicStrip.cs new file mode 100644 index 0000000..74d8241 --- /dev/null +++ b/VibranceHud/Music/MusicStrip.cs @@ -0,0 +1,114 @@ +using System; +using System.Drawing; +using System.Windows.Forms; +using VibranceHud.Design; + +namespace VibranceHud.Music; + +internal sealed class MusicStrip : Control +{ + private readonly Control _slot; + + private readonly IMediaKeys _keys; + + private readonly MusicPoller _poller; + + private readonly MediaGlyphButton[] _buttons; + + internal NowPlaying? Showing { get; private set; } + + internal MusicStrip(Control slot, INowPlayingSource source, IMediaKeys keys) + { + _slot = slot; + _keys = keys; + _poller = MusicPoller.For(source); + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + Bounds = slot.Bounds; + Visible = false; + TabStop = false; + AccessibleName = "Now playing"; + _buttons = new MediaGlyphButton[3] + { + new MediaGlyphButton(MediaKey.Previous), + new MediaGlyphButton(MediaKey.PlayPause), + new MediaGlyphButton(MediaKey.Next) + }; + MediaGlyphButton[] buttons = _buttons; + foreach (MediaGlyphButton mediaGlyphButton in buttons) + { + MediaKey key = mediaGlyphButton.Key; + mediaGlyphButton.Click += (object? _, EventArgs _) => + { + _poller.Command(key, _keys); + }; + Controls.Add(mediaGlyphButton); + } + LayoutButtons(); + } + + protected override void OnResize(EventArgs e) + { + base.OnResize(e); + LayoutButtons(); + } + + internal void AttachPoller(Form popup) + { + _poller.Attach(popup, ShowSnapshot); + } + + private void LayoutButtons() + { + if (_buttons != null) + { + int dpi = ControlInk.Dpi(this); + int num = Math.Min(Height, ControlInk.Px(dpi, 24)); + int y = (Height - num) / 2; + int num2 = ControlInk.Px(dpi, 3) + ((Showing?.Art != null) ? (num + ControlInk.Px(dpi, 4)) : 0); + MediaGlyphButton[] buttons = _buttons; + for (int i = 0; i < buttons.Length; i++) + { + buttons[i].Bounds = new Rectangle(num2, y, num, num); + num2 += num; + } + } + } + + internal void ReadNow() + { + _poller.ReadForTestOrRefresh(ShowSnapshot); + } + + internal void ShowSnapshot(NowPlaying? now) + { + bool flag = now != Showing; + Showing = now; + Visible = now != null; + _slot.Visible = now == null; + _buttons[0].Enabled = now?.CanPrevious ?? false; + _buttons[1].Enabled = now?.CanPlayPause ?? false; + _buttons[1].IsPlaying = now?.IsPlaying ?? false; + _buttons[2].Enabled = now?.CanNext ?? false; + LayoutButtons(); + if (flag) + { + Invalidate(); + } + } + + protected override void OnPaint(PaintEventArgs e) + { + if (!(Showing == null)) + { + int dpi = ControlInk.Dpi(this); + if (Showing.Art != null) + { + int num = Math.Min(Height, ControlInk.Px(dpi, 24)); + e.Graphics.DrawImage(Showing.Art, new Rectangle(ControlInk.Px(dpi, 3), (Height - num) / 2, num, num)); + } + int num2 = _buttons[^1].Right + ControlInk.Px(dpi, 6); + TextRenderer.DrawText(bounds: new Rectangle(num2, 0, Math.Max(0, Width - num2), Height), dc: e.Graphics, text: Showing.Line, font: Fonts.Caption, foreColor: ControlInk.Text2, flags: TextFormatFlags.EndEllipsis | TextFormatFlags.NoPrefix | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter); + } + } +} diff --git a/VibranceHud/Music/NoMediaKeys.cs b/VibranceHud/Music/NoMediaKeys.cs new file mode 100644 index 0000000..f44716d --- /dev/null +++ b/VibranceHud/Music/NoMediaKeys.cs @@ -0,0 +1,8 @@ +namespace VibranceHud.Music; + +internal sealed class NoMediaKeys : IMediaKeys +{ + public void Send(MediaKey key) + { + } +} diff --git a/VibranceHud/Music/NoMusicSource.cs b/VibranceHud/Music/NoMusicSource.cs new file mode 100644 index 0000000..5b444d6 --- /dev/null +++ b/VibranceHud/Music/NoMusicSource.cs @@ -0,0 +1,9 @@ +namespace VibranceHud.Music; + +internal sealed class NoMusicSource : INowPlayingSource +{ + public string? SpotifyWindowTitle() + { + return null; + } +} diff --git a/VibranceHud/Music/NowPlaying.cs b/VibranceHud/Music/NowPlaying.cs new file mode 100644 index 0000000..87254fb --- /dev/null +++ b/VibranceHud/Music/NowPlaying.cs @@ -0,0 +1,58 @@ +using System; +using System.Drawing; + +namespace VibranceHud.Music; + +internal sealed record NowPlaying(string Artist, string Song) +{ + internal string Title => Song; + + internal string? AppName { get; init; } + + internal bool IsPlaying { get; init; } = true; + + internal bool CanPrevious { get; init; } = true; + + internal bool CanNext { get; init; } = true; + + internal bool CanPlayPause { get; init; } = true; + + internal Bitmap? Art { get; init; } + + internal string Line + { + get + { + if (!string.IsNullOrWhiteSpace(Artist)) + { + return Title + " – " + Artist; + } + return Title; + } + } + + internal static NowPlaying? FromSpotifyTitle(string? title) + { + if (string.IsNullOrWhiteSpace(title)) + { + return null; + } + string text = title.Trim(); + if (text.StartsWith("Spotify", StringComparison.OrdinalIgnoreCase)) + { + return null; + } + int num = text.IndexOf(" - ", StringComparison.Ordinal); + if (num <= 0) + { + return null; + } + string text2 = text.Substring(0, num).Trim(); + string text3 = text.Substring(num + 3).Trim(); + if (text2.Length == 0 || text3.Length == 0) + { + return null; + } + return new NowPlaying(text2, text3); + } +} diff --git a/VibranceHud/Music/SpotifyWindowTitleSource.cs b/VibranceHud/Music/SpotifyWindowTitleSource.cs new file mode 100644 index 0000000..e65730b --- /dev/null +++ b/VibranceHud/Music/SpotifyWindowTitleSource.cs @@ -0,0 +1,39 @@ +using System.Diagnostics; + +namespace VibranceHud.Music; + +internal sealed class SpotifyWindowTitleSource : INowPlayingSource +{ + public string? SpotifyWindowTitle() + { + Process[] processesByName; + try + { + processesByName = Process.GetProcessesByName("Spotify"); + } + catch + { + return null; + } + string text = null; + Process[] array = processesByName; + foreach (Process process in array) + { + try + { + if (text == null && !string.IsNullOrWhiteSpace(process.MainWindowTitle)) + { + text = process.MainWindowTitle; + } + } + catch + { + } + finally + { + process.Dispose(); + } + } + return text; + } +} diff --git a/VibranceHud/Music/WindowsMediaKeys.cs b/VibranceHud/Music/WindowsMediaKeys.cs new file mode 100644 index 0000000..9d095bf --- /dev/null +++ b/VibranceHud/Music/WindowsMediaKeys.cs @@ -0,0 +1,40 @@ +using System.Runtime.InteropServices; +using System.Windows.Forms; + +namespace VibranceHud.Music; + +internal sealed class WindowsMediaKeys : IMediaKeys +{ + private const int WM_APPCOMMAND = 793; + + private const int APPCOMMAND_MEDIA_NEXTTRACK = 11; + + private const int APPCOMMAND_MEDIA_PREVIOUSTRACK = 12; + + private const int APPCOMMAND_MEDIA_PLAY_PAUSE = 14; + + private NativeWindow? _window; + + [DllImport("user32.dll")] + private static extern nint SendMessage(nint hWnd, int msg, nint wParam, nint lParam); + + internal static int AppCommandFor(MediaKey key) + { + return key switch + { + MediaKey.Next => 11, + MediaKey.Previous => 12, + _ => 14, + }; + } + + public void Send(MediaKey key) + { + if (_window == null) + { + _window = new NativeWindow(); + _window.CreateHandle(new CreateParams()); + } + SendMessage(_window.Handle, 793, _window.Handle, AppCommandFor(key) << 16); + } +} diff --git a/VibranceHud/Music/WindowsSessionSource.cs b/VibranceHud/Music/WindowsSessionSource.cs new file mode 100644 index 0000000..04f76f5 --- /dev/null +++ b/VibranceHud/Music/WindowsSessionSource.cs @@ -0,0 +1,59 @@ +using System; +using System.Threading; + +namespace VibranceHud.Music; + +internal sealed class WindowsSessionSource : INowPlayingSource +{ + private readonly INowPlayingSource _windows; + + private readonly INowPlayingSource _spotify; + + public bool NeedsWorker => true; + + internal WindowsSessionSource(INowPlayingSource? windows = null, INowPlayingSource? spotify = null) + { + _windows = windows ?? new GsmtcSource(); + _spotify = spotify ?? new SpotifyWindowTitleSource(); + } + + public NowPlaying? Read() + { + return Read(CancellationToken.None); + } + + public NowPlaying? Read(CancellationToken cancellation) + { + try + { + return _windows.Read(cancellation); + } + catch (OperationCanceledException) + { + return null; + } + catch + { + try + { + return _spotify.Read(cancellation); + } + catch + { + return null; + } + } + } + + public bool TryCommand(MediaKey key) + { + try + { + return _windows.TryCommand(key); + } + catch + { + return false; + } + } +} diff --git a/VibranceHud/MusicMiniWindow.cs b/VibranceHud/MusicMiniWindow.cs new file mode 100644 index 0000000..dea8115 --- /dev/null +++ b/VibranceHud/MusicMiniWindow.cs @@ -0,0 +1,203 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; +using VibranceHud.Controls; +using VibranceHud.Design; +using VibranceHud.Music; + +namespace VibranceHud; + +internal sealed class MusicMiniWindow : SignalDialogWindow +{ + private const int W = 340; + + private const int H = 96; + + private const int Pad = 14; + + private const int ButtonSide = 26; + + private readonly MusicPoller _poller; + + private readonly MediaGlyphButton[] _buttons; + + private readonly AppSettings? _settings; + + private readonly Action? _savePosition; + + internal const string NothingPlaying = "Nothing playing"; + + internal NowPlaying? Showing { get; private set; } + + internal string SongText => Showing?.Title ?? ""; + + internal string ArtistText => Showing?.Artist ?? "Nothing playing"; + + protected override bool ShowWithoutActivation => true; + + internal MusicMiniWindow(INowPlayingSource source, IMediaKeys keys, AppSettings? settings = null, Action? savePosition = null) + { + MusicMiniWindow musicMiniWindow = this; + _settings = settings; + _savePosition = savePosition; + _poller = MusicPoller.For(source); + StartPosition = FormStartPosition.Manual; + Text = "PlexusX music"; + AccessibleRole = AccessibleRole.Window; + ClientSize = new Size(S(340), S(96)); + TopMost = true; + VibranceHud.Controls.CaptionButton captionButton = new VibranceHud.Controls.CaptionButton(VibranceHud.Controls.CaptionButton.Kind.Close) + { + Size = new Size(S(32), S(32)), + Location = new Point(ClientSize.Width - S(32), 0) + }; + captionButton.Click += (object? _, EventArgs _) => + { + musicMiniWindow.Hide(); + }; + Controls.Add(captionButton); + _buttons = new MediaGlyphButton[3] + { + new MediaGlyphButton(MediaKey.Previous), + new MediaGlyphButton(MediaKey.PlayPause), + new MediaGlyphButton(MediaKey.Next) + }; + int num = ClientSize.Width - S(14) - 3 * S(26); + MediaGlyphButton[] buttons = _buttons; + foreach (MediaGlyphButton button in buttons) + { + button.Bounds = new Rectangle(num, ClientSize.Height - S(36), S(26), S(26)); + button.Click += (object? _, EventArgs _) => + { + musicMiniWindow._poller.Command(button.Key, keys); + }; + Controls.Add(button); + num += S(26); + } + Rectangle rectangle = Screen.PrimaryScreen?.WorkingArea ?? new Rectangle(0, 0, 1280, 720); + int? num3 = settings?.MusicMiniX; + Point point; + if (num3.HasValue) + { + int valueOrDefault = num3.GetValueOrDefault(); + num3 = settings.MusicMiniY; + if (num3.HasValue) + { + int valueOrDefault2 = num3.GetValueOrDefault(); + point = new Point(valueOrDefault, valueOrDefault2); + goto IL_0274; + } + } + point = new Point(rectangle.Right - Width - S(24), rectangle.Bottom - Height - S(24)); + goto IL_0274; + IL_0274: + Point wanted = point; + Location = Clamp(wanted, Size); + WindowDrag.Enable(this, this); + _poller.Attach(this, ShowSnapshot); + } + + internal static Point Clamp(Point wanted, Size size) + { + Rectangle workingArea = Screen.FromRectangle(new Rectangle(wanted, size)).WorkingArea; + return new Point(Math.Clamp(wanted.X, workingArea.Left, Math.Max(workingArea.Left, workingArea.Right - size.Width)), Math.Clamp(wanted.Y, workingArea.Top, Math.Max(workingArea.Top, workingArea.Bottom - size.Height))); + } + + internal void ReadNow() + { + _poller.ReadForTestOrRefresh(ShowSnapshot); + } + + private void ShowSnapshot(NowPlaying? now) + { + Showing = now; + _buttons[0].Enabled = now?.CanPrevious ?? false; + _buttons[1].Enabled = now?.CanPlayPause ?? false; + _buttons[1].IsPlaying = now?.IsPlaying ?? false; + _buttons[2].Enabled = now?.CanNext ?? false; + Invalidate(); + } + + internal void Toggle() + { + if (Visible) + { + Hide(); + } + else + { + Show(); + } + } + + protected override void OnVisibleChanged(EventArgs e) + { + base.OnVisibleChanged(e); + if (!Visible) + { + RememberPosition(); + } + } + + protected override void OnResizeEnd(EventArgs e) + { + base.OnResizeEnd(e); + RememberPosition(); + } + + private void RememberPosition() + { + if (_settings != null && IsHandleCreated && (_settings.MusicMiniX != Left || _settings.MusicMiniY != Top)) + { + _settings.MusicMiniX = Left; + _settings.MusicMiniY = Top; + _savePosition?.Invoke(); + } + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + RememberPosition(); + } + base.Dispose(disposing); + } + + protected override void OnPaint(PaintEventArgs e) + { + base.OnPaint(e); + int num = S(14); + if (Showing?.Art != null) + { + Rectangle rectangle = new Rectangle(S(14), S(14), S(56), S(56)); + using GraphicsPath clip = Glass.RoundedPath(rectangle, S(6)); + using Region region = e.Graphics.Clip; + e.Graphics.SetClip(clip); + e.Graphics.DrawImage(Showing.Art, rectangle); + e.Graphics.SetClip(region, CombineMode.Replace); + num = rectangle.Right + S(10); + } + TextFormatFlags flags = TextFormatFlags.EndEllipsis | TextFormatFlags.NoPrefix | TextFormatFlags.SingleLine; + int width = ClientSize.Width - num - S(32); + if (Showing != null) + { + TextRenderer.DrawText(e.Graphics, SongText, Fonts.BodyBold, new Rectangle(num, S(12), width, Fonts.BodyBold.Height), ControlInk.Text1, flags); + } + TextRenderer.DrawText(e.Graphics, ArtistText, Fonts.Caption, new Rectangle(num, S(14) + Fonts.BodyBold.Height, width, Fonts.Caption.Height), (Showing != null) ? ControlInk.Text2 : ControlInk.Text3, flags); + } + + protected override void OnFormClosing(FormClosingEventArgs e) + { + if (e.CloseReason == CloseReason.UserClosing) + { + e.Cancel = true; + Hide(); + } + else + { + base.OnFormClosing(e); + } + } +} diff --git a/VibranceHud/NavButton.cs b/VibranceHud/NavButton.cs new file mode 100644 index 0000000..7d1e97c --- /dev/null +++ b/VibranceHud/NavButton.cs @@ -0,0 +1,540 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; +using VibranceHud.Design; + +namespace VibranceHud; + +public sealed class NavButton : Control +{ + private sealed class NavAccessibleObject : ControlAccessibleObject + { + private readonly NavButton _owner; + + public override AccessibleStates State => (AccessibleStates)((int)(base.State | AccessibleStates.Selectable | AccessibleStates.Focusable) | (_owner._active ? 2 : 0)); + + public NavAccessibleObject(NavButton owner) + : base(owner) + { + _owner = owner; + } + } + + private bool _active; + + private readonly HoverFade _fade; + + private readonly HoverFade _press; + + public const int RowHeight = 58; + + private const int RowGap = 2; + + private const int PillW = 64; + + private const int PillRadius = 4; + + private const int IconPx = 20; + + private const int IconTopInPill = 8; + + private const int NameTopInPill = 32; + + private const int MarkerW = 3; + + private const int MarkerH = 20; + + private const int MarkerOut = 6; + + private const int FocusInset = 2; + + private const int FocusRadius = 2; + + private const int LockPx = 12; + + private const int LockInset = 4; + + public const int IconDisplay = 0; + + public const int IconProfiles = 1; + + public const int IconAccount = 3; + + public const int IconCrosshair = 5; + + public const int IconSettings = 6; + + public const int IconResolution = 7; + + public const int IconCustomize = 8; + + public const int IconMonitor = 9; + + public const int IconLibrary = 10; + + public const int IconDarkBoost = 11; + + private bool _locked; + + private float _labelOpacity = 1f; + + private static readonly PointF[] Cog = new PointF[32] + { + new PointF(15.7f, 8.47f), + new PointF(18f, 8.73f), + new PointF(18f, 11.27f), + new PointF(15.7f, 11.53f), + new PointF(15.11f, 12.95f), + new PointF(16.55f, 14.76f), + new PointF(14.76f, 16.55f), + new PointF(12.95f, 15.11f), + new PointF(11.53f, 15.7f), + new PointF(11.27f, 18f), + new PointF(8.73f, 18f), + new PointF(8.47f, 15.7f), + new PointF(7.05f, 15.11f), + new PointF(5.24f, 16.55f), + new PointF(3.45f, 14.76f), + new PointF(4.89f, 12.95f), + new PointF(4.3f, 11.53f), + new PointF(2f, 11.27f), + new PointF(2f, 8.73f), + new PointF(4.3f, 8.47f), + new PointF(4.89f, 7.05f), + new PointF(3.45f, 5.24f), + new PointF(5.24f, 3.45f), + new PointF(7.05f, 4.89f), + new PointF(8.47f, 4.3f), + new PointF(8.73f, 2f), + new PointF(11.27f, 2f), + new PointF(11.53f, 4.3f), + new PointF(12.95f, 4.89f), + new PointF(14.76f, 3.45f), + new PointF(16.55f, 5.24f), + new PointF(15.11f, 7.05f) + }; + + public int IconKind { get; init; } + + public bool Active + { + get + { + return _active; + } + set + { + if (_active != value) + { + _active = value; + Invalidate(); + if (IsHandleCreated) + { + AccessibilityNotifyClients(AccessibleEvents.StateChange, -1); + } + } + } + } + + public bool Locked + { + get + { + return _locked; + } + set + { + if (_locked != value) + { + _locked = value; + AccessibleDescription = (value ? "Comes with a plan" : null); + Invalidate(); + } + } + } + + public float LabelOpacity + { + get + { + return _labelOpacity; + } + set + { + float num; + if (value < 0f) + { + num = 0f; + } + else + { + num = ((value > 1f) ? 1f : value); + } + if (!(Math.Abs(num - _labelOpacity) < 0.004f)) + { + _labelOpacity = num; + Invalidate(); + } + } + } + + private static int NameLinePx => Fonts.Step(FontRole.Caption).LinePx; + + private bool TwoLineName => Text.Contains(" & ", StringComparison.Ordinal); + + internal Rectangle PillForTest => Pill(); + + internal Rectangle IconBoxForTest => IconBox(); + + internal Rectangle NameBoxForTest => NameBox(); + + internal bool KeyboardFocusForTest { get; set; } + + public override bool Focused + { + get + { + if (!KeyboardFocusForTest) + { + return base.Focused; + } + return true; + } + } + + protected override bool ShowFocusCues + { + get + { + if (!KeyboardFocusForTest) + { + return base.ShowFocusCues; + } + return true; + } + } + + protected override AccessibleObject CreateAccessibilityInstance() + { + return new NavAccessibleObject(this); + } + + public NavButton() + { + _fade = new HoverFade(this); + _press = new HoverFade(this); + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + Height = 58; + Cursor = Cursors.Hand; + BackColor = Color.Transparent; + TabStop = true; + SetStyle(ControlStyles.Selectable, value: true); + AccessibleRole = AccessibleRole.PageTab; + } + + private Rectangle Pill() + { + int num = Math.Min(Width, Tokens.Scale(64)); + return new Rectangle((Width - num) / 2, 0, num, Math.Max(1, Height - Tokens.Scale(2))); + } + + private Rectangle IconBox() + { + Rectangle rectangle = Pill(); + int num = Tokens.Scale(TwoLineName ? 16 : 20); + return new Rectangle(rectangle.X + (rectangle.Width - num) / 2, rectangle.Y + Tokens.Scale(TwoLineName ? 4 : 8), num, num); + } + + private Rectangle NameBox() + { + Rectangle rectangle = Pill(); + return new Rectangle(rectangle.X, rectangle.Y + Tokens.Scale(TwoLineName ? 21 : 32), rectangle.Width, Tokens.Scale(TwoLineName ? 34 : NameLinePx)); + } + + protected override void OnTextChanged(EventArgs e) + { + base.OnTextChanged(e); + AccessibleName = Text; + } + + public void PerformClick() + { + OnClick(EventArgs.Empty); + } + + protected override void OnMouseEnter(EventArgs e) + { + base.OnMouseEnter(e); + _fade.Set(hot: true); + Invalidate(); + } + + protected override void OnMouseLeave(EventArgs e) + { + base.OnMouseLeave(e); + _press.Set(hot: false); + _fade.Set(hot: false); + Invalidate(); + } + + protected override void OnGotFocus(EventArgs e) + { + base.OnGotFocus(e); + Invalidate(); + } + + protected override void OnLostFocus(EventArgs e) + { + base.OnLostFocus(e); + Invalidate(); + } + + protected override void OnMouseDown(MouseEventArgs e) + { + base.OnMouseDown(e); + Focus(); + if (e.Button == MouseButtons.Left) + { + _press.Snap(hot: true); + Invalidate(); + } + } + + protected override void OnMouseUp(MouseEventArgs e) + { + base.OnMouseUp(e); + _press.Set(hot: false); + Invalidate(); + } + + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + Keys keyCode = e.KeyCode; + if ((keyCode == Keys.Return || keyCode == Keys.Space) ? true : false) + { + e.Handled = true; + OnClick(EventArgs.Empty); + } + } + + internal void TestPressKey(Keys key) + { + OnKeyDown(new KeyEventArgs(key)); + } + + internal void TestSetHover(bool on) + { + _fade.Snap(on); + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics graphics = e.Graphics; + graphics.SmoothingMode = SmoothingMode.AntiAlias; + graphics.PixelOffsetMode = PixelOffsetMode.Half; + Rectangle rectangle = Pill(); + RectangleF rect = new RectangleF(rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height); + float radius = Tokens.ScaleF(4f); + float num = (Enabled ? _fade.Value : 0f); + float num2 = (Enabled ? _press.Value : 0f); + Color color; + if (_active) + { + color = ControlInk.Surface2; + } + else + { + Color hover = ControlInk.Hover; + color = ControlInk.Mix(ControlInk.Mix(Color.FromArgb(0, hover), hover, num), ControlInk.Pressed, num2); + } + if (color.A > 0) + { + using GraphicsPath path = Glass.RoundedPath(rect, radius); + using SolidBrush brush = new SolidBrush(color); + graphics.FillPath(brush, path); + } + if (_active) + { + int num3 = Tokens.Scale(20); + float num4 = Tokens.ScaleF(3f); + using GraphicsPath path2 = Glass.RoundedPath(new RectangleF(-1f, (float)rectangle.Y + (float)(rectangle.Height - num3) / 2f, num4, num3), num4 / 2f); + using SolidBrush brush2 = new SolidBrush(ControlInk.Accent); + graphics.FillPath(brush2, path2); + } + if (Focused && ShowFocusCues) + { + float num5 = Tokens.ScaleF(2f); + float num6 = Tokens.ScaleF(2f) + num5 / 2f; + using GraphicsPath path3 = Glass.RoundedPath(RectangleF.Inflate(rect, 0f - num6, 0f - num6), Tokens.ScaleF(2f)); + using Pen pen = new Pen(ControlInk.Focus, num5); + graphics.DrawPath(pen, path3); + } + DrawGlyph(graphics, IconBox(), _active || Math.Max(num, num2) > 0.5f); + if (_locked) + { + int num7 = Tokens.Scale(12); + int num8 = Tokens.Scale(4); + SignalIcons.Draw(graphics, SignalIcon.Lock, new RectangleF(rectangle.Right - num8 - num7, rectangle.Y + num8, num7, num7), Theme.TextFaint); + } + if (_labelOpacity > 0.02f) + { + Color color2 = ControlInk.Mix(Theme.TextDim, Theme.Text, _active ? 1f : Math.Max(num, num2)); + if (_labelOpacity < 0.99f) + { + color2 = Color.FromArgb((int)((float)(int)color2.A * _labelOpacity), color2); + } + Font caption = Fonts.Caption; + TextRenderer.DrawText(graphics, TwoLineName ? Text.Replace(" & ", "\n& ") : Text, caption, NameBox(), color2, (TextFormatFlags)(5 | (TwoLineName ? 16 : 32800) | 0x10000000 | 0x800)); + } + } + + private void DrawGlyph(Graphics g, Rectangle box, bool bright) + { + float num = (float)box.Width / 20f; + GraphicsState gstate = g.Save(); + try + { + g.TranslateTransform(box.X, box.Y); + g.ScaleTransform(num, num); + DrawIcon(g, IconKind, bright ? Theme.Text : Theme.TextDim); + } + finally + { + g.Restore(gstate); + } + } + + private static void DrawIcon(Graphics g, int kind, Color color) + { + using Pen pen = new Pen(color, 1.5f) + { + StartCap = LineCap.Round, + EndCap = LineCap.Round, + LineJoin = LineJoin.Round + }; + using SolidBrush brush = new SolidBrush(color); + switch (kind) + { + case 0: + g.DrawEllipse(pen, 3f, 3f, 14f, 14f); + g.FillPie(brush, 3f, 3f, 14f, 14f, -90f, 180f); + break; + case 10: + g.DrawPolygon(pen, new PointF[4] + { + new PointF(10f, 2.8f), + new PointF(17.2f, 6.7f), + new PointF(10f, 10.6f), + new PointF(2.8f, 6.7f) + }); + g.DrawLines(pen, new PointF[3] + { + new PointF(2.8f, 10.2f), + new PointF(10f, 14.1f), + new PointF(17.2f, 10.2f) + }); + g.DrawLines(pen, new PointF[3] + { + new PointF(2.8f, 13.6f), + new PointF(10f, 17.5f), + new PointF(17.2f, 13.6f) + }); + break; + case 7: + Screen(g, pen); + g.DrawLines(pen, new PointF[3] + { + new PointF(5.5f, 9f), + new PointF(5.5f, 6.5f), + new PointF(8f, 6.5f) + }); + g.DrawLines(pen, new PointF[3] + { + new PointF(14.5f, 9f), + new PointF(14.5f, 11.5f), + new PointF(12f, 11.5f) + }); + break; + case 9: + Screen(g, pen); + g.DrawEllipse(pen, 7.75f, 6.75f, 4.5f, 4.5f); + break; + case 8: + { + using (GraphicsPath path3 = RoundedRect(2.5f, 3.5f, 15f, 13f, 1.5f)) + { + g.DrawPath(pen, path3); + } + g.DrawLine(pen, 7.5f, 3.5f, 7.5f, 16.5f); + g.DrawLine(pen, 10.5f, 8f, 14.5f, 8f); + g.DrawLine(pen, 10.5f, 11f, 13.5f, 11f); + break; + } + case 11: + { + using GraphicsPath path2 = Crescent(); + g.DrawPath(pen, path2); + break; + } + case 5: + g.DrawEllipse(pen, 4.5f, 4.5f, 11f, 11f); + g.DrawLine(pen, 10f, 2f, 10f, 6.5f); + g.DrawLine(pen, 10f, 13.5f, 10f, 18f); + g.DrawLine(pen, 2f, 10f, 6.5f, 10f); + g.DrawLine(pen, 13.5f, 10f, 18f, 10f); + g.FillEllipse(brush, 9.1f, 9.1f, 1.8f, 1.8f); + break; + case 1: + { + using (GraphicsPath path = RoundedRect(1.5f, 6.25f, 17f, 8.25f, 4.125f)) + { + g.DrawPath(pen, path); + } + g.DrawLine(pen, 4.6f, 10.4f, 8.4f, 10.4f); + g.DrawLine(pen, 6.5f, 8.5f, 6.5f, 12.3f); + g.FillEllipse(brush, 12.6f, 8.9f, 1.8f, 1.8f); + g.FillEllipse(brush, 14.4f, 10.7f, 1.8f, 1.8f); + break; + } + case 6: + g.DrawPolygon(pen, Cog); + g.DrawEllipse(pen, 7.6f, 7.6f, 4.8f, 4.8f); + break; + default: + g.DrawEllipse(pen, 6.8f, 3.8f, 6.4f, 6.4f); + g.DrawArc(pen, 3.8f, 10.8f, 12.4f, 12.4f, 180f, 180f); + break; + } + } + + private static GraphicsPath Crescent() + { + GraphicsPath graphicsPath = new GraphicsPath(); + graphicsPath.AddArc(2.5f, 2.5f, 15f, 15f, 5f, 260f); + graphicsPath.AddArc(8.208333f, 0.1333332f, 11.666666f, 11.666666f, -143.6f, -162.8f); + graphicsPath.CloseFigure(); + return graphicsPath; + } + + private static void Screen(Graphics g, Pen pen) + { + using GraphicsPath path = RoundedRect(2.5f, 4f, 15f, 10f, 1.5f); + g.DrawPath(pen, path); + g.DrawLine(pen, 7.5f, 17f, 12.5f, 17f); + g.DrawLine(pen, 10f, 14f, 10f, 17f); + } + + private static GraphicsPath RoundedRect(float x, float y, float w, float h, float radius) + { + GraphicsPath graphicsPath = new GraphicsPath(); + float num = radius * 2f; + graphicsPath.AddArc(x, y, num, num, 180f, 90f); + graphicsPath.AddArc(x + w - num, y, num, num, 270f, 90f); + graphicsPath.AddArc(x + w - num, y + h - num, num, num, 0f, 90f); + graphicsPath.AddArc(x, y + h - num, num, num, 90f, 90f); + graphicsPath.CloseFigure(); + return graphicsPath; + } +} diff --git a/VibranceHud/NoNvidiaDisplaysException.cs b/VibranceHud/NoNvidiaDisplaysException.cs new file mode 100644 index 0000000..ef2a568 --- /dev/null +++ b/VibranceHud/NoNvidiaDisplaysException.cs @@ -0,0 +1,11 @@ +using System; + +namespace VibranceHud; + +public sealed class NoNvidiaDisplaysException : Exception +{ + public NoNvidiaDisplaysException() + : base("The NVIDIA driver is present but drives no reachable display.") + { + } +} diff --git a/VibranceHud/NullVibranceController.cs b/VibranceHud/NullVibranceController.cs new file mode 100644 index 0000000..6353114 --- /dev/null +++ b/VibranceHud/NullVibranceController.cs @@ -0,0 +1,26 @@ +namespace VibranceHud; + +public sealed class NullVibranceController : IVibranceController +{ + public int CurrentLevel => 100; + + public int DefaultLevel => 100; + + public bool IsAvailable => false; + + public VibranceDriverState DriverState { get; } + + public NullVibranceController(VibranceDriverState state = VibranceDriverState.NoNvidiaCard) + { + DriverState = state; + } + + public void SetLevel(int level) + { + } + + public bool EveryDisplayIsAt(int level) + { + return true; + } +} diff --git a/VibranceHud/NvapiDisplayAccess.cs b/VibranceHud/NvapiDisplayAccess.cs new file mode 100644 index 0000000..eb4d5c9 --- /dev/null +++ b/VibranceHud/NvapiDisplayAccess.cs @@ -0,0 +1,38 @@ +using System; +using NvAPIWrapper; +using NvAPIWrapper.Native; +using NvAPIWrapper.Native.Display.Structures; + +namespace VibranceHud; + +internal sealed class NvapiDisplayAccess : INvapiDisplayAccess +{ + private DisplayHandle[] _displays = Array.Empty(); + + public int Resolve() + { + NVIDIA.Initialize(); + _displays = DisplayApi.EnumNvidiaDisplayHandle(); + return _displays.Length; + } + + public int ReadCurrentLevel(int display) + { + return DisplayApi.GetDVCInfoEx(_displays[display]).CurrentLevel; + } + + public int ReadDefaultLevel(int display) + { + return DisplayApi.GetDVCInfoEx(_displays[display]).DefaultLevel; + } + + public string DisplayId(int display) + { + return DisplayApi.GetAssociatedNvidiaDisplayName(_displays[display]); + } + + public void WriteLevel(int display, int level) + { + DisplayApi.SetDVCLevelEx(_displays[display], level); + } +} diff --git a/VibranceHud/NvapiFallbackLog.cs b/VibranceHud/NvapiFallbackLog.cs new file mode 100644 index 0000000..4195951 --- /dev/null +++ b/VibranceHud/NvapiFallbackLog.cs @@ -0,0 +1,95 @@ +using System; +using System.Globalization; +using System.IO; +using System.Text; +using System.Windows.Forms; + +namespace VibranceHud; + +internal static class NvapiFallbackLog +{ + internal const string FileName = "nvapi-fail.log"; + + internal const string CustomModeFileName = "custom-mode.log"; + + internal static string CustomModeLine(DateTime whenUtc, string step, string status) + { + return string.Format(CultureInfo.InvariantCulture, "{0:yyyy-MM-dd HH:mm:ss} UTC NVIDIA custom resolution {1} refused: {2}.", whenUtc, step, status); + } + + internal static void NoteCustomMode(string step, string status) + { + try + { + if (ThisIsTheRealApp()) + { + string crashDirectory = CrashLog.CrashDirectory; + if (!string.IsNullOrEmpty(crashDirectory)) + { + File.AppendAllText(Path.Combine(crashDirectory, "custom-mode.log"), CrashLog.Redact(CustomModeLine(DateTime.UtcNow, step, status)) + Environment.NewLine, Encoding.UTF8); + } + } + } + catch + { + } + } + + internal static string CustomModeStepLine(DateTime whenUtc, string what, string status) + { + return string.Format(CultureInfo.InvariantCulture, "{0:yyyy-MM-dd HH:mm:ss} UTC custom resolution {1}: {2}", whenUtc, what, status); + } + + internal static void NoteCustomModeStep(string what, string status) + { + try + { + if (ThisIsTheRealApp()) + { + string crashDirectory = CrashLog.CrashDirectory; + if (!string.IsNullOrEmpty(crashDirectory)) + { + File.AppendAllText(Path.Combine(crashDirectory, "custom-mode.log"), CrashLog.Redact(CustomModeStepLine(DateTime.UtcNow, what, status)) + Environment.NewLine, Encoding.UTF8); + } + } + } + catch + { + } + } + + internal static string Line(DateTime whenUtc, Exception cause) + { + return string.Format(CultureInfo.InvariantCulture, "{0:yyyy-MM-dd HH:mm:ss} UTC NVIDIA stopped answering ({1}: {2}). Re-resolving the display handles did not help, so vibrance continues in software for the rest of this session.", whenUtc, cause?.GetType().Name ?? "unknown", cause?.Message ?? "no message"); + } + + internal static void Note(Exception cause) + { + try + { + if (ThisIsTheRealApp()) + { + string crashDirectory = CrashLog.CrashDirectory; + if (!string.IsNullOrEmpty(crashDirectory)) + { + File.AppendAllText(Path.Combine(crashDirectory, "nvapi-fail.log"), CrashLog.Redact(Line(DateTime.UtcNow, cause)) + Environment.NewLine, Encoding.UTF8); + } + } + } + catch + { + } + } + + private static bool ThisIsTheRealApp() + { + try + { + return string.Equals(Path.GetFileName(Application.ExecutablePath), "PlexusX.exe", StringComparison.OrdinalIgnoreCase); + } + catch + { + return false; + } + } +} diff --git a/VibranceHud/Onboarding/Complaint.cs b/VibranceHud/Onboarding/Complaint.cs new file mode 100644 index 0000000..5977931 --- /dev/null +++ b/VibranceHud/Onboarding/Complaint.cs @@ -0,0 +1,10 @@ +namespace VibranceHud.Onboarding; + +public enum Complaint +{ + None, + TooDark, + WashedOut, + EyeStrain, + FlatRecordings +} diff --git a/VibranceHud/Onboarding/DemoEngine.cs b/VibranceHud/Onboarding/DemoEngine.cs new file mode 100644 index 0000000..8e51a16 --- /dev/null +++ b/VibranceHud/Onboarding/DemoEngine.cs @@ -0,0 +1,71 @@ +using System; + +namespace VibranceHud.Onboarding; + +public static class DemoEngine +{ + internal sealed class NeverTouchesGamma : IGammaRamp + { + public void Apply(ushort[] ramp) + { + throw new InvalidOperationException("The first-run demonstration must never write a gamma ramp. Windows does not restore ramps when a process dies, so a crash mid-demo would leave a stranger's monitor altered with no PlexusX behind it. Everything the demo shows goes through the colour matrix, which dies with the process."); + } + + public void Reset() + { + } + } + + public readonly record struct Built(VibranceEngine? Engine, ISaturationOverlay? Overlay); + + public static Built TryBuild(Func overlay, Func driver, Action log) + { + if (overlay == null) + { + throw new ArgumentNullException("overlay"); + } + if (driver == null) + { + throw new ArgumentNullException("driver"); + } + ISaturationOverlay saturationOverlay = null; + try + { + saturationOverlay = overlay(); + return new Built(Create(saturationOverlay, driver().DriverState), saturationOverlay); + } + catch (Exception obj) + { + try + { + log?.Invoke(obj); + } + catch + { + } + if (saturationOverlay is IDisposable disposable) + { + try + { + disposable.Dispose(); + } + catch + { + } + } + return default; + } + } + + public static VibranceEngine Create(ISaturationOverlay overlay, VibranceDriverState driverState) + { + if (overlay == null) + { + throw new ArgumentNullException("overlay"); + } + return new VibranceEngine(new NullVibranceController(driverState), overlay, new NeverTouchesGamma()) + { + PaidControlsUnlocked = true + }; + } +} diff --git a/VibranceHud/Onboarding/DemoGrades.cs b/VibranceHud/Onboarding/DemoGrades.cs new file mode 100644 index 0000000..457f98d --- /dev/null +++ b/VibranceHud/Onboarding/DemoGrades.cs @@ -0,0 +1,64 @@ +using System; +using System.Linq; + +namespace VibranceHud.Onboarding; + +public static class DemoGrades +{ + public readonly record struct Grade(int Saturation, int Vibrance, int Brightness, int Contrast, int Temperature) + { + public void ApplyTo(VibranceEngine engine) + { + if (engine == null) + { + throw new ArgumentNullException("engine"); + } + engine.Saturation = Saturation; + engine.Vibrance = Vibrance; + engine.Brightness = Brightness; + engine.Contrast = Contrast; + engine.Temperature = Temperature; + } + } + + private const int UntouchedVibrance = 50; + + public static Grade Opening => new Grade(205, 100, 100, 104, -6); + + public static Grade ForGame(string? game) + { + if (string.IsNullOrWhiteSpace(game) || game == "Something else") + { + return Opening; + } + if (!SetupAnswers.Games.Any((string g) => string.Equals(g, game, StringComparison.OrdinalIgnoreCase))) + { + return Opening; + } + return new Grade(SetupAnswers.SaturationFor(game), 50, 100, 100, 0); + } + + public static Grade ForComplaint(Complaint complaint) + { + return complaint switch + { + Complaint.WashedOut => new Grade(245, 100, 100, 110, -8), + Complaint.TooDark => new Grade(215, 100, 108, 92, -12), + Complaint.EyeStrain => new Grade(150, 90, 96, 98, 18), + Complaint.FlatRecordings => new Grade(230, 100, 100, 104, -6), + _ => Opening, + }; + } + + public static string AnswerLine(Complaint complaint, VibranceDriverState driver) + { + return complaint switch + { + Complaint.WashedOut => "More colour and more separation between shades. Grey stops being one shade of grey.", + Complaint.TooDark => "The dark end opened up and contrast eased off, so shade stops being a solid mass.", + Complaint.EyeStrain => "Warmer, and less colour rather than more. This one asks for less - it is the only setting here that does.", + Complaint.FlatRecordings => (driver == VibranceDriverState.Available) ? "Digital Vibrance is added after the picture is put together, so no recorder ever sees it. Everything PlexusX just did is in the picture itself, which is why a recording keeps it." : "All of this is in the picture itself, so what you record is what you see.", + _ => "", + }; + } +} diff --git a/VibranceHud/Onboarding/Pricing.cs b/VibranceHud/Onboarding/Pricing.cs new file mode 100644 index 0000000..7f3fd2d --- /dev/null +++ b/VibranceHud/Onboarding/Pricing.cs @@ -0,0 +1,16 @@ +namespace VibranceHud.Onboarding; + +public static class Pricing +{ + public const string MonthlyPlan = "monthly"; + + public const string LifetimePlan = "lifetime"; + + public const string MonthlyPrice = "€4.99"; + + public const string LifetimePrice = "€15.99"; + + public const string MonthlyLabel = "€4.99 / month"; + + public const string LifetimeLabel = "€15.99 once"; +} diff --git a/VibranceHud/Onboarding/SetupAnswers.cs b/VibranceHud/Onboarding/SetupAnswers.cs new file mode 100644 index 0000000..ef8317e --- /dev/null +++ b/VibranceHud/Onboarding/SetupAnswers.cs @@ -0,0 +1,101 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace VibranceHud.Onboarding; + +public sealed class SetupAnswers +{ + public const string OtherGame = "Something else"; + + private static readonly string[] TunedGames = new string[6] { "Rust", "CS2", "Fortnite", "PUBG", "Valorant", "Rainbow Six Siege" }; + + private const int CalmSaturation = 100; + + public static IReadOnlyList Games => TunedGames.Concat(new string[1] { "Something else" }).ToList(); + + public string Game { get; set; } = ""; + + public Complaint Complaint { get; set; } + + public bool WantsCrosshair { get; set; } + + public int SeededSaturation + { + get + { + if (Complaint != Complaint.EyeStrain) + { + return SaturationFor(Game); + } + return 100; + } + } + + public static int SaturationFor(string? game) + { + if (string.Equals(game, "Valorant", StringComparison.OrdinalIgnoreCase)) + { + return 145; + } + if (string.Equals(game, "Rainbow Six Siege", StringComparison.OrdinalIgnoreCase)) + { + return 160; + } + if (string.Equals(game, "Fortnite", StringComparison.OrdinalIgnoreCase)) + { + return 175; + } + if (string.Equals(game, "Rust", StringComparison.OrdinalIgnoreCase)) + { + return 190; + } + if (string.Equals(game, "CS2", StringComparison.OrdinalIgnoreCase)) + { + return 220; + } + if (string.Equals(game, "PUBG", StringComparison.OrdinalIgnoreCase)) + { + return 235; + } + return DemoGrades.Opening.Saturation; + } + + public void ApplyTo(AppSettings settings) + { + if (settings == null) + { + throw new ArgumentNullException("settings"); + } + settings.FavoriteGame = Game ?? ""; + settings.CrosshairEnabled = WantsCrosshair; + settings.EyeCare = Complaint == Complaint.EyeStrain; + settings.StreamingMode = Complaint == Complaint.FlatRecordings; + settings.SaturationPercent = SeededSaturation; + } + + public string Headline() + { + if (!string.IsNullOrWhiteSpace(Game) && !(Game == "Something else")) + { + return "Your " + Game + " setup is ready"; + } + return "Your setup is ready"; + } + + public IEnumerable WhatWasSetUp() + { + if (!string.IsNullOrWhiteSpace(Game) && Game != "Something else") + { + yield return Game + " presets"; + } + if (Complaint == Complaint.EyeStrain) + { + yield return "Eye care, to take the edge off long sessions"; + } + if (WantsCrosshair) + { + yield return "Crosshair overlay"; + } + } +} diff --git a/VibranceHud/Onboarding/WizardChrome.cs b/VibranceHud/Onboarding/WizardChrome.cs new file mode 100644 index 0000000..b3db362 --- /dev/null +++ b/VibranceHud/Onboarding/WizardChrome.cs @@ -0,0 +1,35 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; +using VibranceHud.Controls; +using VibranceHud.Design; + +namespace VibranceHud.Onboarding; + +internal static class WizardChrome +{ + internal const int Radius = 8; + + internal const int Border = 1; + + internal static void Shape(Form form) + { + using GraphicsPath path = Glass.RoundedPath(new RectangleF(0f, 0f, form.Width + 1, form.Height + 1), Tokens.Scale(8)); + form.Region = new Region(path); + } + + internal static void PaintRim(Graphics g, Form form) + { + SmoothingMode smoothingMode = g.SmoothingMode; + PixelOffsetMode pixelOffsetMode = g.PixelOffsetMode; + g.SmoothingMode = SmoothingMode.AntiAlias; + g.PixelOffsetMode = PixelOffsetMode.Half; + float num = 0.5f; + using GraphicsPath path = Glass.RoundedPath(new RectangleF(num, num, (float)form.Width - num * 2f, (float)form.Height - num * 2f), Math.Max(1f, (float)Tokens.Scale(8) - num)); + using Pen pen = new Pen(SignalDialogWindow.EdgeInk, 1f); + g.DrawPath(pen, path); + g.SmoothingMode = smoothingMode; + g.PixelOffsetMode = pixelOffsetMode; + } +} diff --git a/VibranceHud/OnboardingForm.cs b/VibranceHud/OnboardingForm.cs new file mode 100644 index 0000000..1374b94 --- /dev/null +++ b/VibranceHud/OnboardingForm.cs @@ -0,0 +1,947 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Text; +using System.Windows.Forms; +using VibranceHud.Controls; +using VibranceHud.Design; +using VibranceHud.Onboarding; + +namespace VibranceHud; + +public sealed class OnboardingForm : Form +{ + internal sealed class GameRow : Control + { + private bool _active; + + private readonly HoverFade _fade; + + private const int PadX = 12; + + public bool Active + { + get + { + return _active; + } + set + { + if (_active != value) + { + _active = value; + Invalidate(); + } + } + } + + public GameRow() + { + _fade = new HoverFade(this); + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Theme.Background; + Cursor = Cursors.Hand; + TabStop = true; + SetStyle(ControlStyles.Selectable, value: true); + AccessibleRole = AccessibleRole.RadioButton; + } + + protected override void OnTextChanged(EventArgs e) + { + base.OnTextChanged(e); + AccessibleName = Text; + } + + protected override void OnGotFocus(EventArgs e) + { + base.OnGotFocus(e); + Invalidate(); + } + + protected override void OnLostFocus(EventArgs e) + { + base.OnLostFocus(e); + Invalidate(); + } + + protected override void OnMouseEnter(EventArgs e) + { + base.OnMouseEnter(e); + _fade.Set(hot: true); + Invalidate(); + } + + protected override void OnMouseLeave(EventArgs e) + { + base.OnMouseLeave(e); + _fade.Set(hot: false); + Invalidate(); + } + + protected override void OnMouseDown(MouseEventArgs e) + { + base.OnMouseDown(e); + Focus(); + } + + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + Keys keyCode = e.KeyCode; + if ((keyCode == Keys.Return || keyCode == Keys.Space) ? true : false) + { + e.Handled = true; + OnClick(EventArgs.Empty); + } + } + + internal void TestPressKey(Keys key) + { + OnKeyDown(new KeyEventArgs(key)); + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics graphics = e.Graphics; + graphics.SmoothingMode = SmoothingMode.AntiAlias; + PixelOffsetMode pixelOffsetMode = graphics.PixelOffsetMode; + graphics.PixelOffsetMode = PixelOffsetMode.Half; + int dpi = SignalInk.DpiFor(this); + using (GraphicsPath path = Glass.RoundedPath(new RectangleF(0.5f, 0.5f, Width - 1, Height - 1), Sc(4))) + { + if (_active) + { + using SolidBrush brush = new SolidBrush(Theme.Accent); + graphics.FillPath(brush, path); + } + else if (_fade.Value > 0.01f) + { + using SolidBrush brush2 = new SolidBrush(Theme.SurfaceHover); + graphics.FillPath(brush2, path); + using Pen pen = new Pen(Theme.GlassEdge, 1f); + graphics.DrawPath(pen, path); + } + else + { + using Pen pen2 = new Pen(Theme.GlassEdge, 1f); + graphics.DrawPath(pen2, path); + } + } + Color foreColor = (_active ? Theme.OnAccent : Theme.Text); + Font font = (_active ? Fonts.BodyBold : Fonts.Body); + int num = Sc(12); + TextRenderer.DrawText(graphics, Text, font, new Rectangle(num, 0, Math.Max(1, Width - num * 2), Height), foreColor, TextFormatFlags.EndEllipsis | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding); + graphics.PixelOffsetMode = pixelOffsetMode; + if (Focused && ShowFocusCues) + { + UiHelpers.DrawFocusRing(graphics, ClientRectangle, Sc(4)); + } + int Sc(int v) + { + return Tokens.ScaleAt(dpi, v); + } + } + } + + private const int WindowW = 680; + + private const int WindowH = 520; + + private const int HeaderH = 40; + + private const int HeaderPadX = 16; + + private const int MarkSize = 20; + + private const int MarkInk = 19; + + private const int MarkGap = 4; + + private const int CloseCellW = 46; + + private const int Gutter = 24; + + private const int ContentTop = 56; + + private const int DashW = 20; + + private const int DashH = 2; + + private const int DashGap = 4; + + private const int DashLead = 10; + + private const int TitleGap = 8; + + private const int SubGap = 4; + + private const int GridGap = 20; + + private const int TitleInkLift = 2; + + private const int SubInkLift = 1; + + private const int RowW = 212; + + private const int RowH = 40; + + private const int RowGap = 8; + + private const int ColGap = 24; + + private const int RightW = 396; + + private const int SplitH = 216; + + private const int CaptionGap = 8; + + private const int BoldGap = 10; + + private const int FooterH = 64; + + private const int ButtonH = 32; + + private const int ButtonPadX = 12; + + private const int SeamW = 2; + + private const int HandleSize = 36; + + private const int HandleMark = 20; + + private const int ChipInset = 8; + + private const int ChipH = 24; + + private const int ChipPadX = 8; + + private const int ChipRadius = 4; + + private readonly Timer _timer; + + private DateTime _last = DateTime.UtcNow; + + private float _reveal; + + private int _step; + + private readonly AppSettings _settings; + + private readonly SettingsStore _store; + + private readonly GlassButton _primary; + + private readonly GlassButton _back; + + private readonly GlassButton _skip; + + private readonly List _gameRows = new List(); + + private readonly List _complaintChips = new List(); + + private readonly SetupAnswers _answers = new SetupAnswers(); + + private string _favoriteGame = ""; + + private readonly int _dpi; + + private readonly int _stepLine; + + private readonly int _titleTop; + + private readonly int _titleLine; + + private readonly int _subTop; + + private readonly int _subLine; + + private readonly int _gridTop; + + private readonly int _footerRuleY; + + private readonly int _buttonTop; + + private readonly int _rightX; + + private readonly int _contentW; + + private readonly int _splitH; + + private readonly VibranceEngine? _demo; + + private string _demoLine = ""; + + private const int LastStep = 2; + + private const int CountedSteps = 2; + + private const string GameTitle = "Which game do you play most?"; + + private const string GameSubtitle = "We'll start you on its presets. You can change it any time."; + + private const string ComplaintTitle = "What do you want it to fix?"; + + private const string ComplaintSubtitle = "Pick one - your screen changes to match."; + + private const string SampleFrameLine = "A sample scene. Pick a game to see its look on your screen."; + + private const string NeverTouchesLine = "Changes what your monitor shows, never touches the game."; + + private const string WelcomeTitle = "Welcome to PlexusX"; + + private const string WelcomeLead = "Let's set it up."; + + private const string UnknownCaptureLine = "Settings shows whether your recordings get your colours."; + + private readonly string[] _welcomeLines; + + private readonly Rectangle[] _welcomeBands = new Rectangle[4]; + + internal static IReadOnlyList WelcomeLines => WelcomeLinesWith("Settings shows whether your recordings get your colours."); + + internal IReadOnlyList WelcomeLinesShownForTest => _welcomeLines; + + internal Rectangle[] WelcomeBandsForTest => (Rectangle[])_welcomeBands.Clone(); + + internal static int CountedStepCount => 2; + + internal static string SampleLine => "A sample scene. Pick a game to see its look on your screen."; + + private static Font TitleFont => Fonts.Display; + + private static Font SubFont => Fonts.Body; + + private static Font StepFont => Fonts.Caption; + + private static Font CaptionFont => Fonts.Caption; + + private static Font BrandFont => Fonts.Title; + + internal bool BackVisibleForTest => _back.Visible; + + internal static int StepCount => 3; + + internal bool ShouldDemonstrate => _demo?.ScreenEffectIsLive ?? false; + + private static string CaptureLineFor(OverlayMode overlay, bool driverVibranceAvailable, bool streamingMode) + { + return CaptureStatus.Headline(CaptureStatus.Resolve(overlay, driverVibranceAvailable, streamingMode)); + } + + internal static IReadOnlyList WelcomeLinesFor(OverlayMode overlay, bool driverVibranceAvailable, bool streamingMode) + { + return WelcomeLinesWith(CaptureLineFor(overlay, driverVibranceAvailable, streamingMode)); + } + + private static string[] WelcomeLinesWith(string captureLine) + { + return new string[4] { "Welcome to PlexusX", "Sharper colours. Every game.", "Let's set it up.", captureLine }; + } + + private int S(int logical) + { + return Tokens.ScaleAt(_dpi, logical); + } + + public OnboardingForm(AppSettings settings, SettingsStore store, VibranceEngine? demo = null) + { + _settings = settings; + _store = store; + _demo = demo; + _dpi = SignalInk.DpiFor(this); + _welcomeLines = ((demo == null) ? WelcomeLinesWith("Settings shows whether your recordings get your colours.") : WelcomeLinesWith(CaptureLineFor(settings.OverlayMode, demo.DriverAvailable, settings.StreamingMode))); + FormBorderStyle = FormBorderStyle.None; + StartPosition = FormStartPosition.CenterScreen; + ShowInTaskbar = true; + Text = "Welcome to PlexusX"; + ClientSize = new Size(S(680), S(520)); + BackColor = Theme.Background; + DoubleBuffered = true; + KeyPreview = true; + Icon = AppIcon.Value; + Font = Fonts.Body; + _contentW = ClientSize.Width - 2 * S(24); + _rightX = S(24) + S(212) + S(24); + _footerRuleY = ClientSize.Height - S(64); + _buttonTop = _footerRuleY + (S(64) - S(32)) / 2 + 1; + _stepLine = LineBox("Step 1 of 2", StepFont, _contentW, S(16)); + _titleLine = Math.Max(LineBox("Which game do you play most?", TitleFont, _contentW, S(36)), LineBox("What do you want it to fix?", TitleFont, _contentW, S(36))); + _subLine = Math.Max(LineBox("We'll start you on its presets. You can change it any time.", SubFont, _contentW, S(20)), LineBox("Pick one - your screen changes to match.", SubFont, _contentW, S(20))); + int num = S(56) + _stepLine + S(8); + _titleTop = num - S(2); + _subTop = num + _titleLine + S(4) - S(1); + _gridTop = _subTop + S(1) + _subLine + S(20); + int count = SetupAnswers.Games.Count; + int val = _gridTop + count * S(40) + (count - 1) * S(8) + S(8) + S(64); + ClientSize = new Size(S(680), Math.Max(S(520), val)); + _footerRuleY = ClientSize.Height - S(64); + _buttonTop = _footerRuleY + (S(64) - S(32)) / 2 + 1; + int num2 = _gridTop + S(216) + S(8) + FlowHeight("A sample scene. Pick a game to see its look on your screen.", CaptionFont, S(396)) + S(10) + FlowHeight("Changes what your monitor shows, never touches the game.", SubFont, S(396)); + _splitH = S(216) - Math.Max(0, num2 - (_footerRuleY - S(2))); + VibranceHud.Controls.CaptionButton captionButton = new VibranceHud.Controls.CaptionButton(VibranceHud.Controls.CaptionButton.Kind.Close) + { + Location = new Point(ClientSize.Width - S(46), 0), + Size = new Size(S(46), S(40)), + AccessibleName = "Close setup" + }; + captionButton.Click += (object? s, EventArgs e) => + { + SkipForNow(); + }; + Controls.Add(captionButton); + IReadOnlyList games = SetupAnswers.Games; + int num3 = _gridTop; + foreach (string name in games) + { + GameRow row = new GameRow + { + Text = name, + Location = new Point(S(24), num3), + Size = new Size(S(212), S(40)), + Visible = false + }; + row.Click += (object? s, EventArgs e) => + { + _favoriteGame = name; + _answers.Game = name; + foreach (GameRow gameRow in _gameRows) + { + gameRow.Active = gameRow == row; + } + ShowOnTheirScreen(DemoGrades.ForGame(name)); + _demoLine = MachineLine(); + Invalidate(invalidateChildren: true); + }; + _gameRows.Add(row); + Controls.Add(row); + num3 += S(40) + S(8); + } + (string, Complaint)[] array = new (string, Complaint)[4] + { + ("Everything looks grey and flat", Complaint.WashedOut), + ("I lose people in dark corners", Complaint.TooDark), + ("My recordings look flatter than my screen", Complaint.FlatRecordings), + ("My eyes ache after a long session", Complaint.EyeStrain) + }; + for (int num4 = 0; num4 < array.Length; num4++) + { + (string, Complaint) tuple = array[num4]; + string item = tuple.Item1; + Complaint value = tuple.Item2; + GameRow chip = new GameRow + { + Text = item, + Size = new Size(_contentW, S(40)), + Location = new Point(S(24), _gridTop + num4 * (S(40) + S(8))), + Visible = false + }; + chip.Click += (object? s, EventArgs e) => + { + _answers.Complaint = value; + foreach (GameRow complaintChip in _complaintChips) + { + complaintChip.Active = complaintChip == chip; + } + ShowOnTheirScreen(DemoGrades.ForComplaint(value)); + _demoLine = DemoGrades.AnswerLine(value, DriverState()); + Invalidate(invalidateChildren: true); + }; + _complaintChips.Add(chip); + Controls.Add(chip); + } + _primary = new GlassButton + { + Text = "Continue", + Kind = GlassButtonKind.Primary + }; + _primary.Click += (object? s, EventArgs e) => + { + Advance(); + }; + Controls.Add(_primary); + int num5 = S(8); + int width = TextRenderer.MeasureText("Skip for now", Fonts.BodyBold, Size.Empty, TextFormatFlags.SingleLine | TextFormatFlags.NoPadding).Width + 2 * num5; + int width2 = TextRenderer.MeasureText("Back", Fonts.BodyBold, Size.Empty, TextFormatFlags.SingleLine | TextFormatFlags.NoPadding).Width + 2 * num5; + _skip = new GlassButton + { + Text = "Skip for now", + Kind = GlassButtonKind.Quiet, + Location = new Point(S(24) - num5, _buttonTop), + Size = new Size(width, S(32)) + }; + _skip.Click += (object? s, EventArgs e) => + { + SkipForNow(); + }; + Controls.Add(_skip); + _back = new GlassButton + { + Text = "Back", + AccessibleName = "Back", + Kind = GlassButtonKind.Quiet, + Location = new Point(_skip.Right + S(8), _buttonTop), + Size = new Size(width2, S(32)), + Visible = false + }; + _back.Click += (object? s, EventArgs e) => + { + ShowStep(_step - 1); + }; + Controls.Add(_back); + int tabIndex = 0; + foreach (GameRow gameRow2 in _gameRows) + { + gameRow2.TabIndex = tabIndex++; + } + foreach (GameRow complaintChip2 in _complaintChips) + { + complaintChip2.TabIndex = tabIndex++; + } + _skip.TabIndex = tabIndex++; + _back.TabIndex = tabIndex++; + _primary.TabIndex = tabIndex; + WindowDrag.Enable(this, this); + WizardChrome.Shape(this); + _timer = new Timer + { + Interval = 33 + }; + _timer.Tick += OnTick; + _timer.Start(); + ShowStep(0); + ActiveControl = _primary; + } + + private static int FlowHeight(string text, Font font, int width) + { + return TextRenderer.MeasureText(text, font, new Size(width, int.MaxValue), TextFormatFlags.WordBreak | TextFormatFlags.NoPadding).Height; + } + + private static int LineBox(string text, Font font, int width, int designLine) + { + int num = FlowHeight(text, font, width); + int num2 = Math.Max(1, (int)Math.Round((double)num / (double)Math.Max(1, font.Height))); + if (num2 != 1) + { + return num2 * font.Height; + } + return designLine; + } + + protected override bool ProcessCmdKey(ref Message msg, Keys keyData) + { + if (keyData == Keys.Escape) + { + SkipForNow(); + return true; + } + bool flag = keyData == Keys.Return; + if (flag) + { + Control activeControl = ActiveControl; + bool flag2 = ((activeControl is GlassButton || activeControl is ChipButton || activeControl is GameRow || activeControl is Button) ? true : false); + flag = !flag2; + } + if (flag && _primary.Enabled) + { + Advance(); + return true; + } + return base.ProcessCmdKey(ref msg, keyData); + } + + private void SkipForNow() + { + _settings.OnboardingComplete = true; + _store.Save(_settings); + DialogResult = DialogResult.OK; + Close(); + } + + private void OnTick(object? sender, EventArgs e) + { + DateTime utcNow = DateTime.UtcNow; + double num = Math.Min((utcNow - _last).TotalSeconds, 0.1); + _last = utcNow; + if (_reveal < 1f) + { + _reveal = Math.Min(1f, _reveal + (float)(num / 1.1)); + } + Invalidate(invalidateChildren: true); + } + + private void Advance() + { + if (_step == 2) + { + _answers.ApplyTo(_settings); + } + if (_step == 0 && !ShouldDemonstrate) + { + Finish(); + } + else if (_step < 2) + { + ShowStep(_step + 1); + } + else + { + Finish(); + } + } + + internal void ShowStepForTest(int step) + { + ShowStep(step); + } + + private void ShowStep(int step) + { + _step = Math.Max(0, step); + bool visible = _step == 1; + bool visible2 = _step == 2; + foreach (GameRow gameRow in _gameRows) + { + gameRow.Visible = visible; + } + foreach (GameRow complaintChip in _complaintChips) + { + complaintChip.Visible = visible2; + } + _back.Visible = _step > 0; + GlassButton primary = _primary; + primary.Text = _step switch + { + 0 => "Get started", + 2 => "See what it costs", + _ => "Continue", + }; + int num = TextRenderer.MeasureText(_primary.Text, Fonts.BodyBold).Width + 2 * S(12); + _primary.Size = new Size(num, S(32)); + _primary.Location = new Point(ClientSize.Width - S(24) - num, _buttonTop); + _skip.Visible = true; + Invalidate(invalidateChildren: true); + } + + private void ShowOnTheirScreen(DemoGrades.Grade grade) + { + if (_demo == null) + { + return; + } + try + { + grade.ApplyTo(_demo); + } + catch (Exception ex) + { + try + { + CrashLog.Write(ex); + } + catch + { + } + } + } + + private VibranceDriverState DriverState() + { + return _demo?.DriverState ?? VibranceDriverState.NoNvidiaCard; + } + + private string MachineLine() + { + int value = _demo?.Saturation ?? DemoGrades.Opening.Saturation; + return DriverState() switch + { + VibranceDriverState.Available => $"Vibrance in the NVIDIA panel stops at {100}. PlexusX takes vibrance to {350} and saturation to {300} - your screen is at {value} now.", + VibranceDriverState.DisplayNotOnNvidia => "Your NVIDIA card isn't driving this screen, so PlexusX does it instead.", + _ => "Your graphics card has no vibrance control, so PlexusX does it itself - your " + $"screen is at {value} now, and saturation goes to {300}.", + }; + } + + private void Finish() + { + _answers.Game = _favoriteGame; + _answers.ApplyTo(_settings); + _settings.OnboardingComplete = true; + _store.Save(_settings); + DialogResult = DialogResult.OK; + Close(); + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics graphics = e.Graphics; + graphics.SmoothingMode = SmoothingMode.AntiAlias; + using (SolidBrush brush = new SolidBrush(Theme.Background)) + { + graphics.FillRectangle(brush, ClientRectangle); + } + graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; + DrawHeader(graphics); + if (_step == 0) + { + PaintWelcome(graphics); + } + else if (_step == 1) + { + PaintGameQuestion(graphics); + } + else if (_step == 2) + { + PaintComplaintQuestion(graphics); + } + PixelOffsetMode pixelOffsetMode = graphics.PixelOffsetMode; + graphics.PixelOffsetMode = PixelOffsetMode.Half; + using (SolidBrush brush2 = new SolidBrush(Theme.Border)) + { + graphics.FillRectangle(brush2, 0, _footerRuleY, ClientSize.Width, 1); + } + graphics.PixelOffsetMode = pixelOffsetMode; + if (_reveal < 1f) + { + using SolidBrush brush3 = new SolidBrush(Color.FromArgb((int)(255f * (1f - _reveal)), Theme.Background)); + graphics.FillRectangle(brush3, ClientRectangle); + } + WizardChrome.PaintRim(graphics, this); + base.OnPaint(e); + } + + private void DrawHeader(Graphics g) + { + int num = S(40); + int num2 = S(20); + int num3 = S(19); + Rectangle r = new Rectangle(S(16) + (num2 - num3) / 2, (num - num3) / 2, num3, num3); + using (SolidBrush brush = new SolidBrush(Theme.Accent)) + { + g.FillPolygon(brush, StarPoints(r)); + } + int num4 = S(16) + num2 + S(4); + TextRenderer.DrawText(g, "PlexusX", BrandFont, new Rectangle(num4, SignalInk.TopForBaseline(g, BrandFont, 0, num) - S(1), ClientSize.Width - num4, BrandFont.Height), Theme.Text, TextFormatFlags.NoPadding); + } + + private void PaintWelcome(Graphics g) + { + string[] welcomeLines = _welcomeLines; + int y = _titleTop; + Band(0, y, FlowHeight(welcomeLines[0], TitleFont, _contentW)); + DrawFlow(g, welcomeLines[0], TitleFont, Theme.Text, S(24), ref y, _contentW, S(4)); + Band(1, y, FlowHeight(welcomeLines[1], SubFont, _contentW)); + DrawFlow(g, welcomeLines[1], SubFont, Theme.TextDim, S(24), ref y, _contentW, 0); + Band(2, y, FlowHeight(welcomeLines[2], SubFont, _contentW)); + DrawFlow(g, welcomeLines[2], SubFont, Theme.TextDim, S(24), ref y, _contentW, S(20)); + Band(3, y, FlowHeight(welcomeLines[3], SubFont, _contentW)); + DrawFlow(g, welcomeLines[3], SubFont, Theme.TextDim, S(24), ref y, _contentW, 0); + void Band(int i, int top, int height) + { + _welcomeBands[i] = new Rectangle(S(24), top, _contentW, height); + } + } + + private void PaintGameQuestion(Graphics g) + { + DrawStepCaption(g, 1); + DrawHeadings(g, "Which game do you play most?", "We'll start you on its presets. You can change it any time."); + Rectangle box = new Rectangle(_rightX, _gridTop, S(396), _splitH); + DrawSplitPreview(g, box); + int y = box.Bottom + S(8); + DrawFlow(g, "A sample scene. Pick a game to see its look on your screen.", CaptionFont, SignalInk.Faint, box.X, ref y, box.Width, S(10)); + DrawFlow(g, "Changes what your monitor shows, never touches the game.", SubFont, Theme.Text, box.X, ref y, box.Width, 0); + } + + private void PaintComplaintQuestion(Graphics g) + { + DrawStepCaption(g, 2); + DrawHeadings(g, "What do you want it to fix?", "Pick one - your screen changes to match."); + } + + private void DrawHeadings(Graphics g, string title, string subtitle) + { + TextRenderer.DrawText(g, title, TitleFont, new Rectangle(S(24), _titleTop, _contentW, _titleLine), Theme.Text, TextFormatFlags.VerticalCenter | TextFormatFlags.WordBreak | TextFormatFlags.NoPadding); + TextRenderer.DrawText(g, subtitle, SubFont, new Rectangle(S(24), _subTop, _contentW, _subLine), Theme.TextDim, TextFormatFlags.VerticalCenter | TextFormatFlags.WordBreak | TextFormatFlags.NoPadding); + } + + private void DrawStepCaption(Graphics g, int oneBasedStep) + { + string text = $"Step {oneBasedStep} of {2}"; + int num = S(56); + TextRenderer.DrawText(g, text, StepFont, new Rectangle(S(24), num, _contentW, _stepLine), SignalInk.Faint, TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding); + int width = TextRenderer.MeasureText(g, text, StepFont, new Size(int.MaxValue, int.MaxValue), TextFormatFlags.NoPadding).Width; + int num2 = S(20); + int num3 = S(2); + int num4 = S(24) + width + S(10); + int y = num + (_stepLine - num3) / 2; + PixelOffsetMode pixelOffsetMode = g.PixelOffsetMode; + g.PixelOffsetMode = PixelOffsetMode.Half; + for (int i = 0; i < 2; i++) + { + using SolidBrush brush = new SolidBrush((i < oneBasedStep) ? Theme.Accent : Theme.AccentDim); + g.FillRectangle(brush, num4, y, num2, num3); + num4 += num2 + S(4); + } + g.PixelOffsetMode = pixelOffsetMode; + } + + private void DrawSplitPreview(Graphics g, Rectangle box) + { + int num = S(8); + using (SolidBrush brush = new SolidBrush(SignalInk.PreviewWell)) + { + using GraphicsPath path = Glass.RoundedPath(box, num); + g.FillPath(brush, path); + } + using Region clip = g.Clip; + using GraphicsPath path2 = Glass.RoundedPath(box, num); + using (Region clip2 = new Region(path2)) + { + g.Clip = clip2; + DrawScene(g, new Rectangle(box.X, box.Y, box.Width / 2, box.Height), vivid: false); + DrawScene(g, new Rectangle(box.X + box.Width / 2, box.Y, box.Width - box.Width / 2, box.Height), vivid: true); + int num2 = S(2); + PixelOffsetMode pixelOffsetMode = g.PixelOffsetMode; + g.PixelOffsetMode = PixelOffsetMode.Half; + using (SolidBrush brush2 = new SolidBrush(Theme.Accent)) + { + g.FillRectangle(brush2, box.X + box.Width / 2 - num2 / 2, box.Y, num2, box.Height); + } + g.PixelOffsetMode = pixelOffsetMode; + } + g.Clip = clip; + int num3 = S(36); + Rectangle rect = new Rectangle(box.X + box.Width / 2 - num3 / 2, box.Y + box.Height / 2 - num3 / 2, num3, num3); + using (SolidBrush brush3 = new SolidBrush(Theme.Background)) + { + g.FillEllipse(brush3, rect); + } + using (Pen pen = new Pen(Theme.Accent, 1f)) + { + g.DrawEllipse(pen, rect); + } + int num4 = S(20); + using (SolidBrush brush4 = new SolidBrush(Theme.Accent)) + { + g.FillPolygon(brush4, StarPoints(new Rectangle(rect.X + (num3 - num4) / 2, rect.Y + (num3 - num4) / 2, num4, num4))); + } + DrawCornerChip(g, "100% ", "as recorded", new Point(box.X + S(8), box.Y + S(8)), left: true); + DrawCornerChip(g, "230% ", "simulated", new Point(box.Right - S(8), box.Y + S(8)), left: false); + } + + private static void DrawScene(Graphics g, Rectangle r, bool vivid) + { + Rectangle rectangle = new Rectangle(r.X, r.Y, r.Width, (int)((float)r.Height * 0.62f)); + using (LinearGradientBrush brush = new LinearGradientBrush((rectangle.Height > 0) ? rectangle : new Rectangle(r.X, r.Y, Math.Max(1, r.Width), 1), Grade(Color.FromArgb(255, 108, 168, 224)), Grade(Color.FromArgb(255, 186, 219, 246)), LinearGradientMode.Vertical)) + { + g.FillRectangle(brush, rectangle); + } + using (SolidBrush brush2 = new SolidBrush(Grade(Color.FromArgb(255, 244, 248, 252)))) + { + g.FillEllipse(brush2, (float)r.X + (float)r.Width * 0.15f, (float)r.Y + (float)r.Height * 0.16f, (float)r.Width * 0.34f, (float)r.Height * 0.14f); + } + Rectangle rect = new Rectangle(r.X, rectangle.Bottom, r.Width, Math.Max(0, r.Bottom - rectangle.Bottom)); + using (SolidBrush brush3 = new SolidBrush(Grade(Color.FromArgb(255, 96, 148, 74)))) + { + g.FillRectangle(brush3, rect); + } + using (SolidBrush brush4 = new SolidBrush(Grade(Color.FromArgb(255, 58, 92, 54)))) + { + for (int i = 0; i < 5; i++) + { + float num = (float)r.X + (float)r.Width * (0.05f + (float)i * 0.11f); + float num2 = (float)rectangle.Bottom - (float)r.Height * 0.05f; + g.FillPolygon(brush4, new PointF[3] + { + new PointF(num, num2 - (float)r.Height * 0.12f), + new PointF(num - (float)r.Width * 0.035f, num2), + new PointF(num + (float)r.Width * 0.035f, num2) + }); + } + } + using (SolidBrush brush5 = new SolidBrush(Grade(Color.FromArgb(255, 128, 126, 118)))) + { + g.FillPolygon(brush5, new PointF[4] + { + new PointF((float)r.X + (float)r.Width * 0.55f, r.Bottom), + new PointF((float)r.X + (float)r.Width * 0.68f, (float)r.Bottom - (float)r.Height * 0.22f), + new PointF((float)r.X + (float)r.Width * 0.86f, (float)r.Bottom - (float)r.Height * 0.08f), + new PointF((float)r.X + (float)r.Width * 0.94f, r.Bottom) + }); + } + Color Grade(Color c) + { + if (!vivid) + { + return c; + } + float num3 = (float)(c.R + c.G + c.B) / 3f; + int red = (int)Math.Clamp(num3 + ((float)(int)c.R - num3) * 1.55f, 0f, 255f); + int green = (int)Math.Clamp(num3 + ((float)(int)c.G - num3) * 1.55f, 0f, 255f); + int blue = (int)Math.Clamp(num3 + ((float)(int)c.B - num3) * 1.55f, 0f, 255f); + return Color.FromArgb(red, green, blue); + } + } + + private void DrawCornerChip(Graphics g, string number, string rest, Point corner, bool left) + { + Font captionBold = Fonts.CaptionBold; + Font caption = Fonts.Caption; + TextFormatFlags flags = TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding; + int width = TextRenderer.MeasureText(g, number, captionBold, new Size(int.MaxValue, int.MaxValue), TextFormatFlags.NoPadding).Width; + int width2 = TextRenderer.MeasureText(g, rest, caption, new Size(int.MaxValue, int.MaxValue), TextFormatFlags.NoPadding).Width; + int num = S(8); + int height = Math.Max(S(24), captionBold.Height); + int num2 = width + width2 + num * 2; + Rectangle rectangle = (left ? new Rectangle(corner.X, corner.Y, num2, height) : new Rectangle(corner.X - num2, corner.Y, num2, height)); + using (SolidBrush brush = new SolidBrush(Theme.Background)) + { + using GraphicsPath path = Glass.RoundedPath(rectangle, S(4)); + g.FillPath(brush, path); + } + TextRenderer.DrawText(g, number, captionBold, new Rectangle(rectangle.X + num, rectangle.Y, width, height), Theme.Text, flags); + TextRenderer.DrawText(g, rest, caption, new Rectangle(rectangle.X + num + width, rectangle.Y, width2, height), SignalInk.Faint, flags); + } + + private void DrawDemoLine(Graphics g, int top) + { + if (_demoLine.Length != 0) + { + TextRenderer.DrawText(bounds: new Rectangle(S(24), top, _contentW, S(60)), dc: g, text: _demoLine, font: SubFont, foreColor: Theme.Accent, flags: TextFormatFlags.WordBreak); + } + } + + private void DrawFlow(Graphics g, string text, Font font, Color color, int x, ref int y, int width, int gapAfter) + { + int num = FlowHeight(text, font, width); + TextRenderer.DrawText(g, text, font, new Rectangle(x, y, width, num), color, TextFormatFlags.WordBreak | TextFormatFlags.NoPadding); + y += num + gapAfter; + } + + private static Point[] StarPoints(Rectangle r) + { + float num = (float)r.X + (float)r.Width / 2f; + float num2 = (float)r.Y + (float)r.Height / 2f; + float num3 = (float)r.Width / 2f; + float num4 = num3 * 0.4f; + Point[] array = new Point[24]; + for (int i = 0; i < 24; i++) + { + double num5 = Math.PI / 12.0 * (double)i - Math.PI / 2.0; + float num6 = ((i % 2 == 0) ? num3 : num4); + array[i] = new Point((int)((double)num + (double)num6 * Math.Cos(num5)), (int)((double)num2 + (double)num6 * Math.Sin(num5))); + } + return array; + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _timer?.Stop(); + _timer?.Dispose(); + } + base.Dispose(disposing); + } +} diff --git a/VibranceHud/OutsideDriverChange.cs b/VibranceHud/OutsideDriverChange.cs new file mode 100644 index 0000000..c18f07f --- /dev/null +++ b/VibranceHud/OutsideDriverChange.cs @@ -0,0 +1,57 @@ +using System; + +namespace VibranceHud; + +public static class OutsideDriverChange +{ + public static void AtLaunch(VibranceEngine engine, AppSettings settings, IVibranceController driver) + { + AppSettings.MigrateVibranceOwnership(settings); + try + { + if (settings.VibranceChosenByUser && driver.IsAvailable) + { + int? driverVibranceWeLastWrote = settings.DriverVibranceWeLastWrote; + if (driverVibranceWeLastWrote.HasValue) + { + int valueOrDefault = driverVibranceWeLastWrote.GetValueOrDefault(); + if (HoldsALevelOtherThan(driver, valueOrDefault)) + { + LetGo(settings); + } + } + else + { + int num = Math.Min(settings.ResolvedVibrance, 100); + if (HoldsALevelOtherThan(driver, num)) + { + LetGo(settings); + } + else + { + settings.DriverVibranceWeLastWrote = num; + } + } + } + } + catch + { + } + engine.DriverLevelWeLastWrote = settings.DriverVibranceWeLastWrote; + } + + internal static bool HoldsALevelOtherThan(IVibranceController driver, int level) + { + if (!driver.EveryDisplayIsAt(level)) + { + return driver.CurrentLevel != level; + } + return false; + } + + private static void LetGo(AppSettings settings) + { + settings.VibranceChosenByUser = false; + settings.DriverVibranceWeLastWrote = null; + } +} diff --git a/VibranceHud/OutsideFocusRing.cs b/VibranceHud/OutsideFocusRing.cs new file mode 100644 index 0000000..bed12b9 --- /dev/null +++ b/VibranceHud/OutsideFocusRing.cs @@ -0,0 +1,196 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Windows.Forms; +using VibranceHud.Pages; + +namespace VibranceHud; + +internal sealed class OutsideFocusRing +{ + private readonly Control _owner; + + private readonly Func _radius; + + private readonly Func? _box; + + private readonly List _hosts = new List(); + + private bool _shown; + + private Rectangle _band; + + internal bool Shown => _shown; + + internal IReadOnlyList HostsForTest => _hosts; + + public OutsideFocusRing(Control owner, Func radius, Func? box = null) + { + _owner = owner; + _radius = radius; + _box = box; + } + + public void Rehook() + { + if (_shown) + { + Invalidate(_band); + Hook(); + _band = RingBand(); + Invalidate(_band); + } + } + + public void Release() + { + Unhook(); + _shown = false; + } + + public void Show(bool show) + { + if (show) + { + Rectangle rectangle = RingBand(); + if (!_shown || !(rectangle == _band)) + { + if (_shown) + { + Invalidate(_band); + } + _shown = true; + Hook(); + _band = rectangle; + Invalidate(rectangle); + } + } + else if (_shown) + { + Invalidate(_band); + _shown = false; + Unhook(); + } + } + + private static Point Origin(Control c) + { + int num = 0; + int num2 = 0; + Control control = c; + while (control != null && control.Parent != null) + { + num += control.Left; + num2 += control.Top; + control = control.Parent; + } + return new Point(num, num2); + } + + private static Rectangle ClientInRoot(Control c) + { + return new Rectangle(Origin(c), c.ClientSize); + } + + private Rectangle BoxInRoot() + { + Rectangle result = _box?.Invoke() ?? new Rectangle(Point.Empty, _owner.Size); + Point pos = Origin(_owner); + result.Offset(pos); + return result; + } + + private Rectangle RingBand() + { + int num = ControlInk.FocusRingReach(ControlInk.Dpi(_owner)) + 1; + return Rectangle.Inflate(BoxInRoot(), num, num); + } + + private void Hook() + { + Unhook(); + if (_owner.Parent == null) + { + return; + } + Rectangle rect = RingBand(); + Control control = _owner; + Control parent = _owner.Parent; + while (parent != null) + { + Add(parent); + foreach (Control control2 in parent.Controls) + { + if (control2 != control && control2.Visible && ClientInRoot(control2).IntersectsWith(rect)) + { + Add(control2); + } + } + if (!(parent is Form) && !(parent is GlowPage) && parent.Parent != null && !ClientInRoot(parent).Contains(rect)) + { + control = parent; + parent = parent.Parent; + continue; + } + break; + } + } + + private void Add(Control host) + { + if (!_hosts.Contains(host)) + { + _hosts.Add(host); + host.Paint += OnHostPaint; + } + } + + private void Unhook() + { + foreach (Control host in _hosts) + { + host.Paint -= OnHostPaint; + } + _hosts.Clear(); + } + + private void Invalidate(Rectangle band) + { + foreach (Control host in _hosts) + { + if (!host.IsDisposed && host.IsHandleCreated) + { + Rectangle rc = band; + Point point = Origin(host); + rc.Offset(-point.X, -point.Y); + host.Invalidate(rc); + } + } + } + + private bool WhollyShownBelow(Control host) + { + Rectangle rect = BoxInRoot(); + Control parent = _owner.Parent; + while (parent != null && parent != host && !parent.Contains(host)) + { + if (parent is ScrollableControl { AutoScroll: not false } && !ClientInRoot(parent).Contains(rect)) + { + return false; + } + parent = parent.Parent; + } + return true; + } + + private void OnHostPaint(object? sender, PaintEventArgs e) + { + if (_shown && sender is Control control && !_owner.IsDisposed && _owner.Visible && _owner.Parent != null && WhollyShownBelow(control)) + { + Rectangle bounds = BoxInRoot(); + Point point = Origin(control); + bounds.Offset(-point.X, -point.Y); + ControlInk.PaintFocusRing(e.Graphics, bounds, _radius(), ControlInk.Dpi(_owner)); + } + } +} diff --git a/VibranceHud/OverlayMode.cs b/VibranceHud/OverlayMode.cs new file mode 100644 index 0000000..c6ee351 --- /dev/null +++ b/VibranceHud/OverlayMode.cs @@ -0,0 +1,7 @@ +namespace VibranceHud; + +public enum OverlayMode +{ + Dx, + Mag +} diff --git a/VibranceHud/OverlayModeResolver.cs b/VibranceHud/OverlayModeResolver.cs new file mode 100644 index 0000000..13741a9 --- /dev/null +++ b/VibranceHud/OverlayModeResolver.cs @@ -0,0 +1,9 @@ +namespace VibranceHud; + +public static class OverlayModeResolver +{ + public static OverlayMode Resolve(ISaturationOverlay overlay) + { + return (overlay as IDisplayOverlay)?.ActiveMode ?? OverlayMode.Dx; + } +} diff --git a/VibranceHud/Pages/CrosshairPage.cs b/VibranceHud/Pages/CrosshairPage.cs new file mode 100644 index 0000000..0d57c8b --- /dev/null +++ b/VibranceHud/Pages/CrosshairPage.cs @@ -0,0 +1,2375 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Windows.Forms; +using VibranceHud.Controls; +using VibranceHud.Crosshair; +using VibranceHud.Design; +using VibranceHud.Licensing; + +namespace VibranceHud.Pages; + +public sealed class CrosshairPage : GlowPage +{ + private sealed class PreviewBox : Panel + { + public CrosshairConfig Config { get; set; } = new CrosshairConfig(); + + public PreviewBox() + { + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics graphics = e.Graphics; + graphics.SmoothingMode = SmoothingMode.AntiAlias; + using GraphicsPath path = Glass.RoundedPath(new RectangleF(0f, 0f, Width, Height), Tokens.Scale(4)); + using Region clip = graphics.Clip; + graphics.SetClip(path, CombineMode.Intersect); + CrosshairRender.DrawCheckerboard(graphics, new Rectangle(0, 0, Width, Height), Tokens.Scale(16)); + GraphicsState gstate = graphics.Save(); + graphics.TranslateTransform((float)Width / 2f, (float)Height / 2f); + CrosshairRender.Draw(graphics, Config); + graphics.Restore(gstate); + graphics.Clip = clip; + base.OnPaint(e); + } + } + + private class SwatchDot : Control + { + private readonly Color _colour; + + private readonly OutsideFocusRing _ring; + + private bool _active; + + private bool _hover; + + public Color Colour => _colour; + + public bool Active + { + get + { + return _active; + } + set + { + if (_active != value) + { + _active = value; + Invalidate(); + } + } + } + + public SwatchDot(Color colour) + { + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.Selectable | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + _colour = colour; + Size = new Size(28, 28); + Cursor = Cursors.Hand; + BackColor = Color.Transparent; + AccessibleRole = AccessibleRole.RadioButton; + AccessibleName = ColourWheel.ToHex(colour); + _ring = new OutsideFocusRing(this, () => ControlInk.PxF(ControlInk.Dpi(this), 4f)); + } + + protected override void OnMouseEnter(EventArgs e) + { + base.OnMouseEnter(e); + _hover = true; + Invalidate(); + } + + protected override void OnMouseLeave(EventArgs e) + { + base.OnMouseLeave(e); + _hover = false; + Invalidate(); + } + + protected override void OnGotFocus(EventArgs e) + { + base.OnGotFocus(e); + Invalidate(); + } + + protected override void OnLostFocus(EventArgs e) + { + base.OnLostFocus(e); + Invalidate(); + } + + protected override void OnParentChanged(EventArgs e) + { + base.OnParentChanged(e); + _ring.Rehook(); + } + + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + Keys keyCode = e.KeyCode; + if ((keyCode == Keys.Return || keyCode == Keys.Space) ? true : false) + { + e.Handled = true; + OnClick(EventArgs.Empty); + } + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _ring.Release(); + } + base.Dispose(disposing); + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics graphics = e.Graphics; + graphics.SmoothingMode = SmoothingMode.AntiAlias; + graphics.PixelOffsetMode = PixelOffsetMode.Half; + float num = (float)Width / 28f; + RectangleF rect = new RectangleF(0f, 0f, Width, Height); + RectangleF rect2 = RectangleF.Inflate(rect, -2f * num, -2f * num); + if (_active) + { + using SolidBrush brush = new SolidBrush(ControlInk.Accent); + using GraphicsPath path = Glass.RoundedPath(rect, 4f * num); + graphics.FillPath(brush, path); + } + using (GraphicsPath path2 = Glass.RoundedPath(rect2, 2f * num)) + { + using SolidBrush brush2 = new SolidBrush(Enabled ? _colour : UiHelpers.Muted(_colour)); + graphics.FillPath(brush2, path2); + } + float num2 = Math.Max(1f, (float)Math.Floor(num)); + using (Pen pen = new Pen((_hover && !_active) ? ControlInk.Text2 : ControlInk.Border, num2)) + { + using GraphicsPath path3 = Glass.RoundedPath(RectangleF.Inflate(rect2, (0f - num2) / 2f, (0f - num2) / 2f), Math.Max(0.5f, 2f * num - num2 / 2f)); + graphics.DrawPath(pen, path3); + } + _ring.Show(Focused && ShowFocusCues && Enabled); + } + } + + private sealed class OutlineSwatch : SwatchDot + { + public OutlineSwatch(Color colour) + : base(colour) + { + } + } + + private sealed class AddSwatch : Control + { + private readonly OutsideFocusRing _ring; + + private bool _hover; + + public AddSwatch() + { + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.Selectable | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + Size = new Size(28, 28); + Cursor = Cursors.Hand; + TabStop = true; + AccessibleRole = AccessibleRole.PushButton; + AccessibleName = "Any colour"; + _ring = new OutsideFocusRing(this, () => ControlInk.PxF(ControlInk.Dpi(this), 4f)); + } + + protected override void OnMouseEnter(EventArgs e) + { + base.OnMouseEnter(e); + _hover = true; + Invalidate(); + } + + protected override void OnMouseLeave(EventArgs e) + { + base.OnMouseLeave(e); + _hover = false; + Invalidate(); + } + + protected override void OnGotFocus(EventArgs e) + { + base.OnGotFocus(e); + Invalidate(); + } + + protected override void OnLostFocus(EventArgs e) + { + base.OnLostFocus(e); + Invalidate(); + } + + protected override void OnParentChanged(EventArgs e) + { + base.OnParentChanged(e); + _ring.Rehook(); + } + + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + Keys keyCode = e.KeyCode; + if ((keyCode == Keys.Return || keyCode == Keys.Space) ? true : false) + { + e.Handled = true; + OnClick(EventArgs.Empty); + } + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _ring.Release(); + } + base.Dispose(disposing); + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics graphics = e.Graphics; + graphics.SmoothingMode = SmoothingMode.AntiAlias; + float num = (float)Width / 28f; + RectangleF rect = new RectangleF(0.5f, 0.5f, Width - 1, Height - 1); + using (Pen pen = new Pen(_hover ? ControlInk.Text1 : ControlInk.Edge, 1f) + { + DashStyle = DashStyle.Dash + }) + { + using GraphicsPath path = Glass.RoundedPath(rect, 4f * num); + graphics.DrawPath(pen, path); + } + float num2 = 16f * num; + SignalIcons.Draw(graphics, SignalIcon.Plus, new RectangleF(((float)Width - num2) / 2f, ((float)Height - num2) / 2f, num2, num2), ControlInk.Text2); + _ring.Show(Focused && ShowFocusCues && Enabled); + } + } + + private sealed class GuidanceNote : Control + { + private readonly (string Text, bool Code)[] _runs; + + private static Font? _codeFont; + + private static int _codeFontDpi; + + private static float _codeFontPoints; + + private static int Pad => S(12); + + private static int Icon => S(16); + + private static int IconGap => S(8); + + private static int Line => S(16); + + private static Font CodeFont + { + get + { + float sizeInPoints = Fonts.Caption.SizeInPoints; + if (_codeFont == null || _codeFontDpi != Tokens.Dpi || _codeFontPoints != sizeInPoints) + { + _codeFont?.Dispose(); + _codeFont = Fonts.Of(FontRole.Caption, Fonts.MonoFamily); + _codeFontDpi = Tokens.Dpi; + _codeFontPoints = sizeInPoints; + } + return _codeFont; + } + } + + public GuidanceNote(string before, string code, string after) + { + _runs = new (string, bool)[3] + { + (before, false), + (code, true), + (after, false) + }; + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + Text = before + code + after; + SetStyle(ControlStyles.Selectable, value: false); + TabStop = false; + } + + private static int S(int v) + { + return Tokens.Scale(v); + } + + private static Font FontOf(bool code) + { + if (!code) + { + return Fonts.Caption; + } + return CodeFont; + } + + private List> Wrap(int width) + { + List> list = new List> + { + new List<(string, bool)>() + }; + int num = 0; + int width2 = TextRenderer.MeasureText(" ", Fonts.Caption, Size.Empty, TextFormatFlags.NoPadding).Width; + (string, bool)[] runs = _runs; + for (int i = 0; i < runs.Length; i++) + { + (string, bool) tuple = runs[i]; + string item = tuple.Item1; + bool item2 = tuple.Item2; + string[] array = item.Split(' ', StringSplitOptions.RemoveEmptyEntries); + foreach (string text in array) + { + int num2 = Advance(text, FontOf(item2)); + int num3 = ((list[list.Count - 1].Count != 0) ? width2 : 0) + num2; + if (list[list.Count - 1].Count > 0 && num + num3 > width) + { + list.Add(new List<(string, bool)>()); + num = 0; + num3 = num2; + } + list[list.Count - 1].Add((text, item2)); + num += num3; + } + } + return list; + } + + internal int HeightFor(int width) + { + return S(1) + Pad + Wrap(Math.Max(1, width - Icon - IconGap)).Count * Line; + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics graphics = e.Graphics; + graphics.SmoothingMode = SmoothingMode.AntiAlias; + using (SolidBrush brush = new SolidBrush(ControlInk.Border)) + { + graphics.FillRectangle(brush, 0, 0, Width, ControlInk.Hairline(Tokens.Dpi)); + } + int num = S(1) + Pad; + SignalIcons.Draw(graphics, SignalIcon.Info, new RectangleF(0f, num, Icon, Icon), ControlInk.Info); + int num2 = Icon + IconGap; + int width = TextRenderer.MeasureText(" ", Fonts.Caption, Size.Empty, TextFormatFlags.NoPadding).Width; + List> list = Wrap(Math.Max(1, Width - num2)); + for (int i = 0; i < list.Count; i++) + { + int num3 = num2; + foreach (var item2 in list[i]) + { + string item = item2.Item1; + Font font = FontOf(item2.Item2); + int num4 = Advance(item, font); + TextRenderer.DrawText(graphics, item, font, new Rectangle(num3, num + i * Line, num4 + S(2), Line), Text3, TextFormatFlags.NoPrefix | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding); + num3 += num4 + width; + } + } + } + } + + private sealed class SavedChip : Control + { + private const int PreviewSize = 24; + + private const int DeleteWidth = 24; + + internal const int LogicalWidth = 190; + + internal const int LogicalHeight = 36; + + private readonly CrosshairConfig _config; + + private bool _hover; + + private bool _active; + + private float Px => (float)Height / 36f; + + public bool Active + { + get + { + return _active; + } + set + { + if (_active != value) + { + _active = value; + Invalidate(); + } + } + } + + private Rectangle DeleteRect => new Rectangle(Width - (int)(24f * Px), 0, (int)(24f * Px), Height); + + public event EventHandler? LoadRequested; + + public event EventHandler? DeleteRequested; + + public SavedChip(CrosshairConfig config) + { + _config = config; + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + Cursor = Cursors.Hand; + Font = Fonts.Label; + Size = new Size(190, 36); + } + + protected override void OnMouseEnter(EventArgs e) + { + base.OnMouseEnter(e); + _hover = true; + Invalidate(); + } + + protected override void OnMouseLeave(EventArgs e) + { + base.OnMouseLeave(e); + _hover = false; + Invalidate(); + } + + protected override void OnMouseUp(MouseEventArgs e) + { + base.OnMouseUp(e); + if (e.Button == MouseButtons.Left) + { + if (DeleteRect.Contains(e.Location)) + { + DeleteRequested?.Invoke(this, EventArgs.Empty); + } + else + { + LoadRequested?.Invoke(this, EventArgs.Empty); + } + } + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics graphics = e.Graphics; + graphics.SmoothingMode = SmoothingMode.AntiAlias; + using (GraphicsPath path = Glass.RoundedPath(new RectangleF(0.5f, 0.5f, Width - 1, Height - 1), Tokens.Scale(4))) + { + using (SolidBrush brush = new SolidBrush(_hover ? Theme.SurfaceHover : Theme.Surface)) + { + graphics.FillPath(brush, path); + } + using Pen pen = new Pen(_active ? Theme.Accent : Theme.GlassEdge, 1f); + graphics.DrawPath(pen, path); + } + int num = (int)(24f * Px); + Rectangle target = new Rectangle((int)(7f * Px), (Height - num) / 2, num, num); + CrosshairRender.Draw(graphics, _config, target); + int num2 = target.Right + (int)(10f * Px); + Rectangle bounds = new Rectangle(num2, 0, Width - num2 - DeleteRect.Width, Height); + TextRenderer.DrawText(graphics, _config.Name, Font, bounds, Theme.Text, TextFormatFlags.EndEllipsis | TextFormatFlags.VerticalCenter); + int num3 = Tokens.Scale(12); + LineIcons.Close(graphics, new Rectangle(DeleteRect.X + (DeleteRect.Width - num3) / 2, (Height - num3) / 2, num3, num3), Theme.TextDim); + } + } + + private readonly AppSettings _settings; + + private readonly SettingsStore _store; + + private readonly CrosshairService _service; + + private readonly PreviewBox _preview; + + private readonly CardPanel _card; + + private readonly FlowLayoutPanel _savedFlow; + + private readonly Label _savedEmpty; + + private readonly Label _shareCaption; + + private readonly Label _shareHint; + + private readonly Label _shareStatus; + + private readonly GlassTextBox _codeBox; + + private readonly GlassButton _copyCode; + + private readonly GlassButton _applyCode; + + private readonly GuidanceNote _note; + + private GlassButton _useImageBtn; + + private GlassButton _clearImageBtn; + + private Label _imageNote; + + private readonly ToggleSwitch _enabled; + + private readonly Label _status; + + private readonly Label _onLabel; + + private readonly QuietScrollPanel _galleryHost; + + private readonly List _cells = new List(); + + private readonly SegmentStrip _families; + + private CrosshairGallery.Family _family; + + private readonly CardPanel _right; + + private readonly QuietScrollPanel _leftScroll; + + private readonly QuietScrollPanel _rightScroll; + + private readonly Panel _moreOptionsFade; + + private readonly GlassButton _moreOptions; + + private FlatSlider _sizeSlider; + + private FlatSlider _thicknessSlider; + + private FlatSlider _gapSlider; + + private FlatSlider _dotSlider; + + private FlatSlider _circleSlider; + + private FlatSlider _opacitySlider; + + private FlatSlider _offsetXSlider; + + private FlatSlider _offsetYSlider; + + private FlatSlider _outlineSlider; + + private FlatSlider _imageScaleSlider; + + private FlatSlider _rotationSlider; + + private FlatSlider _dotOpacitySlider; + + private readonly List _partChips = new List(); + + private readonly List _shapeChips = new List(); + + private readonly List _outlineDots = new List(); + + private bool _applyingPreset; + + private readonly List _colourDots = new List(); + + private readonly ColourWheel _wheel; + + private readonly GlassTextBox _hexBox; + + private bool _syncingColour; + + private readonly List<(Label Label, FontRole Role)> _ownLabels = new List<(Label, FontRole)>(); + + private const int PanelH = 508; + + private const int LeftW = 568; + + private const int RightW = 348; + + private const int PanelGap = 16; + + private const int Inset = 17; + + private const int ContentW = 534; + + private const int RightContentW = 314; + + private const int ColGap = 32; + + private const int ColW = 251; + + private const int Col1 = 17; + + private const int Col2 = 300; + + private const int PreviewH = 326; + + private const int LabelH = 20; + + private const int TrackGap = 2; + + private const int TrackH = 16; + + private const int RowH = 38; + + private const int RowPitch = 50; + + private const int SlidersY = 359; + + private const int ColourY = 463; + + private const int LabelBleed = 4; + + private const int SwatchBox = 28; + + private const int SwatchGap = 8; + + private const int WordGap = 8; + + private static readonly Color[] SwatchColours = new Color[6] + { + Color.White, + Color.FromArgb(255, 0, 255, 102), + Color.FromArgb(255, 0, 255, 255), + Color.FromArgb(255, 255, 220, 0), + Color.FromArgb(255, 255, 60, 60), + Color.FromArgb(255, 255, 0, 170) + }; + + private const int FoldY = 516; + + private const int StripH = 32; + + private const int CellH = 72; + + private const int CellGap = 8; + + private const int GalleryRows = 3; + + private const int GalleryTop = 44; + + private CrosshairConfig _current; + + private readonly Label _opacityValue; + + private readonly IReadOnlyList _familyOrder; + + private readonly Label _designsOnTheirWay; + + private bool _showDesignsOnTheirWay; + + private int _designsGeneration; + + private readonly List<(Label Name, Label Value, FlatSlider Slider, bool Second)> _rows = new List<(Label, Label, FlatSlider, bool)>(); + + private readonly Label _opacityWord; + + private readonly Label _outlineWord; + + private readonly Label _shapeWord; + + private readonly Label _partsWord; + + private readonly Label _hexNote; + + private readonly Label _colourWord; + + private readonly Label _outlineColourWord; + + private readonly AddSwatch _anyColour; + + private readonly ToggleSwitch _outlineSwitch; + + private readonly GlassButton _saveBtn; + + private int _opacityRight; + + private const int MinLeftW = 430; + + private const int RightBleed = 4; + + private readonly int _wheelTop; + + private const int ReadoutW = 80; + + private const int ChipH = 32; + + private const int PartChipGap = 8; + + private const int PartChipW = 82; + + private const int ShapeChipW = 100; + + private bool _fittingPage; + + private bool _scaledByTheBase; + + private int _followedDpi = 96; + + private Font? _shareCodeFont; + + [ThreadStatic] + internal static Action? RebuildingTheGalleryForTest; + + internal const int MaxSavedCrosshairs = 10; + + protected override string PageTitle => "Crosshair"; + + protected override string PageSubtitle => "An overlay drawn on your screen, not in the game."; + + protected override bool UsesHeaderPanel => true; + + protected override Control[] HeaderActions => new Control[2] { _onLabel, _enabled }; + + private static Color Text3 + { + get + { + if (!(Theme.CurrentName == "Slate")) + { + return SignalTokens.Ash.Text3; + } + return SignalTokens.Slate.Text3; + } + } + + internal string? TestDesignsOnTheirWay + { + get + { + if (!_showDesignsOnTheirWay) + { + return null; + } + return _designsOnTheirWay.Text; + } + } + + internal Control TestDesignsOnTheirWayLine => _designsOnTheirWay; + + internal Control TestShareHint => _shareHint; + + internal IReadOnlyList TestFamilies => _familyOrder; + + internal CrosshairGallery.Family TestFamily => _family; + + internal IReadOnlyList TestCells => _cells; + + internal string TestOnWord => _onLabel.Text; + + internal CrosshairConfig CurrentCrosshair => _current; + + internal IReadOnlyList TestSavedCrosshairs => _settings.SavedCrosshairs; + + internal Control TestLeftPanel => _card; + + internal ScrollableControl TestLeftScroll => _leftScroll; + + internal Control TestRightPanel => _right; + + internal ScrollableControl TestRightScroll => _rightScroll; + + internal Control TestNote => _note; + + internal Control TestEnabledSwitch => _enabled; + + internal Control TestWheel => _wheel; + + internal int TestSliderCount => CountOf(); + + internal int TestGalleryCellCount => _cells.Count; + + private static string ImageStoreDir => Path.Combine(AppFolders.Local, "crosshairs"); + + public CrosshairPage(AppSettings settings, SettingsStore store, CrosshairService service) + { + _settings = settings; + _store = store; + _service = service; + _current = service.Config.Clone(); + Font = Fonts.Body; + AutoScroll = true; + ContentWidth = 0; + int y = 0; + _enabled = new ToggleSwitch + { + AccessibleName = "Crosshair", + Size = new Size(40, 20), + Checked = _service.IsVisible + }; + _enabled.CheckedChanged += (object? s, EventArgs e2) => + { + if (_enabled.Checked) + { + _service.Show(); + } + else + { + _service.Hide(); + } + _settings.CrosshairEnabled = _enabled.Checked; + _store.Save(_settings); + UpdateStatus(); + }; + _onLabel = Own(new Label + { + ForeColor = Theme.Text, + BackColor = Color.Transparent, + TextAlign = ContentAlignment.MiddleRight, + Size = new Size(40, 20) + }, FontRole.BodyBold); + _card = new CardPanel + { + Location = new Point(16, y), + Size = new Size(568, 508) + }; + _leftScroll = new QuietScrollPanel + { + Location = new Point(0, 0), + Size = new Size(568, 508), + BackColor = Color.Transparent + }; + _card.Controls.Add(_leftScroll); + _moreOptionsFade = new Panel + { + BackColor = Color.Transparent + }; + _moreOptionsFade.Paint += (object? _, PaintEventArgs e2) => + { + if (_moreOptionsFade.Width <= 0 || _moreOptionsFade.Height <= 0) + { + return; + } + using LinearGradientBrush brush = new LinearGradientBrush(_moreOptionsFade.ClientRectangle, Color.FromArgb(0, Theme.Surface), Theme.Surface, LinearGradientMode.Vertical); + e2.Graphics.FillRectangle(brush, _moreOptionsFade.ClientRectangle); + }; + _moreOptions = new GlassButton + { + Name = "moreOptions", + Text = "More options", + Kind = GlassButtonKind.Quiet, + TrailingIcon = SignalIcon.Chevron, + Font = Fonts.Caption + }; + _moreOptions.Click += (object? _, EventArgs _) => + { + _leftScroll.AutoScrollPosition = new Point(0, Math.Max(0, S(516) - S(17))); + UpdateMoreOptions(); + _leftScroll.Invalidate(invalidateChildren: true); + }; + _moreOptionsFade.Controls.Add(_moreOptions); + _card.Controls.Add(_moreOptionsFade); + _leftScroll.Scroll += (object? _, ScrollEventArgs _) => + { + UpdateMoreOptions(); + }; + _leftScroll.Layout += (object? _, LayoutEventArgs _) => + { + UpdateMoreOptions(); + }; + _leftScroll.Invalidated += (object? _, InvalidateEventArgs _) => + { + UpdateMoreOptions(); + }; + _leftScroll.Paint += (object? _, PaintEventArgs _) => + { + UpdateMoreOptions(); + }; + Controls.Add(_card); + _right = new CardPanel + { + Location = new Point(600, y), + Size = new Size(348, 508) + }; + _rightScroll = new QuietScrollPanel + { + Location = new Point(17, 17), + Size = new Size(314, 474), + BackColor = Color.Transparent + }; + _right.Controls.Add(_rightScroll); + Controls.Add(_right); + QuietScrollPanel leftScroll = _leftScroll; + _preview = new PreviewBox + { + Location = new Point(17, 17), + Size = new Size(534, 326) + }; + leftScroll.Controls.Add(_preview); + _sizeSlider = AddRow(leftScroll, "Size", 17, 359, 5, 300, (int)Math.Round(_current.ResolvedSize * 10f), Tenths, (int v) => + { + _current.SetSizeTenths(v); + OnSliderMoved(); + }); + _thicknessSlider = AddRow(leftScroll, "Thickness", 300, 359, 5, 100, (int)Math.Round(_current.ResolvedThickness * 10f), Tenths, (int v) => + { + _current.SetThicknessTenths(v); + OnSliderMoved(); + }); + _gapSlider = AddRow(leftScroll, "Gap", 17, 409, 0, 300, (int)Math.Round(_current.ResolvedGap * 10f), Tenths, (int v) => + { + _current.SetGapTenths(v); + OnSliderMoved(); + }); + _outlineSlider = AddRow(leftScroll, "Outline thickness", 300, 409, 0, 40, _current.OutlineThicknessTenths ?? 10, Tenths, (int v) => + { + _current.OutlineThicknessTenths = v; + OnSliderMoved(); + }); + int y2 = 467; + _colourWord = Own(new Label + { + Text = "Colour", + ForeColor = Theme.TextDim, + BackColor = Color.Transparent, + TextAlign = ContentAlignment.MiddleLeft, + Bounds = new Rectangle(13, y2, 60, 20) + }, FontRole.Body); + leftScroll.Controls.Add(_colourWord); + Color[] swatchColours = SwatchColours; + for (int num = 0; num < swatchColours.Length; num++) + { + Color color = swatchColours[num]; + SwatchDot swatchDot = new SwatchDot(color) + { + Location = new Point(17, 463), + Active = ((color.ToArgb() & 0xFFFFFF) == (_current.ColourArgb & 0xFFFFFF)) + }; + Color captured = color; + swatchDot.Click += (object? s, EventArgs e2) => + { + ApplyColour(captured, null); + }; + _colourDots.Add(swatchDot); + leftScroll.Controls.Add(swatchDot); + } + _anyColour = new AddSwatch + { + Location = new Point(17, 463) + }; + _anyColour.Click += (object? _, EventArgs _) => + { + ShowTheColourPicker(); + }; + leftScroll.Controls.Add(_anyColour); + _opacityValue = Own(new Label + { + Text = $"{_current.Opacity}%", + ForeColor = Theme.Text, + BackColor = Color.Transparent, + TextAlign = ContentAlignment.MiddleLeft, + Bounds = new Rectangle(17, y2, 60, 20) + }, FontRole.BodyBold); + leftScroll.Controls.Add(_opacityValue); + _opacityWord = Own(new Label + { + Text = "Opacity", + ForeColor = Theme.TextDim, + BackColor = Color.Transparent, + TextAlign = ContentAlignment.MiddleLeft, + Bounds = new Rectangle(17, y2, 70, 20) + }, FontRole.Body); + leftScroll.Controls.Add(_opacityWord); + int num2 = 516; + _opacitySlider = AddRow(leftScroll, "Opacity", 300, num2, 10, 100, Math.Clamp(_current.Opacity, 10, 100), (int v) => $"{v}%", (int v) => + { + _opacityValue.Text = $"{v}%"; + LayOutTheOpacityReadout(); + _current.Opacity = v; + OnSliderMoved(); + RefreshGalleryPreviews(); + }); + _opacitySlider.Name = "opacitySlider"; + num2 += 50; + _shapeWord = RowLabel("Shape", 17, num2, 534); + leftScroll.Controls.Add(_shapeWord); + int x = 17; + foreach (CrosshairShapeKind item2 in CrosshairShapeKinds.All) + { + AddShape(num2 + 20 + 8, ref x, item2); + } + num2 += 76; + _partsWord = RowLabel("Parts", 17, num2, 534); + leftScroll.Controls.Add(_partsWord); + int x2 = 17; + int y3 = num2 + 20 + 8; + AddPart(y3, ref x2, "Up", () => _current.ResolvedArmTop, (bool v) => + { + _current.ArmTop = v; + }); + AddPart(y3, ref x2, "Down", () => _current.ResolvedArmBottom, (bool v) => + { + _current.ArmBottom = v; + }); + AddPart(y3, ref x2, "Left", () => _current.ResolvedArmLeft, (bool v) => + { + _current.ArmLeft = v; + }); + AddPart(y3, ref x2, "Right", () => _current.ResolvedArmRight, (bool v) => + { + _current.ArmRight = v; + }); + AddPart(y3, ref x2, "Dot", () => _current.ResolvedCentreDot, (bool v) => + { + _current.CentreDot = v; + }); + AddPart(y3, ref x2, "Ring", () => _current.ResolvedShowCircle, (bool v) => + { + _current.ShowCircle = v; + }); + num2 += 76; + _rotationSlider = AddRow(leftScroll, "Rotation", 17, num2, 0, 90, _current.ResolvedRotationDegrees, Degrees, (int v) => + { + _current.SetRotationDegrees(v); + OnSliderMoved(); + }); + _rotationSlider.Name = "rotationSlider"; + _dotSlider = AddRow(leftScroll, "Dot size", 300, num2, 5, 100, (int)Math.Round(_current.ResolvedDotSize * 10f), Tenths, (int v) => + { + _current.DotSizeTenths = v; + OnSliderMoved(); + }); + num2 += 50; + _dotOpacitySlider = AddRow(leftScroll, "Dot opacity", 17, num2, 10, 100, _current.ResolvedDotOpacity, (int v) => $"{v}%", (int v) => + { + _current.DotOpacity = v; + OnSliderMoved(); + }); + _dotOpacitySlider.Name = "dotOpacitySlider"; + _circleSlider = AddRow(leftScroll, "Ring size", 300, num2, 10, 400, (int)Math.Round(_current.ResolvedCircleRadius * 10f), Tenths, (int v) => + { + _current.CircleRadiusTenths = v; + OnSliderMoved(); + }); + num2 = (_wheelTop = num2 + 58); + _wheel = new ColourWheel + { + Location = new Point(17, num2), + Size = new Size(196, 130), + Colour = Color.FromArgb(_current.ColourArgb) + }; + _wheel.ColourChanged += (object? _, EventArgs _) => + { + ApplyColour(_wheel.Colour, _wheel); + }; + leftScroll.Controls.Add(_wheel); + int num3 = 249; + leftScroll.Controls.Add(RowLabel("Hex", num3, num2 + 4, 120)); + _hexBox = new GlassTextBox + { + AccessibleName = "Hex", + Name = "hexBox", + Location = new Point(num3, num2 + 28), + Size = new Size(110, 32) + }; + _hexBox.Inner.Font = Fonts.Mono; + _hexBox.Inner.AccessibleName = "Hex"; + _hexBox.Inner.CharacterCasing = CharacterCasing.Upper; + _hexBox.Inner.MaxLength = 7; + _hexBox.Text = ColourWheel.ToHex(Color.FromArgb(_current.ColourArgb)); + _hexBox.TextChanged += (object? s, EventArgs e2) => + { + if (ColourWheel.TryParseHex(_hexBox.Text, out var colour)) + { + ApplyColour(colour, _hexBox); + } + }; + leftScroll.Controls.Add(_hexBox); + _hexNote = Own(new Label + { + Text = "Paste a colour to match a friend's crosshair.", + ForeColor = Theme.TextDim, + BackColor = Color.Transparent, + Location = new Point(num3, num2 + 68), + Size = new Size(551 - num3, 34) + }, FontRole.Caption); + leftScroll.Controls.Add(_hexNote); + num2 += 150; + _outlineWord = Own(new Label + { + Text = "Outline", + ForeColor = Theme.TextDim, + BackColor = Color.Transparent, + TextAlign = ContentAlignment.MiddleLeft, + Bounds = new Rectangle(13, num2, 488, 20) + }, FontRole.Body); + leftScroll.Controls.Add(_outlineWord); + ToggleSwitch outline = new ToggleSwitch + { + AccessibleName = "Outline", + Name = "outlineSwitch", + Size = new Size(40, 20), + Location = new Point(511, num2), + Checked = _current.Outline + }; + outline.CheckedChanged += (object? s, EventArgs e2) => + { + _current.Outline = outline.Checked; + if (!_applyingPreset) + { + Push(); + } + }; + leftScroll.Controls.Add(outline); + _outlineSwitch = outline; + num2 += 50; + _outlineColourWord = Own(new Label + { + Text = "Outline colour", + ForeColor = Theme.TextDim, + BackColor = Color.Transparent, + TextAlign = ContentAlignment.MiddleLeft, + Bounds = new Rectangle(13, num2 + 4, 110, 20) + }, FontRole.Body); + leftScroll.Controls.Add(_outlineColourWord); + foreach (Color item3 in new Color[1] { Color.Black }.Concat(SwatchColours)) + { + OutlineSwatch outlineSwatch = new OutlineSwatch(item3) + { + Location = new Point(17, num2) + }; + Color captured2 = item3; + outlineSwatch.Click += (object? _, EventArgs _) => + { + ApplyOutlineColour(captured2); + }; + _outlineDots.Add(outlineSwatch); + leftScroll.Controls.Add(outlineSwatch); + } + SyncOutlineDots(); + num2 += 50; + _offsetXSlider = AddRow(leftScroll, "Offset X", 17, num2, -200, 200, _current.ResolvedOffsetX, (int v) => $"{v} px", (int v) => + { + _current.OffsetXPx = v; + OnSliderMoved(); + }); + _offsetYSlider = AddRow(leftScroll, "Offset Y", 300, num2, -200, 200, _current.ResolvedOffsetY, (int v) => $"{v} px", (int v) => + { + _current.OffsetYPx = v; + OnSliderMoved(); + }); + num2 += 50; + _imageScaleSlider = AddRow(leftScroll, "Image size", 17, num2, 25, 400, _current.ImageScalePercent, (int v) => $"{v}%", (int v) => + { + _current.ImageScalePercent = v; + OnSliderMoved(); + }); + _imageScaleSlider.Name = "imageScaleSlider"; + num2 += 58; + _useImageBtn = Button("Use an image…", 17, num2, 140); + _useImageBtn.Click += (object? _, EventArgs _) => + { + ImportImage(); + }; + leftScroll.Controls.Add(_useImageBtn); + _clearImageBtn = Button("Back to shapes", 167, num2, 130); + _clearImageBtn.Click += (object? _, EventArgs _) => + { + _current.ImagePath = null; + Push(); + SyncImageControls(); + }; + _clearImageBtn.Visible = false; + leftScroll.Controls.Add(_clearImageBtn); + _imageNote = Own(new Label + { + Text = "", + ForeColor = Theme.TextDim, + BackColor = Color.Transparent, + Location = new Point(17, num2 + 40), + AutoSize = true, + MaximumSize = new Size(534, 0) + }, FontRole.Caption); + leftScroll.Controls.Add(_imageNote); + num2 += 76; + _status = Own(new Label + { + ForeColor = Theme.TextDim, + BackColor = Color.Transparent, + Location = new Point(17, num2), + Size = new Size(534, 34) + }, FontRole.Caption); + leftScroll.Controls.Add(_status); + num2 += 46; + leftScroll.Controls.Add(RowLabel("Saved", 17, num2, 200)); + GlassButton glassButton = Button("Save as…", 421, num2 + 20 + 4, 130); + glassButton.Click += (object? s, EventArgs e2) => + { + SaveCurrent(); + }; + leftScroll.Controls.Add(glassButton); + _saveBtn = glassButton; + _savedFlow = new FlowLayoutPanel + { + Location = new Point(17, num2 + 20 + 4), + Size = new Size(394, 36), + MaximumSize = new Size(394, 0), + AutoSize = true, + AutoSizeMode = AutoSizeMode.GrowAndShrink, + WrapContents = true, + BackColor = Color.Transparent + }; + leftScroll.Controls.Add(_savedFlow); + _savedEmpty = Own(new Label + { + Text = "No saved crosshairs yet — tweak, then Save as…", + ForeColor = Theme.TextDim, + BackColor = Color.Transparent, + Location = new Point(17, num2 + 20 + 4), + Size = new Size(394, 32), + TextAlign = ContentAlignment.MiddleLeft + }, FontRole.Caption); + leftScroll.Controls.Add(_savedEmpty); + List list = new List + { + CrosshairGallery.Family.Dot, + CrosshairGallery.Family.Cross, + CrosshairGallery.Family.X, + CrosshairGallery.Family.Ring + }; + CrosshairGallery.Family[] values = Enum.GetValues(); + foreach (CrosshairGallery.Family item in values) + { + if (!list.Contains(item)) + { + list.Add(item); + } + } + _designsGeneration = ServedCrosshairs.Generation; + IReadOnlyList designsAtOpening = CrosshairGallery.All; + if (designsAtOpening.Count > 0) + { + list.RemoveAll((CrosshairGallery.Family family) => !designsAtOpening.Any((CrosshairGallery.GalleryItem i) => i.Group == family)); + } + _familyOrder = list; + _family = OpeningFamily(); + _families = new SegmentStrip(list.Select(FamilyWord).ToArray()) + { + AccessibleName = "Crosshair family", + Location = new Point(0, 0), + Size = new Size(314, 32), + Active = FamilyWord(_family), + ArrowsChoose = true + }; + _families.Chosen += (object? _, string word) => + { + _family = _familyOrder.First((CrosshairGallery.Family family) => FamilyWord(family) == word); + _families.Active = word; + LayOutGallery(); + }; + _rightScroll.Controls.Add(_families); + _galleryHost = new QuietScrollPanel + { + Location = new Point(0, 44), + Size = new Size(314, 232) + }; + _rightScroll.Controls.Add(_galleryHost); + _designsOnTheirWay = Own(new Label + { + Text = "", + ForeColor = Theme.TextDim, + BackColor = Color.Transparent, + Visible = false + }, FontRole.Caption); + _rightScroll.Controls.Add(_designsOnTheirWay); + _shareCaption = Own(new Label + { + Text = "Share code", + ForeColor = Theme.Text, + BackColor = Color.Transparent, + TextAlign = ContentAlignment.MiddleLeft + }, FontRole.BodyBold); + _rightScroll.Controls.Add(_shareCaption); + _shareHint = Own(new Label + { + Text = "Paste one from a friend", + ForeColor = Text3, + BackColor = Color.Transparent, + TextAlign = ContentAlignment.MiddleLeft + }, FontRole.Caption); + _rightScroll.Controls.Add(_shareHint); + _codeBox = new GlassTextBox + { + Name = "shareCodeBox", + CharacterCasing = CharacterCasing.Upper, + PlaceholderText = "Paste a code, e.g. PXC-…" + }; + UseShareCodeFont(); + _rightScroll.Controls.Add(_codeBox); + _copyCode = new GlassButton + { + Text = "Copy", + Icon = SignalIcon.Copy, + Kind = GlassButtonKind.Secondary, + Height = 32 + }; + _copyCode.Click += (object? _, EventArgs _) => + { + CopyMyCode(); + }; + _rightScroll.Controls.Add(_copyCode); + _applyCode = new GlassButton + { + Text = "Apply", + Kind = GlassButtonKind.Primary, + Height = 32 + }; + _applyCode.Click += (object? _, EventArgs _) => + { + ApplySharedCode(); + }; + _rightScroll.Controls.Add(_applyCode); + _shareStatus = Own(new Label + { + Text = "", + ForeColor = Theme.TextDim, + BackColor = Color.Transparent, + TextAlign = ContentAlignment.MiddleLeft + }, FontRole.Caption); + _rightScroll.Controls.Add(_shareStatus); + _note = new GuidanceNote("CS2 hides overlays unless you add ", "-allow_third_party_software", " to its launch options."); + _rightScroll.Controls.Add(_note); + BuildGallery(); + LayOutTheRightPanel(); + LayOutAcrossTheWidth(); + Resize += (object? _, EventArgs _) => + { + LayOutAcrossTheWidth(); + }; + RefreshSavedList(); + SyncImageControls(); + RovingFocus.Attach(_colourDots.Cast().Append(_anyColour), (Control control) => control is SwatchDot swatchDot2 && swatchDot2.Active, (Control control) => control is SwatchDot); + RovingFocus.Attach(_outlineDots, (Control control) => control is SwatchDot swatchDot2 && swatchDot2.Active); + RovingFocus.Attach(_shapeChips, (Control control) => control is ChipButton chipButton && chipButton.Active); + Push(); + } + + private T Own(T label, FontRole role) where T : Label + { + label.Font = Fonts.For(role); + label.UseMnemonic = false; + _ownLabels.Add((label, role)); + return label; + } + + private Label RowLabel(string text, int x, int y, int w) + { + return Own(new Label + { + Text = text, + ForeColor = Theme.TextDim, + BackColor = Color.Transparent, + TextAlign = ContentAlignment.MiddleLeft, + Bounds = new Rectangle(x - 4, y, w + 4, 20) + }, FontRole.Body); + } + + private static int Advance(string text, Font font) + { + return TextRenderer.MeasureText(text, font, Size.Empty, TextFormatFlags.NoPadding).Width; + } + + private static int InkInsetOf(Label l) + { + if (!string.IsNullOrEmpty(l.Text)) + { + return Math.Max(0, (TextRenderer.MeasureText(l.Text, l.Font).Width - Advance(l.Text, l.Font)) / 2); + } + return 0; + } + + private static void PlaceInk(Label l, int inkLeft) + { + l.SetBounds(inkLeft - InkInsetOf(l), l.Top, TextRenderer.MeasureText(l.Text, l.Font).Width, l.Height); + } + + private static string FamilyWord(CrosshairGallery.Family family) + { + if (family != CrosshairGallery.Family.Ring) + { + return family.ToString(); + } + return "Circle"; + } + + private static CrosshairGallery.Family? FamilyForShape(CrosshairConfig c) + { + switch (CrosshairShapeKinds.Of(c)) + { + case CrosshairShapeKind.Cross: + case CrosshairShapeKind.T: + if (c.ResolvedRotationDegrees == 45) + { + return CrosshairGallery.Family.X; + } + return CrosshairGallery.Family.Cross; + case CrosshairShapeKind.Circle: + return CrosshairGallery.Family.Ring; + case CrosshairShapeKind.Dot: + return CrosshairGallery.Family.Dot; + default: + return null; + } + } + + private static string Tenths(int tenths) + { + return ((float)tenths / 10f).ToString("0.#", CultureInfo.InvariantCulture) + " px"; + } + + private static string Degrees(int degrees) + { + return degrees.ToString(CultureInfo.InvariantCulture) + "°"; + } + + private FlatSlider AddRow(Control parent, string label, int x, int y, int min, int max, int value, Func format, Action onChange) + { + Label label2 = Own(new Label + { + Text = label, + ForeColor = Theme.TextDim, + BackColor = Color.Transparent, + TextAlign = ContentAlignment.MiddleLeft, + Bounds = new Rectangle(x - 4, y, 175, 20) + }, FontRole.Body); + parent.Controls.Add(label2); + Label readout = Own(new Label + { + Text = format(value), + ForeColor = Theme.Text, + BackColor = Color.Transparent, + TextAlign = ContentAlignment.MiddleRight, + Bounds = new Rectangle(x + 251 - 80, y, 84, 20) + }, FontRole.BodyBold); + parent.Controls.Add(readout); + FlatSlider slider = new FlatSlider + { + AccessibleName = label, + Minimum = min, + Maximum = max, + Value = Math.Clamp(value, min, max) + }; + slider.SetTrackBounds(x, y + 20 + 2, 251, 16); + slider.ValueChanged += (object? s, EventArgs e2) => + { + readout.Text = format(slider.Value); + onChange(slider.Value); + }; + parent.Controls.Add(slider); + _rows.Add((label2, readout, slider, x == 300)); + return slider; + } + + private void AddPart(int y, ref int x, string label, Func get, Action set) + { + ChipButton chip = new ChipButton + { + Text = label, + Location = new Point(x, y), + Size = new Size(82, 32), + Font = Fonts.Caption, + Active = get() + }; + chip.Click += (object? _, EventArgs _) => + { + set(!chip.Active); + chip.Active = get(); + Push(); + HighlightActivePreset(); + }; + _partChips.Add(chip); + _leftScroll.Controls.Add(chip); + x += 90; + } + + private void AddShape(int y, ref int x, CrosshairShapeKind kind) + { + ChipButton chipButton = new ChipButton + { + Text = ShapeLabel(kind), + Location = new Point(x, y), + Size = new Size(100, 32), + Font = Fonts.Caption, + AccessibleRole = AccessibleRole.RadioButton, + Active = (CrosshairShapeKinds.Of(_current) == kind) + }; + chipButton.Click += (object? _, EventArgs _) => + { + CrosshairShapeKinds.Apply(_current, kind); + Push(); + HighlightActivePreset(); + }; + _shapeChips.Add(chipButton); + _leftScroll.Controls.Add(chipButton); + x += 108; + } + + private static string ShapeLabel(CrosshairShapeKind kind) + { + return kind switch + { + CrosshairShapeKind.Cross => "Cross", + CrosshairShapeKind.T => "T", + CrosshairShapeKind.Circle => "Circle", + CrosshairShapeKind.Dot => "Dot only", + CrosshairShapeKind.Chevron => "Chevron", + _ => kind.ToString(), + }; + } + + private void RefreshPartChips() + { + if (_partChips.Count >= 6) + { + _partChips[0].Active = _current.ResolvedArmTop; + _partChips[1].Active = _current.ResolvedArmBottom; + _partChips[2].Active = _current.ResolvedArmLeft; + _partChips[3].Active = _current.ResolvedArmRight; + _partChips[4].Active = _current.ResolvedCentreDot; + _partChips[5].Active = _current.ResolvedShowCircle; + } + } + + private void RefreshShapeChips() + { + CrosshairShapeKind? crosshairShapeKind = CrosshairShapeKinds.Of(_current); + for (int i = 0; i < _shapeChips.Count; i++) + { + _shapeChips[i].Active = crosshairShapeKind == CrosshairShapeKinds.All[i]; + } + } + + private void ShowTheColourPicker() + { + int y = Math.Max(0, S(_wheelTop) - S(17)); + _leftScroll.AutoScrollPosition = new Point(0, y); + UpdateMoreOptions(); + _leftScroll.Invalidate(invalidateChildren: true); + } + + internal void TestShowTheColourPicker() + { + ShowTheColourPicker(); + } + + private void UpdateMoreOptions() + { + if (_moreOptionsFade != null) + { + int num = _leftScroll.DisplayRectangle.Height - _leftScroll.ClientSize.Height; + _moreOptionsFade.Visible = num > 0 && -_leftScroll.AutoScrollPosition.Y < num; + } + } + + private void FitPageToCards() + { + if (!_scaledByTheBase || !Visible || _fittingPage) + { + return; + } + _fittingPage = true; + try + { + FitScrollToContent(0); + if (AutoScrollMinSize.Height <= ClientSize.Height && DisplayRectangle.Height > ClientSize.Height) + { + AutoScroll = false; + AutoScroll = true; + } + } + finally + { + _fittingPage = false; + } + } + + protected override void OnVisibleChanged(EventArgs e) + { + base.OnVisibleChanged(e); + if (Visible && _scaledByTheBase) + { + LayOutAcrossTheWidth(); + } + } + + private int S(int logical) + { + if (!_scaledByTheBase) + { + return logical; + } + return (int)Math.Round((float)logical * ((float)Tokens.Dpi / 96f)); + } + + protected override void OnHandleCreated(EventArgs e) + { + base.OnHandleCreated(e); + _scaledByTheBase = true; + _followedDpi = Tokens.Dpi; + LayOutTheRightPanel(); + LayOutAcrossTheWidth(); + RefreshSavedList(); + } + + private void FollowTheMonitor() + { + if (!_scaledByTheBase || IsDisposed) + { + return; + } + int dpi = Tokens.Dpi; + if (dpi == _followedDpi) + { + return; + } + ApplyDpi(dpi); + _followedDpi = dpi; + foreach (var ownLabel in _ownLabels) + { + Label item = ownLabel.Label; + FontRole item2 = ownLabel.Role; + item.Font = Fonts.For(item2); + } + UseShareCodeFont(); + _hexBox.Inner.Font = Fonts.Mono; + LayOutTheRightPanel(); + RefreshSavedList(); + } + + private void UseShareCodeFont() + { + Font font = Fonts.Of(FontRole.Caption, Fonts.MonoFamily); + _codeBox.Inner.Font = font; + if (_codeBox.Inner.Font != font) + { + font.Dispose(); + return; + } + _shareCodeFont?.Dispose(); + _shareCodeFont = font; + _codeBox.PerformLayout(); + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + if (disposing) + { + _shareCodeFont?.Dispose(); + _shareCodeFont = null; + } + } + + private void LayOutAcrossTheWidth() + { + FollowTheMonitor(); + int num = S(16); + int num2 = Width + 1 - num; + int num3 = S(348); + int num4 = Math.Clamp(num2 - num - S(16) - num3, S(430), S(568)); + int y = ((_scaledByTheBase && HasHeaderPanel) ? (ContentTop + AutoScrollPosition.Y) : _card.Top); + _card.SetBounds(num, y, num4, S(508)); + _leftScroll.SetBounds(0, 0, num4, S(492)); + _moreOptionsFade.SetBounds(S(1), S(492), num4 - S(2), S(15)); + _moreOptions.SetBounds((_moreOptionsFade.Width - S(136)) / 2, 0, S(136), S(15)); + _moreOptions.Font = Fonts.Caption; + LayOutTheLeftPanel(num4); + _right.SetBounds(num + num4 + S(16), y, num3, S(508)); + int num5 = S(4); + _rightScroll.SetBounds(S(17) - num5, S(17), num3 - 2 * S(17) + 2 * num5, S(508) - 2 * S(17)); + LayOutTheRightPanel(); + FitPageToCards(); + UpdateMoreOptions(); + } + + private void LayOutTheRightPanel() + { + int num = S(4); + int num2 = _rightScroll.Width - 2 * num; + if (num2 <= 0) + { + return; + } + int y = _rightScroll.AutoScrollPosition.Y; + _families.SetBounds(num, y, Math.Min(num2, _families.NaturalWidth), S(32)); + IReadOnlyList designs = CrosshairGallery.All; + int num3 = Math.Clamp((_familyOrder.Max((CrosshairGallery.Family family) => Enumerable.Count(designs, (CrosshairGallery.GalleryItem i) => i.Group == family)) + 3) / 4, 1, 3); + int num4 = num3 * 72 + (num3 - 1) * 8; + _galleryHost.SetBounds(num, S(44) + y, num2, S(num4)); + int num5 = S(44 + num4 + 16); + int num6 = S(4); + if (_showDesignsOnTheirWay) + { + int num7 = Math.Max(S(20), TextRenderer.MeasureText(_designsOnTheirWay.Text, _designsOnTheirWay.Font, new Size(num2, int.MaxValue), TextFormatFlags.WordBreak).Height); + _designsOnTheirWay.SetBounds(num - num6, y, num2 + num6, num7); + num5 = num7 + S(16); + } + else + { + _designsOnTheirWay.SetBounds(num - num6, y, num2 + num6, 0); + } + int num8 = S(24); + _shareHint.Top = num5 + y; + _shareHint.Height = num8; + PlaceInk(_shareHint, num + num2 - Advance(_shareHint.Text, _shareHint.Font)); + _shareCaption.Top = num5 + y; + _shareCaption.Height = num8; + PlaceInk(_shareCaption, num); + _shareCaption.Width = Math.Min(_shareCaption.Width, Math.Max(S(40), _shareHint.Left - _shareCaption.Left)); + num5 += num8 + S(12); + _codeBox.SetBounds(num, num5 + y, num2, S(32)); + num5 += S(32) + S(8); + int width = _copyCode.GetPreferredSize(Size.Empty).Width; + int width2 = _applyCode.GetPreferredSize(Size.Empty).Width; + _copyCode.SetBounds(num, num5 + y, width, S(32)); + _applyCode.SetBounds(num + width + S(8), num5 + y, width2, S(32)); + num5 += S(32) + S(4); + int num9 = S(4); + _shareStatus.SetBounds(num - num9, num5 + y, num2 + num9, S(32)); + num5 += S(32) + S(12); + int num10 = _note.HeightFor(num2); + int height = _rightScroll.ClientSize.Height; + int num11 = Math.Max(num5, height - num10); + _note.SetBounds(num, num11 + y, num2, num10); + _rightScroll.AutoScrollMinSize = new Size(0, num11 + num10); + LayOutGallery(); + } + + private void LayOutTheLeftPanel(int panelW) + { + int num = Math.Max(S(200), panelW - 2 * S(17)); + int num2 = (num - S(32)) / 2; + int num3 = S(17); + int num4 = num3 + num2 + S(32); + int num5 = S(4); + int num6 = S(80); + _preview.SetBounds(num3, _preview.Top, num, _preview.Height); + foreach (var row in _rows) + { + Label item = row.Name; + Label item2 = row.Value; + FlatSlider item3 = row.Slider; + int num7 = (row.Second ? num4 : num3); + int num8 = InkInsetOf(item); + int num9 = InkInsetOf(item2); + item.SetBounds(num7 - num8, item.Top, num2 - num6 + num8, item.Height); + item2.SetBounds(num7 + num2 - num6, item2.Top, num6 + num9, item2.Height); + item3.SetTrackBounds(num7, item3.Top, num2, item3.Height); + } + LayOutASwatchRow(_colourWord, _colourDots.Cast().Append(_anyColour), num3); + LayOutASwatchRow(_outlineColourWord, _outlineDots, num3); + _opacityRight = num3 + num; + LayOutTheOpacityReadout(); + _outlineWord.SetBounds(num3 - num5, _outlineWord.Top, num - S(50) + num5, _outlineWord.Height); + _outlineSwitch.Left = num3 + num - _outlineSwitch.Width; + _shapeWord.Width = num + num5; + _partsWord.Width = num + num5; + int num10 = S(8); + int num11 = (num - 4 * num10) / 5; + for (int i = 0; i < _shapeChips.Count; i++) + { + _shapeChips[i].SetBounds(num3 + i * (num11 + num10), _shapeChips[i].Top, num11, _shapeChips[i].Height); + } + for (int j = 0; j < _partChips.Count; j++) + { + int num12 = (num + num10) * j / 6; + int num13 = (num + num10) * (j + 1) / 6 - num10; + _partChips[j].SetBounds(num3 + num12, _partChips[j].Top, num13 - num12, _partChips[j].Height); + } + _hexNote.Width = Math.Max(S(40), num3 + num - _hexNote.Left); + _imageNote.MaximumSize = new Size(num, 0); + _status.Width = num; + _saveBtn.Left = num3 + num - _saveBtn.Width; + _savedFlow.MaximumSize = new Size(Math.Max(S(40), num - S(140)), 0); + _savedEmpty.Width = Math.Max(S(40), num - S(140)); + } + + private void LayOutASwatchRow(Label word, IEnumerable boxes, int c1) + { + PlaceInk(word, c1); + int num = c1 + Advance(word.Text, word.Font) + S(8); + int num2 = S(28); + int num3 = num2 + S(8); + foreach (Control box in boxes) + { + box.SetBounds(num, box.Top, num2, num2); + num += num3; + } + } + + private void LayOutTheOpacityReadout() + { + if (_opacityRight > 0) + { + int num = _opacityRight - Advance(_opacityValue.Text, _opacityValue.Font); + PlaceInk(_opacityValue, num); + PlaceInk(_opacityWord, num - S(8) - Advance(_opacityWord.Text, _opacityWord.Font)); + } + } + + private CrosshairGallery.Family OpeningFamily() + { + CrosshairGallery.GalleryItem? galleryItem = CrosshairGallery.Matching(_current); + CrosshairGallery.Family? family = (((object)galleryItem != null) ? new CrosshairGallery.Family?(galleryItem.Group) : FamilyForShape(_current)); + if (family.HasValue) + { + CrosshairGallery.Family valueOrDefault = family.GetValueOrDefault(); + if (_familyOrder.Contains(valueOrDefault)) + { + return valueOrDefault; + } + } + return _familyOrder[0]; + } + + private void DecideWhereTheDesignsAre(bool noDesigns) + { + _showDesignsOnTheirWay = noDesigns && ServedCrosshairs.OnTheirWay; + _families.Visible = !_showDesignsOnTheirWay; + _galleryHost.Visible = !_showDesignsOnTheirWay; + _designsOnTheirWay.Visible = _showDesignsOnTheirWay; + _designsOnTheirWay.Text = (_showDesignsOnTheirWay ? DesignsWaitingWords() : ""); + } + + private static string DesignsWaitingWords() + { + return PcClock.WaitingWords("Crosshair designs are on the way. They load when PlexusX reaches our server."); + } + + internal void ReloadServedDesigns() + { + int generation = ServedCrosshairs.Generation; + if (generation == _designsGeneration) + { + if (_showDesignsOnTheirWay && _designsOnTheirWay.Text != DesignsWaitingWords()) + { + _designsOnTheirWay.Text = DesignsWaitingWords(); + LayOutTheRightPanel(); + Invalidate(invalidateChildren: true); + } + return; + } + if (_cells.Count == 0 && CrosshairGallery.All.Count > 0) + { + _family = OpeningFamily(); + _families.Active = FamilyWord(_family); + } + RebuildingTheGalleryForTest?.Invoke(); + BuildGallery(); + LayOutTheRightPanel(); + _designsGeneration = generation; + Invalidate(invalidateChildren: true); + } + + internal void TestChooseFamily(CrosshairGallery.Family family) + { + _families.TestChoose(FamilyWord(family)); + } + + private void BuildGallery() + { + foreach (CrosshairCell cell in _cells) + { + cell.Dispose(); + } + _galleryHost.Controls.Clear(); + _cells.Clear(); + List list = _settings.FavouriteCrosshairs ?? new List(); + IReadOnlyList all = CrosshairGallery.All; + DecideWhereTheDesignsAre(all.Count == 0); + if (all.Count > 0) + { + HashSet galleryIds = new HashSet(all.Select((CrosshairGallery.GalleryItem g) => g.Id), StringComparer.Ordinal); + if (list.RemoveAll((string id) => !galleryIds.Contains(id)) > 0) + { + _store.Save(_settings); + } + } + HashSet favouriteSet = new HashSet(list, StringComparer.Ordinal); + foreach (CrosshairGallery.GalleryItem item in all.Where((CrosshairGallery.GalleryItem i) => favouriteSet.Contains(i.Id)).Concat(all.Where((CrosshairGallery.GalleryItem i) => !favouriteSet.Contains(i.Id)))) + { + CrosshairCell crosshairCell = new CrosshairCell(item) + { + PreviewStyle = _current, + Favourite = favouriteSet.Contains(item.Id) + }; + CrosshairGallery.GalleryItem captured = item; + crosshairCell.Click += (object? _, EventArgs _) => + { + ApplyGalleryItem(captured); + }; + crosshairCell.FavouriteToggled += (object? _, EventArgs _) => + { + ToggleFavourite(captured); + }; + _cells.Add(crosshairCell); + _galleryHost.Controls.Add(crosshairCell); + } + LayOutGallery(); + HighlightActivePreset(); + } + + private void LayOutGallery() + { + int width = _galleryHost.Width; + if (width <= 0) + { + return; + } + int num = S(8); + int num2 = S(72); + double num3 = (double)(width + num) / 4.0; + _galleryHost.SuspendLayout(); + int num4 = 0; + foreach (CrosshairCell cell in _cells) + { + if (cell.Visible = cell.Item.Group == _family) + { + int num5 = num4 % 4; + int num6 = num4 / 4; + int num7 = (int)Math.Round((double)num5 * num3); + int num8 = (int)Math.Round((double)(num5 + 1) * num3 - (double)num); + cell.SetBounds(num7, num6 * (num2 + num) + _galleryHost.AutoScrollPosition.Y, Math.Max(1, num8 - num7), num2); + num4++; + } + } + _galleryHost.ResumeLayout(performLayout: true); + } + + private void ApplyGalleryItem(CrosshairGallery.GalleryItem item) + { + _current.ImagePath = null; + CrosshairGallery.Apply(_current, item); + _applyingPreset = true; + try + { + _sizeSlider.Value = Math.Clamp((int)Math.Round(_current.ResolvedSize * 10f), _sizeSlider.Minimum, _sizeSlider.Maximum); + _thicknessSlider.Value = Math.Clamp((int)Math.Round(_current.ResolvedThickness * 10f), _thicknessSlider.Minimum, _thicknessSlider.Maximum); + _gapSlider.Value = Math.Clamp((int)Math.Round(_current.ResolvedGap * 10f), _gapSlider.Minimum, _gapSlider.Maximum); + _rotationSlider.Value = Math.Clamp(_current.ResolvedRotationDegrees, _rotationSlider.Minimum, _rotationSlider.Maximum); + } + finally + { + _applyingPreset = false; + } + CrosshairGallery.Apply(_current, item); + Push(); + SyncImageControls(); + HighlightActivePreset(); + } + + private void ApplyColour(Color colour, Control? source) + { + if (_syncingColour) + { + return; + } + _syncingColour = true; + try + { + _current.ColourArgb = (_current.ColourArgb & -16777216) | (colour.ToArgb() & 0xFFFFFF); + foreach (SwatchDot colourDot in _colourDots) + { + colourDot.Active = (colourDot.Colour.ToArgb() & 0xFFFFFF) == (_current.ColourArgb & 0xFFFFFF); + } + if (source != _wheel) + { + _wheel.Colour = colour; + } + if (source != _hexBox) + { + _hexBox.Text = ColourWheel.ToHex(colour); + } + Push(); + RefreshGalleryPreviews(); + } + finally + { + _syncingColour = false; + } + } + + private void RefreshGalleryPreviews() + { + foreach (CrosshairCell cell in _cells) + { + cell.PreviewStyle = _current; + cell.Invalidate(); + } + } + + private void ToggleFavourite(CrosshairGallery.GalleryItem item) + { + AppSettings settings = _settings; + if (settings.FavouriteCrosshairs == null) + { + List list = (settings.FavouriteCrosshairs = new List()); + } + if (!_settings.FavouriteCrosshairs.Remove(item.Id)) + { + _settings.FavouriteCrosshairs.Add(item.Id); + } + _store.Save(_settings); + BuildGallery(); + } + + private void OnSliderMoved() + { + if (!_applyingPreset) + { + Push(); + HighlightActivePreset(); + } + } + + private void HighlightActivePreset() + { + CrosshairGallery.GalleryItem galleryItem = CrosshairGallery.Matching(_current); + foreach (CrosshairCell cell in _cells) + { + cell.Active = galleryItem != null && cell.Item.Id == galleryItem.Id; + cell.PreviewStyle = _current; + cell.Invalidate(); + } + RefreshPartChips(); + RefreshShapeChips(); + } + + private void Push() + { + _preview.Config = _current; + _preview.Invalidate(); + _service.Apply(_current.Clone()); + _settings.ActiveCrosshair = _current.Clone(); + _store.Save(_settings); + UpdateStatus(); + } + + private void UpdateStatus() + { + _onLabel.Text = (_enabled.Checked ? "On" : "Off"); + LayoutHeaderPanel(); + if (!_enabled.Checked) + { + _status.Text = "Crosshair is off."; + _status.ForeColor = Theme.TextDim; + } + else if (CrosshairService.IsExclusiveFullscreen()) + { + _status.Text = "A game is in exclusive full-screen - no overlay can draw there. Switch it to borderless."; + _status.ForeColor = Theme.Accent; + } + else + { + _status.Text = "Crosshair is showing, centred on your screen."; + _status.ForeColor = Theme.TextDim; + } + } + + internal void TestSetEnabled(bool on) + { + _enabled.Checked = on; + } + + private void RefreshSavedList() + { + _savedFlow.SuspendLayout(); + _savedFlow.Controls.Clear(); + foreach (CrosshairConfig saved in _settings.SavedCrosshairs) + { + SavedChip savedChip = new SavedChip(saved) + { + Active = (saved.Name == _current.Name), + Size = new Size(AtDesignScale(190), AtDesignScale(36)), + Margin = new Padding(0, 0, AtDesignScale(8), AtDesignScale(8)) + }; + savedChip.LoadRequested += (object? s, EventArgs e2) => + { + LoadSaved(saved.Name); + }; + savedChip.DeleteRequested += (object? s, EventArgs e2) => + { + DeleteSaved(saved.Name); + }; + _savedFlow.Controls.Add(savedChip); + } + _savedFlow.ResumeLayout(performLayout: true); + bool flag = _settings.SavedCrosshairs.Count > 0; + _savedFlow.Visible = flag; + _savedEmpty.Visible = !flag; + int num = (flag ? _savedFlow.Bottom : _savedEmpty.Bottom) - _leftScroll.AutoScrollPosition.Y; + _leftScroll.AutoScrollMinSize = new Size(0, num + S(17) + S(8)); + FitScrollToContent(0); + } + + private void CopyMyCode() + { + string text = CrosshairCode.Encode(_current); + _codeBox.Text = text; + bool flag = TheClipboard.Put(text); + SetShareStatus(flag ? "Copied. Paste it to a friend." : "Couldn't reach the clipboard. Copy the code from the box above.", flag ? Theme.Accent : Theme.TextDim); + } + + internal void ApplyLibraryCrosshair(CrosshairConfig incoming) + { + if (incoming != null) + { + incoming.Name = _current.Name; + _current = incoming; + SyncControlsToCurrent(); + Push(); + RefreshGalleryPreviews(); + } + } + + private void ApplySharedCode() + { + if (!CrosshairCode.TryDecode(_codeBox.Text, out CrosshairConfig crosshair)) + { + SetShareStatus("That code isn't valid. Nothing changed.", Theme.Negative); + return; + } + crosshair.Name = _current.Name; + _current = crosshair; + SyncControlsToCurrent(); + Push(); + RefreshGalleryPreviews(); + SetShareStatus("Applied.", Theme.Accent); + } + + private void SetShareStatus(string text, Color colour) + { + _shareStatus.Text = text; + _shareStatus.ForeColor = colour; + } + + private void LoadSaved(string name) + { + CrosshairConfig crosshairConfig = _settings.SavedCrosshairs.FirstOrDefault((CrosshairConfig crosshairConfig2) => string.Equals(crosshairConfig2.Name, name, StringComparison.OrdinalIgnoreCase)); + if (crosshairConfig != null) + { + _current = crosshairConfig.Clone(); + SyncControlsToCurrent(); + Push(); + RefreshSavedList(); + } + } + + private void SyncControlsToCurrent() + { + _applyingPreset = true; + try + { + _current.SetSizeTenths(Set(_sizeSlider, (int)Math.Round(_current.ResolvedSize * 10f))); + _current.SetThicknessTenths(Set(_thicknessSlider, (int)Math.Round(_current.ResolvedThickness * 10f))); + _current.SetGapTenths(Set(_gapSlider, (int)Math.Round(_current.ResolvedGap * 10f))); + _current.DotSizeTenths = Set(_dotSlider, (int)Math.Round(_current.ResolvedDotSize * 10f)); + _current.CircleRadiusTenths = Set(_circleSlider, (int)Math.Round(_current.ResolvedCircleRadius * 10f)); + _current.Opacity = Set(_opacitySlider, _current.Opacity); + _current.OffsetXPx = Set(_offsetXSlider, _current.ResolvedOffsetX); + _current.OffsetYPx = Set(_offsetYSlider, _current.ResolvedOffsetY); + _current.OutlineThicknessTenths = Set(_outlineSlider, _current.OutlineThicknessTenths ?? 10); + _current.ImageScalePercent = Set(_imageScaleSlider, _current.ImageScalePercent); + _current.SetRotationDegrees(Set(_rotationSlider, _current.ResolvedRotationDegrees)); + _current.DotOpacity = Set(_dotOpacitySlider, _current.ResolvedDotOpacity); + _outlineSwitch.Checked = _current.Outline; + _wheel.Colour = Color.FromArgb(_current.ColourArgb); + _hexBox.Text = ColourWheel.ToHex(Color.FromArgb(_current.ColourArgb)); + } + finally + { + _applyingPreset = false; + } + _opacityValue.Text = $"{_opacitySlider.Value}%"; + HighlightActivePreset(); + SyncColourDots(); + SyncOutlineDots(); + SyncImageControls(); + static int Set(FlatSlider slider, int value) + { + return slider.Value = Math.Clamp(value, slider.Minimum, slider.Maximum); + } + } + + private void SaveCurrent() + { + string text = Prompt.Ask("Save crosshair as", _current.Name); + if (!string.IsNullOrWhiteSpace(text)) + { + SaveCurrentAs(text); + } + } + + private void SaveCurrentAs(string name) + { + name = name.Trim(); + if (WouldExceedCap(name)) + { + GlassDialog.Show(FindForm(), "Presets full", $"You already have {10} saved crosshairs - the most this " + "page keeps. Delete one to save a new one."); + return; + } + _current.Name = name; + _settings.SavedCrosshairs.RemoveAll((CrosshairConfig crosshairConfig) => string.Equals(crosshairConfig.Name, _current.Name, StringComparison.OrdinalIgnoreCase)); + _settings.SavedCrosshairs.Add(_current.Clone()); + _store.Save(_settings); + RefreshSavedList(); + } + + private bool WouldExceedCap(string trimmedName) + { + if (!_settings.SavedCrosshairs.Any((CrosshairConfig crosshairConfig) => string.Equals(crosshairConfig.Name, trimmedName, StringComparison.OrdinalIgnoreCase))) + { + return _settings.SavedCrosshairs.Count >= 10; + } + return false; + } + + internal void TestSaveCurrentAs(string name) + { + SaveCurrentAs(name); + } + + internal bool TestWouldRefuseSave(string name) + { + return WouldExceedCap(name.Trim()); + } + + internal void TestDeleteSaved(string name) + { + DeleteSaved(name); + } + + internal void TestLoadSaved(string name) + { + LoadSaved(name); + } + + private int CountOf() where T : Control + { + int n = 0; + Walk(this); + return n; + void Walk(Control parent) + { + foreach (Control control in parent.Controls) + { + if (control is T) + { + n++; + } + Walk(control); + } + } + } + + private void DeleteSaved(string name) + { + _settings.SavedCrosshairs.RemoveAll((CrosshairConfig crosshairConfig) => string.Equals(crosshairConfig.Name, name, StringComparison.OrdinalIgnoreCase)); + _store.Save(_settings); + RefreshSavedList(); + } + + private void SyncColourDots() + { + foreach (SwatchDot colourDot in _colourDots) + { + colourDot.Active = colourDot.Colour.ToArgb() == _current.ColourArgb; + } + } + + private void ApplyOutlineColour(Color colour) + { + _current.OutlineColourRgb = colour.ToArgb() & 0xFFFFFF; + SyncOutlineDots(); + Push(); + HighlightActivePreset(); + } + + private void SyncOutlineDots() + { + int num = _current.ResolvedOutlineColourArgb & 0xFFFFFF; + foreach (OutlineSwatch outlineDot in _outlineDots) + { + outlineDot.Active = (outlineDot.Colour.ToArgb() & 0xFFFFFF) == num; + } + } + + private void SyncImageControls() + { + bool usesImage = _current.UsesImage; + _clearImageBtn.Visible = usesImage; + _imageNote.Text = (usesImage ? "Using your image. The shape, size and colour controls below do not apply to it - opacity, image size and position still do." : ""); + foreach (ChipButton partChip in _partChips) + { + partChip.Enabled = !usesImage; + } + _sizeSlider.Enabled = !usesImage; + _thicknessSlider.Enabled = !usesImage; + _gapSlider.Enabled = !usesImage; + _dotSlider.Enabled = !usesImage; + _circleSlider.Enabled = !usesImage; + _offsetXSlider.Enabled = true; + _offsetYSlider.Enabled = true; + _outlineSlider.Enabled = !usesImage; + _imageScaleSlider.Enabled = usesImage; + _wheel.Enabled = !usesImage; + _hexBox.Enabled = !usesImage; + foreach (SwatchDot colourDot in _colourDots) + { + colourDot.Enabled = !usesImage; + } + foreach (ChipButton shapeChip in _shapeChips) + { + shapeChip.Enabled = !usesImage; + } + _rotationSlider.Enabled = !usesImage; + _dotOpacitySlider.Enabled = !usesImage; + foreach (OutlineSwatch outlineDot in _outlineDots) + { + outlineDot.Enabled = !usesImage; + } + } + + private void ImportImage() + { + using OpenFileDialog openFileDialog = new OpenFileDialog + { + Title = "Pick a crosshair image", + Filter = "Images (*.png;*.bmp;*.gif;*.jpg)|*.png;*.bmp;*.gif;*.jpg|All files (*.*)|*.*", + CheckFileExists = true + }; + if (openFileDialog.ShowDialog(this) == DialogResult.OK) + { + if (!ImageCrosshair.TryImport(openFileDialog.FileName, ImageStoreDir, out string stored, out string error)) + { + _imageNote.ForeColor = Theme.TextDim; + _imageNote.Text = error; + return; + } + _current.ImagePath = stored; + _imageNote.ForeColor = Theme.TextDim; + Push(); + SyncImageControls(); + } + } + + private static GlassButton Button(string text, int x, int y, int w) + { + GlassButton glassButton = SettingsPage.FlatButton(text, x, y, w); + glassButton.Height = 32; + return glassButton; + } +} \ No newline at end of file diff --git a/VibranceHud/Pages/DarkBoostPage.cs b/VibranceHud/Pages/DarkBoostPage.cs new file mode 100644 index 0000000..ca5262f --- /dev/null +++ b/VibranceHud/Pages/DarkBoostPage.cs @@ -0,0 +1,1745 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; +using A; +using VibranceHud.Controls; +using VibranceHud.DarkBoost; +using VibranceHud.Design; +using VibranceHud.Games; +using VibranceHud.Licensing; +using VibranceHud.Zoom; + +namespace VibranceHud.Pages; + +public sealed class DarkBoostPage : GlowPage +{ + private sealed class StateLabel : Control + { + public StateLabel() + { + TabStop = false; + SetStyle(ControlStyles.Selectable, value: false); + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + Size = new Size(S(60), S(20)); + Text = "Ready"; + } + + protected override void OnTextChanged(EventArgs e) + { + base.OnTextChanged(e); + Remeasure(); + } + + internal void Remeasure() + { + Size = new Size(TextRenderer.MeasureText(Text, Fonts.Body, Size.Empty, TextFormatFlags.SingleLine | TextFormatFlags.NoPadding).Width + 2, S(20)); + Invalidate(); + } + + protected override void OnPaint(PaintEventArgs e) + { + TextRenderer.DrawText(e.Graphics, Text, Fonts.Body, ClientRectangle, Theme.TextDim, TextFormatFlags.Right | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding); + } + } + + private sealed class WarningIcon : Control + { + public WarningIcon() + { + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + TabStop = false; + AccessibleRole = AccessibleRole.Graphic; + AccessibleName = "Warning"; + } + + protected override void OnPaint(PaintEventArgs e) + { + SignalIcons.Draw(e.Graphics, SignalIcon.Warning, new RectangleF(0f, 0f, Width, Height), Theme.Negative); + } + } + + private sealed class AddOnTag : Control + { + private readonly bool _lock; + + internal Size NaturalSize + { + get + { + int width = TextRenderer.MeasureText(Text, Fonts.CaptionBold, Size.Empty, TextFormatFlags.SingleLine | TextFormatFlags.NoPadding).Width; + return new Size(S(8) + (_lock ? (S(12) + S(4)) : 0) + width + S(8) + 2, S(20)); + } + } + + public AddOnTag(bool withLock) + { + TabStop = false; + SetStyle(ControlStyles.Selectable, value: false); + _lock = withLock; + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + Text = "Add-on"; + AccessibleName = (withLock ? "Add-on, locked" : "Add-on"); + AccessibleRole = AccessibleRole.StaticText; + Size = NaturalSize; + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics graphics = e.Graphics; + int dpi = ControlInk.Dpi(this); + ControlInk.PaintBox(graphics, Size, ControlInk.PxF(dpi, 4f), ControlInk.Hairline(dpi), Color.Transparent, ControlInk.Edge); + int num = S(8); + if (_lock) + { + graphics.SmoothingMode = SmoothingMode.AntiAlias; + SignalIcons.Draw(graphics, SignalIcon.Lock, new RectangleF(num, (float)(Height - S(12)) / 2f, S(12), S(12)), Theme.TextDim); + num += S(12) + S(4); + } + TextRenderer.DrawText(graphics, Text, Fonts.CaptionBold, new Rectangle(num, 0, Width - num, Height), Theme.TextDim, TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding); + } + } + + private sealed class FactLine : Control + { + private readonly string _bold; + + private readonly string _rest; + + public FactLine(string bold, string rest) + { + TabStop = false; + SetStyle(ControlStyles.Selectable, value: false); + _bold = bold; + _rest = rest; + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + Text = bold + rest; + AccessibleRole = AccessibleRole.StaticText; + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics graphics = e.Graphics; + graphics.SmoothingMode = SmoothingMode.AntiAlias; + float num = S(6); + using (SolidBrush brush = new SolidBrush(Theme.TextFaint)) + { + graphics.FillEllipse(brush, 0f, ((float)Height - num) / 2f, num, num); + } + int num2 = S(16); + TextRenderer.DrawText(graphics, _bold, Fonts.BodyBold, new Rectangle(num2, 0, Width - num2, Height), Theme.Text, TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding); + num2 += TextRenderer.MeasureText(graphics, _bold, Fonts.BodyBold, Size.Empty, TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding).Width; + TextRenderer.DrawText(graphics, _rest, Fonts.Body, new Rectangle(num2, 0, Math.Max(0, Width - num2), Height), Theme.TextDim, TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding); + } + } + + private sealed class TintTile : Control + { + private sealed class TintAccessibility : ControlAccessibleObject + { + private readonly TintTile _tile; + + public override AccessibleStates State => (AccessibleStates)((int)base.State | (_tile.Selected ? 16 : 0)); + + internal TintAccessibility(TintTile tile) + : base(tile) + { + _tile = tile; + } + } + + private bool _selected; + + private bool _hover; + + private const double CleanHi = 0.8; + + private const double CleanLo = 4.0 / 15.0; + + private static readonly double[] CleanRed = new double[3] + { + 0.8, + 4.0 / 15.0, + 4.0 / 15.0 + }; + + private static readonly double[] CleanGreen = new double[3] + { + 4.0 / 15.0, + 0.8, + 4.0 / 15.0 + }; + + private static readonly double[] CleanBlue = new double[3] + { + 4.0 / 15.0, + 4.0 / 15.0, + 0.8 + }; + + internal DarkBoostTint Tint { get; } + + internal bool Selected + { + get + { + return _selected; + } + set + { + if (_selected != value) + { + _selected = value; + AccessibilityNotifyClients(AccessibleEvents.StateChange, -1); + Invalidate(); + } + } + } + + public TintTile(DarkBoostTint tint) + { + Tint = tint; + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.Selectable | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + Text = DarkBoostTints.Name(tint); + AccessibleName = Text; + AccessibleRole = AccessibleRole.RadioButton; + TabStop = true; + Cursor = Cursors.Hand; + } + + protected override AccessibleObject CreateAccessibilityInstance() + { + return new TintAccessibility(this); + } + + protected override void OnKeyDown(KeyEventArgs e) + { + Keys keyCode = e.KeyCode; + if ((keyCode == Keys.Return || keyCode == Keys.Space) ? true : false) + { + OnClick(EventArgs.Empty); + e.Handled = true; + } + base.OnKeyDown(e); + } + + protected override void OnEnabledChanged(EventArgs e) + { + base.OnEnabledChanged(e); + Invalidate(); + } + + protected override void OnGotFocus(EventArgs e) + { + base.OnGotFocus(e); + Invalidate(); + } + + protected override void OnLostFocus(EventArgs e) + { + base.OnLostFocus(e); + Invalidate(); + } + + protected override void OnMouseEnter(EventArgs e) + { + base.OnMouseEnter(e); + _hover = true; + Invalidate(); + } + + protected override void OnMouseLeave(EventArgs e) + { + base.OnMouseLeave(e); + _hover = false; + Invalidate(); + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics graphics = e.Graphics; + int dpi = ControlInk.Dpi(this); + int line = ControlInk.Hairline(dpi); + float radius = ControlInk.PxF(dpi, 4f); + if (_selected) + { + ControlInk.PaintBox(graphics, Size, radius, line, Enabled ? ControlInk.Accent : ControlInk.Surface2, Color.Transparent); + } + else + { + ControlInk.PaintBox(graphics, Size, radius, line, (Enabled && _hover) ? ControlInk.Hover : Color.Transparent, Enabled ? ControlInk.Edge : ControlInk.TextDisabled); + } + RectangleF rect = new RectangleF((float)(Width - S(28)) / 2f, S(12), S(28), S(6)); + graphics.SmoothingMode = SmoothingMode.AntiAlias; + using (GraphicsPath path = Glass.RoundedPath(rect, rect.Height / 2f)) + { + double[] array = DarkBoostTints.PreviewWeights(Tint); + if (array != null) + { + using SolidBrush brush = new SolidBrush(Swatch(array)); + graphics.FillPath(brush, path); + } + else + { + using LinearGradientBrush linearGradientBrush = new LinearGradientBrush(rect, Theme.TextDim, Theme.TextDim, LinearGradientMode.Horizontal); + linearGradientBrush.InterpolationColors = new ColorBlend + { + Colors = new Color[3] + { + Swatch(CleanRed), + Swatch(CleanGreen), + Swatch(CleanBlue) + }, + Positions = new float[3] { 0f, 0.5f, 1f } + }; + graphics.FillPath(linearGradientBrush, path); + } + } + Color foreColor; + if (Enabled) + { + foreColor = (_selected ? ControlInk.OnAccent : Theme.Text); + } + else + { + foreColor = ControlInk.TextDisabledInk; + } + TextRenderer.DrawText(graphics, Text, Fonts.BodyBold, new Rectangle(0, S(24), Width, S(20)), foreColor, TextFormatFlags.HorizontalCenter | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding); + if (Focused && ShowFocusCues) + { + ControlInk.PaintBox(graphics, Size, radius, ControlInk.Px(dpi, 2), Color.Transparent, _selected ? ControlInk.OnAccent : ControlInk.Focus); + } + } + + private static Color Swatch(double[] w) + { + return Color.FromArgb(255, (int)Math.Round(w[0] * 255.0), (int)Math.Round(w[1] * 255.0), (int)Math.Round(w[2] * 255.0)); + } + } + + private sealed class ScenePreview : Control + { + private Bitmap? _picture; + + internal Bitmap? Picture + { + get + { + return _picture; + } + set + { + Bitmap? picture = _picture; + _picture = value; + picture?.Dispose(); + Invalidate(); + } + } + + public ScenePreview() + { + TabStop = false; + SetStyle(ControlStyles.Selectable, value: false); + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + BackColor = Color.Transparent; + AccessibleRole = AccessibleRole.Graphic; + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics graphics = e.Graphics; + int num = ControlInk.Hairline(ControlInk.Dpi(this)); + if (_picture != null) + { + graphics.InterpolationMode = InterpolationMode.Bilinear; + graphics.PixelOffsetMode = PixelOffsetMode.Half; + using ImageAttributes imageAttributes = new ImageAttributes(); + imageAttributes.SetWrapMode(WrapMode.TileFlipXY); + graphics.DrawImage(_picture, new Rectangle(num, num, Width - 2 * num, Height - 2 * num), 0, 0, _picture.Width, _picture.Height, GraphicsUnit.Pixel, imageAttributes); + graphics.PixelOffsetMode = PixelOffsetMode.Default; + } + using Pen pen = new Pen(ControlInk.Border, num) + { + Alignment = PenAlignment.Inset + }; + graphics.DrawRectangle(pen, 0, 0, Width - num, Height - num); + } + } + + private const int Pad = 21; + + private const int CardGap = 16; + + private const int ViewGap = 16; + + private const int ViewHeight = 182; + + private const int StatusHeight = 84; + + private const int ColumnGap = 32; + + private const int TileHeight = 56; + + private const int TileGap = 8; + + private const int RowHeight = 56; + + private readonly VibranceEngine _engine; + + private readonly AppSettings _settings; + + private readonly Action _save; + + private readonly List _setups; + + private int _selected; + + private readonly Label _title; + + private readonly Label _subtitle; + + private readonly StateLabel _state; + + private readonly AddOnTag _headerTag; + + private readonly CardPanel _weekCard; + + private readonly CardPanel _banCard; + + private readonly Label _banTitle; + + private readonly Label _banBody; + + private readonly Label _weekTitle; + + private readonly Label _weekCaption; + + private readonly GlassButton _manage; + + private readonly GlassButton _buy; + + private readonly CardPanel _viewsCard; + + private readonly ScenePreview _now; + + private readonly ScenePreview _with; + + private readonly Label _nowCaption; + + private readonly Label _nowState; + + private readonly Label _withCaption; + + private readonly Label _withState; + + private readonly Label _tintFact; + + private readonly CardPanel _lockCard; + + private readonly Label _lockTitle; + + private readonly Label _lockCaption; + + private readonly Label _lockFootnote; + + private readonly FactLine[] _facts; + + private readonly CardPanel _settingsCard; + + private CardPanel? _zoomCard; + + private ZoomSection? _zoomSection; + + private readonly Label _settingsTitle; + + private readonly AddOnTag _settingsTag; + + private readonly Label _switchTitle; + + private readonly Label _switchCaption; + + private readonly Label _colourTitle; + + private readonly ToggleSwitch _switch; + + private readonly TintTile[] _tiles; + + private readonly Label _strengthLabel; + + private readonly Label _strengthValue; + + private readonly Label _whiteLabel; + + private readonly Label _whiteValue; + + private readonly Label _blackLabel; + + private readonly Label _blackValue; + + private readonly Label _blackReadout; + + private readonly FlatSlider _strength; + + private readonly FlatSlider _black; + + private readonly Label _keyTitle; + + private readonly Label _keyCaption; + + private readonly Label _keyError; + + private readonly SegmentStrip _mode; + + private readonly HotkeyPicker _key; + + private readonly Label _gamesTitle; + + private readonly Label _gamesCaption; + + private readonly ToggleSwitch _games; + + private readonly Label _fadeTitle; + + private readonly Label _fadeCaption; + + private readonly ToggleSwitch _fade; + + private readonly Label _setupsTitle; + + private readonly Label _setupsCaption; + + private readonly GlassButton _saveNew; + + private readonly GlassButton _delete; + + private readonly List _setupChips = new List(); + + private readonly Label _nextTitle; + + private readonly Label _nextCaption; + + private readonly HotkeyPicker _nextKey; + + private bool _owned; + + private bool _syncing; + + private int? _weekDaysLeft; + + private double _fadeFrom; + + private double _fadeTo; + + private double _nowAmount; + + private DateTime _fadeStart; + + private readonly Timer _fadeTimer = new Timer + { + Interval = 15 + }; + + internal const string KeyRefused = "That key can't be used for Dark Boost."; + + public static readonly string GamesOnlyCaption = "Works while " + string.Join(", ", from g in SupportedGames.All.Take(SupportedGames.All.Count - 1) + select g.DisplayName) + " or " + SupportedGames.All.Last().DisplayName + " runs. Turn this off for any other game."; + + public const string GamesOnlyShortCaption = "Works while one of the six supported games runs. Turn this off for any other game."; + + internal const string OnYourAccount = "Dark Boost & Zoom is on your account."; + + internal const string SeparateFromYourPlan = "Separate from your plan."; + + internal const string InviteLine = "Get a free week of Dark Boost & Zoom when 3 new players sign up with your code and open PlexusX on their own PC this month."; + + internal const string FriendPromptLine = "New here? Got a code from a friend?"; + + internal const string StartWeekLabel = "Start my free week"; + + internal const string BuyLabel = "Get Dark Boost & Zoom"; + + internal const string FreeWeekCaption = "First week free, once per account. Card needed to start it."; + + private GlassTextBox? _friendCode; + + private bool _hasWeekRows; + + internal ZoomSection? ZoomSectionForTest => _zoomSection; + + internal Control? ZoomCardForTest => _zoomCard; + + protected override bool LaysOutInLogicalPixels => false; + + internal bool Owned => _owned; + + internal int? WeekDaysLeft + { + get + { + return _weekDaysLeft; + } + set + { + _weekDaysLeft = value; + ApplyStatus(); + LayoutContent(); + } + } + + private bool OnTheWeek + { + get + { + int? weekDaysLeft = _weekDaysLeft; + if (weekDaysLeft.HasValue) + { + return weekDaysLeft.GetValueOrDefault() > 0; + } + return false; + } + } + + internal Func? AskBanRiskForTest { get; set; } + + internal Control BanCardForTest => _banCard; + + internal Label BanTitleForTest => _banTitle; + + internal Label BanBodyForTest => _banBody; + + internal bool FadeRunningForTest => _fadeTimer.Enabled; + + private DarkBoostSetup Current => _setups[DarkBoostSetups.Selected(_selected, _setups.Count)]; + + internal IReadOnlyList Setups => _setups; + + internal int SelectedSetup => _selected; + + internal IReadOnlyList SetupChipsForTest => _setupChips; + + internal string BuyUrl => "https://plexusx.lol/#pricing"; + + internal GlassButton BuyForTest => _buy; + + internal GlassTextBox FriendCodeForTest => _friendCode; + + internal ToggleSwitch SwitchForTest => _switch; + + internal ToggleSwitch FadeForTest => _fade; + + internal ToggleSwitch GamesOnlyForTest => _games; + + internal FlatSlider StrengthForTest => _strength; + + internal FlatSlider BlackForTest => _black; + + internal IReadOnlyList TintTilesForTest => _tiles; + + internal HotkeyPicker KeyPickerForTest => _key; + + internal HotkeyPicker NextKeyPickerForTest => _nextKey; + + internal SegmentStrip ModeForTest => _mode; + + internal GlassButton SaveNewForTest => _saveNew; + + internal GlassButton DeleteForTest => _delete; + + internal Control LockCardForTest => _lockCard; + + internal Control WeekCardForTest => _weekCard; + + internal GlassButton ManageForTest => _manage; + + internal Control SettingsCardForTest => _settingsCard; + + internal Label KeyErrorForTest => _keyError; + + internal string StateTextForTest => _state.Text; + + internal string WhiteValueTextForTest => _whiteValue.Text; + + internal Bitmap? WithPictureForTest => _with.Picture; + + internal bool StateShownForTest => _state.Visible; + + public event Func? KeyChanged; + + public event Action? NextKeyChanged; + + public event Action? ManageRequested; + + public DarkBoostPage(VibranceEngine engine, AppSettings settings, Action save) + { + _engine = engine ?? throw new ArgumentNullException("engine"); + _settings = settings ?? throw new ArgumentNullException("settings"); + _save = save ?? ((Action)(() => + { + })); + _setups = DarkBoostSetups.Normalise(settings.DarkBoostSetups); + _selected = DarkBoostSetups.Selected(settings.DarkBoostSelected, _setups.Count); + _title = new Label + { + Text = "Dark Boost & Zoom", + Font = Fonts.Display, + ForeColor = Theme.Text, + BackColor = Color.Transparent, + AutoSize = false, + TextAlign = ContentAlignment.MiddleLeft, + UseMnemonic = false, + Name = "PageTitle" + }; + _subtitle = new Label + { + Text = "Brings out detail in very dark scenes. Hold a key to zoom in.", + Font = Fonts.Label, + ForeColor = Theme.TextDim, + BackColor = Color.Transparent, + AutoSize = false, + TextAlign = ContentAlignment.TopLeft, + UseMnemonic = false, + Name = "PageSubtitle" + }; + _state = new StateLabel(); + _headerTag = new AddOnTag(withLock: false); + _banCard = new CardPanel + { + Name = "BanWarningCard", + AccessibleName = "Dark Boost can get you banned" + }; + _banCard.Paint += (object? _, PaintEventArgs e2) => + { + PaintBanFrame(e2.Graphics, _banCard.ClientSize); + }; + _banCard.Controls.Add(new WarningIcon()); + _banTitle = Words(_banCard, "Dark Boost can get you banned", Fonts.Title, Theme.Negative, ContentAlignment.MiddleLeft); + _banBody = Words(_banCard, "Some games, like Rust, ban players who see in the dark. It mostly happens when another player reports you. PlexusX never touches the game, but the ban risk is yours.", Fonts.Body, Theme.Text); + _banTitle.Name = "BanWarningTitle"; + _banBody.Name = "BanWarningBody"; + _weekCard = new CardPanel + { + Visible = false + }; + _weekTitle = Words(_weekCard, "Free week. 7 days left.", Fonts.BodyBold, Theme.Text); + _weekCaption = Words(_weekCard, "No card. It turns off by itself.", Fonts.Caption, Theme.TextFaint); + _manage = new GlassButton + { + Text = "Manage", + Kind = GlassButtonKind.Secondary, + AccessibleName = "Manage on the Account page" + }; + _manage.Click += (object? _, EventArgs _) => + { + ManageRequested?.Invoke(); + }; + _weekCard.Controls.Add(_manage); + _viewsCard = new CardPanel(); + _now = new ScenePreview + { + AccessibleName = "Your screen now" + }; + _with = new ScenePreview + { + AccessibleName = "With Dark Boost" + }; + _viewsCard.Controls.Add(_now); + _viewsCard.Controls.Add(_with); + _nowCaption = Words(_viewsCard, "Now", Fonts.CaptionBold, Theme.TextDim); + _nowState = Words(_viewsCard, "Off", Fonts.Caption, Theme.TextFaint, ContentAlignment.TopRight); + _withCaption = Words(_viewsCard, "With Dark Boost", Fonts.CaptionBold, Theme.TextDim); + _withState = Words(_viewsCard, "Your settings below", Fonts.Caption, Theme.TextFaint, ContentAlignment.TopRight); + _tintFact = Words(_viewsCard, "", Fonts.Caption, Theme.TextFaint); + _lockCard = new CardPanel(); + _lockCard.Paint += (object? _, PaintEventArgs e2) => + { + if (!_hasWeekRows) + { + return; + } + using Pen pen = new Pen(ControlInk.Edge, ControlInk.Hairline(ControlInk.Dpi(_lockCard))); + e2.Graphics.DrawLine(pen, S(21), S(225), _lockCard.Width - S(21), S(225)); + }; + _lockTitle = Words(_lockCard, "Get Dark Boost & Zoom", Fonts.Heading, Theme.Text, ContentAlignment.MiddleLeft); + _lockCaption = Words(_lockCard, "First week free, once per account. Card needed to start it.", Fonts.Caption, Theme.TextFaint); + _facts = new FactLine[8] + { + new FactLine("Strength", " from soft to full."), + new FactLine("5 colours", " to pick from."), + new FactLine("Black level", " keeps black spots black."), + new FactLine("Your key", ", hold or toggle."), + new FactLine("Saved setups", ", one key flips them."), + new FactLine("Only in games", ", or always."), + new FactLine("Hold to zoom", ", 1.5x to 4x."), + new FactLine("Smooth zoom", " if you want.") + }; + _buy = new GlassButton + { + Text = "Get Dark Boost & Zoom", + Kind = GlassButtonKind.Primary, + AccessibleName = "Get Dark Boost & Zoom" + }; + _buy.Click += (object? _, EventArgs _) => + { + LoopbackSignIn.OpenBrowser(BuyUrl); + }; + _lockCard.Controls.Add(_buy); + FactLine[] facts = _facts; + foreach (FactLine value in facts) + { + _lockCard.Controls.Add(value); + } + _lockFootnote = Words(_lockCard, "One-off owners: one free week. No card. Ends by itself.", Fonts.Caption, Theme.TextFaint); + _settingsCard = new CardPanel(); + _settingsTitle = Words(_settingsCard, "Dark Boost settings", Fonts.Heading, Theme.Text, ContentAlignment.MiddleLeft); + _settingsTag = new AddOnTag(withLock: true); + _settingsCard.Controls.Add(_settingsTag); + _switchTitle = Words(_settingsCard, "Dark Boost", Fonts.BodyBold, Theme.Text); + _switchCaption = Words(_settingsCard, "Stays on until you turn it off.", Fonts.Caption, Theme.TextFaint); + _switch = new ToggleSwitch + { + Size = new Size(40, 20), + AccessibleName = "Dark Boost" + }; + _switch.CheckedChanged += (object? _, EventArgs _) => + { + OnSwitch(); + }; + _settingsCard.Controls.Add(_switch); + _colourTitle = Words(_settingsCard, "Colour", Fonts.BodyBold, Theme.Text); + _tiles = DarkBoostTints.All.Select((DarkBoostTint t) => + { + TintTile tintTile = new TintTile(t); + tintTile.Click += (object? _, EventArgs _) => + { + ChooseTint(t); + }; + _settingsCard.Controls.Add(tintTile); + return tintTile; + }).ToArray(); + _strengthLabel = Words(_settingsCard, "Strength", Fonts.Body, Theme.TextDim); + _strengthValue = Words(_settingsCard, "", Fonts.BodyBold, Theme.Text, ContentAlignment.TopRight); + _strength = new FlatSlider + { + Minimum = 0, + Maximum = 100, + AccessibleName = "Strength" + }; + _strength.ValueChanged += (object? _, EventArgs _) => + { + if (!_syncing) + { + SetStrength(_strength.Value); + } + }; + _settingsCard.Controls.Add(_strength); + _whiteLabel = Words(_settingsCard, "Turns white above", Fonts.Caption, Theme.TextFaint); + _whiteValue = Words(_settingsCard, "", Fonts.CaptionBold, Theme.TextDim, ContentAlignment.TopRight); + _blackLabel = Words(_settingsCard, "Black level", Fonts.Body, Theme.TextDim); + _blackValue = Words(_settingsCard, "", Fonts.BodyBold, Theme.Text, ContentAlignment.TopRight); + _black = new FlatSlider + { + Minimum = 0, + Maximum = 100, + AccessibleName = "Black level" + }; + _black.ValueChanged += (object? _, EventArgs _) => + { + if (!_syncing) + { + SetBlackLevel(_black.Value); + } + }; + _settingsCard.Controls.Add(_black); + _blackReadout = Words(_settingsCard, "Higher keeps dark spots black", Fonts.Caption, Theme.TextFaint); + _keyTitle = Words(_settingsCard, "Key", Fonts.BodyBold, Theme.Text); + _keyCaption = Words(_settingsCard, "", Fonts.Caption, Theme.TextFaint); + _keyError = Words(_settingsCard, "That key can't be used for Dark Boost.", Fonts.Caption, Theme.Negative); + _keyError.Visible = false; + _mode = new SegmentStrip(new string[2] { "Toggle", "Hold" }) + { + AccessibleName = "Key mode" + }; + _mode.Chosen += (object? _, string kind) => + { + if (!_syncing) + { + ChooseHold(kind == "Hold"); + } + }; + _settingsCard.Controls.Add(_mode); + _key = new HotkeyPicker + { + AllowMouseButtons = true, + AccessibleName = "Dark Boost key" + }; + _key.HotkeyChanged += (uint mask, uint vk) => + { + ChooseKey(mask, vk); + }; + _settingsCard.Controls.Add(_key); + _gamesTitle = Words(_settingsCard, "Only while a game is running", Fonts.BodyBold, Theme.Text); + _gamesCaption = Words(_settingsCard, GamesOnlyCaption, Fonts.Caption, Theme.TextFaint); + _games = new ToggleSwitch + { + Size = new Size(40, 20), + AccessibleName = "Only while a game is running" + }; + _games.CheckedChanged += (object? _, EventArgs _) => + { + if (!_syncing) + { + SetGamesOnly(_games.Checked); + } + }; + _settingsCard.Controls.Add(_games); + _fadeTitle = Words(_settingsCard, "Smooth fade", Fonts.BodyBold, Theme.Text); + _fadeCaption = Words(_settingsCard, "No sudden flash.", Fonts.Caption, Theme.TextFaint); + _fade = new ToggleSwitch + { + Size = new Size(40, 20), + AccessibleName = "Smooth fade" + }; + _fade.CheckedChanged += (object? _, EventArgs _) => + { + if (!_syncing) + { + SetFade(_fade.Checked); + } + }; + _settingsCard.Controls.Add(_fade); + _setupsTitle = Words(_settingsCard, "Saved setups", Fonts.BodyBold, Theme.Text); + _setupsCaption = Words(_settingsCard, "The sliders save into the one you pick.", Fonts.Caption, Theme.TextFaint); + _saveNew = new GlassButton + { + Text = "Save new", + Kind = GlassButtonKind.Secondary + }; + _saveNew.Click += (object? _, EventArgs _) => + { + SaveNewSetup(); + }; + _delete = new GlassButton + { + Text = "Delete", + Kind = GlassButtonKind.Quiet + }; + _delete.Click += (object? _, EventArgs _) => + { + DeleteSetup(); + }; + _settingsCard.Controls.Add(_saveNew); + _settingsCard.Controls.Add(_delete); + _nextTitle = Words(_settingsCard, "Next setup key", Fonts.BodyBold, Theme.Text); + _nextCaption = Words(_settingsCard, "Flips to the next setup.", Fonts.Caption, Theme.TextFaint); + _nextKey = new HotkeyPicker + { + AllowMouseButtons = true, + AccessibleName = "Next setup key" + }; + _nextKey.HotkeyChanged += (uint mask, uint vk) => + { + ChooseNextKey(mask, vk); + }; + _settingsCard.Controls.Add(_nextKey); + Controls.Add(_banCard); + Controls.Add(_viewsCard); + Controls.Add(_weekCard); + Controls.Add(_lockCard); + Controls.Add(_settingsCard); + UseHeaderPanel(_title, _subtitle, new Control[2] { _state, _headerTag }); + _fadeTimer.Tick += (object? _, EventArgs _) => + { + FadeTick(); + }; + _owned = global::A.A.Available; + _nowAmount = (_fadeFrom = (_fadeTo = ((_owned && _engine.NightVision) ? 1 : 0))); + RebuildSetupChips(); + ApplyOffer(); + SyncControls(); + VisibleChanged += (object? _, EventArgs _) => + { + if (Visible) + { + ReloadOffer(); + } + }; + } + + public void AttachZoom(AppSettings settings, Action save, Func allowed, ZoomHooks hooks) + { + _zoomCard?.Dispose(); + _zoomCard = new CardPanel + { + Name = "ZoomCard", + AccessibleName = "Zoom" + }; + _zoomSection = new ZoomSection(settings, save, allowed, hooks.BindKey, hooks.WhyRefused); + _zoomSection.Changed += hooks.Changed; + _zoomCard.Controls.Add(_zoomSection); + Controls.Add(_zoomCard); + _zoomCard.TabIndex = _settingsCard.TabIndex; + _settingsCard.TabIndex = _zoomCard.TabIndex + 1; + LayoutContent(); + } + + public void RefreshZoomStanding() + { + _zoomSection?.Sync(); + } + + private static int S(int logical) + { + return Tokens.Scale(logical); + } + + private static Label Words(Control parent, string text, Font font, Color ink, ContentAlignment align = ContentAlignment.TopLeft) + { + Label label = new Label + { + Text = text, + Font = font, + ForeColor = ink, + BackColor = Color.Transparent, + AutoSize = false, + TextAlign = align, + UseMnemonic = false + }; + parent.Controls.Add(label); + return label; + } + + internal void ReloadOffer() + { + RefreshZoomStanding(); + bool flag; + try + { + flag = global::A.A.Available; + } + catch + { + flag = false; + } + if (flag == _owned) + { + SyncSwitch(); + return; + } + _owned = flag; + ApplyOffer(); + SyncControls(); + SyncSwitch(); + LayoutContent(); + Invalidate(invalidateChildren: true); + } + + internal IEnumerable InteractiveControls() + { + yield return _switch; + TintTile[] tiles = _tiles; + for (int i = 0; i < tiles.Length; i++) + { + yield return tiles[i]; + } + yield return _strength; + yield return _black; + yield return _mode; + yield return _key; + yield return _games; + yield return _fade; + yield return _saveNew; + yield return _delete; + foreach (ChipButton setupChip in _setupChips) + { + yield return setupChip; + } + yield return _nextKey; + } + + private void ApplyOffer() + { + _lockCard.Visible = !_owned; + _settingsTag.Visible = !_owned; + _state.Visible = _owned; + ApplyStatus(); + foreach (Control item in InteractiveControls()) + { + item.Enabled = _owned; + } + _delete.Enabled = _owned && DarkBoostSetups.CanDelete(_setups.Count); + if (!_owned) + { + _keyError.Visible = false; + StopFade(0.0); + } + if (HasHeaderPanel) + { + LayoutHeaderPanel(); + } + } + + private void ApplyStatus() + { + _weekCard.Visible = _owned; + if (OnTheWeek) + { + _weekTitle.Text = ((_weekDaysLeft == 1) ? "Free week. 1 day left." : $"Free week. {_weekDaysLeft} days left."); + } + else + { + _weekTitle.Text = "Dark Boost & Zoom is on your account."; + } + _weekCaption.Text = (OnTheWeek ? "No card. It turns off by itself." : "Separate from your plan."); + _manage.Visible = !OnTheWeek; + } + + public void SyncSwitch() + { + bool flag = _owned && _engine.NightVision; + if (_switch.Checked != flag) + { + _syncing = true; + try + { + _switch.Checked = flag; + } + finally + { + _syncing = false; + } + StartFade(flag ? 1 : 0); + } + UpdateState(); + } + + private void OnSwitch() + { + if (_syncing) + { + return; + } + if (!global::A.A.Available) + { + _syncing = true; + try + { + _switch.Checked = false; + return; + } + finally + { + _syncing = false; + } + } + bool flag = _switch.Checked; + if (flag && !new DarkBoostBanGate(_settings, _save, AskBanRiskForTest).Pass(FindForm())) + { + _syncing = true; + try + { + _switch.Checked = false; + return; + } + finally + { + _syncing = false; + } + } + _engine.NightVision = flag && global::A.A.Available; + _settings.NightVisionOn = flag; + _save(); + StartFade(flag ? 1 : 0); + UpdateState(); + } + + internal void SetOnForTest(bool on) + { + _switch.Checked = on; + } + + private void UpdateState() + { + _state.Text = (_switch.Checked ? ("On · " + Current.Name) : "Ready"); + _nowState.Text = (_switch.Checked ? "On" : "Off"); + if (HasHeaderPanel) + { + LayoutHeaderPanel(); + } + _state.Invalidate(); + } + + private void StartFade(double to) + { + _fadeFrom = _nowAmount; + _fadeTo = to; + _fadeStart = DateTime.UtcNow; + if (!_settings.DarkBoostFade || _fadeFrom == _fadeTo) + { + StopFade(to); + } + else + { + _fadeTimer.Start(); + } + } + + private void StopFade(double at) + { + _fadeTimer.Stop(); + _nowAmount = (_fadeFrom = (_fadeTo = at)); + RenderNow(); + } + + private void FadeTick() + { + TimeSpan timeSpan = DateTime.UtcNow - _fadeStart; + _nowAmount = NowAmountAt(timeSpan); + if (timeSpan >= DarkBoostFade.Duration) + { + StopFade(_fadeTo); + } + else + { + RenderNow(); + } + } + + internal double NowAmountAt(TimeSpan elapsed) + { + return DarkBoostFade.Amount(_fadeFrom, _fadeTo, elapsed, _settings.DarkBoostFade); + } + + private void Replace(DarkBoostSetup s) + { + _setups[_selected] = s.Clamped(); + Persist(); + SyncControls(); + } + + private void Persist() + { + _settings.DarkBoostSetups = _setups.ToList(); + _settings.DarkBoostSelected = _selected; + _save(); + PushToEngine(); + } + + private void PushToEngine() + { + DarkBoostSetup current = Current; + _engine.SetDarkBoostLook(current.Tint, current.Strength, current.BlackLevel, _settings.DarkBoostFade); + } + + internal void ChooseTint(DarkBoostTint tint) + { + if (global::A.A.Available) + { + Replace(Current with + { + Tint = tint + }); + } + } + + internal void SetStrength(int value) + { + if (!global::A.A.Available) + { + SyncControls(); + return; + } + Replace(Current with + { + Strength = value + }); + } + + internal void SetBlackLevel(int value) + { + if (!global::A.A.Available) + { + SyncControls(); + return; + } + Replace(Current with + { + BlackLevel = value + }); + } + + internal void SelectSetup(int index) + { + if (global::A.A.Available) + { + _selected = DarkBoostSetups.Selected(index, _setups.Count); + Persist(); + SyncControls(); + UpdateState(); + } + } + + internal void NextSetup() + { + if (global::A.A.Available) + { + SelectSetup(DarkBoostSetups.Next(_selected, _setups.Count)); + } + } + + internal void ReloadSetupsFromSettings() + { + _setups.Clear(); + _setups.AddRange(DarkBoostSetups.Normalise(_settings.DarkBoostSetups)); + _selected = DarkBoostSetups.Selected(_settings.DarkBoostSelected, _setups.Count); + RebuildSetupChips(); + SyncControls(); + UpdateState(); + LayoutContent(); + } + + internal void SaveNewSetup() + { + if (global::A.A.Available) + { + _selected = DarkBoostSetups.SaveNew(_setups, _selected); + Persist(); + RebuildSetupChips(); + SyncControls(); + UpdateState(); + LayoutContent(); + } + } + + internal void DeleteSetup() + { + if (global::A.A.Available && DarkBoostSetups.CanDelete(_setups.Count)) + { + _selected = DarkBoostSetups.Delete(_setups, _selected); + Persist(); + RebuildSetupChips(); + SyncControls(); + UpdateState(); + LayoutContent(); + } + } + + private void RebuildSetupChips() + { + foreach (ChipButton setupChip in _setupChips) + { + _settingsCard.Controls.Remove(setupChip); + setupChip.Dispose(); + } + _setupChips.Clear(); + for (int i = 0; i < _setups.Count; i++) + { + int at = i; + ChipButton chipButton = new ChipButton + { + Text = _setups[i].Name, + Enabled = _owned + }; + chipButton.Click += (object? _, EventArgs _) => + { + SelectSetup(at); + }; + _setupChips.Add(chipButton); + _settingsCard.Controls.Add(chipButton); + } + _delete.Enabled = _owned && DarkBoostSetups.CanDelete(_setups.Count); + _nextKey.TabIndex = _settingsCard.Controls.Cast().Max((Control control) => control.TabIndex) + 1; + } + + private void SetFade(bool on) + { + if (!global::A.A.Available) + { + SyncControls(); + return; + } + _settings.DarkBoostFade = on; + _save(); + PushToEngine(); + } + + private void SetGamesOnly(bool on) + { + if (!global::A.A.Available) + { + SyncControls(); + return; + } + _settings.HotkeysOnlyInGames = on; + _save(); + if (_settings.NightVisionHotkeyEnabled && _settings.NightVisionHotkeyVirtualKey != 0) + { + KeyChanged?.Invoke(_settings.NightVisionHotkeyModifierMask, _settings.NightVisionHotkeyVirtualKey); + } + NextKeyChanged?.Invoke(); + } + + internal void ChooseHold(bool hold) + { + if (!global::A.A.Available) + { + SyncControls(); + return; + } + _settings.NightVisionHotkeyHold = hold; + _save(); + if (_settings.NightVisionHotkeyEnabled && _settings.NightVisionHotkeyVirtualKey != 0) + { + KeyChanged?.Invoke(_settings.NightVisionHotkeyModifierMask, _settings.NightVisionHotkeyVirtualKey); + } + SyncControls(); + } + + internal void ChooseKey(uint mask, uint vk) + { + if (!global::A.A.Available) + { + SyncControls(); + return; + } + bool flag = KeyChanged?.Invoke(mask, vk) ?? false; + _keyError.Visible = !flag; + _keyCaption.Visible = flag; + SyncKeyPicker(); + RefreshZoomStanding(); + } + + internal void ChooseNextKey(uint mask, uint vk) + { + if (!global::A.A.Available) + { + SyncControls(); + return; + } + if (vk != 0 && !HotkeyPicker.IsBindable(mask, vk, out string _)) + { + SyncControls(); + return; + } + if (vk != 0 && _settings.NightVisionHotkeyEnabled && vk == _settings.NightVisionHotkeyVirtualKey && mask == _settings.NightVisionHotkeyModifierMask) + { + SyncControls(); + return; + } + if (vk != 0 && HotkeyConflicts.Owner(_settings, HotkeySlot.NightVision, mask, vk).HasValue) + { + SyncControls(); + return; + } + _settings.DarkBoostNextKeyModifierMask = ((vk != 0) ? mask : 0u); + _settings.DarkBoostNextKeyVirtualKey = vk; + _save(); + SyncControls(); + NextKeyChanged?.Invoke(); + RefreshZoomStanding(); + } + + private void SyncKeyPicker() + { + _key.ModifierMask = _settings.NightVisionHotkeyModifierMask; + _key.VirtualKey = (_settings.NightVisionHotkeyEnabled ? _settings.NightVisionHotkeyVirtualKey : 0u); + } + + private void SyncControls() + { + _syncing = true; + try + { + DarkBoostSetup current = Current; + TintTile[] tiles = _tiles; + foreach (TintTile obj in tiles) + { + obj.Selected = obj.Tint == current.Tint; + } + _strength.Value = current.Strength; + _black.Value = current.BlackLevel; + _strengthValue.Text = current.Strength + "%"; + _blackValue.Text = ((current.BlackLevel == 0) ? "Off" : (current.BlackLevel + "%")); + _whiteValue.Text = (int)Math.Round(DarkBoostScene.WhiteFrom(current, _engine.DarkBoostPreviewBasis().Basis) * 100.0, MidpointRounding.ToEven) + "% brightness"; + _tintFact.Text = DarkBoostTints.Fact(current.Tint); + _fade.Checked = _settings.DarkBoostFade; + _games.Checked = _settings.HotkeysOnlyInGames; + _mode.Active = (_settings.NightVisionHotkeyHold ? "Hold" : "Toggle"); + _keyCaption.Text = (_settings.NightVisionHotkeyHold ? "On only while you hold the key." : "Press once for on, again for off."); + SyncKeyPicker(); + _nextKey.ModifierMask = _settings.DarkBoostNextKeyModifierMask; + _nextKey.VirtualKey = _settings.DarkBoostNextKeyVirtualKey; + if (!_owned) + { + _switch.Checked = false; + } + for (int j = 0; j < _setupChips.Count; j++) + { + _setupChips[j].Text = _setups[j].Name; + _setupChips[j].Active = j == _selected; + } + } + finally + { + _syncing = false; + } + _with.Picture = RenderSetup(1.0); + RenderNow(); + Invalidate(invalidateChildren: true); + } + + private void RenderNow() + { + _now.Picture = RenderSetup(_nowAmount); + } + + private Bitmap RenderSetup(double amount) + { + (float[]? Basis, ushort[]? Ramp) tuple = _engine.DarkBoostPreviewBasis(); + float[] item = tuple.Basis; + ushort[] item2 = tuple.Ramp; + DarkBoostSetup current = Current; + double strength = (double)current.Strength / 100.0 * amount; + return DarkBoostScene.Render(DarkBoostScene.PictureFor(current, strength, item), (item2 == null) ? null : DarkBoostPicture.Ramp(item2, strength)); + } + + private int LayoutWeeks(int top, int inner) + { + return 0; + } + + protected override void OnResize(EventArgs e) + { + base.OnResize(e); + LayoutContent(); + } + + protected override void OnHandleCreated(EventArgs e) + { + base.OnHandleCreated(e); + LayoutContent(); + } + + private void LayoutContent() + { + if (Width <= 0) + { + return; + } + _headerTag.Size = _headerTag.NaturalSize; + _state.Remeasure(); + if (HasHeaderPanel) + { + LayoutHeaderPanel(); + } + int contentLeft = GlowPage.ContentLeft; + int num = Math.Max(S(480), ContentRight - GlowPage.ContentLeft); + int num2 = ContentTop + AutoScrollPosition.Y; + int num3 = S(21); + int num4 = num - 2 * num3; + int num5 = S(24); + int num6 = num3 + num5 + S(12); + int num7 = Math.Max(S(120), num - num3 - num6); + int num8 = S(28); + int num9 = TextRenderer.MeasureText("Some games, like Rust, ban players who see in the dark. It mostly happens when another player reports you. PlexusX never touches the game, but the ban risk is yours.", Fonts.Body, new Size(num7, 0), TextFormatFlags.NoPrefix | TextFormatFlags.WordBreak | TextFormatFlags.NoPadding).Height + S(4); + int num10 = num3 + num8 + S(6) + num9 + num3 - S(2); + _banCard.SetBounds(contentLeft, num2, num, num10); + foreach (Control control in _banCard.Controls) + { + if (control is WarningIcon) + { + control.SetBounds(num3, num3 - S(1) + (num8 - num5) / 2, num5, num5); + } + } + Place(_banTitle, num6, num3 - S(1), num7, num8); + Place(_banBody, num6, num3 - S(1) + num8 + S(6), num7, num9); + num2 += num10 + S(16); + int num11 = (num4 - S(16)) / 2; + int num12 = S(182); + _viewsCard.SetBounds(contentLeft, num2, num, S(272)); + _now.SetBounds(num3, num3, num11, num12); + _with.SetBounds(num3 + num11 + S(16), num3, num11, num12); + int y = num3 + num12 + S(6); + Place(_nowCaption, num3, y, num11 / 2, S(16)); + Place(_nowState, num3 + num11 / 2, y, num11 - num11 / 2, S(16), right: true); + Place(_withCaption, _with.Left, y, num11 / 2, S(16)); + Place(_withState, _with.Left + num11 / 2, y, num11 - num11 / 2, S(16), right: true); + Place(_tintFact, num3, S(235), num4, S(16)); + num2 += _viewsCard.Height + S(16); + if (_owned) + { + _weekCard.SetBounds(contentLeft, num2, num, S(84)); + _manage.Size = new Size(Math.Max(S(82), _manage.PreferredSize.Width), S(32)); + _manage.Location = new Point(num - num3 - _manage.Width, (S(84) - _manage.Height) / 2); + int w = _manage.Left - num3 - S(16); + Place(_weekTitle, num3, S(21), w, S(22)); + Place(_weekCaption, num3, S(47), w, S(16)); + num2 += _weekCard.Height + S(16); + } + if (!_owned) + { + int num13 = LayoutWeeks(S(241), num4); + _hasWeekRows = num13 > 0; + _lockCard.SetBounds(contentLeft, num2, num, S(234) + num13 + (_hasWeekRows ? S(16) : 0)); + int num14 = Math.Max(S(130), _buy.PreferredSize.Width); + _buy.SetBounds(num - num3 - num14, num3 - S(1), num14, S(32)); + Place(_lockTitle, num3, num3 - S(1), num4 - num14 - S(12), S(28)); + Place(_lockCaption, num3, S(53), num4, S(16)); + int num15 = (num4 + S(16)) / 2 + S(4); + for (int i = 0; i < _facts.Length; i++) + { + _facts[i].SetBounds(num3 + i % 2 * num15, S(83) + i / 2 * S(28), num15 - S(8), S(20)); + } + Place(_lockFootnote, num3, S(197), num4, S(16)); + num2 += _lockCard.Height + S(16); + } + if (_zoomCard != null && _zoomSection != null) + { + int gutter = _zoomSection.Gutter; + _zoomSection.Width = num4 + 2 * gutter; + int wantedHeight = _zoomSection.WantedHeight; + _zoomSection.SetBounds(num3 - gutter, num3, num4 + 2 * gutter, wantedHeight); + _zoomCard.SetBounds(contentLeft, num2, num, wantedHeight + 2 * num3); + num2 += _zoomCard.Height + S(16); + } + LayoutSettings(contentLeft, num2, num); + FitScrollToContent(S(16)); + } + + private void LayoutSettings(int left, int top, int w) + { + int num = S(21); + int num2 = w - 2 * num; + int num3 = w - num; + Place(_settingsTitle, num, num - S(1), num2 / 2, S(28)); + _settingsTag.Size = _settingsTag.NaturalSize; + _settingsTag.Location = new Point(num3 - _settingsTag.Width, S(25)); + Place(_switchTitle, num, S(57), num2 - S(60), S(20)); + Place(_switchCaption, num, S(79), num2 - S(60), S(16)); + _switch.SetBounds(num3 - S(40), S(68), S(40), S(20)); + Place(_colourTitle, num, S(121), num2, S(20)); + int num4 = _tiles.Length; + for (int i = 0; i < num4; i++) + { + int num5 = num + (int)Math.Round((double)(i * (num2 + S(8))) / (double)num4); + int num6 = num + (int)Math.Round((double)((i + 1) * (num2 + S(8))) / (double)num4) - S(8); + _tiles[i].SetBounds(num5, S(149), num6 - num5, S(56)); + } + int num7 = (num2 - S(32)) / 2; + int num8 = num + num7 + S(32); + Place(_strengthLabel, num, S(221), num7 / 2, S(20)); + Place(_strengthValue, num + num7 / 2, S(221), num7 - num7 / 2, S(20), right: true); + _strength.SetTrackBounds(num, S(241), num7); + Place(_whiteLabel, num, S(275), num7 / 2, S(16)); + Place(_whiteValue, num + num7 / 2, S(275), num7 - num7 / 2, S(16), right: true); + Place(_blackLabel, num8, S(221), num7 / 2, S(20)); + Place(_blackValue, num8 + num7 / 2, S(221), num7 - num7 / 2, S(20), right: true); + _black.SetTrackBounds(num8, S(241), num7); + Place(_blackReadout, num8, S(275), num7, S(16)); + int num9 = S(307); + _key.Size = new Size(S(260), S(40)); + _key.Location = new Point(num3 - _key.Width, num9 + (S(56) - _key.Height) / 2); + int num10 = Math.Max(S(120), _mode.NaturalWidth); + _mode.SetBounds(_key.Left - S(8) - num10, num9 + (S(56) - S(32)) / 2, num10, S(32)); + RowText(_keyTitle, _keyCaption, num9, _mode.Left - num - S(16)); + Place(_keyError, num, num9 + S(28), _mode.Left - num - S(16), S(16)); + num9 += S(56); + int num11 = num2 - S(60); + _gamesCaption.Text = ((TextRenderer.MeasureText(GamesOnlyCaption, _gamesCaption.Font).Width <= num11) ? GamesOnlyCaption : "Works while one of the six supported games runs. Turn this off for any other game."); + int num12 = Math.Max(S(16), TextRenderer.MeasureText(_gamesCaption.Text, _gamesCaption.Font, new Size(num11, int.MaxValue), TextFormatFlags.WordBreak).Height); + int num13 = Math.Max(S(56), S(28) + num12 + S(12)); + RowText(_gamesTitle, _gamesCaption, num9, num11); + Place(_gamesCaption, num, num9 + S(28), num11, num12); + _games.SetBounds(num3 - S(40), num9 + (num13 - S(20)) / 2, S(40), S(20)); + num9 += num13; + RowText(_fadeTitle, _fadeCaption, num9, num2 - S(60)); + _fade.SetBounds(num3 - S(40), num9 + (S(56) - S(20)) / 2, S(40), S(20)); + num9 += S(56); + RowText(_setupsTitle, _setupsCaption, num9, num2 - S(220)); + int num14 = S(28); + int y = num9 + (S(56) - num14) / 2; + _delete.Size = new Size(Math.Max(S(64), _delete.PreferredSize.Width), num14); + _delete.Location = new Point(num3 - _delete.Width, y); + _saveNew.Size = new Size(Math.Max(S(84), _saveNew.PreferredSize.Width), num14); + _saveNew.Location = new Point(_delete.Left - S(8) - _saveNew.Width, y); + num9 += S(56); + int num15 = num; + foreach (ChipButton setupChip in _setupChips) + { + int num16 = TextRenderer.MeasureText(setupChip.Text, Fonts.BodyBold).Width + S(24); + if (num15 + num16 > num3 && num15 > num) + { + num15 = num; + num9 += S(36); + } + setupChip.SetBounds(num15, num9, num16, S(28)); + num15 += num16 + S(8); + } + num9 += S(28) + S(8); + _nextKey.Size = new Size(S(260), S(40)); + _nextKey.Location = new Point(num3 - _nextKey.Width, num9 + (S(56) - _nextKey.Height) / 2); + RowText(_nextTitle, _nextCaption, num9, _nextKey.Left - num - S(16)); + num9 += S(56); + _settingsCard.SetBounds(left, top, w, num9 + num - S(8)); + } + + private static void RowText(Label title, Label caption, int top, int width) + { + Place(title, S(21), top + S(8), width, S(20)); + Place(caption, S(21), top + S(28), width, S(16)); + } + + private static void Place(Label l, int x, int y, int w, int h, bool right = false) + { + int num = ControlInk.LabelInkInset(l.Font); + l.SetBounds(right ? (x + num) : (x - num), y, w, h + S(2)); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _fadeTimer.Stop(); + _fadeTimer.Dispose(); + _now.Picture = null; + _with.Picture = null; + } + base.Dispose(disposing); + } + + private static void PaintBanFrame(Graphics g, Size size) + { + g.SmoothingMode = SmoothingMode.AntiAlias; + float num = S(8); + RectangleF rectangleF = new RectangleF(0.75f, 0.75f, (float)size.Width - 1.5f, (float)size.Height - 1.5f); + using GraphicsPath graphicsPath = new GraphicsPath(); + graphicsPath.AddArc(rectangleF.Left, rectangleF.Top, num * 2f, num * 2f, 180f, 90f); + graphicsPath.AddArc(rectangleF.Right - num * 2f, rectangleF.Top, num * 2f, num * 2f, 270f, 90f); + graphicsPath.AddArc(rectangleF.Right - num * 2f, rectangleF.Bottom - num * 2f, num * 2f, num * 2f, 0f, 90f); + graphicsPath.AddArc(rectangleF.Left, rectangleF.Bottom - num * 2f, num * 2f, num * 2f, 90f, 90f); + graphicsPath.CloseFigure(); + GraphicsState gstate = g.Save(); + try + { + using SolidBrush brush = new SolidBrush(Theme.Negative); + float width = Math.Max(4f, S(5)); + RectangleF rect = new RectangleF(rectangleF.Left + 1f, rectangleF.Top, width, rectangleF.Height); + g.SetClip(graphicsPath, CombineMode.Intersect); + g.FillRectangle(brush, rect); + } + finally + { + g.Restore(gstate); + } + using Pen pen = new Pen(Theme.Negative, 1.5f); + g.DrawPath(pen, graphicsPath); + } +} diff --git a/VibranceHud/Pages/DarkBoostScene.cs b/VibranceHud/Pages/DarkBoostScene.cs new file mode 100644 index 0000000..8413b60 --- /dev/null +++ b/VibranceHud/Pages/DarkBoostScene.cs @@ -0,0 +1,162 @@ +using System; +using System.Drawing; +using System.Drawing.Imaging; +using System.Runtime.InteropServices; +using VibranceHud.DarkBoost; + +namespace VibranceHud.Pages; + +internal static class DarkBoostScene +{ + internal const int W = 360; + + internal const int H = 120; + + private const double Gain = 4.0; + + private static float[]? _scene; + + private static double Hash(double x, double y) + { + double num = Math.Sin(x * 127.1 + y * 311.7) * 43758.5453; + return num - Math.Floor(num); + } + + internal static float[] Scene() + { + if (_scene != null) + { + return _scene; + } + float[] array = new float[129600]; + for (int i = 0; i < 120; i++) + { + for (int j = 0; j < 360; j++) + { + double num = 70.0 + 10.0 * Math.Sin((double)j / 40.0) + 5.0 * Math.Sin((double)j / 13.0); + double num2 = (Hash(j, i) - 0.5) * 0.004; + double num4; + double num5; + double num6; + if ((double)i < num) + { + double num3 = 0.022 + 0.012 * ((double)i / num); + num4 = num3 * 0.6; + num5 = num3 * 0.75; + num6 = num3; + } + else + { + double num7 = 0.016 + 0.005 * Math.Sin((double)j / 23.0) * Math.Sin((double)i / 11.0); + num4 = num7 * 0.9; + num5 = num7; + num6 = num7 * 0.6; + } + double value = j % 70 - 35; + double num8 = num - 34.0; + if (j > 20 && j < 330 && (double)i > num8 + Math.Abs(value) * 1.3 && (double)i < num + 6.0 && Math.Abs(value) < 18.0 && Math.Floor((double)j / 70.0) % 2.0 == 0.0) + { + num4 = 0.006; + num5 = 0.009; + num6 = 0.006; + } + if (j >= 230 && j <= 300 && i >= 48 && i <= 96) + { + num4 = 0.03; + num5 = 0.024; + num6 = 0.02; + } + if (j >= 250 && j <= 266 && i >= 60 && i <= 74) + { + num4 = 0.85; + num5 = 0.62; + num6 = 0.3; + } + double num9 = Math.Sqrt((j - 120) * (j - 120) + (i - 30) * (i - 30)); + if (num9 < 4.0) + { + num4 = 0.95; + num5 = 0.9; + num6 = 0.75; + } + else if (num9 < 30.0) + { + double num10 = (30.0 - num9) / 30.0 * 0.05; + num4 += num10; + num5 += num10 * 0.9; + num6 += num10 * 0.6; + } + if (Math.Sqrt(Math.Pow((double)(j - 60) / 1.6, 2.0) + Math.Pow(i - 104, 2.0)) < 9.0 || Math.Sqrt(Math.Pow((double)(j - 175) / 2.0, 2.0) + Math.Pow(i - 100, 2.0)) < 7.0) + { + num4 = 0.008; + num5 = 0.008; + num6 = 0.009; + } + int num11 = (i * 360 + j) * 3; + array[num11] = (float)(num4 + num2); + array[num11 + 1] = (float)(num5 + num2); + array[num11 + 2] = (float)(num6 + num2); + } + } + return _scene = array; + } + + internal static float[] IllustrationBase() + { + double[] array = DarkBoostTints.PreviewWeights(DarkBoostTint.Green); + float[] array2 = new float[25]; + for (int i = 0; i < 3; i++) + { + for (int j = 0; j < 3; j++) + { + array2[i * 5 + j] = (float)(4.0 * array[j]); + } + } + for (int k = 0; k < 3; k++) + { + array2[20 + k] = (float)(-12.0 * array[k] / 255.0); + } + array2[18] = 1f; + array2[24] = 1f; + return array2; + } + + internal static float[] PictureFor(DarkBoostSetup setup, double strength, float[]? basis) + { + return DarkBoostLook.Picture(basis ?? IllustrationBase(), setup.Tint, setup.BlackLevel, strength); + } + + internal static double WhiteFrom(DarkBoostSetup setup, float[]? basis) + { + return DarkBoostLook.WhiteFrom(PictureFor(setup, (double)setup.Strength / 100.0, basis)); + } + + internal static Bitmap Render(float[] matrix, ushort[]? ramp) + { + float[] array = Scene(); + Bitmap bitmap = new Bitmap(360, 120, PixelFormat.Format32bppArgb); + BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, 360, 120), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); + try + { + byte[] array2 = new byte[1440]; + for (int i = 0; i < 120; i++) + { + for (int j = 0; j < 360; j++) + { + int num = (i * 360 + j) * 3; + var (b, b2, b3) = DarkBoostLook.Pixel(array[num], array[num + 1], array[num + 2], matrix, ramp); + array2[j * 4] = b3; + array2[j * 4 + 1] = b2; + array2[j * 4 + 2] = b; + array2[j * 4 + 3] = byte.MaxValue; + } + Marshal.Copy(array2, 0, bitmapData.Scan0 + i * bitmapData.Stride, array2.Length); + } + } + finally + { + bitmap.UnlockBits(bitmapData); + } + return bitmap; + } +} diff --git a/VibranceHud/Pages/GlowPage.cs b/VibranceHud/Pages/GlowPage.cs new file mode 100644 index 0000000..a506d97 --- /dev/null +++ b/VibranceHud/Pages/GlowPage.cs @@ -0,0 +1,875 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Linq; +using System.Runtime.InteropServices; +using System.Windows.Forms; +using VibranceHud.Controls; +using VibranceHud.Design; +using VibranceHud.Theming; + +namespace VibranceHud.Pages; + +public class GlowPage : UserControl +{ + private sealed class HeaderLabel : Label + { + protected override void OnPaint(PaintEventArgs e) + { + if (!NeedsAHalo || Font.Height < 28) + { + base.OnPaint(e); + } + else + { + PaintHeaderText(e.Graphics, Text, Font, ForeColor, ClientRectangle); + } + } + } + + private bool _bringingIntoView; + + private const int SB_BOTH = 3; + + protected const int HeaderHeight = 86; + + private bool _headerAdded; + + protected const int Gutter = 16; + + internal const int HeaderPanelHeight = 84; + + internal const int HeaderToolbarGap = 12; + + internal const int HeaderToolbarHeight = 32; + + private const int HeaderPadX = 20; + + private const int HeaderPadY = 12; + + private const int ShellEdge = 1; + + private HeaderPanel? _headerCard; + + private Control? _headerTitleControl; + + private Control? _headerSubtitleControl; + + private Control? _headerToolbar; + + private Control[] _headerActions = Array.Empty(); + + private int _headerSubtitleExtra; + + private int _scaledForDpi = 96; + + private HeaderLabel? _headerTitle; + + private HeaderLabel? _headerSubtitle; + + private int _contentWidth; + + private Dictionary? _designLeft; + + private int _centredForWidth = -1; + + private int _lastOffset; + + public IBackdrop? Field { get; set; } + + public Point FieldOffset { get; set; } + + protected override CreateParams CreateParams + { + get + { + CreateParams createParams = base.CreateParams; + createParams.ExStyle |= 33554432; + return createParams; + } + } + + public int ScrollExtent => HonestExtentHeight(); + + public int ScrollViewport => ClientSize.Height; + + public int ScrollOffset => -AutoScrollPosition.Y; + + protected virtual int ScrollBottomPadding => 40; + + protected virtual string? PageTitle => null; + + protected virtual string PageSubtitle => ""; + + protected virtual bool UsesHeaderPanel => false; + + protected virtual Control[] HeaderActions => Array.Empty(); + + protected virtual Control? HeaderToolbar => null; + + internal HeaderPanel? HeaderCardForTest => _headerCard; + + internal Control? HeaderTitleForTest => _headerTitleControl; + + internal Control? HeaderSubtitleForTest => _headerSubtitleControl; + + protected bool HasHeaderPanel => _headerCard != null; + + protected static int ContentLeft => S(16); + + protected int ContentRight => Width + 1 - S(16); + + protected int HeaderPanelHeightPx + { + get + { + if (_headerCard != null) + { + return S(84) + _headerSubtitleExtra + ((_headerToolbar != null) ? S(44) : 0); + } + return 0; + } + } + + protected int ContentTop + { + get + { + if (_headerCard != null) + { + return S(16) + HeaderPanelHeightPx + S(16); + } + return S(16); + } + } + + protected virtual bool LaysOutInLogicalPixels => true; + + internal static bool NeedsAHalo => SlateSurface.Active; + + protected int ContentWidth + { + get + { + return _contentWidth; + } + set + { + _contentWidth = value; + CentreContent(); + } + } + + protected float DesignScale => (float)_scaledForDpi / 96f; + + public event EventHandler? ScrollStateChanged; + + protected GlowPage() + { + Dock = DockStyle.Fill; + BackColor = Theme.Background; + SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true); + } + + protected override void OnScroll(ScrollEventArgs se) + { + base.OnScroll(se); + RaiseScrollState(); + Invalidate(invalidateChildren: true); + } + + internal void InvalidateBackdropOnly() + { + Invalidate(invalidateChildren: true); + } + + protected override void OnMouseWheel(MouseEventArgs e) + { + int extent = ScrollExtent - ClientSize.Height; + ScrollTrace.Write(() => $"{GetType().Name} wheel {e.Delta} autoScroll={AutoScroll} client={ClientSize.Height} min={AutoScrollMinSize.Height} extent={extent} offset={-AutoScrollPosition.Y}"); + int num = -AutoScrollPosition.Y; + if (AutoScroll && extent > 0) + { + int num2 = SystemInformation.MouseWheelScrollLines; + if (num2 <= 0) + { + num2 = 3; + } + int num3 = e.Delta * num2 * 22 / 120; + int target = Math.Clamp(-AutoScrollPosition.Y - num3, 0, extent); + if (target != -AutoScrollPosition.Y) + { + AutoScrollPosition = new Point(-AutoScrollPosition.X, target); + } + ScrollTrace.Write(() => $" -> target={target} landed={-AutoScrollPosition.Y}"); + if (e is HandledMouseEventArgs e2) + { + e2.Handled = true; + } + } + else + { + ScrollTrace.Write(() => " -> IGNORED (nothing to scroll)"); + base.OnMouseWheel(e); + } + if (-AutoScrollPosition.Y != num) + { + RaiseScrollState(); + Invalidate(invalidateChildren: true); + } + } + + public void ScrollByWheel(int delta) + { + OnMouseWheel(new MouseEventArgs(MouseButtons.None, 0, 0, 0, delta)); + } + + internal void TestScrollWheel(int delta) + { + ScrollByWheel(delta); + } + + private void HookWheelForwarding(Control root) + { + foreach (Control control in root.Controls) + { + control.MouseWheel -= ForwardWheel; + control.MouseWheel += ForwardWheel; + control.GotFocus -= OnDescendantGotFocus; + control.GotFocus += OnDescendantGotFocus; + control.ControlAdded -= OnDescendantAdded; + control.ControlAdded += OnDescendantAdded; + HookWheelForwarding(control); + } + } + + private void OnDescendantAdded(object? sender, ControlEventArgs e) + { + Control control = e.Control; + if (control != null) + { + control.MouseWheel -= ForwardWheel; + control.MouseWheel += ForwardWheel; + control.GotFocus -= OnDescendantGotFocus; + control.GotFocus += OnDescendantGotFocus; + control.ControlAdded -= OnDescendantAdded; + control.ControlAdded += OnDescendantAdded; + HookWheelForwarding(control); + } + } + + private void ForwardWheel(object? sender, MouseEventArgs e) + { + OnMouseWheel(e); + } + + protected override bool ProcessDialogKey(Keys keyData) + { + Control control = ActiveControl; + while (control is ContainerControl containerControl) + { + Control activeControl = containerControl.ActiveControl; + if (activeControl == null) + { + break; + } + control = activeControl; + } + if (control != null) + { + RovingFocus rovingFocus = RovingFocus.Of(control); + if (rovingFocus != null) + { + Control control2 = rovingFocus.Target(control, keyData); + if (control2 != null) + { + if (control2 != control) + { + control2.Focus(); + if (rovingFocus.ArrowChooses(control2) && !control2.IsDisposed) + { + InvokeOnClick(control2, EventArgs.Empty); + } + rovingFocus.Refresh(); + } + return true; + } + } + } + return base.ProcessDialogKey(keyData); + } + + private void OnDescendantGotFocus(object? sender, EventArgs e) + { + if (sender is Control focused && KeyboardNavigation.Consume()) + { + ScrollIntoViewForKeyboard(focused); + } + } + + internal void ScrollIntoViewForKeyboard(Control focused) + { + if (_bringingIntoView || !IsHandleCreated || focused.IsDisposed || !Contains(focused)) + { + return; + } + _bringingIntoView = true; + try + { + Control target = ((focused is TextBox && focused.Parent is GlassTextBox glassTextBox) ? glassTextBox : focused); + if (target.Parent == null || !target.IsHandleCreated) + { + return; + } + int margin = ControlInk.FocusRingReach(ControlInk.Dpi(target)) + S(16); + Control parent = target.Parent; + while (parent != null && parent != this) + { + if (parent is ScrollableControl { AutoScroll: not false, IsHandleCreated: not false } scrollableControl) + { + BringInto(scrollableControl, target, margin); + } + parent = parent.Parent; + } + int num = ScrollExtent - ClientSize.Height; + if (AutoScroll && num > 0) + { + int before = -AutoScrollPosition.Y; + int want = OffsetThatShows(before, RectIn(this, target), ClientSize.Height, margin, num); + ScrollTrace.Write(() => $"{GetType().Name} keyboard focus {target.GetType().Name} '{target.Text}' offset {before} -> {want}"); + if (want != before) + { + AutoScrollPosition = new Point(-AutoScrollPosition.X, want); + RaiseScrollState(); + Invalidate(invalidateChildren: true); + } + } + } + finally + { + _bringingIntoView = false; + } + } + + private static void BringInto(ScrollableControl inner, Control target, int margin) + { + int num = inner.DisplayRectangle.Height - inner.ClientSize.Height; + if (num > 0) + { + int num2 = -inner.AutoScrollPosition.Y; + int num3 = OffsetThatShows(num2, RectIn(inner, target), inner.ClientSize.Height, margin, num); + if (num3 != num2) + { + inner.AutoScrollPosition = new Point(-inner.AutoScrollPosition.X, num3); + inner.Invalidate(invalidateChildren: true); + } + } + } + + private static Rectangle RectIn(Control container, Control target) + { + return container.RectangleToClient(target.Parent.RectangleToScreen(target.Bounds)); + } + + internal static int OffsetThatShows(int offset, Rectangle box, int viewport, int margin, int max) + { + int num = box.Top - margin; + int num2 = box.Bottom + margin; + int value = offset; + if (num < 0 || num2 - num > viewport) + { + value = offset + num; + } + else if (num2 > viewport) + { + value = offset + (num2 - viewport); + } + return Math.Clamp(value, 0, Math.Max(0, max)); + } + + protected override void OnControlAdded(ControlEventArgs e) + { + base.OnControlAdded(e); + OnDescendantAdded(this, e); + } + + private void RaiseScrollState() + { + HideNativeScrollBars(); + ScrollStateChanged?.Invoke(this, EventArgs.Empty); + } + + public void ScrollTo(int offset) + { + ScrollTrace.Write(() => $"{GetType().Name} ScrollTo({offset}) from offset={-AutoScrollPosition.Y}\n" + Environment.StackTrace); + AutoScrollPosition = new Point(-AutoScrollPosition.X, Math.Max(0, offset)); + Invalidate(invalidateChildren: true); + } + + protected override void OnHandleCreated(EventArgs e) + { + base.OnHandleCreated(e); + AddHeaderIfWanted(); + ApplyDpi(Tokens.Dpi); + LayoutHeaderPanel(); + KeyboardNavigation.EnsureInstalled(); + HookWheelForwarding(this); + RaiseScrollState(); + ScrollTrace.Write(() => $"{GetType().Name} shown: dpi={DeviceDpi} client={ClientSize.Width}x{ClientSize.Height} min={AutoScrollMinSize.Height} autoScroll={AutoScroll}"); + } + + protected override void WndProc(ref Message m) + { + base.WndProc(ref m); + int msg = m.Msg; + if ((uint)(msg - 276) <= 1u) + { + Message msg2 = m; + ScrollTrace.Write(() => $"{GetType().Name} WM_{((msg2.Msg == 277) ? "V" : "H")}SCROLL wParam=0x{msg2.WParam:X} now offset={-AutoScrollPosition.Y}"); + Invalidate(invalidateChildren: true); + } + msg = m.Msg; + if ((msg == 131 || (uint)(msg - 276) <= 1u) ? true : false) + { + HideNativeScrollBars(); + } + } + + [DllImport("user32.dll")] + private static extern bool ShowScrollBar(nint hWnd, int wBar, bool bShow); + + protected override void OnLayout(LayoutEventArgs e) + { + int before = -AutoScrollPosition.Y; + base.OnLayout(e); + int after = -AutoScrollPosition.Y; + if (before != after) + { + ScrollTrace.Write(() => $"{GetType().Name} layout moved the page {before} -> {after} (affected={e.AffectedControl?.GetType().Name} '{e.AffectedProperty}')\n" + Environment.StackTrace); + } + RaiseScrollState(); + } + + protected override Point ScrollToControl(Control activeControl) + { + ScrollTrace.Write(() => $"{GetType().Name} ScrollToControl({activeControl?.GetType().Name} '{activeControl?.Text}') declined at offset={-AutoScrollPosition.Y}"); + return AutoScrollPosition; + } + + private int HonestExtentHeight() + { + int height = AutoScrollMinSize.Height; + int num = LowestChildBottom(); + if (num <= 0) + { + return height; + } + return Math.Min(height, num + ScrollBottomPadding); + } + + private void AddHeaderIfWanted() + { + if (!_headerAdded && PageTitle != null) + { + _headerAdded = true; + AddPageHeader(PageTitle, PageSubtitle); + } + } + + private static int S(int logical) + { + return Tokens.Scale(logical); + } + + protected void UseHeaderPanel(Control title, Control subtitle, Control[]? actions = null, Control? toolbar = null) + { + if (_headerCard == null) + { + _headerCard = new HeaderPanel + { + Name = "HeaderPanel", + AccessibleRole = AccessibleRole.Grouping + }; + Controls.Add(_headerCard); + foreach (Control control in Controls) + { + if (control != _headerCard) + { + control.TabIndex++; + } + } + _headerCard.TabIndex = 0; + } + _headerCard.AccessibleName = title.Text; + _headerTitleControl = title; + _headerSubtitleControl = subtitle; + _headerActions = actions ?? Array.Empty(); + _headerToolbar = toolbar; + foreach (Control item in new Control[2] { title, subtitle }.Concat(_headerActions).Concat((toolbar == null) ? Array.Empty() : new Control[1] { toolbar })) + { + if (item.Parent != _headerCard) + { + item.Parent?.Controls.Remove(item); + _headerCard.Controls.Add(item); + } + } + LayoutHeaderPanel(); + } + + protected void LayoutHeaderPanel() + { + if (_headerCard == null || Width <= 0) + { + return; + } + int num = Math.Max(S(200), ContentRight - ContentLeft); + int num2 = ControlInk.Hairline(Tokens.Dpi); + int num3 = num2 + S(20); + int num4 = num2 + S(12); + int num5 = S(36); + int num6 = S(20); + int num7 = num4 + (num5 + S(2) + num6) / 2; + int num8 = num - num3; + bool flag = false; + for (int num9 = _headerActions.Length - 1; num9 >= 0; num9--) + { + Control control = _headerActions[num9]; + if (control.Visible) + { + if (flag) + { + num8 -= S(8); + } + int num10 = InkInset(control); + int num11 = Math.Max(0, control.Width - 2 * num10); + control.Location = new Point(num8 - num11 - num10, num7 - control.Height / 2); + num8 -= num11; + flag = true; + } + } + int num12 = (flag ? (num8 - S(16)) : (num - num3)); + int num13 = Math.Max(S(40), num12 - num3); + Control headerTitleControl = _headerTitleControl; + if (headerTitleControl != null) + { + int num14 = Math.Max(num5, TextRenderer.MeasureText(headerTitleControl.Text, headerTitleControl.Font).Height); + int num15 = InkInset(headerTitleControl); + headerTitleControl.SetBounds(num3 - num15, num4 - (num14 - num5) / 2, num13 + num15, num14); + } + _headerSubtitleExtra = 0; + Control headerSubtitleControl = _headerSubtitleControl; + if (headerSubtitleControl != null) + { + int num16 = num6; + if (headerSubtitleControl.Visible && headerSubtitleControl.Text.Length > 0) + { + int height = TextRenderer.MeasureText(headerSubtitleControl.Text, headerSubtitleControl.Font, new Size(num13, int.MaxValue), TextFormatFlags.WordBreak).Height; + num16 = Math.Max(num6, height); + } + _headerSubtitleExtra = num16 - num6; + int num17 = InkInset(headerSubtitleControl); + headerSubtitleControl.SetBounds(num3 - num17, num4 + num5 + S(2), num13 + num17, num16); + } + if (_headerToolbar != null) + { + _headerToolbar.SetBounds(num3, num4 + num5 + S(2) + num6 + _headerSubtitleExtra + S(12), num - 2 * num3, S(32)); + } + _headerCard.SetBounds(ContentLeft, S(16) + AutoScrollPosition.Y, num, HeaderPanelHeightPx); + } + + private static int InkInset(Control c) + { + if (!(c is Label label) || string.IsNullOrEmpty(label.Text)) + { + return 0; + } + int width = TextRenderer.MeasureText(label.Text, label.Font).Width; + int width2 = TextRenderer.MeasureText(label.Text, label.Font, Size.Empty, TextFormatFlags.SingleLine | TextFormatFlags.NoPadding).Width; + return Math.Max(0, (width - width2) / 2); + } + + public void ApplyDpi(int dpi) + { + if (!LaysOutInLogicalPixels || dpi <= 0 || dpi == _scaledForDpi) + { + return; + } + float num = (float)dpi / (float)_scaledForDpi; + _scaledForDpi = dpi; + SuspendLayout(); + foreach (Control control in Controls) + { + control.Scale(new SizeF(num, num)); + } + if (AutoScrollMinSize.Height > 0) + { + AutoScrollMinSize = new Size((int)Math.Round((float)AutoScrollMinSize.Width * num), (int)Math.Round((float)AutoScrollMinSize.Height * num)); + } + ResumeLayout(performLayout: true); + LayoutHeaderPanel(); + Invalidate(invalidateChildren: true); + } + + internal static void PaintHeaderText(Graphics g, string text, Font font, Color ink, Rectangle box) + { + Color foreColor = Color.FromArgb(150, Theme.IsLight ? Color.White : Color.Black); + for (int i = 1; i <= 2; i++) + { + (int, int)[] array = new (int, int)[8] + { + (i, 0), + (-i, 0), + (0, i), + (0, -i), + (i, i), + (-i, -i), + (i, -i), + (-i, i) + }; + for (int j = 0; j < array.Length; j++) + { + var (num, num2) = array[j]; + TextRenderer.DrawText(g, text, font, new Rectangle(box.X + num, box.Y + num2, box.Width, box.Height), foreColor, TextFormatFlags.NoPrefix | TextFormatFlags.VerticalCenter); + } + } + TextRenderer.DrawText(g, text, font, box, ink, TextFormatFlags.NoPrefix | TextFormatFlags.VerticalCenter); + } + + protected void AddPageHeader(string title, string subtitle) + { + if (UsesHeaderPanel) + { + AddPageHeaderPanel(title, subtitle); + return; + } + int num = 86; + int num2 = int.MaxValue; + foreach (Control control in Controls) + { + if (control.Visible && control.Left > 0) + { + num2 = Math.Min(num2, control.Left); + } + } + if (num2 == int.MaxValue) + { + num2 = 24; + } + foreach (Control control2 in Controls) + { + control2.Top += num; + } + _headerTitle = new HeaderLabel + { + Text = title, + Font = Fonts.Display, + ForeColor = Theme.Text, + BackColor = Color.Transparent, + AutoSize = false, + TextAlign = ContentAlignment.MiddleLeft, + Bounds = new Rectangle(num2, 16, Wide(title, Fonts.Display), 36) + }; + Controls.Add(_headerTitle); + _headerSubtitle = new HeaderLabel + { + Text = subtitle, + Font = Fonts.Label, + ForeColor = Theme.TextDim, + BackColor = Color.Transparent, + AutoSize = false, + TextAlign = ContentAlignment.MiddleLeft, + Bounds = new Rectangle(num2, 56, Wide(subtitle, Fonts.Label), 20), + Visible = (subtitle.Length > 0) + }; + Controls.Add(_headerSubtitle); + if (AutoScrollMinSize.Height > 0) + { + AutoScrollMinSize = new Size(AutoScrollMinSize.Width, AutoScrollMinSize.Height + num); + } + static int Wide(string text, Font font) + { + return TextRenderer.MeasureText(text, font).Width + 4; + } + } + + private void AddPageHeaderPanel(string title, string subtitle) + { + Control[] headerActions = HeaderActions; + Control headerToolbar = HeaderToolbar; + HashSet hashSet = new HashSet(headerActions); + if (headerToolbar != null) + { + hashSet.Add(headerToolbar); + } + int num = 116 + ((headerToolbar != null) ? 44 : 0); + foreach (Control control in Controls) + { + if (!hashSet.Contains(control)) + { + control.Top += num; + } + } + Label title2 = new Label + { + Text = title, + Font = Fonts.Display, + ForeColor = Theme.Text, + BackColor = Color.Transparent, + AutoSize = false, + TextAlign = ContentAlignment.MiddleLeft, + UseMnemonic = false, + Name = "PageTitle" + }; + Label subtitle2 = new Label + { + Text = subtitle, + Font = Fonts.Label, + ForeColor = Theme.TextDim, + BackColor = Color.Transparent, + AutoSize = false, + TextAlign = ContentAlignment.TopLeft, + UseMnemonic = false, + Visible = (subtitle.Length > 0), + Name = "PageSubtitle" + }; + UseHeaderPanel(title2, subtitle2, headerActions, headerToolbar); + if (AutoScrollMinSize.Height > 0) + { + AutoScrollMinSize = new Size(AutoScrollMinSize.Width, AutoScrollMinSize.Height + num); + } + } + + private int LowestChildBottom() + { + int num = 0; + int y = AutoScrollPosition.Y; + foreach (Control control in Controls) + { + if (control.Visible) + { + num = Math.Max(num, control.Bottom - y); + } + } + return num; + } + + private void HideNativeScrollBars() + { + if (IsHandleCreated && !IsDisposed) + { + ShowScrollBar(Handle, 3, bShow: false); + } + } + + protected void FitScrollToContent(int bottomPadding = 40) + { + int y = AutoScrollPosition.Y; + int num = 0; + foreach (Control control in Controls) + { + if (control.Visible) + { + num = Math.Max(num, control.Bottom - y); + } + } + if (num > 0) + { + AutoScrollMinSize = new Size(0, num + bottomPadding); + } + } + + protected override void OnResize(EventArgs e) + { + base.OnResize(e); + CentreContent(); + LayoutHeaderPanel(); + } + + protected int AtDesignScale(int logical) + { + return (int)Math.Round((float)logical * DesignScale); + } + + protected void ScaleToCurrentDesign(Control c) + { + float designScale = DesignScale; + if (!(Math.Abs(designScale - 1f) < 0.001f)) + { + c.Scale(new SizeF(designScale, designScale)); + } + } + + private void CentreContent() + { + if (_contentWidth <= 0 || Width <= 0 || Width == _centredForWidth) + { + return; + } + _centredForWidth = Width; + float scale = DesignScale; + if (_designLeft == null) + { + _designLeft = Controls.Cast().ToDictionary((Control c) => c, (Control c) => (int)Math.Round((float)c.Left / scale)); + } + if (_designLeft.Count > Controls.Count) + { + HashSet live = new HashSet(Controls.Cast()); + foreach (Control item in _designLeft.Keys.Where((Control k) => !live.Contains(k)).ToList()) + { + _designLeft.Remove(item); + } + } + int num = Math.Max(0, (Width - (int)Math.Round((float)_contentWidth * scale)) / 2); + foreach (Control control in Controls) + { + if (control != _headerCard) + { + if (!_designLeft.TryGetValue(control, out var value)) + { + value = (int)Math.Round((float)(control.Left - CurrentOffset()) / scale); + _designLeft[control] = value; + } + control.Left = (int)Math.Round((float)value * scale) + num; + } + } + _lastOffset = num; + } + + private int CurrentOffset() + { + return _lastOffset; + } + + protected override void OnPaint(PaintEventArgs e) + { + using (SolidBrush brush = new SolidBrush(Theme.Background)) + { + e.Graphics.FillRectangle(brush, ClientRectangle); + } + Graphics g = e.Graphics; + PaintGuard.Try(this, () => + { + AppBackground.Paint(g, FieldOffset.X, FieldOffset.Y); + Field?.Paint(g, FieldOffset.X, FieldOffset.Y); + PaintHeaderScrim(g); + }); + base.OnPaint(e); + } + + private void PaintHeaderScrim(Graphics g) + { + if (Width <= 0 || _headerCard != null) + { + return; + } + Rectangle rect = new Rectangle(0, 0, Width, 102); + if (rect.Height <= 0) + { + return; + } + int alpha = (SlateSurface.Active ? 215 : 150); + using LinearGradientBrush brush = new LinearGradientBrush(rect, Color.FromArgb(alpha, Theme.Background), Color.FromArgb(0, Theme.Background), LinearGradientMode.Vertical); + g.FillRectangle(brush, rect); + } +} diff --git a/VibranceHud/Pages/LegalPage.cs b/VibranceHud/Pages/LegalPage.cs new file mode 100644 index 0000000..bdab3ea --- /dev/null +++ b/VibranceHud/Pages/LegalPage.cs @@ -0,0 +1,385 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text.RegularExpressions; +using System.Windows.Forms; +using VibranceHud.Controls; +using VibranceHud.Design; + +namespace VibranceHud.Pages; + +public sealed class LegalPage : GlowPage +{ + internal static readonly (string Title, string Resource)[] Documents = new (string, string)[4] + { + ("Terms of use", "EULA.md"), + ("Privacy", "PRIVACY.md"), + ("Licence", "LICENSE.md"), + ("Third-party notices", "THIRD-PARTY-NOTICES.md") + }; + + internal const string CouldNotShow = "This document couldn't be shown. A copy is installed next to PlexusX.exe."; + + private const int HeadingLimit = 90; + + private readonly CardPanel _card; + + private readonly Label _caption; + + private readonly GlassDropdown _picker; + + private readonly NotesView _notes; + + private readonly GlassButton _back; + + private bool _laying; + + private bool _built; + + private static readonly Regex Rule = new Regex("^(-{3,}|\\*{3,}|_{3,})$", RegexOptions.Compiled); + + private static readonly Regex TableSeparator = new Regex("^\\|?[\\s:|\\-]+\\|?$", RegexOptions.Compiled); + + private static readonly Regex Numbered = new Regex("^\\d+[.)]\\s+", RegexOptions.Compiled); + + private static readonly Regex Link = new Regex("\\[([^\\]]+)\\]\\(([^)\\s]+)\\)", RegexOptions.Compiled); + + private static readonly Regex Italic = new Regex("(? "Legal & licences"; + + protected override string PageSubtitle => "The terms of use, the privacy policy and the licences of the parts PlexusX uses."; + + protected override bool UsesHeaderPanel => true; + + protected override Control[] HeaderActions => new Control[1] { _back }; + + protected override bool LaysOutInLogicalPixels => false; + + private static int S(int logical) + { + return Tokens.Scale(logical); + } + + public LegalPage(Action? onBack = null) + { + LegalPage legalPage = this; + AutoScroll = false; + SetStyle(ControlStyles.Selectable, value: true); + TabStop = false; + _back = new GlassButton + { + Text = "Back", + Kind = GlassButtonKind.Secondary + }; + _back.Click += (object? _, EventArgs _) => + { + onBack?.Invoke(); + }; + SizeBack(); + _card = new CardPanel + { + Name = "LegalCard" + }; + _caption = UiHelpers.Caption("Document", 0, 0, 100); + _caption.UseMnemonic = false; + _card.Controls.Add(_caption); + _picker = new GlassDropdown + { + AccessibleName = "Document" + }; + _picker.SetItems(Documents.Select(((string Title, string Resource) d) => d.Title)); + _card.Controls.Add(_picker); + _notes = new NotesView + { + OnCard = true, + HeadingLimit = 90, + AccessibleName = "Document text", + AccessibleRole = AccessibleRole.Document + }; + _notes.MouseDown += (object? _, MouseEventArgs _) => + { + if (!legalPage.ContainsFocus) + { + legalPage.Focus(); + } + }; + _card.Controls.Add(_notes); + _picker.SelectedIndexChanged += (object? _, EventArgs _) => + { + legalPage.Show(legalPage._picker.SelectedIndex); + }; + Controls.Add(_card); + Show(0); + _built = true; + } + + private void SizeBack() + { + int height = S(32); + _back.Height = height; + _back.Width = Math.Max(S(64), _back.GetPreferredSize(Size.Empty).Width); + } + + protected override void OnHandleCreated(EventArgs e) + { + base.OnHandleCreated(e); + LayoutContent(); + BeginInvoke(() => + { + if (!IsDisposed && Visible && !ContainsFocus) + { + Focus(); + } + }); + } + + protected override void OnLayout(LayoutEventArgs e) + { + base.OnLayout(e); + LayoutContent(); + } + + protected override void OnResize(EventArgs e) + { + base.OnResize(e); + LayoutContent(); + } + + private void LayoutContent() + { + if (!_built || _laying || IsDisposed || ClientSize.Width <= 0 || ClientSize.Height <= 0) + { + return; + } + _laying = true; + try + { + int num = _back.Width * 4096 + _back.Height; + SizeBack(); + if (HasHeaderPanel && num != _back.Width * 4096 + _back.Height) + { + LayoutHeaderPanel(); + } + int contentLeft = GlowPage.ContentLeft; + int contentTop = ContentTop; + int num2 = ClientSize.Height + 1 - S(16); + int num3 = Math.Max(S(240), ContentRight - GlowPage.ContentLeft); + int num4 = Math.Max(S(120), num2 - contentTop); + _card.SetBounds(contentLeft, contentTop, num3, num4); + int num5 = S(20); + int num6 = S(16); + int num7 = Math.Max(S(120), num3 - 2 * num5); + int num8 = Fonts.LineHeight(FontRole.CaptionBold); + _caption.SetBounds(num5, num6, num7, num8); + int num9 = num6 + num8 + S(8); + _picker.SetBounds(num5, num9, Math.Min(S(280), num7), S(32)); + int num10 = num9 + S(32) + S(16); + _notes.SetBounds(num5, num10, num7, Math.Max(S(40), num4 - num10 - num6)); + } + finally + { + _laying = false; + } + } + + private void Show(int index) + { + if (index < 0 || index >= Documents.Length) + { + index = 0; + } + _notes.NotesText = LoadDocument(Documents[index].Resource); + } + + protected override void OnMouseWheel(MouseEventArgs e) + { + if (!(e is HandledMouseEventArgs { Handled: not false })) + { + _notes.Wheel(e.Delta); + if (e is HandledMouseEventArgs e3) + { + e3.Handled = true; + } + } + } + + protected override bool ProcessCmdKey(ref Message msg, Keys keyData) + { + Control control = ActiveControl; + while (control is ContainerControl containerControl) + { + Control activeControl = containerControl.ActiveControl; + if (activeControl == null) + { + break; + } + control = activeControl; + } + if (ScrollKey(keyData, control)) + { + return true; + } + return base.ProcessCmdKey(ref msg, keyData); + } + + private bool ScrollKey(Keys keyData, Control? focused) + { + if ((keyData & Keys.Modifiers) != 0) + { + return false; + } + bool flag; + switch (keyData) + { + case Keys.End: + case Keys.Home: + case Keys.Up: + case Keys.Down: + flag = true; + break; + default: + flag = false; + break; + } + if (flag && focused is GlassDropdown) + { + return false; + } + return _notes.ScrollByKey(keyData); + } + + internal bool PressKeyForTest(Keys key, Control? focused = null) + { + return ScrollKey(key, focused); + } + + internal static string LoadDocument(string resource) + { + return LoadDocument(resource, (string name) => Assembly.GetExecutingAssembly().GetManifestResourceStream(name)); + } + + internal static string LoadDocument(string resource, Func open) + { + try + { + using Stream stream = open(resource); + if (stream == null) + { + return "This document couldn't be shown. A copy is installed next to PlexusX.exe."; + } + using StreamReader streamReader = new StreamReader(stream); + return Normalise(streamReader.ReadToEnd()); + } + catch (Exception ex) + { + try + { + CrashLog.Write(ex); + } + catch + { + } + return "This document couldn't be shown. A copy is installed next to PlexusX.exe."; + } + } + + internal static string Normalise(string markdown) + { + List lines = new List(); + bool flag = false; + bool flag2 = false; + string[] array = markdown.Replace("\r\n", "\n").Split('\n'); + for (int i = 0; i < array.Length; i++) + { + string text = array[i].Trim(); + if (text.StartsWith("```")) + { + flag = !flag; + Blank(); + continue; + } + if (flag) + { + if (text.Length > 0) + { + lines.Add(text); + lines.Add(""); + } + continue; + } + bool flag3 = text.StartsWith("|"); + if (flag2 && !flag3) + { + Blank(); + flag2 = false; + } + if (text.Length == 0) + { + Blank(); + } + else if (Rule.IsMatch(text)) + { + Blank(); + } + else if (text.StartsWith("#")) + { + Blank(); + lines.Add(Inline(text.TrimStart('#').Trim())); + lines.Add(""); + } + else if (flag3) + { + flag2 = true; + if (!TableSeparator.IsMatch(text)) + { + IEnumerable values = from c in text.Trim('|').Split('|') + select Inline(c.Trim()) into c + where c.Length > 0 + select c; + lines.Add("• " + string.Join(" — ", values)); + } + } + else if (text.StartsWith("> ") || text == ">") + { + lines.Add(Inline(text.TrimStart('>').Trim())); + } + else if ((text[0] == '-' || text[0] == '*' || text[0] == '+') && text.Length > 1 && char.IsWhiteSpace(text[1])) + { + lines.Add("• " + Inline(text.Substring(1).Trim())); + } + else if (Numbered.IsMatch(text)) + { + Blank(); + lines.Add(Inline(text)); + } + else + { + lines.Add(Inline(text)); + } + } + return string.Join("\n", lines).Trim('\n'); + void Blank() + { + if (lines.Count > 0) + { + List list = lines; + if (list[list.Count - 1].Length != 0) + { + lines.Add(""); + } + } + } + } + + private static string Inline(string s) + { + s = Link.Replace(s, (Match m) => (!(m.Groups[1].Value == m.Groups[2].Value)) ? (m.Groups[1].Value + " (" + m.Groups[2].Value + ")") : m.Groups[1].Value); + s = s.Replace("**", "").Replace("`", ""); + s = Italic.Replace(s, "$1"); + return s; + } +} diff --git a/VibranceHud/Pages/LibraryPage.cs b/VibranceHud/Pages/LibraryPage.cs new file mode 100644 index 0000000..a8cf6f3 --- /dev/null +++ b/VibranceHud/Pages/LibraryPage.cs @@ -0,0 +1,1340 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Globalization; +using System.Linq; +using System.Windows.Forms; +using A; +using VibranceHud.Controls; +using VibranceHud.Crosshair; +using VibranceHud.Design; +using VibranceHud.Display; +using VibranceHud.Licensing; +using VibranceHud.Presets; + +namespace VibranceHud.Pages; + +public sealed class LibraryPage : GlowPage +{ + private sealed record Fact(string Name, string Author, string Blurb, string Summary, string Glyph, Action Apply, string? CommunityId); + + internal sealed class StatusLine : Label + { + private readonly bool _link; + + private bool _hovered; + + private readonly OutsideFocusRing _focusRing; + + internal StatusLine(bool link = false) + { + _link = link; + _focusRing = new OutsideFocusRing(this, () => ControlInk.PxF(ControlInk.Dpi(this), 4f)); + if (link) + { + SetStyle(ControlStyles.Selectable, value: true); + } + TabStop = link; + } + + protected override void OnTextChanged(EventArgs e) + { + base.OnTextChanged(e); + AccessibleName = Text; + } + + protected override void OnParentChanged(EventArgs e) + { + base.OnParentChanged(e); + _focusRing?.Rehook(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _focusRing.Release(); + } + base.Dispose(disposing); + } + + protected override bool IsInputKey(Keys keyData) + { + if (!_link || (keyData & Keys.KeyCode) != Keys.Return) + { + return base.IsInputKey(keyData); + } + return true; + } + + protected override void OnMouseEnter(EventArgs e) + { + base.OnMouseEnter(e); + _hovered = true; + Invalidate(); + } + + protected override void OnMouseLeave(EventArgs e) + { + base.OnMouseLeave(e); + _hovered = false; + Invalidate(); + } + + protected override void OnGotFocus(EventArgs e) + { + base.OnGotFocus(e); + Invalidate(); + } + + protected override void OnLostFocus(EventArgs e) + { + base.OnLostFocus(e); + Invalidate(); + } + + protected override void OnPaint(PaintEventArgs e) + { + _focusRing.Show(_link && Focused && ShowFocusCues); + using Font font = ((_link && (_hovered || Focused)) ? new Font(Font, Font.Style | FontStyle.Underline) : null); + Font font2 = font ?? Font; + if (SlateSurface.Active && Text.Length > 0) + { + TextFormatFlags flags = TextFormatFlags.NoPrefix | TextFormatFlags.WordBreak | TextFormatFlags.NoPadding; + int num = Tokens.Scale(8); + int width = Math.Max(1, Width - 2 * num); + Size size = TextRenderer.MeasureText(e.Graphics, Text, font2, new Size(width, int.MaxValue), flags); + RectangleF rect = new RectangleF(0f, 0f, Math.Min(Width, size.Width + 2 * num), Math.Min(Height, size.Height + 2)); + e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; + Glass.PaintPanel(e.Graphics, rect, Tokens.Scale(4), Glass.BackdropOffsetOf(this)); + TextRenderer.DrawText(e.Graphics, Text, font2, new Rectangle(num, 1, width, Math.Max(1, Height - 1)), ForeColor, flags); + } + else if (_link) + { + TextRenderer.DrawText(e.Graphics, Text, font2, ClientRectangle, ForeColor, TextFormatFlags.NoPrefix | TextFormatFlags.WordBreak); + } + else + { + base.OnPaint(e); + } + } + } + + private const int Pad = 16; + + private const int CardW = 932; + + private const int RightInset = 15; + + private new const int Gutter = 0; + + private const int CardGap = 16; + + private const int RowGap = 16; + + private const int WallTop = 0; + + private const int RowHeight = 32; + + private readonly AppSettings _settings; + + private readonly SettingsStore _store; + + private readonly Func _onApply; + + private readonly Func _nvidiaDriverAvailable; + + internal const string ColourKind = "Colour looks"; + + internal const string CrosshairKind = "Crosshairs"; + + internal const string DisplayKind = "Resolutions"; + + internal const string ConfigKind = "Setups"; + + internal const string AllGamesLabel = "All games"; + + internal static readonly string[] Kinds = new string[4] { "Colour looks", "Crosshairs", "Resolutions", "Setups" }; + + private const int TabStripW = 369; + + private const int GamePickerW = 128; + + private const int SortSlotW = 112; + + private const int FilterGap = 8; + + private const int WallHeight = 424; + + private const int DesignCardH = 204; + + private readonly SegmentStrip _kindTabs; + + private readonly GlassTextBox _search; + + private readonly Panel _toolbar; + + private readonly GlassDropdown _gamePicker; + + private readonly List _crosshairChips = new List(); + + private readonly Action? _onApplyCrosshair; + + private readonly Func? _onApplyMode; + + private string _kind = "Colour looks"; + + private readonly QuietScrollPanel _wall; + + private readonly Label _status; + + private readonly List _chips = new List(); + + private readonly GlassButton _upload; + + private readonly GlassButton _retry; + + private readonly Action? _onOpenPage; + + private bool _fetchFailed; + + private readonly LibraryToast _toast; + + private LibraryPreset? _currentApply; + + private LibraryPreset? _previousApply; + + private readonly List