From 153f37009c735f3879705d7d56329e382d811cf9 Mon Sep 17 00:00:00 2001 From: David Torcivia Date: Tue, 15 Sep 2026 16:42:59 -0400 Subject: [PATCH 1/9] Resolve spotread -y selector from the instrument table (fixes #7) DisplayTypeExtensions.ToSpotreadFlag mapped each DisplayType to a fixed Argyll technology letter (e, o, b, l, c, m, p). Argyll builds the -y table per instrument at run time: a driver's static base rows plus one row per installed CCSS/CCMX. The i1D3 driver's static rows are only n|l (Non-Refresh) and r|c (Refresh), and the technology letters exist only when the X-Rite EDR corrections have been imported into Argyll's data directory. On a fresh install spotread therefore exits with "Failed to locate display type matching 'o'" for OLED, and the same happens for LcdLed (e) and LcdWideGamut (b). SpotreadDisplayTypeTable.Parse reads the -y block from spotread usage text (first row prefixed with -y, continuation rows indented, the generic "l|c Other" row, one- and two-character selectors, log-prefixed lines). SpotreadDisplayTypeTable.Resolve picks, in order: a non-base row whose description names the technology, preferring Argyll's own letter for it; the base row for the type's refresh class (OLED and all LCD types are non-refresh per disptechs.c; CRT, plasma and projector are refresh); a row accepting the generic selector; the generic selector l or c when the table is unknown. ColorimeterService parses the table from the spotread -? output it already captures at detection, stores it on ColorimeterInfo.DisplayTypes, and passes it to SpotreadSession.StartAsync for the persistent and transient sessions. SetDisplayType logs the resolved selector and the reason. SpotreadSession recognises the rejection diagnostic, stops classifying the usage lines that follow it, and keeps them in a dedicated buffer. StartProcessAsync waits for the exited process's output to drain (Process.WaitForExit without a timeout is the only call that guarantees the async handlers ran) before parsing that buffer, and StartAsync restarts once with a selector resolved against the table spotread itself printed. The failure message lists the selectors the instrument accepts. Session ownership in StartProcessAsync is now a try/finally. Tests pin the reporter's clean-install i1D3 usage, a usage with imported EDR rows, and a usage with no enumerated instrument, and check the resolved selector for every DisplayType against each. Session tests cover argument construction with and without a table and the rejection capture. Release notes and version 1.9.2. --- docs/release-notes/v1.9.2.md | 9 + .../Calibration/ColorimeterService.cs | 26 +- src/Gloam.Core/Calibration/DisplayType.cs | 35 +- .../Calibration/SpotreadDisplayTypes.cs | 298 ++++++++++++++++++ src/Gloam.Core/Calibration/SpotreadSession.cs | 209 +++++++++++- src/Gloam/Gloam.csproj | 2 +- .../SpotreadDisplayTypeTableTests.cs | 242 ++++++++++++++ tests/Gloam.Tests/SpotreadSessionTests.cs | 82 +++++ 8 files changed, 863 insertions(+), 40 deletions(-) create mode 100644 docs/release-notes/v1.9.2.md create mode 100644 src/Gloam.Core/Calibration/SpotreadDisplayTypes.cs create mode 100644 tests/Gloam.Tests/SpotreadDisplayTypeTableTests.cs diff --git a/docs/release-notes/v1.9.2.md b/docs/release-notes/v1.9.2.md new file mode 100644 index 0000000..712c34c --- /dev/null +++ b/docs/release-notes/v1.9.2.md @@ -0,0 +1,9 @@ +# Gloam 1.9.2 + +Calibration no longer fails at instrument startup with "Failed to locate display type matching 'o'" (issue #7). + +- The spotread display-type selector (`-y`) is now taken from the table spotread prints for the connected instrument instead of a fixed letter per display type. ArgyllCMS only lists the technology letters (`o` OLED, `e` white LED, `b` RGB LED, `m` plasma, `p` projector) when matching X-Rite EDR corrections have been imported, which a fresh install never has. On a clean install the i1 Display Pro family accepts only `n|l` (Non-Refresh), `r|c` (Refresh) and a built-in CCFL row, so OLED, LCD LED and wide-gamut LCD all failed there. +- OLED and every LCD type now resolve to the instrument's Non-Refresh base calibration when no matching correction is installed; CRT, plasma and projector resolve to the Refresh base. When a matching EDR row exists, the same letters as before are used. When a `.ccss` meter correction is selected, it continues to supply both the spectral calibration and the refresh mode, as spotread already did. +- If spotread still rejects the selector, Gloam reads the table spotread prints on the way out and restarts once with a selector from that table. The failure message now lists the selectors the instrument accepts. + +Validation: all 1,388 tests pass and the strict Release build has zero warnings or errors. The rejection and retry path was exercised against an i1 Display Pro on Argyll 3.5.0 by forcing an invalid selector; the retry restarted with a listed selector and reached the ready prompt. The reporter's clean-install table and a table with imported EDR rows are pinned as test fixtures. diff --git a/src/Gloam.Core/Calibration/ColorimeterService.cs b/src/Gloam.Core/Calibration/ColorimeterService.cs index 0aaac50..7b0e7fd 100644 --- a/src/Gloam.Core/Calibration/ColorimeterService.cs +++ b/src/Gloam.Core/Calibration/ColorimeterService.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; @@ -248,7 +249,8 @@ public void SetDisplayIndex(int index) public void SetDisplayType(DisplayType type) { _displayType = type; - Log($"Display type set to: {type} (flag: -{type.ToSpotreadFlag()})"); + string selector = SpotreadDisplayTypeTable.Resolve(type, _connectedColorimeter?.DisplayTypes, out string reason); + Log($"Display type set to: {type} (spotread -y {selector}: {reason})"); } /// @@ -350,7 +352,7 @@ public virtual async Task BeginMeasurementSessionAsync(bool hdrMode, Cancellatio { _session = await SpotreadSession.StartAsync( _spotreadPath, instrumentIndex, _displayType, hdrMode, Log, cancellationToken, - _correctionFilePath); + _correctionFilePath, displayTypeTable: _connectedColorimeter?.DisplayTypes); _sessionHdrMode = hdrMode; RaiseStatusChanged(ColorimeterStatus.Ready, "Spotread session ready"); } @@ -542,7 +544,7 @@ private async Task TakeMeasurementAsync(bool hdrMode, CancellationToken { transient = await SpotreadSession.StartAsync( _spotreadPath, instrumentIndex, _displayType, hdrMode, Log, cancellationToken, - _correctionFilePath); + _correctionFilePath, displayTypeTable: _connectedColorimeter?.DisplayTypes); } catch (InvalidOperationException ex) when (UsbDriverHelper.IsDriverError(ex.Message)) { @@ -567,14 +569,22 @@ private async Task TakeMeasurementAsync(bool hdrMode, CancellationToken // Use help output to get the instrument list (spotread doesn't support -l) var listResult = await RunSpotreadCommandAsync(TimeSpan.FromSeconds(10), cancellationToken, "-?"); + IReadOnlyList displayTypes = Array.Empty(); if (listResult != null) { Log($"spotread -? output: {listResult}"); + // The usage text lists the -y selectors the enumerated instrument accepts. + // Argyll builds that table per instrument and per installed correction, so it + // is the only reliable source for the display-type flag (issue #7). + displayTypes = SpotreadDisplayTypeTable.Parse(listResult); + Log($"spotread -y table: {SpotreadDisplayTypeTable.Describe(displayTypes)}"); + // Parse actual connected device from list var deviceInfo = ParseDeviceListOutput(listResult); if (deviceInfo != null) { + deviceInfo.DisplayTypes = displayTypes; Log($"Detected device from -?: {deviceInfo.Model}"); return deviceInfo; } @@ -589,7 +599,8 @@ private async Task TakeMeasurementAsync(bool hdrMode, CancellationToken return new ColorimeterInfo { Model = "Colorimeter Detected", - IsHdrCapable = true // Assume capable, actual capability tested during measurement + IsHdrCapable = true, // Assume capable, actual capability tested during measurement + DisplayTypes = displayTypes }; } @@ -848,6 +859,13 @@ public class ColorimeterInfo /// public string? InstrumentDescriptor { get; init; } + /// + /// The -y display-type table spotread printed for the enumerated instrument(s) + /// at detection time. Empty when no instrument was enumerated. Settable because it is + /// attached after the descriptor parse that constructs this object. + /// + public IReadOnlyList DisplayTypes { get; set; } = Array.Empty(); + /// /// Whether this colorimeter supports HDR measurement modes. /// diff --git a/src/Gloam.Core/Calibration/DisplayType.cs b/src/Gloam.Core/Calibration/DisplayType.cs index cbd4b8b..620cf81 100644 --- a/src/Gloam.Core/Calibration/DisplayType.cs +++ b/src/Gloam.Core/Calibration/DisplayType.cs @@ -2,7 +2,8 @@ namespace Gloam.Core.Calibration { /// /// Display technology types for colorimeter measurement configuration. - /// These map to ArgyllCMS spotread -y flag values. + /// Resolved to an ArgyllCMS spotread -y selector per instrument by + /// . /// public enum DisplayType { @@ -34,30 +35,22 @@ public enum DisplayType public static class DisplayTypeExtensions { /// - /// Gets the ArgyllCMS spotread -y flag value for this display type. + /// True for technologies Argyll measures in refresh mode (CRT, plasma, DLP). OLED and + /// every LCD are non-refresh, matching Argyll's disptechs.c table. /// /// - /// CAVEAT: these letter codes are NOT a stable ArgyllCMS contract. The -y table is - /// generated per instrument and per Argyll version — spotread prints the letters - /// that are valid for the CONNECTED probe in its usage output, and the same letter - /// can mean different things for different instruments (or be absent entirely). - /// The mapping below matches Argyll V2.2+ with an i1 Display Pro/Plus class - /// colorimeter, which is the hardware this app targets. Parsing the actual -y - /// table from `spotread -?` output for the connected instrument is future work; - /// until then, an unknown letter degrades to a wrong generic correction rather - /// than a hard failure (spotread reports "unrecognised" and exits, which surfaces - /// through the session's fatal-error path). + /// The spotread -y selector for a display type is NOT a fixed letter: Argyll + /// builds the table per instrument at run time and the technology letters only exist + /// when matching corrections are installed. Use + /// with the table parsed from the + /// instrument's usage output. /// - public static string ToSpotreadFlag(this DisplayType type) => type switch + public static bool IsRefreshTechnology(this DisplayType type) => type switch { - DisplayType.LcdLed => "e", // LCD with white LED backlight - DisplayType.Oled => "o", // OLED (since Argyll V2.2.0) - DisplayType.LcdWideGamut => "b", // LCD with wide gamut LED backlight - DisplayType.LcdCcfl => "l", // LCD with CCFL backlight - DisplayType.Crt => "c", // CRT - DisplayType.Plasma => "m", // Plasma - DisplayType.Projector => "p", // DLP projector - _ => "e" // Default to LED LCD + DisplayType.Crt => true, + DisplayType.Plasma => true, + DisplayType.Projector => true, + _ => false }; /// diff --git a/src/Gloam.Core/Calibration/SpotreadDisplayTypes.cs b/src/Gloam.Core/Calibration/SpotreadDisplayTypes.cs new file mode 100644 index 0000000..639fe2b --- /dev/null +++ b/src/Gloam.Core/Calibration/SpotreadDisplayTypes.cs @@ -0,0 +1,298 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Text.RegularExpressions; + +namespace Gloam.Core.Calibration +{ + /// + /// One row of the -y table that spotread prints in its usage output for the + /// connected instrument, e.g. n|l i1D3: Non-Refresh display [Default,CB1]. + /// + public sealed class SpotreadDisplayTypeEntry + { + public SpotreadDisplayTypeEntry(IReadOnlyList selectors, string instrument, string description) + { + Selectors = selectors; + Instrument = instrument; + Description = description; + } + + /// Selector tokens accepted by -y for this row ("n", "l", "1", "_X"). + public IReadOnlyList Selectors { get; } + + /// Instrument short name printed before the colon ("i1D3"), or "Other" for the generic row. + public string Instrument { get; } + + /// Calibration description, including any trailing "[Default,CB1]" marker. + public string Description { get; } + + /// True for the instrument's default calibration ("[Default" marker). + public bool IsDefault => Description.Contains("[Default", StringComparison.OrdinalIgnoreCase); + + /// True for the instrument's generic non-refresh base calibration. + public bool IsNonRefreshBase => + IsDefault || Description.Contains("non-refresh", StringComparison.OrdinalIgnoreCase); + + /// True for the instrument's generic refresh (CRT-style) base calibration. + public bool IsRefreshBase => + !IsNonRefreshBase && Description.Contains("refresh display", StringComparison.OrdinalIgnoreCase); + + /// True for the generic "Other: l = LCD, c = CRT" row spotread prints for serial ports. + public bool IsGeneric => string.Equals(Instrument, "Other", StringComparison.OrdinalIgnoreCase); + + /// True when the row is a base or generic calibration rather than a technology-specific one. + public bool IsBaseOrGeneric => IsGeneric || IsNonRefreshBase || IsRefreshBase; + + public bool HasSelector(string selector) + { + foreach (string s in Selectors) + { + if (string.Equals(s, selector, StringComparison.Ordinal)) + return true; + } + return false; + } + + /// The selector to pass on the command line: the first single-character one, else the first. + public string PreferredSelector + { + get + { + foreach (string s in Selectors) + { + if (s.Length == 1) return s; + } + return Selectors[0]; + } + } + + public override string ToString() => $"{string.Join("|", Selectors)} {Instrument}: {Description}"; + } + + /// + /// Parses spotread's per-instrument -y table and resolves a + /// to a selector that instrument actually accepts. + /// + /// + /// The selector letters are not a stable ArgyllCMS contract. Argyll builds the table per + /// instrument at run time: a driver's static base calibrations (the i1D3 has only + /// Non-Refresh n|l and Refresh r|c) plus one row per installed CCSS/CCMX + /// file. The technology letters (e white LED, o OLED, b RGB LED, + /// m plasma, p projector) only appear when an X-Rite EDR-derived + /// correction of that technology has been imported into Argyll's data directory, which a + /// fresh Gloam install never does. Passing one of those letters to a clean install makes + /// spotread exit with "Failed to locate display type matching 'o'" (issue #7). + /// + /// When a -X file.ccss correction is also passed, spotread replaces both the + /// spectral calibration and the refresh mode with the ones implied by the CCSS + /// (i1d3_col_cal_spec_set in Argyll's i1d3.c), so -y then only has to be + /// a selector the instrument accepts. + /// + public static class SpotreadDisplayTypeTable + { + // First row of the block: " -y n|l i1D3: Non-Refresh display [Default,CB1]" + // Continuation rows: " r|c i1D3: Refresh display [CB2]" + // Generic row (serial ports): " l|c Other: l = LCD, c = CRT" + // Selector tokens are one character, or '_' plus one character for the two-character form. + private const string SelectorGroup = @"((?:_?[A-Za-z0-9])(?:\|_?[A-Za-z0-9])*)"; + private static readonly Regex FirstRowPattern = new( + @"^\s*-y\s+" + SelectorGroup + @"\s{2,}(\S.*)$", RegexOptions.Compiled); + private static readonly Regex ContinuationRowPattern = new( + @"^\s{2,}" + SelectorGroup + @"\s{2,}(\S.*)$", RegexOptions.Compiled); + + /// + /// Extracts the -y table from spotread usage text. Returns an empty list when + /// the text contains no table (no instrument was enumerated, or the output is not a + /// usage dump). Lines may carry a "stderr> " style prefix from a log. + /// + public static IReadOnlyList Parse(string? usageOutput) + { + var entries = new List(); + if (string.IsNullOrEmpty(usageOutput)) + return entries; + + bool inBlock = false; + foreach (string rawLine in usageOutput.Split('\n')) + { + string line = StripLogPrefix(rawLine.TrimEnd('\r')); + + Match m; + if (!inBlock) + { + m = FirstRowPattern.Match(line); + if (!m.Success) continue; + inBlock = true; + } + else + { + m = ContinuationRowPattern.Match(line); + if (!m.Success) + { + // The block ends at the next option (" -I illum ...") or any other line. + inBlock = false; + continue; + } + } + + string[] selectors = m.Groups[1].Value.Split('|'); + string rest = m.Groups[2].Value.Trim(); + string instrument; + string description; + int colon = rest.IndexOf(": ", StringComparison.Ordinal); + if (colon > 0) + { + instrument = rest.Substring(0, colon).Trim(); + description = rest.Substring(colon + 2).Trim(); + } + else + { + instrument = ""; + description = rest; + } + entries.Add(new SpotreadDisplayTypeEntry(selectors, instrument, description)); + } + return entries; + } + + private static string StripLogPrefix(string line) + { + // Colorimeter log lines look like "[2026-09-15 09:59:06.930] stderr> -y n|l ...". + int idx = line.IndexOf("stderr> ", StringComparison.Ordinal); + if (idx < 0) idx = line.IndexOf("stdout> ", StringComparison.Ordinal); + if (idx < 0) idx = line.IndexOf("[e] ", StringComparison.Ordinal); + if (idx < 0) idx = line.IndexOf("[o] ", StringComparison.Ordinal); + if (idx < 0) return line; + int prefixLen = line[idx] == '[' ? 4 : 8; + return line.Substring(idx + prefixLen); + } + + private readonly struct TypeRule + { + public TypeRule(DisplayType type, string[] preferredSelectors, string[] keywords) + { + PreferredSelectors = preferredSelectors; + Keywords = keywords; + Refresh = type.IsRefreshTechnology(); + } + public string[] PreferredSelectors { get; } + public string[] Keywords { get; } + public bool Refresh { get; } + } + + // Preferred selectors are the letters Argyll's disptechs.c assigns to the matching + // technology; keywords match the description of any installed correction of that + // technology. + private static TypeRule RuleFor(DisplayType type) => type switch + { + DisplayType.LcdLed => new TypeRule(type, new[] { "e" }, new[] { "white led", "wled" }), + DisplayType.Oled => new TypeRule(type, new[] { "o" }, new[] { "oled" }), + DisplayType.LcdWideGamut => new TypeRule(type, new[] { "b" }, + new[] { "rgb led", "rg phosphor", "pfs phosphor", "gb-r phosphor", "wide gamut" }), + DisplayType.LcdCcfl => new TypeRule(type, new[] { "l" }, new[] { "ccfl" }), + DisplayType.Crt => new TypeRule(type, new[] { "c" }, new[] { "crt" }), + DisplayType.Plasma => new TypeRule(type, new[] { "m" }, new[] { "plasma" }), + DisplayType.Projector => new TypeRule(type, new[] { "p" }, new[] { "projector", "dlp" }), + _ => new TypeRule(type, Array.Empty(), Array.Empty()) + }; + + /// + /// The selector to pass as -y for on an instrument + /// whose table is unknown. l (LCD) and c (CRT) are in every Argyll + /// colorimeter driver's static list, so they are the safe generic choice. + /// + public static string GenericSelector(DisplayType type) => RuleFor(type).Refresh ? "c" : "l"; + + /// + /// Picks the -y selector for from the instrument's + /// table: a technology-matched correction if one is installed, else the instrument's + /// base calibration for the refresh class, else the generic selector. + /// + public static string Resolve(DisplayType type, IReadOnlyList? table, out string reason) + { + var rule = RuleFor(type); + + if (table == null || table.Count == 0) + { + reason = "the instrument's display-type table is unknown; using the generic " + + (rule.Refresh ? "CRT" : "LCD") + " selector"; + return GenericSelector(type); + } + + // 1. Technology-specific rows (installed EDR/CCSS corrections) whose description + // names this technology. Prefer the row carrying Argyll's own letter for it. + SpotreadDisplayTypeEntry? keywordMatch = null; + foreach (var entry in table) + { + if (entry.IsBaseOrGeneric || !MatchesKeyword(entry.Description, rule.Keywords)) + continue; + keywordMatch ??= entry; + foreach (string sel in rule.PreferredSelectors) + { + if (entry.HasSelector(sel)) + { + reason = $"matched the installed correction '{entry.Description}'"; + return sel; + } + } + } + if (keywordMatch != null) + { + reason = $"matched the installed correction '{keywordMatch.Description}'"; + return keywordMatch.PreferredSelector; + } + + // 2. The instrument's base calibration for this refresh class. + foreach (var entry in table) + { + if (rule.Refresh ? entry.IsRefreshBase : entry.IsNonRefreshBase) + { + reason = $"no {type}-specific correction is installed for this instrument; " + + $"using its base calibration '{entry.Description}'"; + return entry.PreferredSelector; + } + } + + // 3. Any row that accepts the generic selector (including the "Other" row). + string generic = GenericSelector(type); + foreach (var entry in table) + { + if (entry.HasSelector(generic)) + { + reason = $"no {type}-specific correction is installed for this instrument; " + + $"using '{entry.Description}'"; + return generic; + } + } + + // 4. The table lists nothing usable at all (unexpected); the generic selector is + // still the most likely to be accepted. + reason = "the instrument's display-type table lists no base calibration; using the generic " + + (rule.Refresh ? "CRT" : "LCD") + " selector"; + return generic; + } + + private static bool MatchesKeyword(string description, string[] keywords) + { + foreach (string keyword in keywords) + { + if (description.Contains(keyword, StringComparison.OrdinalIgnoreCase)) + return true; + } + return false; + } + + /// One-line summary for logs: "n|l Non-Refresh display [Default,CB1]; r|c Refresh display [CB2]; ...". + public static string Describe(IReadOnlyList? table) + { + if (table == null || table.Count == 0) return "(none)"; + var sb = new StringBuilder(); + foreach (var entry in table) + { + if (sb.Length > 0) sb.Append("; "); + sb.Append(string.Join("|", entry.Selectors)).Append(' ').Append(entry.Description); + } + return sb.ToString(); + } + } +} diff --git a/src/Gloam.Core/Calibration/SpotreadSession.cs b/src/Gloam.Core/Calibration/SpotreadSession.cs index 410acd7..71daf0b 100644 --- a/src/Gloam.Core/Calibration/SpotreadSession.cs +++ b/src/Gloam.Core/Calibration/SpotreadSession.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; @@ -48,6 +49,12 @@ internal sealed class SpotreadSession : IAsyncDisposable @"XYZ:\s*([+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)\s+([+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)\s+([+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)", RegexOptions.Compiled | RegexOptions.IgnoreCase); + // "Diagnostic: Failed to locate display type matching 'o'" (spotread.c usage() call + // after inst_get_disptype_index fails). The selector is quoted as printed. + private static readonly Regex DisplayTypeRejectedPattern = new( + @"Failed to locate display type matching '([^']+)'", + RegexOptions.Compiled | RegexOptions.IgnoreCase); + // Spectral header emitted by spotread -s with a spectrometer, e.g. // "Spectrum from 380.000000 to 730.000000 nm in 36 steps" // Wording/precision varies across Argyll versions: the trailing noun after the count @@ -199,6 +206,14 @@ private static bool IsFatalErrorLine(string lowerLine) private volatile string? _fatalError; private volatile bool _disposed; + + // Set when spotread rejects our -y selector ("Failed to locate display type matching + // 'o'"). spotread then prints its usage, including the connected instrument's own -y + // table, and exits. Everything after the diagnostic is kept in _usageCapture so the + // table can be parsed and the session restarted with a selector the instrument lists. + private volatile bool _displayTypeRejected; + private readonly StringBuilder _usageCapture = new(); + private const int MaxUsageCaptureChars = 32_000; private volatile bool _attemptedHidOpen; private volatile bool _sharingViolationSeen; private volatile bool _poisoned; @@ -293,7 +308,8 @@ public static async Task StartAsync( Action log, CancellationToken cancellationToken, string? correctionFilePath = null, - bool spectralMode = false) + bool spectralMode = false, + IReadOnlyList? displayTypeTable = null) { // NOTE (flag hygiene): spotread's -H flag is HIGH-RESOLUTION SPECTRAL mode and // only applies to spectrometers (i1 Pro etc.) — it is NOT an "HDR mode". This @@ -306,8 +322,68 @@ public static async Task StartAsync( // OS display-mode flip. _ = hdrMode; - var args = BuildSpotreadArguments(instrumentIndex, displayType, spectralMode, correctionFilePath); + var args = BuildSpotreadArguments(instrumentIndex, displayType, spectralMode, correctionFilePath, + displayTypeTable, out string? selectorReason); + if (selectorReason != null) + log($"spotread -y selector for {displayType}: {selectorReason}"); + + try + { + return await StartProcessAsync(spotreadPath, args, spectralMode, log, cancellationToken); + } + catch (DisplayTypeRejectedException rejected) when (!spectralMode) + { + // The table spotread printed while rejecting the selector comes from the + // instrument it actually opened, so it outranks the one captured at detection + // (which may be empty, stale, or from another instrument). Resolve against it + // and retry once. + int selectorIndex = args.IndexOf("-y") + 1; + string rejectedSelector = args[selectorIndex]; + string retrySelector = SpotreadDisplayTypeTable.Resolve(displayType, rejected.Table, out string retryReason); + if (rejected.Table.Count == 0 || retrySelector == rejectedSelector) + throw new InvalidOperationException(rejected.Message, rejected); + + log($"spotread rejected -y {rejectedSelector}; retrying with -y {retrySelector} ({retryReason}). " + + $"Instrument -y table: {SpotreadDisplayTypeTable.Describe(rejected.Table)}"); + args[selectorIndex] = retrySelector; + try + { + return await StartProcessAsync(spotreadPath, args, spectralMode, log, cancellationToken); + } + catch (DisplayTypeRejectedException rejectedAgain) + { + throw new InvalidOperationException(rejectedAgain.Message, rejectedAgain); + } + } + catch (DisplayTypeRejectedException rejected) + { + throw new InvalidOperationException(rejected.Message, rejected); + } + } + /// + /// Thrown by when spotread exited because it did not + /// accept the -y selector. Carries the -y table spotread printed on + /// the way out (empty if the output was cut off). + /// + internal sealed class DisplayTypeRejectedException : InvalidOperationException + { + public DisplayTypeRejectedException(string message, IReadOnlyList table) + : base(message) + { + Table = table; + } + + public IReadOnlyList Table { get; } + } + + private static async Task StartProcessAsync( + string spotreadPath, + List args, + bool spectralMode, + Action log, + CancellationToken cancellationToken) + { var psi = new ProcessStartInfo(spotreadPath) { UseShellExecute = false, @@ -333,7 +409,10 @@ public static async Task StartAsync( KillStraySpotread(log); var process = new Process { StartInfo = psi, EnableRaisingEvents = true }; - var session = new SpotreadSession(process, log) { SpectralMode = spectralMode }; + // Owned by this method until the ready prompt arrives; the finally block tears it + // down on every failure path and the success path hands ownership to the caller. + SpotreadSession? session = new SpotreadSession(process, log) { SpectralMode = spectralMode }; + var started = session; log($"SpotreadSession starting: {spotreadPath} {string.Join(" ", args)}"); process.Start(); @@ -351,28 +430,85 @@ public static async Task StartAsync( { await session._readyTcs.Task.WaitAsync(startupCts.Token); log("SpotreadSession ready."); - return session; + var ready = session; + session = null; + return ready; } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { - await session.DisposeAsync(); throw; } catch (OperationCanceledException) { - string tail = session.SnapshotRecentLog(); - await session.DisposeAsync(); + string tail = started.SnapshotRecentLog(); throw new InvalidOperationException( "Colorimeter did not become ready within 15 seconds. " + "Another application (DisplayCAL's profile loader, i1Profiler) may be " + "holding the device, or the USB driver needs to be installed.\n\n" + "Recent spotread output:\n" + tail); } - catch + catch (Exception ex) { - await session.DisposeAsync(); + // spotread's exit is observed before its last stderr lines are delivered, so + // let the redirected streams drain before deciding why it failed. + await started.DrainOutputAfterExitAsync(); + if (started._displayTypeRejected) + { + var table = started.UsageDisplayTypeTable; + throw new DisplayTypeRejectedException(started.BuildDisplayTypeRejectedMessage(table, ex.Message), table); + } throw; } + finally + { + if (session != null) + await session.DisposeAsync(); + } + } + + /// + /// Waits (bounded) for the exited process's redirected output to reach EOF. Only + /// without a timeout guarantees that the + /// asynchronous output handlers have run for every line. + /// + private async Task DrainOutputAfterExitAsync() + { + if (_process == null) return; + try + { + if (!_process.HasExited && !_displayTypeRejected) return; + var drain = Task.Run(() => _process.WaitForExit()); + await Task.WhenAny(drain, Task.Delay(TimeSpan.FromSeconds(3))); + } + catch + { + // Best effort: the process may already be disposed or unreachable. + } + } + + /// + /// The -y table parsed from the usage text spotread printed after rejecting + /// our selector. Empty until is set. + /// + internal IReadOnlyList UsageDisplayTypeTable + { + get + { + string captured; + lock (_stateLock) captured = _usageCapture.ToString(); + return SpotreadDisplayTypeTable.Parse(captured); + } + } + + /// True once spotread reported that it does not accept the -y selector. + internal bool DisplayTypeRejected => _displayTypeRejected; + + private string BuildDisplayTypeRejectedMessage(IReadOnlyList table, string fallback) + { + string head = _fatalError ?? fallback; + return table.Count > 0 + ? $"{head} Selectors this instrument accepts: {SpotreadDisplayTypeTable.Describe(table)}" + : $"{head} spotread exited before listing the selectors this instrument accepts."; } /// @@ -398,13 +534,31 @@ public static async Task StartAsync( /// Spectral mode adds -s (print the raw emission spectrum after each reading) and -H /// (the instrument's high-resolution spectral mode, ~3.3 nm bins on an i1 Pro). /// - internal static System.Collections.Generic.List BuildSpotreadArguments( + internal static List BuildSpotreadArguments( int instrumentIndex, DisplayType displayType, bool spectralMode, - string? correctionFilePath) + string? correctionFilePath, + IReadOnlyList? displayTypeTable = null) + => BuildSpotreadArguments(instrumentIndex, displayType, spectralMode, correctionFilePath, + displayTypeTable, out _); + + /// + /// The connected instrument's -y table as parsed from spotread -?, or + /// null/empty when the instrument was not enumerated. The selector is resolved against + /// it so spotread is never handed a letter the instrument does not list. + /// + /// Why that selector was chosen (for the log); null in spectral mode. + internal static List BuildSpotreadArguments( + int instrumentIndex, + DisplayType displayType, + bool spectralMode, + string? correctionFilePath, + IReadOnlyList? displayTypeTable, + out string? displayTypeReason) { - var args = new System.Collections.Generic.List { "-v" }; + displayTypeReason = null; + var args = new List { "-v" }; if (!spectralMode) args.Add("-N"); // colorimeter-only: skip power-up dark calibration @@ -416,8 +570,10 @@ internal static System.Collections.Generic.List BuildSpotreadArguments( if (!spectralMode) { // colorimeter-only: display-type correction (a spectrometer needs none) + string selector = SpotreadDisplayTypeTable.Resolve(displayType, displayTypeTable, out string reason); + displayTypeReason = $"-y {selector} ({reason})"; args.Add("-y"); - args.Add(displayType.ToSpotreadFlag()); + args.Add(selector); } if (spectralMode) @@ -660,6 +816,27 @@ private void OnLine(string? line, bool isError) // Keep the recent-log window bounded so a very chatty spotread doesn't // let it grow without bound over a long calibration. if (_recentLog.Length > 4000) _recentLog.Remove(0, _recentLog.Length - 2000); + + // Everything spotread prints after rejecting the -y selector is its usage + // text, which carries the instrument's real -y table. Keep it whole. + if (_displayTypeRejected && _usageCapture.Length < MaxUsageCaptureChars) + _usageCapture.AppendLine(line); + } + + // 0. spotread rejected our -y selector. It prints its usage next and exits; the + // exit handler fails the session with _fatalError, and StartAsync retries with + // a selector taken from the table in that usage text. Usage lines are only + // captured, never classified as prompts or errors. + if (_displayTypeRejected) + return; + var rejected = DisplayTypeRejectedPattern.Match(line); + if (rejected.Success) + { + _fatalError = + $"spotread does not accept display type selector '{rejected.Groups[1].Value}' " + + $"for this instrument ({line.Trim()})."; + _displayTypeRejected = true; + return; } // 1. Did a measurement just complete? @@ -1031,7 +1208,11 @@ private void OnExited(object? sender, EventArgs e) // the output alone — we only know something held the device. Surface the // likely cause instead of the cryptic "exited before producing a measurement". string msg; - if (_fatalError != null) + if (_displayTypeRejected && _fatalError != null) + { + msg = BuildDisplayTypeRejectedMessage(UsageDisplayTypeTable, _fatalError); + } + else if (_fatalError != null) { msg = _fatalError; } diff --git a/src/Gloam/Gloam.csproj b/src/Gloam/Gloam.csproj index fb5d11b..573d638 100644 --- a/src/Gloam/Gloam.csproj +++ b/src/Gloam/Gloam.csproj @@ -20,7 +20,7 @@ - 1.9.1 + 1.9.2 $(Version).0 $(Version).0 $(Version) diff --git a/tests/Gloam.Tests/SpotreadDisplayTypeTableTests.cs b/tests/Gloam.Tests/SpotreadDisplayTypeTableTests.cs new file mode 100644 index 0000000..1b0b988 --- /dev/null +++ b/tests/Gloam.Tests/SpotreadDisplayTypeTableTests.cs @@ -0,0 +1,242 @@ +using System.Collections.Generic; +using Gloam.Core.Calibration; +using Xunit; + +namespace Gloam.Tests +{ + /// + /// Issue #7: spotread's -y selectors are built per instrument and per installed + /// correction. These fixtures are verbatim usage output from three real machines. + /// + public class SpotreadDisplayTypeTableTests + { + // Argyll 3.5.0 downloaded by Gloam, i1Display3, no corrections imported (the reporter). + internal const string CleanI1D3Usage = + " -rw Use reflection white point relative chromatically adjusted mode\n" + + " -y n|l i1D3: Non-Refresh display [Default,CB1]\n" + + " r|c i1D3: Refresh display [CB2]\n" + + " 1 i1D3: LCD CCFL PVA (Resolve JVC CPF)\n" + + " l|c Other: l = LCD, c = CRT\n" + + " -I illum Set simulated instrument illumination using FWA (def -i illum):\n" + + " M0, M1, M2, A, C, D50, D50M2, D65, F5, F8, F10 or file.sp]\n"; + + // Same Argyll build on a machine where the X-Rite EDR corrections were imported. + internal const string EdrRichI1D3Usage = + " -y n i1D3: Non-Refresh display [Default,CB1]\n" + + " r i1D3: Refresh display [CB2]\n" + + " c i1D3: CRT (Hitachi CM2112MET, Diamond View 1772ie)\n" + + " l i1D3: LCD CCFL IPS (CCFL AC EIZO HP with CORRECTION)\n" + + " L i1D3: LCD CCFL Wide Gamut IPS (WG CCFL NEC241 271)\n" + + " i i1D3: LCD GB-R Phosphor IPS (Dell U2413)\n" + + " h i1D3: LCD PFS Phosphor IPS (LED display backlight using potassium fluorosilicate (PFS) phosphors)\n" + + " 1 i1D3: LCD PFS Phosphor IPS (Panasonic VVX17P051J00 in Lenovo P70)\n" + + " 2 i1D3: LCD RG Phosphor (Addition of Dell Ultrasharp U2413 to the RG-Phosphor Family EDR (created originall\n" + + " b i1D3: LCD RGB LED IPS (RGBLED HP SOYO)\n" + + " e i1D3: LCD White LED IPS (WLED AC LG Samsung)\n" + + " o i1D3: LED OLED (EDR for OLED created with primaries R, G, B, White)\n" + + " 5 i1D3: LED OLED (Sony PVM_2541 & Samsung Galaxy S7 & LEN4140)\n" + + " 6 i1D3: LED WOLED (LG OLED 6-Series)\n" + + " m i1D3: Plasma (EDR for Plasma created with primaries R, G, B and White)\n" + + " p i1D3: Projector (Marantz HP Panasonic Projectors Hybrid EDR)\n" + + " U i1D3: Unknown ()\n" + + " l|c Other: l = LCD, c = CRT\n" + + " -I illum Set simulated instrument illumination using FWA (def -i illum):\n"; + + // spotread -? on the reporter's machine at app start: only a serial port was + // enumerated, so the usage carries no instrument table at all. + internal const string NoInstrumentUsage = + " -c listno Set instrument port from the following list (default 1)\n" + + " 1 = 'COM6'\n" + + " -rw Use reflection white point relative chromatically adjusted mode\n" + + " -y l|c Other: l = LCD, c = CRT\n" + + " -I illum Set simulated instrument illumination using FWA (def -i illum):\n"; + + [Fact] + public void Parse_CleanI1D3_ListsBaseRowsAndOemCcss() + { + var table = SpotreadDisplayTypeTable.Parse(CleanI1D3Usage); + + Assert.Equal(4, table.Count); + Assert.Equal(new[] { "n", "l" }, table[0].Selectors); + Assert.Equal("i1D3", table[0].Instrument); + Assert.Equal("Non-Refresh display [Default,CB1]", table[0].Description); + Assert.True(table[0].IsDefault); + Assert.True(table[0].IsNonRefreshBase); + Assert.False(table[0].IsRefreshBase); + + Assert.Equal(new[] { "r", "c" }, table[1].Selectors); + Assert.True(table[1].IsRefreshBase); + Assert.False(table[1].IsNonRefreshBase); + + Assert.Equal(new[] { "1" }, table[2].Selectors); + Assert.False(table[2].IsBaseOrGeneric); + + Assert.Equal(new[] { "l", "c" }, table[3].Selectors); + Assert.True(table[3].IsGeneric); + } + + [Fact] + public void Parse_StopsAtNextOption() + { + // The "-I illum" continuation line ("M0, M1, ...") is indented like a table row + // and must not be read as one. + var table = SpotreadDisplayTypeTable.Parse(CleanI1D3Usage); + Assert.DoesNotContain(table, e => e.Description.Contains("M0")); + } + + [Fact] + public void Parse_EdrRich_KeepsTruncatedDescriptionsAndCaseSensitiveSelectors() + { + var table = SpotreadDisplayTypeTable.Parse(EdrRichI1D3Usage); + + Assert.Equal(18, table.Count); + Assert.Contains(table, e => e.HasSelector("L") && e.Description.StartsWith("LCD CCFL Wide Gamut")); + Assert.Contains(table, e => e.HasSelector("l") && e.Description.StartsWith("LCD CCFL IPS")); + Assert.Contains(table, e => e.HasSelector("2") && e.Description.EndsWith("created originall")); + } + + [Fact] + public void Parse_NoInstrument_YieldsOnlyGenericRow() + { + var table = SpotreadDisplayTypeTable.Parse(NoInstrumentUsage); + + var row = Assert.Single(table); + Assert.True(row.IsGeneric); + Assert.Equal(new[] { "l", "c" }, row.Selectors); + } + + [Fact] + public void Parse_LogPrefixedLines_ParseLikeRawOutput() + { + string logged = + "[2026-09-15 09:59:06.930] stderr> -y n|l i1D3: Non-Refresh display [Default,CB1]\n" + + "[2026-09-15 09:59:06.931] stderr> r|c i1D3: Refresh display [CB2]\n" + + "[2026-09-15 09:59:06.931] stderr> -I illum Set simulated instrument illumination\n"; + + var table = SpotreadDisplayTypeTable.Parse(logged); + + Assert.Equal(2, table.Count); + Assert.Equal(new[] { "r", "c" }, table[1].Selectors); + } + + [Fact] + public void Parse_TwoCharacterSelector_PreferredIsSingleCharacter() + { + var table = SpotreadDisplayTypeTable.Parse( + " -y _a|b K10: Two-character selector row\n"); + + var row = Assert.Single(table); + Assert.Equal(new[] { "_a", "b" }, row.Selectors); + Assert.Equal("b", row.PreferredSelector); + } + + [Fact] + public void Parse_EmptyOrNull_ReturnsEmpty() + { + Assert.Empty(SpotreadDisplayTypeTable.Parse(null)); + Assert.Empty(SpotreadDisplayTypeTable.Parse("")); + Assert.Empty(SpotreadDisplayTypeTable.Parse("Measure spot values, Version 3.5.0\n")); + } + + [Theory] + [InlineData(DisplayType.LcdLed, "n")] + [InlineData(DisplayType.Oled, "n")] + [InlineData(DisplayType.LcdWideGamut, "n")] + [InlineData(DisplayType.LcdCcfl, "1")] + [InlineData(DisplayType.Crt, "r")] + [InlineData(DisplayType.Plasma, "r")] + [InlineData(DisplayType.Projector, "r")] + public void Resolve_CleanI1D3_UsesBaseCalibrationForTheRefreshClass(DisplayType type, string expected) + { + // No OLED/WLED/RGB-LED rows exist on a clean install, so the reporter's OLED must + // land on the Non-Refresh base (Argyll's disptechs.c marks OLED as non-refresh), + // never on "o". The one CCFL row (built-in OEM CCSS) still serves LcdCcfl. + var table = SpotreadDisplayTypeTable.Parse(CleanI1D3Usage); + + string selector = SpotreadDisplayTypeTable.Resolve(type, table, out string reason); + + Assert.Equal(expected, selector); + Assert.False(string.IsNullOrWhiteSpace(reason)); + } + + [Theory] + [InlineData(DisplayType.LcdLed, "e")] + [InlineData(DisplayType.Oled, "o")] + [InlineData(DisplayType.LcdWideGamut, "b")] + [InlineData(DisplayType.LcdCcfl, "l")] + [InlineData(DisplayType.Crt, "c")] + [InlineData(DisplayType.Plasma, "m")] + [InlineData(DisplayType.Projector, "p")] + public void Resolve_EdrRich_UsesArgyllTechnologyLetters(DisplayType type, string expected) + { + // The letters the old fixed map emitted are exactly right when the EDR rows exist. + var table = SpotreadDisplayTypeTable.Parse(EdrRichI1D3Usage); + + Assert.Equal(expected, SpotreadDisplayTypeTable.Resolve(type, table, out _)); + } + + [Fact] + public void Resolve_EdrRich_PrefersArgyllLetterOverOtherRowsOfSameTechnology() + { + // Three OLED rows exist ("o", "5", "6"); "o" is the generic X-Rite OLED EDR. + var table = SpotreadDisplayTypeTable.Parse(EdrRichI1D3Usage); + + Assert.Equal("o", SpotreadDisplayTypeTable.Resolve(DisplayType.Oled, table, out string reason)); + Assert.Contains("EDR for OLED", reason); + } + + [Fact] + public void Resolve_KeywordMatchWithoutPreferredLetter_UsesThatRow() + { + var table = SpotreadDisplayTypeTable.Parse( + " -y n|l i1D3: Non-Refresh display [Default,CB1]\n" + + " r|c i1D3: Refresh display [CB2]\n" + + " 6 i1D3: LED WOLED (LG OLED 6-Series)\n"); + + Assert.Equal("6", SpotreadDisplayTypeTable.Resolve(DisplayType.Oled, table, out _)); + } + + [Theory] + [InlineData(DisplayType.Oled, "l")] + [InlineData(DisplayType.LcdLed, "l")] + [InlineData(DisplayType.Crt, "c")] + public void Resolve_NoInstrumentTable_UsesGenericRow(DisplayType type, string expected) + { + var table = SpotreadDisplayTypeTable.Parse(NoInstrumentUsage); + + Assert.Equal(expected, SpotreadDisplayTypeTable.Resolve(type, table, out _)); + } + + [Theory] + [InlineData(DisplayType.Oled, "l")] + [InlineData(DisplayType.LcdWideGamut, "l")] + [InlineData(DisplayType.Plasma, "c")] + public void Resolve_UnknownTable_UsesGenericSelector(DisplayType type, string expected) + { + Assert.Equal(expected, SpotreadDisplayTypeTable.Resolve(type, null, out string reason)); + Assert.Contains("unknown", reason); + Assert.Equal(expected, SpotreadDisplayTypeTable.Resolve(type, new List(), out _)); + Assert.Equal(expected, SpotreadDisplayTypeTable.GenericSelector(type)); + } + + [Fact] + public void Resolve_TableWithoutBaseOrGenericRows_FallsBackToGenericSelector() + { + var table = SpotreadDisplayTypeTable.Parse( + " -y 1 i1D3: LCD CCFL PVA (Resolve JVC CPF)\n"); + + Assert.Equal("l", SpotreadDisplayTypeTable.Resolve(DisplayType.Oled, table, out _)); + } + + [Fact] + public void Describe_ListsSelectorsAndDescriptions() + { + var table = SpotreadDisplayTypeTable.Parse(CleanI1D3Usage); + + string text = SpotreadDisplayTypeTable.Describe(table); + + Assert.StartsWith("n|l Non-Refresh display [Default,CB1]; r|c Refresh display [CB2]", text); + Assert.Equal("(none)", SpotreadDisplayTypeTable.Describe(null)); + } + } +} diff --git a/tests/Gloam.Tests/SpotreadSessionTests.cs b/tests/Gloam.Tests/SpotreadSessionTests.cs index f47f5cd..626f624 100644 --- a/tests/Gloam.Tests/SpotreadSessionTests.cs +++ b/tests/Gloam.Tests/SpotreadSessionTests.cs @@ -421,6 +421,88 @@ public void BuildSpotreadArguments_SpectralMode_OmitsDarkCalSkipAndDisplayType() Assert.Contains("-H", args); // high-res spectral mode on } + [Fact] + public void BuildSpotreadArguments_Oled_CleanI1D3Table_UsesNonRefreshBase() + { + // Issue #7: "-y o" only exists when an OLED EDR is installed. On the reporter's + // clean install the i1D3 lists n|l, r|c and 1, so OLED must go out as -y n. + var table = SpotreadDisplayTypeTable.Parse(SpotreadDisplayTypeTableTests.CleanI1D3Usage); + + var args = SpotreadSession.BuildSpotreadArguments( + 1, DisplayType.Oled, spectralMode: false, correctionFilePath: null, table, out string? reason); + + Assert.Equal("n", args[args.IndexOf("-y") + 1]); + Assert.NotNull(reason); + Assert.StartsWith("-y n", reason); + } + + [Fact] + public void BuildSpotreadArguments_Oled_EdrTable_UsesOledLetter() + { + var table = SpotreadDisplayTypeTable.Parse(SpotreadDisplayTypeTableTests.EdrRichI1D3Usage); + + var args = SpotreadSession.BuildSpotreadArguments( + 1, DisplayType.Oled, spectralMode: false, correctionFilePath: null, table); + + Assert.Equal("o", args[args.IndexOf("-y") + 1]); + } + + [Fact] + public void BuildSpotreadArguments_NoTable_UsesGenericLcdSelector() + { + var args = SpotreadSession.BuildSpotreadArguments( + 1, DisplayType.Oled, spectralMode: false, correctionFilePath: null); + + Assert.Equal("l", args[args.IndexOf("-y") + 1]); + } + + [Fact] + public void BuildSpotreadArguments_SpectralMode_HasNoDisplayTypeReason() + { + var args = SpotreadSession.BuildSpotreadArguments( + 1, DisplayType.Oled, spectralMode: true, correctionFilePath: null, null, out string? reason); + + Assert.DoesNotContain("-y", args); + Assert.Null(reason); + } + + [Fact] + public void DisplayTypeRejection_CapturesUsageTableAndFailsWithoutReady() + { + // The exact stderr sequence from the issue #7 colorimeter.log. + var session = CreateFakeSession(out _, out _); + + session.SimulateOutputLine("Measure spot values, Version 3.5.0", isError: true); + session.SimulateOutputLine("Diagnostic: Failed to locate display type matching 'o'", isError: true); + session.SimulateOutputLine("usage: spotread [-options] [logfile]", isError: true); + session.SimulateOutputLine(" -c listno Set instrument port from the following list (default 1)", isError: true); + session.SimulateOutputLine(" 1 = 'hid:/33 (X-Rite i1 DisplayPro, ColorMunki Display)'", isError: true); + foreach (string line in SpotreadDisplayTypeTableTests.CleanI1D3Usage.Split('\n')) + session.SimulateOutputLine(line, isError: true); + + Assert.True(session.DisplayTypeRejected); + Assert.False(session.ReadyForTest); + Assert.Contains("'o'", session.FatalErrorForTest); + + var table = session.UsageDisplayTypeTable; + Assert.Equal(4, table.Count); + Assert.Equal("n", SpotreadDisplayTypeTable.Resolve(DisplayType.Oled, table, out _)); + } + + [Fact] + public void DisplayTypeRejection_UsageLinesAreNotClassifiedAsPromptsOrErrors() + { + var session = CreateFakeSession(out _, out _); + + session.SimulateOutputLine("Diagnostic: Failed to locate display type matching 'o'", isError: true); + // Usage text that would otherwise trip the ready or fatal classifiers. + session.SimulateOutputLine(" place instrument on the spot to take a reading", isError: true); + session.SimulateOutputLine("error: not really", isError: true); + + Assert.False(session.ReadyForTest); + Assert.Contains("display type selector 'o'", session.FatalErrorForTest); + } + [Fact] public void CalibrationPrompt_InSpectralMode_IsNotTreatedAsReady() { From 7b2614026ded767b50a5a65fb3a77a87f6c944c7 Mon Sep 17 00:00:00 2001 From: David Torcivia Date: Tue, 15 Sep 2026 17:14:52 -0400 Subject: [PATCH 2/9] Fix wide-gamut keyword, refresh stale -y tables, simplify session start Drop "wide gamut" from the LcdWideGamut keywords: it matched the CCFL wide-gamut EDR row (L) ahead of the LED phosphor rows when no RGB LED row (b) was installed. A default row that names a technology ("LCD, CCFL Backlight [Default,CB1]" on non-i1D3 drivers) is now a correction, not a base row. ColorimeterService re-runs the spotread -? probe before opening a session when the cached table has no instrument rows (meter plugged in after detection), and adopts the table a session actually resolved against, so a rejection retry happens once per app run rather than once per session. SpotreadSession.StartProcessAsync: the rejection check now covers the 15 s timeout path, the drain uses WaitForExitAsync with a 3 s token, the enriched message is built once after the drain, DisplayTypeRejectedException propagates as the InvalidOperationException it already is, and the retry rebuilds the argument list instead of patching it by index. Release notes state the CCFL LCD selector change on clean installs. --- docs/release-notes/v1.9.2.md | 2 +- .../Calibration/ColorimeterService.cs | 40 ++++++ .../Calibration/SpotreadDisplayTypes.cs | 38 +++++- src/Gloam.Core/Calibration/SpotreadSession.cs | 126 +++++++++--------- .../SpotreadDisplayTypeTableTests.cs | 38 ++++++ 5 files changed, 175 insertions(+), 69 deletions(-) diff --git a/docs/release-notes/v1.9.2.md b/docs/release-notes/v1.9.2.md index 712c34c..fca7b71 100644 --- a/docs/release-notes/v1.9.2.md +++ b/docs/release-notes/v1.9.2.md @@ -3,7 +3,7 @@ Calibration no longer fails at instrument startup with "Failed to locate display type matching 'o'" (issue #7). - The spotread display-type selector (`-y`) is now taken from the table spotread prints for the connected instrument instead of a fixed letter per display type. ArgyllCMS only lists the technology letters (`o` OLED, `e` white LED, `b` RGB LED, `m` plasma, `p` projector) when matching X-Rite EDR corrections have been imported, which a fresh install never has. On a clean install the i1 Display Pro family accepts only `n|l` (Non-Refresh), `r|c` (Refresh) and a built-in CCFL row, so OLED, LCD LED and wide-gamut LCD all failed there. -- OLED and every LCD type now resolve to the instrument's Non-Refresh base calibration when no matching correction is installed; CRT, plasma and projector resolve to the Refresh base. When a matching EDR row exists, the same letters as before are used. When a `.ccss` meter correction is selected, it continues to supply both the spectral calibration and the refresh mode, as spotread already did. +- OLED, LCD LED and wide-gamut LCD now resolve to the instrument's Non-Refresh base calibration when no matching correction is installed; CRT, plasma and projector resolve to the Refresh base. When a matching EDR row exists, the same letters as before are used. One measured-output change: on a clean i1D3, CCFL LCD now uses the built-in "LCD CCFL PVA" spectral row (`-y 1`) instead of the Non-Refresh base it reached through `-y l` before, because it is the only CCFL row listed. If you calibrated a CCFL display with 1.9.1, re-run the calibration. When a `.ccss` meter correction is selected, it continues to supply both the spectral calibration and the refresh mode, as spotread already did. - If spotread still rejects the selector, Gloam reads the table spotread prints on the way out and restarts once with a selector from that table. The failure message now lists the selectors the instrument accepts. Validation: all 1,388 tests pass and the strict Release build has zero warnings or errors. The rejection and retry path was exercised against an i1 Display Pro on Argyll 3.5.0 by forcing an invalid selector; the retry restarted with a listed selector and reached the ready prompt. The reporter's clean-install table and a table with imported EDR rows are pinned as test fixtures. diff --git a/src/Gloam.Core/Calibration/ColorimeterService.cs b/src/Gloam.Core/Calibration/ColorimeterService.cs index 7b0e7fd..24aa621 100644 --- a/src/Gloam.Core/Calibration/ColorimeterService.cs +++ b/src/Gloam.Core/Calibration/ColorimeterService.cs @@ -350,9 +350,11 @@ public virtual async Task BeginMeasurementSessionAsync(bool hdrMode, Cancellatio Log($"Opening persistent spotread session (instrument {instrumentIndex}, HDR={hdrMode})"); try { + await RefreshDisplayTypeTableIfUnknownAsync(cancellationToken); _session = await SpotreadSession.StartAsync( _spotreadPath, instrumentIndex, _displayType, hdrMode, Log, cancellationToken, _correctionFilePath, displayTypeTable: _connectedColorimeter?.DisplayTypes); + AdoptDisplayTypeTable(_session.EffectiveDisplayTypeTable); _sessionHdrMode = hdrMode; RaiseStatusChanged(ColorimeterStatus.Ready, "Spotread session ready"); } @@ -369,6 +371,42 @@ public virtual async Task BeginMeasurementSessionAsync(bool hdrMode, Cancellatio } } + /// + /// Keeps the table a session actually resolved against (after a rejection retry it is + /// the one spotread printed for the opened instrument) so later sessions start right. + /// + private void AdoptDisplayTypeTable(IReadOnlyList table) + { + if (_connectedColorimeter == null || !SpotreadDisplayTypeTable.HasInstrumentRows(table)) + return; + if (ReferenceEquals(_connectedColorimeter.DisplayTypes, table)) + return; + _connectedColorimeter.DisplayTypes = table; + Log($"spotread -y table updated from session: {SpotreadDisplayTypeTable.Describe(table)}"); + } + + /// + /// Detection only sees the -y table when the instrument is enumerated at that moment + /// (the meter may be plugged in after the app starts). If the cached table has no + /// instrument rows, re-run the usage probe once before opening a session. + /// + private async Task RefreshDisplayTypeTableIfUnknownAsync(CancellationToken cancellationToken) + { + if (_connectedColorimeter == null || SpotreadDisplayTypeTable.HasInstrumentRows(_connectedColorimeter.DisplayTypes)) + return; + var usage = await RunSpotreadCommandAsync(TimeSpan.FromSeconds(10), cancellationToken, "-?"); + var table = SpotreadDisplayTypeTable.Parse(usage); + if (SpotreadDisplayTypeTable.HasInstrumentRows(table)) + { + _connectedColorimeter.DisplayTypes = table; + Log($"spotread -y table refreshed before session: {SpotreadDisplayTypeTable.Describe(table)}"); + } + else + { + Log("spotread -y table still unknown (no instrument enumerated by -?); using the generic selector"); + } + } + /// /// Closes the persistent spotread session. Safe to call if no session is active. /// @@ -542,9 +580,11 @@ private async Task TakeMeasurementAsync(bool hdrMode, CancellationToken SpotreadSession transient; try { + await RefreshDisplayTypeTableIfUnknownAsync(cancellationToken); transient = await SpotreadSession.StartAsync( _spotreadPath, instrumentIndex, _displayType, hdrMode, Log, cancellationToken, _correctionFilePath, displayTypeTable: _connectedColorimeter?.DisplayTypes); + AdoptDisplayTypeTable(transient.EffectiveDisplayTypeTable); } catch (InvalidOperationException ex) when (UsbDriverHelper.IsDriverError(ex.Message)) { diff --git a/src/Gloam.Core/Calibration/SpotreadDisplayTypes.cs b/src/Gloam.Core/Calibration/SpotreadDisplayTypes.cs index 639fe2b..e662f34 100644 --- a/src/Gloam.Core/Calibration/SpotreadDisplayTypes.cs +++ b/src/Gloam.Core/Calibration/SpotreadDisplayTypes.cs @@ -30,13 +30,33 @@ public SpotreadDisplayTypeEntry(IReadOnlyList selectors, string instrume /// True for the instrument's default calibration ("[Default" marker). public bool IsDefault => Description.Contains("[Default", StringComparison.OrdinalIgnoreCase); + // Words that mark a row as technology-specific. A default row that names a technology + // (some drivers' "LCD, CCFL Backlight [Default,CB1]") is a correction, not a base. + private static readonly string[] TechnologyWords = + { "lcd", "led", "oled", "ccfl", "crt", "plasma", "projector", "dlp", "phosphor" }; + + private bool NamesTechnology + { + get + { + foreach (string word in TechnologyWords) + { + if (Description.Contains(word, StringComparison.OrdinalIgnoreCase)) + return true; + } + return false; + } + } + /// True for the instrument's generic non-refresh base calibration. public bool IsNonRefreshBase => - IsDefault || Description.Contains("non-refresh", StringComparison.OrdinalIgnoreCase); + Description.Contains("non-refresh", StringComparison.OrdinalIgnoreCase) || + (IsDefault && !NamesTechnology && !IsRefreshBase); /// True for the instrument's generic refresh (CRT-style) base calibration. public bool IsRefreshBase => - !IsNonRefreshBase && Description.Contains("refresh display", StringComparison.OrdinalIgnoreCase); + !Description.Contains("non-refresh", StringComparison.OrdinalIgnoreCase) && + Description.Contains("refresh display", StringComparison.OrdinalIgnoreCase); /// True for the generic "Other: l = LCD, c = CRT" row spotread prints for serial ports. public bool IsGeneric => string.Equals(Instrument, "Other", StringComparison.OrdinalIgnoreCase); @@ -187,8 +207,9 @@ public TypeRule(DisplayType type, string[] preferredSelectors, string[] keywords { DisplayType.LcdLed => new TypeRule(type, new[] { "e" }, new[] { "white led", "wled" }), DisplayType.Oled => new TypeRule(type, new[] { "o" }, new[] { "oled" }), + // No "wide gamut" keyword: it would match the CCFL wide-gamut EDR row. DisplayType.LcdWideGamut => new TypeRule(type, new[] { "b" }, - new[] { "rgb led", "rg phosphor", "pfs phosphor", "gb-r phosphor", "wide gamut" }), + new[] { "rgb led", "rg phosphor", "pfs phosphor", "gb-r phosphor" }), DisplayType.LcdCcfl => new TypeRule(type, new[] { "l" }, new[] { "ccfl" }), DisplayType.Crt => new TypeRule(type, new[] { "c" }, new[] { "crt" }), DisplayType.Plasma => new TypeRule(type, new[] { "m" }, new[] { "plasma" }), @@ -282,6 +303,17 @@ private static bool MatchesKeyword(string description, string[] keywords) return false; } + /// True when the table has at least one row printed by an instrument (not just the generic row). + public static bool HasInstrumentRows(IReadOnlyList? table) + { + if (table == null) return false; + foreach (var entry in table) + { + if (!entry.IsGeneric) return true; + } + return false; + } + /// One-line summary for logs: "n|l Non-Refresh display [Default,CB1]; r|c Refresh display [CB2]; ...". public static string Describe(IReadOnlyList? table) { diff --git a/src/Gloam.Core/Calibration/SpotreadSession.cs b/src/Gloam.Core/Calibration/SpotreadSession.cs index 71daf0b..8986d98 100644 --- a/src/Gloam.Core/Calibration/SpotreadSession.cs +++ b/src/Gloam.Core/Calibration/SpotreadSession.cs @@ -3,6 +3,7 @@ using System.Diagnostics; using System.Globalization; using System.IO; +using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; @@ -329,42 +330,29 @@ public static async Task StartAsync( try { - return await StartProcessAsync(spotreadPath, args, spectralMode, log, cancellationToken); + return await StartProcessAsync(spotreadPath, args, spectralMode, displayTypeTable, log, cancellationToken); } - catch (DisplayTypeRejectedException rejected) when (!spectralMode) + catch (DisplayTypeRejectedException rejected) { // The table spotread printed while rejecting the selector comes from the // instrument it actually opened, so it outranks the one captured at detection - // (which may be empty, stale, or from another instrument). Resolve against it - // and retry once. - int selectorIndex = args.IndexOf("-y") + 1; - string rejectedSelector = args[selectorIndex]; - string retrySelector = SpotreadDisplayTypeTable.Resolve(displayType, rejected.Table, out string retryReason); - if (rejected.Table.Count == 0 || retrySelector == rejectedSelector) - throw new InvalidOperationException(rejected.Message, rejected); - - log($"spotread rejected -y {rejectedSelector}; retrying with -y {retrySelector} ({retryReason}). " + + // (which may be empty, stale, or from another instrument). Retry once with it. + var retryArgs = BuildSpotreadArguments(instrumentIndex, displayType, spectralMode, correctionFilePath, + rejected.Table, out string? retryReason); + if (rejected.Table.Count == 0 || retryArgs.SequenceEqual(args)) + throw; + + log($"spotread rejected the -y selector; retrying with {retryReason}. " + $"Instrument -y table: {SpotreadDisplayTypeTable.Describe(rejected.Table)}"); - args[selectorIndex] = retrySelector; - try - { - return await StartProcessAsync(spotreadPath, args, spectralMode, log, cancellationToken); - } - catch (DisplayTypeRejectedException rejectedAgain) - { - throw new InvalidOperationException(rejectedAgain.Message, rejectedAgain); - } - } - catch (DisplayTypeRejectedException rejected) - { - throw new InvalidOperationException(rejected.Message, rejected); + return await StartProcessAsync(spotreadPath, retryArgs, spectralMode, rejected.Table, log, cancellationToken); } } /// /// Thrown by when spotread exited because it did not /// accept the -y selector. Carries the -y table spotread printed on - /// the way out (empty if the output was cut off). + /// the way out (empty if the output was cut off). Derives from + /// so existing callers need no new handling. /// internal sealed class DisplayTypeRejectedException : InvalidOperationException { @@ -377,10 +365,18 @@ public DisplayTypeRejectedException(string message, IReadOnlyList Table { get; } } + /// + /// The -y table the session's selector was resolved against. After a retry this + /// is the table spotread itself printed, which callers should keep for later sessions. + /// + public IReadOnlyList EffectiveDisplayTypeTable { get; private set; } + = Array.Empty(); + private static async Task StartProcessAsync( string spotreadPath, List args, bool spectralMode, + IReadOnlyList? displayTypeTable, Action log, CancellationToken cancellationToken) { @@ -409,10 +405,14 @@ private static async Task StartProcessAsync( KillStraySpotread(log); var process = new Process { StartInfo = psi, EnableRaisingEvents = true }; - // Owned by this method until the ready prompt arrives; the finally block tears it - // down on every failure path and the success path hands ownership to the caller. - SpotreadSession? session = new SpotreadSession(process, log) { SpectralMode = spectralMode }; - var started = session; + var session = new SpotreadSession(process, log) + { + SpectralMode = spectralMode, + EffectiveDisplayTypeTable = displayTypeTable ?? Array.Empty() + }; + // Disposed by the finally block unless the ready prompt arrives, which hands the + // session to the caller. + SpotreadSession? owned = session; log($"SpotreadSession starting: {spotreadPath} {string.Join(" ", args)}"); process.Start(); @@ -430,59 +430,59 @@ private static async Task StartProcessAsync( { await session._readyTcs.Task.WaitAsync(startupCts.Token); log("SpotreadSession ready."); - var ready = session; - session = null; - return ready; + owned = null; + return session; } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; } - catch (OperationCanceledException) - { - string tail = started.SnapshotRecentLog(); - throw new InvalidOperationException( - "Colorimeter did not become ready within 15 seconds. " + - "Another application (DisplayCAL's profile loader, i1Profiler) may be " + - "holding the device, or the USB driver needs to be installed.\n\n" + - "Recent spotread output:\n" + tail); - } catch (Exception ex) { - // spotread's exit is observed before its last stderr lines are delivered, so - // let the redirected streams drain before deciding why it failed. - await started.DrainOutputAfterExitAsync(); - if (started._displayTypeRejected) + // spotread prints its usage after rejecting the -y selector and only then + // exits, and its exit is observed before those last lines are delivered. + if (session._displayTypeRejected) + { + await session.DrainOutputAsync(); + var table = session.UsageDisplayTypeTable; + throw new DisplayTypeRejectedException(session.BuildDisplayTypeRejectedMessage(table), table); + } + if (ex is OperationCanceledException) { - var table = started.UsageDisplayTypeTable; - throw new DisplayTypeRejectedException(started.BuildDisplayTypeRejectedMessage(table, ex.Message), table); + throw new InvalidOperationException( + "Colorimeter did not become ready within 15 seconds. " + + "Another application (DisplayCAL's profile loader, i1Profiler) may be " + + "holding the device, or the USB driver needs to be installed.\n\n" + + "Recent spotread output:\n" + session.SnapshotRecentLog()); } throw; } finally { - if (session != null) - await session.DisposeAsync(); + if (owned != null) + await owned.DisposeAsync(); } } /// - /// Waits (bounded) for the exited process's redirected output to reach EOF. Only - /// without a timeout guarantees that the - /// asynchronous output handlers have run for every line. + /// Waits (bounded) for the process to exit and its redirected output to reach EOF, so + /// every usage line has passed through . /// - private async Task DrainOutputAfterExitAsync() + private async Task DrainOutputAsync() { if (_process == null) return; try { - if (!_process.HasExited && !_displayTypeRejected) return; - var drain = Task.Run(() => _process.WaitForExit()); - await Task.WhenAny(drain, Task.Delay(TimeSpan.FromSeconds(3))); + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3)); + await _process.WaitForExitAsync(cts.Token); + } + catch (OperationCanceledException) + { + // Still running or still writing after 3 s; parse whatever was captured. } - catch + catch (InvalidOperationException) { - // Best effort: the process may already be disposed or unreachable. + // Process already released. } } @@ -503,9 +503,9 @@ internal IReadOnlyList UsageDisplayTypeTable /// True once spotread reported that it does not accept the -y selector. internal bool DisplayTypeRejected => _displayTypeRejected; - private string BuildDisplayTypeRejectedMessage(IReadOnlyList table, string fallback) + private string BuildDisplayTypeRejectedMessage(IReadOnlyList table) { - string head = _fatalError ?? fallback; + string head = _fatalError ?? "spotread rejected the display type selector."; return table.Count > 0 ? $"{head} Selectors this instrument accepts: {SpotreadDisplayTypeTable.Describe(table)}" : $"{head} spotread exited before listing the selectors this instrument accepts."; @@ -1208,11 +1208,7 @@ private void OnExited(object? sender, EventArgs e) // the output alone — we only know something held the device. Surface the // likely cause instead of the cryptic "exited before producing a measurement". string msg; - if (_displayTypeRejected && _fatalError != null) - { - msg = BuildDisplayTypeRejectedMessage(UsageDisplayTypeTable, _fatalError); - } - else if (_fatalError != null) + if (_fatalError != null) { msg = _fatalError; } diff --git a/tests/Gloam.Tests/SpotreadDisplayTypeTableTests.cs b/tests/Gloam.Tests/SpotreadDisplayTypeTableTests.cs index 1b0b988..aaa6025 100644 --- a/tests/Gloam.Tests/SpotreadDisplayTypeTableTests.cs +++ b/tests/Gloam.Tests/SpotreadDisplayTypeTableTests.cs @@ -185,6 +185,44 @@ public void Resolve_EdrRich_PrefersArgyllLetterOverOtherRowsOfSameTechnology() Assert.Contains("EDR for OLED", reason); } + [Fact] + public void Resolve_WideGamut_WithoutRgbLedRow_NeverPicksCcflWideGamutRow() + { + // "L LCD CCFL Wide Gamut IPS" is a CCFL correction; an LED wide-gamut panel must + // land on one of the LED phosphor rows instead. + string usage = EdrRichI1D3Usage.Replace( + " b i1D3: LCD RGB LED IPS (RGBLED HP SOYO)\n", ""); + var table = SpotreadDisplayTypeTable.Parse(usage); + + string selector = SpotreadDisplayTypeTable.Resolve(DisplayType.LcdWideGamut, table, out string reason); + + Assert.Equal("i", selector); + Assert.DoesNotContain("CCFL", reason); + } + + [Fact] + public void Resolve_DefaultRowNamingATechnology_IsACorrectionNotABase() + { + // Drivers other than the i1D3 mark a technology row as the default. + var table = SpotreadDisplayTypeTable.Parse( + " -y l X: LCD, CCFL Backlight [Default,CB1]\n" + + " 2 X: Wide Gamut LCD, CCFL Backlight\n" + + " c X: CRT [CB2]\n"); + + Assert.False(table[0].IsNonRefreshBase); + Assert.Equal("l", SpotreadDisplayTypeTable.Resolve(DisplayType.LcdCcfl, table, out _)); + Assert.Equal("l", SpotreadDisplayTypeTable.Resolve(DisplayType.Oled, table, out _)); + Assert.Equal("c", SpotreadDisplayTypeTable.Resolve(DisplayType.Crt, table, out _)); + } + + [Fact] + public void HasInstrumentRows_FalseForGenericOnlyOrEmpty() + { + Assert.False(SpotreadDisplayTypeTable.HasInstrumentRows(null)); + Assert.False(SpotreadDisplayTypeTable.HasInstrumentRows(SpotreadDisplayTypeTable.Parse(NoInstrumentUsage))); + Assert.True(SpotreadDisplayTypeTable.HasInstrumentRows(SpotreadDisplayTypeTable.Parse(CleanI1D3Usage))); + } + [Fact] public void Resolve_KeywordMatchWithoutPreferredLetter_UsesThatRow() { From ab17f1b1fd401e56d5cb164a6247d4a1e9cd657d Mon Sep 17 00:00:00 2001 From: David Torcivia Date: Tue, 15 Sep 2026 17:25:17 -0400 Subject: [PATCH 3/9] Scope the -y table per instrument and show the resolved row in setup SpotreadDisplayTypeTable.ForInstrument keeps only the rows whose instrument short name (Argyll inst_sname) matches the port descriptor of the opened meter (inst_name), plus the generic row, so a second connected meter's rows are not selected. ShortNameForDescriptor carries the name pairs from insttypes.c. ColorimeterService applies it at detection, on refresh, and SpotreadSession applies it to the table parsed from a rejection. Resolve now returns a SpotreadDisplayTypeChoice with the matched row. CalibrationSetupViewModel shows it under the correction picker (MeterCalibrationText) and passes meterUsesGenericCalibration to BuildPreflightMessages, which warns when no correction row exists for the type and no correction file is chosen. --- docs/release-notes/v1.9.2.md | 2 + .../Calibration/ColorimeterService.cs | 24 ++- .../Calibration/SpotreadDisplayTypes.cs | 140 +++++++++++++++--- src/Gloam.Core/Calibration/SpotreadSession.cs | 12 +- src/Gloam/CalibrationSetupWindow.xaml | 3 + .../ViewModels/CalibrationSetupViewModel.cs | 77 +++++++++- .../CalibrationSetupPreflightTests.cs | 17 +++ .../SpotreadDisplayTypeTableTests.cs | 65 ++++++++ 8 files changed, 305 insertions(+), 35 deletions(-) diff --git a/docs/release-notes/v1.9.2.md b/docs/release-notes/v1.9.2.md index fca7b71..4910e09 100644 --- a/docs/release-notes/v1.9.2.md +++ b/docs/release-notes/v1.9.2.md @@ -5,5 +5,7 @@ Calibration no longer fails at instrument startup with "Failed to locate display - The spotread display-type selector (`-y`) is now taken from the table spotread prints for the connected instrument instead of a fixed letter per display type. ArgyllCMS only lists the technology letters (`o` OLED, `e` white LED, `b` RGB LED, `m` plasma, `p` projector) when matching X-Rite EDR corrections have been imported, which a fresh install never has. On a clean install the i1 Display Pro family accepts only `n|l` (Non-Refresh), `r|c` (Refresh) and a built-in CCFL row, so OLED, LCD LED and wide-gamut LCD all failed there. - OLED, LCD LED and wide-gamut LCD now resolve to the instrument's Non-Refresh base calibration when no matching correction is installed; CRT, plasma and projector resolve to the Refresh base. When a matching EDR row exists, the same letters as before are used. One measured-output change: on a clean i1D3, CCFL LCD now uses the built-in "LCD CCFL PVA" spectral row (`-y 1`) instead of the Non-Refresh base it reached through `-y l` before, because it is the only CCFL row listed. If you calibrated a CCFL display with 1.9.1, re-run the calibration. When a `.ccss` meter correction is selected, it continues to supply both the spectral calibration and the refresh mode, as spotread already did. - If spotread still rejects the selector, Gloam reads the table spotread prints on the way out and restarts once with a selector from that table. The failure message now lists the selectors the instrument accepts. +- With two meters connected, only the rows spotread printed for the meter Gloam opened are considered. +- The calibration setup screen now shows which calibration row the meter will use for the selected display type, and warns when the meter has no correction for that type and no CCSS/CCMX file is chosen. Validation: all 1,388 tests pass and the strict Release build has zero warnings or errors. The rejection and retry path was exercised against an i1 Display Pro on Argyll 3.5.0 by forcing an invalid selector; the retry restarted with a listed selector and reached the ready prompt. The reporter's clean-install table and a table with imported EDR rows are pinned as test fixtures. diff --git a/src/Gloam.Core/Calibration/ColorimeterService.cs b/src/Gloam.Core/Calibration/ColorimeterService.cs index 24aa621..e12c373 100644 --- a/src/Gloam.Core/Calibration/ColorimeterService.cs +++ b/src/Gloam.Core/Calibration/ColorimeterService.cs @@ -249,10 +249,19 @@ public void SetDisplayIndex(int index) public void SetDisplayType(DisplayType type) { _displayType = type; - string selector = SpotreadDisplayTypeTable.Resolve(type, _connectedColorimeter?.DisplayTypes, out string reason); - Log($"Display type set to: {type} (spotread -y {selector}: {reason})"); + var choice = ResolveDisplayTypeChoice(type); + Log($"Display type set to: {type} (spotread -y {choice.Selector}: {choice.Reason})"); } + /// + /// How the connected instrument will measure : the selector + /// spotread gets and the table row it comes from. Uses the table captured at + /// detection (or adopted from a session), so it is exact for colorimeters with an + /// enumerated table and a best guess otherwise. + /// + public SpotreadDisplayTypeChoice ResolveDisplayTypeChoice(DisplayType type) + => SpotreadDisplayTypeTable.Resolve(type, _connectedColorimeter?.DisplayTypes); + /// /// Gets the current display type setting. /// @@ -353,7 +362,8 @@ public virtual async Task BeginMeasurementSessionAsync(bool hdrMode, Cancellatio await RefreshDisplayTypeTableIfUnknownAsync(cancellationToken); _session = await SpotreadSession.StartAsync( _spotreadPath, instrumentIndex, _displayType, hdrMode, Log, cancellationToken, - _correctionFilePath, displayTypeTable: _connectedColorimeter?.DisplayTypes); + _correctionFilePath, displayTypeTable: _connectedColorimeter?.DisplayTypes, + instrumentDescriptor: _connectedColorimeter?.InstrumentDescriptor); AdoptDisplayTypeTable(_session.EffectiveDisplayTypeTable); _sessionHdrMode = hdrMode; RaiseStatusChanged(ColorimeterStatus.Ready, "Spotread session ready"); @@ -395,7 +405,8 @@ private async Task RefreshDisplayTypeTableIfUnknownAsync(CancellationToken cance if (_connectedColorimeter == null || SpotreadDisplayTypeTable.HasInstrumentRows(_connectedColorimeter.DisplayTypes)) return; var usage = await RunSpotreadCommandAsync(TimeSpan.FromSeconds(10), cancellationToken, "-?"); - var table = SpotreadDisplayTypeTable.Parse(usage); + var table = SpotreadDisplayTypeTable.ForInstrument( + SpotreadDisplayTypeTable.Parse(usage), _connectedColorimeter.InstrumentDescriptor); if (SpotreadDisplayTypeTable.HasInstrumentRows(table)) { _connectedColorimeter.DisplayTypes = table; @@ -583,7 +594,8 @@ private async Task TakeMeasurementAsync(bool hdrMode, CancellationToken await RefreshDisplayTypeTableIfUnknownAsync(cancellationToken); transient = await SpotreadSession.StartAsync( _spotreadPath, instrumentIndex, _displayType, hdrMode, Log, cancellationToken, - _correctionFilePath, displayTypeTable: _connectedColorimeter?.DisplayTypes); + _correctionFilePath, displayTypeTable: _connectedColorimeter?.DisplayTypes, + instrumentDescriptor: _connectedColorimeter?.InstrumentDescriptor); AdoptDisplayTypeTable(transient.EffectiveDisplayTypeTable); } catch (InvalidOperationException ex) when (UsbDriverHelper.IsDriverError(ex.Message)) @@ -624,7 +636,7 @@ private async Task TakeMeasurementAsync(bool hdrMode, CancellationToken var deviceInfo = ParseDeviceListOutput(listResult); if (deviceInfo != null) { - deviceInfo.DisplayTypes = displayTypes; + deviceInfo.DisplayTypes = SpotreadDisplayTypeTable.ForInstrument(displayTypes, deviceInfo.InstrumentDescriptor); Log($"Detected device from -?: {deviceInfo.Model}"); return deviceInfo; } diff --git a/src/Gloam.Core/Calibration/SpotreadDisplayTypes.cs b/src/Gloam.Core/Calibration/SpotreadDisplayTypes.cs index e662f34..c5be748 100644 --- a/src/Gloam.Core/Calibration/SpotreadDisplayTypes.cs +++ b/src/Gloam.Core/Calibration/SpotreadDisplayTypes.cs @@ -90,6 +90,31 @@ public string PreferredSelector public override string ToString() => $"{string.Join("|", Selectors)} {Instrument}: {Description}"; } + /// + /// The outcome of resolving a against an instrument's table. + /// + public sealed class SpotreadDisplayTypeChoice + { + public SpotreadDisplayTypeChoice(string selector, string reason, SpotreadDisplayTypeEntry? entry) + { + Selector = selector; + Reason = reason; + Entry = entry; + } + + /// The value passed to spotread's -y. + public string Selector { get; } + + /// Why it was chosen, for logs and the setup screen. + public string Reason { get; } + + /// The table row the selector came from; null when the table was unknown. + public SpotreadDisplayTypeEntry? Entry { get; } + + /// True when a technology-specific correction row was found on the instrument. + public bool IsTechnologyMatch => Entry != null && !Entry.IsBaseOrGeneric; + } + /// /// Parses spotread's per-instrument -y table and resolves a /// to a selector that instrument actually accepts. @@ -230,14 +255,23 @@ public TypeRule(DisplayType type, string[] preferredSelectors, string[] keywords /// base calibration for the refresh class, else the generic selector. /// public static string Resolve(DisplayType type, IReadOnlyList? table, out string reason) + { + var choice = Resolve(type, table); + reason = choice.Reason; + return choice.Selector; + } + + /// + public static SpotreadDisplayTypeChoice Resolve(DisplayType type, IReadOnlyList? table) { var rule = RuleFor(type); + string generic = GenericSelector(type); + string genericName = rule.Refresh ? "CRT" : "LCD"; if (table == null || table.Count == 0) { - reason = "the instrument's display-type table is unknown; using the generic " + - (rule.Refresh ? "CRT" : "LCD") + " selector"; - return GenericSelector(type); + return new SpotreadDisplayTypeChoice(generic, + $"the instrument's display-type table is unknown; using the generic {genericName} selector", null); } // 1. Technology-specific rows (installed EDR/CCSS corrections) whose description @@ -251,16 +285,13 @@ public static string Resolve(DisplayType type, IReadOnlyList b.LongName.Length.CompareTo(a.LongName.Length)); + return names; + } + + /// + /// The short instrument name spotread prints before each -y row ("i1D3") for a + /// port-list descriptor such as "hid:/33 (X-Rite i1 DisplayPro, ColorMunki Display)". + /// Null when the descriptor names no known instrument (serial ports, unknown models). + /// + public static string? ShortNameForDescriptor(string? descriptor) + { + if (string.IsNullOrWhiteSpace(descriptor)) return null; + foreach (var (longName, shortName) in InstrumentNames) + { + if (descriptor.Contains(longName, StringComparison.OrdinalIgnoreCase)) + return shortName; + } + return null; + } + + /// + /// Restricts a table to the rows printed by the instrument named in + /// (plus the generic row). spotread prints one merged + /// block for every enumerated instrument, so with two meters connected a row from the + /// other meter would otherwise be selected. Returns the table unchanged when the + /// instrument is unknown or none of its rows are present. + /// + public static IReadOnlyList ForInstrument( + IReadOnlyList table, string? descriptor) + { + string? shortName = ShortNameForDescriptor(descriptor); + if (shortName == null || table.Count == 0) return table; + + var scoped = new List(); + bool anyInstrumentRow = false; + foreach (var entry in table) + { + if (entry.IsGeneric) + { + scoped.Add(entry); + } + else if (string.Equals(entry.Instrument, shortName, StringComparison.OrdinalIgnoreCase)) + { + scoped.Add(entry); + anyInstrumentRow = true; + } + } + return anyInstrumentRow ? scoped : table; } private static bool MatchesKeyword(string description, string[] keywords) diff --git a/src/Gloam.Core/Calibration/SpotreadSession.cs b/src/Gloam.Core/Calibration/SpotreadSession.cs index 8986d98..9baf41b 100644 --- a/src/Gloam.Core/Calibration/SpotreadSession.cs +++ b/src/Gloam.Core/Calibration/SpotreadSession.cs @@ -310,7 +310,8 @@ public static async Task StartAsync( CancellationToken cancellationToken, string? correctionFilePath = null, bool spectralMode = false, - IReadOnlyList? displayTypeTable = null) + IReadOnlyList? displayTypeTable = null, + string? instrumentDescriptor = null) { // NOTE (flag hygiene): spotread's -H flag is HIGH-RESOLUTION SPECTRAL mode and // only applies to spectrometers (i1 Pro etc.) — it is NOT an "HDR mode". This @@ -337,14 +338,15 @@ public static async Task StartAsync( // The table spotread printed while rejecting the selector comes from the // instrument it actually opened, so it outranks the one captured at detection // (which may be empty, stale, or from another instrument). Retry once with it. + var table = SpotreadDisplayTypeTable.ForInstrument(rejected.Table, instrumentDescriptor); var retryArgs = BuildSpotreadArguments(instrumentIndex, displayType, spectralMode, correctionFilePath, - rejected.Table, out string? retryReason); - if (rejected.Table.Count == 0 || retryArgs.SequenceEqual(args)) + table, out string? retryReason); + if (table.Count == 0 || retryArgs.SequenceEqual(args)) throw; log($"spotread rejected the -y selector; retrying with {retryReason}. " + - $"Instrument -y table: {SpotreadDisplayTypeTable.Describe(rejected.Table)}"); - return await StartProcessAsync(spotreadPath, retryArgs, spectralMode, rejected.Table, log, cancellationToken); + $"Instrument -y table: {SpotreadDisplayTypeTable.Describe(table)}"); + return await StartProcessAsync(spotreadPath, retryArgs, spectralMode, table, log, cancellationToken); } } diff --git a/src/Gloam/CalibrationSetupWindow.xaml b/src/Gloam/CalibrationSetupWindow.xaml index 8fe4702..ca921b3 100644 --- a/src/Gloam/CalibrationSetupWindow.xaml +++ b/src/Gloam/CalibrationSetupWindow.xaml @@ -147,6 +147,9 @@ + + public string MeterCalibrationText + { + get => _meterCalibrationText; + private set + { + if (SetProperty(ref _meterCalibrationText, value)) + OnPropertyChanged(nameof(HasMeterCalibrationText)); + } + } + + public bool HasMeterCalibrationText => !string.IsNullOrEmpty(_meterCalibrationText); + + /// + /// True when the connected colorimeter has no correction row for the selected display + /// type and will fall back to its generic base calibration. + /// + public bool MeterUsesGenericCalibration { get; private set; } + + private void RefreshMeterCalibrationText() + { + var service = ColorimeterService; + if (service == null || !service.IsReady || service.ConnectedInstrumentIsSpectrometer) + { + MeterUsesGenericCalibration = false; + MeterCalibrationText = ""; + return; + } + + var choice = service.ResolveDisplayTypeChoice(_displayType); + MeterUsesGenericCalibration = !choice.IsTechnologyMatch; + + string correctionFile = SelectedCorrection?.Path is { } path && path.Length > 0 + ? System.IO.Path.GetFileName(path) + : ""; + if (correctionFile.Length > 0) + { + MeterCalibrationText = + $"Meter calibration: {correctionFile} supplies the spectral calibration; spotread -y {choice.Selector} only sets the base mode."; + } + else if (choice.IsTechnologyMatch) + { + MeterCalibrationText = $"Meter calibration: {choice.Entry!.Description} (spotread -y {choice.Selector})."; + } + else + { + string row = choice.Entry?.Description ?? "generic calibration"; + MeterCalibrationText = + $"Meter calibration: no {DisplayTypeLabel(_displayType)} correction is installed on this meter, " + + $"so it will use its {row} (spotread -y {choice.Selector})."; } } @@ -634,7 +697,8 @@ private void SelectTarget(TargetOption? selected) bool whitePointOnly, MonitorProfileData? monitorProfile, bool? nightLightActive = null, - bool? sdrAcmActive = null) + bool? sdrAcmActive = null, + bool meterUsesGenericCalibration = false) { var items = new List<(string Severity, string Message)>(); @@ -684,7 +748,9 @@ private void SelectTarget(TargetOption? selected) bool correctionRecommended = displayType is DisplayType.Oled or DisplayType.LcdWideGamut || detectedDisplayType is DisplayType.Oled or DisplayType.LcdWideGamut; - if (correctionRecommended && string.IsNullOrEmpty(correction?.Path)) + if (meterUsesGenericCalibration && string.IsNullOrEmpty(correction?.Path)) + items.Add(("WARN", $"The meter has no {DisplayTypeLabel(displayType)} correction installed and will use its generic base calibration. Use a panel-matched CCSS/CCMX meter correction.")); + else if (correctionRecommended && string.IsNullOrEmpty(correction?.Path)) items.Add(("WARN", "Use a panel-matched CCSS/CCMX meter correction for OLED and wide-gamut displays.")); if (!string.IsNullOrEmpty(correction?.Path) && @@ -783,7 +849,8 @@ private void RefreshPreflight() WhitePointOnly, profile, nightLightActive, - sdrAcmActive)) + sdrAcmActive, + MeterUsesGenericCalibration)) { PreflightItems.Add(new CalibrationPreflightItem(item.Severity, item.Message, BrushForSeverity(item.Severity))); } @@ -1016,7 +1083,6 @@ private void UpdateColorimeterStatus() StatusBrush = SuccessBrush; StatusDetailText = ColorimeterService.ConnectedColorimeter?.Model ?? "Unknown model"; _colorimeterReady = true; - RefreshCanStart(); } else { @@ -1024,8 +1090,9 @@ private void UpdateColorimeterStatus() StatusBrush = WarningBrush; StatusDetailText = "Connect your colorimeter and click Refresh"; _colorimeterReady = false; - RefreshCanStart(); } + RefreshMeterCalibrationText(); + RefreshPreflight(); } #endregion diff --git a/tests/Gloam.Tests/CalibrationSetupPreflightTests.cs b/tests/Gloam.Tests/CalibrationSetupPreflightTests.cs index b5a1415..1a13688 100644 --- a/tests/Gloam.Tests/CalibrationSetupPreflightTests.cs +++ b/tests/Gloam.Tests/CalibrationSetupPreflightTests.cs @@ -43,6 +43,23 @@ public void Preflight_HdrActiveWithSdrTarget_BlocksStart() Assert.Contains(messages, m => m.Severity == "ERROR" && m.Message.Contains("HDR is active", StringComparison.OrdinalIgnoreCase)); } + [Fact] + public void Preflight_MeterUsesGenericCalibration_WarnsUnlessCorrectionChosen() + { + var withoutCorrection = CalibrationSetupViewModel.BuildPreflightMessages( + Monitor(), StandardTargets.SrgbGamma22, selectedOption: null, DisplayType.LcdLed, + detectedDisplayType: null, correction: new CorrectionChoice("Built-in", null), + whitePointOnly: false, monitorProfile: null, meterUsesGenericCalibration: true); + Assert.Contains(withoutCorrection, m => m.Severity == "WARN" && m.Message.Contains("generic base calibration", StringComparison.Ordinal)); + Assert.DoesNotContain(withoutCorrection, m => m.Message.StartsWith("Use a panel-matched", StringComparison.Ordinal)); + + var withCorrection = CalibrationSetupViewModel.BuildPreflightMessages( + Monitor(), StandardTargets.SrgbGamma22, selectedOption: null, DisplayType.LcdLed, + detectedDisplayType: null, correction: new CorrectionChoice("Panel", @"C:\nonexistent.ccss"), + whitePointOnly: false, monitorProfile: null, meterUsesGenericCalibration: true); + Assert.DoesNotContain(withCorrection, m => m.Message.Contains("generic base calibration", StringComparison.Ordinal)); + } + [Fact] public void ViewModel_HdrInitialMonitor_SelectsOnlyHdrTarget() { diff --git a/tests/Gloam.Tests/SpotreadDisplayTypeTableTests.cs b/tests/Gloam.Tests/SpotreadDisplayTypeTableTests.cs index aaa6025..fc97737 100644 --- a/tests/Gloam.Tests/SpotreadDisplayTypeTableTests.cs +++ b/tests/Gloam.Tests/SpotreadDisplayTypeTableTests.cs @@ -266,6 +266,71 @@ public void Resolve_TableWithoutBaseOrGenericRows_FallsBackToGenericSelector() Assert.Equal("l", SpotreadDisplayTypeTable.Resolve(DisplayType.Oled, table, out _)); } + // Two meters enumerated at once: spotread prints one merged -y block. + internal const string TwoInstrumentUsage = + " -y n|l i1D3: Non-Refresh display [Default,CB1]\n" + + " r|c i1D3: Refresh display [CB2]\n" + + " 1 i1D3: LCD CCFL PVA (Resolve JVC CPF)\n" + + " o Spyder4: LED OLED (imported)\n" + + " e Spyder4: LCD White LED [Default,CB1]\n" + + " l|c Other: l = LCD, c = CRT\n" + + " -I illum Set simulated instrument illumination using FWA (def -i illum):\n"; + + [Theory] + [InlineData("hid:/33 (X-Rite i1 DisplayPro, ColorMunki Display)", "i1D3")] + [InlineData("usb:/2 (Datacolor SpyderX2)", "SpyderX2")] + [InlineData("usb:/2 (Datacolor SpyderX)", "SpyderX")] + [InlineData("usb:/1 (X-Rite i1 Pro 2)", "i1Pro2")] + [InlineData("COM6", null)] + [InlineData(null, null)] + public void ShortNameForDescriptor_MapsArgyllPortNames(string? descriptor, string? expected) + { + Assert.Equal(expected, SpotreadDisplayTypeTable.ShortNameForDescriptor(descriptor)); + } + + [Fact] + public void ForInstrument_KeepsOnlyTheOpenedInstrumentsRows() + { + var merged = SpotreadDisplayTypeTable.Parse(TwoInstrumentUsage); + + var i1d3 = SpotreadDisplayTypeTable.ForInstrument(merged, "hid:/33 (X-Rite i1 DisplayPro, ColorMunki Display)"); + Assert.Equal(4, i1d3.Count); + Assert.DoesNotContain(i1d3, e => e.Instrument == "Spyder4"); + Assert.Contains(i1d3, e => e.IsGeneric); + // The other meter's OLED row must not leak into this meter's resolution. + Assert.Equal("n", SpotreadDisplayTypeTable.Resolve(DisplayType.Oled, i1d3, out _)); + + var spyder = SpotreadDisplayTypeTable.ForInstrument(merged, "usb:/4 (Datacolor Spyder4)"); + Assert.Equal(3, spyder.Count); + Assert.Equal("o", SpotreadDisplayTypeTable.Resolve(DisplayType.Oled, spyder, out _)); + } + + [Fact] + public void ForInstrument_UnknownOrAbsentInstrument_ReturnsTableUnchanged() + { + var merged = SpotreadDisplayTypeTable.Parse(TwoInstrumentUsage); + + Assert.Same(merged, SpotreadDisplayTypeTable.ForInstrument(merged, "COM6")); + Assert.Same(merged, SpotreadDisplayTypeTable.ForInstrument(merged, "usb:/9 (Klein K-10)")); + } + + [Fact] + public void Resolve_ReturnsTheMatchedRow() + { + var table = SpotreadDisplayTypeTable.Parse(EdrRichI1D3Usage); + + var choice = SpotreadDisplayTypeTable.Resolve(DisplayType.Oled, table); + Assert.True(choice.IsTechnologyMatch); + Assert.Equal("o", choice.Selector); + Assert.StartsWith("LED OLED", choice.Entry!.Description); + + var clean = SpotreadDisplayTypeTable.Resolve(DisplayType.Oled, SpotreadDisplayTypeTable.Parse(CleanI1D3Usage)); + Assert.False(clean.IsTechnologyMatch); + Assert.True(clean.Entry!.IsNonRefreshBase); + + Assert.Null(SpotreadDisplayTypeTable.Resolve(DisplayType.Oled, null).Entry); + } + [Fact] public void Describe_ListsSelectorsAndDescriptions() { From 820c28f9b744a4fd907fd088596aae20b4e1455e Mon Sep 17 00:00:00 2001 From: David Torcivia Date: Tue, 15 Sep 2026 18:47:06 -0400 Subject: [PATCH 4/9] Import i1Display EDR files with oeminst from the setup screen OemCorrectionImporter enumerates *.edr under the X-Rite, Calibrite and I-O DATA folders of every Program Files root and runs the bundled oeminst -v on them, which converts each EDR to a CCSS in Argyll's per-user data folder. ParseOutput reads the "Wrote ''" lines and the exit code. Nothing is downloaded; oeminst's own search covers only one fixed X-Rite path, so the files are passed explicitly. CalibrationSetupViewModel.ImportOemCorrectionsAsync runs it from a new "Import EDRs" button next to the correction picker, shows the result under it, reloads the correction list, and re-runs meter detection so the -y table gains the technology rows. The generic-calibration preflight warning names the button. Tests cover the vendor folder search, output parsing (CRT.ccss from Argyll's ref folder is not counted), the no-files and missing-oeminst paths. --- docs/release-notes/v1.9.2.md | 1 + .../Calibration/OemCorrectionImporter.cs | 217 ++++++++++++++++++ src/Gloam/CalibrationSetupWindow.xaml | 7 + .../ViewModels/CalibrationSetupViewModel.cs | 70 +++++- .../Gloam.Tests/OemCorrectionImporterTests.cs | 108 +++++++++ 5 files changed, 402 insertions(+), 1 deletion(-) create mode 100644 src/Gloam.Core/Calibration/OemCorrectionImporter.cs create mode 100644 tests/Gloam.Tests/OemCorrectionImporterTests.cs diff --git a/docs/release-notes/v1.9.2.md b/docs/release-notes/v1.9.2.md index 4910e09..e8e5e5d 100644 --- a/docs/release-notes/v1.9.2.md +++ b/docs/release-notes/v1.9.2.md @@ -7,5 +7,6 @@ Calibration no longer fails at instrument startup with "Failed to locate display - If spotread still rejects the selector, Gloam reads the table spotread prints on the way out and restarts once with a selector from that table. The failure message now lists the selectors the instrument accepts. - With two meters connected, only the rows spotread printed for the meter Gloam opened are considered. - The calibration setup screen now shows which calibration row the meter will use for the selected display type, and warns when the meter has no correction for that type and no CCSS/CCMX file is chosen. +- New "Import EDRs" button on the setup screen: converts the i1Display EDR files of an installed X-Rite i1Profiler or Calibrite PROFILER into ArgyllCMS corrections with Argyll's oeminst, then re-detects the meter. This is what gives the meter its OLED, white LED and RGB LED calibration rows. Nothing is downloaded; the files must already be on the PC. Validation: all 1,388 tests pass and the strict Release build has zero warnings or errors. The rejection and retry path was exercised against an i1 Display Pro on Argyll 3.5.0 by forcing an invalid selector; the retry restarted with a listed selector and reached the ready prompt. The reporter's clean-install table and a table with imported EDR rows are pinned as test fixtures. diff --git a/src/Gloam.Core/Calibration/OemCorrectionImporter.cs b/src/Gloam.Core/Calibration/OemCorrectionImporter.cs new file mode 100644 index 0000000..0db5e89 --- /dev/null +++ b/src/Gloam.Core/Calibration/OemCorrectionImporter.cs @@ -0,0 +1,217 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; + +namespace Gloam.Core.Calibration +{ + /// Outcome of an run. + public sealed class OemImportResult + { + public OemImportResult(bool success, IReadOnlyList installedFiles, string message, string output) + { + Success = success; + InstalledFiles = installedFiles; + Message = message; + Output = output; + } + + /// True when oeminst exited cleanly and wrote at least one file. + public bool Success { get; } + + /// Full paths oeminst reported writing. + public IReadOnlyList InstalledFiles { get; } + + /// One or two sentences for the setup screen. + public string Message { get; } + + /// Raw oeminst output, for the log. + public string Output { get; } + } + + /// + /// Converts the i1Display EDR calibration files that X-Rite i1Profiler and Calibrite + /// PROFILER install into ArgyllCMS CCSS corrections, using Argyll's own oeminst. + /// Once installed, spotread lists them as technology rows (OLED, white LED, RGB LED, ...) + /// in its -y table, so a display type resolves to a matching correction instead + /// of the instrument's generic base calibration. + /// + /// + /// The EDR files are the vendor's; nothing is downloaded. They are only converted when + /// already present on this PC under the user's own software license. oeminst itself + /// searches one fixed X-Rite path, so the files are enumerated here (Calibrite and + /// 32-bit install roots included) and handed to it explicitly. + /// + public static class OemCorrectionImporter + { + // Vendor folders under each Program Files root that may hold i1d3 EDR files. + private static readonly string[] VendorFolders = { "X-Rite", "Calibrite", "I-O DATA" }; + + // oeminst -v prints one of these per installed file. + private static readonly Regex WrotePattern = new(@"^Wrote '([^']+)'", RegexOptions.Compiled | RegexOptions.Multiline); + + /// The Program Files roots to search on this machine. + public static IReadOnlyList DefaultSearchRoots() + { + var roots = new List(); + foreach (string variable in new[] { "ProgramFiles", "ProgramFiles(x86)", "ProgramW6432" }) + { + string? value = Environment.GetEnvironmentVariable(variable); + if (!string.IsNullOrEmpty(value) && !roots.Contains(value, StringComparer.OrdinalIgnoreCase)) + roots.Add(value); + } + return roots; + } + + /// Every .edr file under a known vendor folder of the given roots. + public static IReadOnlyList FindEdrFiles(IEnumerable? searchRoots = null) + { + var found = new List(); + foreach (string root in searchRoots ?? DefaultSearchRoots()) + { + foreach (string vendor in VendorFolders) + { + string dir = Path.Combine(root, vendor); + if (!Directory.Exists(dir)) continue; + try + { + found.AddRange(Directory.EnumerateFiles(dir, "*.edr", SearchOption.AllDirectories)); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // A vendor folder we cannot read contributes nothing. + } + } + } + found.Sort(StringComparer.OrdinalIgnoreCase); + return found; + } + + /// Path of oeminst next to spotread, or null if the Argyll bundle lacks it. + public static string? FindOeminst(string argyllBinPath) + { + foreach (string name in new[] { "oeminst.exe", "oeminst" }) + { + string path = Path.Combine(argyllBinPath, name); + if (File.Exists(path)) return path; + } + return null; + } + + /// Message shown when the search found nothing to import. + public const string NothingFoundMessage = + "No i1Display EDR files were found on this PC. They ship with X-Rite i1Profiler and Calibrite PROFILER; " + + "install either, then import again. A panel-matched correction from Find / Create is better than any EDR."; + + /// + /// Runs oeminst -v on (found with + /// ) and reports what it wrote. + /// + public static async Task ImportAsync( + string argyllBinPath, + IReadOnlyList edrFiles, + Action? log, + CancellationToken cancellationToken) + { + if (edrFiles.Count == 0) + return new OemImportResult(false, Array.Empty(), NothingFoundMessage, ""); + + string? oeminst = FindOeminst(argyllBinPath); + if (oeminst == null) + { + return new OemImportResult(false, Array.Empty(), + "The bundled ArgyllCMS has no oeminst tool. Click Refresh to reinstall ArgyllCMS, then import again.", ""); + } + + var psi = new ProcessStartInfo(oeminst) + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + WorkingDirectory = argyllBinPath + }; + psi.ArgumentList.Add("-v"); + foreach (string file in edrFiles) + psi.ArgumentList.Add(file); + + log?.Invoke($"oeminst: importing {edrFiles.Count} EDR file(s) with {oeminst}"); + + string output; + int exitCode; + try + { + using var process = Process.Start(psi) + ?? throw new InvalidOperationException("oeminst did not start."); + using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + cts.CancelAfter(TimeSpan.FromMinutes(2)); + + var stdout = process.StandardOutput.ReadToEndAsync(cts.Token); + var stderr = process.StandardError.ReadToEndAsync(cts.Token); + try + { + await process.WaitForExitAsync(cts.Token); + } + catch (OperationCanceledException) + { + try { process.Kill(entireProcessTree: true); } catch { /* already gone */ } + throw; + } + output = await stdout + "\n" + await stderr; + exitCode = process.ExitCode; + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + return new OemImportResult(false, Array.Empty(), + "oeminst did not finish within two minutes and was stopped.", ""); + } + + log?.Invoke($"oeminst exit {exitCode}:\n{output}"); + return ParseOutput(output, exitCode); + } + + /// Turns oeminst's verbose output and exit code into a result. + internal static OemImportResult ParseOutput(string output, int exitCode) + { + var installed = new List(); + foreach (Match m in WrotePattern.Matches(output)) + installed.Add(m.Groups[1].Value); + + if (exitCode != 0) + { + string lastLine = LastNonEmptyLine(output); + return new OemImportResult(false, installed, + $"oeminst failed (exit {exitCode}): {lastLine}", output); + } + if (installed.Count == 0) + return new OemImportResult(false, installed, "oeminst ran but reported no installed files.", output); + + // oeminst also installs Argyll's own ref/CRT.ccss alongside any EDR set; count + // only the files that came from the EDRs for the message. + int edrCount = 0; + foreach (string path in installed) + { + if (!Path.GetFileName(path).Equals("CRT.ccss", StringComparison.OrdinalIgnoreCase)) + edrCount++; + } + string dir = Path.GetDirectoryName(installed[0]) ?? ""; + return new OemImportResult(true, installed, + $"Imported {edrCount} meter correction(s) into {dir}. Re-detecting the meter to pick them up.", output); + } + + private static string LastNonEmptyLine(string text) + { + string last = ""; + foreach (string line in text.Split('\n')) + { + string t = line.Trim(); + if (t.Length > 0) last = t; + } + return last; + } + } +} diff --git a/src/Gloam/CalibrationSetupWindow.xaml b/src/Gloam/CalibrationSetupWindow.xaml index ca921b3..0390afc 100644 --- a/src/Gloam/CalibrationSetupWindow.xaml +++ b/src/Gloam/CalibrationSetupWindow.xaml @@ -132,6 +132,7 @@ + @@ -144,7 +145,13 @@ Margin="6,0,0,0" Padding="10,2" Click="FindCorrection_Click"/>