diff --git a/docs/theming.md b/docs/theming.md index 817a32792860..c81468bce100 100644 --- a/docs/theming.md +++ b/docs/theming.md @@ -14,6 +14,33 @@ Aim for a video between five and seven seconds long that opens on its scene setu A theme installed from a git repo is held to a much shorter list; see [What an installed theme may not ship](#what-an-installed-theme-may-not-ship). +## Background image variants + +A still image can have alternatives in a sibling directory named after the image without its extension: + +```text +backgrounds/ + 01-ink-signature.webp + 01-ink-signature/ + 5120x2160.webp + portrait.png + 02-paper-signature.webp + 02-paper-signature/ + 5120x2160.webp +``` + +The top-level file is both the default image and the design's identity. The existing picker, cycling commands, and current-background symlink continue to refer to that file. Nested alternatives do not add picker entries. Themes therefore work without variant support, using their default images. + +The desktop background plugin considers the default plus JPG, JPEG, PNG, WebP, and BMP files immediately inside its matching directory. It reads actual image dimensions; filenames do not declare dimensions. Choose distinct default basenames within a background directory. GIF and video wallpapers retain their existing behavior and do not participate in variant selection. + +Each output independently chooses the least-cropped aspect ratio, then the smallest sufficient resolution at that aspect ratio, or the largest available if all would require enlargement. Logical window dimensions multiplied by the window's fractional pixel density account for scaling and rotation. Screen changes reevaluate selection without rescanning images. Metadata is cached under `~/.cache/omarchy/background-dimensions` (or nonempty `$XDG_CACHE_HOME`) by path and a hash of the compressed file contents, so unchanged theme copies reuse dimensions. Changed files replace their cache record; records unused for 30 days are pruned. Cache write failures do not prevent variant selection. Selecting a different background or applying a theme refreshes its candidate list; unreadable alternatives are skipped. + +The same convention works for additional user backgrounds. The lock screen and picker previews continue to use the default image. Selecting an alternative file directly displays that file normally unless it also has a matching sibling directory. + +Matching intros still use the top-level image's basename in `intros/`; image variants do not select separate intro videos. Intro playback and its outgoing cover use the shared/default artwork, then the desktop returns to each output's selected still variant. If a variant changes the composition, the handoff can visibly change framing. A change from a still to a video has the same seam the other way round: OWE loads the outgoing still from the default path to fade from it, so an output showing a variant returns to the default artwork for a moment before the video fades in. + +Video wallpapers and intros have no variants. OWE decodes one video for every output, so a video per output would cost a decode for each distinct variant, and choosing one is OWE's to do, not this plugin's. Video files inside a variant directory are ignored, which leaves the convention free to carry them if OWE gains per-output playback. + ## Theme activation flow `omarchy-theme-set ` builds a clean staging directory at diff --git a/manual/39-backgrounds.md b/manual/39-backgrounds.md index b023e108ad7d..7183060dd930 100644 --- a/manual/39-backgrounds.md +++ b/manual/39-backgrounds.md @@ -6,6 +6,8 @@ You can do this most easily by going to _Install > Style > Background_ in the Om Backgrounds can be videos as well as stills. Drop an `mp4`, `m4v`, `mov`, `webm`, `mkv`, or `avi` file in the same folder and it appears alongside the images. Videos are played by the OWE wallpaper engine. It decodes the video once for all monitors and plays its sound through the default audio output, and it stops playback whenever nothing can see it. A video wallpaper still costs far more power than a still one. +A still background can have alternatives for different monitor shapes and resolutions. Keep the default image in the background folder (for example, `design.webp`) and put alternatives directly in a sibling folder named without the extension (`design/`). Only the default appears in the picker; each monitor automatically chooses its best-fitting image. The lock screen continues to use the default. See [Background sizes](43-making-your-own-theme.md#background-sizes) for an example and supported formats. + Themes can include a short intro for a still background. For `backgrounds/road.webp`, the matching video lives at `backgrounds/intros/road.mp4`. It plays automatically at boot, when switching to a theme with that background selected, and when choosing that background, then returns to the still. Intro videos stay out of the background picker and never loop. Turning off _Appearance > Animations_ also turns off background intros. Omarchy does this by default in a virtual machine. The `omarchy theme bg intro toggle` command can toggle intros separately. Refreshing a theme does not play an intro. diff --git a/manual/43-making-your-own-theme.md b/manual/43-making-your-own-theme.md index 975be8f743ce..952ea37d6b81 100644 --- a/manual/43-making-your-own-theme.md +++ b/manual/43-making-your-own-theme.md @@ -16,6 +16,24 @@ Everything else still works exactly as the theme author wrote it — `btop.theme Omarchy tells the two apart by whether the theme has its own git repo inside it, which is what `omarchy theme install` leaves behind when it clones. So a theme you wrote stays yours, and one you pulled off the internet stays colours. +### Background sizes + +You can provide different sizes or compositions of a background for ordinary, ultrawide, and portrait screens. Keep one default image directly in `backgrounds/`, then put alternatives in a directory with the same name without the file extension: + +```text +backgrounds/ + 01-landscape.webp + 01-landscape/ + ultrawide.webp + portrait.png +``` + +Only the default appears in the background picker. Omarchy automatically chooses the image that best fits each monitor's shape and resolution. Alternative filenames are up to you: Omarchy reads the dimensions from the files. JPG, JPEG, PNG, WebP, and BMP alternatives are supported; put them directly inside the matching directory. + +The default also supplies the picker preview and lock-screen background, and remains usable on older versions of Omarchy. Themes without alternatives work as before. + +Alternatives are for still images. A video background, and the intro video of a still, plays the same on every monitor. + ### Light mode If you're making a light mode theme, set `mode = "light"` at the top of your `colors.toml`. Then it'll automatically be paired with light mode for all the apps. (The old way of dropping an empty file called `light.mode` in the root of your theme still works too.) diff --git a/shell/plugins/background/Background.qml b/shell/plugins/background/Background.qml index 1b785e0c417f..6f44c798d718 100644 --- a/shell/plugins/background/Background.qml +++ b/shell/plugins/background/Background.qml @@ -7,6 +7,7 @@ import QtQuick.Shapes import qs.Commons import qs.Commons as Commons import qs.Ui +import "BackgroundVariants.js" as BackgroundVariants Item { id: root @@ -20,6 +21,7 @@ Item { property string currentBackground: "" property string displayedBackground: "" + property int displayedVersion: 0 property string incomingBackground: "" property string oldBackground: "" // A theme switch names its next background before it has staged the rest of @@ -40,7 +42,6 @@ Item { property var sizeQueue: [] property bool finishingTransition: false property int backgroundVersion: 0 - property int reloadVersion: 0 property int revealStartedVersion: -1 property int pendingThemeVersion: -1 property string pendingColorsRaw: "" @@ -48,12 +49,45 @@ Item { property real revealProgress: 1 readonly property bool ready: { if (isVideo(displayedBackground)) return true - if (backgrounds.instances.length === 0) return false + // A scan clears busy before onResolved installs its dimensions and paths. + // Keep startup covered until those candidates and every output settle. + if (variantCatalog.busy || resolvedVariantGeneration !== variantCatalog.generation || backgrounds.instances.length === 0) return false for (var panel of backgrounds.instances) { if (!panel.backgroundReady) return false } return true } + property var displayedCandidates: [] + // What the variant catalog scans. A video held behind the last still is + // OWE's to draw, so it must not replace the candidates of the stills this + // layer still shows or is revealing. + property string catalogBackground: "" + property int catalogVersion: 0 + property int resolvedVariantGeneration: -1 + // A change that arrives while a reveal is on screen waits for it to end. + // Starting over at once would capture each base, which still holds the + // image from before that reveal, and step the desktop back to it. + property var queuedTransition: null + // The latest selection, ahead of currentBackground while a change is queued. + readonly property string selectedBackground: queuedTransition ? queuedTransition.finalPath : currentBackground + signal captureBackground() + + BackgroundVariantCatalog { + id: variantCatalog + path: root.catalogBackground + revision: root.catalogVersion + onResolved: { + // Variant paths must have a native size before any frame can load them. + var known = Object.assign({}, root.nativeSizes) + for (var i = 0; i < candidates.length; i++) { + var candidate = candidates[i] + known[candidate.path] = { width: candidate.width, height: candidate.height } + } + root.nativeSizes = known + if (!root.incomingBackground) root.displayedCandidates = candidates + root.resolvedVariantGeneration = variantCatalog.generation + } + } function isVideo(path) { return Util.isVideoPath(path) @@ -98,7 +132,6 @@ Item { } function setBackground(path, instant) { - if (instant) reloadVersion += 1 transitionBackground("", path, path, instant, instant) } @@ -106,7 +139,23 @@ Item { path = String(path || "").trim() finalPath = String(finalPath || path).trim() fromPath = String(fromPath || "").trim() - if (!path || (!force && finalPath === currentBackground)) return + if (!path) return false + // Reselecting what is already coming in withdraws a change queued behind it. + if (!force && finalPath === currentBackground) { + discardQueuedTransition() + return false + } + if (!instant && !isVideo(path) && (revealAnimation.running || finishingTransition)) { + // The theme files are not watched, so a queued theme's palette passes + // on to the change that replaces it. + var theme = queuedTransition ? queuedTransition.theme : null + queuedTransition = { fromPath: fromPath, path: path, finalPath: finalPath, force: force, theme: theme } + queuedTransitionTimer.restart() + return true + } + discardQueuedTransition() + // Capture each output's actual variant before theme paths are replaced. + captureBackground() if (path !== preparedBackground) preparedBackground = "" preparedBackgroundTimer.stop() lastTransitionPath = path @@ -123,8 +172,10 @@ Item { // still stays on screen until OWE has the first frame and suspends this // layer, so the desktop does not show an empty background meanwhile. A // running reveal finishes on its incoming still, which OWE fades from. - if (!instant && !root.suspended && displayedBackground && isVideo(path) && !isVideo(displayedBackground)) return + if (!instant && !root.suspended && displayedBackground && isVideo(path) && !isVideo(displayedBackground)) return false + catalogBackground = finalPath + catalogVersion = backgroundVersion revealAnimation.stop() revealGraceTimer.stop() finishingTransition = false @@ -135,14 +186,40 @@ Item { oldBackground = "" incomingBackground = "" preparedBackground = "" + displayedCandidates = [] + displayedVersion = backgroundVersion displayedBackground = finalPath revealProgress = 1 - return + return false } oldBackground = fromPath || displayedBackground incomingBackground = path revealProgress = 0 + return false + } + + function takeQueuedTransition() { + var queued = queuedTransition + queuedTransitionTimer.stop() + queuedTransition = null + return queued + } + + // A queued change that will not run still owes its theme's palette. It is + // applied at once: left pending, it could land after a newer theme's. + function discardQueuedTransition() { + var queued = takeQueuedTransition() + if (!queued || !queued.theme) return + setPendingTheme(queued.theme.colors, queued.theme.shell) + applyPendingTheme() + } + + function runQueuedTransition() { + var queued = takeQueuedTransition() + if (!queued) return + if (queued.theme) transitionBackgroundWithTheme(queued.fromPath, queued.path, queued.finalPath, queued.theme.colors, queued.theme.shell) + else transitionBackground(queued.fromPath, queued.path, queued.finalPath, false, queued.force) } function setPendingTheme(colorsB64, shellB64) { @@ -168,7 +245,11 @@ Item { } function transitionBackgroundWithTheme(fromPath, path, finalPath, colorsB64, shellB64) { - transitionBackground(fromPath, path, finalPath, false, true) + // A queued switch keeps its palette, so the colors still turn with its reveal. + if (transitionBackground(fromPath, path, finalPath, false, true)) { + queuedTransition.theme = { colors: colorsB64, shell: shellB64 } + return + } setPendingTheme(colorsB64, shellB64) if (!incomingBackground || revealProgress >= 1) applyPendingTheme() } @@ -213,6 +294,7 @@ Item { preparedBackground = "" finishingTransition = false pruneNativeSizes() + runQueuedTransition() } onReadyChanged: maybeFinishTransition() @@ -244,6 +326,7 @@ Item { function pruneNativeSizes() { var kept = {} var paths = [displayedBackground, incomingBackground, oldBackground, preparedBackground] + for (var c = 0; c < displayedCandidates.length; c++) paths.push(displayedCandidates[c].path) for (var i = 0; i < paths.length; i++) { if (paths[i] && nativeSizes[paths[i]] !== undefined) kept[paths[i]] = nativeSizes[paths[i]] } @@ -358,6 +441,18 @@ Item { onTriggered: root.beginReveal() } + // A reveal that an output never completes must not hold later changes back. + Timer { + id: queuedTransitionTimer + interval: 2000 + repeat: false + onTriggered: { + revealAnimation.stop() + root.finishingTransition = false + root.runQueuedTransition() + } + } + Timer { id: pendingThemeFallbackTimer interval: 300 @@ -375,6 +470,8 @@ Item { easing.type: Easing.OutCubic onFinished: { if (root.incomingBackground) { + root.displayedCandidates = variantCatalog.candidates + root.displayedVersion = root.backgroundVersion // After a video was chosen during the reveal, the incoming still // stays until OWE takes the background. root.displayedBackground = root.currentBackground && !root.isVideo(root.currentBackground) @@ -413,7 +510,7 @@ Item { // A function, not a binding: onStatusChanged can run before a binding // on the same status has caught up. function incomingReady() { - return root.incomingBackground !== "" && incomingFrame.status === Image.Ready + return root.incomingBackground !== "" && !variantCatalog.busy && incomingFrame.status === Image.Ready } property int readyFrames: 0 readonly property bool backgroundReady: base.ready && readyFrames >= 2 @@ -423,6 +520,21 @@ Item { onTriggered: panel.readyFrames += 1 } + property var failedVariants: [] + // ShellScreen's ratio is rounded up on Wayland; the window follows + // wp_fractional_scale_v1 and reports the actual output scale. + readonly property real pixelScale: panel.devicePixelRatio + readonly property string displayedPath: BackgroundVariants.choose( + root.displayedCandidates.filter(function(candidate) { return panel.failedVariants.indexOf(candidate.path) === -1 }), + root.displayedBackground, width, height, pixelScale) + readonly property string incomingPath: BackgroundVariants.choose( + variantCatalog.candidates.filter(function(candidate) { return panel.failedVariants.indexOf(candidate.path) === -1 }), + root.incomingBackground, width, height, pixelScale) + + function rejectVariant(path) { + if (failedVariants.indexOf(path) === -1) failedVariants = failedVariants.concat([path]) + } + // Decode the wallpaper at the size this screen can show, not the size // it was shipped at. With PreserveAspectCrop Qt takes sourceSize as the // area to cover, so this is the smallest decode that still fills the @@ -433,8 +545,8 @@ Item { // decoded at native size first, and a wallpaper smaller than the screen // is decoded at its own size rather than scaled up to cover the screen. readonly property bool sized: width > 0 && height > 0 - readonly property int decodeWidth: sized ? Math.ceil(width * screen.devicePixelRatio) : 0 - readonly property int decodeHeight: sized ? Math.ceil(height * screen.devicePixelRatio) : 0 + readonly property int decodeWidth: sized ? Math.ceil(width * pixelScale) : 0 + readonly property int decodeHeight: sized ? Math.ceil(height * pixelScale) : 0 function decodeSize(path) { if (!sized || !path) return Qt.size(0, 0) @@ -462,29 +574,37 @@ Item { BackgroundMedia { id: base anchors.fill: parent - path: root.displayedBackground - version: root.reloadVersion + path: panel.displayedPath + version: root.displayedVersion + // Versioned URLs invalidate replaced files without disabling sharing + // between outputs that use the same path and decode size. cached: true constrainDecode: true - decodeSize: panel.decodeSize(root.displayedBackground) - onFailedChanged: if (failed) root.recoverBackground(path) + decodeSize: panel.decodeSize(panel.displayedPath) + onFailedChanged: { + if (!failed) return + var failedPath = path + // Changing the chosen variant synchronously reenters Image.failed. + Qt.callLater(function() { + if (!base.failed || base.path !== failedPath) return + // A broken alternative is local to this output. Only a failed + // default should resolve the shared selection from the state link. + if (failedPath === root.displayedBackground) root.recoverBackground(failedPath) + else panel.rejectVariant(failedPath) + }) + } onReadyChanged: panel.readyFrames = 0 } - Image { + ShaderEffectSource { id: oldFrame anchors.fill: parent - readonly property size decode: panel.decodeSize(root.oldBackground) - source: decode.width > 0 ? root.imageUrl(root.oldBackground) : "" - sourceSize.width: decode.width - sourceSize.height: decode.height - fillMode: Image.PreserveAspectCrop - asynchronous: true - cache: false + sourceItem: root.oldBackground !== "" ? base : null + live: false smooth: true - mipmap: true - visible: root.oldBackground !== "" && root.revealProgress < 1 - onStatusChanged: panel.maybeStartReveal() + // Another output can finish the shared reveal before this one's + // incoming image decodes, including with animations disabled. + visible: root.oldBackground !== "" && (root.revealProgress < 1 || incomingFrame.status !== Image.Ready) } Item { @@ -508,8 +628,11 @@ Item { // The same URL and size as a prepared frame keeps its decoded // image, so a transition to it can reveal at once. readonly property string framePath: root.incomingBackground || root.preparedBackground - readonly property size decode: panel.decodeSize(framePath) - source: decode.width > 0 ? root.imageUrl(framePath) : "" + readonly property string resolvedPath: root.incomingBackground && !variantCatalog.busy ? panel.incomingPath : framePath + readonly property size decode: panel.decodeSize(resolvedPath) + // Keep a prepared default decoded while the catalog scans. Only + // maybeStartReveal is gated; a flat background retains its frame. + source: decode.width > 0 ? root.imageUrl(resolvedPath) : "" sourceSize.width: decode.width sourceSize.height: decode.height fillMode: Image.PreserveAspectCrop @@ -517,7 +640,10 @@ Item { cache: false smooth: true mipmap: true - onStatusChanged: panel.maybeStartReveal() + onStatusChanged: { + if (status === Image.Error && root.incomingBackground) panel.rejectVariant(resolvedPath) + panel.maybeStartReveal() + } } } @@ -551,12 +677,21 @@ Item { Connections { target: root + function onCaptureBackground() { + oldFrame.scheduleUpdate() + panel.failedVariants = [] + } function onIncomingBackgroundChanged() { panel.maskReady = false panel.maybeStartReveal() } } + Connections { + target: variantCatalog + function onResolved() { panel.maybeStartReveal() } + } + DesktopClicks { service: root } } } diff --git a/shell/plugins/background/BackgroundVariantCatalog.qml b/shell/plugins/background/BackgroundVariantCatalog.qml new file mode 100644 index 000000000000..33614001f9db --- /dev/null +++ b/shell/plugins/background/BackgroundVariantCatalog.qml @@ -0,0 +1,53 @@ +import QtQuick +import Quickshell.Io + +Item { + id: root + + property string path: "" + property int revision: 0 + property var candidates: [] + property bool busy: false + property int generation: 0 + property int timeoutSeconds: 10 + signal resolved() + + function refresh() { + generation += 1 + busy = true + if (!scan.running) Qt.callLater(root.start) + } + + function start() { + if (scan.running) return + scan.generation = generation + scan.command = ["timeout", String(timeoutSeconds), "python", + decodeURIComponent(Qt.resolvedUrl("variant-images.py").toString().replace(/^file:\/\//, "")), path] + scan.running = true + } + + onPathChanged: refresh() + onRevisionChanged: refresh() + + Process { + id: scan + property int generation: 0 + stdout: StdioCollector { id: output; waitForEnd: true } + onExited: function(exitCode, exitStatus) { + if (generation !== root.generation) { + root.start() + return + } + var next = [] + // The scanner flushes one candidate at a time. A bounded scan may end + // before the last file, but must not discard already discovered images. + var lines = String(output.text || "").split("\n") + for (var i = 0; i < lines.length; i++) { + try { next.push(JSON.parse(lines[i])) } catch (error) {} + } + root.candidates = next + root.busy = false + root.resolved() + } + } +} diff --git a/shell/plugins/background/BackgroundVariants.js b/shell/plugins/background/BackgroundVariants.js new file mode 100644 index 000000000000..8e7b5213b95e --- /dev/null +++ b/shell/plugins/background/BackgroundVariants.js @@ -0,0 +1,34 @@ +// The default image remains the selected design; rendering never changes its +// symlink. Screen dimensions are already rotated and expressed in logical pixels. +function choose(candidates, fallback, width, height, scale) { + width *= scale || 1 + height *= scale || 1 + if (!(width > 0 && height > 0)) return fallback + + var best = null + var bestFit = -1 + var bestScale = Infinity + for (var i = 0; i < candidates.length; i++) { + var candidate = candidates[i] + if (!(candidate.width > 0 && candidate.height > 0)) continue + var ratio = candidate.width / candidate.height + var target = width / height + var fit = Math.min(ratio / target, target / ratio) + var enlargement = Math.max(width / candidate.width, height / candidate.height) + var tied = Math.abs(fit - bestFit) < 0.000000001 + // At the same shape, choose the smallest sufficient image. If none is + // sufficient, choose the largest available one. + var betterSize = enlargement <= 1 + ? bestScale > 1 || enlargement > bestScale + : bestScale > 1 && enlargement < bestScale + if (!best || fit > bestFit + 0.000000001 || (tied && (betterSize + || (enlargement === bestScale && candidate.path < best.path)))) { + best = candidate + bestFit = fit + bestScale = enlargement + } + } + return best ? best.path : fallback +} + +if (typeof module !== "undefined") module.exports = { choose: choose } diff --git a/shell/plugins/background/variant-images.py b/shell/plugins/background/variant-images.py new file mode 100644 index 000000000000..918478e99c39 --- /dev/null +++ b/shell/plugins/background/variant-images.py @@ -0,0 +1,106 @@ +#!/usr/bin/python +"""List still-image variants without decoding wallpapers into the shell.""" + +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import time + + +EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp"} +CACHE_LIFETIME = 30 * 24 * 60 * 60 + + +def cache_directory(): + return Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache") / "omarchy/background-dimensions" + + +def dimensions(path, cache): + try: + # Theme staging changes both timestamps even when the pixels are unchanged. + # Hash compressed bytes instead; one record per path also bounds replacements. + with path.open("rb") as image: + signature = hashlib.file_digest(image, "sha256").hexdigest() + cached = cache / hashlib.sha256(str(path).encode()).hexdigest() + except OSError: + return None + + try: + record = json.loads(cached.read_text()) + if record["signature"] == signature and record["width"] > 0 and record["height"] > 0: + try: + cached.touch() + except OSError: + pass + return {"path": str(path), "width": record["width"], "height": record["height"]} + except (OSError, ValueError, KeyError, TypeError): + pass + + try: + # Read both fields in one process, rather than starting libvips twice. + header = subprocess.check_output( + ["vipsheader", "-a", str(path)], + stderr=subprocess.DEVNULL, timeout=2, text=True, + ) + fields = dict(line.split(": ", 1) for line in header.splitlines() if ": " in line) + width, height = int(fields["width"]), int(fields["height"]) + if width <= 0 or height <= 0: + return None + except (OSError, ValueError, KeyError, subprocess.SubprocessError): + return None + + # Caching is best-effort: a full or read-only cache must not hide a valid image. + temporary = cached.with_suffix(f".{os.getpid()}.tmp") + try: + cache.mkdir(parents=True, exist_ok=True) + temporary.write_text(json.dumps({"signature": signature, "width": width, "height": height})) + temporary.replace(cached) + except OSError: + try: + temporary.unlink(missing_ok=True) + except OSError: + pass + return {"path": str(path), "width": width, "height": height} + + +def prune_cache(cache): + try: + cutoff = time.time() - CACHE_LIFETIME + for entry in cache.iterdir(): + if entry.is_file() and entry.stat().st_mtime < cutoff: + entry.unlink() + except OSError: + pass + + +def iter_candidates(default, cache): + # The sibling directory opts an image into the convention. A directly + # selected variant without its own sibling directory stays an ordinary file. + if default.suffix.lower() not in EXTENSIONS: + return + directory = default.with_suffix("") + if not directory.is_dir(): + return + prune_cache(cache) + files = [default] + files.extend(sorted(p for p in directory.iterdir() + if p.is_file() and p.suffix.lower() in EXTENSIONS)) + for path in files: + if result := dimensions(path, cache): + yield result + + +def candidates(default, cache): + return list(iter_candidates(default, cache)) + + +if __name__ == "__main__": + default = Path(sys.argv[1]) + try: + for candidate in iter_candidates(default, cache_directory()): + print(json.dumps(candidate), flush=True) + except OSError: + pass diff --git a/shell/services/BackgroundSwitch.qml b/shell/services/BackgroundSwitch.qml index 3b629663d941..8627497a12f0 100644 --- a/shell/services/BackgroundSwitch.qml +++ b/shell/services/BackgroundSwitch.qml @@ -52,7 +52,7 @@ Item { function selected() { if (queuedPath) return queuedPath if (token && intro && (snapshotProc.running || token === intro.themeToken)) return still - return backgroundService ? backgroundService.currentBackground : "" + return backgroundService ? backgroundService.selectedBackground : "" } function displayedStill() { @@ -66,7 +66,7 @@ Item { if (!path || !intro || !backgroundService) return "unavailable" if (busy) { queuedPath = path - } else if (path !== backgroundService.currentBackground) { + } else if (path !== backgroundService.selectedBackground) { // A playing intro hides the shell's background, so even a still // without an intro of its own has to come in under the cover. if (clipPath || backgroundService.suspended) { diff --git a/test/shell.d/background-transition-test.sh b/test/shell.d/background-transition-test.sh new file mode 100644 index 000000000000..e028a2cf1cd7 --- /dev/null +++ b/test/shell.d/background-transition-test.sh @@ -0,0 +1,27 @@ +#!/bin/bash + +set -euo pipefail +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +# OpenGL-backed Qt Quick rendering in a private X server: no desktop surfaces, +# compositor, or user state. The software Qt Quick backend cannot render masks. +for dependency in python quickshell magick vipsheader xvfb-run Xvfb xauth; do + if ! command -v "$dependency" >/dev/null; then + skip "$dependency unavailable; skipping rendered background transition fixture" + exit 0 + fi +done + +# Set OMARCHY_BACKGROUND_TEST_DIR to retain screenshots after a successful run. +render_dir=${OMARCHY_BACKGROUND_TEST_DIR:-$(mktemp -d /tmp/omarchy-background-render.XXXXXX)} +trap 'if (( $? == 0 )) && [[ -z ${OMARCHY_BACKGROUND_TEST_DIR:-} ]]; then rm -rf "$render_dir"; fi' EXIT +ulimit -c 0 2>/dev/null || true + +for scenario in handoff slow-incoming reduced-motion; do + if ! env -u WAYLAND_DISPLAY -u QT_QUICK_BACKEND -u QSG_RHI_BACKEND \ + QT_QPA_PLATFORM=xcb QT_QPA_PLATFORMTHEME=basic LIBGL_ALWAYS_SOFTWARE=1 \ + xvfb-run -a python "$SHELL_TEST_DIR/fixtures/background-transition/render-test.py" "$ROOT" "$render_dir/$scenario" "$scenario"; then + fail "rendered background transitions preserve per-output frames ($scenario)" "Artifacts: $render_dir/$scenario" + fi + pass "rendered backgrounds preserve per-output frames ($scenario)" +done diff --git a/test/shell.d/background-variants-test.sh b/test/shell.d/background-variants-test.sh new file mode 100755 index 000000000000..e3ef2e1a343c --- /dev/null +++ b/test/shell.d/background-variants-test.sh @@ -0,0 +1,179 @@ +#!/bin/bash + +set -euo pipefail +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +run_node_test <<'JS' +const { choose } = requireFromRoot('shell/plugins/background/BackgroundVariants.js') +const image = (path, width, height) => ({ path, width, height }) +const choices = [image('default', 3840, 2160), image('wide', 5120, 2160), image('portrait', 2160, 3840)] +assertEqual(choose(choices, 'default', 1920, 1080, 1), 'default', '16:9 output keeps the default') +assertEqual(choose(choices, 'default', 2560, 1080, 2), 'wide', 'scaled ultrawide output chooses its authored variant') +assertEqual(choose(choices, 'default', 1080, 1920, 2), 'portrait', 'rotated output chooses portrait artwork') +assertEqual(choose(choices, 'default', 1920, 1080, 1), 'default', 'selection on another monitor remains independent') +const resolutions = [image('1080', 1920, 1080), image('4k', 3840, 2160), image('8k', 7680, 4320)] +assertEqual(choose(resolutions, 'default', 1920, 1080, 1), '1080', 'smallest sufficient image wins at equal aspect ratio') +assertEqual(choose(resolutions, 'default', 1920, 1080, 2), '4k', 'physical pixel density controls resolution selection') +const fractional = [image('2560x1600', 2560, 1600), image('3840x2400', 3840, 2400)] +assertEqual(choose(fractional, 'default', 1600, 1000, 1.6), '2560x1600', 'fractional scale does not select an oversized file') +assertEqual(choose(resolutions, 'default', 10000, 5625, 1), '8k', 'largest image wins when all require enlargement') +assertEqual(choose([image('huge', 8000, 8000), image('right-shape', 1280, 720)], 'default', 1920, 1080, 1), 'right-shape', 'aspect ratio takes precedence over resolution') +assertEqual(choose([], 'default', 1920, 1080, 1), 'default', 'empty groups fall back to the default') +assertEqual(choose([image('invalid', 0, 0)], 'default', 1920, 1080, 1), 'default', 'invalid dimensions are ignored') +assertEqual(choose(choices, 'default', 0, 0, 1), 'default', 'disconnected output has a safe fallback') +assertEqual(choose([image('b', 1920, 1080), image('a', 1920, 1080)], 'default', 1920, 1080, 1), 'a', 'equal candidates have a deterministic tie break') +JS + +require_command python +require_command vipsheader +python - <<'PY' +import importlib.util +import os +from pathlib import Path +import struct +import shutil +import time +import subprocess +import tempfile +from unittest.mock import patch +import zlib + +spec = importlib.util.spec_from_file_location('variants', Path(os.environ['ROOT']) / 'shell/plugins/background/variant-images.py') +variants = importlib.util.module_from_spec(spec) +spec.loader.exec_module(variants) + +def png(path, width, height): + def chunk(name, data): + return struct.pack('!I', len(data)) + name + data + struct.pack('!I', zlib.crc32(name + data)) + path.write_bytes(b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('!2I5B', width, height, 8, 2, 0, 0, 0)) + + chunk(b'IDAT', zlib.compress((b'\0' + b'\x00\x88\xff' * width) * height)) + chunk(b'IEND', b'')) + +with tempfile.TemporaryDirectory(prefix='omarchy-variant-test-') as temporary: + root = Path(temporary) + default = root / '01 image $(untouched).png' + cache = root / 'cache' + png(default, 160, 90) + assert variants.candidates(default, cache) == [], 'flat backgrounds should need no probing' + folder = default.with_suffix('') + folder.mkdir() + alternate = folder / 'arbitrary name.PNG' + png(alternate, 210, 90) + (folder / 'broken.webp').write_text('invalid') + (folder / 'video.mp4').write_text('not a still') + (folder / 'nested').mkdir() + png(folder / 'nested' / 'ignored.png', 90, 160) + expected = [{'path': str(default), 'width': 160, 'height': 90}, + {'path': str(alternate), 'width': 210, 'height': 90}] + assert variants.candidates(default, cache) == expected + print('ok - discovery reads actual dimensions, handles special paths, skips broken images and ignores deeper nesting') + with patch.object(variants.subprocess, 'check_output', side_effect=AssertionError('cache miss')): + assert variants.dimensions(alternate, cache) == expected[1] + before = len(list(cache.iterdir())) + png(alternate, 90, 160) + assert variants.dimensions(alternate, cache)['width'] == 90 + assert len(list(cache.iterdir())) == before + print('ok - dimension cache avoids repeat probes and replaces entries for changed images') + + blocked = root / 'blocked' + blocked.write_text('not a directory') + assert len(variants.candidates(default, blocked / 'cache')) == 2 + with patch.object(Path, 'write_text', side_effect=OSError('disk full')): + assert variants.dimensions(default, root / 'full-cache') == expected[0] + print('ok - unwritable and full caches do not discard successfully probed images') + + # Mirror theme-set staging with plain cp -r, which changes mtime and ctime. + theme = root / 'theme' + staged = root / 'current' / 'next-theme' + current = root / 'current' / 'theme' + (theme / 'backgrounds' / 'design').mkdir(parents=True) + png(theme / 'backgrounds' / 'design.png', 160, 90) + png(theme / 'backgrounds' / 'design' / 'wide.png', 210, 90) + theme_cache = root / 'theme-cache' + def apply_theme(): + staged.mkdir(parents=True) + subprocess.run(['cp', '-r', str(theme / 'backgrounds'), str(staged)], check=True) + shutil.rmtree(current, ignore_errors=True) + staged.rename(current) + apply_theme() + selected = current / 'backgrounds' / 'design.png' + first = variants.candidates(selected, theme_cache) + apply_theme() + with patch.object(variants.subprocess, 'check_output', side_effect=AssertionError('theme reapply cache miss')): + assert variants.candidates(selected, theme_cache) == first + assert len(list(theme_cache.iterdir())) == 2 + print('ok - reapplying an unchanged theme reuses dimensions without adding cache entries') + + stale = theme_cache / 'obsolete' + stale.write_text('old entry') + expired = time.time() - variants.CACHE_LIFETIME - 1 + os.utime(stale, (expired, expired)) + variants.candidates(selected, theme_cache) + assert not stale.exists() and len(list(theme_cache.iterdir())) == 2 + print('ok - unused dimension cache entries are pruned') + with patch.dict(os.environ, XDG_CACHE_HOME='', HOME=str(root)): + assert variants.cache_directory() == root / '.cache/omarchy/background-dimensions' + print('ok - an empty XDG_CACHE_HOME uses the home cache, not the working directory') + assert variants.candidates(alternate, cache) == [] + assert variants.candidates(folder / 'video.mp4', cache) == [] + print('ok - direct variant and video selection retain ordinary file behavior') + + backgrounds = root / 'backgrounds' + backgrounds.mkdir() + for index in range(4): + png(backgrounds / f'{index}.png', 160, 90) + (backgrounds / str(index)).mkdir() + png(backgrounds / str(index) / 'wide.png', 210, 90) + picker_cache = root / 'picker-cache' + subprocess.run(['bash', str(Path(os.environ['ROOT']) / 'bin/omarchy-menu-images'), '--prepare-only', str(backgrounds)], + env=dict(os.environ, XDG_CACHE_HOME=str(picker_cache)), check=True) + rows = list((picker_cache / 'omarchy/image-selector').glob('*.rows')) + assert len(rows) == 1 and len(rows[0].read_text().splitlines()) == 4 + print('ok - the real picker lists four designs from eight files without listing variants') +PY + +# This fixture exercises the real asynchronous Process lifecycle without +# creating any desktop surfaces or requiring a running compositor. +if command -v quickshell >/dev/null && command -v magick >/dev/null; then + variant_test_dir=$(mktemp -d /tmp/omarchy-variants.XXXXXX) + trap 'rm -rf "$variant_test_dir"' EXIT + mkdir -p "$variant_test_dir/config" "$variant_test_dir/images/design" "$variant_test_dir/runtime" + chmod 700 "$variant_test_dir/runtime" + ln -s "$ROOT/shell/plugins/background" "$variant_test_dir/config/background" + cp "$ROOT/test/shell.d/fixtures/background-variant-catalog.qml" "$variant_test_dir/config/shell.qml" + magick -size 160x90 xc:red "$variant_test_dir/images/design.png" + magick -size 210x90 xc:blue "$variant_test_dir/images/design/wide.png" + ulimit -c 0 2>/dev/null || true + env -u WAYLAND_DISPLAY QT_QPA_PLATFORM=offscreen QT_QPA_PLATFORMTHEME=basic \ + XDG_RUNTIME_DIR="$variant_test_dir/runtime" XDG_CACHE_HOME="$variant_test_dir/cache" \ + VARIANT_TEST_DIR="$variant_test_dir/images" \ + timeout 15 quickshell -p "$variant_test_dir/config" --no-color >"$variant_test_dir/runtime.log" 2>&1 || + fail "variant catalog runtime fixture exits" "$(cat "$variant_test_dir/runtime.log")" + if ! rg -q 'PASS variant catalog' "$variant_test_dir/runtime.log" || rg -q 'FAIL variant catalog' "$variant_test_dir/runtime.log"; then + fail "variant catalog rejects stale scans" "$(cat "$variant_test_dir/runtime.log")" + fi + pass "variant catalog resolves real files and rejects stale asynchronous scans" + + # Real fast candidates followed by a probe that outlasts the total deadline. + # Cover both uncached probes and cache hits before reaching the slow file. + mkdir -p "$variant_test_dir/bin" + real_vipsheader=$(command -v vipsheader) + printf '#!/bin/bash\nif [[ ${*: -1} == */zz-slow.png ]]; then sleep 3; fi\nexec "%s" "$@"\n' "$real_vipsheader" >"$variant_test_dir/bin/vipsheader" + chmod +x "$variant_test_dir/bin/vipsheader" + magick -size 90x160 xc:green "$variant_test_dir/images/design/zz-slow.png" + cp "$ROOT/test/shell.d/fixtures/background-variant-catalog-timeout.qml" "$variant_test_dir/config/shell.qml" + rm -rf "$variant_test_dir/cache" + for cache_state in cold warm; do + env -u WAYLAND_DISPLAY QT_QPA_PLATFORM=offscreen QT_QPA_PLATFORMTHEME=basic \ + PATH="$variant_test_dir/bin:$PATH" \ + XDG_RUNTIME_DIR="$variant_test_dir/runtime" XDG_CACHE_HOME="$variant_test_dir/cache" \ + VARIANT_TEST_DIR="$variant_test_dir/images" \ + timeout 8 quickshell -p "$variant_test_dir/config" --no-color >"$variant_test_dir/timeout.log" 2>&1 || + fail "timed-out variant catalog runtime fixture exits" "$(<"$variant_test_dir/timeout.log")" + if ! rg -q 'PASS partial variant catalog' "$variant_test_dir/timeout.log" || rg -q 'FAIL partial variant catalog' "$variant_test_dir/timeout.log"; then + fail "timed-out variant catalog retains completed candidates" "$(<"$variant_test_dir/timeout.log")" + fi + pass "timed-out variant catalog retains $cache_state-cache candidates and releases the reveal gate" + done +else + skip "quickshell or ImageMagick unavailable; skipping catalog runtime fixtures" +fi diff --git a/test/shell.d/fixtures/background-intro-lifecycle/switch-sequence.qml b/test/shell.d/fixtures/background-intro-lifecycle/switch-sequence.qml index df4c0d366e3e..e4b554656fe9 100644 --- a/test/shell.d/fixtures/background-intro-lifecycle/switch-sequence.qml +++ b/test/shell.d/fixtures/background-intro-lifecycle/switch-sequence.qml @@ -26,6 +26,7 @@ ShellRoot { property bool suspended: false property bool ready: true property string currentBackground: test.stage + "/old.png" + readonly property string selectedBackground: currentBackground property string displayedBackground: test.stage + "/old.png" property var nativeSizes: ({}) property var sets: [] diff --git a/test/shell.d/fixtures/background-transition/render-test.py b/test/shell.d/fixtures/background-transition/render-test.py new file mode 100644 index 000000000000..439d557f45c3 --- /dev/null +++ b/test/shell.d/fixtures/background-transition/render-test.py @@ -0,0 +1,194 @@ +"""Render production background logic on two isolated, differently shaped Items. + +Only desktop integration is replaced (screen surfaces, IPC, theme styling). +The production catalog, selection, capture, mask, images, and maybeFinishTransition +run unchanged. A delayed HTTP image exercises real Image.Loading at handoff. +""" + +from functools import partial +from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer +import os +from pathlib import Path +import shutil +import subprocess +import sys +import threading +import time +from urllib.parse import urlsplit + + +root, work = map(Path, sys.argv[1:3]) +scenario = sys.argv[3] if len(sys.argv) > 3 else "handoff" +config = work / "config" +images = work / "images" +runtime = work / "runtime" +for directory in (config, images, runtime, config / "Commons", config / "Ui"): + directory.mkdir(parents=True, exist_ok=True) +runtime.chmod(0o700) +for marker in ("waiting", "release"): + (work / marker).unlink(missing_ok=True) + + +def replace_once(text, old, new): + assert text.count(old) == 1, f"fixture boundary changed: {old}" + return text.replace(old, new) + + +def image(name, size, color): + path = images / name + path.parent.mkdir(parents=True, exist_ok=True) + subprocess.run(["magick", "-size", size, f"xc:{color}", str(path)], check=True) + + +image("old.png", "100x100", "white") +image("old/wide.png", "160x90", "red") +image("old/portrait.png", "90x160", "blue") +image("new.png", "100x100", "green") +image("new/wide.png", "160x90", "yellow") +image("new/portrait.png", "90x160", "cyan") +image("decoy.png", "100x100", "magenta") + +# A failed default must resolve the real saved selection, then choose variants. +state = work / ".local/state/omarchy/current" +state.mkdir(parents=True, exist_ok=True) +(state / "background").unlink(missing_ok=True) +(state / "background").symlink_to(images / "old.png") + + +class DelayedImage(SimpleHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_GET(self): + request = urlsplit(self.path) + if request.path == "/new/portrait.png" and (scenario != "handoff" or request.query == "v=2"): + # Hold the displayed frame alone, or both the incoming and displayed + # frames. The latter reproduces a slow output missing the shared reveal. + (work / "waiting").touch() + deadline = time.monotonic() + 15 + while not (work / "release").exists() and time.monotonic() < deadline: + time.sleep(0.02) + try: + super().do_GET() + except (BrokenPipeError, ConnectionResetError): + # Qt may cancel a replaced image's in-flight request. + pass + + +server = ThreadingHTTPServer(("127.0.0.1", 0), partial(DelayedImage, directory=str(images))) +threading.Thread(target=server.serve_forever, daemon=True).start() +port = server.server_port + +# Keep the real visual subtree and transition functions; replace only the +# Wayland-only surface with an Item in an OpenGL-backed QQuickWindow. +background = (root / "shell/plugins/background/Background.qml").read_text() +background = replace_once(background, "import Quickshell.Wayland\n", "") +background = replace_once(background, " id: root\n", """ id: root + property alias testPanels: backgrounds + function testPause() { revealAnimation.pause(); revealProgress = 0 } + function testFinish() { revealAnimation.complete() } +""") +background = replace_once(background, " Component.onCompleted: refreshBackground()", "") +if scenario != "handoff": + background = replace_once(background, "return Util.fileUrl(path)", + f'return "http://127.0.0.1:{port}/" + path.slice({len(str(images)) + 1})') +# The transparent click-only layer is desktop integration, not image rendering. +click_layer = background.index(" // OWE's video layer takes no clicks,") +click_component = background.index(" // Inline components do not see this file's ids,") +background = background[:click_layer] + background[click_component:] +background = replace_once(background, "model: Quickshell.screens", "model: [{width: 160, height: 90, x: 0}, {width: 90, height: 160, x: 180}]") +background = replace_once(background, " PanelWindow {\n id: panel", """ Item { + id: panel + parent: root + width: modelData.width + height: modelData.height + x: modelData.x + property real devicePixelRatio: 1 + property alias testBase: base + property alias testIncoming: incomingFrame""") +for boundary in ( + " screen: modelData\n", + " anchors { top: true; bottom: true; left: true; right: true }\n", + ' color: "transparent"\n', + " updatesEnabled: true\n", + ' WlrLayershell.namespace: "omarchy-background"\n', + " WlrLayershell.layer: WlrLayer.Background\n", + " WlrLayershell.keyboardFocus: WlrKeyboardFocus.None\n", + " exclusionMode: ExclusionMode.Ignore\n", +): + background = replace_once(background, boundary, "") +(config / "BackgroundUnderTest.qml").write_text(background) +for name in ("BackgroundVariantCatalog.qml", "BackgroundVariants.js", "variant-images.py"): + shutil.copy(root / "shell/plugins/background" / name, config / name) + +# Serve displayed frames over HTTP to control an actual asynchronous decode. +media = (root / "shell/Ui/BackgroundMedia.qml").read_text() +media = replace_once(media, "Util.fileUrl(path)", f'("http://127.0.0.1:{port}/" + path.slice({len(str(images)) + 1}))') +(config / "Ui/BackgroundMedia.qml").write_text(media) +(config / "Ui/ScreenMoveRemap.qml").write_text("import QtQuick\nItem { property var window; property bool remapping: false }\n") +shutil.copy(root / "shell/Commons/Util.qml", config / "Commons/Util.qml") +(config / "Commons/Style.qml").write_text("""pragma Singleton +import QtQuick +import Quickshell +QtObject { + function duration(ms) { return Quickshell.env("VARIANT_RENDER_SCENARIO") === "reduced-motion" ? 0 : 1000000 } + function scheduleRefresh() {} +} +""") +(config / "Commons/Color.qml").write_text("""pragma Singleton +import QtQuick +QtObject { + property string loadedColors: "" + function loadColors(raw) { loadedColors = raw } + function loadShell(raw) {} +} +""") +(config / "Commons/ShellIpc.qml").write_text("import QtQuick\nQtObject { property string target }\n") +(config / "Commons/qmldir").write_text("singleton Util 1.0 Util.qml\nsingleton Style 1.0 Style.qml\nsingleton Color 1.0 Color.qml\nShellIpc 1.0 ShellIpc.qml\n") +shutil.copy(Path(__file__).with_name("shell.qml"), config / "shell.qml") + +try: + result = subprocess.run( + ["quickshell", "-p", str(config), "--no-color"], + env=dict(os.environ, XDG_RUNTIME_DIR=str(runtime), XDG_CACHE_HOME=str(work / "cache"), + HOME=str(work), VARIANT_RENDER_DIR=str(work), VARIANT_RENDER_SCENARIO=scenario), + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=25, + ) + (work / "runtime.log").write_text(result.stdout) + assert result.returncode == 0 and "PASS rendered transition" in result.stdout and "FAIL" not in result.stdout, result.stdout + assert not any(error in result.stdout for error in ("Binding loop", "ReferenceError", "TypeError")), result.stdout + assert (work / "waiting").exists(), "portrait frame never exercised Image.Loading" + + # Sample the center and edges of both outputs: old pixels must be the + # authored variants (red/blue), not the white default or magenta live base. + stages = (("initial", (b"\xff\0\0", b"\0\0\xff")), + ("finished", (b"\xff\xff\0", b"\0\xff\xff"))) + if scenario == "handoff": + stages += (("captured", (b"\xff\0\0", b"\0\0\xff")), + ("held", (b"\xff\xff\0", b"\0\xff\xff")), + ("reloaded", (b"\xff\0\xff", b"\xff\0\0")), + ("variant-fallback", (b"\0\x80\0", b"\xff\0\0")), + ("recovered", (b"\xff\0\0", b"\0\0\xff"))) + else: + stages += (("slow-incoming", (b"\xff\xff\0", b"\0\0\xff")),) + for stage, colors in stages: + for points, color in ((("5,5", "80,45", "155,85"), colors[0]), + (("185,5", "225,80", "265,155"), colors[1])): + for point in points: + actual = subprocess.check_output(["magick", str(work / f"{stage}.png"), + "-crop", "1x1+" + point.replace(",", "+"), "+repage", "-depth", "8", "rgb:-"]) + assert actual == color, f"{stage} at {point}: expected {color!r}, got {actual!r}" + print(f"ok - rendered {stage} pixels match both output variants") + + if scenario == "handoff": + # A change made mid-reveal waits for it, so the frame stays as it was. + for stage in ("reveal", "interrupted"): + for point, color in (("5,5", b"\xff\0\0"), ("80,45", b"\xff\xff\0"), + ("155,85", b"\xff\0\0"), ("185,5", b"\0\0\xff"), + ("225,80", b"\0\xff\xff"), ("265,155", b"\0\0\xff")): + actual = subprocess.check_output(["magick", str(work / f"{stage}.png"), + "-crop", "1x1+" + point.replace(",", "+"), "+repage", "-depth", "8", "rgb:-"]) + assert actual == color, f"{stage} at {point}: expected {color!r}, got {actual!r}" + print("ok - rendered reveal mask shows incoming centers and captured outgoing edges, also under a queued change") +finally: + server.shutdown() diff --git a/test/shell.d/fixtures/background-transition/shell.qml b/test/shell.d/fixtures/background-transition/shell.qml new file mode 100644 index 000000000000..76b84c9acb86 --- /dev/null +++ b/test/shell.d/fixtures/background-transition/shell.qml @@ -0,0 +1,204 @@ +import Quickshell +import Quickshell.Io +import QtQuick +import QtQuick.Window +import qs.Commons as Commons + +ShellRoot { + id: test + readonly property string directory: Quickshell.env("VARIANT_RENDER_DIR") + readonly property string images: directory + "/images/" + readonly property string scenario: Quickshell.env("VARIANT_RENDER_SCENARIO") + property int step: 0 + property int ticks: 0 + property bool grabbing: false + + function fail(message) { + console.error("FAIL rendered transition: " + message) + Qt.quit() + } + + function capture(name, next) { + grabbing = true + if (!background.grabToImage(function(result) { + if (!result.saveToFile(directory + "/" + name + ".png")) { + test.fail("could not save " + name) + return + } + test.grabbing = false + next() + })) test.fail("could not grab " + name) + } + + Window { + width: 270 + height: 160 + visible: true + color: "black" + + BackgroundUnderTest { + id: background + anchors.fill: parent + } + } + + Process { + id: release + command: ["touch", test.directory + "/release"] + } + + Process { + id: replaceImages + command: ["bash", "-c", 'magick -size 160x90 xc:magenta "$1/new/wide.png" && magick -size 90x160 xc:red "$1/new/portrait.png"', "--", test.images] + onExited: function(exitCode) { + if (exitCode !== 0) test.fail("could not replace variant images") + else test.step = 7 + } + } + + Process { + id: removeVariant + command: ["rm", test.images + "new/wide.png"] + onExited: function(exitCode) { + if (exitCode !== 0) test.fail("could not remove the wide variant") + else { + test.step = 10 + // Keep the known catalog so the real Image.Error path is exercised. + background.displayedVersion += 1 + } + } + } + + Timer { + interval: 50 + repeat: true + running: true + onTriggered: { + test.ticks++ + if (test.ticks > 400) { test.fail("timed out at step " + test.step); return } + if (test.grabbing) return + var panels = background.testPanels.instances + if (panels.length !== 2) return + var wide = panels[0] + var portrait = panels[1] + if (test.step === 0) { + background.setBackground(test.images + "old.png", true) + test.step = 1 + } else if (test.step === 1 && background.ready && + /wide.png$/.test(wide.displayedPath) && /portrait.png$/.test(portrait.displayedPath)) { + test.capture("initial", function() { + background.transitionBackground("", test.images + "new.png", test.images + "new.png", false, false) + test.step = 2 + }) + } else if (test.step === 2 && test.scenario !== "handoff" && wide.maskReady && + portrait.testIncoming.status === Image.Loading) { + // End the fast output's reveal while the portrait still has neither + // replacement frame. Reduced motion reaches this point on its own. + if (test.scenario !== "reduced-motion") background.testFinish() + test.step = 20 + } else if (test.step === 20 && background.finishingTransition && + wide.testBase.ready && !portrait.testBase.ready && + portrait.testIncoming.status === Image.Loading) { + test.capture("slow-incoming", function() { + release.running = true + test.step = 21 + }) + } else if (test.step === 21 && background.ready && !background.incomingBackground) { + test.capture("finished", function() { + console.log("PASS rendered transition") + Qt.quit() + }) + } else if (test.step === 2 && test.scenario === "handoff" && wide.maskReady && portrait.maskReady && + wide.testIncoming.status === Image.Ready && portrait.testIncoming.status === Image.Ready) { + background.testPause() + // Reload the live bases with a different image. Frozen outgoing pixels + // must remain each output's old variant, proving an actual capture. + var known = Object.assign({}, background.nativeSizes) + known[test.images + "decoy.png"] = {width: 100, height: 100} + background.nativeSizes = known + background.displayedCandidates = [{path: test.images + "decoy.png", width: 100, height: 100}] + test.step = 3 + } else if (test.step === 3 && wide.testBase.ready && portrait.testBase.ready && + /decoy.png$/.test(wide.displayedPath) && /decoy.png$/.test(portrait.displayedPath)) { + test.capture("captured", function() { + background.revealProgress = 0.5 + test.step = 31 + }) + } else if (test.step === 31) { + test.capture("reveal", function() { + // A change made mid-reveal must wait for it, not restart it from + // the bases, which hold the decoy here. + background.transitionBackgroundWithTheme("", test.images + "old.png", test.images + "old.png", "cXVldWVk", "") + test.step = 32 + }) + } else if (test.step === 32) { + if (background.selectedBackground !== test.images + "old.png" || background.incomingBackground !== test.images + "new.png") { + test.fail("a change during a reveal was not queued behind it") + return + } + test.capture("interrupted", function() { + // Reselecting the incoming background withdraws the queued change. + background.setBackground(test.images + "new.png", false) + if (background.selectedBackground !== test.images + "new.png") { + test.fail("reselecting the incoming background kept the queued change") + return + } + if (Commons.Color.loadedColors !== "queued" || background.pendingThemeVersion !== -1) { + test.fail("a withdrawn theme switch did not apply its palette at once") + return + } + background.testFinish() + test.step = 4 + }) + } else if (test.step === 4 && wide.testBase.ready && !portrait.testBase.ready) { + if (!background.finishingTransition || !background.incomingBackground) { + test.fail("incoming frame released while portrait is still loading") + return + } + test.capture("held", function() { + release.running = true + test.step = 5 + }) + } else if (test.step === 5 && background.ready && !background.incomingBackground) { + if (background.finishingTransition || background.oldBackground || background.preparedBackground) { + test.fail("transition frames were not released") + return + } + test.capture("finished", function() { + test.step = 6 + replaceImages.running = true + }) + } else if (test.step === 7) { + background.setBackground(test.images + "new.png", true) + if (background.ready) { + test.fail("instant reload reported ready before the variant scan finished") + return + } + test.step = 8 + } else if (test.step === 8 && background.ready && + /wide.png$/.test(wide.displayedPath) && /portrait.png$/.test(portrait.displayedPath)) { + test.capture("reloaded", function() { + test.step = 9 + removeVariant.running = true + }) + } else if (test.step === 10 && background.ready && + wide.displayedPath === test.images + "new.png" && /portrait.png$/.test(portrait.displayedPath)) { + if (background.currentBackground !== test.images + "new.png") { + test.fail("a failed variant changed the shared selection") + return + } + test.capture("variant-fallback", function() { + background.setBackground(test.images + "missing.png", true) + test.step = 11 + }) + } else if (test.step === 11 && background.ready && + background.currentBackground === test.images + "old.png" && + /wide.png$/.test(wide.displayedPath) && /portrait.png$/.test(portrait.displayedPath)) { + test.capture("recovered", function() { + console.log("PASS rendered transition") + Qt.quit() + }) + } + } + } +} diff --git a/test/shell.d/fixtures/background-variant-catalog-timeout.qml b/test/shell.d/fixtures/background-variant-catalog-timeout.qml new file mode 100644 index 000000000000..aecd8d216aa8 --- /dev/null +++ b/test/shell.d/fixtures/background-variant-catalog-timeout.qml @@ -0,0 +1,27 @@ +import Quickshell +import QtQuick +import "background" + +ShellRoot { + BackgroundVariantCatalog { + path: Quickshell.env("VARIANT_TEST_DIR") + "/design.png" + timeoutSeconds: 1 + onResolved: { + if (busy || candidates.length !== 2 || candidates[1].width !== 210) { + console.error("FAIL partial variant catalog: " + JSON.stringify(candidates)) + } else { + console.log("PASS partial variant catalog") + } + Qt.quit() + } + } + + Timer { + running: true + interval: 5000 + onTriggered: { + console.error("FAIL partial variant catalog: timeout") + Qt.quit() + } + } +} diff --git a/test/shell.d/fixtures/background-variant-catalog.qml b/test/shell.d/fixtures/background-variant-catalog.qml new file mode 100644 index 000000000000..7d1b348a8c4d --- /dev/null +++ b/test/shell.d/fixtures/background-variant-catalog.qml @@ -0,0 +1,36 @@ +import Quickshell +import QtQuick +import "background" + +ShellRoot { + BackgroundVariantCatalog { + id: catalog + path: Quickshell.env("VARIANT_TEST_DIR") + "/design.png" + property int step: 0 + onResolved: { + if (candidates.length !== 2 || candidates[1].width !== 210) { + console.error("FAIL variant catalog: " + JSON.stringify(candidates)) + Qt.quit() + } else if (step === 0) { + step = 1 + // Begin a scan, then supersede it while its Process is still running. + path = Quickshell.env("VARIANT_TEST_DIR") + "/missing.png" + catalog.start() + path = Quickshell.env("VARIANT_TEST_DIR") + "/design.png" + revision++ + } else { + console.log("PASS variant catalog") + Qt.quit() + } + } + } + + Timer { + running: true + interval: 12000 + onTriggered: { + console.error("FAIL variant catalog: timeout") + Qt.quit() + } + } +}