Files
glassMxrph/quickshell/services/WallpaperService.qml
T
mxandClaude Opus 5.5 de9b863f3f Make the wallpaper picker a full-screen live preview
The screen previews the selected wallpaper with the real transition
(TransitionStage, now shared with the desktop background) under a
frosted sheet with a 16:9 thumbnail grid. Click or arrows preview,
double-click or Enter applies and switches the picker's output directly,
Space peeks, typing searches. Thumbnails mark outline wallpapers (wallfx
status).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 22:52:55 +01:00

324 lines
13 KiB
QML

pragma Singleton
import QtQuick
import Quickshell
import Quickshell.Io
import "../core"
Singleton {
id: root
property var images: []
property var observed: ({})
property string backend: "none"
property string error: ""
property string notice: ""
// "all" applies to every connected output in turn; "primary" or an output name targets one.
property string selectedMonitor: "all"
property var queue: []
readonly property var output: ScreenService.resolve(selectedMonitor)
readonly property string monitor: output ? output.name : ""
readonly property var paletteOutput: ConfigService.ready ? ScreenService.resolve(ConfigService.data.wallpaper.paletteMonitor) : null
readonly property string palettePath: paletteOutput ? (observed[paletteOutput.name] || (ConfigService.ready ? ConfigService.data.wallpaper.byMonitor[paletteOutput.name] : "") || "") : ""
readonly property string currentPath: observed[monitor] || (ConfigService.ready ? ConfigService.data.wallpaper.byMonitor[monitor] : "") || ""
property var nativePending: null
readonly property bool busy: applyJob.running || nativePending !== null || queue.length > 0
readonly property bool scanning: scanJob.running
function request(action, target) {
const name = target || monitor;
return {
action: action,
monitor: name,
backend: ConfigService.data.wallpaper.backend,
command: ConfigService.data.wallpaper.command,
current: observed[name] || ConfigService.data.wallpaper.byMonitor[name] || ""
};
}
function refresh() {
if (ConfigService.ready && monitor)
probeJob.start(request("provider"));
}
function scan() {
if (ConfigService.ready)
scanJob.start({
action: "scan",
directories: ConfigService.data.wallpaper.directories
});
}
function changed(output, path) {
const next = Object.assign({}, observed);
next[output] = path;
observed = next;
}
// Output -> path that switches without a change, because the picker's live
// preview already shows it there (see WallpaperBackground).
property var instant: ({})
function apply(path, instantOutput) {
const outputs = selectedMonitor === "all" ? Quickshell.screens.map(s => s.name) : [monitor];
if (!ConfigService.ready || !ConfigService.writable || !outputs.length || !outputs[0] || busy)
return false;
error = "";
const nextInstant = {};
if (instantOutput)
nextInstant[instantOutput] = path;
instant = nextInstant;
prepareTransition(path);
// Native rendering needs no provider round trip: decode once, then switch
// every output in one write so their transitions start together.
if (backend === "native" && ["native", "auto"].includes(ConfigService.data.wallpaper.backend)) {
const url = "file://" + encodeURI(path).replace(/#/g, "%23").replace(/\?/g, "%3F");
nativePending = {
request: {monitors: outputs},
result: {backend: "native", path: path, providerPath: path, url: url}
};
decodeCheck.source = "";
decodeCheck.source = url;
return true;
}
queue = outputs.slice(1).map(name => ({
path: path,
monitor: name
}));
const req = request("apply", outputs[0]);
req.path = path;
return applyJob.start(req);
}
// Starts the next queued output once the previous one has fully applied.
function applyNext() {
if (!queue.length)
return;
const next = queue[0];
const req = request("apply", next.monitor);
req.path = next.path;
queue = queue.slice(1);
applyJob.start(req);
}
onMonitorChanged: refresh()
// The monitor resolves before the configuration loads, so also probe once the
// configured backend is known (startup) and whenever it changes.
readonly property string configuredBackend: ConfigService.ready ? ConfigService.data.wallpaper.backend : ""
onConfiguredBackendChanged: refresh()
ProviderJob {
id: probeJob
onFinished: (request, result) => {
if (!result.ok) {
root.error = result.error;
return;
}
root.backend = result.backend;
root.notice = result.notice || "";
if (result.current)
root.changed(request.monitor, ConfigService.data.wallpaper.providerPaths[request.monitor] === result.current ? (ConfigService.data.wallpaper.byMonitor[request.monitor] || result.current) : result.current);
}
}
ProviderJob {
id: scanJob
onFinished: (request, result) => {
if (result.ok) {
root.images = result.images;
root.warmOutlines(result.images.map(image => image.path));
root.refreshOutlineStatus();
root.notice = (result.notice || "") + (result.limited ? " Showing the first 1,000 images." : "");
} else
root.error = result.error;
}
}
ProviderJob {
id: applyJob
onFinished: (request, result) => {
if (!result.ok) {
root.error = result.error;
root.queue = [];
return;
}
if(result.backend === "native") {
// Reload even when the previous output used the same file, so every output gets its decode check.
root.nativePending = {request:request,result:result};
decodeCheck.source = "";
decodeCheck.source = result.url;
} else root.finishApply(request,result);
}
}
function finishApply(request,result) {
const monitors = request.monitors || [request.monitor];
const next = Object.assign({}, ConfigService.data.wallpaper.byMonitor);
const providerPaths = Object.assign({}, ConfigService.data.wallpaper.providerPaths);
for (const name of monitors) {
next[name] = result.path;
providerPaths[name] = result.providerPath;
}
ConfigService.setValue("wallpaper.byMonitor", next);
ConfigService.setValue("wallpaper.providerPaths", providerPaths);
root.backend = result.backend;
for (const name of monitors)
root.changed(name, result.path);
root.error = "";
ConfigService.setValue("wallpaper.history",[result.path].concat(ConfigService.data.wallpaper.history.filter(p=>p!==result.path)).slice(0,50));
Qt.callLater(root.applyNext);
}
// Which change a wallpaper gets (wallpaper/shaders/transition.frag): its
// subject's outline when helpers/wallfx.py has cached maps for it, colonies
// otherwise. Nothing waits for a cut-out: an unprocessed wallpaper gets
// colonies now and is processed in the background for next time. The
// package sets GLASSMXRPH_WALLFX_PYTHON (numpy, opencv, onnxruntime) and
// GLASSMXRPH_WALLFX_MODEL; without them every change is colonies.
readonly property string wallfxPython: Quickshell.env("GLASSMXRPH_WALLFX_PYTHON") || ""
readonly property bool outlinesAvailable: wallfxPython !== "" && (Quickshell.env("GLASSMXRPH_WALLFX_MODEL") || "") !== ""
property var transitions: ({}) // path -> {kind, field, line}
property var choosing: []
function setTransition(path, plan) {
const next = Object.assign({}, transitions);
next[path] = plan;
transitions = next;
}
// `ifUnknown`: keep an answer already given in this change (the picker asks
// at apply time, every output's background asks again when it switches).
function prepareTransition(path, ifUnknown) {
if (!path || choosing.includes(path) || (ifUnknown && path in transitions))
return;
const excluded = ConfigService.ready && ConfigService.data.wallpaper.outlineExclude.includes(path);
if (!outlinesAvailable || excluded)
return setTransition(path, {kind: "colonies"});
const next = Object.assign({}, transitions);
delete next[path];
transitions = next;
choosing = choosing.concat([path]);
chooseNext();
}
function chooseNext() {
if (chooseJob.running || !choosing.length)
return;
chooseJob.path = choosing[0];
chooseJob.command = [wallfxPython, Quickshell.shellPath("helpers/wallfx.py"), "choose", choosing[0]];
chooseJob.running = true;
}
function warmOutlines(paths) {
if (!outlinesAvailable || warmJob.running || !paths.length)
return;
warmJob.command = ["nice", "-n", "15", wallfxPython, Quickshell.shellPath("helpers/wallfx.py"), "warm"].concat(paths);
warmJob.running = true;
}
// Session libraries on LD_LIBRARY_PATH (JACK, SANE) can be built against
// another glibc than the helper's interpreter: keep them out.
Process {
id: chooseJob
property string path: ""
environment: ({LD_LIBRARY_PATH: null})
stdout: StdioCollector {
id: chooseOutput
}
onExited: {
let plan = {kind: "colonies"};
try {
plan = JSON.parse(chooseOutput.text);
} catch (error) {}
const path = chooseJob.path;
root.choosing = root.choosing.filter(p => p !== path);
root.setTransition(path, plan);
if (plan.pending)
root.warmOutlines([path]);
Qt.callLater(root.chooseNext);
}
}
// Processes uncached wallpapers at low priority (~5 s each on the CPU);
// one pass at a time, and the helper skips what is already cached.
Process {
id: warmJob
environment: ({LD_LIBRARY_PATH: null})
onExited: root.refreshOutlineStatus()
}
// Path -> "outline", "colonies" or "pending", for the picker's badges.
property var outlineStatus: ({})
function refreshOutlineStatus() {
if (!outlinesAvailable || !images.length)
return;
if (statusJob.running)
return void (statusJob.again = true);
statusJob.command = [wallfxPython, Quickshell.shellPath("helpers/wallfx.py"), "status"].concat(images.map(image => image.path));
statusJob.running = true;
}
Process {
id: statusJob
property bool again: false
environment: ({LD_LIBRARY_PATH: null})
stdout: StdioCollector {
id: statusOutput
}
onExited: {
try {
root.outlineStatus = JSON.parse(statusOutput.text);
} catch (error) {}
if (statusJob.again) {
statusJob.again = false;
Qt.callLater(root.refreshOutlineStatus);
}
}
}
// Native backgrounds report when their new image has decoded; the reveal
// starts on every output together once all of them are ready.
property var revealWaiting: ({})
property int revealSerial: 0
function revealLoading(output) {
const next = Object.assign({}, revealWaiting);
next[output] = false;
revealWaiting = next;
revealFallback.restart();
}
function revealReady(output) {
// Arrived after the fallback already started the others: go now.
if (!(output in revealWaiting))
return void revealSerial++;
const next = Object.assign({}, revealWaiting);
next[output] = true;
revealWaiting = next;
if (Object.keys(next).every(k => next[k]))
startReveal();
}
function startReveal() {
revealFallback.stop();
revealWaiting = {};
revealSerial++;
}
// A stalled output must not hold the others back for long.
Timer {
id: revealFallback
interval: 400
onTriggered: root.startReveal()
}
// Confirms a native wallpaper decodes before it is saved; set imperatively by applyJob.
Image {
id: decodeCheck
visible:false
asynchronous:true
sourceSize:Qt.size(32,32)
onStatusChanged: {
if(!root.nativePending || source.toString()!==root.nativePending.result.url)return;
if(status===Image.Ready) {const pending=root.nativePending;root.nativePending=null;Qt.callLater(()=>root.finishApply(pending.request,pending.result));}
else if(status===Image.Error) {root.error="Could not decode this wallpaper";root.nativePending=null;root.queue=[];}
}
}
IpcHandler {
target: "wallpaper"
function picker(): void {ShellState.openWallpaperPicker();}
function changed(monitor: string, path: string): void {
root.changed(monitor, path);
}
function refresh(): void {
root.refresh();
root.scan();
}
function apply(path: string): bool {
return root.apply(path);
}
function status(): string {
return JSON.stringify({
backend: root.backend,
current: root.currentPath,
palettePath: root.palettePath,
busy: root.busy,
images: root.images.length,
error: root.error,
notice: root.notice
});
}
}
}