diff --git a/bin/omarchy-hyprland-monitor-capabilities b/bin/omarchy-hyprland-monitor-capabilities new file mode 100755 index 000000000000..473ffd55b462 --- /dev/null +++ b/bin/omarchy-hyprland-monitor-capabilities @@ -0,0 +1,110 @@ +#!/bin/bash + +# omarchy:summary=Report per-display HDR capability from EDID +# omarchy:group=hyprland +# omarchy:hidden=true +# omarchy:args=[OUTPUT] + +# Hyprland reports what a display is currently doing, not what it can do: +# `hyprctl monitors` has colorManagementPreset and sdrMaxLuminance, but nothing +# that says whether the panel understands HDR at all. Without that, a Display +# panel can only offer an HDR switch to every display and let the ones that +# cannot do it fail confusingly. +# +# The EDID does carry it. A display is treated as HDR-capable when it publishes +# an HDR Static Metadata Data Block advertising the PQ transfer function +# (SMPTE ST2084); that block also carries the mastering luminances Hyprland +# wants for max_luminance / max_avg_luminance / min_luminance, so the same read +# both gates the control and supplies sensible values for it. +# +# Prints one JSON object per line, or a single object when given an output. + +set -euo pipefail + +connector_edid() { + local output="$1" + local path + + # sysfs reports these as zero-length regardless of content, so an `-s` test + # would reject every real EDID; read it to find out whether it has one. + for path in /sys/class/drm/card*/card*-"$output"; do + [[ -r $path/edid ]] || continue + (($(wc -c <"$path/edid") > 0)) || continue + printf '%s\n' "$path/edid" + return 0 + done + + return 1 +} + +capabilities_for() { + local output="$1" + local edid decoded block + + if ! edid=$(connector_edid "$output"); then + jq -nc --arg name "$output" '{name: $name, hdr: false, reason: "no-edid"}' + return 0 + fi + + # A missing decoder would otherwise read as "this display has no PQ block", + # which is indistinguishable from a genuinely SDR panel: the HDR switch would + # simply never appear and nothing would say why. + if omarchy-cmd-missing edid-decode; then + jq -nc --arg name "$output" '{name: $name, hdr: false, reason: "no-decoder"}' + return 0 + fi + + decoded=$(edid-decode "$edid" 2>/dev/null) || decoded="" + block=$(printf '%s\n' "$decoded" | sed -n '/HDR Static Metadata Data Block:/,/^ [A-Za-z]/p') + + if [[ -z $block ]] || ! grep -q "SMPTE ST2084" <<<"$block"; then + jq -nc --arg name "$output" '{name: $name, hdr: false, reason: "no-pq-eotf"}' + return 0 + fi + + # edid-decode prints "Desired content max luminance: 138 (993.486 cd/m^2)"; + # the parenthesised value is the one Hyprland's luminance fields expect. + local peak average floor + peak=$(sed -n 's/.*Desired content max luminance:.*(\([0-9.]*\) cd\/m\^2).*/\1/p' <<<"$block" | head -1) + average=$(sed -n 's/.*Desired content max frame-average luminance:.*(\([0-9.]*\) cd\/m\^2).*/\1/p' <<<"$block" | head -1) + floor=$(sed -n 's/.*Desired content min luminance:.*(\([0-9.]*\) cd\/m\^2).*/\1/p' <<<"$block" | head -1) + + jq -nc \ + --arg name "$output" \ + --arg peak "${peak:-}" \ + --arg average "${average:-}" \ + --arg floor "${floor:-}" \ + '{ + name: $name, + hdr: true, + max_luminance: (if $peak == "" then null else ($peak | tonumber | round) end), + max_avg_luminance: (if $average == "" then null else ($average | tonumber | round) end), + min_luminance: (if $floor == "" then null else ($floor | tonumber) end) + }' +} + +case "${1:-}" in +-h | --help) + cat <<'USAGE' +Usage: omarchy-hyprland-monitor-capabilities [OUTPUT] + +Prints what a display advertises about HDR in its EDID, as JSON. With no +OUTPUT, prints one line per connected display. +USAGE + exit 0 + ;; +# A display is never named like a flag, so answering one as if it were a +# display would report a confident "no HDR" for a typo. +-*) + echo "Error: unknown option: $1" >&2 + exit 1 + ;; +esac + +if (($# >= 1)); then + capabilities_for "$1" +else + while read -r name; do + [[ -n $name ]] && capabilities_for "$name" + done < <(hyprctl monitors all -j 2>/dev/null | jq -r '.[].name') +fi diff --git a/bin/omarchy-hyprland-monitor-hdr b/bin/omarchy-hyprland-monitor-hdr new file mode 100755 index 000000000000..84c4746d537f --- /dev/null +++ b/bin/omarchy-hyprland-monitor-hdr @@ -0,0 +1,264 @@ +#!/bin/bash + +# omarchy:summary=Show or set per-display HDR +# omarchy:group=hyprland +# omarchy:args=[on|off|status] [--monitor OUTPUT] [--sdr-brightness NITS] [--force] +# omarchy:examples=omarchy hyprland monitor hdr | omarchy hyprland monitor hdr on | omarchy hyprland monitor hdr --sdr-brightness 250 --monitor DP-1 + +# HDR is per display, so this never touches the catch-all rule: everything is +# written through omarchy-hyprland-monitor-rule against one output. +# +# Two different brightness controls exist once HDR is on, and conflating them is +# the thing to avoid: +# +# * omarchy-brightness-display drives the panel's own backlight (or DDC/CI on +# an external). It dims everything the display shows, HDR highlights +# included, and is what the brightness keys use. +# * sdr_max_luminance, set here, is a compositor mapping: it decides how +# bright plain SDR white is inside the HDR volume. It moves SDR content +# only and leaves HDR highlights where the display put them. +# +# So on an HDR display the two are complementary rather than alternatives, and +# the Display panel shows both rather than silently repurposing one slider. +# +# Panels dim under sustained full-field load (ABL), so a comfortable default for +# SDR white sits below the EDID's max frame-average luminance rather than at the +# peak, which only applies to small highlights. + +set -euo pipefail + +# Fraction of the display's sustained full-field luminance to map SDR white to +# by default. Below the ABL ceiling, so a full white window does not visibly +# dim as the panel pulls power back. +SDR_DEFAULT_FRACTION=0.8 +SDR_DEFAULT_FLOOR=80 +SDR_DEFAULT_CEILING=300 + +usage() { + cat <<'USAGE' +Usage: omarchy-hyprland-monitor-hdr [on|off|status] [--monitor OUTPUT] + [--sdr-brightness NITS] [--force] + + on Enable HDR: 10-bit, wide colour, and the luminances the display + advertises in its EDID. Existing tuned values are kept. + off Return the display to sRGB. Luminance values are left in place so + switching back restores your tuning. + status Print the display's HDR state as JSON. + +--sdr-brightness sets how bright SDR white is within the HDR volume +(sdr_max_luminance, in nits). This is not the backlight: use the brightness +keys or `omarchy brightness display` for that. + +Refuses to enable HDR on a display whose EDID does not advertise it, unless +--force is given. +USAGE +} + +action="" monitor="" sdr_brightness="" force=0 + +while (($#)); do + case "$1" in + on | off | status) + action="$1" + shift + ;; + --monitor) + (($# >= 2)) || { + echo "Error: --monitor needs a value." >&2 + exit 1 + } + monitor="$2" + shift 2 + ;; + --monitor=*) + monitor="${1#*=}" + [[ -n $monitor ]] || { + echo "Error: --monitor needs a value." >&2 + exit 1 + } + shift + ;; + --sdr-brightness) + (($# >= 2)) || { + echo "Error: --sdr-brightness needs a value." >&2 + exit 1 + } + sdr_brightness="$2" + shift 2 + ;; + --sdr-brightness=*) + sdr_brightness="${1#*=}" + [[ -n $sdr_brightness ]] || { + echo "Error: --sdr-brightness needs a value." >&2 + exit 1 + } + shift + ;; + --force) + force=1 + shift + ;; + -h | --help) + usage + exit 0 + ;; + *) + usage >&2 + exit 1 + ;; + esac +done + +monitors_json=$(hyprctl monitors all -j) + +if [[ -z $monitor ]]; then + monitor=$(printf '%s\n' "$monitors_json" | jq -r '[.[] | select(.focused == true)][0].name // ""') +fi + +if [[ -z $monitor ]]; then + echo "Error: no display selected." >&2 + exit 1 +fi + +monitor_json=$(printf '%s\n' "$monitors_json" | jq -c --arg name "$monitor" '[.[] | select(.name == $name)][0] // empty') + +if [[ -z $monitor_json ]]; then + echo "Error: no such display: $monitor" >&2 + exit 1 +fi + +capabilities=$(omarchy-hyprland-monitor-capabilities "$monitor") +hdr_capable=$(jq -r '.hdr' <<<"$capabilities") +current_preset=$(jq -r '.colorManagementPreset // "srgb"' <<<"$monitor_json") + +print_status() { + jq -nc \ + --argjson monitor "$monitor_json" \ + --argjson capabilities "$capabilities" \ + '{ + name: $monitor.name, + enabled: ($monitor.colorManagementPreset == "hdr"), + preset: $monitor.colorManagementPreset, + capable: $capabilities.hdr, + format: $monitor.currentFormat, + sdr_max_luminance: $monitor.sdrMaxLuminance, + sdr_brightness: $monitor.sdrBrightness, + sdr_saturation: $monitor.sdrSaturation, + max_luminance: $capabilities.max_luminance, + max_avg_luminance: $capabilities.max_avg_luminance, + min_luminance: $capabilities.min_luminance + }' +} + +# Only write a field the user has not already set, so enabling HDR does not +# discard luminances someone tuned by hand. +set_unless_present() { + local field="$1" value="$2" + + [[ -n $value && $value != "null" ]] || return 0 + [[ -z $(omarchy-hyprland-monitor-rule get "$monitor" "$field") ]] || return 0 + + rule_fields+=("$field=$value") +} + +default_sdr_brightness() { + local average + average=$(jq -r '.max_avg_luminance // empty' <<<"$capabilities") + + if [[ -z $average ]]; then + printf '%s\n' "$SDR_DEFAULT_FLOOR" + return 0 + fi + + awk -v average="$average" -v fraction="$SDR_DEFAULT_FRACTION" \ + -v floor="$SDR_DEFAULT_FLOOR" -v ceiling="$SDR_DEFAULT_CEILING" 'BEGIN { + value = int(average * fraction + 0.5) + if (value < floor) value = floor + if (value > ceiling) value = ceiling + print value + }' +} + +apply_live() { + local assignments="$1" + + hyprctl eval "hl.monitor({ output = \"$monitor\", $assignments })" >/dev/null +} + +if [[ -z $action && -z $sdr_brightness ]]; then + print_status + exit 0 +fi + +# `status` prints, but asking for a brightness at the same time is still a +# request to set it -- dropping it silently is worse than either alone. +if [[ $action == "status" && -z $sdr_brightness ]]; then + print_status + exit 0 +fi + +rule_fields=() + +if [[ $action == "on" ]]; then + if [[ $hdr_capable != "true" ]] && ((force == 0)); then + echo "Error: $monitor does not advertise HDR support in its EDID." >&2 + echo "Use --force to enable it anyway." >&2 + exit 1 + fi + + rule_fields+=("cm=hdr" "bitdepth=10" "supports_hdr=1" "supports_wide_color=1") + set_unless_present max_luminance "$(jq -r '.max_luminance // empty' <<<"$capabilities")" + set_unless_present max_avg_luminance "$(jq -r '.max_avg_luminance // empty' <<<"$capabilities")" + set_unless_present min_luminance "$(jq -r '.min_luminance // empty' <<<"$capabilities")" + set_unless_present sdr_max_luminance "$(default_sdr_brightness)" +elif [[ $action == "off" ]]; then + # Luminance fields are inert under sRGB, so they stay: switching back on + # should restore the tuning rather than reset it to the EDID defaults. The + # capability flags are not inert -- leaving them on keeps the display + # advertising HDR and wide colour to clients after it has been turned off, + # a state this command could set but not undo. + rule_fields+=("cm=srgb" "bitdepth=8" "supports_hdr=0" "supports_wide_color=0") +fi + +if [[ -n $sdr_brightness ]]; then + if ! [[ $sdr_brightness =~ ^[0-9]+$ ]] || ((sdr_brightness < 1)); then + echo "Error: --sdr-brightness takes a whole number of nits." >&2 + exit 1 + fi + + if [[ $action != "on" && $current_preset != "hdr" ]]; then + echo "Note: $monitor is not in HDR, so SDR brightness has no visible effect yet." >&2 + fi + + # An explicit value replaces whatever is there, unlike the defaults above. + rule_fields=("${rule_fields[@]/#sdr_max_luminance=*/}") + rule_fields+=("sdr_max_luminance=$sdr_brightness") +fi + +# Drop any entries blanked out above. +filtered=() +for field in "${rule_fields[@]}"; do + [[ -n $field ]] && filtered+=("$field") +done +rule_fields=("${filtered[@]}") + +((${#rule_fields[@]})) || exit 0 + +assignments="" +for field in "${rule_fields[@]}"; do + name="${field%%=*}" + value="${field#*=}" + [[ -n $assignments ]] && assignments+=", " + if [[ $value =~ ^-?[0-9]+(\.[0-9]+)?$ ]]; then + assignments+="$name = $value" + else + assignments+="$name = \"$value\"" + fi +done + +apply_live "$assignments" +omarchy-hyprland-monitor-rule set "$monitor" "${rule_fields[@]}" + +# Re-read so the printed state reflects what the compositor actually accepted. +monitor_json=$(hyprctl monitors all -j | jq -c --arg name "$monitor" '[.[] | select(.name == $name)][0] // empty') +print_status diff --git a/bin/omarchy-hyprland-monitor-rotate b/bin/omarchy-hyprland-monitor-rotate new file mode 100755 index 000000000000..7f089f28c069 --- /dev/null +++ b/bin/omarchy-hyprland-monitor-rotate @@ -0,0 +1,165 @@ +#!/bin/bash + +# omarchy:summary=Show or set display rotation +# omarchy:group=hyprland +# omarchy:args=[0|90|180|270|left|right|flip] [--monitor OUTPUT] [--flipped] [--no-tidy] +# omarchy:examples=omarchy hyprland monitor rotate | omarchy hyprland monitor rotate 90 | omarchy hyprland monitor rotate 0 --monitor DP-3 + +# Rotation is a `transform` on the Hyprland monitor rule, which is an integer +# 0-7 rather than an angle: 0-3 are the plain rotations and 4-7 repeat them +# mirrored. Users think in degrees, so this speaks degrees and keeps the +# mirrored half behind --flipped. +# +# The change is applied live with `hyprctl eval` and persisted per display via +# omarchy-hyprland-monitor-rule, so it survives a reload without touching any +# other display's rule. + +set -euo pipefail + +usage() { + cat <<'USAGE' +Usage: omarchy-hyprland-monitor-rotate [ROTATION] [--monitor OUTPUT] [--flipped] + +Rotations: 0 / normal, 90 / left, 180 / flip, 270 / right. +Add --flipped to mirror the display as well as rotating it, and --no-flipped +to stop mirroring. An already-mirrored display stays mirrored otherwise. + +Displays that the turn would collide with are moved clear first; --no-tidy +leaves every position alone. + +With no rotation, prints the current one in degrees. +USAGE +} + +rotation="" monitor="" flipped=0 unflip=0 tidy=1 + +while (($#)); do + case "$1" in + --monitor) + (($# >= 2)) || { + echo "Error: --monitor needs a value." >&2 + exit 1 + } + monitor="$2" + shift 2 + ;; + --monitor=*) + monitor="${1#*=}" + [[ -n $monitor ]] || { + echo "Error: --monitor needs a value." >&2 + exit 1 + } + shift + ;; + --flipped) + flipped=1 + shift + ;; + --no-tidy) + tidy=0 + shift + ;; + --no-flipped) + flipped=0 + unflip=1 + shift + ;; + -h | --help) + usage + exit 0 + ;; + *) + if [[ -n $rotation ]]; then + usage >&2 + exit 1 + fi + rotation="$1" + shift + ;; + esac +done + +monitors_json=$(hyprctl monitors all -j) + +if [[ -z $monitor ]]; then + monitor=$(printf '%s\n' "$monitors_json" | jq -r '[.[] | select(.focused == true)][0].name // ""') +fi + +if [[ -z $monitor ]]; then + echo "Error: no display to rotate." >&2 + exit 1 +fi + +if ! printf '%s\n' "$monitors_json" | jq -e --arg name "$monitor" 'any(.[]; .name == $name)' >/dev/null; then + echo "Error: no such display: $monitor" >&2 + exit 1 +fi + +current_transform=$(printf '%s\n' "$monitors_json" | + jq -r --arg name "$monitor" '[.[] | select(.name == $name)][0].transform // 0') + +# Transforms 4-7 are the mirrored counterparts of 0-3, so the angle is the +# transform modulo 4 scaled by 90. +degrees_for_transform() { + echo $((($1 % 4) * 90)) +} + +# With no rotation there is nothing to turn, but --flipped/--no-flipped are +# still a request to change the mirroring, so only a bare call just reports. +if [[ -z $rotation ]] && ((flipped == 0 && unflip == 0)); then + degrees_for_transform "$current_transform" + exit 0 +fi + +# Flipping on its own keeps whatever angle the display already has. +if [[ -z $rotation ]]; then + rotation=$(degrees_for_transform "$current_transform") +fi + +case "${rotation,,}" in +0 | normal | none) base=0 ;; +90 | left) base=1 ;; +180 | flip | inverted | upside-down) base=2 ;; +270 | right) base=3 ;; +*) + echo "Error: unsupported rotation: $rotation" >&2 + usage >&2 + exit 1 + ;; +esac + +# Keep the display mirrored if it already was and the caller did not say +# otherwise, so rotating a mirrored display does not silently unmirror it. +# --no-flipped is the way back, since degrees alone cannot express it. +if ((flipped)) || { ((current_transform >= 4)) && ((unflip == 0)); }; then + transform=$((base + 4)) +else + transform=$base +fi + +# A quarter turn swaps how much desk space the display takes up, but nothing +# else moves to make room. Hyprland notifies the instant two displays overlap +# and that warning stays up after the layout is valid again, so the neighbours +# have to be clear BEFORE the display grows into them -- repairing afterwards is +# too late. +# +# Only a turn that widens the display along the layout axis can collide, and +# only then is a clearance pass needed. A turn that narrows it just opens a gap, +# which is not an error and is left alone. +if ((tidy)); then + turned=$(printf '%s\n' "$monitors_json" | + jq -c --arg name "$monitor" --argjson transform "$transform" \ + '[.[] | if .name == $name then .transform = $transform else . end]') + + omarchy-hyprland-monitor-tidy apply --intended "$turned" >/dev/null || true +fi + +hyprctl eval "hl.monitor({ output = \"$monitor\", transform = $transform })" >/dev/null + +omarchy-hyprland-monitor-rule set "$monitor" "transform=$transform" + +# The turn itself can leave the display overlapping something the clearance +# pass could not predict, so settle the layout once more. +((tidy)) && omarchy-hyprland-monitor-tidy apply >/dev/null || true + +degrees_for_transform "$transform" diff --git a/bin/omarchy-hyprland-monitor-rule b/bin/omarchy-hyprland-monitor-rule new file mode 100755 index 000000000000..a3ce9cab459d --- /dev/null +++ b/bin/omarchy-hyprland-monitor-rule @@ -0,0 +1,497 @@ +#!/bin/bash + +# omarchy:summary=Read and write per-display fields in monitors.lua +# omarchy:group=hyprland +# omarchy:hidden=true +# omarchy:args=get | set ... | unset ... | path +# omarchy:examples=omarchy hyprland monitor rule get DP-1 transform | omarchy hyprland monitor rule set DP-1 cm=hdr bitdepth=10 + +# Every per-display setting in the Display panel has to survive a reboot, which +# means editing the user's own ~/.config/hypr/monitors.lua rather than only +# calling `hyprctl eval`. Doing that with sed is what produced #6673: the scale +# writer matched the catch-all `omarchy_monitor_scale` line and so persisted one +# display's choice to every display. This command exists so each caller can name +# the display it means and touch nothing else. +# +# Rules are matched by `output`, against both the connector name (DP-1) and a +# `desc:` string the user may have written instead, so a hand-written config +# keeps the identifier its author chose. The catch-all rule (`output = ""`) is +# never matched for a specific display -- it speaks for all of them, and editing +# it is precisely the bug above. + +set -euo pipefail + +MONITOR_LUA="${OMARCHY_MONITOR_LUA:-$HOME/.config/hypr/monitors.lua}" + +usage() { + cat <<'USAGE' +Usage: omarchy-hyprland-monitor-rule get + omarchy-hyprland-monitor-rule set ... + omarchy-hyprland-monitor-rule unset ... + omarchy-hyprland-monitor-rule path + +Values are typed the way Lua expects them: numbers and true/false are written +bare, anything else is quoted. Prefix a value with `raw:` to write it verbatim. + +`set` creates a rule for the display if none exists, seeding it with the live +mode, position, and scale so the new rule does not silently drop the geometry +the display is already using. +USAGE +} + +# The Lua editing is real parsing, not pattern matching: rules are written both +# inline and spread over many lines, and a rule can contain comments and nested +# tables. python3 is already a dependency of several bin/ commands. +edit_rule() { + python3 - "$MONITOR_LUA" "$@" <<'PYTHON' +import json +import os +import re +import shutil +import sys +import time + +path, action, output = sys.argv[1], sys.argv[2], sys.argv[3] +args = sys.argv[4:] + + +def read(path): + if not os.path.exists(path): + return "" + # newline="" so CRLF files are not silently rewritten as LF. + with open(path, encoding="utf-8", newline="") as handle: + return handle.read() + + +def long_bracket_level(text, index): + """Level of a Lua long bracket opening at index, or None.""" + if index >= len(text) or text[index] != "[": + return None + cursor = index + 1 + while cursor < len(text) and text[cursor] == "=": + cursor += 1 + if cursor < len(text) and text[cursor] == "[": + return cursor - index - 1 + return None + + +def long_bracket_end(text, index, level): + closing = "]" + "=" * level + "]" + found = text.find(closing, index) + return len(text) if found == -1 else found + len(closing) + + +def code_mask(text): + """True for each character that is real code, False inside comments and + strings. + + Everything structural is decided through this: which braces count, where a + value ends, and whether an hl.monitor call is live or commented out. Without + it a --[[ ]] block comment reads as a line comment, so a commented-out + example gets edited as though it were the real rule. + """ + mask = [True] * len(text) + index = 0 + while index < len(text): + if text.startswith("--", index): + level = long_bracket_level(text, index + 2) + if level is None: + newline = text.find("\n", index) + end = len(text) if newline == -1 else newline + else: + end = long_bracket_end(text, index + 2 + level + 2, level) + for position in range(index, end): + mask[position] = False + index = end + continue + + if text[index] in "\"'": + quote = text[index] + cursor = index + 1 + while cursor < len(text) and text[cursor] != quote: + cursor += 2 if text[cursor] == "\\" else 1 + end = min(cursor + 1, len(text)) + for position in range(index, end): + mask[position] = False + index = end + continue + + level = long_bracket_level(text, index) + if level is not None: + end = long_bracket_end(text, index + level + 2, level) + for position in range(index, end): + mask[position] = False + index = end + continue + + index += 1 + return mask + + +def find_calls(text, mask): + """Yield (start, body_start, body_end, end) for each live hl.monitor call.""" + for match in re.finditer(r"hl\.monitor\s*\(\s*\{", text): + if not mask[match.start()]: + continue + index = match.end() + depth = 1 + body_start = index + while index < len(text) and depth: + if mask[index]: + if text[index] == "{": + depth += 1 + elif text[index] == "}": + depth -= 1 + if not depth: + break + index += 1 + if depth: + continue + body_end = index + close = text.find(")", body_end) + yield match.start(), body_start, body_end, (close + 1 if close != -1 else body_end + 1) + + +def field_span(text, mask, start, end, field): + """Absolute (name_start, value_start, value_end) for a top-level field.""" + depth = 0 + index = start + while index < end: + if not mask[index]: + index += 1 + continue + char = text[index] + if char in "{(": + depth += 1 + elif char in "})": + depth -= 1 + elif depth == 0: + match = re.match(r"([A-Za-z_][A-Za-z0-9_]*)\s*=", text[index:end]) + if match: + if match.group(1) == field: + value_start = index + match.end() + cursor = value_start + value_depth = 0 + while cursor < end: + if not mask[cursor]: + cursor += 1 + continue + inner = text[cursor] + if inner in "{(": + value_depth += 1 + elif inner in "})": + if value_depth == 0: + break + value_depth -= 1 + elif inner == "," and value_depth == 0: + break + cursor += 1 + return index, value_start, cursor + index += match.end() + continue + index += 1 + return None + + +def field_value(text, mask, start, end, field): + span = field_span(text, mask, start, end, field) + if not span: + return None + return text[span[1]:span[2]].strip() + + +def last_field_end(text, mask, start, end): + """End of the final top-level field, which is where a new one is inserted. + + Not the end of the body: a rule commonly ends `vrr = 0, -- why`, and + appending past that puts the separating comma inside the comment where Lua + cannot see it. + """ + last = None + depth = 0 + index = start + while index < end: + if not mask[index]: + index += 1 + continue + char = text[index] + if char in "{(": + depth += 1 + elif char in "})": + depth -= 1 + elif depth == 0: + match = re.match(r"([A-Za-z_][A-Za-z0-9_]*)\s*=", text[index:end]) + if match: + span = field_span(text, mask, index, end, match.group(1)) + if span: + last = span[2] if last is None else max(last, span[2]) + index += match.end() + continue + index += 1 + return last + + +def unquote(value): + if value and value[0] in "\"'" and value[-1] == value[0]: + return value[1:-1] + return value + + +def lua_value(raw): + if raw.startswith("raw:"): + return raw[4:] + if re.fullmatch(r"-?\d+(\.\d+)?", raw) or raw in ("true", "false", "nil"): + return raw + return "\"%s\"" % raw.replace("\\", "\\\\").replace("\"", "\\\"") + + +def aliases_for(output): + names = set() + raw = os.environ.get("OMARCHY_MONITOR_DESCRIPTIONS", "") + try: + for entry in json.loads(raw) if raw else []: + if entry.get("name") == output: + description = entry.get("description", "") + if description: + names.add("desc:" + description) + except (ValueError, AttributeError): + pass + return names + + +text = read(path) +mask = code_mask(text) +aliases = aliases_for(output) + + +def rule_matches(body_start, body_end): + value = field_value(text, mask, body_start, body_end, "output") + if value is None: + return False + name = unquote(value) + # The catch-all speaks for every display; a per-display edit must never land + # on it. That conflation is bug #6673. + if name == "": + return False + return name == output or name in aliases + + +target = None +for start, body_start, body_end, end in find_calls(text, mask): + if rule_matches(body_start, body_end): + target = (start, body_start, body_end, end) + +if action == "get": + if target is not None: + value = field_value(text, mask, target[1], target[2], args[0]) + if value is not None: + print(unquote(value)) + sys.exit(0) + +if target is None and action == "unset": + sys.exit(0) + +if target is None: + # No rule for this display yet. Seed one from the live geometry: a rule that + # omits position does not inherit the catch-all one, so a bare rule here + # would move the display to 0x0 on the next reload. + seed = os.environ.get("OMARCHY_MONITOR_SEED", "") + fields = ["output = \"%s\"" % output] + try: + live = json.loads(seed) if seed else {} + except ValueError: + live = {} + for key in ("mode", "position", "scale"): + if live.get(key) not in (None, ""): + fields.append("%s = %s" % (key, lua_value(str(live[key])))) + rule = "hl.monitor({ %s })" % ", ".join(fields) + text = text.rstrip("\n") + "\n\n" + rule + "\n" + mask = code_mask(text) + for start, body_start, body_end, end in find_calls(text, mask): + if rule_matches(body_start, body_end): + target = (start, body_start, body_end, end) + +start, body_start, body_end, end = target + +for argument in args: + if action == "unset": + field, value = argument, None + else: + field, _, raw = argument.partition("=") + field, value = field.strip(), lua_value(raw) + + span = field_span(text, mask, body_start, body_end, field) + body = text[body_start:body_end] + multiline = "\n" in body.strip() + indent = " " + if multiline: + for line in body.splitlines(): + if line.strip() and re.match(r"\s", line): + indent = re.match(r"\s*", line).group(0) + break + + if action == "unset": + if not span: + continue + head, _, tail = span + remainder = text[tail:body_end] + trailing = re.match(r"\s*,[ \t]*(\r?\n)?", remainder) + if trailing: + cut = tail + trailing.end() + if trailing.group(1) and text[:head].rstrip(" \t").endswith("\n"): + head = len(text[:head].rstrip(" \t")) + else: + # Nothing follows, so the separator that mattered was in front; + # leaving it behind would strand a comma before the brace. + preceding = re.search(r",[ \t]*$", text[body_start:head]) + if preceding: + head = body_start + preceding.start() + cut = tail + replacement = "" + if not multiline and not text[cut:body_end].strip(): + replacement = " " + text = text[:head] + replacement + text[cut:] + removed = (cut - head) - len(replacement) + body_end -= removed + mask = code_mask(text) + continue + + if span: + # Keep the spacing the author used, so replacing a value does not reflow + # the line around it. + original = text[span[1]:span[2]] + lead = re.match(r"\s*", original).group(0) or " " + tail_space = re.search(r"\s*$", original).group(0) + text = text[:span[1]] + lead + value + tail_space + text[span[2]:] + body_end += len(lead + value + tail_space) - len(original) + mask = code_mask(text) + continue + + insert_at = last_field_end(text, mask, body_start, body_end) + if insert_at is None: + addition = ("\n" + indent if multiline else " ") + field + " = " + value + ("," if multiline else " ") + text = text[:body_start] + addition + text[body_start:] + body_end += len(addition) + mask = code_mask(text) + continue + + # The separator and the new field belong in two different places. The comma + # goes straight after the previous value, while the field goes on its own + # line after anything already trailing that line. + following = re.match(r"[ \t]*,", text[insert_at:body_end]) + separator = "" if following else "," + after_separator = insert_at + (following.end() if following else 0) + + if multiline: + newline = text.find("\n", after_separator) + line_end = body_end if newline == -1 or newline > body_end else newline + addition = separator + text = (text[:insert_at] + separator + text[insert_at:line_end] + + "\n" + indent + field + " = " + value + "," + text[line_end:]) + body_end += len(separator) + len("\n" + indent + field + " = " + value + ",") + else: + # A one-line rule keeps its single space before the closing brace. + head = text[:insert_at].rstrip() + trimmed = len(text[:insert_at]) - len(head) + tail_text = text[after_separator:body_end] + closing = tail_text if tail_text.strip() else " " + addition = separator + " " + field + " = " + value + closing + text = head + addition + text[body_end:] + body_end = len(head) + len(addition) + mask = code_mask(text) + +original_text = read(path) +if text != original_text: + if os.path.exists(path) and not os.path.isfile(path): + sys.stderr.write("Error: %s is not a regular file.\n" % path) + sys.exit(1) + + # Write through a symlink rather than replacing it, so a monitors.lua linked + # from a dotfiles repo keeps pointing at its source. + resolved = os.path.realpath(path) + try: + if os.path.exists(resolved): + shutil.copy2(resolved, "%s.bak.%d" % (resolved, int(time.time()))) + directory = os.path.dirname(resolved) or "." + os.makedirs(directory, exist_ok=True) + temporary = "%s.tmp.%d" % (resolved, os.getpid()) + with open(temporary, "w", encoding="utf-8", newline="") as handle: + handle.write(text) + os.replace(temporary, resolved) + + # Keep the backups from growing without bound in the config directory. + backups = sorted( + name for name in os.listdir(directory) + if name.startswith(os.path.basename(resolved) + ".bak.") + ) + for stale in backups[:-5]: + try: + os.remove(os.path.join(directory, stale)) + except OSError: + pass + except OSError as error: + sys.stderr.write("Error: could not update %s: %s\n" % (path, error)) + sys.exit(1) +PYTHON +} + +# Live geometry for a display the config does not mention yet, plus the +# descriptions needed to recognise a `desc:` rule as the same display. +export_live_state() { + local output="$1" + local monitors + + # Pre-set values win, so tests and offline callers can describe a display + # without a compositor to ask. + if [[ -n ${OMARCHY_MONITOR_DESCRIPTIONS:-} && -n ${OMARCHY_MONITOR_SEED:-} ]]; then + export OMARCHY_MONITOR_DESCRIPTIONS OMARCHY_MONITOR_SEED + return 0 + fi + + monitors=$(hyprctl monitors all -j 2>/dev/null) || monitors="[]" + + OMARCHY_MONITOR_DESCRIPTIONS=$(printf '%s' "$monitors" | + jq -c '[.[] | {name, description}]' 2>/dev/null || echo "[]") + OMARCHY_MONITOR_SEED=$(printf '%s' "$monitors" | + jq -c --arg name "$output" ' + [.[] | select(.name == $name)][0] // {} | + if . == {} then {} else { + mode: "\(.width)x\(.height)@\(.refreshRate | . * 100 | round / 100)", + position: "\(.x)x\(.y)", + scale: (.scale | tostring) + } end' 2>/dev/null || echo "{}") + + export OMARCHY_MONITOR_DESCRIPTIONS OMARCHY_MONITOR_SEED +} + +case "${1:-}" in +get) + (($# == 3)) || { + usage >&2 + exit 1 + } + export_live_state "$2" + edit_rule get "$2" "$3" + ;; +set | unset) + (($# >= 3)) || { + usage >&2 + exit 1 + } + action="$1" + output="$2" + shift 2 + export_live_state "$output" + edit_rule "$action" "$output" "$@" + ;; +path) + printf '%s\n' "$MONITOR_LUA" + ;; +-h | --help) + usage + ;; +*) + usage >&2 + exit 1 + ;; +esac diff --git a/bin/omarchy-hyprland-monitor-tidy b/bin/omarchy-hyprland-monitor-tidy new file mode 100755 index 000000000000..e33d9a9394b0 --- /dev/null +++ b/bin/omarchy-hyprland-monitor-tidy @@ -0,0 +1,239 @@ +#!/bin/bash + +# omarchy:summary=Move overlapping displays clear of each other +# omarchy:group=hyprland +# omarchy:args=[check|apply] [--dry-run] [--intended JSON] +# omarchy:examples=omarchy hyprland monitor tidy | omarchy hyprland monitor tidy check + +# Changing a display's scale or rotation changes how much desk space it takes +# up, but every display keeps the position it already had. Nothing moves to make +# room, so the displays start overlapping -- which is what Hyprland's "Your +# monitor layout is set up incorrectly" warning means. +# +# This re-packs the displays along whichever axis they were already arranged on, +# keeping their order and the first one anchored where it is, so they sit edge +# to edge again. It is called automatically after a rotation or scale change. +# +# Rotation matters to the arithmetic: `hyprctl` reports the mode, not the +# rotated result, so a display on an odd transform occupies height-by-width. + +set -euo pipefail + +usage() { + cat <<'USAGE' +Usage: omarchy-hyprland-monitor-tidy [check|apply] [--dry-run] + + check Report overlapping displays. Exits non-zero when any overlap. + apply Move overlapping displays clear of each other (the default). + +Gaps are left alone: a gap is not an error, and closing one would move +displays that were placed on purpose. + +--dry-run prints what apply would do without changing anything. + +--intended takes a monitor listing describing the layout a change is about to +produce, and positions the displays for that instead of for the current one. +A caller growing a display uses it to move the neighbours clear first, so the +displays never overlap even for an instant -- Hyprland notifies the moment they +do, and that warning stays on screen after the layout is valid again. +USAGE +} + +action="apply" dry_run=0 intended= + +while (($#)); do + case "$1" in + check | apply) + action="$1" + shift + ;; + --dry-run) + dry_run=1 + shift + ;; + --intended) + (($# >= 2)) || { + echo "Error: --intended needs a value." >&2 + exit 1 + } + intended="$2" + shift 2 + ;; + --intended=*) + intended="${1#*=}" + shift + ;; + -h | --help) + usage + exit 0 + ;; + *) + usage >&2 + exit 1 + ;; + esac +done + +# OMARCHY_MONITOR_JSON lets the tests describe a layout without a compositor. +if [[ -n $intended ]]; then + monitors_json=$intended +else + monitors_json=${OMARCHY_MONITOR_JSON:-$(hyprctl monitors -j)} +fi + +plan=$(printf '%s' "$monitors_json" | python3 -c ' +import json +import sys + +monitors = json.load(sys.stdin) + + +def occupies_space(monitor): + if monitor.get("disabled"): + return False + # A mirrored display repeats what another one shows and shares its + # position, so it is not a second area of desk. Counting it reads as a total + # overlap, and tidying would move the display being mirrored out from under + # it -- silently breaking the mirror. + mirror_of = monitor.get("mirrorOf") or "none" + return mirror_of == "none" + + +active = [m for m in monitors if occupies_space(m)] + + +def rect(monitor): + scale = float(monitor.get("scale") or 1) or 1 + width = float(monitor.get("width") or 0) / scale + height = float(monitor.get("height") or 0) / scale + # Odd transforms are the quarter turns, which swap the axes. + if int(monitor.get("transform") or 0) % 2: + width, height = height, width + return { + "name": monitor.get("name", ""), + "x": float(monitor.get("x") or 0), + "y": float(monitor.get("y") or 0), + "w": round(width), + "h": round(height), + } + + +rects = [rect(m) for m in active] + +if len(rects) < 2: + print(json.dumps({"ok": True, "problems": [], "moves": []})) + sys.exit(0) + + +def overlap(a, b): + horizontal = min(a["x"] + a["w"], b["x"] + b["w"]) - max(a["x"], b["x"]) + vertical = min(a["y"] + a["h"], b["y"] + b["h"]) - max(a["y"], b["y"]) + if horizontal > 0 and vertical > 0: + return (round(horizontal), round(vertical)) + return None + + +problems = [] +for i in range(len(rects)): + for j in range(i + 1, len(rects)): + collision = overlap(rects[i], rects[j]) + if collision: + problems.append({ + "kind": "overlap", + "a": rects[i]["name"], + "b": rects[j]["name"], + "by": collision, + }) + +# Which way are these displays laid out? Compare how far apart their centres are +# on each axis and pack along the wider spread, so a stacked arrangement is not +# flattened into a row. +def spread(key, size): + centres = [r[key] + r[size] / 2 for r in rects] + return max(centres) - min(centres) + + +axis = "x" if spread("x", "w") >= spread("y", "h") else "y" +size = "w" if axis == "x" else "h" + +# Only overlapping displays are moved, and each is pushed just clear of what it +# runs into along the layout axis. +# +# Closing gaps as well was tried and is wrong: a gap is not an error. Hyprland +# only ever complains about overlaps, and a layout can be deliberately spaced or +# arranged in rows. Packing everything onto one axis flattened valid L-shaped +# layouts, and a tall display beside two stacked ones dragged a whole row +# sideways because it shared the cross axis with both rows. +moves = [] +placed = sorted(rects, key=lambda r: (r[axis], r["name"])) + +for index, r in enumerate(placed): + target = r[axis] + # Clear of every display already settled ahead of this one that it hits. + for earlier in placed[:index]: + probe = dict(r) + probe[axis] = target + if overlap(probe, earlier) is not None: + target = earlier[axis] + earlier[size] + + if target != r[axis]: + moves.append({ + "name": r["name"], + "axis": axis, + "from": round(r[axis]), + "to": round(target), + "x": round(target if axis == "x" else r["x"]), + "y": round(target if axis == "y" else r["y"]), + }) + r[axis] = target + +# Order matters as much as the destinations. Applied left to right, a display +# shifting outward lands on its neighbour before that neighbour has moved, and +# Hyprland notifies on the overlap even though the finished layout is fine. +# Displays moving outward are therefore moved outermost first, and displays +# moving inward innermost first, so no intermediate state overlaps. +outward = sorted([m for m in moves if m["to"] > m["from"]], key=lambda m: -m["to"]) +inward = sorted([m for m in moves if m["to"] < m["from"]], key=lambda m: m["to"]) +moves = outward + inward + +print(json.dumps({"ok": not problems and not moves, "problems": problems, "moves": moves, "axis": axis})) +') + +ok=$(jq -r '.ok' <<<"$plan") +moves=$(jq -c '.moves' <<<"$plan") + +describe_problems() { + jq -r ' + .problems[] | + " \(.a) and \(.b) overlap by \(.by[0])x\(.by[1]) logical pixels" + ' <<<"$plan" +} + +if [[ $ok == "true" ]]; then + [[ $action == "check" ]] && echo "No displays overlap." + exit 0 +fi + +if [[ $action == "check" ]]; then + echo "Display layout needs tidying:" + describe_problems + exit 1 +fi + +if ((dry_run)); then + echo "Would move:" + jq -r '.moves[] | " \(.name): \(.axis) \(.from) -> \(.to)"' <<<"$plan" + exit 0 +fi + +count=$(jq -r 'length' <<<"$moves") +((count)) || exit 0 + +while read -r name x y; do + [[ -n $name ]] || continue + hyprctl eval "hl.monitor({ output = \"$name\", position = \"${x}x${y}\" })" >/dev/null + omarchy-hyprland-monitor-rule set "$name" "position=${x}x${y}" +done < <(jq -r '.[] | "\(.name) \(.x) \(.y)"' <<<"$moves") + +echo "Moved $count display(s) clear of an overlap:" +jq -r '.[] | " \(.name): \(.axis) \(.from) -> \(.to)"' <<<"$moves" diff --git a/bin/omarchy-monitor-state b/bin/omarchy-monitor-state index fe0e72f433b0..4da1ecb9bd6a 100755 --- a/bin/omarchy-monitor-state +++ b/bin/omarchy-monitor-state @@ -19,5 +19,19 @@ printf '%s\n' "$monitors_json" | jq -r ' printf '%s\n' "$focused_monitor" omarchy-hyprland-monitor-scaling 2>/dev/null || echo +# transform, colour preset, and SDR luminance all come straight out of the same +# hyprctl payload, so the panel gets them without another process. Whether a +# display *can* do HDR is a separate, slower EDID read +# (omarchy-hyprland-monitor-capabilities) that the panel makes on its own +# schedule, since it only changes when displays are plugged or unplugged. printf '%s\n' "$monitors_json" | jq -c \ - '[.[] | {name, enabled:(.disabled != true), focused:(.focused == true), width, height}]' + '[.[] | { + name, + enabled: (.disabled != true), + focused: (.focused == true), + width, + height, + transform: (.transform // 0), + hdr: (.colorManagementPreset == "hdr"), + sdrMaxLuminance: (.sdrMaxLuminance // 0) + }]' diff --git a/manual/33-monitors.md b/manual/33-monitors.md index e6a5e30e021a..55b42ebbd240 100644 --- a/manual/33-monitors.md +++ b/manual/33-monitors.md @@ -42,6 +42,58 @@ Hyprland works great with multiple screens. Read more about how to lay them out You can also checkout [Hyprmon](https://github.com/erans/hyprmon/), if you'd like a TUI to help you with the positioning of multiple screens. +### Rotating a screen + +Portrait screens, and screens on an arm that swivels, need a rotation. Open the Display panel and pick one of `0°`, `90°`, `180°`, `270°` under _Rotation_; it applies to the screen you're focused on and is saved to that screen's rule in `~/.config/hypr/monitors.lua`, so it comes back after a reboot. + +From the terminal: + +```bash +omarchy hyprland monitor rotate 90 +omarchy hyprland monitor rotate 0 --monitor DP-3 +``` + +Run it without a rotation to print the current one. A mirrored screen stays mirrored when you rotate it; `--no-flipped` stops the mirroring. + +### When screens overlap + +Changing a screen's scale or rotation changes how much room it takes up, but screens pinned to explicit positions in `monitors.lua` don't move to make space. They end up overlapping, which is what Hyprland's _"Your monitor layout is set up incorrectly"_ warning means. + +Rotating from the Display panel moves the other screens clear first, so they never overlap even briefly. If a layout does end up overlapping — after a scale change, or a screen coming back on a different port — you can settle it yourself: + +```bash +omarchy hyprland monitor tidy check +omarchy hyprland monitor tidy +``` + +Add `--dry-run` to see what it would move first. Screens are only ever moved clear of something they overlap, along the axis they're already arranged on; gaps are left alone, since a gap isn't an error and closing one would shove screens you positioned deliberately. If you'd rather place screens entirely by hand, `omarchy hyprland monitor rotate --no-tidy` leaves the positions alone. + +### HDR + +If a screen's EDID says it can do HDR, the Display panel shows an _HDR_ switch for it at the top right, and hovering it tells you the peak brightness that screen reports. Screens that can't do HDR don't get the switch at all. + +Turning it on puts the screen into 10-bit wide-colour HDR using the luminance values the screen itself advertises, so there's usually nothing to tune. If you've already set luminances by hand in `monitors.lua`, they're kept. + +```bash +omarchy hyprland monitor hdr # what's the current state? +omarchy hyprland monitor hdr on +omarchy hyprland monitor hdr off --monitor DP-1 +``` + +#### HDR and brightness + +Most screens lock their own brightness control while they're in HDR, and drive the panel from the HDR tone curve instead. They'll still accept a brightness change and report the new number back afterwards, so nothing can tell you it didn't take — the picture simply doesn't change. + +So with HDR on, the Display panel's Brightness slider moves the knob that does work: how bright ordinary, non-HDR content is within the HDR range. It reads as a percentage like it always did, labelled _Adjusts SDR brightness_. Turn it down if HDR video looks right but your terminal and web pages look washed out; turn it up if they look dim next to it. The brightness keys still drive the backlight for the screens where that does something. + +From the terminal, the same control in nits: + +```bash +omarchy hyprland monitor hdr --sdr-brightness 250 +``` + +100% on the slider is the brightness your screen can hold across the whole panel, not its peak, because peak brightness only applies to small highlights — push plain white past that and the screen dims itself as its brightness limiter kicks in. + ### Controlling brightness Monitor brightness is controlled by the dedicated function keys for brightness up/down. If you hold down shift while pressing these, you'll go to maximum or minimum brightness. The keys control the display you're focused on, so external monitors that speak DDC/CI are adjusted the same way as the laptop screen. diff --git a/shell/plugins/panels/monitor/Model.js b/shell/plugins/panels/monitor/Model.js index 215972b9b525..995e58595c4d 100644 --- a/shell/plugins/panels/monitor/Model.js +++ b/shell/plugins/panels/monitor/Model.js @@ -53,7 +53,10 @@ function matchingScaleIndex(scales, currentScale, width, height) { } function availableScales(scales, width, height) { - if (!Array.isArray(scales) || Number(width) <= 0 || Number(height) <= 0) return scales || [] + // isFinite as well as the range check: NaN fails every comparison, so a + // non-numeric mode would slip through and collapse every preset onto one key. + if (!Array.isArray(scales) || !isFinite(Number(width)) || !isFinite(Number(height)) + || Number(width) <= 0 || Number(height) <= 0) return scales || [] var byEffectiveScale = {} for (var i = 0; i < scales.length; i++) { @@ -91,6 +94,76 @@ function brightnessName(percent) { return "Night owl" } +// Hyprland's `transform` is 0-7: 0-3 are the plain rotations, 4-7 repeat them +// mirrored. The panel offers degrees and hands them to the rotate command, +// which owns the mapping back to a transform and the mirrored half with it. +// Declared under the name QML uses. A .js module only exposes its top-level +// declarations, so an alias that exists solely in module.exports would read as +// undefined from QML while still passing the Node tests. +var rotationDegrees = [0, 90, 180, 270] + +function transformDegrees(transform) { + var value = Number(transform) + if (!isFinite(value) || value < 0) return 0 + return (Math.floor(value) % 4) * 90 +} + +// The usable range for SDR white inside the HDR volume. The top is the +// display's sustained full-field luminance rather than its peak: peak applies +// to small highlights, and mapping SDR white there makes a full white window +// dim as the panel's automatic brightness limiter pulls power back. +function sdrLuminanceRange(maxAvgLuminance) { + var ceiling = Math.round(Number(maxAvgLuminance)) + if (!isFinite(ceiling) || ceiling <= 0) ceiling = 400 + // At least 100 nits wide: a narrower range cannot survive a round trip + // through whole percentages, and the slider would jump a notch on its own. + return { minimum: 40, maximum: Math.max(140, ceiling) } +} + +function clampSdrLuminance(value, maxAvgLuminance) { + var range = sdrLuminanceRange(maxAvgLuminance) + var nits = Math.round(Number(value)) + if (!isFinite(nits)) return range.minimum + return Math.max(range.minimum, Math.min(range.maximum, nits)) +} + +// The panel shows one percentage whichever knob the brightness slider is on, so +// an SDR luminance is expressed as its position within the range the display +// can hold, and back again. +function sdrLuminanceToPercent(nits, maxAvgLuminance) { + var range = sdrLuminanceRange(maxAvgLuminance) + var span = Math.max(1, range.maximum - range.minimum) + var value = Number(nits) + if (!isFinite(value)) return 0 + return Math.max(0, Math.min(100, Math.round(((value - range.minimum) / span) * 100))) +} + +function sdrPercentToLuminance(percent, maxAvgLuminance) { + var range = sdrLuminanceRange(maxAvgLuminance) + var span = range.maximum - range.minimum + var value = Number(percent) + if (!isFinite(value)) return range.minimum + var clamped = Math.max(0, Math.min(100, value)) + return Math.round(range.minimum + (clamped / 100) * span) +} + +function parseCapabilities(raw) { + var parsed = {} + try { + parsed = raw ? JSON.parse(String(raw)) : {} + } catch (e) { + parsed = {} + } + if (!parsed || typeof parsed !== "object") parsed = {} + return { + name: parsed.name || "", + hdr: parsed.hdr === true, + maxLuminance: Number(parsed.max_luminance) || 0, + maxAvgLuminance: Number(parsed.max_avg_luminance) || 0, + minLuminance: Number(parsed.min_luminance) || 0 + } +} + function parseDisplays(raw) { var displays = [] try { @@ -119,6 +192,13 @@ if (typeof module !== "undefined") { matchingScaleIndex: matchingScaleIndex, availableScales: availableScales, brightnessName: brightnessName, - parseDisplays: parseDisplays + parseDisplays: parseDisplays, + rotationDegrees: rotationDegrees, + transformDegrees: transformDegrees, + sdrLuminanceRange: sdrLuminanceRange, + clampSdrLuminance: clampSdrLuminance, + sdrLuminanceToPercent: sdrLuminanceToPercent, + sdrPercentToLuminance: sdrPercentToLuminance, + parseCapabilities: parseCapabilities } } diff --git a/shell/plugins/panels/monitor/Panel.qml b/shell/plugins/panels/monitor/Panel.qml index 1753906ea893..eeb8f94cfd27 100644 --- a/shell/plugins/panels/monitor/Panel.qml +++ b/shell/plugins/panels/monitor/Panel.qml @@ -17,6 +17,9 @@ Panel { property int brightnessPercent: 0 property int pendingBrightnessPercent: 0 property bool brightnessSetQueued: false + property int pendingSdrLuminance: 0 + property bool sdrLuminanceSetQueued: false + property string capabilitiesRequestedMonitor: "" property bool brightnessAvailable: false property string internalMonitor: "" property string externalMonitor: "" @@ -27,16 +30,61 @@ Panel { property var displays: [] property int enabledDisplayCount: 0 + // HDR capability comes from the display's EDID, which is a slower read than + // the rest of the state and only changes when displays are plugged in, so it + // is fetched separately rather than on the 5s poll. + property var focusedCapabilities: Model.parseCapabilities("") + + readonly property var focusedDisplay: { + for (var i = 0; i < displays.length; i++) + if (displays[i] && displays[i].focused) return displays[i] + return null + } + + readonly property int focusedTransform: focusedDisplay ? Number(focusedDisplay.transform) || 0 : 0 + readonly property bool hdrEnabled: !!(focusedDisplay && focusedDisplay.hdr) + readonly property bool hdrCapable: focusedCapabilities.hdr && focusedCapabilities.name === focusedMonitor + + // Where SDR white sits inside the HDR volume. Only meaningful while HDR is on. + property int sdrLuminance: 0 + readonly property var sdrRange: Model.sdrLuminanceRange(focusedCapabilities.maxAvgLuminance) + + // With HDR on, the backlight stops being the control that matters. Displays + // typically lock their brightness to the HDR tone curve, and they still + // acknowledge a DDC/CI write and read the new value back afterwards, so + // nothing here can detect that the change did nothing. A slider that silently + // does nothing is worse than one that moves, so the brightness slider drives + // sdr_max_luminance instead while HDR is on: the knob that actually changes + // how bright the desktop looks. It stays a percentage of what this display can + // hold, so the control reads the same either way, with a caption naming which + // knob it is on. The brightness keys still drive the backlight. + readonly property bool brightnessControlsSdr: hdrEnabled + // The slider is a percentage either way. Under HDR that percentage spans the + // luminance range this display can actually hold, so the control reads the + // same whichever knob is behind it. + // root-qualified: an `id` elsewhere in this file can otherwise shadow a plain + // property name here, and the binding then silently fails to assign. + readonly property int brightnessValue: root.brightnessControlsSdr + ? Model.sdrLuminanceToPercent(root.sdrLuminance, root.focusedCapabilities.maxAvgLuminance) + : root.brightnessPercent + // SDR luminance is always adjustable under HDR, even where no backlight was + // found, so the section can be useful on a display with no controllable one. + readonly property bool brightnessSectionVisible: brightnessAvailable || brightnessControlsSdr + // Carry sub-notch touchpad deltas between wheel events. property real wheelAccumulator: 0 // Cursor model shared by keyboard and mouse. Sections: // "brightness" - single slider row, selectedIndex = -1 sentinel - // (mirrors Audio's slider rows). Only present if a - // controllable backlight was detected. + // (mirrors Audio's slider rows). Drives the backlight, or + // sdr_max_luminance while HDR is on. // "scale" - 6 Button scale presets; treated as a single // horizontal row from j/k's perspective. h/l moves // between presets, identical to bluetooth's header. + // "rotation" - 4 Button rotation presets, same horizontal treatment as + // scale. + // "hdr" - the hero's toggle, selectedIndex = -1 sentinel. Only + // present when the focused display's EDID advertises HDR. // "monitors" - vertical display row list for enabling/disabling displays; // j/k walks each row. // Mouse hover on a target updates root state via the components' `hovered` @@ -50,6 +98,7 @@ Panel { } return scalePresets } + readonly property var rotationValues: Model.rotationDegrees property string focusSection: "scale" property int selectedIndex: 0 property bool cursorActive: false @@ -74,28 +123,40 @@ Panel { readonly property var visibleSections: { var list = [] - if (brightnessAvailable) list.push("brightness") + // HDR sits in the hero, above everything else, so j/k reaches it first. + // Offering the switch on a display that cannot do HDR only invites a + // failure, so it is absent rather than disabled. + if (hdrCapable) list.push("hdr") + if (brightnessSectionVisible) list.push("brightness") list.push("textsize") list.push("scale") + list.push("rotation") if (displays.length > 1) list.push("monitors") return list } + // Sections whose only navigable target is the slider/toggle itself, addressed + // with the -1 sentinel rather than an index. + function sectionIsSentinel(section) { + return section === "brightness" || section === "textsize" || section === "hdr" + } + function sectionCount(section) { - if (section === "brightness") return 0 // only the slider sentinel at -1 - if (section === "textsize") return 0 // slider sentinel at -1, like brightness + if (sectionIsSentinel(section)) return 0 if (section === "scale") return scaleValues.length + if (section === "rotation") return rotationValues.length if (section === "monitors") return displays.length return 0 } function sectionIsSingleRow(section) { - // brightness and text size are lone sliders; scale presets sit horizontally. - return section === "brightness" || section === "textsize" || section === "scale" + // Sliders and the HDR toggle are lone rows; scale and rotation are chips + // sitting horizontally, which j/k also treats as one row. + return sectionIsSentinel(section) || section === "scale" || section === "rotation" } function sectionFirstIndex(section) { - if (section === "brightness" || section === "textsize") return -1 + if (sectionIsSentinel(section)) return -1 return 0 } @@ -129,21 +190,21 @@ Panel { } } - // h/l: in scale section, walks the preset row; everywhere else, no-op - // because adjustBrightness handles horizontal motion on the brightness - // slider. + // h/l: in the chip sections, walks the row; everywhere else, no-op because + // adjustBrightness handles horizontal motion on the sliders. function moveCursorH(delta) { - if (focusSection !== "scale") return + if (focusSection !== "scale" && focusSection !== "rotation") return + var count = sectionCount(focusSection) var next = selectedIndex + delta if (next < 0) next = 0 - if (next > scaleValues.length - 1) next = scaleValues.length - 1 + if (next > count - 1) next = count - 1 selectedIndex = next } function adjustBrightness(delta) { if (focusSection !== "brightness") return - if (!brightnessAvailable) return - setBrightness(root.brightnessPercent + delta) + if (!brightnessSectionVisible) return + root.applyBrightness(root.brightnessValue + delta) } function activateCursor() { @@ -151,6 +212,14 @@ Panel { setScale(scaleValues[selectedIndex]) return } + if (focusSection === "rotation" && selectedIndex >= 0 && selectedIndex < rotationValues.length) { + setRotation(rotationValues[selectedIndex]) + return + } + if (focusSection === "hdr") { + toggleHdr() + return + } if (focusSection === "monitors" && selectedIndex >= 0 && selectedIndex < displays.length) { var d = displays[selectedIndex] if (d) toggleDisplay(d.name, d.enabled) @@ -168,8 +237,8 @@ Panel { } var count = sectionCount(focusSection) if (sectionIsSingleRow(focusSection)) { - // brightness/text size use the -1 sentinel; scale clamps into the presets. - if (focusSection === "brightness" || focusSection === "textsize") selectedIndex = -1 + // Sliders and toggles use the -1 sentinel; chip rows clamp into the row. + if (sectionIsSentinel(focusSection)) selectedIndex = -1 else if (selectedIndex < 0 || selectedIndex >= count) selectedIndex = 0 return } @@ -253,6 +322,25 @@ Panel { brightnessDebounce.restart() } + // The brightness slider drives whichever control is the live one for this + // display: SDR white mapping under HDR, the backlight otherwise. + function applyBrightness(percent) { + if (root.brightnessControlsSdr) + root.setSdrLuminance(Model.sdrPercentToLuminance(percent, root.focusedCapabilities.maxAvgLuminance)) + else root.setBrightness(percent) + } + + function previewBrightnessValue(percent) { + if (root.brightnessControlsSdr) + root.previewSdrLuminance(Model.sdrPercentToLuminance(percent, root.focusedCapabilities.maxAvgLuminance)) + else root.previewBrightness(percent) + } + + function stopBrightnessDebounce() { + if (root.brightnessControlsSdr) sdrLuminanceDebounce.stop() + else brightnessDebounce.stop() + } + function showBrightnessOsd(percent) { if (!bar || !bar.shell) return bar.shell.summon("omarchy.osd", JSON.stringify({ @@ -309,6 +397,60 @@ Panel { if (!actionProc.running) actionProc.running = true } + // ---- Rotation and HDR (both per display, both aimed at the focused one) ---- + function setRotation(degrees) { + if (!root.focusedMonitor) return + if (Model.transformDegrees(root.focusedTransform) === degrees) return + + actionProc.command = ["omarchy-hyprland-monitor-rotate", String(degrees), "--monitor", root.focusedMonitor] + if (!actionProc.running) actionProc.running = true + } + + function toggleHdr() { + if (!root.focusedMonitor || !root.hdrCapable) return + + actionProc.command = ["omarchy-hyprland-monitor-hdr", root.hdrEnabled ? "off" : "on", "--monitor", root.focusedMonitor] + if (!actionProc.running) actionProc.running = true + } + + function setSdrLuminance(value) { + if (!root.focusedMonitor) return + var nits = Model.clampSdrLuminance(value, root.focusedCapabilities.maxAvgLuminance) + root.sdrLuminance = nits + root.pendingSdrLuminance = nits + + // Assigning command to a Process that is already running does not start it + // again, so without a queue the write issued mid-flight is simply dropped -- + // and during a drag that is the final value, the one that matters. + if (sdrLuminanceProc.running) { + root.sdrLuminanceSetQueued = true + return + } + + root.sdrLuminanceSetQueued = false + sdrLuminanceProc.command = ["omarchy-hyprland-monitor-hdr", "--sdr-brightness", String(nits), "--monitor", root.focusedMonitor] + sdrLuminanceProc.running = true + } + + function previewSdrLuminance(value) { + root.sdrLuminance = Model.clampSdrLuminance(value, root.focusedCapabilities.maxAvgLuminance) + sdrLuminanceDebounce.restart() + } + + function refreshCapabilities() { + if (!root.focusedMonitor) return + + // Focus can move again before this EDID read finishes. Dropping the newer + // request would leave the panel showing the previous display's capability + // with nothing to ask again, so the display this run was launched for is + // recorded and compared against the focused one when it exits. + if (capabilitiesProc.running) return + + root.capabilitiesRequestedMonitor = root.focusedMonitor + capabilitiesProc.command = ["omarchy-hyprland-monitor-capabilities", root.focusedMonitor] + capabilitiesProc.running = true + } + // ---- Text size (shell base font + GTK text-scaling, via one CLI) ---- function nearestTextStop(px) { var best = 0 @@ -349,7 +491,10 @@ Panel { implicitWidth: button.implicitWidth implicitHeight: button.implicitHeight - Component.onCompleted: refresh() + Component.onCompleted: { + refresh() + refreshCapabilities() + } // KeyboardPanel primes focus at open-time, so SUPER-bound IPC summons land // with j/k ready to navigate. Keep a default landing point, but don't paint @@ -357,7 +502,8 @@ Panel { onOpenedChanged: { if (opened) { refresh() - if (brightnessAvailable) { + refreshCapabilities() + if (brightnessSectionVisible) { focusSection = "brightness" selectedIndex = -1 } else { @@ -370,6 +516,11 @@ Panel { onBrightnessAvailableChanged: clampCursor() onDisplaysChanged: clampCursor() + onHdrCapableChanged: clampCursor() + onHdrEnabledChanged: clampCursor() + // EDID capability belongs to a specific display, so it is re-read whenever + // the focus moves to another one. + onFocusedMonitorChanged: refreshCapabilities() onScaleValuesChanged: clampCursor() onVisibleSectionsChanged: clampCursor() @@ -400,6 +551,11 @@ Panel { root.focusedMonitor = String(lines[5] || "").trim() root.monitorScale = root.normalizeScale(String(lines[6] || "").trim()) root.updateDisplays(String(lines[7] || "[]").trim()) + + // Track the compositor's value unless a change of ours is still in + // flight, which would otherwise snap the slider back mid-drag. + if (!sdrLuminanceDebounce.running && !sdrLuminanceProc.running && root.focusedDisplay) + root.sdrLuminance = Number(root.focusedDisplay.sdrMaxLuminance) || 0 } } } @@ -435,6 +591,44 @@ Panel { onRunningChanged: if (!running) root.refresh() } + Process { + id: capabilitiesProc + stdout: StdioCollector { + waitForEnd: true + onStreamFinished: root.focusedCapabilities = Model.parseCapabilities(text) + } + // Re-issue only when focus has moved on since this run was launched. + // Comparing against the parsed output instead would respawn forever + // whenever the read returns nothing to parse. + onRunningChanged: { + if (running) return + if (root.focusedMonitor && root.focusedMonitor !== root.capabilitiesRequestedMonitor) { + root.refreshCapabilities() + } + } + } + + Timer { + id: sdrLuminanceDebounce + interval: 180 + repeat: false + onTriggered: root.setSdrLuminance(root.sdrLuminance) + } + + Process { + id: sdrLuminanceProc + stdout: StdioCollector { waitForEnd: true } + // As with brightness, the value just written is authoritative; re-reading + // immediately races the compositor's own update. + stderr: StdioCollector { waitForEnd: true } + onRunningChanged: { + if (running) return + if (root.sdrLuminanceSetQueued) { + root.setSdrLuminance(root.pendingSdrLuminance) + } + } + } + // Applies text size via the CLI, which rewrites the shell override file; // Style picks the new base-size up through its own file watch, so there's // nothing to refresh here. @@ -472,12 +666,14 @@ Panel { text: Quickshell.screens.length > 1 ? "󰍺" : "󰍹" onPressed: function(b) { root.toggle() } onWheelMoved: function(delta) { - if (!root.brightnessAvailable) return + if (!root.brightnessSectionVisible) return var wheel = Util.wheelSteps(root.wheelAccumulator, delta) root.wheelAccumulator = wheel.remainder if (wheel.steps === 0) return - root.setBrightness(root.brightnessPercent + wheel.steps * 5) - root.showBrightnessOsd(root.brightnessPercent) + // Scrolling the bar icon moves the same knob the panel's slider does, so + // the two never disagree about what "brighter" means on this display. + root.applyBrightness(root.brightnessValue + wheel.steps * 5) + root.showBrightnessOsd(root.brightnessValue) } } @@ -527,7 +723,7 @@ Panel { // ---------- Hero: display icon · title/status ---------- Item { width: parent.width - implicitHeight: Math.max(heroIcon.implicitHeight, heroLabels.implicitHeight) + implicitHeight: Math.max(heroIcon.implicitHeight, heroLabels.implicitHeight, hdrControl.implicitHeight) Text { id: heroIcon @@ -539,11 +735,58 @@ Panel { anchors.verticalCenter: parent.verticalCenter } + // HDR lives on the hero's trailing edge rather than in a section of + // its own, the way the Bluetooth panel carries its power switch. + // A whole row for one toggle was what pushed the panel past the + // height it can show without scrolling. + Row { + id: hdrControl + visible: root.hdrCapable + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + spacing: Style.space(8) + + Text { + text: "HDR" + color: Qt.darker(root.bar.foreground, root.hdrEnabled ? 1.0 : 1.4) + font.family: root.bar.fontFamily + font.pixelSize: Style.font.caption + font.bold: true + font.letterSpacing: 1.2 + anchors.verticalCenter: parent.verticalCenter + } + + ToggleSwitch { + id: hdrSwitch + checked: root.hdrEnabled + hasCursor: root.cursorActive && root.focusSection === "hdr" && root.selectedIndex === -1 + foreground: root.bar.foreground + anchors.verticalCenter: parent.verticalCenter + onHovered: function(on) { + if (!on || root.reflowingText) return + root.cursorActive = true + root.focusSection = "hdr" + root.selectedIndex = -1 + } + onToggled: root.toggleHdr() + + // The peak is this display's own, read from its EDID. + PanelToolTip { + visible: hdrSwitch.containsMouse + text: root.focusedCapabilities.maxLuminance > 0 + ? "High dynamic range, up to " + root.focusedCapabilities.maxLuminance + " nits" + : "High dynamic range" + fontFamily: root.bar.fontFamily + } + } + } + Column { id: heroLabels anchors.left: heroIcon.right anchors.leftMargin: Style.space(14) anchors.right: parent.right + anchors.rightMargin: hdrControl.visible ? hdrControl.width + Style.space(12) : 0 anchors.verticalCenter: parent.verticalCenter spacing: Style.space(2) @@ -560,8 +803,9 @@ Panel { Text { id: heroLabel text: { - if (root.brightnessAvailable) { - return root.brightnessName(brightnessSlider.dragging ? brightnessSlider.liveValue : root.brightnessPercent).toUpperCase() + if (root.brightnessSectionVisible) { + var live = brightnessSlider.dragging ? brightnessSlider.liveValue : root.brightnessValue + return root.brightnessName(live).toUpperCase() } return "FIXED BRIGHTNESS" } @@ -578,18 +822,18 @@ Panel { // ---------- Brightness ---------- PanelSeparator { - visible: root.brightnessAvailable + visible: root.brightnessSectionVisible foreground: root.bar.foreground } Column { - visible: root.brightnessAvailable + visible: root.brightnessSectionVisible width: parent.width spacing: Style.space(6) Item { width: parent.width - implicitHeight: Math.max(brightnessHeader.implicitHeight, brightnessPercent.implicitHeight) + implicitHeight: Math.max(brightnessHeader.implicitHeight, brightnessReadout.implicitHeight) PanelSectionHeader { id: brightnessHeader @@ -600,9 +844,12 @@ Panel { anchors.verticalCenter: parent.verticalCenter } + // Always a percentage, whichever knob the slider is on: under HDR + // it is the position within the SDR luminance range this display + // can hold, so the control reads the same either way. Text { - id: brightnessPercent - text: Math.round(brightnessSlider.dragging ? brightnessSlider.liveValue : root.brightnessPercent) + "%" + id: brightnessReadout + text: Math.round(brightnessSlider.dragging ? brightnessSlider.liveValue : root.brightnessValue) + "%" color: Qt.darker(root.bar.foreground, 1.4) font.family: root.bar.fontFamily font.pixelSize: Style.font.caption @@ -631,12 +878,12 @@ Panel { minimum: 1 maximum: 100 step: 1 - value: root.brightnessPercent + value: root.brightnessValue integer: true - onMoved: function(v) { root.previewBrightness(v) } + onMoved: function(v) { root.previewBrightnessValue(v) } onReleased: function(v) { - brightnessDebounce.stop() - root.setBrightness(v) + root.stopBrightnessDebounce() + root.applyBrightness(v) } } @@ -648,6 +895,16 @@ Panel { } } } + + // Names the knob, since it changes with HDR. + Text { + visible: root.brightnessControlsSdr + text: "Adjusts SDR brightness" + color: Qt.darker(root.bar.foreground, 1.5) + font.family: root.bar.fontFamily + font.pixelSize: Style.font.caption + x: Style.space(6) + } } // ---------- Text size ---------- @@ -785,6 +1042,67 @@ Panel { } } + // ---------- Rotation ---------- + PanelSeparator { + foreground: root.bar.foreground + } + + Column { + width: parent.width + spacing: Style.space(10) + + Item { + width: parent.width + implicitHeight: Math.max(rotationHeader.implicitHeight, rotationMonitor.implicitHeight) + + PanelSectionHeader { + id: rotationHeader + text: "ROTATION" + foreground: root.bar.foreground + fontFamily: root.bar.fontFamily + anchors.left: parent.left + anchors.verticalCenter: parent.verticalCenter + } + + // Like SCALE, rotation applies to the focused display, so name it + // once there is more than one to confuse it with. + Text { + id: rotationMonitor + text: root.focusedMonitor + visible: root.focusedMonitor !== "" && root.enabledDisplayCount > 1 + color: Qt.darker(root.bar.foreground, 1.4) + font.family: root.bar.fontFamily + font.pixelSize: Style.font.caption + font.bold: true + anchors.right: parent.right + anchors.rightMargin: Style.space(6) + anchors.verticalCenter: parent.verticalCenter + } + } + + Grid { + id: rotationRow + width: parent.width + columns: root.rotationValues.length + spacing: Style.spacing.xs + + readonly property real cellWidth: (width - spacing * (columns - 1)) / columns + + Repeater { + model: root.rotationValues + + RotationPill { + required property int modelData + required property int index + + degrees: modelData + rotationIndex: index + width: rotationRow.cellWidth + } + } + } + } + // ---------- Monitors ---------- PanelSeparator { visible: root.displays.length > 1 @@ -850,6 +1168,31 @@ Panel { } } + component RotationPill: Button { + id: rotationPill + required property int degrees + required property int rotationIndex + + text: rotationPill.degrees + "°" + fontSize: Style.font.caption + foreground: root.bar.foreground + fontFamily: root.bar.fontFamily + horizontalPadding: Style.spacing.sm + verticalPadding: Style.spacing.controlPaddingY + bordered: true + + active: Model.transformDegrees(root.focusedTransform) === rotationPill.degrees + hasCursor: root.cursorActive && root.focusSection === "rotation" && root.selectedIndex === rotationIndex + + onClicked: root.setRotation(rotationPill.degrees) + onHovered: function(isHovered) { + if (!isHovered || root.reflowingText) return + root.cursorActive = true + root.focusSection = "rotation" + root.selectedIndex = rotationPill.rotationIndex + } + } + component MonitorRow: CursorSurface { id: monitorRow required property var display diff --git a/test/shell.d/monitor-hdr-test.sh b/test/shell.d/monitor-hdr-test.sh new file mode 100755 index 000000000000..d5a711d57aae --- /dev/null +++ b/test/shell.d/monitor-hdr-test.sh @@ -0,0 +1,456 @@ +#!/bin/bash + +# Covers omarchy-hyprland-monitor-hdr and omarchy-hyprland-monitor-capabilities. +# +# Nothing here talks to a compositor or to the user's config: hyprctl and the +# capability probe are replaced by stubs on PATH, and every rule write is +# redirected to a temp monitors.lua through OMARCHY_MONITOR_LUA. A guard below +# refuses to run at all unless the stub is the hyprctl that would be found, +# because `hdr on` issues `hyprctl eval` and that would reconfigure the real +# desktop. +# +# Assertions are collected rather than aborting on the first miss, so one +# unfixed defect does not hide the coverage below it; the run still exits +# non-zero if anything failed. + +set -uo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +require_command jq +require_command python3 + +HDR="$ROOT/bin/omarchy-hyprland-monitor-hdr" +CAPABILITIES="$ROOT/bin/omarchy-hyprland-monitor-capabilities" + +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT + +STUB="$WORK/bin" +CAPS_DIR="$WORK/caps" +mkdir -p "$STUB" "$CAPS_DIR" + +HYPRCTL_LOG="$WORK/hyprctl.log" +MONITORS_JSON="$WORK/monitors.json" + +FAILURES=() + +record_fail() { + local description="$1" detail="${2:-}" + + FAILURES+=("$description") + [[ -n $detail ]] && printf '%s\n' "$detail" >&2 + printf 'not ok - %s\n' "$description" >&2 +} + +assert_equal() { + local actual="$1" expected="$2" description="$3" + + if [[ $actual == "$expected" ]]; then + pass "$description" + else + record_fail "$description" "expected: $expected +actual: $actual" + fi +} + +assert_contains() { + local haystack="$1" needle="$2" description="$3" + + if [[ $haystack == *"$needle"* ]]; then + pass "$description" + else + record_fail "$description" "expected to contain: $needle +actual: $haystack" + fi +} + +# Takes a command so the reason for a failure is visible in the log. +assert_ok() { + local description="$1" + shift + + if "$@"; then + pass "$description" + else + record_fail "$description" "failed: $*" + fi +} + +assert_nonzero_exit() { + local status="$1" description="$2" + + if [[ $status != 0 ]]; then + pass "$description" + else + record_fail "$description" "expected a non-zero exit, got 0" + fi +} + +# ---- Stubs ---- + +cat >"$STUB/hyprctl" <<'SH' +#!/bin/bash +printf '%s\n' "$*" >>"$OMARCHY_TEST_HYPRCTL_LOG" + +if [[ $1 == "monitors" ]]; then + cat "$OMARCHY_TEST_MONITORS_JSON" + exit 0 +fi + +# `eval` is the mutating path; the stub records it and changes nothing. +exit 0 +SH + +cat >"$STUB/omarchy-hyprland-monitor-capabilities" <<'SH' +#!/bin/bash +if [[ -f "$OMARCHY_TEST_CAPS_DIR/$1.json" ]]; then + cat "$OMARCHY_TEST_CAPS_DIR/$1.json" +else + jq -nc --arg name "$1" '{name: $name, hdr: false, reason: "no-edid"}' +fi +SH + +chmod +x "$STUB"/* + +export OMARCHY_TEST_HYPRCTL_LOG="$HYPRCTL_LOG" +export OMARCHY_TEST_MONITORS_JSON="$MONITORS_JSON" +export OMARCHY_TEST_CAPS_DIR="$CAPS_DIR" + +# omarchy-hyprland-monitor-rule is the real one, but pointed at a temp file and +# told what the displays are so it never shells out to hyprctl itself. +export OMARCHY_MONITOR_DESCRIPTIONS='[{"name":"DP-1","description":"Acme HDR 32"},{"name":"DP-2","description":"Acme SDR 24"},{"name":"DP-3","description":"Acme Dim 27"}]' +export OMARCHY_MONITOR_SEED='{"mode":"3840x2160@144","position":"0x0","scale":"1.5"}' + +TEST_PATH="$STUB:$ROOT/bin:$PATH" + +# Safety guard: if the stub is not what `hyprctl` resolves to under the test +# PATH, `hdr on` would reconfigure the real session. Refuse to continue. +resolved=$(PATH="$TEST_PATH" command -v hyprctl) +[[ $resolved == "$STUB/hyprctl" ]] || fail "hyprctl stub shadows the real binary" "resolved: $resolved" +pass "hyprctl stub shadows the real binary" + +# DP-1: HDR panel currently in sRGB. DP-2: SDR panel already claiming hdr as its +# preset (so "enabled" can be checked independently of capability). +cat >"$MONITORS_JSON" <<'JSON' +[ + {"name":"DP-1","focused":true,"colorManagementPreset":"srgb","currentFormat":"XRGB8888","sdrMaxLuminance":200,"sdrBrightness":1.0,"sdrSaturation":1.0}, + {"name":"DP-2","focused":false,"colorManagementPreset":"hdr","currentFormat":"XRGB2101010","sdrMaxLuminance":180,"sdrBrightness":1.0,"sdrSaturation":1.0}, + {"name":"DP-3","focused":false,"colorManagementPreset":"srgb","currentFormat":"XRGB8888","sdrMaxLuminance":100,"sdrBrightness":1.0,"sdrSaturation":1.0} +] +JSON + +cat >"$CAPS_DIR/DP-1.json" <<'JSON' +{"name":"DP-1","hdr":true,"max_luminance":993,"max_avg_luminance":277,"min_luminance":0.001} +JSON +cat >"$CAPS_DIR/DP-2.json" <<'JSON' +{"name":"DP-2","hdr":false,"reason":"no-pq-eotf"} +JSON +# A panel whose advertised frame-average luminance is very low, to pin down the +# behaviour of the derived SDR white default at the bottom of its range. +cat >"$CAPS_DIR/DP-3.json" <<'JSON' +{"name":"DP-3","hdr":true,"max_luminance":400,"max_avg_luminance":50,"min_luminance":0.05} +JSON + +CATCH_ALL='hl.monitor({ output = "", mode = "preferred", position = "auto", scale = 1 })' + +reset_lua() { + export OMARCHY_MONITOR_LUA="$WORK/monitors.lua" + printf '%s\n' "$CATCH_ALL" >"$OMARCHY_MONITOR_LUA" + : >"$HYPRCTL_LOG" +} + +rule_get() { + PATH="$TEST_PATH" "$ROOT/bin/omarchy-hyprland-monitor-rule" get "$1" "$2" 2>/dev/null +} + +HDR_OUT="" HDR_ERR="" HDR_STATUS=0 + +run_hdr() { + HDR_OUT=$(PATH="$TEST_PATH" timeout 10 "$HDR" "$@" 2>"$WORK/stderr" /dev/null || true +} + +lua_unchanged() { + [[ $(cat "$OMARCHY_MONITOR_LUA") == "$CATCH_ALL" ]] +} + +is_json() { + jq -e . >/dev/null 2>&1 <<<"$1" +} + +# ---- Argument parsing ---- + +reset_lua +run_hdr --help +assert_equal "$HDR_STATUS" "0" "hdr --help exits 0" +assert_contains "$HDR_OUT" "Usage:" "hdr --help prints usage on stdout" +assert_equal "$(eval_count)" "0" "hdr --help asks the compositor for nothing" +assert_ok "hdr --help leaves monitors.lua alone" lua_unchanged + +reset_lua +run_hdr -h +assert_equal "$HDR_STATUS" "0" "hdr -h is the same as --help" +assert_contains "$HDR_OUT" "Usage:" "hdr -h prints usage" + +reset_lua +run_hdr --nonsense +assert_nonzero_exit "$HDR_STATUS" "hdr rejects an unknown flag" +assert_contains "$HDR_ERR" "Usage:" "hdr prints usage on stderr when the arguments are wrong" +assert_equal "$HDR_OUT" "" "hdr prints nothing on stdout when the arguments are wrong" +assert_ok "a rejected invocation writes no rule" lua_unchanged + +reset_lua +run_hdr sideways +assert_nonzero_exit "$HDR_STATUS" "hdr rejects an unknown action" + +# A flag that takes a value, given none, must fail rather than spin: run_hdr +# wraps the command in `timeout 10`, so a hang shows up as exit 124. +for flag in --monitor --sdr-brightness; do + reset_lua + run_hdr "$flag" + assert_ok "hdr $flag with no value fails instead of spinning" \ + bash -c "[[ '$HDR_STATUS' != 0 && '$HDR_STATUS' != 124 ]]" + assert_ok "hdr $flag with no value writes no rule" lua_unchanged +done + +# An explicitly empty --monitor= is a caller interpolating an unset variable; it +# must not quietly retarget whichever display happens to be focused. +reset_lua +run_hdr --monitor= status +assert_nonzero_exit "$HDR_STATUS" "hdr rejects an empty --monitor=" + +reset_lua +run_hdr --monitor DP-9 status +assert_nonzero_exit "$HDR_STATUS" "hdr rejects an unknown display" +assert_contains "$HDR_ERR" "DP-9" "hdr names the display it could not find" +assert_ok "an unknown display writes no rule" lua_unchanged +assert_equal "$(eval_count)" "0" "an unknown display is not reconfigured" + +# ---- Status output shape ---- + +reset_lua +run_hdr status +assert_equal "$HDR_STATUS" "0" "hdr status exits 0" +assert_ok "hdr status prints one JSON object" is_json "$HDR_OUT" +assert_equal "$(jq -r '.name' <<<"$HDR_OUT")" "DP-1" "hdr status defaults to the focused display" +assert_equal "$(jq -r '.preset' <<<"$HDR_OUT")" "srgb" "hdr status reports the live colour preset" +assert_equal "$(jq -r '.enabled' <<<"$HDR_OUT")" "false" "an sRGB display reports HDR as not enabled" +assert_equal "$(jq -r '.capable' <<<"$HDR_OUT")" "true" "hdr status reports EDID capability" +assert_equal "$(jq -r '.max_luminance' <<<"$HDR_OUT")" "993" "hdr status carries the EDID luminances through" +assert_equal "$(eval_count)" "0" "hdr status changes nothing on the compositor" +assert_ok "hdr status writes no rule" lua_unchanged + +# The keys are a contract with the Display panel, which reads them by name. +for key in name enabled preset capable format sdr_max_luminance max_luminance max_avg_luminance min_luminance; do + assert_equal "$(jq -e "has(\"$key\")" <<<"$HDR_OUT")" "true" "hdr status includes $key" +done + +reset_lua +run_hdr +assert_equal "$HDR_STATUS" "0" "hdr with no arguments exits 0" +assert_ok "hdr with no arguments prints JSON" is_json "$HDR_OUT" +assert_equal "$(eval_count)" "0" "hdr with no arguments is read-only" + +# enabled must track the live preset, not the EDID: DP-2 cannot do HDR but the +# compositor has it in the hdr preset anyway (e.g. it was forced). +reset_lua +run_hdr --monitor DP-2 status +assert_equal "$(jq -r '.enabled' <<<"$HDR_OUT")" "true" "enabled follows the live preset" +assert_equal "$(jq -r '.capable' <<<"$HDR_OUT")" "false" "capable follows the EDID, independently of the preset" + +# ---- Refusal without EDID HDR support ---- + +reset_lua +run_hdr on --monitor DP-2 +assert_nonzero_exit "$HDR_STATUS" "hdr on refuses a display whose EDID does not advertise HDR" +assert_contains "$HDR_ERR" "--force" "the refusal points at --force" +assert_equal "$(eval_count)" "0" "a refused hdr on reconfigures nothing" +assert_ok "a refused hdr on writes no rule" lua_unchanged + +reset_lua +run_hdr on --monitor DP-2 --force +assert_equal "$HDR_STATUS" "0" "--force enables HDR on a display without EDID support" +assert_equal "$(rule_get DP-2 cm)" "hdr" "--force writes the HDR colour management rule" +assert_ok "--force issues the live reconfiguration" test "$(eval_count)" -ge 1 +# The catch-all must never pick up a per-display setting (bug #6673). +assert_ok "the catch-all rule is untouched" grep -qF "$CATCH_ALL" "$OMARCHY_MONITOR_LUA" +assert_equal "$(grep -c 'output = ""' "$OMARCHY_MONITOR_LUA")" "1" "no second catch-all rule appears" + +# ---- Enabling on a capable display ---- + +reset_lua +run_hdr on +assert_equal "$HDR_STATUS" "0" "hdr on succeeds on a capable display" +assert_ok "hdr on prints the resulting status as JSON" is_json "$HDR_OUT" +assert_equal "$(rule_get DP-1 cm)" "hdr" "hdr on persists cm = hdr" +assert_equal "$(rule_get DP-1 bitdepth)" "10" "hdr on persists 10-bit output" +assert_equal "$(rule_get DP-1 max_luminance)" "993" "hdr on persists the EDID peak luminance" +assert_equal "$(rule_get DP-1 max_avg_luminance)" "277" "hdr on persists the EDID frame-average luminance" + +# SDR white is mapped below the panel's sustained full-field ceiling, or the +# whole screen visibly dims under a full white window. +sdr_default=$(rule_get DP-1 sdr_max_luminance) +assert_ok "hdr on derives an SDR white level" test -n "$sdr_default" +assert_ok "the derived SDR white is a positive whole number of nits" \ + bash -c "[[ '$sdr_default' =~ ^[0-9]+$ ]] && ((${sdr_default:-0} > 0))" +assert_ok "the derived SDR white stays under the frame-average ceiling (277)" \ + test "${sdr_default:-0}" -le 277 + +# Running it again must be a no-op: the panel re-enables HDR on every toggle. +before=$(cat "$OMARCHY_MONITOR_LUA") +run_hdr on +assert_equal "$HDR_STATUS" "0" "hdr on a second time still succeeds" +assert_equal "$(cat "$OMARCHY_MONITOR_LUA")" "$before" "hdr on is idempotent in monitors.lua" + +# A dim panel must still get a usable SDR white rather than 0.8 of a tiny +# frame-average figure. +reset_lua +run_hdr on --monitor DP-3 +assert_equal "$HDR_STATUS" "0" "hdr on succeeds on a low-luminance HDR panel" +dim_default=$(rule_get DP-3 sdr_max_luminance) +assert_ok "a dim panel still gets a legible SDR white" test "${dim_default:-0}" -ge 1 +assert_ok "a dim panel's SDR white is not absurdly high" test "${dim_default:-0}" -le 1000 + +# Hand-tuned luminances survive enabling HDR: the script documents that it only +# fills in fields the user has not already set. +reset_lua +PATH="$TEST_PATH" "$ROOT/bin/omarchy-hyprland-monitor-rule" set DP-1 max_luminance=1234 sdr_max_luminance=111 >/dev/null +run_hdr on +assert_equal "$(rule_get DP-1 max_luminance)" "1234" "hdr on keeps a hand-tuned max_luminance" +assert_equal "$(rule_get DP-1 sdr_max_luminance)" "111" "hdr on keeps a hand-tuned SDR white" + +# ---- Disabling ---- + +reset_lua +run_hdr on +run_hdr off +assert_equal "$HDR_STATUS" "0" "hdr off exits 0" +assert_equal "$(rule_get DP-1 cm)" "srgb" "hdr off returns the display to sRGB" +assert_equal "$(rule_get DP-1 bitdepth)" "8" "hdr off returns the display to 8-bit" +assert_equal "$(rule_get DP-1 supports_hdr)" "0" "hdr off stops advertising HDR support" +assert_equal "$(rule_get DP-1 supports_wide_color)" "0" "hdr off stops advertising wide colour" +# Documented behaviour: the tuning is kept so switching back restores it. +assert_equal "$(rule_get DP-1 max_luminance)" "993" "hdr off leaves the luminance tuning in place" + +before=$(cat "$OMARCHY_MONITOR_LUA") +run_hdr off +assert_equal "$(cat "$OMARCHY_MONITOR_LUA")" "$before" "hdr off is idempotent in monitors.lua" + +# ---- sdr-brightness validation ---- + +for bad in 0 -5 abc 12.5 " " 1e3; do + reset_lua + run_hdr --sdr-brightness "$bad" + assert_nonzero_exit "$HDR_STATUS" "hdr rejects --sdr-brightness '$bad'" + assert_ok "hdr writes no rule for --sdr-brightness '$bad'" lua_unchanged + assert_equal "$(eval_count)" "0" "hdr reconfigures nothing for --sdr-brightness '$bad'" +done + +reset_lua +run_hdr --sdr-brightness= +assert_nonzero_exit "$HDR_STATUS" "hdr rejects an empty --sdr-brightness=" + +reset_lua +run_hdr --sdr-brightness 250 +assert_equal "$HDR_STATUS" "0" "hdr accepts a whole number of nits" +assert_equal "$(rule_get DP-1 sdr_max_luminance)" "250" "hdr persists the requested SDR white" +assert_ok "hdr applies the requested SDR white live" test "$(eval_count)" -ge 1 + +reset_lua +run_hdr --sdr-brightness=250 +assert_equal "$HDR_STATUS" "0" "hdr accepts --sdr-brightness=NITS" +assert_equal "$(rule_get DP-1 sdr_max_luminance)" "250" "the = form persists the same value" + +# An explicit value must beat the EDID-derived default in the same invocation, +# whichever order the two are computed in. +reset_lua +run_hdr on --sdr-brightness 175 +assert_equal "$HDR_STATUS" "0" "hdr on with an explicit SDR white succeeds" +assert_equal "$(rule_get DP-1 sdr_max_luminance)" "175" "an explicit SDR white overrides the derived default" +assert_equal "$(rule_get DP-1 cm)" "hdr" "the on action still applies alongside --sdr-brightness" +assert_equal "$(grep -c 'sdr_max_luminance' "$OMARCHY_MONITOR_LUA")" "1" "only one SDR white value is written" + +# A requested change must never be silently dropped: either apply it or refuse. +reset_lua +run_hdr status --sdr-brightness 200 +if [[ $HDR_STATUS != 0 ]]; then + pass "hdr status with --sdr-brightness is refused rather than ignored" +else + assert_equal "$(rule_get DP-1 sdr_max_luminance)" "200" \ + "hdr status with --sdr-brightness applies the value rather than dropping it" +fi + +# ---- omarchy-hyprland-monitor-capabilities ---- + +cap_run() { + CAP_OUT=$(PATH="$TEST_PATH" timeout 10 "$CAPABILITIES" "$@" 2>"$WORK/stderr" "$HYPRCTL_LOG" +cap_run "$ABSENT" +assert_equal "$CAP_STATUS" "0" "capabilities exits 0 for a display it cannot read" +assert_ok "capabilities prints JSON" is_json "$CAP_OUT" +assert_equal "$(jq -r '.name' <<<"$CAP_OUT")" "$ABSENT" "capabilities echoes the display it was asked about" +assert_equal "$(jq -r '.hdr' <<<"$CAP_OUT")" "false" "an unreadable display is not claimed to be HDR capable" +assert_ok "capabilities gives a reason when it reports no HDR" \ + bash -c "[[ -n \$(jq -r '.reason // empty' <<<'$CAP_OUT') ]]" +assert_equal "$(jq -r 'type' <<<"$CAP_OUT")" "object" "capabilities prints a single object for a single display" + +# hdr:false is only meaningful when it means "the EDID says so". Every reason it +# reports must be distinguishable, and asking about something with no EDID at +# all must not be reported as a decoded EDID lacking PQ. +assert_ok "an absent EDID is not reported as a decoded EDID without PQ" \ + bash -c "[[ \$(jq -r '.reason' <<<'$CAP_OUT') != 'no-pq-eotf' ]]" + +# Real capability output is consumed by hdr, which reads .hdr and the luminance +# fields; a capable display must carry numbers, not strings. +cap_run "$ABSENT" +assert_equal "$(jq -r 'has("max_luminance") | not' <<<"$CAP_OUT")" "true" \ + "a non-capable display advertises no luminances" + +# Every flag its two siblings accept is either handled or rejected. Reporting a +# flag as a non-HDR-capable display is a fabricated answer. +for flag in --help -h --bogus; do + cap_run "$flag" + if [[ $CAP_STATUS != 0 ]]; then + pass "capabilities rejects $flag" + elif [[ $flag == --bogus ]]; then + assert_ok "capabilities $flag is not answered as if it were a display" \ + bash -c "[[ \$(jq -r '.name // empty' <<<'$CAP_OUT' 2>/dev/null) != '$flag' ]]" + else + # Both siblings answer -h/--help with usage text and exit 0; whatever this + # one does, it must not invent a display called "--help". + assert_contains "$CAP_OUT" "Usage" "capabilities $flag prints usage rather than a fabricated display" + fi +done + +# With no arguments it enumerates the compositor's displays: one JSON object per +# line, so a caller can read it with a while loop. +: >"$HYPRCTL_LOG" +cap_run +assert_equal "$CAP_STATUS" "0" "capabilities with no arguments exits 0" +assert_equal "$(printf '%s\n' "$CAP_OUT" | wc -l)" "3" "capabilities prints one line per display" +assert_ok "every enumerated line is valid JSON with a name and an hdr flag" \ + bash -c "printf '%s\n' \"\$1\" | jq -e -s 'length == 3 and all(has(\"name\") and (.hdr | type) == \"boolean\")' >/dev/null" _ "$CAP_OUT" +assert_equal "$(printf '%s\n' "$CAP_OUT" | jq -rs 'map(.name) | join(",")')" "DP-1,DP-2,DP-3" \ + "capabilities reports the displays the compositor lists, in order" + +# ---- Result ---- + +if ((${#FAILURES[@]})); then + fail "monitor hdr and capabilities suite" "$(printf ' %s\n' "${FAILURES[@]}")" +fi + +pass "monitor hdr and capabilities suite" diff --git a/test/shell.d/monitor-rotate-test.sh b/test/shell.d/monitor-rotate-test.sh new file mode 100755 index 000000000000..fafd802baa8c --- /dev/null +++ b/test/shell.d/monitor-rotate-test.sh @@ -0,0 +1,399 @@ +#!/bin/bash + +# Covers omarchy-hyprland-monitor-rotate: the degrees the user types, the +# Hyprland `transform` those become, and the argument handling around them. +# +# Nothing here may rotate a real display, so hyprctl, omarchy-hyprland-monitor-rule +# and omarchy-hyprland-monitor-tidy are all replaced by stubs on PATH that record +# what they were asked to do. The layout the command reads comes from the stubbed +# `hyprctl monitors`, so no compositor is involved. + +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +require_command jq + +ROTATE="$ROOT/bin/omarchy-hyprland-monitor-rotate" + +test_tmp=$(mktemp -d) +trap 'rm -rf "$test_tmp"' EXIT + +stub_bin="$test_tmp/bin" +order_log="$test_tmp/order" +err_log="$test_tmp/stderr" +mkdir -p "$stub_bin" + +# One shared log for every side effect, in the order it happened, so tests can +# assert *ordering* (the clearance pass has to run before the display turns) +# rather than just that something was called. +cat >"$stub_bin/hyprctl" <<'SH' +#!/bin/bash +if [[ $1 == "monitors" ]]; then + printf '%s\n' "$OMARCHY_TEST_MONITORS" +elif [[ $1 == "eval" ]]; then + printf 'eval %s\n' "$2" >>"$OMARCHY_TEST_ORDER_LOG" +else + exit 1 +fi +SH + +cat >"$stub_bin/omarchy-hyprland-monitor-rule" <<'SH' +#!/bin/bash +printf 'rule %s\n' "$*" >>"$OMARCHY_TEST_ORDER_LOG" +SH + +cat >"$stub_bin/omarchy-hyprland-monitor-tidy" <<'SH' +#!/bin/bash +printf 'tidy %s\n' "$1" >>"$OMARCHY_TEST_ORDER_LOG" +SH + +chmod +x "$stub_bin/hyprctl" "$stub_bin/omarchy-hyprland-monitor-rule" "$stub_bin/omarchy-hyprland-monitor-tidy" + +assert_equal() { + local actual="$1" expected="$2" description="$3" + + if [[ $actual == "$expected" ]]; then + pass "$description" + else + fail "$description" "expected: $expected +actual: $actual" + fi +} + +assert_true() { + local condition="$1" description="$2" detail="${3:-}" + + if [[ $condition == "yes" ]]; then + pass "$description" + else + fail "$description" "$detail" + fi +} + +# The confirmed-open defects get soft assertions so one failure does not hide the +# others; the file still exits non-zero if any of them is still broken. +open_defects=0 + +expect() { + local condition="$1" description="$2" detail="${3:-}" + + if [[ $condition == "yes" ]]; then + pass "$description" + else + [[ -n $detail ]] && printf '%s\n' "$detail" >&2 + printf 'not ok - %s\n' "$description" >&2 + open_defects=$((open_defects + 1)) + fi +} + +yes_no() { + if "$@"; then echo yes; else echo no; fi +} + +# A layout of one focused display at the given transform, plus an unfocused +# neighbour so --monitor has something else to aim at. +layout() { + local transform="${1:-0}" + + jq -cn --argjson t "$transform" '[ + {name:"DP-1",focused:true,width:1920,height:1080,scale:1,transform:$t,x:0,y:0,mirrorOf:"none"}, + {name:"DP-2",focused:false,width:1920,height:1080,scale:1,transform:0,x:1920,y:0,mirrorOf:"none"} + ]' +} + +rotate_out="" +rotate_status=0 + +# Every invocation runs under a timeout: an argument the command cannot make +# progress on must fail, not spin. +rotate() { + local monitors="$1" + shift + + : >"$order_log" + : >"$err_log" + rotate_status=0 + rotate_out=$( + PATH="$stub_bin:$PATH" \ + OMARCHY_TEST_MONITORS="$monitors" \ + OMARCHY_TEST_ORDER_LOG="$order_log" \ + timeout 10 "$ROTATE" "$@" 2>"$err_log" + ) || rotate_status=$? +} + +applied_transform() { + { grep '^eval ' "$order_log" || true; } | sed -n 's/.*transform = \([0-9]*\).*/\1/p' | tail -1 +} + +persisted_transform() { + { grep '^rule ' "$order_log" || true; } | sed -n 's/.*transform=\([0-9]*\).*/\1/p' | tail -1 +} + +target_display() { + { grep '^eval ' "$order_log" || true; } | sed -n 's/.*output = "\([^"]*\)".*/\1/p' | tail -1 +} + +no_side_effects() { + [[ ! -s $order_log ]] +} + +# --- degrees to transform ----------------------------------------------------- + +# The whole point of the command: users say degrees, Hyprland wants 0-3. +while read -r degrees expected; do + rotate "$(layout 0)" "$degrees" + + assert_equal "$rotate_status" "0" "rotate $degrees succeeds" + assert_equal "$(applied_transform)" "$expected" "rotate $degrees applies transform $expected" + assert_equal "$(persisted_transform)" "$expected" "rotate $degrees persists transform $expected" + # What it prints back must agree with what it did, so a caller reading the + # output sees the rotation that is now in effect. + assert_equal "$rotate_out" "$degrees" "rotate $degrees reports $degrees degrees" +done <<'CASES' +0 0 +90 1 +180 2 +270 3 +CASES + +# The named aliases are documented in the usage text, so each has to land on the +# same transform as its degree form. +while read -r name expected; do + rotate "$(layout 0)" "$name" + + assert_equal "$rotate_status" "0" "rotate $name succeeds" + assert_equal "$(applied_transform)" "$expected" "rotate $name is transform $expected" + assert_equal "$rotate_out" "$((expected * 90))" "rotate $name reports $((expected * 90)) degrees" +done <<'CASES' +normal 0 +none 0 +left 1 +flip 2 +inverted 2 +upside-down 2 +right 3 +CASES + +# Names are matched case-insensitively, so a shell alias or menu entry using +# capitals is not silently rejected. +rotate "$(layout 0)" "LEFT" +assert_equal "$rotate_status" "0" "rotate accepts a rotation name in capitals" +assert_equal "$(applied_transform)" "1" "rotate LEFT is the same as rotate left" + +# --- flipped transforms 4-7 --------------------------------------------------- + +# 4-7 are 0-3 mirrored. The invariant is: transform - 4 is the plain rotation, +# and the reported degrees stay the plain angle. +while read -r degrees expected; do + rotate "$(layout 0)" "$degrees" --flipped + + assert_equal "$(applied_transform)" "$expected" "rotate $degrees --flipped is transform $expected" + assert_equal "$(persisted_transform)" "$expected" "rotate $degrees --flipped persists transform $expected" + assert_equal "$rotate_out" "$degrees" "rotate $degrees --flipped still reports $degrees degrees" +done <<'CASES' +0 4 +90 5 +180 6 +270 7 +CASES + +# A display that is already mirrored must stay mirrored when it is merely +# rotated, otherwise a rotation silently undoes the mirroring. +while read -r current degrees expected; do + rotate "$(layout "$current")" "$degrees" + + assert_equal "$(applied_transform)" "$expected" \ + "rotate $degrees from transform $current keeps the display mirrored (transform $expected)" +done <<'CASES' +4 90 5 +5 180 6 +6 270 7 +7 0 4 +CASES + +# --no-flipped is the only way back out of the mirrored half. +while read -r current degrees expected; do + rotate "$(layout "$current")" "$degrees" --no-flipped + + assert_equal "$(applied_transform)" "$expected" \ + "rotate $degrees --no-flipped from transform $current unmirrors to transform $expected" +done <<'CASES' +4 0 0 +5 90 1 +6 180 2 +7 270 3 +CASES + +# --flipped on an already-mirrored display is a no-op rather than a double flip +# back to the plain half. +rotate "$(layout 5)" 90 --flipped +assert_equal "$(applied_transform)" "5" "rotate --flipped on an already mirrored display stays mirrored" + +# An unmirrored display stays unmirrored without --flipped, and --no-flipped on +# one changes nothing about the mirroring. +rotate "$(layout 0)" 90 +assert_equal "$(applied_transform)" "1" "rotate leaves an unmirrored display unmirrored" +rotate "$(layout 1)" 270 --no-flipped +assert_equal "$(applied_transform)" "3" "rotate --no-flipped on an unmirrored display just rotates" + +# Asking for the rotation a display is already in must still produce that +# rotation: running the command twice is the same as running it once. +rotate "$(layout 1)" 90 +first_transform=$(applied_transform) +first_out="$rotate_out" +rotate "$(layout "$first_transform")" 90 +assert_equal "$(applied_transform)" "$first_transform" "rotating to the current rotation is idempotent" +assert_equal "$rotate_out" "$first_out" "rotating to the current rotation reports the same degrees" + +# --- reading the current rotation --------------------------------------------- + +# With no rotation the command is a read: every transform 0-7 reports its plain +# angle, and nothing is written anywhere. +for current in 0 1 2 3 4 5 6 7; do + rotate "$(layout "$current")" + + assert_equal "$rotate_status" "0" "reading the rotation of transform $current succeeds" + assert_equal "$rotate_out" "$(((current % 4) * 90))" "transform $current reads as $(((current % 4) * 90)) degrees" + assert_true "$(yes_no no_side_effects)" "reading the rotation of transform $current changes nothing" \ + "side effects: $(cat "$order_log")" +done + +# --- rejected rotations ------------------------------------------------------- + +# Only quarter turns exist as transforms. Anything else must be refused +# outright, and refused *before* anything is applied -- a half-applied rotation +# would leave the live layout and monitors.lua disagreeing. +for bad in 45 91 360 -90 1 3 89 270.0 900 leftish "90deg" " "; do + rotate "$(layout 0)" "$bad" + + assert_true "$(yes_no test "$rotate_status" -ne 0)" "rotate rejects '$bad'" \ + "exit=$rotate_status out=$rotate_out" + assert_true "$(yes_no no_side_effects)" "rotate applies nothing for '$bad'" \ + "side effects: $(cat "$order_log")" + assert_true "$(yes_no test -s "$err_log")" "rotate explains why '$bad' was rejected" +done + +# An empty rotation argument is read as "no rotation given", which is at worst +# harmless: what must never happen is a partial turn, so nothing may be applied. +rotate "$(layout 2)" "" +assert_true "$(yes_no no_side_effects)" "rotate applies nothing for an empty rotation" \ + "side effects: $(cat "$order_log")" + +# --- argument validation ------------------------------------------------------ + +# A second rotation is ambiguous, so it is an error rather than last-wins. +rotate "$(layout 0)" 90 180 +assert_true "$(yes_no test "$rotate_status" -ne 0)" "rotate rejects two rotations" +assert_true "$(yes_no no_side_effects)" "rotate applies nothing when given two rotations" + +# An unknown display name must not fall back to the focused one. +rotate "$(layout 0)" 90 --monitor NO-SUCH +assert_true "$(yes_no test "$rotate_status" -ne 0)" "rotate rejects an unknown display" +assert_true "$(yes_no no_side_effects)" "rotate applies nothing for an unknown display" + +# Nothing to rotate is an error, not a silent success. +rotate '[]' 90 +assert_true "$(yes_no test "$rotate_status" -ne 0)" "rotate fails when there is no display at all" +assert_true "$(yes_no no_side_effects)" "rotate applies nothing when there is no display" + +# No display is focused (a locked or headless session): there is no sensible +# default target, so it must not pick one arbitrarily. +UNFOCUSED='[{"name":"DP-1","focused":false,"width":1920,"height":1080,"scale":1,"transform":0,"x":0,"y":0,"mirrorOf":"none"}]' +rotate "$UNFOCUSED" 90 +assert_true "$(yes_no test "$rotate_status" -ne 0)" "rotate fails when no display is focused" +assert_true "$(yes_no no_side_effects)" "rotate applies nothing when no display is focused" + +# --monitor aims at a named display instead of the focused one, in both spellings. +rotate "$(layout 0)" 90 --monitor DP-2 +assert_equal "$rotate_status" "0" "rotate --monitor targets a named display" +assert_equal "$(target_display)" "DP-2" "rotate --monitor DP-2 rotates DP-2" +rotate "$(layout 0)" 90 --monitor=DP-2 +assert_equal "$(target_display)" "DP-2" "rotate --monitor=DP-2 rotates DP-2" + +# Order of flags and rotation must not matter. +rotate "$(layout 0)" --monitor DP-2 --flipped 270 +assert_equal "$(applied_transform)" "7" "rotate accepts the rotation after its flags" +assert_equal "$(target_display)" "DP-2" "rotate still targets the named display with the rotation last" + +# --help is a documented read-only path. +for flag in -h --help; do + rotate "$(layout 0)" "$flag" + + assert_equal "$rotate_status" "0" "rotate $flag succeeds" + assert_true "$(yes_no grep -q 'Usage:' <<<"$rotate_out")" "rotate $flag prints usage" + assert_true "$(yes_no no_side_effects)" "rotate $flag changes nothing" +done + +# The usage text is the only documentation of the rotation vocabulary, so it has +# to actually list the words the parser accepts. +rotate "$(layout 0)" --help +for word in 90 180 270 left right flip --flipped --no-flipped --no-tidy; do + assert_true "$(yes_no grep -q -- "$word" <<<"$rotate_out")" "usage mentions $word" +done + +# --- tidying ------------------------------------------------------------------ + +# A quarter turn changes the display's footprint, so by default neighbours are +# re-packed: once to clear room *before* the turn (Hyprland warns the instant two +# displays overlap) and once afterwards to close the gap that left. +rotate "$(layout 0)" 90 +tidy_calls=$(grep -c '^tidy' "$order_log" || true) +assert_true "$(yes_no test "$tidy_calls" -ge 1)" "rotate re-packs displays by default" +assert_equal \ + "$(grep -n '^tidy\|^eval' "$order_log" | head -1 | cut -d: -f2 | cut -d' ' -f1)" \ + "tidy" \ + "rotate clears room before it turns the display" + +# --no-tidy leaves positions alone but must still perform the rotation itself. +rotate "$(layout 0)" 90 --no-tidy +assert_equal "$rotate_status" "0" "rotate --no-tidy succeeds" +assert_equal "$(grep -c '^tidy' "$order_log" || true)" "0" "rotate --no-tidy re-packs nothing" +assert_equal "$(applied_transform)" "1" "rotate --no-tidy still applies the rotation" +assert_equal "$(persisted_transform)" "1" "rotate --no-tidy still persists the rotation" + +# A rotation is only useful if it survives a reload, so the live change and the +# persisted rule must always agree. +for degrees in 0 90 180 270; do + rotate "$(layout 0)" "$degrees" --flipped + assert_equal "$(applied_transform)" "$(persisted_transform)" \ + "the live and persisted transform agree for $degrees --flipped" +done + +# --- regressions for confirmed defects --------------------------------------- + +# A value-taking flag given no value must fail, not loop forever. `shift 2` on a +# single remaining argument shifts nothing, so the parser can spin at 100% CPU. +for flag in --monitor; do + rotate "$(layout 0)" "$flag" + + expect "$(yes_no test "$rotate_status" -ne 124)" "rotate $flag with no value terminates" \ + "timed out: the argument loop never made progress" + expect "$(yes_no test "$rotate_status" -ne 0)" "rotate $flag with no value is an error" +done + +# An explicitly empty --monitor= is a scripted caller interpolating an unset +# variable; retargeting the focused display instead is how the wrong display +# gets rotated. +rotate "$(layout 0)" 90 --monitor= +expect "$(yes_no test "$rotate_status" -ne 0)" "rotate rejects an empty --monitor=" \ + "exit=$rotate_status, rotated: $(target_display)" +expect "$(yes_no no_side_effects)" "rotate applies nothing for an empty --monitor=" \ + "side effects: $(cat "$order_log")" + +# The usage text advertises --no-flipped as the way to stop mirroring. On its own +# it currently prints the current angle and exits 0 having done nothing, so the +# documented way to unmirror silently does not work. +rotate "$(layout 5)" --no-flipped +unflipped=$(applied_transform) +expect "$(yes_no test "$rotate_status" -ne 0 -o -n "$unflipped")" \ + "rotate --no-flipped alone is not a silent no-op" \ + "exit=$rotate_status, side effects: $(cat "$order_log")" +if [[ -n $unflipped ]]; then + expect "$(yes_no test "$unflipped" -lt 4)" "rotate --no-flipped alone unmirrors the display" +fi + +if ((open_defects)); then + printf '%s confirmed defect(s) still unfixed\n' "$open_defects" >&2 + exit 1 +fi diff --git a/test/shell.d/monitor-rule-test.sh b/test/shell.d/monitor-rule-test.sh new file mode 100755 index 000000000000..ff1d7ede8efd --- /dev/null +++ b/test/shell.d/monitor-rule-test.sh @@ -0,0 +1,693 @@ +#!/bin/bash + +# Covers omarchy-hyprland-monitor-rule, which edits per-display rules in +# monitors.lua. The risk it exists to remove is bug #6673 -- a per-display +# setting landing on the catch-all rule and so applying to every display -- so +# most of what is asserted here is about touching one rule and nothing else. + +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +require_command python3 + +RULE="$ROOT/bin/omarchy-hyprland-monitor-rule" + +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT + +# No compositor is consulted: both are supplied so the command never shells out +# to hyprctl during the test. +export OMARCHY_MONITOR_DESCRIPTIONS='[{"name":"DP-1","description":"Dell Inc. AW3225QF HFL3YZ3"}]' +export OMARCHY_MONITOR_SEED='{"mode":"3840x2160@240","position":"0x0","scale":"1.6"}' + +assert_equal() { + local actual="$1" expected="$2" description="$3" + + if [[ $actual == "$expected" ]]; then + pass "$description" + else + fail "$description" "expected: $expected +actual: $actual" + fi +} + +assert_file_equals() { + local path="$1" expected="$2" description="$3" + + if [[ $(cat "$path") == "$expected" ]]; then + pass "$description" + else + fail "$description" "expected: +$expected + +actual: +$(cat "$path")" + fi +} + +write_config() { + cat >"$OMARCHY_MONITOR_LUA" +} + +# ---- Reading ---- + +export OMARCHY_MONITOR_LUA="$WORK/read.lua" +write_config <<'LUA' +hl.monitor({ output = "", mode = "preferred", position = "auto", scale = 1.6 }) +hl.monitor({ + output = "DP-1", + scale = 1.6, + cm = "hdr", + sdr_max_luminance = 250, +}) +hl.monitor({ output = "DP-3", position = "2400x0", transform = 1 }) +LUA + +assert_equal "$("$RULE" get DP-1 cm)" "hdr" "rule reads a field from a multi-line rule" +assert_equal "$("$RULE" get DP-1 sdr_max_luminance)" "250" "rule reads a numeric field" +assert_equal "$("$RULE" get DP-3 transform)" "1" "rule reads a field from a one-line rule" +assert_equal "$("$RULE" get DP-1 transform)" "" "rule reports an unset field as empty" +assert_equal "$("$RULE" get HDMI-A-1 scale)" "" "rule reports nothing for a display it has no rule for" + +# The catch-all speaks for every display, so a per-display read must not answer +# from it -- that conflation is what made a scale set on one display apply to +# all of them. +assert_equal "$("$RULE" get DP-9 mode)" "" "rule never answers from the catch-all" + +# ---- Updating in place ---- + +export OMARCHY_MONITOR_LUA="$WORK/update.lua" +write_config <<'LUA' +hl.monitor({ output = "", mode = "preferred", position = "auto", scale = 1.6 }) +hl.monitor({ output = "DP-3", position = "2400x0", transform = 1 }) +LUA + +"$RULE" set DP-3 transform=3 +assert_file_equals "$OMARCHY_MONITOR_LUA" 'hl.monitor({ output = "", mode = "preferred", position = "auto", scale = 1.6 }) +hl.monitor({ output = "DP-3", position = "2400x0", transform = 3 })' "rule updates a field without reflowing the line" + +# ---- Adding a field ---- + +export OMARCHY_MONITOR_LUA="$WORK/add.lua" +write_config <<'LUA' +hl.monitor({ output = "DP-3", position = "2400x0" }) +LUA + +"$RULE" set DP-3 transform=1 +assert_file_equals "$OMARCHY_MONITOR_LUA" 'hl.monitor({ output = "DP-3", position = "2400x0", transform = 1 })' "rule adds a field to a one-line rule" + +# A rule whose last line carries a trailing comment is the case that breaks +# naive appending: the separating comma ends up inside the comment, where Lua +# cannot see it, and the comment ends up describing the wrong field. +export OMARCHY_MONITOR_LUA="$WORK/comment.lua" +write_config <<'LUA' +hl.monitor({ + output = "DP-1", + scale = 1.6, + vrr = 0, -- off: adaptive sync flickers on this panel +}) +LUA + +"$RULE" set DP-1 transform=2 +assert_file_equals "$OMARCHY_MONITOR_LUA" 'hl.monitor({ + output = "DP-1", + scale = 1.6, + vrr = 0, -- off: adaptive sync flickers on this panel + transform = 2, +})' "rule adds a field after a commented line without stealing the comment" + +# ---- Removing a field ---- + +export OMARCHY_MONITOR_LUA="$WORK/remove.lua" +write_config <<'LUA' +hl.monitor({ output = "DP-3", position = "2400x0", transform = 1 }) +LUA + +"$RULE" unset DP-3 transform +assert_file_equals "$OMARCHY_MONITOR_LUA" 'hl.monitor({ output = "DP-3", position = "2400x0" })' "rule removes a trailing field and its separator" + +# ---- Creating a rule ---- + +export OMARCHY_MONITOR_LUA="$WORK/create.lua" +write_config <<'LUA' +hl.monitor({ output = "", mode = "preferred", position = "auto", scale = 1.6 }) +LUA + +"$RULE" set DP-1 cm=hdr +# The seeded geometry matters: a rule that omits position does not inherit the +# catch-all's, so a bare new rule would move the display to 0x0 on next reload. +assert_file_equals "$OMARCHY_MONITOR_LUA" 'hl.monitor({ output = "", mode = "preferred", position = "auto", scale = 1.6 }) + +hl.monitor({ output = "DP-1", mode = "3840x2160@240", position = "0x0", scale = 1.6, cm = "hdr" })' "rule creates a missing rule seeded with live geometry" + +# ---- Matching a desc: rule ---- + +# Users are encouraged to identify displays by description, since connector +# names move between ports. Such a rule must be recognised as the same display +# and keep the identifier its author chose. +export OMARCHY_MONITOR_LUA="$WORK/desc.lua" +write_config <<'LUA' +hl.monitor({ output = "desc:Dell Inc. AW3225QF HFL3YZ3", scale = 1.6 }) +LUA + +"$RULE" set DP-1 cm=hdr +assert_file_equals "$OMARCHY_MONITOR_LUA" 'hl.monitor({ output = "desc:Dell Inc. AW3225QF HFL3YZ3", scale = 1.6, cm = "hdr" })' "rule matches a display written as desc: without rewriting it" + +# ---- Value typing ---- + +export OMARCHY_MONITOR_LUA="$WORK/types.lua" +write_config <<'LUA' +hl.monitor({ output = "DP-1" }) +LUA + +"$RULE" set DP-1 bitdepth=10 cm=hdr min_luminance=0.001 supports_hdr=1 +assert_file_equals "$OMARCHY_MONITOR_LUA" 'hl.monitor({ output = "DP-1", bitdepth = 10, cm = "hdr", min_luminance = 0.001, supports_hdr = 1 })' "rule writes numbers bare and strings quoted" + +# ---- Leaving other rules alone ---- + +export OMARCHY_MONITOR_LUA="$WORK/isolated.lua" +write_config <<'LUA' +local omarchy_monitor_scale = 1.6 + +hl.env("GDK_SCALE", "2") +hl.monitor({ output = "", mode = "preferred", position = "auto", scale = omarchy_monitor_scale }) +hl.monitor({ output = "DP-1", scale = omarchy_monitor_scale }) +hl.monitor({ output = "DP-3", scale = omarchy_monitor_scale, transform = 1 }) +LUA + +"$RULE" set DP-1 transform=2 +assert_file_equals "$OMARCHY_MONITOR_LUA" 'local omarchy_monitor_scale = 1.6 + +hl.env("GDK_SCALE", "2") +hl.monitor({ output = "", mode = "preferred", position = "auto", scale = omarchy_monitor_scale }) +hl.monitor({ output = "DP-1", scale = omarchy_monitor_scale, transform = 2 }) +hl.monitor({ output = "DP-3", scale = omarchy_monitor_scale, transform = 1 })' "rule edits one display and leaves the catch-all and siblings untouched" + +# ---- Backups ---- + +export OMARCHY_MONITOR_LUA="$WORK/backup.lua" +write_config <<'LUA' +hl.monitor({ output = "DP-1", scale = 1.6 }) +LUA + +"$RULE" set DP-1 transform=1 +backup_count=$(find "$WORK" -maxdepth 1 -name 'backup.lua.bak.*' | wc -l) +assert_equal "$backup_count" "1" "rule backs the config up before rewriting it" + +# A write that changes nothing should not churn backups. +"$RULE" set DP-1 transform=1 +backup_count=$(find "$WORK" -maxdepth 1 -name 'backup.lua.bak.*' | wc -l) +assert_equal "$backup_count" "1" "rule does not back up when nothing changes" + +# ---- Refusing an unusable target ---- + +OMARCHY_MONITOR_LUA=/dev/null "$RULE" set DP-1 transform=1 2>/dev/null && status=0 || status=$? +assert_equal "$status" "1" "rule fails cleanly when the config is not a regular file" + +# ---- Additional coverage ---- + +# monitors.lua is executed by Hyprland's Lua config loader, so a rewrite that +# produces text Lua cannot parse takes the user's whole display configuration +# out, not just the field being edited. Every mutation below is checked for +# parseability rather than only for its expected text. +LUAC=$(command -v luac || true) + +assert_valid_lua() { + local path="$1" description="$2" output + + if [[ -z $LUAC ]]; then + pass "no luac; skipping $description" + return 0 + fi + + if output=$("$LUAC" -p "$path" 2>&1); then + pass "$description" + else + fail "$description" "$output + +file: +$(cat "$path")" + fi +} + +assert_files_equal() { + local left="$1" right="$2" description="$3" + + if cmp -s "$left" "$right"; then + pass "$description" + else + fail "$description" "$(diff -u "$left" "$right" || true)" + fi +} + +assert_files_differ() { + local left="$1" right="$2" description="$3" + + if cmp -s "$left" "$right"; then + fail "$description" "files are identical but should differ" + else + pass "$description" + fi +} + +# ---- Round-trip fidelity ---- + +# Callers toggle fields on and off all session long (the Display panel's HDR +# switch is set-then-unset). Adding a field and removing it again has to leave +# the file byte-identical, or every toggle erodes the user's formatting a little +# more. +export OMARCHY_MONITOR_LUA="$WORK/roundtrip-oneline.lua" +write_config <<'LUA' +hl.monitor({ output = "", mode = "preferred", position = "auto", scale = 1.6 }) +hl.monitor({ output = "DP-1", mode = "3840x2160@240", position = "0x0" }) +LUA +cp "$OMARCHY_MONITOR_LUA" "$WORK/roundtrip-oneline.orig" + +"$RULE" set DP-1 cm=hdr +assert_valid_lua "$OMARCHY_MONITOR_LUA" "a one-line rule is still valid Lua after set" +assert_files_differ "$WORK/roundtrip-oneline.orig" "$OMARCHY_MONITOR_LUA" "set on a one-line rule actually changes the file" +"$RULE" unset DP-1 cm +assert_files_equal "$WORK/roundtrip-oneline.orig" "$OMARCHY_MONITOR_LUA" "set then unset restores a one-line rule byte for byte" + +export OMARCHY_MONITOR_LUA="$WORK/roundtrip-multiline.lua" +write_config <<'LUA' +hl.monitor({ output = "", mode = "preferred", position = "auto", scale = 1.6 }) +hl.monitor({ + output = "DP-1", + mode = "3840x2160@240", + position = "0x0", +}) +LUA +cp "$OMARCHY_MONITOR_LUA" "$WORK/roundtrip-multiline.orig" + +"$RULE" set DP-1 cm=hdr +assert_valid_lua "$OMARCHY_MONITOR_LUA" "a multi-line rule is still valid Lua after set" +"$RULE" unset DP-1 cm +assert_files_equal "$WORK/roundtrip-multiline.orig" "$OMARCHY_MONITOR_LUA" "set then unset restores a multi-line rule byte for byte" + +# A rule indented with something other than two spaces is the user's choice; a +# new field has to join it rather than impose the command's own indentation. +export OMARCHY_MONITOR_LUA="$WORK/indent.lua" +write_config <<'LUA' +hl.monitor({ + output = "DP-1", + scale = 1.6, +}) +LUA + +"$RULE" set DP-1 transform=1 +assert_file_equals "$OMARCHY_MONITOR_LUA" 'hl.monitor({ + output = "DP-1", + scale = 1.6, + transform = 1, +})' "rule adds a field at the indentation the rule already uses" + +# ---- Writing is idempotent ---- + +# The Display panel re-asserts values it has already written (a slider that +# lands back where it started, a reload that re-applies the current state). +# Writing the value a field already holds must be a no-op: not a reformat, and +# not another backup file. +export OMARCHY_MONITOR_LUA="$WORK/idempotent.lua" +write_config <<'LUA' +hl.monitor({ output = "", scale = 1.6 }) +hl.monitor({ output = "DP-1", scale = 1.6, transform = 1 }) +LUA +cp "$OMARCHY_MONITOR_LUA" "$WORK/idempotent.orig" + +"$RULE" set DP-1 transform=1 +assert_files_equal "$WORK/idempotent.orig" "$OMARCHY_MONITOR_LUA" "setting a field to the value it already holds changes nothing" + +"$RULE" set DP-1 transform=3 +cp "$OMARCHY_MONITOR_LUA" "$WORK/idempotent.after" +"$RULE" set DP-1 transform=3 +assert_files_equal "$WORK/idempotent.after" "$OMARCHY_MONITOR_LUA" "repeating a set is stable the second time" + +"$RULE" unset DP-1 transform +cp "$OMARCHY_MONITOR_LUA" "$WORK/idempotent.unset" +"$RULE" unset DP-1 transform +assert_files_equal "$WORK/idempotent.unset" "$OMARCHY_MONITOR_LUA" "unsetting an absent field changes nothing" + +# ---- Catch-all isolation ---- + +# Bug #6673 again, from the read side and the remove side: a field present only +# on the catch-all must look absent for a specific display, and unsetting it for +# that display must not strip it from the rule that speaks for every display. +export OMARCHY_MONITOR_LUA="$WORK/catchall.lua" +write_config <<'LUA' +hl.monitor({ output = "", mode = "preferred", position = "auto", scale = 1.6, vrr = 1 }) +hl.monitor({ output = "DP-1", scale = 1.6 }) +LUA +cp "$OMARCHY_MONITOR_LUA" "$WORK/catchall.orig" + +assert_equal "$("$RULE" get DP-1 vrr)" "" "a field set only on the catch-all reads as unset for a display" +"$RULE" unset DP-1 vrr +assert_files_equal "$WORK/catchall.orig" "$OMARCHY_MONITOR_LUA" "unsetting a catch-all-only field leaves the catch-all intact" + +"$RULE" set DP-1 vrr=0 +assert_equal "$("$RULE" get DP-1 vrr)" "0" "the per-display value is what reads back" +assert_valid_lua "$OMARCHY_MONITOR_LUA" "the file is still valid Lua after overriding a catch-all field" +# The catch-all line itself must be exactly as it was: the whole point is that +# one display's choice does not leak to the others. +assert_equal "$(head -n 1 "$OMARCHY_MONITOR_LUA")" 'hl.monitor({ output = "", mode = "preferred", position = "auto", scale = 1.6, vrr = 1 })' "overriding a field for one display does not rewrite the catch-all" + +# `set` addresses a display, never the catch-all, so asking for the catch-all by +# its own empty name must not hand back the shared value either. +assert_equal "$("$RULE" get "" scale)" "" "the catch-all is not readable as a display" + +# ---- Duplicate rules ---- + +# Hyprland applies the later rule, so when a config repeats a display the +# command has to read and write the one that is actually in force; editing the +# earlier one would look like it worked and change nothing. +export OMARCHY_MONITOR_LUA="$WORK/duplicate.lua" +write_config <<'LUA' +hl.monitor({ output = "DP-1", transform = 1 }) +hl.monitor({ output = "DP-1", transform = 2 }) +LUA + +assert_equal "$("$RULE" get DP-1 transform)" "2" "rule reads the later of two rules for the same display" +"$RULE" set DP-1 transform=3 +assert_file_equals "$OMARCHY_MONITOR_LUA" 'hl.monitor({ output = "DP-1", transform = 1 }) +hl.monitor({ output = "DP-1", transform = 3 })' "rule writes the later of two rules for the same display" + +# ---- desc: matching ---- + +# A desc: string can legally contain the punctuation the rule parser cares +# about. Braces inside it must not be read as rule structure, or the rule ends +# early and the display looks unconfigured. +export OMARCHY_MONITOR_LUA="$WORK/desc-punctuation.lua" +write_config <<'LUA' +hl.monitor({ output = "", scale = 1.6 }) +hl.monitor({ output = "desc:Dell {AW} 3225QF", scale = 2, transform = 1 }) +LUA + +assert_equal "$(OMARCHY_MONITOR_DESCRIPTIONS='[{"name":"DP-1","description":"Dell {AW} 3225QF"}]' "$RULE" get DP-1 scale)" "2" "rule reads a desc: rule whose description contains braces" +OMARCHY_MONITOR_DESCRIPTIONS='[{"name":"DP-1","description":"Dell {AW} 3225QF"}]' "$RULE" unset DP-1 transform +assert_file_equals "$OMARCHY_MONITOR_LUA" 'hl.monitor({ output = "", scale = 1.6 }) +hl.monitor({ output = "desc:Dell {AW} 3225QF", scale = 2 })' "rule unsets a field on a desc: rule and keeps the desc: identifier" +assert_valid_lua "$OMARCHY_MONITOR_LUA" "a desc: rule containing braces is still valid Lua after unset" + +# The alias only exists because the compositor told us this connector carries +# that description. Without that link the desc: rule is some other display's, +# and matching it would edit the wrong monitor. +export OMARCHY_MONITOR_LUA="$WORK/desc-unknown.lua" +write_config <<'LUA' +hl.monitor({ output = "desc:Some Other Panel", scale = 2 }) +LUA +assert_equal "$("$RULE" get DP-1 scale)" "" "a desc: rule for a different display is not matched" + +# ---- Comment and structure preservation ---- + +# Standalone comments inside and around a rule are the user's notes about their +# own hardware. An edit elsewhere in the rule must not disturb them. +export OMARCHY_MONITOR_LUA="$WORK/comments.lua" +write_config <<'LUA' +-- Displays, left to right. +hl.monitor({ + output = "DP-1", + -- 240 Hz needs DSC on this cable + mode = "3840x2160@240", + scale = 1.6, +}) +-- end of displays +LUA + +"$RULE" set DP-1 transform=1 +assert_file_equals "$OMARCHY_MONITOR_LUA" '-- Displays, left to right. +hl.monitor({ + output = "DP-1", + -- 240 Hz needs DSC on this cable + mode = "3840x2160@240", + scale = 1.6, + transform = 1, +}) +-- end of displays' "rule preserves standalone comments inside and around the rule" +assert_valid_lua "$OMARCHY_MONITOR_LUA" "a rule with interleaved comments is still valid Lua after set" + +# Removing a field from the middle of a rule must close the gap cleanly: no +# stray comma, no blank line, and the surviving fields in their original order. +export OMARCHY_MONITOR_LUA="$WORK/middle.lua" +write_config <<'LUA' +hl.monitor({ + output = "DP-1", + scale = 1.6, + transform = 1, + vrr = 0, +}) +LUA + +"$RULE" unset DP-1 transform +assert_file_equals "$OMARCHY_MONITOR_LUA" 'hl.monitor({ + output = "DP-1", + scale = 1.6, + vrr = 0, +})' "rule removes a middle field without leaving a hole" +assert_valid_lua "$OMARCHY_MONITOR_LUA" "the file is still valid Lua after removing a middle field" + +# A field whose name is a prefix of another must not be confused with it; `scale` +# and `scale_factor` (or `mode` and `modeline`) sit side by side in real configs. +export OMARCHY_MONITOR_LUA="$WORK/prefix.lua" +write_config <<'LUA' +hl.monitor({ output = "DP-1", scale = 1.6, scale_factor = 3 }) +LUA + +assert_equal "$("$RULE" get DP-1 scale)" "1.6" "a field name is matched whole, not as a prefix" +"$RULE" set DP-1 scale=2 +assert_file_equals "$OMARCHY_MONITOR_LUA" 'hl.monitor({ output = "DP-1", scale = 2, scale_factor = 3 })' "setting a field does not touch a field whose name extends it" + +# A nested table can repeat a top-level field name. Only the top-level one is a +# monitor setting; rewriting the nested copy would change something else. +export OMARCHY_MONITOR_LUA="$WORK/nested.lua" +write_config <<'LUA' +hl.monitor({ output = "DP-1", extra = { scale = 99 }, scale = 1.6 }) +LUA + +assert_equal "$("$RULE" get DP-1 scale)" "1.6" "rule reads the top-level field, not a same-named one nested inside" +"$RULE" set DP-1 scale=2 +assert_file_equals "$OMARCHY_MONITOR_LUA" 'hl.monitor({ output = "DP-1", extra = { scale = 99 }, scale = 2 })' "rule writes the top-level field and leaves a nested table alone" +assert_valid_lua "$OMARCHY_MONITOR_LUA" "a rule with a nested table is still valid Lua after set" + +# ---- Values ---- + +export OMARCHY_MONITOR_LUA="$WORK/values.lua" +write_config <<'LUA' +hl.monitor({ output = "DP-1" }) +LUA + +"$RULE" set DP-1 vrr=true transform=-1 min_luminance=0.005 mode=raw:omarchy_mode cm='wide gamut' +assert_valid_lua "$OMARCHY_MONITOR_LUA" "a rule written with mixed value types is valid Lua" +assert_equal "$("$RULE" get DP-1 vrr)" "true" "a boolean round-trips through get" +assert_equal "$("$RULE" get DP-1 transform)" "-1" "a negative number round-trips through get" +assert_equal "$("$RULE" get DP-1 min_luminance)" "0.005" "a fractional number round-trips through get" +# `raw:` exists so a rule can reference a Lua variable (the catch-all scale +# local); it must land unquoted or Lua sees a string, not the variable. +assert_equal "$("$RULE" get DP-1 mode)" "omarchy_mode" "a raw: value is written verbatim and reads back unquoted" +assert_equal "$("$RULE" get DP-1 cm)" "wide gamut" "a string with a space round-trips through get" + +# ---- Creating a rule ---- + +# Displays whose scale the user pinned are addressed by name; the created rule +# must carry the requested value rather than the seeded one when they collide on +# the same field, or the request is silently discarded. +export OMARCHY_MONITOR_LUA="$WORK/create-collision.lua" +write_config <<'LUA' +hl.monitor({ output = "", mode = "preferred", position = "auto", scale = 1.6 }) +LUA + +"$RULE" set DP-1 scale=2 +assert_equal "$("$RULE" get DP-1 scale)" "2" "creating a rule keeps the requested value over the seeded one" +assert_valid_lua "$OMARCHY_MONITOR_LUA" "a freshly created rule is valid Lua" +assert_equal "$(grep -c 'output = "DP-1"' "$OMARCHY_MONITOR_LUA")" "1" "creating a rule adds exactly one rule for the display" +assert_equal "$(head -n 1 "$OMARCHY_MONITOR_LUA")" 'hl.monitor({ output = "", mode = "preferred", position = "auto", scale = 1.6 })' "creating a rule leaves the catch-all untouched" + +# A display already addressed by desc: must not gain a second, conflicting rule +# under its connector name. +export OMARCHY_MONITOR_LUA="$WORK/create-desc.lua" +write_config <<'LUA' +hl.monitor({ output = "desc:Dell Inc. AW3225QF HFL3YZ3", scale = 1.6 }) +LUA + +"$RULE" set DP-1 transform=1 +assert_equal "$(grep -c 'hl.monitor' "$OMARCHY_MONITOR_LUA")" "1" "a display already written as desc: does not gain a duplicate rule" + +# ---- Absent config ---- + +export OMARCHY_MONITOR_LUA="$WORK/absent.lua" +assert_equal "$("$RULE" get DP-1 scale)" "" "get on a config that does not exist reports nothing" +"$RULE" get DP-1 scale >/dev/null && status=0 || status=$? +assert_equal "$status" "0" "get on a config that does not exist succeeds" + +"$RULE" unset DP-1 scale +[[ -e $OMARCHY_MONITOR_LUA ]] && created=yes || created=no +assert_equal "$created" "no" "unset does not conjure a config file" + +"$RULE" set DP-1 transform=1 +assert_valid_lua "$OMARCHY_MONITOR_LUA" "a config created from nothing is valid Lua" +assert_equal "$("$RULE" get DP-1 transform)" "1" "a rule written into a new config reads back" + +# ---- Unknown display ---- + +export OMARCHY_MONITOR_LUA="$WORK/unknown.lua" +write_config <<'LUA' +hl.monitor({ output = "", scale = 1.6 }) +hl.monitor({ output = "DP-1", scale = 1.6 }) +LUA +cp "$OMARCHY_MONITOR_LUA" "$WORK/unknown.orig" + +"$RULE" unset HDMI-A-1 scale +assert_files_equal "$WORK/unknown.orig" "$OMARCHY_MONITOR_LUA" "unset for a display with no rule leaves the config alone" + +# ---- Removing every optional field ---- + +# The Display panel can walk a display back to defaults one field at a time. The +# rule that is left must still be a legal, matchable rule, not an empty husk. +export OMARCHY_MONITOR_LUA="$WORK/strip.lua" +write_config <<'LUA' +hl.monitor({ output = "DP-1", scale = 1.6, transform = 1, vrr = 0 }) +LUA + +"$RULE" unset DP-1 scale transform vrr +assert_valid_lua "$OMARCHY_MONITOR_LUA" "a rule stripped of every optional field is valid Lua" +assert_equal "$("$RULE" get DP-1 output)" "DP-1" "a stripped rule still identifies its display" + +# ---- Backups ---- + +# The backup only earns its place if it holds what was there before the write. +export OMARCHY_MONITOR_LUA="$WORK/backup-content.lua" +write_config <<'LUA' +hl.monitor({ output = "DP-1", scale = 1.6 }) +LUA +cp "$OMARCHY_MONITOR_LUA" "$WORK/backup-content.orig" + +"$RULE" set DP-1 scale=2 +assert_files_equal "$WORK/backup-content.orig" "$(find "$WORK" -maxdepth 1 -name 'backup-content.lua.bak.*' | head -n 1)" "the backup holds the config as it was before the write" + +# ---- Interface ---- + +assert_equal "$(OMARCHY_MONITOR_LUA=/some/where/monitors.lua "$RULE" path)" "/some/where/monitors.lua" "path reports the config the command edits" + +"$RULE" --help >/dev/null 2>&1 && status=0 || status=$? +assert_equal "$status" "0" "--help succeeds" + +"$RULE" >/dev/null 2>&1 && status=0 || status=$? +assert_equal "$status" "1" "no arguments is a usage error" + +"$RULE" frobnicate DP-1 scale >/dev/null 2>&1 && status=0 || status=$? +assert_equal "$status" "1" "an unknown action is a usage error" + +"$RULE" get DP-1 >/dev/null 2>&1 && status=0 || status=$? +assert_equal "$status" "1" "get without a field is a usage error" + +"$RULE" set DP-1 >/dev/null 2>&1 && status=0 || status=$? +assert_equal "$status" "1" "set without a field is a usage error" + +"$RULE" unset DP-1 >/dev/null 2>&1 && status=0 || status=$? +assert_equal "$status" "1" "unset without a field is a usage error" + +# Usage text belongs on stderr when it is an error, so a caller capturing stdout +# does not mistake it for a value. +assert_equal "$("$RULE" get DP-1 2>/dev/null || true)" "" "a usage error writes nothing to stdout" + +# ---- Lua the scanner has to actually understand ---- +# +# These all come from one root cause: a scanner that knows only `--` line +# comments. It cannot see a --[[ ]] block comment or a [[ ]] long string, so +# commented-out examples read as live rules and quotes inside long strings +# throw off the brace matching. + +assert_lua_valid() { + local path="$1" description="$2" + + if command -v luac >/dev/null; then + if luac -p "$path" 2>/dev/null; then + pass "$description" + else + fail "$description" "$(cat "$path")" + fi + else + pass "$description (luac absent)" + fi +} + +# A commented-out rule is documentation, not configuration. Editing it instead +# of the live rule silently drops the change and rewrites the example. +export OMARCHY_MONITOR_LUA="$WORK/commented.lua" +write_config <<'LUA' +-- hl.monitor({ output = "DP-1", scale = 9 }) +hl.monitor({ output = "DP-1", scale = 1.6 }) +LUA +"$RULE" set DP-1 scale=2 +assert_file_equals "$OMARCHY_MONITOR_LUA" '-- hl.monitor({ output = "DP-1", scale = 9 }) +hl.monitor({ output = "DP-1", scale = 2 })' "rule ignores a commented-out rule and edits the live one" + +export OMARCHY_MONITOR_LUA="$WORK/block.lua" +write_config <<'LUA' +--[[ +hl.monitor({ output = "DP-1", scale = 9 }) +]] +hl.monitor({ output = "DP-1", scale = 1.6 }) +LUA +assert_equal "$("$RULE" get DP-1 scale)" "1.6" "rule reads past a block-commented rule" +"$RULE" set DP-1 transform=1 +assert_lua_valid "$OMARCHY_MONITOR_LUA" "rule leaves valid Lua beside a block comment" +assert_equal "$("$RULE" get DP-1 transform)" "1" "rule writes to the live rule beside a block comment" + +# A value must stop at its separator. Swallowing the trailing comment means get +# returns the comment text and set deletes it. +export OMARCHY_MONITOR_LUA="$WORK/trailing.lua" +write_config <<'LUA' +hl.monitor({ + output = "DP-1", + vrr = 0, -- adaptive sync flickers on this panel +}) +LUA +assert_equal "$("$RULE" get DP-1 vrr)" "0" "rule reads a value without its trailing comment" + +# A long string can contain a quote, which naive quote-tracking reads as the +# start of a string, hiding the rule and appending a duplicate. +export OMARCHY_MONITOR_LUA="$WORK/longstring.lua" +write_config <<'LUA' +local note = [[a " quote]] +hl.monitor({ output = "DP-1", scale = 1.6 }) +LUA +"$RULE" set DP-1 transform=1 +assert_equal "$(grep -c 'hl.monitor' "$OMARCHY_MONITOR_LUA")" "1" "rule does not duplicate a rule hidden behind a long string" +assert_lua_valid "$OMARCHY_MONITOR_LUA" "rule leaves valid Lua beside a long string" + +# Lua allows the last field to have no trailing comma. +export OMARCHY_MONITOR_LUA="$WORK/nocomma.lua" +write_config <<'LUA' +hl.monitor({ + output = "DP-1", + scale = 1.6 +}) +LUA +"$RULE" set DP-1 transform=1 +assert_lua_valid "$OMARCHY_MONITOR_LUA" "rule leaves valid Lua when the last field had no comma" +assert_equal "$("$RULE" get DP-1 scale)" "1.6" "rule keeps the neighbouring field when the last had no comma" + +# ---- Not disturbing the file itself ---- + +# A config kept in a dotfiles repo is usually symlinked. Replacing the link with +# a regular file orphans the source, and the next dotfiles sync undoes the edit. +export OMARCHY_MONITOR_LUA="$WORK/link.lua" +printf 'hl.monitor({ output = "DP-1", scale = 1.6 })\n' >"$WORK/linked-source.lua" +ln -sf "$WORK/linked-source.lua" "$OMARCHY_MONITOR_LUA" +"$RULE" set DP-1 transform=1 +if [[ -L $OMARCHY_MONITOR_LUA ]]; then + pass "rule writes through a symlink instead of replacing it" +else + fail "rule writes through a symlink instead of replacing it" +fi +assert_equal "$(grep -c 'transform = 1' "$WORK/linked-source.lua")" "1" "rule writes through to the symlink source" + +export OMARCHY_MONITOR_LUA="$WORK/crlf.lua" +printf 'hl.monitor({ output = "DP-1", scale = 1.6 })\r\n' >"$OMARCHY_MONITOR_LUA" +"$RULE" set DP-1 transform=1 +if grep -qU $'\r' "$OMARCHY_MONITOR_LUA"; then + pass "rule leaves CRLF line endings alone" +else + fail "rule leaves CRLF line endings alone" "$(cat -A "$OMARCHY_MONITOR_LUA")" +fi diff --git a/test/shell.d/monitor-state-test.sh b/test/shell.d/monitor-state-test.sh index b568172fdcda..ef1b8acfebe8 100755 --- a/test/shell.d/monitor-state-test.sh +++ b/test/shell.d/monitor-state-test.sh @@ -109,9 +109,9 @@ assert_line 4 "" "monitor state reports no mirror while clamshelled" pass "monitor state separates a disabled internal monitor from a missing one" monitor_state "$extended" -[[ ${state_lines[7]-} == '[{"name":"eDP-1","enabled":true,"focused":false,"width":1920,"height":1080},{"name":"DP-1","enabled":true,"focused":true,"width":2560,"height":1440}]' ]] || +[[ ${state_lines[7]-} == '[{"name":"eDP-1","enabled":true,"focused":false,"width":1920,"height":1080,"transform":0,"hdr":false,"sdrMaxLuminance":0},{"name":"DP-1","enabled":true,"focused":true,"width":2560,"height":1440,"transform":0,"hdr":false,"sdrMaxLuminance":0}]' ]] || fail "monitor state lists every display for the panel" "actual: ${state_lines[7]-}" monitor_state "$clamshell" -[[ ${state_lines[7]-} == '[{"name":"eDP-1","enabled":false,"focused":false,"width":0,"height":0},{"name":"DP-1","enabled":true,"focused":true,"width":2560,"height":1440}]' ]] || +[[ ${state_lines[7]-} == '[{"name":"eDP-1","enabled":false,"focused":false,"width":0,"height":0,"transform":0,"hdr":false,"sdrMaxLuminance":0},{"name":"DP-1","enabled":true,"focused":true,"width":2560,"height":1440,"transform":0,"hdr":false,"sdrMaxLuminance":0}]' ]] || fail "monitor state lists every display for the panel" "actual: ${state_lines[7]-}" pass "monitor state lists every display with its enabled and focused state" diff --git a/test/shell.d/monitor-test.sh b/test/shell.d/monitor-test.sh old mode 100644 new mode 100755 index 30014b22b965..77672b0d6c30 --- a/test/shell.d/monitor-test.sh +++ b/test/shell.d/monitor-test.sh @@ -4,6 +4,14 @@ set -euo pipefail source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" +require_command jq + +# Feed the panel what the capabilities command really prints, rather than a +# hand-written imitation of it. A connector name that cannot exist keeps the +# output identical on every machine while still exercising the real code path. +OMARCHY_TEST_CAPABILITIES_JSON=$("$ROOT/bin/omarchy-hyprland-monitor-capabilities" OMARCHY-TEST-0) +export OMARCHY_TEST_CAPABILITIES_JSON + run_node_test <<'JS' const monitor = requireFromRoot('shell/plugins/panels/monitor/Model.js') @@ -75,4 +83,359 @@ assertDeepEqual( ) assertDeepEqual(monitor.parseDisplays('{'), { displays: [], enabledDisplayCount: 0 }, 'monitor handles invalid display JSON') + +// ---- Rotation ---- +assertEqual(monitor.transformDegrees(0), 0, 'monitor reads an unrotated transform') +assertEqual(monitor.transformDegrees(1), 90, 'monitor reads a quarter-turn transform') +assertEqual(monitor.transformDegrees(3), 270, 'monitor reads a three-quarter-turn transform') +// 4-7 are the mirrored repeats of 0-3, so the angle is the transform mod 4. +assertEqual(monitor.transformDegrees(5), 90, 'monitor reads the angle of a mirrored transform') +assertEqual(monitor.transformDegrees('nope'), 0, 'monitor rejects an invalid transform') + +// ---- SDR luminance ---- +// The ceiling is the sustained full-field luminance, not the peak: peak applies +// to small highlights, and mapping SDR white there makes a white window dim as +// the panel's brightness limiter pulls power back. +assertDeepEqual(monitor.sdrLuminanceRange(277), { minimum: 40, maximum: 277 }, 'monitor derives the SDR range from full-field luminance') +assertDeepEqual(monitor.sdrLuminanceRange(0), { minimum: 40, maximum: 400 }, 'monitor falls back to a default SDR range') +// The range never narrows below 100 nits, because a narrower one cannot survive +// a round trip through whole percentages and the slider drifts a notch on its own. +assertDeepEqual(monitor.sdrLuminanceRange(50), { minimum: 40, maximum: 140 }, 'monitor keeps a usable SDR range on a dim display') + +assertEqual(monitor.clampSdrLuminance(250, 277), 250, 'monitor keeps an in-range SDR luminance') +assertEqual(monitor.clampSdrLuminance(900, 277), 277, 'monitor clamps SDR luminance to full-field luminance') +assertEqual(monitor.clampSdrLuminance(1, 277), 40, 'monitor clamps SDR luminance to the floor') +assertEqual(monitor.clampSdrLuminance('nope', 277), 40, 'monitor rejects an invalid SDR luminance') + +// ---- HDR capability ---- +assertDeepEqual( + monitor.parseCapabilities(JSON.stringify({ + name: 'DP-1', hdr: true, max_luminance: 993, max_avg_luminance: 277, min_luminance: 0.001 + })), + { name: 'DP-1', hdr: true, maxLuminance: 993, maxAvgLuminance: 277, minLuminance: 0.001 }, + 'monitor parses HDR capabilities' +) +assertDeepEqual( + monitor.parseCapabilities(JSON.stringify({ name: 'DP-3', hdr: false, reason: 'no-pq-eotf' })), + { name: 'DP-3', hdr: false, maxLuminance: 0, maxAvgLuminance: 0, minLuminance: 0 }, + 'monitor parses a display without HDR' +) +assertDeepEqual( + monitor.parseCapabilities('{'), + { name: '', hdr: false, maxLuminance: 0, maxAvgLuminance: 0, minLuminance: 0 }, + 'monitor handles invalid capability JSON' +) + +// The slider stays a percentage in both modes, so an SDR luminance converts to +// its position within the range the display can hold, and back. +assertEqual(monitor.sdrLuminanceToPercent(250, 277), 89, 'monitor expresses SDR luminance as a percentage') +assertEqual(monitor.sdrLuminanceToPercent(40, 277), 0, 'monitor puts the SDR floor at zero percent') +assertEqual(monitor.sdrLuminanceToPercent(277, 277), 100, 'monitor puts the SDR ceiling at full percent') +assertEqual(monitor.sdrPercentToLuminance(100, 277), 277, 'monitor maps full percent to the SDR ceiling') +assertEqual(monitor.sdrPercentToLuminance(0, 277), 40, 'monitor maps zero percent to the SDR floor') +assertEqual(monitor.sdrPercentToLuminance(150, 277), 277, 'monitor clamps an out-of-range percentage') +assertEqual(monitor.sdrPercentToLuminance('nope', 277), 40, 'monitor rejects an invalid percentage') +// Round-tripping must land back on the same percentage the slider showed. +assertEqual(monitor.sdrLuminanceToPercent(monitor.sdrPercentToLuminance(60, 277), 277), 60, 'monitor round-trips a percentage through luminance') + +// --------------------------------------------------------------------------- +// Properties. The cases above pin specific values; these assert the invariants +// the panel actually depends on, so a change of internal representation stays +// free but a change of behaviour does not. Each property is one assertion over +// a whole input space, reporting the offending inputs rather than a bare false. +// --------------------------------------------------------------------------- + +function assertHolds(violations, description) { + assert( + violations.length === 0, + description, + violations.length + ' violation(s), first few: ' + JSON.stringify(violations.slice(0, 5)) + ) +} + +var everyTransform = [0, 1, 2, 3, 4, 5, 6, 7] + +// ---- Rotation / transform mapping ---- + +// Every Hyprland transform is one of the four quarter turns, mirrored or not. +// The panel only offers degrees, so an angle outside that set is one it can +// neither render nor undo. +assertHolds( + everyTransform.filter(function(t) { + return monitor.rotationDegrees.indexOf(monitor.transformDegrees(t)) < 0 + }), + 'monitor reports every transform as one of the offered angles' +) + +// Hyprland reports transforms as numbers but the panel reads them back out of +// JSON, where a string is just as likely; the two readings must agree. +assertEqual(monitor.transformDegrees('2'), 180, 'monitor reads a transform given as a string') + +// Garbage must degrade to "unrotated" rather than to NaN, which would +// otherwise be written straight into monitors.lua. +assertHolds( + ['nope', null, undefined, NaN, -1, -8, Infinity].filter(function(bad) { + return monitor.transformDegrees(bad) !== 0 + }).map(String), + 'monitor reads an unusable transform as unrotated' +) + +// ---- SDR luminance range, clamp and percent round-trip ---- + +// 0 and the low ceilings matter because a panel that advertises a modest +// desired frame-average luminance is common; 4000 covers the other end. +var luminanceCeilings = [0, 50, 100, 120, 140, 200, 277, 400, 600, 1000, 4000] +var unusableCeilings = [0, -100, 'nope', null, undefined, NaN, Infinity] + +// A collapsed or inverted range would make the slider unusable and make the +// percent conversions divide by zero. A non-HDR display carries no full-field +// luminance in its EDID at all, so the unusable ceilings are the normal case. +assertHolds( + luminanceCeilings.concat(unusableCeilings).filter(function(ceiling) { + var range = monitor.sdrLuminanceRange(ceiling) + return !isFinite(range.minimum) || !isFinite(range.maximum) || range.maximum <= range.minimum + }).map(String), + 'monitor derives a usable SDR range from any ceiling' +) + +// Clamping is what stops a stale or hand-edited sdr_max_luminance being handed +// back to the compositor unchanged; and clamping an already-clamped value must +// not move it again, or the stored luminance drifts every time the panel opens. +var clampViolations = [] +luminanceCeilings.forEach(function(ceiling) { + var range = monitor.sdrLuminanceRange(ceiling) + ;[-1000, 0, 1, 39, 40, 100, 250, 5000, 'nope', NaN, Infinity, null].forEach(function(value) { + var clamped = monitor.clampSdrLuminance(value, ceiling) + if (clamped < range.minimum || clamped > range.maximum) { + clampViolations.push(String(value) + ' @ ' + ceiling + ' -> ' + clamped + ' (outside range)') + } else if (monitor.clampSdrLuminance(clamped, ceiling) !== clamped) { + clampViolations.push(String(value) + ' @ ' + ceiling + ' -> ' + clamped + ' (not settled)') + } + }) +}) +assertHolds(clampViolations, 'monitor clamps any SDR luminance into the range and leaves it there') + +// The slider position must always be a whole percentage, whatever luminance it +// is handed -- including one carried over from a display with another ceiling. +var percentViolations = [] +luminanceCeilings.forEach(function(ceiling) { + ;[-1000, 0, 40, 120, 5000, 'nope', NaN, null].forEach(function(value) { + var percent = monitor.sdrLuminanceToPercent(value, ceiling) + if (!Number.isInteger(percent) || percent < 0 || percent > 100) { + percentViolations.push(String(value) + ' @ ' + ceiling + ' -> ' + percent) + } + }) +}) +assertHolds(percentViolations, 'monitor expresses any SDR luminance as a whole percentage') + +// And the reverse: any percentage must land inside the range the display can +// hold, so the value written to monitors.lua is always legal. +var toLuminanceViolations = [] +luminanceCeilings.forEach(function(ceiling) { + var range = monitor.sdrLuminanceRange(ceiling) + ;[-50, 0, 33, 50, 100, 1000, 'nope', NaN, null].forEach(function(value) { + var nits = monitor.sdrPercentToLuminance(value, ceiling) + if (!(nits >= range.minimum && nits <= range.maximum)) { + toLuminanceViolations.push(String(value) + ' @ ' + ceiling + ' -> ' + nits) + } + }) +}) +assertHolds(toLuminanceViolations, 'monitor maps any percentage into the SDR range') + +// Dragging the slider right must never lower the luminance. +var monotonicViolations = [] +luminanceCeilings.forEach(function(ceiling) { + var previous = -Infinity + for (var p = 0; p <= 100; p++) { + var nits = monitor.sdrPercentToLuminance(p, ceiling) + if (nits < previous) monotonicViolations.push(p + '% @ ' + ceiling + ' -> ' + nits + ' after ' + previous) + previous = nits + } +}) +assertHolds(monotonicViolations, 'monitor raises SDR luminance monotonically with the slider') + +// The ends of the slider must reach the ends of the range exactly, or the user +// can never pick the dimmest or brightest SDR white the panel supports. +var endpointViolations = [] +luminanceCeilings.forEach(function(ceiling) { + var range = monitor.sdrLuminanceRange(ceiling) + if (monitor.sdrPercentToLuminance(0, ceiling) !== range.minimum) endpointViolations.push('0% @ ' + ceiling) + if (monitor.sdrPercentToLuminance(100, ceiling) !== range.maximum) endpointViolations.push('100% @ ' + ceiling) + if (monitor.sdrLuminanceToPercent(range.minimum, ceiling) !== 0) endpointViolations.push('floor @ ' + ceiling) + if (monitor.sdrLuminanceToPercent(range.maximum, ceiling) !== 100) endpointViolations.push('ceiling @ ' + ceiling) +}) +assertHolds(endpointViolations, 'monitor reaches both ends of the SDR range from both directions') + +// The same in the other direction: a luminance already in monitors.lua must +// survive being shown as a percentage and written back, to within one step of +// the slider it is displayed on. +var storedViolations = [] +luminanceCeilings.forEach(function(ceiling) { + var range = monitor.sdrLuminanceRange(ceiling) + var step = Math.ceil((range.maximum - range.minimum) / 100) + for (var nits = range.minimum; nits <= range.maximum; nits++) { + var again = monitor.sdrPercentToLuminance(monitor.sdrLuminanceToPercent(nits, ceiling), ceiling) + if (Math.abs(again - nits) > step) storedViolations.push(nits + ' @ ' + ceiling + ' -> ' + again) + } +}) +assertHolds(storedViolations, 'monitor keeps a stored SDR luminance within one slider step') + +// ---- HDR capability parsing ---- + +// The panel is handed whatever omarchy-hyprland-monitor-capabilities printed, so +// the parser must always produce the same five-field shape with usable types. A +// missing field has to read as absent, never as NaN or undefined, because the +// luminances go on to feed sdrLuminanceRange. +function capabilityShapeProblem(parsed) { + if (parsed === null || typeof parsed !== 'object') return 'not an object' + if (typeof parsed.name !== 'string') return 'name is ' + typeof parsed.name + if (typeof parsed.hdr !== 'boolean') return 'hdr is ' + typeof parsed.hdr + if (!isFinite(parsed.maxLuminance)) return 'maxLuminance is ' + parsed.maxLuminance + if (!isFinite(parsed.maxAvgLuminance)) return 'maxAvgLuminance is ' + parsed.maxAvgLuminance + if (!isFinite(parsed.minLuminance)) return 'minLuminance is ' + parsed.minLuminance + return '' +} + +var capabilityInputs = [ + '', null, undefined, '{', '[]', '[1,2]', 'null', 'true', '42', '"text"', '{}', + JSON.stringify({ name: 'DP-1', hdr: false, reason: 'no-edid' }), + JSON.stringify({ name: 'DP-1', hdr: false, reason: 'no-pq-eotf' }), + JSON.stringify({ name: 'DP-1', hdr: true, max_luminance: 'x', max_avg_luminance: null }), + JSON.stringify({ name: 'DP-1', hdr: true, max_luminance: null, max_avg_luminance: null, min_luminance: null }), + JSON.stringify({ name: 'DP-1', hdr: true, max_luminance: 993, max_avg_luminance: 277, min_luminance: 0.001 }) +] +assertHolds( + capabilityInputs.map(function(raw) { + var problem = capabilityShapeProblem(monitor.parseCapabilities(raw)) + return problem ? JSON.stringify(raw) + ': ' + problem : '' + }).filter(Boolean), + 'monitor parses any capabilities output into the panel shape' +) + +// Whatever came back, it must be safe to feed straight into the SDR range: a +// non-HDR reply carries no luminances at all and is the common case. +assertHolds( + capabilityInputs.filter(function(raw) { + var range = monitor.sdrLuminanceRange(monitor.parseCapabilities(raw).maxAvgLuminance) + return range.maximum <= range.minimum + }).map(function(raw) { return JSON.stringify(raw) }), + 'monitor derives a usable SDR range from any parsed capabilities' +) + +// HDR must be enabled only on an explicit true. A truthy-but-not-true value +// (the string "true" from a shell, a 1) would otherwise switch the compositor +// into HDR on a display that never claimed it. +assertHolds( + ['true', 1, 'yes', {}, [], 'TRUE', 'false'].filter(function(truthy) { + return monitor.parseCapabilities(JSON.stringify({ name: 'DP-1', hdr: truthy })).hdr !== false + }).map(function(v) { return JSON.stringify(v) }), + 'monitor refuses HDR for any non-boolean hdr value' +) +assertEqual(monitor.parseCapabilities(JSON.stringify({ hdr: true })).hdr, true, 'monitor accepts an explicit HDR claim') + +// min_luminance is a fraction of a nit on real panels; rounding it away would +// lose the whole value. +assertEqual( + monitor.parseCapabilities(JSON.stringify({ min_luminance: 0.0005 })).minLuminance, + 0.0005, + 'monitor keeps a sub-nit minimum luminance' +) + +// The real command's output must be parseable by the panel. This is the +// contract between bin/omarchy-hyprland-monitor-capabilities and Model.js, and +// nothing else checks that the two still agree. +var live = process.env.OMARCHY_TEST_CAPABILITIES_JSON || '' +assertEqual( + capabilityShapeProblem(monitor.parseCapabilities(live)), + '', + 'monitor parses what omarchy-hyprland-monitor-capabilities actually prints' +) +assertEqual( + monitor.parseCapabilities(live).name, + JSON.parse(live).name, + 'monitor keeps the display name the capabilities command reported' +) + +// ---- Scale helpers reached with an unusable mode ---- + +var presets = ['1', '1.25', '1.6', '2', '3', '4'] + +// availableScales must only ever return presets it was given, never invent or +// duplicate one, and never return nothing. +var realModes = [[1280, 800], [1280, 804], [5968, 3230], [6016, 3384], [3840, 2160], [2256, 1504], [2560, 1440]] +assertHolds( + realModes.filter(function(mode) { + var offered = monitor.availableScales(presets, mode[0], mode[1]) + return offered.length === 0 + || !offered.every(function(s) { return presets.indexOf(s) >= 0 }) + || new Set(offered).size !== offered.length + }).map(function(mode) { return mode.join('x') }), + 'monitor offers a non-empty subset of the presets for every real mode' +) + +// Every offered preset must be selectable: the panel highlights the current +// scale by looking it up again, so a button that can never match is dead. +var unhighlightable = [] +realModes.forEach(function(mode) { + monitor.availableScales(presets, mode[0], mode[1]).forEach(function(s) { + var effective = monitor.cleanScale(s, mode[0], mode[1]) + var offered = monitor.availableScales(presets, mode[0], mode[1]) + if (monitor.matchingScaleIndex(offered, Number(effective), mode[0], mode[1]) < 0) { + unhighlightable.push(s + ' @ ' + mode.join('x') + ' (effective ' + effective + ')') + } + }) +}) +assertHolds(unhighlightable, 'monitor can highlight every scale it offers') + +// --------------------------------------------------------------------------- +// Regressions for defects confirmed against this Model.js. Kept last so a +// still-unfixed defect does not mask the coverage above. +// --------------------------------------------------------------------------- + +// Percent -> luminance -> percent must be stable across the whole slider for +// every plausible ceiling: Panel.qml stores the luminance the slider produced +// and reads it straight back as a percentage, so any drift makes the brightness +// knob jump a notch on its own after the user lets go. +var roundTripViolations = [] +luminanceCeilings.forEach(function(ceiling) { + for (var p = 0; p <= 100; p++) { + var nits = monitor.sdrPercentToLuminance(p, ceiling) + var back = monitor.sdrLuminanceToPercent(nits, ceiling) + if (back !== p) roundTripViolations.push(p + '% @ ' + ceiling + ' -> ' + nits + ' nits -> ' + back + '%') + } +}) +assertHolds(roundTripViolations, 'monitor round-trips every percentage through SDR luminance') + +// Panel.qml feeds display.width/height straight from parsed JSON, so a display +// whose mode has not been reported yet arrives as undefined or as a string. +// That must fall through to the full preset list the way width 0 already does; +// collapsing to a single button leaves the user unable to change scale at all. +assertHolds( + [[undefined, undefined], ['a', 'b'], [NaN, NaN], [null, undefined], ['', ''], [0, 0], [-1, -1]].filter(function(mode) { + return JSON.stringify(monitor.availableScales(presets, mode[0], mode[1])) !== JSON.stringify(presets) + }).map(function(mode) { + return JSON.stringify(mode) + ' -> ' + JSON.stringify(monitor.availableScales(presets, mode[0], mode[1])) + }), + 'monitor keeps every scale preset when the mode is unusable' +) + +// cleanScale snaps a requested scale to one the mode can actually render, so +// its own output must already be snapped -- otherwise re-saving a display +// nobody touched changes its scale. +// +// Scoped to the presets the panel actually offers. cleanScale reports through +// normalizeScale, which rounds to two decimals, so an arbitrary scale whose +// clean value needs three (1920x1080 at 1.7 cleans to 1.875, reported as 1.88) +// does not survive a second pass. That rounding is pre-existing and is what +// matchingScaleIndex compares against, so it is left alone; the panel only ever +// feeds cleanScale these presets, and every one of them is a fixed point. +var unsettled = [] +realModes.forEach(function(mode) { + presets.forEach(function(preset) { + var once = monitor.cleanScale(preset, mode[0], mode[1]) + var twice = monitor.cleanScale(once, mode[0], mode[1]) + if (once !== twice) unsettled.push(mode.join('x') + ' ' + preset + ': ' + once + ' -> ' + twice) + }) +}) +assertHolds(unsettled, 'monitor settles every offered preset after one pass') JS diff --git a/test/shell.d/monitor-tidy-test.sh b/test/shell.d/monitor-tidy-test.sh new file mode 100755 index 000000000000..9278f4778a5a --- /dev/null +++ b/test/shell.d/monitor-tidy-test.sh @@ -0,0 +1,766 @@ +#!/bin/bash + +# Covers omarchy-hyprland-monitor-tidy, which re-packs displays after a scale or +# rotation change resizes one of them. Layouts are described through +# OMARCHY_MONITOR_JSON so none of this needs a compositor. + +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +require_command python3 +require_command jq + +TIDY="$ROOT/bin/omarchy-hyprland-monitor-tidy" + +assert_equal() { + local actual="$1" expected="$2" description="$3" + + if [[ $actual == "$expected" ]]; then + pass "$description" + else + fail "$description" "expected: $expected +actual: $actual" + fi +} + +tidy() { + OMARCHY_MONITOR_JSON="$1" "$TIDY" "${@:2}" 2>&1 || true +} + +tidy_status() { + OMARCHY_MONITOR_JSON="$1" "$TIDY" "${@:2}" >/dev/null 2>&1 && echo 0 || echo $? +} + +# Two 4K displays at scale 1.6 are 2400x1350 each, so one at 0 and one at 2400 +# sit exactly edge to edge. +ALIGNED='[ + {"name":"DP-1","x":0,"y":0,"width":3840,"height":2160,"scale":1.6,"transform":0}, + {"name":"DP-2","x":2400,"y":0,"width":3840,"height":2160,"scale":1.6,"transform":0} +]' + +assert_equal "$(tidy_status "$ALIGNED" check)" "0" "tidy accepts a layout that already sits edge to edge" +assert_equal "$(tidy "$ALIGNED" check)" "No displays overlap." "tidy says so when nothing overlaps" + +# The reported case: the same displays at scale 1.25 are 3072 wide, so the one +# pinned at 2400 is overrun by 672. +OVERLAPPING='[ + {"name":"DP-1","x":0,"y":0,"width":3840,"height":2160,"scale":1.25,"transform":0}, + {"name":"DP-2","x":2400,"y":0,"width":3840,"height":2160,"scale":1.25,"transform":0} +]' + +assert_equal "$(tidy_status "$OVERLAPPING" check)" "1" "tidy reports an overlapping layout" +assert_equal \ + "$(tidy "$OVERLAPPING" check | tail -1)" \ + " DP-1 and DP-2 overlap by 672x1728 logical pixels" \ + "tidy measures the overlap" +assert_equal \ + "$(tidy "$OVERLAPPING" --dry-run | tail -1)" \ + " DP-2: x 2400 -> 3072" \ + "tidy moves the second display clear of the first" + +# hyprctl reports the mode rather than the rotated result, so a quarter turn has +# to swap the axes before any of this arithmetic works. Rotated, DP-2 is 1350 +# wide rather than 2400. Sitting at 3000 it clears DP-1 entirely, so there is +# nothing to fix -- a gap is not an error, and moving a display nobody asked to +# move is how a deliberate layout gets destroyed. +ROTATED_CLEAR='[ + {"name":"DP-1","x":0,"y":0,"width":3840,"height":2160,"scale":1.6,"transform":0}, + {"name":"DP-2","x":3000,"y":0,"width":3840,"height":2160,"scale":1.6,"transform":1} +]' +assert_equal "$(tidy_status "$ROTATED_CLEAR" check)" "0" "tidy leaves a gap after a rotation alone" + +# Unrotated, the same display would be 2400 wide and would overrun DP-1 -- which +# is what proves the axis swap is being applied rather than the raw mode. +ROTATED_COLLIDING='[ + {"name":"DP-1","x":0,"y":0,"width":3840,"height":2160,"scale":1.6,"transform":0}, + {"name":"DP-2","x":1800,"y":0,"width":3840,"height":2160,"scale":1.6,"transform":1} +]' +assert_equal \ + "$(tidy "$ROTATED_COLLIDING" --dry-run | tail -1)" \ + " DP-2: x 1800 -> 2400" \ + "tidy accounts for a quarter turn swapping the axes" + +# Stacked displays must stay stacked; packing them along x would silently +# rearrange the desktop. +STACKED='[ + {"name":"DP-1","x":0,"y":0,"width":3840,"height":2160,"scale":1.6,"transform":0}, + {"name":"DP-2","x":0,"y":2000,"width":3840,"height":2160,"scale":1.6,"transform":0} +]' + +assert_equal "$(tidy_status "$STACKED" check)" "0" "tidy leaves a spaced-out stack alone" + +# Overlapping vertically, though, must be resolved along the vertical axis +# rather than shoved sideways. +STACKED_OVERLAP='[ + {"name":"DP-1","x":0,"y":0,"width":3840,"height":2160,"scale":1.6,"transform":0}, + {"name":"DP-2","x":0,"y":900,"width":3840,"height":2160,"scale":1.6,"transform":0} +]' +assert_equal \ + "$(tidy "$STACKED_OVERLAP" --dry-run | tail -1)" \ + " DP-2: y 900 -> 1350" \ + "tidy resolves a stacked overlap along the axis it was already on" + +# The anchor never moves, so tidying does not drag the whole desktop. +OFFSET='[ + {"name":"DP-1","x":500,"y":300,"width":3840,"height":2160,"scale":1.6,"transform":0}, + {"name":"DP-2","x":1000,"y":300,"width":3840,"height":2160,"scale":1.6,"transform":0} +]' + +assert_equal \ + "$(tidy "$OFFSET" --dry-run | tail -1)" \ + " DP-2: x 1000 -> 2900" \ + "tidy leaves the first display where it is" + +# A single display cannot overlap anything, and a disabled one is not part of +# the layout. +SINGLE='[{"name":"DP-1","x":0,"y":0,"width":3840,"height":2160,"scale":1.6,"transform":0}]' +assert_equal "$(tidy_status "$SINGLE" check)" "0" "tidy accepts a single display" + +DISABLED='[ + {"name":"DP-1","x":0,"y":0,"width":3840,"height":2160,"scale":1.25,"transform":0}, + {"name":"DP-2","x":2400,"y":0,"width":3840,"height":2160,"scale":1.25,"transform":0,"disabled":true} +]' +assert_equal "$(tidy_status "$DISABLED" check)" "0" "tidy ignores a disabled display" + +# --intended positions displays for the layout a change is about to produce, +# rather than the current one. Callers use it to move neighbours clear *before* +# growing a display, because Hyprland notifies the instant two displays overlap +# and that warning stays on screen after the layout is valid again. +CURRENT_16='[ + {"name":"DP-1","x":0,"y":0,"width":3840,"height":2160,"scale":1.6,"transform":0}, + {"name":"DP-2","x":2400,"y":0,"width":3840,"height":2160,"scale":1.6,"transform":0} +]' +INTENDED_125='[ + {"name":"DP-1","x":0,"y":0,"width":3840,"height":2160,"scale":1.25,"transform":0}, + {"name":"DP-2","x":2400,"y":0,"width":3840,"height":2160,"scale":1.25,"transform":0} +]' + +# The current layout is fine, so without --intended there is nothing to do. +assert_equal "$(tidy_status "$CURRENT_16" check)" "0" "tidy sees nothing wrong with the layout before the change" + +# Asked about the layout the change will produce, it moves the neighbour clear. +assert_equal \ + "$(OMARCHY_MONITOR_JSON="$CURRENT_16" "$TIDY" --intended "$INTENDED_125" --dry-run 2>&1 | tail -1)" \ + " DP-2: x 2400 -> 3072" \ + "tidy plans for the layout a pending change will produce" + +# A mirrored display repeats another one and shares its position. Counting it as +# its own area reads as a total overlap, and tidying then moves the display +# being mirrored out from under it, breaking the mirror on the next scale +# change -- mirroring is a first-class Omarchy feature (projectors, clamshell). +MIRRORED='[ + {"name":"eDP-1","x":0,"y":0,"width":1920,"height":1080,"scale":1,"transform":0,"mirrorOf":"none"}, + {"name":"HDMI-A-1","x":0,"y":0,"width":1920,"height":1080,"scale":1,"transform":0,"mirrorOf":"eDP-1"} +]' +assert_equal "$(tidy_status "$MIRRORED" check)" "0" "tidy leaves a mirrored pair alone" + +# Three displays in a row pack cumulatively, each against the one before it. +TRIPLE='[ + {"name":"DP-1","x":0,"y":0,"width":3840,"height":2160,"scale":1.25,"transform":0}, + {"name":"DP-2","x":2400,"y":0,"width":3840,"height":2160,"scale":1.25,"transform":0}, + {"name":"DP-3","x":4800,"y":0,"width":3840,"height":2160,"scale":1.25,"transform":0} +]' +assert_equal \ + "$(tidy "$TRIPLE" --dry-run | grep -- '->' | sort | tr -s ' \n' ' ')" \ + " DP-2: x 2400 -> 3072 DP-3: x 4800 -> 6144 " \ + "tidy packs three displays cumulatively" + +# An L-shaped layout is valid: nothing overlaps, the second row simply sits +# below. Displays only pack against ones they stand beside, so a second row is +# not flattened into the first. +LSHAPE='[ + {"name":"DP-1","x":0,"y":0,"width":3840,"height":2160,"scale":1.6,"transform":0}, + {"name":"DP-2","x":2400,"y":0,"width":3840,"height":2160,"scale":1.6,"transform":0}, + {"name":"DP-3","x":0,"y":1350,"width":3840,"height":2160,"scale":1.6,"transform":0} +]' +assert_equal "$(tidy_status "$LSHAPE" check)" "0" "tidy leaves a valid L-shaped layout alone" + +# A tall display beside two stacked ones shares the cross axis with both rows. +# Grouping displays transitively on that basis dragged the lower row sideways, +# even though nothing overlapped. Only collisions may move a display. +SPANNING='[ + {"name":"A","x":0,"y":0,"width":1920,"height":1080,"scale":1,"transform":0}, + {"name":"C","x":0,"y":1080,"width":1920,"height":1080,"scale":1,"transform":0}, + {"name":"D","x":1920,"y":0,"width":1920,"height":2160,"scale":1,"transform":0} +]' +assert_equal "$(tidy_status "$SPANNING" check)" "0" "tidy leaves a row beside a full-height display alone" + +# A display sitting entirely inside another still has to be moved clear. +CONTAINED='[ + {"name":"BIG","x":0,"y":0,"width":3840,"height":2160,"scale":1,"transform":0}, + {"name":"SMALL","x":500,"y":500,"width":800,"height":600,"scale":1,"transform":0} +]' +assert_equal "$(tidy_status "$CONTAINED" check)" "1" "tidy reports a display contained inside another" + +# Tidying must settle in one pass: whatever it proposes has to leave a layout it +# then considers finished, or the callers would fight it on every change. +assert_idempotent() { + local description="$1" layout="$2" + local settled + settled=$(OMARCHY_MONITOR_JSON="$layout" python3 -c ' +import json, os, subprocess, sys +monitors = json.loads(os.environ["OMARCHY_MONITOR_JSON"]) +result = subprocess.run([sys.argv[1], "--dry-run"], capture_output=True, text=True, + env=dict(os.environ)) +for line in result.stdout.splitlines(): + if "->" not in line: + continue + name = line.split(":")[0].strip() + axis = line.split(":")[1].strip().split()[0] + for monitor in monitors: + if monitor["name"] == name: + monitor[axis] = float(line.split("->")[1]) +print(json.dumps(monitors)) +' "$TIDY") + + assert_equal "$(tidy_status "$settled" check)" "0" "$description" +} + +assert_idempotent "tidy settles a contained display in one pass" "$CONTAINED" +assert_idempotent "tidy settles three overlapping displays in one pass" '[ + {"name":"A","x":0,"y":0,"width":1920,"height":1080,"scale":1,"transform":0}, + {"name":"B","x":1000,"y":0,"width":1920,"height":1080,"scale":1,"transform":0}, + {"name":"C","x":2000,"y":0,"width":1920,"height":1080,"scale":1,"transform":0} +]' +assert_idempotent "tidy settles a stacked overlap in one pass" "$STACKED_OVERLAP" + +# -------------------------------------------------------------------------- +# Command line surface +# -------------------------------------------------------------------------- + +# The usage text is the only documentation a user gets, so --help has to reach +# stdout and succeed -- a help screen on stderr behind a non-zero exit is what +# breaks `omarchy hyprland monitor tidy --help | less`. +for flag in -h --help; do + help_out=$(OMARCHY_MONITOR_JSON='[]' "$TIDY" "$flag" 2>/dev/null) && help_status=0 || help_status=$? + assert_equal "$help_status" "0" "tidy exits 0 for $flag" + case $help_out in + *"Usage:"*check*apply*) pass "tidy describes both actions in $flag" ;; + *) fail "tidy describes both actions in $flag" "got: $help_out" ;; + esac +done + +# An unrecognised flag must be refused rather than silently ignored; a caller +# that typos --dry-run would otherwise move the user's displays for real. +unknown_out=$(OMARCHY_MONITOR_JSON='[]' "$TIDY" --no-such-flag 2>&1 >/dev/null) || true +assert_equal "$(tidy_status '[]' --no-such-flag)" "1" "tidy rejects an unknown flag" +case $unknown_out in +*"Usage:"*) pass "tidy explains itself on stderr when refusing a flag" ;; +*) fail "tidy explains itself on stderr when refusing a flag" "got: $unknown_out" ;; +esac + +# apply is the default action, so naming it explicitly must not change anything. +assert_equal \ + "$(tidy "$OVERLAPPING" apply --dry-run | tail -1)" \ + "$(tidy "$OVERLAPPING" --dry-run | tail -1)" \ + "tidy treats apply as the default action" + +# No displays at all is what a headless or still-starting session reports. +# Falling over there would break the scale and rotation commands that call this +# unconditionally. +assert_equal "$(tidy_status '[]' check)" "0" "tidy accepts an empty monitor listing" +assert_equal "$(tidy_status '[]' --dry-run)" "0" "tidy has nothing to do with no displays" + +# -------------------------------------------------------------------------- +# Layout arithmetic +# -------------------------------------------------------------------------- + +# hyprctl reports the unrotated mode, so every odd transform -- the quarter +# turns, including the flipped ones (4-7) -- has to swap width and height. +# Getting only transform 1 right is the easy half-fix. +for transform in 0 1 2 3 4 5 6 7; do + ROTATION_CASE="[ + {\"name\":\"A\",\"x\":0,\"y\":0,\"width\":1920,\"height\":1080,\"scale\":1,\"transform\":$transform}, + {\"name\":\"B\",\"x\":1000,\"y\":0,\"width\":1920,\"height\":1080,\"scale\":1,\"transform\":0} + ]" + if ((transform % 2)); then + expected=" B: x 1000 -> 1080" + else + expected=" B: x 1000 -> 1920" + fi + assert_equal "$(tidy "$ROTATION_CASE" --dry-run | tail -1)" "$expected" \ + "tidy swaps the axes for transform $transform only when it is a quarter turn" +done + +# hyprctl omits scale on some paths and can report 0 while a display is coming +# up. Either has to read as 1x rather than dividing by zero or by nothing. +NO_SCALE='[ + {"name":"A","x":0,"y":0,"width":1920,"height":1080,"transform":0}, + {"name":"B","x":1000,"y":0,"width":1920,"height":1080,"transform":0} +]' +assert_equal "$(tidy "$NO_SCALE" --dry-run | tail -1)" " B: x 1000 -> 1920" \ + "tidy treats a missing scale as 1x" + +ZERO_SCALE='[ + {"name":"A","x":0,"y":0,"width":1920,"height":1080,"scale":0,"transform":0}, + {"name":"B","x":1000,"y":0,"width":1920,"height":1080,"scale":0,"transform":0} +]' +assert_equal "$(tidy "$ZERO_SCALE" --dry-run | tail -1)" " B: x 1000 -> 1920" \ + "tidy survives a scale of 0" + +# 3840 / 1.5 is exactly 2560, so a fractional scale must divide the mode rather +# than being rounded to an integer first. +SCALED_15='[ + {"name":"A","x":0,"y":0,"width":3840,"height":2160,"scale":1.5,"transform":0}, + {"name":"B","x":1000,"y":0,"width":3840,"height":2160,"scale":1.5,"transform":0} +]' +assert_equal "$(tidy "$SCALED_15" --dry-run | tail -1)" " B: x 1000 -> 2560" \ + "tidy divides the mode by a fractional scale" + +# Hyprland's coordinate space is signed: a display placed left of or above the +# primary has negative coordinates, and arithmetic that assumes non-negative +# positions parks it in the wrong place. +NEGATIVE='[ + {"name":"A","x":-1920,"y":-1080,"width":1920,"height":1080,"scale":1,"transform":0}, + {"name":"B","x":-1000,"y":-1080,"width":1920,"height":1080,"scale":1,"transform":0} +]' +assert_equal "$(tidy "$NEGATIVE" --dry-run | tail -1)" " B: x -1000 -> 0" \ + "tidy handles displays at negative coordinates" + +# -------------------------------------------------------------------------- +# Overlap detection +# -------------------------------------------------------------------------- + +# Sharing an edge is the goal state, not a collision. Treating >= as an overlap +# would make every tidied layout report as broken forever after. +CORNER_TOUCH='[ + {"name":"A","x":0,"y":0,"width":1920,"height":1080,"scale":1,"transform":0}, + {"name":"B","x":1920,"y":1080,"width":1920,"height":1080,"scale":1,"transform":0} +]' +assert_equal "$(tidy_status "$CORNER_TOUCH" check)" "0" "tidy does not call a shared corner an overlap" + +# The reported size must be the real intersection on both axes, not the offset +# on one of them; a diagonal overlap is where those two differ. +DIAGONAL='[ + {"name":"A","x":0,"y":0,"width":1920,"height":1080,"scale":1,"transform":0}, + {"name":"B","x":1720,"y":1000,"width":1920,"height":1080,"scale":1,"transform":0} +]' +assert_equal "$(tidy "$DIAGONAL" check | tail -1)" \ + " A and B overlap by 200x80 logical pixels" \ + "tidy measures a diagonal overlap on both axes" + +# One display fully inside another intersects by the whole of the smaller one. +assert_equal "$(tidy "$CONTAINED" check | tail -1)" \ + " BIG and SMALL overlap by 800x600 logical pixels" \ + "tidy measures a containment as the whole inner display" + +# Every colliding pair has to be listed, not just the first: a user fixing them +# by hand needs the full picture, and three displays in a heap is three pairs. +PILE='[ + {"name":"A","x":0,"y":0,"width":1920,"height":1080,"scale":1,"transform":0}, + {"name":"B","x":100,"y":0,"width":1920,"height":1080,"scale":1,"transform":0}, + {"name":"C","x":200,"y":0,"width":1920,"height":1080,"scale":1,"transform":0} +]' +assert_equal "$(tidy "$PILE" check | grep -c 'overlap by')" "3" \ + "tidy reports every overlapping pair" + +# -------------------------------------------------------------------------- +# Run grouping: only displays that actually collide may move +# -------------------------------------------------------------------------- + +# Two independent rows. The bottom row overlaps; the top row is already right. +# Grouping displays by anything looser than a real collision drags the innocent +# row along with the fix. +TWO_ROWS='[ + {"name":"TL","x":0,"y":0,"width":1920,"height":1080,"scale":1,"transform":0}, + {"name":"TR","x":1920,"y":0,"width":1920,"height":1080,"scale":1,"transform":0}, + {"name":"BL","x":0,"y":1080,"width":1920,"height":1080,"scale":1,"transform":0}, + {"name":"BR","x":1000,"y":1080,"width":1920,"height":1080,"scale":1,"transform":0} +]' +assert_equal "$(tidy "$TWO_ROWS" --dry-run | grep -c '\->')" "1" \ + "tidy moves only the display that collides, not the whole row" +assert_equal "$(tidy "$TWO_ROWS" --dry-run | tail -1)" " BR: x 1000 -> 1920" \ + "tidy fixes the colliding row in place" + +# A deliberately distant display is a spaced layout, not a gap to close. +DISTANT='[ + {"name":"A","x":0,"y":0,"width":1920,"height":1080,"scale":1,"transform":0}, + {"name":"B","x":1000,"y":0,"width":1920,"height":1080,"scale":1,"transform":0}, + {"name":"FAR","x":9000,"y":0,"width":1920,"height":1080,"scale":1,"transform":0} +]' +assert_equal "$(tidy "$DISTANT" --dry-run | grep -c '\->')" "1" \ + "tidy does not drag a distant display in to close a gap" + +# -------------------------------------------------------------------------- +# Mirrored and disabled displays +# -------------------------------------------------------------------------- + +# hyprctl reports mirrorOf as the string "none", but a null slips through some +# paths; both mean the same thing and neither may read as "mirrors a display +# called none". +MIRROR_NULL='[ + {"name":"A","x":0,"y":0,"width":1920,"height":1080,"scale":1,"transform":0,"mirrorOf":null}, + {"name":"M","x":0,"y":0,"width":1920,"height":1080,"scale":1,"transform":0,"mirrorOf":"A"} +]' +assert_equal "$(tidy_status "$MIRROR_NULL" check)" "0" "tidy reads a null mirrorOf as not mirroring" + +# A mirror shares its source's position by definition. It must never be given a +# move of its own, even while the rest of the layout is being repacked. +MIRROR_PLUS_OVERLAP='[ + {"name":"A","x":0,"y":0,"width":1920,"height":1080,"scale":1,"transform":0,"mirrorOf":"none"}, + {"name":"M","x":0,"y":0,"width":1920,"height":1080,"scale":1,"transform":0,"mirrorOf":"A"}, + {"name":"B","x":1000,"y":0,"width":1920,"height":1080,"scale":1,"transform":0,"mirrorOf":"none"} +]' +assert_equal "$(tidy "$MIRROR_PLUS_OVERLAP" --dry-run | grep -c '\->')" "1" \ + "tidy never plans a move for a mirrored display" +assert_equal "$(tidy "$MIRROR_PLUS_OVERLAP" --dry-run | tail -1)" " B: x 1000 -> 1920" \ + "tidy repacks around a mirrored pair without disturbing it" + +# A disabled display keeps its stale coordinates in hyprctl's listing. Counting +# them invents collisions and moves live displays to dodge a dark panel. +DISABLED_IN_THE_WAY='[ + {"name":"A","x":0,"y":0,"width":1920,"height":1080,"scale":1,"transform":0}, + {"name":"OFF","x":100,"y":0,"width":1920,"height":1080,"scale":1,"transform":0,"disabled":true}, + {"name":"B","x":1000,"y":0,"width":1920,"height":1080,"scale":1,"transform":0} +]' +assert_equal "$(tidy "$DISABLED_IN_THE_WAY" --dry-run | grep -c '\->')" "1" \ + "tidy plans no move for a disabled display" +assert_equal "$(tidy "$DISABLED_IN_THE_WAY" --dry-run | tail -1)" " B: x 1000 -> 1920" \ + "tidy ignores a disabled display sitting between two live ones" + +# Everything but one display mirrored or off is a clamshell/projector session: +# one effective area, so nothing can collide. +ONLY_ONE_EFFECTIVE='[ + {"name":"eDP-1","x":0,"y":0,"width":1920,"height":1080,"scale":1,"transform":0,"disabled":true}, + {"name":"HDMI-A-1","x":0,"y":0,"width":1920,"height":1080,"scale":1,"transform":0,"mirrorOf":"none"}, + {"name":"HDMI-A-2","x":0,"y":0,"width":1920,"height":1080,"scale":1,"transform":0,"mirrorOf":"HDMI-A-1"} +]' +assert_equal "$(tidy_status "$ONLY_ONE_EFFECTIVE" check)" "0" \ + "tidy accepts a clamshell layout with one effective display" + +# -------------------------------------------------------------------------- +# --intended planning +# -------------------------------------------------------------------------- + +# Both spellings of the flag have to mean the same thing; scaling and rotation +# call it one way and a user may well type the other. +assert_equal \ + "$(OMARCHY_MONITOR_JSON="$CURRENT_16" "$TIDY" --intended="$INTENDED_125" --dry-run 2>&1 | tail -1)" \ + "$(OMARCHY_MONITOR_JSON="$CURRENT_16" "$TIDY" --intended "$INTENDED_125" --dry-run 2>&1 | tail -1)" \ + "tidy accepts --intended=VALUE and --intended VALUE alike" + +# --intended replaces the current layout outright. If the current one still had +# a say, a caller shrinking a display would be told to fix an overlap that is +# about to disappear on its own. +assert_equal \ + "$(OMARCHY_MONITOR_JSON="$OVERLAPPING" "$TIDY" --intended "$ALIGNED" --dry-run 2>&1)" \ + "" \ + "tidy plans nothing when the pending change resolves the current overlap" +assert_equal \ + "$(OMARCHY_MONITOR_JSON="$OVERLAPPING" "$TIDY" check --intended "$ALIGNED" 2>&1)" \ + "No displays overlap." \ + "tidy checks the intended layout rather than the current one" + +# check and --intended compose, so a caller can ask "will this change break the +# layout?" without applying anything. +assert_equal \ + "$(OMARCHY_MONITOR_JSON="$ALIGNED" "$TIDY" check --intended "$OVERLAPPING" >/dev/null 2>&1 && echo 0 || echo 1)" \ + "1" \ + "tidy reports a pending change that would overlap" + +# An explicitly empty --intended= carries no layout, so the current one is all +# there is to work from; dropping to no displays at all would silently skip the +# tidy a caller asked for. +assert_equal \ + "$(OMARCHY_MONITOR_JSON="$OVERLAPPING" "$TIDY" --intended= --dry-run 2>&1 | tail -1)" \ + " DP-2: x 2400 -> 3072" \ + "tidy falls back to the current layout for an empty --intended=" + +# -------------------------------------------------------------------------- +# Properties over generated layouts +# -------------------------------------------------------------------------- + +# An exact tiling of a rectangle has no gap and no overlap anywhere, so there is +# nothing for tidy to do -- whatever shape it happens to be. Grouping displays +# transitively (a tall display "connecting" two stacked neighbours) used to +# flatten such layouts into a row and tear a real hole in the desktop. +tilings_disturbed=$(python3 - "$TIDY" <<'PY' +import json, os, random, subprocess, sys + +tidy = sys.argv[1] + + +def carve(rect, depth, out): + x, y, w, h = rect + if depth == 0 or random.random() < 0.3 or (w < 2 and h < 2): + out.append(rect) + return + if w >= 2 and (h < 2 or random.random() < 0.5): + cut = random.randint(1, w - 1) + carve((x, y, cut, h), depth - 1, out) + carve((x + cut, y, w - cut, h), depth - 1, out) + else: + cut = random.randint(1, h - 1) + carve((x, y, w, cut), depth - 1, out) + carve((x, y + cut, w, h - cut), depth - 1, out) + + +disturbed = 0 +for seed in range(120): + random.seed(seed) + cells = [] + carve((0, 0, 8, 8), 3, cells) + if len(cells) < 2: + continue + layout = [ + {"name": "M%d" % i, "x": x * 240, "y": y * 240, + "width": w * 240, "height": h * 240, "scale": 1, "transform": 0} + for i, (x, y, w, h) in enumerate(cells) + ] + env = dict(os.environ, OMARCHY_MONITOR_JSON=json.dumps(layout)) + result = subprocess.run([tidy, "--dry-run"], capture_output=True, text=True, env=env) + if "->" in result.stdout: + disturbed += 1 + if disturbed == 1: + print(json.dumps(layout), result.stdout, file=sys.stderr) +print(disturbed) +PY +) +assert_equal "$tilings_disturbed" "0" "tidy never disturbs an exact tiling of the desktop" + +# Whatever tidy proposes has to leave a layout with no overlaps in it -- judged +# independently here rather than by asking tidy again, so a shared blind spot in +# the overlap test cannot make both passes agree on a broken result. A second +# pass proposing further moves is the visible symptom: the display jumps, the +# success message prints, and Hyprland still says the layout is wrong. +unsettled=$(python3 - "$TIDY" <<'PY' +import json, os, random, subprocess, sys + +tidy = sys.argv[1] +MODES = [(1920, 1080), (2560, 1440), (3840, 2160), (1280, 1024), (3440, 1440)] +SCALES = [1, 1.25, 1.5, 1.6, 2, 2.5] + + +def run(layout, *args): + env = dict(os.environ, OMARCHY_MONITOR_JSON=json.dumps(layout)) + return subprocess.run([tidy, *args], capture_output=True, text=True, env=env) + + +def moves(stdout): + found = {} + for line in stdout.splitlines(): + if "->" not in line: + continue + name, rest = line.split(":", 1) + axis = rest.strip().split()[0] + found.setdefault(name.strip(), {})[axis] = float(line.split("->")[1]) + return found + + +def rects(layout): + out = [] + for monitor in layout: + scale = float(monitor.get("scale") or 1) or 1 + w = monitor["width"] / scale + h = monitor["height"] / scale + if monitor["transform"] % 2: + w, h = h, w + out.append((monitor["name"], monitor["x"], monitor["y"], w, h)) + return out + + +def collisions(layout): + boxes = rects(layout) + hits = [] + for i in range(len(boxes)): + for j in range(i + 1, len(boxes)): + _, ax, ay, aw, ah = boxes[i] + _, bx, by, bw, bh = boxes[j] + if min(ax + aw, bx + bw) - max(ax, bx) > 0.5 and \ + min(ay + ah, by + bh) - max(ay, by) > 0.5: + hits.append((boxes[i][0], boxes[j][0])) + return hits + + +broken = 0 +for seed in range(150): + random.seed(seed + 5000) + layout = [ + {"name": "M%d" % i, + "x": random.randrange(-2000, 4000, 80), + "y": random.randrange(-2000, 3000, 80), + "width": mode[0], "height": mode[1], + "scale": random.choice(SCALES), + "transform": random.randrange(0, 8)} + for i, mode in enumerate(random.choice(MODES) for _ in range(random.randint(2, 5))) + ] + planned = moves(run(layout, "--dry-run").stdout) + settled = [dict(m) for m in layout] + for monitor in settled: + for axis, value in planned.get(monitor["name"], {}).items(): + monitor[axis] = value + second = run(settled, "check") + if collisions(settled) or second.returncode != 0: + broken += 1 + if broken == 1: + print(json.dumps(layout), collisions(settled), second.stdout, file=sys.stderr) +print(broken) +PY +) +assert_equal "$unsettled" "0" "tidy leaves no overlaps behind and settles in a single pass" + +# -------------------------------------------------------------------------- +# apply, against stand-in hyprctl and monitor-rule commands +# -------------------------------------------------------------------------- + +# apply is the only path that changes anything, so it is worth exercising -- +# but it must never reach the real compositor or the real monitors.lua. Both +# collaborators are invoked by name, so a directory at the front of PATH is +# enough to record the calls instead of making them. +STUB_BIN=$(mktemp -d) +trap 'rm -rf "$STUB_BIN"' EXIT + +cat >"$STUB_BIN/hyprctl" <<'STUB' +#!/bin/bash +printf 'hyprctl %s\n' "$*" >>"$TIDY_CALL_LOG" +STUB +cat >"$STUB_BIN/omarchy-hyprland-monitor-rule" <<'STUB' +#!/bin/bash +printf 'rule %s\n' "$*" >>"$TIDY_CALL_LOG" +STUB +chmod +x "$STUB_BIN/hyprctl" "$STUB_BIN/omarchy-hyprland-monitor-rule" + +apply_calls() { + local layout="$1" + export TIDY_CALL_LOG="$STUB_BIN/log" + : >"$TIDY_CALL_LOG" + OMARCHY_MONITOR_JSON="$layout" PATH="$STUB_BIN:$PATH" "$TIDY" "${@:2}" >/dev/null 2>&1 || true + cat "$TIDY_CALL_LOG" +} + +# A layout that is already right must not be "fixed": every write here is a +# monitors.lua edit and a compositor round trip the user did not ask for. +assert_equal "$(apply_calls "$ALIGNED" apply)" "" "tidy applying a settled layout touches nothing" + +# --dry-run has to be genuinely inert, or the flag callers use to preview a +# change is itself the change. +assert_equal "$(apply_calls "$OVERLAPPING" apply --dry-run)" "" "tidy --dry-run issues no commands" + +# The move has to reach both the compositor (so it takes effect now) and the +# rule file (so it survives a reload). One without the other is a layout that +# silently reverts. +applied=$(apply_calls "$OVERLAPPING" apply) +case $applied in +*'output = "DP-2"'*'position = "3072x0"'*) pass "tidy applies the planned position to the compositor" ;; +*) fail "tidy applies the planned position to the compositor" "got: $applied" ;; +esac +case $applied in +*"rule set DP-2 position=3072x0"*) pass "tidy persists the planned position to the display rule" ;; +*) fail "tidy persists the planned position to the display rule" "got: $applied" ;; +esac +assert_equal "$(printf '%s\n' "$applied" | grep -c '^hyprctl ')" "1" \ + "tidy issues one compositor call per moved display" + +# Packing along one axis must leave the other coordinate exactly where it was; +# writing a whole position means it is easy to reset the untouched axis to 0. +OFFSET_STACK='[ + {"name":"A","x":700,"y":0,"width":1920,"height":1080,"scale":1,"transform":0}, + {"name":"B","x":700,"y":900,"width":1920,"height":1080,"scale":1,"transform":0} +]' +case $(apply_calls "$OFFSET_STACK" apply) in +*"rule set B position=700x1080"*) pass "tidy preserves the cross-axis coordinate when it repacks" ;; +*) fail "tidy preserves the cross-axis coordinate when it repacks" "got: $(apply_calls "$OFFSET_STACK" apply)" ;; +esac + +# apply must be a fixed point: feeding back exactly what it wrote has to leave +# nothing to do. Otherwise the automatic tidy after every scale or rotation +# change fights itself and the display visibly jumps twice. +REAPPLIED='[ + {"name":"DP-1","x":0,"y":0,"width":3840,"height":2160,"scale":1.25,"transform":0}, + {"name":"DP-2","x":3072,"y":0,"width":3840,"height":2160,"scale":1.25,"transform":0} +]' +assert_equal "$(tidy_status "$REAPPLIED" check)" "0" "tidy considers its own applied result finished" +assert_equal "$(apply_calls "$REAPPLIED" apply)" "" "tidy applied a second time changes nothing" + +# --intended's whole purpose is that the displays never overlap even for an +# instant. When a clearance pass shifts a column outward, moving the near +# neighbour first drops it on top of the far one until the next call lands -- +# so the moves have to be ordered outermost first. Replayed against the live +# geometry, because the resize the caller is clearing space for has not +# happened yet. +CLEARANCE_STACK='[ + {"name":"A","x":0,"y":0,"width":1920,"height":1080,"scale":1,"transform":0}, + {"name":"B","x":0,"y":1080,"width":1920,"height":1080,"scale":1,"transform":0}, + {"name":"C","x":0,"y":2160,"width":1920,"height":1080,"scale":1,"transform":0} +]' +CLEARANCE_INTENDED=$(jq -c '[.[] | if .name == "A" then (.width = 1920 | .height = 1920) else . end]' <<<"$CLEARANCE_STACK") + +assert_equal "$(tidy_status "$CLEARANCE_STACK" check)" "0" \ + "the column the clearance pass starts from is already settled" + +CLEARANCE_LOG=$(apply_calls "$CLEARANCE_STACK" apply --intended "$CLEARANCE_INTENDED") +transient=$(python3 - "$CLEARANCE_STACK" "$CLEARANCE_LOG" <<'PY' +import json +import re +import sys + +layout = {m["name"]: dict(m) for m in json.loads(sys.argv[1])} +worst = 0 + +def collide(): + boxes = [(n, m["x"], m["y"], m["width"], m["height"]) for n, m in layout.items()] + for i in range(len(boxes)): + for j in range(i + 1, len(boxes)): + _, ax, ay, aw, ah = boxes[i] + _, bx, by, bw, bh = boxes[j] + h = min(ax + aw, bx + bw) - max(ax, bx) + v = min(ay + ah, by + bh) - max(ay, by) + if h > 0 and v > 0: + yield boxes[i][0], boxes[j][0], h, v + +for line in sys.argv[2].splitlines(): + found = re.search(r'output = "([^"]+)".*position = "(-?\d+)x(-?\d+)"', line) + if not found: + continue + name, x, y = found.group(1), int(found.group(2)), int(found.group(3)) + if name in layout: + layout[name]["x"], layout[name]["y"] = x, y + for _, _, h, v in collide(): + worst = max(worst, min(h, v)) + +print(worst) +PY +) +# The two checks below cover defects that are still live in +# bin/omarchy-hyprland-monitor-tidy. `fail` exits on the first one, which would +# hide the second, so they are collected and reported together -- both are +# useful to see at once while the fixes are being written. +outstanding=() + +record() { + local description="$1" detail="$2" + + if [[ -z $detail ]]; then + pass "$description" + else + outstanding+=("$description") + printf '%s\nnot ok - %s\n' "$detail" "$description" >&2 + fi +} + +if [[ $transient == "0" ]]; then + record "tidy orders a clearance pass so no intermediate state overlaps" "" +else + record "tidy orders a clearance pass so no intermediate state overlaps" \ + "expected no overlap at any point; two displays overlapped by ${transient}px +between compositor calls: +$CLEARANCE_LOG" +fi + +# A flag that takes a value and is given none is a usage error. Spinning +# instead pins a CPU core forever, and callers interpolating an unset variable +# (--intended "$plan") hit it with no way out but SIGKILL. +OMARCHY_MONITOR_JSON='[]' timeout --kill-after=1s 5s "$TIDY" --intended >/dev/null 2>&1 && intended_status=0 || intended_status=$? +if ((intended_status == 124 || intended_status == 137)); then + record "tidy refuses --intended with no value instead of hanging" \ + "expected a usage error; the command had to be killed (exit $intended_status)" +else + record "tidy refuses --intended with no value instead of hanging" "" +fi + +if ((${#outstanding[@]})); then + printf 'not ok - %d known defect(s) in omarchy-hyprland-monitor-tidy remain unfixed\n' \ + "${#outstanding[@]}" >&2 + exit 1 +fi