Files
DankMaterialShell/core/internal/icc/parser_test.go
T
Minghao YUandbbedward e809733e3a feat(display): per-output ICC color profiles and color temperature (#3388)
* feat(display): per-output ICC color profiles and color temperature

Rebuild of #3388 on current master: the previous branch was cut from an
older base and reverted unrelated fixes in the gamma stack and the display
settings UI.

ICC profiles:
- core/internal/icc: ICC v2/v4 parser (TRC, LUT8/16 and parametric curves,
  vcgt, description/version/color space) plus gamma ramp generation, with
  synthetic coverage and optional vendor-profile tests (ICC_TEST_DIR).
- wayland manager: load iccProfiles from the compositor's DMS config dir,
  build the ramp from the profile when one is set (falling back to the
  temperature ramp when it is missing or unparsable), and re-apply on
  output hotplug and after resume.
- ICC ramps apply while the night light schedule is disabled; outputs
  without a profile keep an identity ramp.
- desc/mluc offsets are validated before slicing, so a malformed profile
  returns an error instead of panicking the daemon.

Per-output temperature:
- outputTemps in the same config; SetOutputTemp accepts 1000-10000K and the
  Display Config slider exposes 3000-10000K, which matters for displays
  calibrated at a higher white point (e.g. a 7000K profile).

Gamma control lifecycle:
- needsControls() now keeps the controls alive for configured ICC profiles
  and per-output temperatures, so toggling the night light off no longer
  destroys the controls and drops the ramps.
- Re-apply paths clear the per-output dedup state instead of adding a
  manager-level guard, which would have suppressed contrast-only writes and
  the post-resume forced resend (#1235), and left a recreated control
  without a ramp.
- Monitor sleep/disconnect still re-establishes controls when an output
  comes back.

IPC / CLI / UI:
- wayland.icc.{getStatus,apply,remove,listOutputs,setTemp,getTemps}
- dms icc list | info <file> | apply <output> <file> | remove <output> | status
- Display Config output card gains a Color Profile row (browse/apply/remove
  with description, version, color space and active state) and a per-output
  color temperature slider, backed by Services/ICCService.qml.

Config path:
- DMSConfigDir() follows the compositor layout (niri/dms, hypr/dms,
  mango/dms) via the shared compositor detection and utils.XDGConfigHome(),
  replacing the hardcoded niri path in both the manager and `dms icc`.

Tests: TZ=UTC go test ./... (60 packages ok), including red/green coverage
for the icc parser bounds checks and needsControls().

* feat(icc): add `dms icc set-temp` and show per-output temps in `status`

The per-output temperature override was reachable from the Display Config
slider and from `wayland.icc.setTemp` over IPC, but not from the CLI.

- `dms icc set-temp <output> <kelvin>` (alias `setTemp`) sets a per-output
  override, 1000-10000K, and 0 clears it so the output follows the night
  light schedule again. Range checking matches the daemon so an invalid
  value fails in the CLI instead of over IPC.
- `dms icc status` gains a Temp column (the override in K, or `schedule`),
  so an override can be verified without opening the settings UI.

Verified against a running daemon: `dms icc status` reports 7000K for the
three overridden outputs and `schedule` for the remaining one.

* feat(icc): treat the per-output temperature as the profile's reference white point

The per-output temperature was documented as the white point a profile was
produced at, but an output with a profile ignored it entirely: the ramp was
generated from the profile and the temperature only applied to outputs
without one (or as the fallback when a profile failed to parse). A display
calibrated at 7000K therefore got the profile ramp, and enabling the night
light had no effect on it at all.

- `ProfileRampWithTemp` composes the profile ramp with the ratio between the
  target temperature ramp and the reference ramp, so the temperature is the
  white point the profile describes and the night light shifts relative to
  it.
- `applyGamma` passes the night light temperature as the target, and
  `noTempTarget` when the schedule is disabled, which leaves profiled
  outputs at their reference white point and drives plain outputs with the
  neutral ramp.
- The re-apply sentinel stays 0, so it cannot collide with an applied
  temperature.

Covered by TestProfileRampWithTemp (reference == target is a no-op, warmer
and cooler targets move the expected channels).

Also: `dms icc set-temp` help text describes the reference-white-point
semantics.

* fix(icc): load the configured profiles even when controls already exist

Restoring the upstream "output returned, re-establishing controls" branch
made the registry handler establish the gamma controls before the startup
post runs, and that post returned early on `m.controlsInitialized`, so the
configured ICC profiles and per-output temperatures were never attached:
every output reported "(none)" and the night light ran with defaults until
the user re-applied a profile by hand.

- `initializeControlsAndICC` (the startup post) loads the configuration
  first and only creates the controls when they are missing.
- The loading is split into `loadConfiguredICC` / `applyConfiguredICCForOutput`
  so it can also run per output.
- A hotplugged output now gets its configured profile and temperature as soon
  as its name is known (name handler) or when its control is created, which
  also makes the "re-applies on hotplug" claim in the description true.
- After attaching, the output's dedup state is cleared so the ramp is written.

Covered by TestManager_LoadConfiguredICCWhenControlsAlreadyExist and
TestManager_AttachConfiguredICCForNamedOutput.

* fix(icc): make the per-output temperature an actual target

The per-output value was treated as the white point a profile was produced
at, which meant a display with a profile never changed when the user set a
temperature: the profile ramp was applied as measured and the value only
mattered when a night light target existed. Per-display temperatures were
therefore unusable on profiled outputs while the night light was disabled,
which is the normal state for users who want each monitor at its own value.

- `effectiveTempTarget` decides per output: a per-output override wins over
  the night light schedule, the schedule applies when there is no override,
  and `noTempTarget` means neither. `0` is "no override", not 0K.
- `applyGamma` composes the override on top of the profile ramp, treating the
  profile as measured at 6500K (D65), and drives outputs without a profile
  with the same target so both paths agree.
- `dms icc set-temp` help text and the Display Config slider description go
  back to describing an independent per-output temperature.

Covered by TestEffectiveTempTarget (override wins, schedule fallback, none)
and the updated TestProfileRampWithTemp (7000K cools, 5000K warms relative to
the 6500K reference).

* feat(icc): show the profile details in Display Config

The profile row only showed the description, so there was no way to tell
which profile a display actually has applied (whitepoint, curve type, file
provenance) without leaving the settings page.

- `ICCStatus` carries the descriptive metadata: class, tone-curve kind (plus
  gamma or table size), vcgt channels/entries, white point chromaticity with
  a derived CCT and standard illuminant name, file size and mtime.
- `internal/icc` gains `WhitePointXY`, `WhitePointCCT` (McCamy),
  `WhitePointName` (D50/D65) and `TRCKind`, all covered by tests.
- Display Config's Color Profile row gets an info button that opens
  `ICCProfileInfoModal` with those fields and the profile path, alongside
  the existing browse/remove actions.
- `dms icc info` reports the white point as name/xy/CCT instead of raw XYZ.

* fix(icc): keep the daemon, the state snapshot and the temp slider honest

A malformed profile could still take the daemon down, the ICC getters ran off
the wayland actor goroutine, the pushed state hid a removal, and the
per-output temperature slider dropped wheel changes.

- `internal/icc`: the tag table was sized with `uint32` arithmetic, so
  `tagCount*12` wrapped (`0x15555556*12 == 8`) and a 140-byte profile passed
  the bounds check, allocated ~4.3 GB and then panicked. `ParseFile` runs on
  the wayland actor goroutine, which has no `recover()`, so a bad profile
  persisted in `wayland.json` took the daemon down at startup. The count is now
  compared against the bytes that are actually left before anything is sized
  with it.
- The manager publishes an ICC snapshot (`iccStatus`/`iccTemps`) whenever the
  actor changes an output's profile or temperature, and `GetICCStatus`/
  `GetOutputTemps` serve that snapshot instead of ranging `m.outputs` and
  reading fields the actor owns. That removes the data race reported by
  `go test -race` for `dms icc status` running against a hotplug, and keeps the
  per-profile `os.Stat` off the night light animation path, where it ran on
  every `updateStateFromSchedule` (including each 25 K step).
- `State.ICCProfiles`/`OutputTemps` drop `omitempty`, so removing the last
  profile pushes `{}` instead of omitting the key: the QML truthiness guard
  then clears `ICCService.status` instead of leaving the removed profile on
  screen with a green "active" dot.
- `removeOutputByRegistryName` (extracted from the registry remove handler)
  deletes the `outputNames`/`outputRegNames` entries along with the output, so
  a disconnected monitor stops being listed by `dms icc status`/`listOutputs`,
  and a rebound `wl_output` reusing the released object ID cannot attach the
  previous monitor's profile from the stale name.
- The per-output temperature slider sets `wheelEnabled: false` like the other
  drag-finished sliders: `DankSlider`'s wheel handler assigns `value` and emits
  `sliderValueChanged` without `sliderDragFinished`, so scrolling dropped the
  change, froze the label on the scrolled value and destroyed the value binding.

Covered by TestParseBytesTagTableBounds (allocates 4,299,161,600 bytes at
parser.go:138 and dies with an unrecovered fatal error on the previous
commit), TestManager_ICCStatusServesPublishedSnapshot,
TestManager_RemoveOutputByRegistryNamePrunesNames and
TestManager_ICCStatusConcurrentPublishAndRead; a temporary copy of the getter
test against the previous commit reports DATA RACE and passes here.

* fix(icc): keep the attached profile when a gamma control is re-created

`setupOutputControls` stored a fresh `outputState` for every output it touched,
and `createControls` calls it whenever the controls are rebuilt, so recreating a
control dropped the output's `iccPath`/`iccProfile`/`outputTemp` — configured
state that does not belong to the control. The path is dormant today because
`destroyControls` only runs when nothing is configured (`needsControls()` covers
`ICCProfiles`/`OutputTemps`), but the snapshot published after `createControls`
would then report whatever the rebuilt state holds instead of the profile the
display is configured with.

`controlStateFor` reuses the state of a known output and resets only what belongs
to the new control: the ramp bookkeeping and the failure budget (rampSize,
failed, retryCount, lastFailTime, lastTemp, lastGamma, lastContrast). A control
that has not reported gamma_size yet has to receive its ramp again, while the
profile and the per-output temperature survive. An output seen for the first
time still starts from a clean state.

Covered by TestManager_ControlStateReuseKeepsAttachedICC.

* fix(icc): keep the config a real snapshot and make the per-output temperature apply

Third review round.

- `Config` is copied by value all over the manager, but `ICCProfiles` and
  `OutputTemps` are maps, so every copy aliased the ones the manager writes under
  `configMutex`. `updateStateFromSchedule` stored such a copy in `m.state` and it
  was marshalled on the connection writer goroutine while `ApplyICC` stored a
  profile from the IPC goroutine (`fatal error: concurrent map iteration and map
  write`, which no `recover()` catches); `SaveConfig` marshalled its copy after
  the unlock, and `loadConfiguredICC`/`attachConfiguredICC` indexed the maps after
  releasing the lock. Every copy that outlives the lock is cloned now
  (`cloneConfig`/`configSnapshot`), so a value copy is a snapshot again.
- `SetOutputTemp` never created the gamma controls. On a default install (night
  light off, gamma 1.0, contrast 1.0, no profile, no override) they do not exist,
  so the `Range` over `m.outputs` matched nothing: the value was written to
  `wayland.json`, no ramp was applied, and the settings slider snapped back to
  "Default" until a daemon restart. It now persists first, creates the controls
  through `ensureOutputControls` (shared with `ApplyICC`), and pushes the state
  from the actor, and the published temperatures report the configured value even
  before an output is known.
- A TRC is not a video card gamma ramp: `rTRC`/`gTRC`/`bTRC` describe the
  display's own transfer function, so a gamma-2.2 profile was written as
  `t^(1/2.2)` — mid gray 0.5 became 47909/65535 — washing the display out instead
  of correcting it. `ApplyICC` refuses a profile without `vcgt`, the attach path
  skips one with a warning, and `GenerateGammaRamp` returns an error instead of
  falling back to the TRC or to an identity ramp. TRC stays profile metadata
  (`dms icc info`, the settings dialog).
- `icc: applied ICC ramp` was logged at Info on every 25 K animation step; it is
  Debug now, which is where a per-step message belongs.
- `I18n.tr("No information available")` in the profile info modal passes its
  translator context, like every other string this PR adds.

Covered by TestManager_ConfigSnapshotOwnsItsMaps,
TestManager_ConfigSnapshotConcurrentMarshal (the previous commit dies with
`fatal error: concurrent map iteration and map write`),
TestManager_SetOutputTempWithoutControlsPublishesValue (the previous commit
reports 0 for the value it just stored), TestGenerateGammaRampRequiresVCGT, and
the updated TestProfileRampWithTemp, whose fixture now carries an identity vcgt
table instead of relying on an empty profile.

* fix(icc): push the state when only the ICC part changed

Found while sweeping the same class of problem: `stateChanged` compared only the
schedule fields, so a change that touches nothing else — applying or removing a
profile, `dms icc set-temp` — was treated as "no change" and the notifier never
pushed it. The settings page then only caught up because the UI path calls
`requestStatus()` afterwards, and the CLI path did not catch up at all, which is
the symptom the omitempty fix was meant to remove.

`iccStateChanged` compares the ICC profile status and the per-output
temperatures, so those changes reach the subscribers on their own. Covered by
the new TestStateChanged cases (profile applied, profile removed, profile
description changed, output temp changed, unchanged ICC state); the four
change cases report `stateChanged() = false` on the previous commit.

* fix(icc): keep the night light state, prune names without a control, use a 0 sentinel

Fifth review round.

- `SaveICCConfig` replaces `SaveConfig` on the three ICC paths (apply, remove,
  set-temp). Writing the daemon's whole config persisted the night light fields
  it happens to hold in memory: with the night light on, applying a profile
  stored `"Enabled": true`, and since the shell only ever sends
  `wayland.gamma.setEnabled` when the mode is on, turning it off afterwards (an
  in-memory change on the daemon side, no write) left that `true` on disk — after
  log out/in the daemon came up driving the schedule while the UI showed night
  mode off, with no way to resync short of a toggle. The ICC save now reads the
  file and rewrites only `iccProfiles`/`outputTemps`, so the fields the shell
  owns stay as they are.
- `removeOutputByRegistryName` resolved the output from `m.outputs`, which only
  has entries once the gamma controls exist. On a default install (night light
  off, no profile, no override) no control is ever created, so a disconnected
  monitor kept its `outputNames`/`outputRegNames` entries for the life of the
  daemon: `dms icc status`/`listOutputs` listed monitors that were gone, and both
  maps grew with every dock/undock cycle. The object ID is resolved from
  `m.outputRegNames` (populated for every `wl_output`), the name entries are
  dropped before the output state is looked up, and a state that is known without
  a registry name still falls back to matching its own.
- The Display Config temperature row used `7000` as its fallback for an output
  with no override. `publishICCState` only copies entries with `temp != 0`, so
  the value is absent rather than `0` for an unconfigured output: the card claimed
  "7000K" while the daemon drove the night light or neutral, and a user who
  deliberately set 7000K got the "no override" colouring because the highlight
  tested `!== 7000`. The sentinel is `0` now, which is what the `Default` label
  branches and the "is overridden" tests were written against.

Covered by TestSaveICCConfigKeepsNightLightFields (the previous commit brings the
night light back on after a restart), TestManager_RemoveOutputByRegistryNameWithoutControl
(the previous commit keeps an unplugged monitor listed) and the existing
TestManager_RemoveOutputByRegistryNamePrunesNames.

* fix(icc): validate the CLI arguments and the IPC parameters of the ICC commands

Sweep of the two surfaces the review has not looked at yet, so the failures are
found here instead of in the next round.

- `dms icc apply` copied the profile into the config directory before asking the
  daemon, and only the *parse* was checked locally. A profile the daemon refuses
  (no `vcgt` table, non-RGB color space) was therefore left in the profile
  directory for `dms icc list` to keep offering, and an IPC failure left the copy
  behind as well. The command now checks the same rules the daemon enforces
  before copying anything, and removes the copy it just made when the request
  fails (a file that was already there is left alone).
- `dms icc list` marks a profile without a `vcgt` table, so the rule that makes
  `apply` refuse it is visible where the profiles are listed.
- `ApplyICC`/`RemoveICC`/`SetOutputTemp` reach the manager over IPC with whatever
  the caller sent: an empty (or whitespace-padded) output name used to be
  persisted as an entry in `wayland.json` that no `wl_output` can ever match, and
  a relative profile path was stored to be resolved again on the next start, from
  a different working directory. Both are rejected now, before anything is
  written.

Verified with the built CLI against the previous binary: with a profile that has
no vcgt table, `dms icc apply` now exits before touching the config directory
(`residual=[]`) where the previous one copied the file and went on to the IPC
(`residual=[nogamma.icc]`); with a valid profile and no daemon reachable, the
previous one leaves `vcgt.icc` behind and this one does not. Covered by
TestManager_RejectsInvalidICCArguments.

* fix(icc): apply the user gamma and contrast on profiled outputs

* fix(icc): recreate failed controls without the night light and allow clearing a per-output temp

* test(icc): cover the recreated control and the cleared temperature override

Follow-up on d55d3d1f, which fixed both points without tests:

- TestManager_RecreateOutputControlFollowsNeedsControls pins the predicate: with
  the night light off and nothing configured there is nothing to recreate, and
  with a configured profile or a per-output temperature the control has to be
  recreated. Both configured cases return nil on 9226251c.
- TestManager_SetOutputTempZeroClearsTheOverride pins what the reset button in
  Display Config does end to end: the stored value and the published entry both
  disappear, so the row reads "Default" and the output follows the schedule.

Also keeps the reset button's slot instead of revealing it on demand. The
temperature row shares its column with the slider below it, so the height change
between "Default" (no button) and an override moved the slider 14 px under the
pointer while it was being dragged; the button is now always laid out and only
its opacity and enabled state follow the override, which also lets the label
width drop the conditional.

* fix(icc): replicate a one-channel vcgt and keep the temp slider in sync

* fix(icc): release idle gamma controls and push the output list

* fix(icc): dedupe ramps on the effective target

* fix(icc): never overwrite a same-named profile in the config dir

---------

Co-authored-by: bbedward <[email protected]>
2026-09-15 11:45:35 -04:00

664 lines
20 KiB
Go

package icc
import (
"encoding/binary"
"fmt"
"math"
"os"
"path/filepath"
"slices"
"strings"
"testing"
)
// Vendor-profile tests are optional: set ICC_TEST_DIR to a directory holding
// the files below to run them against real display profiles. CI has none, so
// they are skipped there and the synthetic tests at the bottom cover parsing
// and ramp generation instead.
var testFiles = []struct {
name string
file string
}{
{
name: "Samsung Odyssey Neo G8 (v2.1, matrix-TRC, vcgt)",
file: "1D8HG_B173ZAN_31-08-2023.icm",
},
{
name: "DisplayPort monitor (v2.1, matrix-TRC, vcgt)",
file: "DP_31-08-2023.icm",
},
{
name: "GPD Win Max 2 (v2.2, XYZLUT+MTX, vcgt)",
file: "GPD1001H #1 2024-11-29 22-12 D6500 2.2 F-S XYZLUT+MTX.icm",
},
}
// vendorProfile resolves an optional vendor profile, skipping the test when
// ICC_TEST_DIR is unset or the file is missing.
func vendorProfile(t *testing.T, file string) string {
t.Helper()
dir := os.Getenv("ICC_TEST_DIR")
if dir == "" {
t.Skip("ICC_TEST_DIR not set; skipping vendor profile test")
}
path := filepath.Join(dir, file)
if _, err := os.Stat(path); err != nil {
t.Skipf("vendor profile unavailable: %v", err)
}
return path
}
func TestParseFile(t *testing.T) {
for _, tc := range testFiles {
t.Run(tc.name, func(t *testing.T) {
path := vendorProfile(t, tc.file)
// Read file to get expected size
info, err := os.Stat(path)
if err != nil {
t.Fatalf("cannot stat file: %v", err)
}
p, err := ParseFile(path)
if err != nil {
t.Fatalf("ParseFile failed: %v", err)
}
// Verify size matches file size
if p.Size != uint32(info.Size()) {
t.Errorf("Size: got %d, want %d", p.Size, info.Size())
}
// Verify version
if p.Version != "2.1.0" && p.Version != "2.2.0" && p.Version != "2.4.0" {
t.Errorf("Version: got %q, want v2.x", p.Version)
}
t.Logf(" Version: %s", p.Version)
// Verify class
if p.Class != "mntr" {
t.Errorf("Class: got %q, want %q", p.Class, "mntr")
}
// Verify color space
if p.ColorSpace != "RGB" {
t.Errorf("ColorSpace: got %q, want %q", p.ColorSpace, "RGB")
}
// Verify description is non-empty
if p.Description == "" {
t.Error("Description is empty")
}
t.Logf(" Description: %s", p.Description)
// Verify matrix
if !p.HasMatrix {
t.Error("HasMatrix is false, expected true")
} else {
t.Logf(" Matrix:")
for i := 0; i < 3; i++ {
t.Logf(" [%6.4f %6.4f %6.4f]", p.Matrix[0][i], p.Matrix[1][i], p.Matrix[2][i])
}
// Each Y value (second row of matrix) should be in [0, 1]
for _, col := range p.Matrix {
if col[1] < -0.01 || col[1] > 1.5 {
t.Errorf("Matrix Y value out of range: %f", col[1])
}
}
}
// Verify VCGT
if !p.HasVCGT {
t.Error("HasVCGT is false, expected true")
} else {
t.Logf(" VCGT: %d channels, %d entries", p.VCGT.Channels, p.VCGT.Entries)
t.Logf(" VCGT Red: [%d ... %d]", p.VCGT.Red[0], p.VCGT.Red[len(p.VCGT.Red)-1])
// Verify entry count matches declared
if len(p.VCGT.Red) != p.VCGT.Entries {
t.Errorf("VCGT Red entries: got %d, want %d", len(p.VCGT.Red), p.VCGT.Entries)
}
if len(p.VCGT.Green) != p.VCGT.Entries {
t.Errorf("VCGT Green entries: got %d, want %d", len(p.VCGT.Green), p.VCGT.Entries)
}
if len(p.VCGT.Blue) != p.VCGT.Entries {
t.Errorf("VCGT Blue entries: got %d, want %d", len(p.VCGT.Blue), p.VCGT.Entries)
}
// Verify channels
if p.VCGT.Channels != 3 {
t.Errorf("VCGT channels: got %d, want 3", p.VCGT.Channels)
}
// Verify monotonic non-decreasing per channel
for _, ch := range []struct {
name string
data []uint16
}{{"Red", p.VCGT.Red}, {"Green", p.VCGT.Green}, {"Blue", p.VCGT.Blue}} {
for i := 1; i < len(ch.data); i++ {
if ch.data[i] < ch.data[i-1] {
t.Errorf("VCGT %s not monotonic at index %d: %d < %d", ch.name, i, ch.data[i], ch.data[i-1])
break
}
}
}
}
// Log white point
t.Logf(" White point: [%6.4f %6.4f %6.4f]", p.WhitePoint[0], p.WhitePoint[1], p.WhitePoint[2])
})
}
}
func TestGenerateGammaRamp(t *testing.T) {
for _, tc := range testFiles {
t.Run(tc.name, func(t *testing.T) {
p, err := ParseFile(vendorProfile(t, tc.file))
if err != nil {
t.Fatalf("ParseFile failed: %v", err)
}
if !p.HasVCGT {
if _, err := GenerateGammaRamp(256, p); err == nil {
t.Error("expected an error for a profile without a vcgt table")
}
t.Skip("profile carries no vcgt table, so it has no ramp")
}
for _, rampSize := range []uint32{256, 4096} {
t.Run("size="+itoa(rampSize), func(t *testing.T) {
ramp, err := GenerateGammaRamp(rampSize, p)
if err != nil {
t.Fatalf("GenerateGammaRamp failed: %v", err)
}
// Verify lengths
if uint32(len(ramp.Red)) != rampSize {
t.Errorf("Red length: got %d, want %d", len(ramp.Red), rampSize)
}
if uint32(len(ramp.Green)) != rampSize {
t.Errorf("Green length: got %d, want %d", len(ramp.Green), rampSize)
}
if uint32(len(ramp.Blue)) != rampSize {
t.Errorf("Blue length: got %d, want %d", len(ramp.Blue), rampSize)
}
// Verify range [0, 65535]
channels := []struct {
name string
data []uint16
}{
{"Red", ramp.Red},
{"Green", ramp.Green},
{"Blue", ramp.Blue},
}
for _, ch := range channels {
// All values must be in [0, 65535] (uint16 guarantees this, but double-check)
for i, v := range ch.data {
if v > 65535 {
t.Errorf("%s[%d] = %d, out of range", ch.name, i, v)
break
}
}
// Verify ramp values match VCGT-derived data.
// Real VCGT calibration data does NOT guarantee ramp[0]==0
// or ramp[last]==65535 — these are gamma corrections.
// Log endpoints for inspection.
t.Logf(" %s: [%d ... %d]", ch.name, ch.data[0], ch.data[rampSize-1])
// Verify monotonic non-decreasing
for i := 1; i < len(ch.data); i++ {
if ch.data[i] < ch.data[i-1] {
t.Errorf("%s not monotonic at index %d: %d < %d", ch.name, i, ch.data[i], ch.data[i-1])
break
}
}
// ramp[last] >= ramp[0] (endpoints must be ordered)
if ch.data[rampSize-1] < ch.data[0] {
t.Errorf("%s: last value %d < first value %d", ch.name, ch.data[rampSize-1], ch.data[0])
}
}
})
}
})
}
}
func TestSampleCurve(t *testing.T) {
t.Run("Identity", func(t *testing.T) {
c := Curve{Type: CurveIdentity}
for _, tt := range []float64{0, 0.25, 0.5, 0.75, 1.0} {
got := SampleCurve(c, tt)
if got != tt {
t.Errorf("SampleCurve(identity, %f) = %f, want %f", tt, got, tt)
}
}
})
t.Run("Parametric", func(t *testing.T) {
c := Curve{Type: CurveParametric, Gamma: 2.2}
// pow(0.5, 1/2.2) ≈ 0.7297
got := SampleCurve(c, 0.5)
want := math.Pow(0.5, 1.0/2.2)
if math.Abs(got-want) > 0.001 {
t.Errorf("SampleCurve(gamma2.2, 0.5) = %f, want %f", got, want)
}
// Boundary conditions
if v := SampleCurve(c, 0); v != 0 {
t.Errorf("SampleCurve(gamma2.2, 0) = %f, want 0", v)
}
if v := SampleCurve(c, 1); v != 1 {
t.Errorf("SampleCurve(gamma2.2, 1) = %f, want 1", v)
}
})
t.Run("Table", func(t *testing.T) {
// Identity table: 2 entries [0, 65535]
c := Curve{
Type: CurveTable,
Entries: []uint16{0, 65535},
}
if v := SampleCurve(c, 0.5); math.Abs(v-0.5) > 0.001 {
t.Errorf("SampleCurve(identityTable, 0.5) = %f, want ~0.5", v)
}
// 4-entry table: [0, 21845, 43690, 65535] (approx 1/3, 2/3, 3/3)
c2 := Curve{
Type: CurveTable,
Entries: []uint16{0, 21845, 43690, 65535},
}
if v := SampleCurve(c2, 0); v != 0 {
t.Errorf("SampleCurve(4entry, 0) = %f, want 0", v)
}
if v := SampleCurve(c2, 1.0); math.Abs(v-1.0) > 0.001 {
t.Errorf("SampleCurve(4entry, 1.0) = %f, want ~1.0", v)
}
// 256-entry identity table
entries256 := make([]uint16, 256)
for i := range entries256 {
entries256[i] = uint16(i * 65535 / 255)
}
c3 := Curve{Type: CurveTable, Entries: entries256}
if v := SampleCurve(c3, 0.5); math.Abs(v-0.5) > 0.01 {
t.Errorf("SampleCurve(256entry, 0.5) = %f, want ~0.5", v)
}
})
t.Run("ClampInput", func(t *testing.T) {
c := Curve{Type: CurveIdentity}
// Negative t should be clamped to 0
if v := SampleCurve(c, -0.5); v != 0 {
t.Errorf("SampleCurve(identity, -0.5) = %f, want 0", v)
}
// t > 1 should be clamped to 1
if v := SampleCurve(c, 1.5); v != 1 {
t.Errorf("SampleCurve(identity, 1.5) = %f, want 1", v)
}
})
}
func TestParseBytes(t *testing.T) {
t.Run("TooShort", func(t *testing.T) {
_, err := ParseBytes([]byte{0, 1, 2})
if err == nil {
t.Error("expected error for short data")
}
})
}
// itoa converts a uint32 to string (avoids importing strconv)
func itoa(n uint32) string {
if n == 0 {
return "0"
}
digits := ""
for n > 0 {
digits = string(rune('0'+n%10)) + digits
n /= 10
}
return digits
}
// --- synthetic profile tests (self-contained; also cover CI) ---
func putS15Fixed16(b []byte, off int, v float64) {
binary.BigEndian.PutUint32(b[off:], uint32(int32(math.Round(v*65536))))
}
func putU8Fixed8(b []byte, off int, v float64) {
binary.BigEndian.PutUint16(b[off:], uint16(math.Round(v*256)))
}
// buildSyntheticProfile builds a minimal but valid ICC v2 monitor profile with
// desc, rXYZ/gXYZ/bXYZ, rTRC/gTRC/bTRC (single gamma per channel), wtpt and a
// table vcgt tag, so parsing and ramp generation can be exercised without a
// vendor profile on disk.
func buildSyntheticProfile(desc string, gamma float64) []byte {
xyzTag := func(x, y, z float64) []byte {
d := make([]byte, 20)
copy(d[0:], "XYZ ")
putS15Fixed16(d, 8, x)
putS15Fixed16(d, 12, y)
putS15Fixed16(d, 16, z)
return d
}
curvTag := func(g float64) []byte {
d := make([]byte, 16)
copy(d[0:], "curv")
binary.BigEndian.PutUint32(d[8:], 1) // count=1 -> single gamma value
putU8Fixed8(d, 12, g)
return d
}
descTag := make([]byte, 12+len(desc)+1)
copy(descTag[0:], "desc")
binary.BigEndian.PutUint32(descTag[8:], uint32(len(desc)+1)) // length includes NUL
copy(descTag[12:], desc)
const vcgtEntries = 4
vcgtTag := make([]byte, 18+3*vcgtEntries*2)
copy(vcgtTag[0:], "vcgt")
binary.BigEndian.PutUint16(vcgtTag[12:], 3) // channels
binary.BigEndian.PutUint16(vcgtTag[14:], vcgtEntries) // entries per channel
binary.BigEndian.PutUint16(vcgtTag[16:], 2) // entry size in bytes
for ch := 0; ch < 3; ch++ {
for i := 0; i < vcgtEntries; i++ {
v := uint16(math.Round(65535.0 * float64(i) / float64(vcgtEntries-1)))
binary.BigEndian.PutUint16(vcgtTag[18+(ch*vcgtEntries+i)*2:], v)
}
}
type tag struct {
sig string
data []byte
}
tags := []tag{
{"desc", descTag},
{"rXYZ", xyzTag(0.4360, 0.2225, 0.0139)},
{"gXYZ", xyzTag(0.3851, 0.7169, 0.0971)},
{"bXYZ", xyzTag(0.1431, 0.0606, 0.7141)},
{"rTRC", curvTag(gamma)},
{"gTRC", curvTag(gamma)},
{"bTRC", curvTag(gamma)},
{"wtpt", xyzTag(0.9642, 1.0, 0.8249)},
{"vcgt", vcgtTag},
}
const headerSize = 128
tableSize := 4 + 12*len(tags)
total := headerSize + tableSize
for _, tg := range tags {
total += len(tg.data)
}
buf := make([]byte, total)
binary.BigEndian.PutUint32(buf[0:], uint32(total))
binary.BigEndian.PutUint32(buf[8:], 0x02100000) // version 2.1.0
copy(buf[12:], "mntr")
copy(buf[16:], "RGB ")
copy(buf[20:], "XYZ ")
binary.BigEndian.PutUint16(buf[24:], 2026)
binary.BigEndian.PutUint16(buf[26:], 9)
binary.BigEndian.PutUint16(buf[28:], 10)
copy(buf[36:], "acsp")
putS15Fixed16(buf, 68, 0.9642) // D50 illuminant
putS15Fixed16(buf, 72, 1.0)
putS15Fixed16(buf, 76, 0.8249)
binary.BigEndian.PutUint32(buf[128:], uint32(len(tags)))
off := headerSize + tableSize
for i, tg := range tags {
base := 132 + i*12
copy(buf[base:], tg.sig)
binary.BigEndian.PutUint32(buf[base+4:], uint32(off))
binary.BigEndian.PutUint32(buf[base+8:], uint32(len(tg.data)))
copy(buf[off:], tg.data)
off += len(tg.data)
}
return buf
}
func TestParseBytesSynthetic(t *testing.T) {
const desc = "Synthetic Test Display"
data := buildSyntheticProfile(desc, 2.2)
p, err := ParseBytes(data)
if err != nil {
t.Fatalf("ParseBytes failed: %v", err)
}
if p.Size != uint32(len(data)) {
t.Errorf("Size = %d, want %d", p.Size, len(data))
}
if p.Version != "2.1.0" {
t.Errorf("Version = %q, want %q", p.Version, "2.1.0")
}
if p.Class != "mntr" {
t.Errorf("Class = %q, want %q", p.Class, "mntr")
}
if p.ColorSpace != "RGB" {
t.Errorf("ColorSpace = %q, want %q", p.ColorSpace, "RGB")
}
if p.Description != desc {
t.Errorf("Description = %q, want %q", p.Description, desc)
}
if !p.HasMatrix {
t.Error("HasMatrix = false, want true")
}
if !p.HasTRC {
t.Error("HasTRC = false, want true")
}
if !p.HasVCGT {
t.Error("HasVCGT = false, want true")
}
if got := p.TRC[0].Gamma; math.Abs(got-2.2) > 0.01 {
t.Errorf("TRC[0].Gamma = %f, want ~2.2", got)
}
if got := p.WhitePoint[0]; math.Abs(got-0.9642) > 0.001 {
t.Errorf("WhitePoint X = %f, want ~0.9642", got)
}
}
func TestGenerateGammaRampSynthetic(t *testing.T) {
p, err := ParseBytes(buildSyntheticProfile("Synthetic Test Display", 2.2))
if err != nil {
t.Fatalf("ParseBytes failed: %v", err)
}
const size = 256
ramp, err := GenerateGammaRamp(size, p)
if err != nil {
t.Fatalf("GenerateGammaRamp failed: %v", err)
}
if len(ramp.Red) != size || len(ramp.Green) != size || len(ramp.Blue) != size {
t.Fatalf("ramp lengths = %d/%d/%d, want %d", len(ramp.Red), len(ramp.Green), len(ramp.Blue), size)
}
if ramp.Red[size-1] <= ramp.Red[0] {
t.Errorf("ramp not increasing: first=%d last=%d", ramp.Red[0], ramp.Red[size-1])
}
}
// A profile without a vcgt table has no video card gamma ramp: the TRC tags
// describe the display's own transfer function, so writing them into the GPU
// LUT washes the output out instead of calibrating it.
func TestGenerateGammaRampRequiresVCGT(t *testing.T) {
trcOnly := &Profile{
HasTRC: true,
HasVCGT: false,
TRC: [3]Curve{
{Type: CurveParametric, Gamma: 2.2},
{Type: CurveParametric, Gamma: 2.2},
{Type: CurveParametric, Gamma: 2.2},
},
}
if _, err := GenerateGammaRamp(256, trcOnly); err == nil {
t.Fatal("expected an error for a profile without a vcgt table")
}
// A vcgt tag with no channel data is unusable in the same way.
emptyVCGT := &Profile{HasVCGT: true}
if _, err := GenerateGammaRamp(256, emptyVCGT); err == nil {
t.Fatal("expected an error for a profile without a vcgt table")
}
// The ramp size has to be at least 2: the values are spread over size-1.
if _, err := GenerateGammaRamp(1, &Profile{HasVCGT: true, VCGT: &VCGT{Channels: 3, Entries: 4}}); err == nil {
t.Fatal("expected an error for a ramp size below 2")
}
}
// TestParseDescriptionMalformed feeds desc/mluc tags whose offsets or lengths
// point outside the buffer. These must return an error or a clamped string
// instead of a slice-bounds panic: `dms icc list` parses every file in the
// profile directory and the daemon parses user-picked files in-process, so a
// panic here takes the whole daemon down.
func TestParseDescriptionMalformed(t *testing.T) {
descSig := [4]byte{'d', 'e', 's', 'c'}
mlucSig := [4]byte{'m', 'l', 'u', 'c'}
t.Run("desc length wraps past end", func(t *testing.T) {
data := make([]byte, 32)
copy(data[0:], "desc")
// 12 + 0xFFFFFFF8 wraps to 4 in uint32 arithmetic.
binary.BigEndian.PutUint32(data[8:], 0xFFFFFFF8)
if _, err := parseDescription(data, tagEntry{sig: descSig, offset: 0, size: 32}); err != nil {
t.Fatalf("expected clamped string, got error %v", err)
}
})
t.Run("desc length past end", func(t *testing.T) {
data := make([]byte, 24)
copy(data[0:], "desc")
binary.BigEndian.PutUint32(data[8:], 4096)
desc, err := parseDescription(data, tagEntry{sig: descSig, offset: 0, size: 24})
if err != nil {
t.Fatalf("expected clamped string, got error %v", err)
}
if desc != "" {
t.Errorf("expected empty description, got %q", desc)
}
})
t.Run("mluc record header past end", func(t *testing.T) {
data := make([]byte, 16)
copy(data[0:], "mluc")
binary.BigEndian.PutUint32(data[8:], 1) // numRecords
binary.BigEndian.PutUint32(data[12:], 12) // recordSize
if _, err := parseDescription(data, tagEntry{sig: mlucSig, offset: 0, size: 16}); err == nil {
t.Fatal("expected error for truncated mluc record header")
}
})
t.Run("mluc string offset past end", func(t *testing.T) {
data := make([]byte, 32)
copy(data[0:], "mluc")
binary.BigEndian.PutUint32(data[8:], 1) // numRecords
binary.BigEndian.PutUint32(data[12:], 12) // recordSize
binary.BigEndian.PutUint32(data[20:], 4) // string length
binary.BigEndian.PutUint32(data[24:], 0xFFFFFF00)
if _, err := parseDescription(data, tagEntry{sig: mlucSig, offset: 0, size: 32}); err == nil {
t.Fatal("expected error for out-of-bounds mluc string")
}
})
}
// TestParseBytesTagTableBounds feeds tag counts that do not fit in the file.
// The count sizes a slice before any entry is read, so a wrapping count has to
// be rejected up front: with tagCount*12 wrapping in uint32, a 140-byte profile
// passed the old bounds check, allocated a ~4 GB tag slice and then panicked
// with slice bounds out of range. ParseFile runs on the wayland actor goroutine,
// which has no recover(), so that panic took the dms daemon down at startup.
func TestParseBytesTagTableBounds(t *testing.T) {
t.Run("count wraps in uint32 arithmetic", func(t *testing.T) {
data := buildSyntheticProfile("Wrapping tag count", 2.2)
binary.BigEndian.PutUint32(data[128:132], 0x15555556) // *12 == 8
_, err := ParseBytes(data)
if err == nil {
t.Fatal("expected error for a tag count that does not fit in the profile")
}
if !strings.Contains(err.Error(), "tag entries") {
t.Fatalf("ParseBytes() error = %v, want a tag entry count error", err)
}
})
t.Run("count exceeds remaining bytes", func(t *testing.T) {
data := buildSyntheticProfile("Too many tags", 2.2)
binary.BigEndian.PutUint32(data[128:132], uint32((len(data)-132)/12+1))
_, err := ParseBytes(data)
if err == nil {
t.Fatal("expected error for more tag entries than the profile can hold")
}
if !strings.Contains(err.Error(), "tag entries") {
t.Fatalf("ParseBytes() error = %v, want a tag entry count error", err)
}
})
t.Run("count filling the file exactly still parses", func(t *testing.T) {
data := buildSyntheticProfile("Exact fit", 2.2)
binary.BigEndian.PutUint32(data[128:132], uint32((len(data)-132)/12))
if _, err := ParseBytes(data); err != nil {
t.Fatalf("ParseBytes() = %v, want the boundary count accepted", err)
}
})
}
func vcgtTableTag(channels int, entries []uint16) []byte {
tag := make([]byte, 18+channels*len(entries)*2)
copy(tag[0:], "vcgt")
binary.BigEndian.PutUint16(tag[12:], uint16(channels))
binary.BigEndian.PutUint16(tag[14:], uint16(len(entries)))
binary.BigEndian.PutUint16(tag[16:], 2)
for ch := 0; ch < channels; ch++ {
for i, v := range entries {
binary.BigEndian.PutUint16(tag[18+(ch*len(entries)+i)*2:], v)
}
}
return tag
}
func TestParseVCGTChannelCount(t *testing.T) {
entries := []uint16{0, 21845, 43690, 65535}
t.Run("one channel is replicated to all three", func(t *testing.T) {
tag := vcgtTableTag(1, entries)
vcgt, err := parseVCGT(tag, tagEntry{offset: 0, size: uint32(len(tag))})
if err != nil {
t.Fatalf("parseVCGT: %v", err)
}
if !slices.Equal(vcgt.Red, entries) {
t.Fatalf("red = %v, want %v", vcgt.Red, entries)
}
if !slices.Equal(vcgt.Green, entries) || !slices.Equal(vcgt.Blue, entries) {
t.Fatalf("green/blue must copy the single curve: green=%v blue=%v", vcgt.Green, vcgt.Blue)
}
})
t.Run("three channels are read independently", func(t *testing.T) {
tag := vcgtTableTag(3, entries)
vcgt, err := parseVCGT(tag, tagEntry{offset: 0, size: uint32(len(tag))})
if err != nil {
t.Fatalf("parseVCGT: %v", err)
}
if !slices.Equal(vcgt.Blue, entries) {
t.Fatalf("blue = %v, want %v", vcgt.Blue, entries)
}
})
for _, channels := range []int{0, 2, 4} {
t.Run(fmt.Sprintf("%d channels are rejected", channels), func(t *testing.T) {
tag := vcgtTableTag(channels, entries)
if _, err := parseVCGT(tag, tagEntry{offset: 0, size: uint32(len(tag))}); err == nil {
t.Fatalf("expected an error for a %d-channel vcgt", channels)
}
})
}
}