65 lines
2.8 KiB
QML
65 lines
2.8 KiB
QML
pragma ComponentBehavior: Bound
|
|
import QtQuick
|
|
import Quickshell
|
|
import Quickshell.Io
|
|
|
|
QtObject {
|
|
id: root
|
|
// Tests inject an explicit helper command; production never reads mock values from the environment.
|
|
property var backendCommand: ["python3", Quickshell.shellPath("backend/power.py")]
|
|
property var capabilities: ({})
|
|
property bool busy: false
|
|
property bool timedOut: false
|
|
property int timeoutMs: 90000
|
|
property string operation: ""
|
|
property string error: ""
|
|
property string capabilityError: ""
|
|
signal succeeded(string action)
|
|
function available(action) { return ["yes", "challenge"].includes(capabilities[action]?.state); }
|
|
function start(action) {
|
|
if (busy || worker.running) return false;
|
|
if (!["capabilities", "lock", "logout", "suspend", "reboot", "poweroff"].includes(action)) { error = "Неизвестное действие"; return false; }
|
|
if (action !== "capabilities" && !available(action)) { error = "Действие недоступно"; return false; }
|
|
operation = action;
|
|
if (action !== "capabilities") error = "";
|
|
timedOut = false;
|
|
busy = true;
|
|
worker.command = backendCommand.concat([action]);
|
|
worker.running = true;
|
|
return true;
|
|
}
|
|
function refresh() { return start("capabilities"); }
|
|
function finish(code) {
|
|
busy = false;
|
|
if (timedOut) return;
|
|
try {
|
|
if (!output.text.trim()) throw new Error(errors.text.trim().slice(0, 2000) || "Не удалось запустить backend");
|
|
const reply = JSON.parse(output.text);
|
|
if (code !== 0 || reply.ok !== true) throw new Error(reply.error || "Backend завершился с ошибкой");
|
|
if (operation === "capabilities") {
|
|
if (!reply.capabilities || typeof reply.capabilities !== "object") throw new Error("Некорректные возможности backend");
|
|
capabilities = reply.capabilities;
|
|
capabilityError = "";
|
|
} else succeeded(operation);
|
|
} catch (e) {
|
|
if (operation === "capabilities") { capabilities = ({}); capabilityError = String(e); }
|
|
else error = String(e);
|
|
}
|
|
}
|
|
property Process worker: Process {
|
|
stdout: StdioCollector { id: output }
|
|
stderr: StdioCollector { id: errors }
|
|
onExited: (code, status) => root.finish(code)
|
|
}
|
|
property Timer watchdog: Timer {
|
|
interval: root.timeoutMs
|
|
running: root.busy
|
|
onTriggered: {
|
|
root.timedOut = true;
|
|
root.error = "Время ожидания истекло. Результат действия не подтверждён.";
|
|
root.worker.signal(9);
|
|
if (!root.worker.running) root.busy = false;
|
|
}
|
|
}
|
|
}
|