diff --git a/docs/release-notes/v1.10.0.md b/docs/release-notes/v1.10.0.md new file mode 100644 index 0000000..8fca5aa --- /dev/null +++ b/docs/release-notes/v1.10.0.md @@ -0,0 +1,7 @@ +# Gloam 1.10.0 + +- SDR calibration now ACTUALLY reaches the display. Gloam used to register SDR profiles only where Windows ignores calibration data, so verification measured the uncorrected panel. If your most recent Gloam calibration was in SDR, Gloam re-applies it the next time the display is in SDR. For an older calibration of the other mode, switch the display to that mode and activate it once in Profile Manager; Gloam swaps it in from then on. +- SDR calibration applies only while **Automatically manage color for apps** is on (Settings > System > Display). Gloam tells you after installing if it's off. Keep measuring with it off, then turn it on. +- SDR and HDR calibrations are now kept separately. Windows has room for one calibration per display, so Gloam swaps in the right one whenever you turn HDR on or off. When you switch to a mode with no Gloam calibration, or deactivate one in Profile Manager, the advanced color profile Gloam replaced comes back (for profiles replaced by 1.10 or later). + +Thanks to MrBrown55 for the detailed report and diagnostics in [#11](https://github.com/halideworks/gloam/issues/11)! diff --git a/src/Gloam.Core/Calibration/AdvancedColorProfileAssociation.cs b/src/Gloam.Core/Calibration/AdvancedColorProfileAssociation.cs index 4a7bc8a..d2bd033 100644 --- a/src/Gloam.Core/Calibration/AdvancedColorProfileAssociation.cs +++ b/src/Gloam.Core/Calibration/AdvancedColorProfileAssociation.cs @@ -58,12 +58,14 @@ internal static class AdvancedColorProfileAssociation /// /// "There was nothing there" HRESULTs: FILE_NOT_FOUND, PATH_NOT_FOUND and - /// NOT_FOUND. Removing an association that does not exist is a success, not a fault. + /// NOT_FOUND, plus PROFILE_NOT_ASSOCIATED_WITH_DEVICE. Removing an association that + /// does not exist is a success, not a fault. /// private static bool IsNotFound(int hr) => hr == unchecked((int)0x80070002) || hr == unchecked((int)0x80070003) || - hr == unchecked((int)0x80070490); + hr == unchecked((int)0x80070490) || + hr == unchecked((int)0x800707DF); internal static IAdvancedColorProfilePlatform Platform { get; set; } = new WindowsAdvancedColorProfilePlatform(); diff --git a/src/Gloam.Core/Calibration/AdvancedColorProfileMigrationService.cs b/src/Gloam.Core/Calibration/AdvancedColorProfileMigrationService.cs index 596a023..a9fe975 100644 --- a/src/Gloam.Core/Calibration/AdvancedColorProfileMigrationService.cs +++ b/src/Gloam.Core/Calibration/AdvancedColorProfileMigrationService.cs @@ -44,6 +44,8 @@ public Result Run() return new Result(0, 0, 0, 0, 1); } + ReconcileModeChanges(monitors); + foreach (var monitor in monitors) { var saved = _settings.GetMonitorProfile(monitor.MonitorDevicePath); @@ -148,6 +150,145 @@ public Result Run() return result; } + internal readonly record struct ModeSwitch(string? Disable, string? Enable, bool VerifyOnly, bool RestorePrevious); + + /// + /// Windows has one Advanced Color default for SDR and HDR, so the Gloam profile built + /// for the display's current mode must be swapped in whenever that mode changes. + /// Acts on first sight of a monitor and on each SDR/HDR transition, not on every + /// display event. + /// + public void ReconcileModeChanges() + { + IReadOnlyList monitors; + try { monitors = _enumerateMonitors(); } + catch (Exception ex) + { + Log.Info($"AdvancedColorProfileMigration: monitor enumeration failed: {ex.Message}"); + return; + } + ReconcileModeChanges(monitors); + } + + internal void ReconcileModeChanges(IReadOnlyList monitors) + { + foreach (var monitor in monitors) + { + if (string.IsNullOrEmpty(monitor.MonitorDevicePath)) continue; + lock (_lastHdrLock) + { + if (_lastHdr.TryGetValue(monitor.MonitorDevicePath, out bool last) && last == monitor.IsHdrActive) + continue; + _lastHdr[monitor.MonitorDevicePath] = monitor.IsHdrActive; + } + bool settled; + try { settled = ReconcileMode(monitor); } + catch (Exception ex) + { + settled = false; + Log.Error($"AdvancedColorProfileMigration: mode reconcile failed on {monitor.FriendlyName}: {ex.Message}"); + } + // Forget the mode so the next display event retries instead of waiting for a flip. + if (!settled) + lock (_lastHdrLock) _lastHdr.Remove(monitor.MonitorDevicePath); + } + } + + private readonly Dictionary _lastHdr = new(StringComparer.OrdinalIgnoreCase); + private readonly object _lastHdrLock = new(); + private readonly HashSet _restorePending = new(StringComparer.OrdinalIgnoreCase); + + /// Returns false when Windows refused a step and the reconcile should be retried. + private bool ReconcileMode(MonitorInfo monitor) + { + string path = monitor.MonitorDevicePath; + var saved = _settings.GetMonitorProfile(path); + if (saved == null) return true; + + // Records from before per-mode slots: classify the active profile from its + // generated name, else from the mode stored with the pre-Gloam default. + if (saved.Mhc2SdrProfileName == null && saved.Mhc2HdrProfileName == null && + !string.IsNullOrEmpty(saved.Mhc2ProfileName) && + (CalibrationProfileInstaller.ClassifyHdrFromName(saved.Mhc2ProfileName) ?? saved.PreviousColorProfileHdrMode) + is bool legacyHdr) + { + _settings.SetMhc2ModeSlot(path, saved.Mhc2ProfileName, legacyHdr); + saved = _settings.GetMonitorProfile(path)!; + } + + var plan = DecideModeSwitch(saved.Mhc2SdrProfileName, saved.Mhc2HdrProfileName, + saved.Mhc2ProfileName, monitor.IsHdrActive); + bool hdr = monitor.IsHdrActive; + + if (plan.VerifyOnly) + { + // Same handling as the startup repair always had: re-assert, never clear. + if (!AdvancedColorProfileAssociation.TryIsVerifiedCurrentUserDefault( + monitor, plan.Enable!, out bool isActive, out _)) + return false; + if (isActive) return true; + if (CalibrationProfileInstaller.Reenable(monitor, plan.Enable!, hdr, out string? displacedOnVerify)) + { + _settings.RecordDisplacedAdvancedColorProfile(path, displacedOnVerify); + Log.Info($"AdvancedColorProfileMigration: re-activated '{plan.Enable}' on {monitor.FriendlyName}."); + return true; + } + Log.Error($"AdvancedColorProfileMigration: could not re-activate '{plan.Enable}' on {monitor.FriendlyName}."); + return false; + } + + if (plan.Disable != null) + { + if (!CalibrationProfileInstaller.Disable(monitor, plan.Disable)) + { + Log.Error($"AdvancedColorProfileMigration: could not retire '{plan.Disable}' on {monitor.FriendlyName}; keeping it recorded as active."); + return false; + } + _settings.SetActiveMhc2Profile(path, null); + Log.Info($"AdvancedColorProfileMigration: retired '{plan.Disable}' on {monitor.FriendlyName}; it was built for {(hdr ? "SDR" : "HDR")}."); + } + + if (plan.Enable != null) + { + if (!CalibrationProfileInstaller.Reenable(monitor, plan.Enable, hdr, out string? displaced)) + { + Log.Error($"AdvancedColorProfileMigration: could not activate {(hdr ? "HDR" : "SDR")} profile '{plan.Enable}' on {monitor.FriendlyName}."); + return false; + } + _settings.SetActiveMhc2Profile(path, plan.Enable); + _settings.RecordDisplacedAdvancedColorProfile(path, displaced); + Log.Info($"AdvancedColorProfileMigration: activated {(hdr ? "HDR" : "SDR")} profile '{plan.Enable}' on {monitor.FriendlyName}."); + } + + bool restorePending; + lock (_lastHdrLock) restorePending = _restorePending.Remove(path); + if (plan.Enable == null && (plan.RestorePrevious || restorePending) && + saved.PreviousAdvancedColorProfileName is { Length: > 0 } previous) + { + bool restored = CalibrationProfileInstaller.RestoreDefaultProfile(monitor, previous, hdrMode: true); + Log.Info($"AdvancedColorProfileMigration: {(restored ? "restored" : "could not restore")} previous Advanced Color profile '{previous}' on {monitor.FriendlyName}."); + if (!restored) + { + // The retire already happened, so the retry's plan will not ask for this again. + lock (_lastHdrLock) _restorePending.Add(path); + return false; + } + // Back in place; a later Gloam activation records whatever is default then. + _settings.ClearDisplacedAdvancedColorProfile(path); + } + return true; + } + + internal static ModeSwitch DecideModeSwitch(string? sdrSlot, string? hdrSlot, string? active, bool hdr) + { + // No slot at all: no calibration, or a legacy record whose mode is unknown. + if (sdrSlot == null && hdrSlot == null) return default; + string? desired = hdr ? hdrSlot : sdrSlot; + if (string.Equals(desired, active, StringComparison.OrdinalIgnoreCase)) + return desired == null ? default : new ModeSwitch(null, desired, VerifyOnly: true, RestorePrevious: false); + return new ModeSwitch(active, desired, VerifyOnly: false, RestorePrevious: desired == null && active != null); + } + internal static string BuildRepairedProfileName(string existingProfileName) { string stem = Path.GetFileNameWithoutExtension(existingProfileName); diff --git a/src/Gloam.Core/Calibration/CalibrationProfileInstaller.cs b/src/Gloam.Core/Calibration/CalibrationProfileInstaller.cs index 2d4ce01..454f5fa 100644 --- a/src/Gloam.Core/Calibration/CalibrationProfileInstaller.cs +++ b/src/Gloam.Core/Calibration/CalibrationProfileInstaller.cs @@ -26,7 +26,8 @@ public static class CalibrationProfileInstaller /// really on the wire. Null for SDR installs and failures before LUT generation. /// public sealed record InstallResult(bool Success, string ProfileName, string? Error, - HdrMhc2LutBuilder.Result? HdrLuts = null); + HdrMhc2LutBuilder.Result? HdrLuts = null, string? Warning = null, + string? DisplacedAdvancedColorProfile = null); /// /// The exact gamut-matrix plan the installer will write. Joint HDR refinement uses @@ -358,8 +359,25 @@ public static InstallResult Install( // Override names support the live white-trim preview: it alternates between two // fixed names so each step forces the compositor to load fresh content instead // of trusting a possibly-cached profile, without littering the store. - string profileName = profileNameOverride ?? BuildProfileName(monitor, target); + string profileName = profileNameOverride ?? UniqueInColorStore(BuildProfileName(monitor, target)); string srcPath = Path.Combine(Path.GetTempPath(), profileName); + string? warning = null; + bool newlyInstalled = false, legacyAssociated = false; + + void UndoFailedInstall() + { + try + { + if (legacyAssociated) + Wcs.DisassociateColorProfileFromDevice(null, profileName, monitor.MonitorDevicePath); + if (newlyInstalled) + AdvancedColorProfileAssociation.Platform.UninstallColorProfile(profileName, delete: true); + } + catch (Exception ex) + { + Log.Error($"CalibrationProfileInstaller: cleanup after failed install of '{profileName}' failed: {ex.Message}"); + } + } try { @@ -385,48 +403,60 @@ public static InstallResult Install( ? characterization.PeakLuminance : null); - if (hdrMode) + var platform = AdvancedColorProfileAssociation.Platform; + // Override names (the trim preview's A/B) are reused with new bytes and are + // never the recorded calibration, so the old file can go first. + if (profileNameOverride != null && File.Exists(Path.Combine(platform.ColorStoreDirectory, profileName))) + Uninstall(monitor, profileName); + if (!TryInstallVerified(srcPath, profileName, platform, out newlyInstalled, out string? installError)) { - if (!TryInstallVerified(srcPath, profileName, - AdvancedColorProfileAssociation.Platform, out bool newlyInstalled, out string? installError)) - { - Log.Error($"CalibrationProfileInstaller: color-store install failed for '{profileName}': {installError}"); - return new InstallResult(false, profileName, installError); - } - - if (!AdvancedColorProfileAssociation.TryActivateInstalled( - monitor, profileName, out _, out string? associationError)) - { - Log.Error($"CalibrationProfileInstaller: Advanced Color association failed for '{profileName}': {associationError}"); - if (newlyInstalled) - AdvancedColorProfileAssociation.Platform.UninstallColorProfile(profileName, delete: true); - return new InstallResult(false, profileName, associationError); - } + Log.Error($"CalibrationProfileInstaller: color-store install failed for '{profileName}': {installError}"); + return new InstallResult(false, profileName, installError); } - else + + // Apps read the legacy list, but Windows applies MHC2 only from the + // Advanced Color list, and in SDR only while ACM is on. + if (!hdrMode) { - if (!Wcs.InstallColorProfile(null, srcPath)) - Log.Info($"CalibrationProfileInstaller: InstallColorProfile returned false for {profileName} (may already exist)."); - if (!Wcs.AssociateColorProfileWithDevice(null, srcPath, monitor.MonitorDevicePath)) + legacyAssociated = AssociateLegacyDefault(monitor, profileName); + if (!legacyAssociated) { Log.Error($"CalibrationProfileInstaller: SDR association failed for '{profileName}' " + $"(Win32 {Marshal.GetLastWin32Error()})."); + UndoFailedInstall(); return new InstallResult(false, profileName, "Windows refused to associate the profile with the display. Make sure the monitor is active."); } + } - if (!Wcs.WcsSetDefaultColorProfile( - Wcs.WCS_PROFILE_MANAGEMENT_SCOPE.WCS_PROFILE_MANAGEMENT_SCOPE_CURRENT_USER, - monitor.MonitorDevicePath, Wcs.CPT_ICC, Wcs.CPST_PERCEPTUAL, 0, profileName)) - Log.Info($"CalibrationProfileInstaller: WcsSetDefaultColorProfile returned false for {profileName}."); + if (!AdvancedColorProfileAssociation.TryActivateInstalled( + monitor, profileName, out var receipt, out string? associationError)) + { + Log.Error($"CalibrationProfileInstaller: Advanced Color association failed for '{profileName}': {associationError}"); + UndoFailedInstall(); + return new InstallResult(false, profileName, hdrMode + ? associationError + : $"Windows refused the Advanced Color association, so the correction cannot apply: {associationError}"); } - Log.Info($"CalibrationProfileInstaller: Installed + set default '{profileName}' for {monitor.FriendlyName} ({(hdrMode ? "advanced color" : "SDR")} association)."); - return new InstallResult(true, profileName, null, installedHdrLuts); + string? displaced = ForeignPriorDefault(monitor, receipt); + + if (!hdrMode && + CalibrationInstallPreflight.DetectSdrAutoColorManagement(monitor.DeviceName, hdrActive: false) == false) + { + warning = "The profile is installed, but Windows applies SDR calibration only while " + + "\"Automatically manage color for apps\" is on (Settings > System > Display). " + + "Turn it on, then verify."; + Log.Info($"CalibrationProfileInstaller: SDR profile '{profileName}' installed with Auto Color Management off; it will not apply until ACM is enabled."); + } + + Log.Info($"CalibrationProfileInstaller: Installed + set default '{profileName}' for {monitor.FriendlyName} ({(hdrMode ? "advanced color" : "SDR + advanced color")} association)."); + return new InstallResult(true, profileName, null, installedHdrLuts, warning, displaced); } catch (Exception ex) { Log.Error($"CalibrationProfileInstaller: Install failed: {ex.Message}"); + UndoFailedInstall(); return new InstallResult(false, profileName, ex.Message); } finally @@ -481,22 +511,36 @@ public static bool Disable(MonitorInfo monitor, string profileName) /// refuses the association. /// public static bool Reenable(MonitorInfo monitor, string profileName, bool hdrMode) + => Reenable(monitor, profileName, hdrMode, out _); + + /// + /// The non-Gloam Advanced Color default this activation replaced, if any. + /// + public static bool Reenable( + MonitorInfo monitor, string profileName, bool hdrMode, out string? displacedAdvancedColorProfile) { + displacedAdvancedColorProfile = null; if (string.IsNullOrEmpty(monitor.MonitorDevicePath) || string.IsNullOrEmpty(profileName)) return false; try { - if (hdrMode) + bool legacyWasDefault = false; + if (!hdrMode) { - return AdvancedColorProfileAssociation.TryActivateInstalled( - monitor, profileName, out _, out _); + legacyWasDefault = string.Equals(GetCurrentDefaultProfile(monitor, hdrMode: false), profileName, + StringComparison.OrdinalIgnoreCase); + if (!AssociateLegacyDefault(monitor, profileName)) + return false; } - if (!Wcs.AssociateColorProfileWithDevice(null, profileName, monitor.MonitorDevicePath)) - return false; - Wcs.WcsSetDefaultColorProfile( - Wcs.WCS_PROFILE_MANAGEMENT_SCOPE.WCS_PROFILE_MANAGEMENT_SCOPE_CURRENT_USER, - monitor.MonitorDevicePath, Wcs.CPT_ICC, Wcs.CPST_PERCEPTUAL, 0, profileName); - return true; + // SDR MHC2 applies only from the Advanced Color list; see Install. + if (AdvancedColorProfileAssociation.TryActivateInstalled(monitor, profileName, out var receipt, out _)) + { + displacedAdvancedColorProfile = ForeignPriorDefault(monitor, receipt); + return true; + } + if (!hdrMode && !legacyWasDefault) + Wcs.DisassociateColorProfileFromDevice(null, profileName, monitor.MonitorDevicePath); + return false; } catch (Exception ex) { @@ -505,6 +549,16 @@ public static bool Reenable(MonitorInfo monitor, string profileName, bool hdrMod } } + private static string? ForeignPriorDefault( + MonitorInfo monitor, AdvancedColorProfileAssociation.ActivationReceipt? receipt) + { + string? prior = receipt?.PriorCurrentUserDefault; + return string.IsNullOrWhiteSpace(prior) || + prior.StartsWith(BuildProfileNamePrefix(monitor), StringComparison.OrdinalIgnoreCase) + ? null + : prior; + } + /// /// Creates and installs an ICC-safe copy of an existing Gloam HDR profile while /// preserving its measured MHC2 calibration payload. The new copy becomes the @@ -648,6 +702,17 @@ public static void Uninstall(MonitorInfo monitor, string profileName) } } + private static bool AssociateLegacyDefault(MonitorInfo monitor, string profileName) + { + if (!Wcs.AssociateColorProfileWithDevice(null, profileName, monitor.MonitorDevicePath)) + return false; + if (!Wcs.WcsSetDefaultColorProfile( + Wcs.WCS_PROFILE_MANAGEMENT_SCOPE.WCS_PROFILE_MANAGEMENT_SCOPE_CURRENT_USER, + monitor.MonitorDevicePath, Wcs.CPT_ICC, Wcs.CPST_PERCEPTUAL, 0, profileName)) + Log.Info($"CalibrationProfileInstaller: WcsSetDefaultColorProfile returned false for {profileName}."); + return true; + } + /// /// Installs a staged profile and verifies the color-store bytes. InstallColorProfile /// returns false both for real failures and for a filename that already exists, so a @@ -738,6 +803,47 @@ private static string BuildProfileName(MonitorInfo monitor, CalibrationTarget ta return $"{monitorName} - {targetName} - {stamp}.icm"; } + /// + /// Minute stamps repeat (a white trim accepted right after Apply), and Windows will + /// not overwrite a store file, so a taken name gets a numeric suffix. + /// + private static string UniqueInColorStore(string profileName) + { + string store = AdvancedColorProfileAssociation.Platform.ColorStoreDirectory; + string stem = Path.GetFileNameWithoutExtension(profileName); + string ext = Path.GetExtension(profileName); + string candidate = profileName; + for (int n = 2; File.Exists(Path.Combine(store, candidate)); n++) + candidate = $"{stem} ({n}){ext}"; + return candidate; + } + + /// Mode a Gloam profile was built for; see . + public static bool? ClassifyHdrFromName(string profileName) => TargetFromProfileName(profileName)?.IsHdr; + + /// + /// Standard target a Gloam profile was built for, read from the target segment of its + /// generated name. Null for custom targets and foreign names. + /// + public static CalibrationTarget? TargetFromProfileName(string profileName) + { + CalibrationTarget[] targets = + { + StandardTargets.SrgbGamma22, StandardTargets.SrgbPiecewise, StandardTargets.Rec709Gamma24, + StandardTargets.Rec709PureGamma22, StandardTargets.P3D65Gamma22, StandardTargets.P3D65Gamma26, + StandardTargets.Rec2020Gamma24, StandardTargets.Rec2020Pq, StandardTargets.Rec2020Hlg, + StandardTargets.Rec709Pq, StandardTargets.P3Pq, + }; + foreach (var t in targets) + { + string segment = Sanitize(ShortTargetName(t)); + if (profileName.Contains($" - {segment} - ", StringComparison.OrdinalIgnoreCase) || + profileName.Contains($" - {segment} WPonly - ", StringComparison.OrdinalIgnoreCase)) + return t; + } + return null; + } + /// /// Prefix used by all Gloam-generated profile filenames for a monitor. This must /// match so profile listing and stale-association diff --git a/src/Gloam.Core/Calibration/VerificationPatchSets.cs b/src/Gloam.Core/Calibration/VerificationPatchSets.cs index b7dd8b1..fe8e73a 100644 --- a/src/Gloam.Core/Calibration/VerificationPatchSets.cs +++ b/src/Gloam.Core/Calibration/VerificationPatchSets.cs @@ -438,7 +438,7 @@ public static ProfileActivationCheck AnalyzeProfileActivation( pairs.Count, nativeAverage, verifiedAverage, - $"Profile activation sentinel warning: comparable patches were avg ΔE {nativeAverage:F2} native and {verifiedAverage:F2} after install, so the verification did not detect the expected movement toward target. Confirm the Windows color profile is active for this display and that verification ran on the same HDR/SDR mode used during measurement."); + $"Profile activation sentinel warning: comparable patches were avg ΔE {nativeAverage:F2} native and {verifiedAverage:F2} after install, so the verification did not detect the expected movement toward target. Confirm the Windows color profile is active for this display and that verification ran on the same HDR/SDR mode used during measurement. In SDR, Windows applies the profile only while \"Automatically manage color for apps\" is on."); } private static IEnumerable Eligible(IEnumerable? patches, bool whitePointOnly) diff --git a/src/Gloam.Core/SettingsManager.cs b/src/Gloam.Core/SettingsManager.cs index ddd3427..845e00c 100644 --- a/src/Gloam.Core/SettingsManager.cs +++ b/src/Gloam.Core/SettingsManager.cs @@ -94,6 +94,21 @@ public class MonitorProfileData /// public string? Mhc2ProfileName { get; set; } + /// + /// Gloam profile built for each display mode. Windows keeps one Advanced Color + /// default for both SDR and HDR, so the active profile is swapped on mode changes. + /// + public string? Mhc2SdrProfileName { get; set; } + + /// + public string? Mhc2HdrProfileName { get; set; } + + /// + /// Non-Gloam Advanced Color default that a Gloam install displaced, restored while + /// the current mode has no Gloam profile. + /// + public string? PreviousAdvancedColorProfileName { get; set; } + /// /// Windows color profile that was the display default before Gloam made an MHC2 /// calibration active. Kept so explicit deactivation/delete can restore the user's @@ -181,6 +196,9 @@ public class MonitorProfileData CalibrationProfileId = CalibrationProfileId, UseCalibrationForGamma = UseCalibrationForGamma, Mhc2ProfileName = Mhc2ProfileName, + Mhc2SdrProfileName = Mhc2SdrProfileName, + Mhc2HdrProfileName = Mhc2HdrProfileName, + PreviousAdvancedColorProfileName = PreviousAdvancedColorProfileName, PreviousColorProfileName = PreviousColorProfileName, PreviousColorProfileHdrMode = PreviousColorProfileHdrMode, MeterCorrectionPath = MeterCorrectionPath, @@ -680,6 +698,17 @@ public void SetMonitorProfile(string monitorDevicePath, MonitorProfileData profi Log.Info($"SettingsManager.SetMonitorProfile: Saving {monitorDevicePath} - Brightness={profile.Brightness}, Gamma={profile.GammaMode}"); lock (_dataLock) { + // Calibration fields change underneath an open editor (mode swaps on an HDR + // toggle), so a whole-record save from a stale copy must not roll them back. + if (_data.MonitorProfiles.TryGetValue(monitorDevicePath, out var current)) + { + profile.Mhc2ProfileName = current.Mhc2ProfileName; + profile.Mhc2SdrProfileName = current.Mhc2SdrProfileName; + profile.Mhc2HdrProfileName = current.Mhc2HdrProfileName; + profile.PreviousAdvancedColorProfileName = current.PreviousAdvancedColorProfileName; + profile.PreviousColorProfileName = current.PreviousColorProfileName; + profile.PreviousColorProfileHdrMode = current.PreviousColorProfileHdrMode; + } _data.MonitorProfiles[monitorDevicePath] = profile; _dataVersion++; } @@ -702,12 +731,15 @@ public void SetNightMode(NightModeSettings settings) /// /// Records (or clears, with null) the installed native MHC2 calibration profile for a /// monitor. Used by the apply path to compose night mode on top without double-gamma. + /// A name with also fills that mode's slot; null + /// clears the active profile and the slot that held it. /// public void SetMhc2Calibration( string monitorDevicePath, string? profileName, string? previousColorProfileName = null, - bool? previousColorProfileHdrMode = null) + bool? previousColorProfileHdrMode = null, + bool? builtForHdr = null) { if (string.IsNullOrEmpty(monitorDevicePath)) return; lock (_dataLock) @@ -717,8 +749,16 @@ public void SetMhc2Calibration( profile = new MonitorProfileData(); _data.MonitorProfiles[monitorDevicePath] = profile; } + if (profileName == null) + ForgetSlot(profile, profile.Mhc2ProfileName); + else if (builtForHdr == true) + profile.Mhc2HdrProfileName = profileName; + else if (builtForHdr == false) + profile.Mhc2SdrProfileName = profileName; profile.Mhc2ProfileName = profileName; - if (!string.IsNullOrEmpty(previousColorProfileName)) + // A backup passed through unchanged keeps the mode it was captured in. + if (!string.IsNullOrEmpty(previousColorProfileName) && + !string.Equals(profile.PreviousColorProfileName, previousColorProfileName, StringComparison.OrdinalIgnoreCase)) { profile.PreviousColorProfileName = previousColorProfileName; profile.PreviousColorProfileHdrMode = previousColorProfileHdrMode; @@ -729,6 +769,95 @@ public void SetMhc2Calibration( NotifyMonitorProfileChanged(monitorDevicePath); } + /// + /// Drops a profile from both mode slots and, if it is active, from the active record. + /// For explicit user deactivation or deletion. + /// + public void ForgetMhc2Profile(string monitorDevicePath, string profileName) + { + if (string.IsNullOrEmpty(monitorDevicePath) || string.IsNullOrEmpty(profileName)) return; + lock (_dataLock) + { + if (!_data.MonitorProfiles.TryGetValue(monitorDevicePath, out var profile)) return; + ForgetSlot(profile, profileName); + if (string.Equals(profile.Mhc2ProfileName, profileName, StringComparison.OrdinalIgnoreCase)) + profile.Mhc2ProfileName = null; + _dataVersion++; + } + Save(); + NotifyMonitorProfileChanged(monitorDevicePath); + } + + /// Changes only the active profile record; both mode slots are kept. + public void SetActiveMhc2Profile(string monitorDevicePath, string? profileName) + { + if (string.IsNullOrEmpty(monitorDevicePath)) return; + lock (_dataLock) + { + if (!_data.MonitorProfiles.TryGetValue(monitorDevicePath, out var profile)) return; + profile.Mhc2ProfileName = profileName; + _dataVersion++; + } + Save(); + NotifyMonitorProfileChanged(monitorDevicePath); + } + + /// Records which mode a profile belongs to without changing the active one. + public void SetMhc2ModeSlot(string monitorDevicePath, string profileName, bool hdr) + { + if (string.IsNullOrEmpty(monitorDevicePath) || string.IsNullOrEmpty(profileName)) return; + lock (_dataLock) + { + if (!_data.MonitorProfiles.TryGetValue(monitorDevicePath, out var profile)) return; + if (hdr) profile.Mhc2HdrProfileName = profileName; + else profile.Mhc2SdrProfileName = profileName; + _dataVersion++; + } + Save(); + } + + /// + /// Remembers the first non-Gloam Advanced Color default a Gloam install displaced. + /// Later installs see a Gloam profile there, so the first record is the one to keep. + /// + public void RecordDisplacedAdvancedColorProfile(string monitorDevicePath, string? profileName) + { + if (string.IsNullOrEmpty(monitorDevicePath) || string.IsNullOrEmpty(profileName)) return; + lock (_dataLock) + { + if (!_data.MonitorProfiles.TryGetValue(monitorDevicePath, out var profile) || + !string.IsNullOrEmpty(profile.PreviousAdvancedColorProfileName)) + return; + profile.PreviousAdvancedColorProfileName = profileName; + _dataVersion++; + } + Save(); + } + + /// Clears the displaced Advanced Color profile once it is the default again. + public void ClearDisplacedAdvancedColorProfile(string monitorDevicePath) + { + if (string.IsNullOrEmpty(monitorDevicePath)) return; + lock (_dataLock) + { + if (!_data.MonitorProfiles.TryGetValue(monitorDevicePath, out var profile) || + profile.PreviousAdvancedColorProfileName == null) + return; + profile.PreviousAdvancedColorProfileName = null; + _dataVersion++; + } + Save(); + } + + private static void ForgetSlot(MonitorProfileData profile, string? profileName) + { + if (string.IsNullOrEmpty(profileName)) return; + if (string.Equals(profile.Mhc2SdrProfileName, profileName, StringComparison.OrdinalIgnoreCase)) + profile.Mhc2SdrProfileName = null; + if (string.Equals(profile.Mhc2HdrProfileName, profileName, StringComparison.OrdinalIgnoreCase)) + profile.Mhc2HdrProfileName = null; + } + /// Clears the saved pre-Gloam Windows profile after it has been restored. public void ClearMhc2PreviousColorProfile(string monitorDevicePath) { @@ -1030,6 +1159,8 @@ public bool TryReplaceMhc2Calibration( StringComparison.OrdinalIgnoreCase)) return false; profile.Mhc2ProfileName = replacementProfileName; + if (string.Equals(profile.Mhc2HdrProfileName, expectedProfileName, StringComparison.OrdinalIgnoreCase)) + profile.Mhc2HdrProfileName = replacementProfileName; _dataVersion++; } @@ -1046,6 +1177,8 @@ public bool TryReplaceMhc2Calibration( StringComparison.OrdinalIgnoreCase)) { profile.Mhc2ProfileName = expectedProfileName; + if (string.Equals(profile.Mhc2HdrProfileName, replacementProfileName, StringComparison.OrdinalIgnoreCase)) + profile.Mhc2HdrProfileName = expectedProfileName; _dataVersion++; } } diff --git a/src/Gloam/CalibrationReportWindow.xaml.cs b/src/Gloam/CalibrationReportWindow.xaml.cs index 0681d78..44de3a3 100644 --- a/src/Gloam/CalibrationReportWindow.xaml.cs +++ b/src/Gloam/CalibrationReportWindow.xaml.cs @@ -137,6 +137,8 @@ private void RememberProbePlacement(double offsetX, double offsetY) // Everything needed to install the calibration as a native Windows MHC2 profile and // to verify it afterwards. Set by the calibration window; when present, "Apply // Profile" does the real install and "Verify" can re-measure through it. + private bool _acmWarningShown; + public sealed record ApplyContext( MonitorInfo Monitor, CalibrationTarget Target, double[] LutR, double[] LutG, double[] LutB, double WhiteLevel, @@ -1439,6 +1441,16 @@ private async Task ApplyAndVerifyAsync(bool runVerify = true) _installedHdrXyzCorrection = HdrColorMatrixLoop.IdentityCorrection(); Vm.ApplyButtonContent = "Disable Profile"; ctx.OnInstalled?.Invoke(result.ProfileName, previousDefaultProfile); + ctx.SettingsManager?.RecordDisplacedAdvancedColorProfile( + installMonitor.MonitorDevicePath, result.DisplacedAdvancedColorProfile); + + // Modal on purpose: the user can turn ACM on before dismissing, so the + // verification below measures the corrected display. + if (result.Warning != null && !_acmWarningShown) + { + _acmWarningShown = true; + ConfirmDialog.Info(this, "Turn On Auto Color Management", result.Warning); + } if (runVerify && ctx.Colorimeter != null) { diff --git a/src/Gloam/CalibrationWindow.xaml.cs b/src/Gloam/CalibrationWindow.xaml.cs index 41976c6..d335f86 100644 --- a/src/Gloam/CalibrationWindow.xaml.cs +++ b/src/Gloam/CalibrationWindow.xaml.cs @@ -433,7 +433,8 @@ private void RestoreProfileDisabledForMeasurement() _disabledProfileForMeasurement = null; if (CalibrationProfileInstaller.Reenable(_targetMonitor, profileName, _disabledProfileForMeasurementHdrMode)) { - _settingsManager?.SetMhc2Calibration(_targetMonitor.MonitorDevicePath, profileName); + _settingsManager?.SetMhc2Calibration(_targetMonitor.MonitorDevicePath, profileName, + builtForHdr: _disabledProfileForMeasurementHdrMode); Log.Info($"CalibrationWindow: Restored calibration profile disabled for measurement: {profileName}"); } else @@ -1776,7 +1777,8 @@ private void ViewReport_Click(object sender, RoutedEventArgs e) monitor.MonitorDevicePath, profileName, previousDefaultProfile, - _measuredInHdr); + _measuredInHdr, + builtForHdr: _measuredInHdr); _disabledProfileForMeasurement = null; Log.Info($"CalibrationWindow: Installed + recorded calibration profile {profileName}"); }, diff --git a/src/Gloam/Gloam.csproj b/src/Gloam/Gloam.csproj index 137fcaf..33cf767 100644 --- a/src/Gloam/Gloam.csproj +++ b/src/Gloam/Gloam.csproj @@ -20,7 +20,7 @@ - 1.9.3 + 1.10.0 $(Version).0 $(Version).0 $(Version) diff --git a/src/Gloam/ProfileManagerWindow.cs b/src/Gloam/ProfileManagerWindow.cs index 47aaef5..cb572ce 100644 --- a/src/Gloam/ProfileManagerWindow.cs +++ b/src/Gloam/ProfileManagerWindow.cs @@ -197,7 +197,7 @@ private void ActivateSelectedProfile() previous, saved?.PreviousColorProfileName); - if (CalibrationProfileInstaller.Reenable(_monitor, row.Name, _monitor.IsHdrActive)) + if (CalibrationProfileInstaller.Reenable(_monitor, row.Name, _monitor.IsHdrActive, out string? displaced)) { if (!string.IsNullOrEmpty(previous) && !string.Equals(previous, row.Name, StringComparison.OrdinalIgnoreCase)) CalibrationProfileInstaller.Disable(_monitor, previous); @@ -205,8 +205,14 @@ private void ActivateSelectedProfile() _monitor.MonitorDevicePath, row.Name, previousDefault, - _monitor.IsHdrActive); - SetStatus($"Activated: {row.Name}"); + _monitor.IsHdrActive, + builtForHdr: CalibrationProfileInstaller.ClassifyHdrFromName(row.Name) ?? _monitor.IsHdrActive); + // After SetMhc2Calibration: it creates the monitor's settings record. + _settings?.RecordDisplacedAdvancedColorProfile(_monitor.MonitorDevicePath, displaced); + SetStatus(!_monitor.IsHdrActive && + CalibrationInstallPreflight.DetectSdrAutoColorManagement(_monitor.DeviceName, hdrActive: false) == false + ? $"Activated: {row.Name}. Windows applies it only while \"Automatically manage color for apps\" is on (Settings > System > Display)." + : $"Activated: {row.Name}"); } else { @@ -230,8 +236,8 @@ private void Deactivate() { touchedActive = true; restoreMessage = RestorePreviousProfileIfAvailable(); - _settings?.SetMhc2Calibration(_monitor.MonitorDevicePath, null); } + _settings?.ForgetMhc2Profile(_monitor.MonitorDevicePath, row.Name); } if (!string.IsNullOrEmpty(restoreMessage)) SetStatus(restoreMessage); @@ -264,10 +270,8 @@ private void Delete() bool wasActive = string.Equals(row.Name, activeBefore, StringComparison.OrdinalIgnoreCase); CalibrationProfileInstaller.Uninstall(_monitor, row.Name); if (wasActive) - { restoreMessage = RestorePreviousProfileIfAvailable(); - _settings?.SetMhc2Calibration(_monitor.MonitorDevicePath, null); - } + _settings?.ForgetMhc2Profile(_monitor.MonitorDevicePath, row.Name); } if (!string.IsNullOrEmpty(restoreMessage)) SetStatus(restoreMessage); @@ -279,18 +283,38 @@ private void Delete() private string RestorePreviousProfileIfAvailable() { var profile = ActiveMonitorProfile; + string previousMessage = ""; string? previous = profile?.PreviousColorProfileName; - if (string.IsNullOrWhiteSpace(previous)) - return ""; - - bool hdrMode = profile?.PreviousColorProfileHdrMode ?? _monitor.IsHdrActive; - if (CalibrationProfileInstaller.RestoreDefaultProfile(_monitor, previous, hdrMode)) + if (!string.IsNullOrWhiteSpace(previous)) { - _settings?.ClearMhc2PreviousColorProfile(_monitor.MonitorDevicePath); - return $"Restored previous Windows color profile: {previous}"; + bool hdrMode = profile?.PreviousColorProfileHdrMode ?? _monitor.IsHdrActive; + if (CalibrationProfileInstaller.RestoreDefaultProfile(_monitor, previous, hdrMode)) + { + _settings?.ClearMhc2PreviousColorProfile(_monitor.MonitorDevicePath); + previousMessage = $"Restored previous Windows color profile: {previous}"; + } + else + { + previousMessage = $"Gloam profile disabled, but Windows refused to restore previous profile: {previous}"; + } } - return $"Gloam profile disabled, but Windows refused to restore previous profile: {previous}"; + // Last, so it wins the Advanced Color slot: it is re-recorded on every + // displacement, while the backup above is captured once and can be older. + string? displaced = profile?.PreviousAdvancedColorProfileName; + if (string.IsNullOrWhiteSpace(displaced)) + return previousMessage; + string displacedMessage; + if (CalibrationProfileInstaller.RestoreDefaultProfile(_monitor, displaced, hdrMode: true)) + { + _settings?.ClearDisplacedAdvancedColorProfile(_monitor.MonitorDevicePath); + displacedMessage = $"Restored previous advanced color profile: {displaced}"; + } + else + { + displacedMessage = $"Gloam profile disabled, but Windows refused to restore previous advanced color profile: {displaced}"; + } + return string.IsNullOrEmpty(previousMessage) ? displacedMessage : previousMessage + " " + displacedMessage; } } } diff --git a/src/Gloam/TrustCheckWindow.cs b/src/Gloam/TrustCheckWindow.cs index 89ff230..bd76499 100644 --- a/src/Gloam/TrustCheckWindow.cs +++ b/src/Gloam/TrustCheckWindow.cs @@ -118,9 +118,16 @@ private async Task RunAsync() return; } - var target = StandardTargets.GetByName(profile.CalibTargetName ?? string.Empty) + var target = CalibrationProfileInstaller.TargetFromProfileName(profile.Mhc2ProfileName) + ?? StandardTargets.GetByName(profile.CalibTargetName ?? string.Empty) ?? StandardTargets.SrgbGamma22; - bool hdrMode = profile.PreviousColorProfileHdrMode ?? monitor.IsHdrActive; + bool hdrMode = monitor.IsHdrActive; + if (target.IsHdr != hdrMode) + { + _status.Text = $"The active calibration targets {target.Name}, which does not match the display's current " + + $"{(hdrMode ? "HDR" : "SDR")} mode. Switch modes or recalibrate, then check again."; + return; + } string? argyllBin = ArgyllDownloader.IsInstalled() ? ArgyllDownloader.LocalArgyllBinDir diff --git a/src/Gloam/ViewModels/TrayViewModel.cs b/src/Gloam/ViewModels/TrayViewModel.cs index 6abf883..d2f096c 100644 --- a/src/Gloam/ViewModels/TrayViewModel.cs +++ b/src/Gloam/ViewModels/TrayViewModel.cs @@ -24,6 +24,7 @@ public class TrayViewModel : ObservableObject, IDisposable public event Action? NotificationRequested; private readonly MonitorManager _monitorManager; + private readonly AdvancedColorProfileMigrationService? _profileModeService; private readonly ProfileManager _profileManager; private readonly DispwinRunner _dispwinRunner; private readonly SettingsManager _settingsManager; @@ -76,7 +77,8 @@ public TrayViewModel( UpdateService updateService, IToastService? toastService = null, MelanopicMonitorService? melanopicService = null, - HotkeyManager? hotkeyManager = null) + HotkeyManager? hotkeyManager = null, + AdvancedColorProfileMigrationService? profileModeService = null) { // Dependencies are constructed by the DI container (App.ConfigureServices) // and must all be assigned before starting any service: NightModeService and @@ -84,6 +86,7 @@ public TrayViewModel( // and those handlers reach the apply service. The wiring/start order in // this constructor body is load-bearing; do not reorder it. _monitorManager = monitorManager; + _profileModeService = profileModeService; _settingsManager = settingsManager; _nightModeService = nightModeService; _profileManager = profileManager; @@ -602,6 +605,8 @@ private async Task HandleDisplayEventAsync(int settleDelayMs) // dedupe skip the re-apply. _applyService.InvalidateAppliedState(); RefreshMonitors(); + // Must precede ApplyAll: the apply path reads the active MHC2 profile. + _profileModeService?.ReconcileModeChanges(); // HMONITOR handles and output facts can change across HDR/display events. // Re-run foreground assignment so Gameplay Lock follows the refreshed path. _appDetectionService.Refresh(); diff --git a/tests/Gloam.Tests/AdvancedColorProfileAssociationTests.cs b/tests/Gloam.Tests/AdvancedColorProfileAssociationTests.cs index 284beed..e88497b 100644 --- a/tests/Gloam.Tests/AdvancedColorProfileAssociationTests.cs +++ b/tests/Gloam.Tests/AdvancedColorProfileAssociationTests.cs @@ -141,6 +141,17 @@ public void RemoveCurrentUser_WhenWindowsReportsAnEmptyList_StillRemoves() Assert.NotEqual("Gloam stale.icm", platform.CurrentDefault); } + [Fact] + public void RemoveCurrentUser_ProfileNeverAssociated_IsSuccess() + { + var platform = new FakeAdvancedColorPlatform { PerUserEnabled = true }; + + bool success = AdvancedColorProfileAssociation.TryRemoveCurrentUser( + Monitor(), "Gloam never associated.icm", out string? error, platform); + + Assert.True(success, error); + } + [Fact] public void VerifiedCurrentUserDefault_RejectsMatchingSystemDefault() { @@ -274,7 +285,8 @@ public int RemoveDisplayAssociation(Wcs.WCS_PROFILE_MANAGEMENT_SCOPE scope, stri if (scope == Wcs.WCS_PROFILE_MANAGEMENT_SCOPE.WCS_PROFILE_MANAGEMENT_SCOPE_SYSTEM_WIDE && string.Equals(SystemDefault, profileName, StringComparison.OrdinalIgnoreCase)) SystemDefault = null; - return removed ? 0 : unchecked((int)0x80070490); + // Windows answers ERROR_PROFILE_NOT_ASSOCIATED_WITH_DEVICE here. + return removed ? 0 : unchecked((int)0x800707DF); } public bool InstallColorProfile(string stagedPath) diff --git a/tests/Gloam.Tests/ProfileModeSwitchTests.cs b/tests/Gloam.Tests/ProfileModeSwitchTests.cs new file mode 100644 index 0000000..605f6e5 --- /dev/null +++ b/tests/Gloam.Tests/ProfileModeSwitchTests.cs @@ -0,0 +1,279 @@ +using System; +using System.IO; +using Gloam.Core; +using Gloam.Core.Calibration; +using Gloam.Interop; +using Xunit; + +namespace Gloam.Tests +{ + public sealed class ProfileModeSwitchTests + { + [Theory] + // sdrSlot, hdrSlot, active, hdr, disable, enable, verifyOnly, restorePrevious + [InlineData(null, null, null, true, null, null, false, false)] + [InlineData(null, null, "legacy.icm", false, null, null, false, false)] + [InlineData("sdr.icm", "hdr.icm", "sdr.icm", true, "sdr.icm", "hdr.icm", false, false)] + [InlineData("sdr.icm", "hdr.icm", "hdr.icm", false, "hdr.icm", "sdr.icm", false, false)] + [InlineData("sdr.icm", null, "sdr.icm", true, "sdr.icm", null, false, true)] + [InlineData(null, "hdr.icm", "hdr.icm", false, "hdr.icm", null, false, true)] + [InlineData("sdr.icm", null, null, false, null, "sdr.icm", false, false)] + [InlineData("sdr.icm", null, null, true, null, null, false, false)] + [InlineData("sdr.icm", "hdr.icm", "HDR.icm", true, null, "hdr.icm", true, false)] + public void DecideModeSwitch_PicksTheProfileBuiltForTheCurrentMode( + string? sdrSlot, string? hdrSlot, string? active, bool hdr, + string? disable, string? enable, bool verifyOnly, bool restorePrevious) + { + var plan = AdvancedColorProfileMigrationService.DecideModeSwitch(sdrSlot, hdrSlot, active, hdr); + + Assert.Equal(disable, plan.Disable); + Assert.Equal(enable, plan.Enable, StringComparer.OrdinalIgnoreCase); + Assert.Equal(verifyOnly, plan.VerifyOnly); + Assert.Equal(restorePrevious, plan.RestorePrevious); + } + + [Fact] + public void Settings_SlotsFollowInstallsAndExplicitForgets() + { + WithIsolatedSettings(settings => + { + const string path = @"MONITOR\TEST\INSTANCE"; + settings.SetMhc2Calibration(path, "sdr.icm", builtForHdr: false); + settings.SetMhc2Calibration(path, "hdr.icm", builtForHdr: true); + var p = settings.GetMonitorProfile(path)!; + Assert.Equal(("sdr.icm", "hdr.icm", "hdr.icm"), (p.Mhc2SdrProfileName, p.Mhc2HdrProfileName, p.Mhc2ProfileName)); + + // Clearing the active profile (measurement bypass) drops only its own slot. + settings.SetMhc2Calibration(path, null); + p = settings.GetMonitorProfile(path)!; + Assert.Equal(("sdr.icm", (string?)null, (string?)null), (p.Mhc2SdrProfileName, p.Mhc2HdrProfileName, p.Mhc2ProfileName)); + + settings.SetActiveMhc2Profile(path, "sdr.icm"); + settings.ForgetMhc2Profile(path, "sdr.icm"); + p = settings.GetMonitorProfile(path)!; + Assert.Null(p.Mhc2SdrProfileName); + Assert.Null(p.Mhc2ProfileName); + + settings.RecordDisplacedAdvancedColorProfile(path, "first.icc"); + settings.RecordDisplacedAdvancedColorProfile(path, "second.icc"); + Assert.Equal("first.icc", settings.GetMonitorProfile(path)!.PreviousAdvancedColorProfileName); + }); + } + + [Fact] + public void Reconcile_SwitchToHdr_SwapsInTheHdrProfile_OnlyOnTransition() + { + WithIsolatedSettings(settings => + { + var monitor = Monitor(hdr: true); + settings.SetMhc2Calibration(monitor.MonitorDevicePath, "hdr.icm", builtForHdr: true); + settings.SetMhc2Calibration(monitor.MonitorDevicePath, "sdr.icm", builtForHdr: false); + var platform = new FakeAdvancedColorPlatform { PerUserEnabled = true, CurrentDefault = "sdr.icm" }; + platform.CurrentProfiles.Add("sdr.icm"); + + WithPlatform(platform, () => + { + var service = new AdvancedColorProfileMigrationService(settings, () => new[] { monitor }); + service.ReconcileModeChanges(); + + Assert.Equal("hdr.icm", platform.CurrentDefault); + Assert.DoesNotContain("sdr.icm", platform.CurrentProfiles); + var p = settings.GetMonitorProfile(monitor.MonitorDevicePath)!; + Assert.Equal(("hdr.icm", "sdr.icm", "hdr.icm"), (p.Mhc2ProfileName, p.Mhc2SdrProfileName, p.Mhc2HdrProfileName)); + + // Same mode again: a resolution change or burst event must not touch Windows. + platform.CurrentDefault = "user choice.icm"; + service.ReconcileModeChanges(); + Assert.Equal("user choice.icm", platform.CurrentDefault); + }); + }); + } + + [Fact] + public void Reconcile_SwitchToSdrWithoutSdrProfile_RestoresDisplacedForeignProfile() + { + WithIsolatedSettings(settings => + { + var monitor = Monitor(hdr: false); + settings.SetMhc2Calibration(monitor.MonitorDevicePath, "hdr.icm", builtForHdr: true); + settings.RecordDisplacedAdvancedColorProfile(monitor.MonitorDevicePath, "HDR Calibration.icc"); + var platform = new FakeAdvancedColorPlatform { PerUserEnabled = true, CurrentDefault = "hdr.icm" }; + platform.CurrentProfiles.Add("hdr.icm"); + + WithPlatform(platform, () => + { + new AdvancedColorProfileMigrationService(settings, () => new[] { monitor }).ReconcileModeChanges(); + + Assert.Equal("HDR Calibration.icc", platform.CurrentDefault); + var p = settings.GetMonitorProfile(monitor.MonitorDevicePath)!; + Assert.Null(p.Mhc2ProfileName); + Assert.Equal("hdr.icm", p.Mhc2HdrProfileName); + // Restored, so a profile the user picks later is never overwritten with this one. + Assert.Null(p.PreviousAdvancedColorProfileName); + }); + }); + } + + [Theory] + [InlineData("Test Display - HDR Desktop PQ sRGB gamut - 2026-01-01 1200.icm", true)] + [InlineData("Test Display - HDR Desktop PQ sRGB gamut - 2026-01-01 1200 ICC-safe 1.7.8.icm", true)] + [InlineData("Test Display - Rec.2020 HLG - 2026-01-01 1200 (2).icm", true)] + [InlineData("Test Display - sRGB G2.2 - 2026-01-01 1200.icm", false)] + [InlineData("Test Display - sRGB G2.2 WPonly - 2026-01-01 1200.icm", false)] + [InlineData("Test Display - Display Native - 2026-01-01 1200.icm", null)] + [InlineData("HDR-kalibreret profil.icc", null)] + public void ClassifyHdrFromName_ReadsTheTargetSegment(string name, bool? expected) + { + Assert.Equal(expected, CalibrationProfileInstaller.ClassifyHdrFromName(name)); + } + + [Fact] + public void Reconcile_LegacyHdrRecordInSdr_IsClassifiedAndRetired() + { + WithIsolatedSettings(settings => + { + var monitor = Monitor(hdr: false); + const string legacy = "Test Display - HDR Desktop PQ sRGB gamut - 2026-01-01 1200.icm"; + settings.SetMhc2Calibration(monitor.MonitorDevicePath, legacy); + var platform = new FakeAdvancedColorPlatform { PerUserEnabled = true, CurrentDefault = legacy }; + platform.CurrentProfiles.Add(legacy); + + WithPlatform(platform, () => + { + new AdvancedColorProfileMigrationService(settings, () => new[] { monitor }).ReconcileModeChanges(); + + var p = settings.GetMonitorProfile(monitor.MonitorDevicePath)!; + Assert.Equal(legacy, p.Mhc2HdrProfileName); + Assert.Null(p.Mhc2ProfileName); + Assert.Null(platform.CurrentDefault); + }); + }); + } + + [Fact] + public void Reconcile_WhenWindowsRefusesTheRetire_KeepsActiveAndRetriesNextEvent() + { + WithIsolatedSettings(settings => + { + var monitor = Monitor(hdr: true); + settings.SetMhc2Calibration(monitor.MonitorDevicePath, "sdr.icm", builtForHdr: false); + var platform = new FakeAdvancedColorPlatform { PerUserEnabled = true, CurrentDefault = "sdr.icm", FailRemove = true }; + platform.CurrentProfiles.Add("sdr.icm"); + + WithPlatform(platform, () => + { + var service = new AdvancedColorProfileMigrationService(settings, () => new[] { monitor }); + service.ReconcileModeChanges(); + Assert.Equal("sdr.icm", settings.GetMonitorProfile(monitor.MonitorDevicePath)!.Mhc2ProfileName); + + platform.FailRemove = false; + service.ReconcileModeChanges(); // same mode, but the failed attempt must retry + Assert.Null(settings.GetMonitorProfile(monitor.MonitorDevicePath)!.Mhc2ProfileName); + Assert.Null(platform.CurrentDefault); + }); + }); + } + + [Fact] + public void Reconcile_RefusedForeignRestore_IsRetriedOnTheNextEvent() + { + WithIsolatedSettings(settings => + { + var monitor = Monitor(hdr: false); + settings.SetMhc2Calibration(monitor.MonitorDevicePath, "hdr.icm", builtForHdr: true); + settings.RecordDisplacedAdvancedColorProfile(monitor.MonitorDevicePath, "HDR Calibration.icc"); + var platform = new FakeAdvancedColorPlatform + { + PerUserEnabled = true, CurrentDefault = "hdr.icm", IgnoreDefaultWrites = true + }; + platform.CurrentProfiles.Add("hdr.icm"); + + WithPlatform(platform, () => + { + var service = new AdvancedColorProfileMigrationService(settings, () => new[] { monitor }); + service.ReconcileModeChanges(); + Assert.NotEqual("HDR Calibration.icc", platform.CurrentDefault); + + platform.IgnoreDefaultWrites = false; + service.ReconcileModeChanges(); + Assert.Equal("HDR Calibration.icc", platform.CurrentDefault); + }); + }); + } + + [Fact] + public void Settings_StaleWholeRecordSave_DoesNotRollBackCalibrationFields() + { + WithIsolatedSettings(settings => + { + const string path = @"MONITOR\TEST\INSTANCE"; + settings.SetMhc2Calibration(path, "sdr.icm", builtForHdr: false); + var staleEditorCopy = settings.GetMonitorProfile(path)!; + settings.SetMhc2Calibration(path, "hdr.icm", builtForHdr: true); + + staleEditorCopy.Brightness = 42; + settings.SetMonitorProfile(path, staleEditorCopy); + + var p = settings.GetMonitorProfile(path)!; + Assert.Equal(42, p.Brightness); + Assert.Equal("hdr.icm", p.Mhc2ProfileName); + Assert.Equal("hdr.icm", p.Mhc2HdrProfileName); + }); + } + + [Fact] + public void Settings_NewFieldsSurviveReload_AndRepairRenamesTheHdrSlot() + { + WithIsolatedSettings(settings => + { + const string path = @"MONITOR\TEST\INSTANCE"; + settings.SetMhc2Calibration(path, "sdr.icm", builtForHdr: false); + settings.SetMhc2Calibration(path, "hdr.icm", builtForHdr: true); + settings.RecordDisplacedAdvancedColorProfile(path, "foreign.icc"); + Assert.True(settings.TryReplaceMhc2Calibration(path, "hdr.icm", "hdr ICC-safe.icm")); + + var p = new SettingsManager().GetMonitorProfile(path)!; + Assert.Equal("sdr.icm", p.Mhc2SdrProfileName); + Assert.Equal("hdr ICC-safe.icm", p.Mhc2HdrProfileName); + Assert.Equal("hdr ICC-safe.icm", p.Mhc2ProfileName); + Assert.Equal("foreign.icc", p.PreviousAdvancedColorProfileName); + }); + } + + private static MonitorInfo Monitor(bool hdr) => new() + { + DeviceName = @"\\.\DISPLAY1", + MonitorDevicePath = @"MONITOR\TEST\INSTANCE", + FriendlyName = "Test Display", + IsHdrActive = hdr, + HasDisplayConfigIds = true, + DisplayConfigAdapterId = new Dxgi.LUID { LowPart = 10, HighPart = 20 }, + DisplayConfigSourceId = 30 + }; + + private static void WithPlatform(IAdvancedColorProfilePlatform platform, Action body) + { + var previous = AdvancedColorProfileAssociation.Platform; + AdvancedColorProfileAssociation.Platform = platform; + try { body(); } + finally { AdvancedColorProfileAssociation.Platform = previous; } + } + + private static void WithIsolatedSettings(Action body) + { + string originalData = AppPaths.DataDir; + string originalRoaming = AppPaths.RoamingDataDir; + string root = Path.Combine(Path.GetTempPath(), $"gloam-mode-switch-test-{Guid.NewGuid():N}"); + try + { + AppPaths.UseDataDirectoriesForCurrentProcess(Path.Combine(root, "data"), Path.Combine(root, "roaming")); + body(new SettingsManager()); + } + finally + { + AppPaths.UseDataDirectoriesForCurrentProcess(originalData, originalRoaming); + try { if (Directory.Exists(root)) Directory.Delete(root, recursive: true); } catch { } + } + } + } +}