added adaptive quickshell

This commit is contained in:
wt committed 2026-11-17 18:15:16 +07:00
1 parent 6eb56d2065
commit 5b33a73fd8
189 files changed
+8678 -15

No files matched your search

@@ -0,0 +1,56 @@
pragma ComponentBehavior: Bound
import QtQuick
import Quickshell
import Quickshell.Io
QtObject {
id: root
property var backendCommand: ["python3", Quickshell.shellPath("backend/bluetooth.py")]
property bool busy: false
property bool timedOut: false
property int timeoutMs: 50000
property string operation: ""
property string error: ""
property string readiness: "unknown"
property int adapterCount: 0
signal succeeded(string action)
function start(action, path) {
if (busy || worker.running) return false;
if (!["status", "power-on", "power-off", "connect", "disconnect", "forget"].includes(action)) { error = "Неизвестное действие Bluetooth"; return false; }
if (action !== "status" && typeof path !== "string") { error = "Некорректный путь Bluetooth-устройства"; return false; }
operation = action; error = ""; timedOut = false; busy = true;
worker.command = backendCommand.concat(action === "status" ? [action] : [action, path]);
worker.running = true;
return true;
}
function refresh() { return start("status", ""); }
function finish(code) {
busy = false;
if (timedOut) return;
try {
if (!reply.text.trim()) throw new Error(errors.text.trim().slice(0, 2000) || "Не удалось запустить Bluetooth backend");
const result = JSON.parse(reply.text);
if (code !== 0 || result.ok !== true) throw new Error(result.error || "Ошибка Bluetooth");
if (operation === "status") {
if (!Number.isInteger(result.adapterCount) || result.adapterCount < 0) throw new Error("Некорректный ответ Bluetooth backend");
adapterCount = result.adapterCount; readiness = "ready";
} else succeeded(operation);
} catch(e) { error = String(e); if (operation === "status") readiness = "unavailable"; }
}
property Process worker: Process {
stdout: StdioCollector { id: reply }
stderr: StdioCollector { id: errors }
onExited: (code, status) => root.finish(code)
}
property Timer watchdog: Timer {
running: root.busy
interval: root.timeoutMs
onTriggered: {
root.timedOut = true;
root.error = "Время ожидания истекло. Результат действия Bluetooth не подтверждён.";
if (root.operation === "status") root.readiness = "unavailable";
root.worker.signal(9);
if (!root.worker.running) root.busy = false;
}
}
}
@@ -0,0 +1,70 @@
pragma ComponentBehavior: Bound
import QtQuick
import Quickshell
import Quickshell.Io
QtObject {
id: root
property var adapter: null
property bool active: false
property var backendCommand: ["python3", Quickshell.shellPath("backend/bluetooth.py")]
property bool owned: false
property bool starting: false
property bool stopping: false
readonly property bool busy: starting || worker.running
property int durationMs: 60000
property int startTimeoutMs: 6000
property string error: ""
property string backendError: ""
function start() {
if (busy) return false;
if (!active || !adapter?.enabled) { error = "Bluetooth выключен или адаптер недоступен"; return false; }
if (adapter.discovering) { error = "Поиск уже выполняется"; return false; }
error = ""; backendError = ""; stopping = false; starting = true;
worker.command = backendCommand.concat(["discover", adapter.dbusPath]);
worker.running = true;
startup.restart();
return true;
}
function stop() {
startup.stop(); deadline.stop();
if (!busy) return;
stopping = true; starting = false; owned = false;
worker.signal(15);
shutdown.restart();
}
onActiveChanged: if (!active) stop()
onAdapterChanged: stop()
Component.onDestruction: if (worker.running) worker.signal(9)
property Connections events: Connections {
target: root.adapter
function onEnabledChanged() { if (!root.adapter?.enabled) root.stop(); }
}
property Process worker: Process {
stdout: SplitParser {
onRead: data => {
try {
const result = JSON.parse(data);
if (result.ok !== true) { root.backendError = result.error || "Ошибка поиска Bluetooth"; return; }
if (result.event === "started" && !root.stopping) {
root.starting = false; root.owned = true; startup.stop(); deadline.restart();
}
} catch(e) { root.backendError = "Некорректный ответ поиска Bluetooth"; }
}
}
stderr: StdioCollector { id: errors }
onExited: (code, status) => {
startup.stop(); deadline.stop(); shutdown.stop();
root.starting = false; root.owned = false;
if (!root.stopping && (code !== 0 || root.backendError !== ""))
root.error = root.backendError || errors.text.trim().slice(0, 2000) || "Поиск Bluetooth завершился с ошибкой";
root.stopping = false;
}
}
property Timer startup: Timer {
interval: root.startTimeoutMs
onTriggered: if (root.starting) { root.error = "Не удалось подтвердить начало поиска"; root.stop(); }
}
property Timer deadline: Timer { interval: root.durationMs; onTriggered: root.stop() }
property Timer shutdown: Timer { interval: 2000; onTriggered: { root.worker.signal(9); root.starting = false; if (!root.worker.running) root.stopping = false; } }
}
@@ -0,0 +1,50 @@
pragma ComponentBehavior: Bound
import QtQuick
import Quickshell
import Quickshell.Io
QtObject {
id: root
property var devices: []
property bool busy: false
property string error: ""
property var command: ["python3", Quickshell.shellPath("backend/brightness.py")]
function refresh() {
if (busy) return false;
error = "";
busy = true;
worker.command = command.concat(["list"]);
worker.running = true;
return true;
}
function setBrightness(device, percent) {
if (busy || !/^[A-Za-z0-9_.:-]{1,128}$/.test(device) || !Number.isInteger(percent) || percent < 1 || percent > 100)
return false;
if (!devices.some(d => d.name === device)) return false;
error = "";
busy = true;
worker.command = command.concat(["set", device, String(percent)]);
worker.running = true;
return true;
}
property Process worker: Process {
stdout: StdioCollector { id: output }
stderr: StdioCollector { id: errors }
onExited: (code, status) => {
root.busy = false;
try {
const result = JSON.parse(output.text);
if (code !== 0 || !result.ok || !Array.isArray(result.devices))
throw new Error(result.error || errors.text || "Ошибка управления яркостью");
root.devices = result.devices;
} catch (e) { root.error = String(e); }
}
}
property Timer refreshTimer: Timer {
interval: 10000
repeat: true
running: true
triggeredOnStart: true
onTriggered: root.refresh()
}
}
+38
View File
@@ -0,0 +1,38 @@
pragma ComponentBehavior: Bound
import QtQuick
import Quickshell
import Quickshell.Io
QtObject {
id: root
property var monitors: []
property bool busy: false
property string error: ""
function refresh() {
if (busy) return;
busy = true;
worker.command = ["python3", Quickshell.shellPath("backend/displays.py"), "list"];
worker.running = true;
}
property Process worker: Process {
stdout: StdioCollector { id: output }
stderr: StdioCollector { id: errors }
onExited: (code, status) => {
root.busy = false;
try {
const result = JSON.parse(output.text);
if (code !== 0 || !result.ok || !Array.isArray(result.monitors))
throw new Error(result.error || errors.text || "Не удалось получить список дисплеев");
root.monitors = result.monitors;
root.error = "";
} catch (e) { root.error = String(e); }
}
}
property Timer refreshTimer: Timer {
interval: 5000
repeat: true
running: true
triggeredOnStart: true
onTriggered: root.refresh()
}
}
+62
View File
@@ -0,0 +1,62 @@
pragma ComponentBehavior: Bound
import QtQuick
import Quickshell
import Quickshell.Io
QtObject {
id: root
property bool busy: false
property string error: ""
property string token: ""
property int secondsRemaining: 0
property string operation: ""
function preview(name, mode, scale, transform, x, y) {
if (busy || token !== "") return;
busy = true;
error = "";
operation = "preview";
worker.command = ["python3", Quickshell.shellPath("backend/display_preview.py"), "preview", name, mode, String(scale), String(transform), String(x), String(y)];
worker.running = true;
}
function confirm() {
if (busy || token === "") return;
busy = true;
operation = "confirm";
worker.command = ["python3", Quickshell.shellPath("backend/display_preview.py"), "confirm", token];
worker.running = true;
}
property Process worker: Process {
stdout: StdioCollector { id: output }
stderr: StdioCollector { id: errors }
onExited: (code, status) => {
root.busy = false;
try {
const result = JSON.parse(output.text);
if (code !== 0 || !result.ok)
throw new Error(result.error || errors.text || "Не удалось изменить дисплей");
if (root.operation === "preview") {
root.token = result.token;
root.secondsRemaining = result.seconds;
countdown.start();
} else {
root.token = "";
root.secondsRemaining = 0;
countdown.stop();
}
root.error = "";
} catch (e) { root.error = String(e); }
}
}
property Timer countdown: Timer {
id: countdown
interval: 1000
repeat: true
onTriggered: {
root.secondsRemaining = Math.max(0, root.secondsRemaining - 1);
if (root.secondsRemaining === 0) {
stop();
root.token = "";
}
}
}
}
+30
View File
@@ -0,0 +1,30 @@
pragma Singleton
import QtQuick
import Quickshell
import Quickshell.Networking
import Quickshell.Bluetooth
import Quickshell.Services.Pipewire
import Quickshell.Services.UPower
import Quickshell.Services.Mpris
import "HardwarePolicy.js" as HardwarePolicy
Singleton {
readonly property bool networkReady: Networking.backend !== NetworkBackendType.None
readonly property string networkBackend: NetworkBackendType.toString(Networking.backend)
readonly property var networks: Networking.devices.values
readonly property var networkCapabilities: HardwarePolicy.networkCapabilities(networks, DeviceType.Wifi, DeviceType.Wired)
readonly property bool wifiPresent: networkCapabilities.wifi
readonly property var wiredDevices: networkCapabilities.wired
readonly property bool wiredPresent: wiredDevices.length > 0
readonly property string ethernetSummary: HardwarePolicy.ethernetSummary(wiredDevices)
readonly property var bluetoothAdapters: Bluetooth.adapters.values
readonly property var outputs: Pipewire.nodes.values.filter(n => !n.isStream && n.isSink && n.audio !== null)
readonly property var inputs: Pipewire.nodes.values.filter(n => !n.isStream && !n.isSink && n.audio !== null)
readonly property var sink: Pipewire.defaultAudioSink
readonly property var source: Pipewire.defaultAudioSource
readonly property bool audioReady: Pipewire.ready
readonly property var batteries: UPower.devices.values.filter(d => d.isPresent && d.isLaptopBattery)
readonly property var players: Mpris.players.values
readonly property string wifiState: !networkReady ? "unsupported" : !wifiPresent ? "unavailable" : !Networking.wifiHardwareEnabled ? "blocked" : Networking.wifiEnabled ? "available" : "disabled"
PwObjectTracker { objects: Hardware.outputs.concat(Hardware.inputs) }
}
+46
View File
@@ -0,0 +1,46 @@
.pragma library
// Pure capability-to-UI policy. Device existence and device state are different:
// disconnected Ethernet and disabled Wi-Fi must remain discoverable.
function networkCapabilities(devices, wifiType, wiredType) {
const list = devices || [];
return {
wifi: list.some(d => d && d.type === wifiType),
wired: list.filter(d => d && d.type === wiredType),
hasNetworkDevices: list.length > 0
};
}
function ethernetSummary(devices) {
const list = devices || [];
if (list.length === 0) return "";
const connected = list.filter(d => d && d.connected).length;
if (list.length === 1) return connected ? "Ethernet · подключено" : "Ethernet · нет подключения";
return "Ethernet · " + connected + "/" + list.length;
}
function visibleSettingsSections(hasAudio, hasNetwork, hasBluetooth, hasModem, hasBattery) {
const sections = [{id: "appearance", title: "Оболочка"}];
if (hasAudio) sections.push({id: "audio", title: "Звук"});
if (hasNetwork) sections.push({id: "network", title: "Сеть и подключения"});
sections.push({id: "wallpaper", title: "Обои"});
if (hasBluetooth) sections.push({id: "bluetooth", title: "Bluetooth"});
if (hasModem) sections.push({id: "modem", title: "Мобильная сеть и SIM"});
if (hasBattery) sections.push({id: "battery", title: "Батарея и питание"});
sections.push({id: "display", title: "Дисплей и яркость"});
sections.push({id: "system", title: "О системе"});
return sections;
}
// Map stable section identifiers to the fixed StackLayout pages.
function pageIndex(id) {
const pages = {appearance: 0, audio: 1, network: 2, wallpaper: 3, bluetooth: 4, modem: 5, system: 6, battery: 7, display: 8};
return Object.prototype.hasOwnProperty.call(pages, id) ? pages[id] : 0;
}
function sectionIndex(sections, id) {
const list = sections || [];
for (let i = 0; i < list.length; ++i)
if (list[i].id === id) return i;
return -1;
}
+45
View File
@@ -0,0 +1,45 @@
pragma Singleton
import QtQuick
import Quickshell
import Quickshell.Io
Singleton {
id: root
property var profiles: []
property string error: ""
property bool busy: false
property string action: ""
property string target: ""
property string apn: ""
function refresh() { if (!busy && !probe.running) probe.running = true }
function perform(operation, value, accessPoint) {
if (busy || !["create", "activate", "deactivate", "delete"].includes(operation)) return;
action = operation; target = value; apn = accessPoint || "";
error = ""; busy = true; actionProcess.running = true;
}
Process {
id: probe
command: ["python3", Qt.resolvedUrl("../backend/mobile_connections.py").toString().replace(/^file:\/\//, ""), "list"]
stdout: StdioCollector {
onStreamFinished: {
try {
const result = JSON.parse(text);
root.profiles = result.profiles || [];
root.error = result.error || "";
} catch (e) { root.error = String(e) }
}
}
}
Process {
id: actionProcess
command: ["python3", Qt.resolvedUrl("../backend/mobile_connections.py").toString().replace(/^file:\/\//, ""), root.action, root.target].concat(root.action === "create" ? [root.apn] : [])
stdout: StdioCollector {
onStreamFinished: {
try { const result = JSON.parse(text); root.error = result.error || "" }
catch (e) { root.error = String(e) }
}
}
onExited: { root.busy = false; root.refresh() }
}
Timer { interval: 20000; repeat: true; running: true; triggeredOnStart: true; onTriggered: root.refresh() }
}
+59
View File
@@ -0,0 +1,59 @@
pragma Singleton
import QtQuick
import Quickshell
import Quickshell.Io
Singleton {
id: root
property string backend: "unknown"
property var devices: []
property string error: ""
readonly property bool present: devices.length > 0
property bool busy: false
property bool actionBusy: false
property string actionError: ""
property string pendingId: ""
property string pendingAction: ""
function setEnabled(modemId, enabled) {
if (actionBusy || !/^[0-9]{1,5}$/.test(String(modemId))) return;
pendingId = String(modemId);
pendingAction = enabled ? "enable" : "disable";
actionError = "";
actionBusy = true;
actionProcess.running = true;
}
Process {
id: actionProcess
command: ["python3", Qt.resolvedUrl("../backend/modem_control.py").toString().replace(/^file:\/\//, ""), root.pendingId, root.pendingAction]
stdout: StdioCollector {
onStreamFinished: {
try {
const response = JSON.parse(text);
root.actionError = response.ok ? "" : response.error;
} catch (e) { root.actionError = String(e); }
}
}
onExited: { root.actionBusy = false; root.refresh(); }
}
function refresh() {
if (!busy) { busy = true; probe.running = true; }
}
Process {
id: probe
command: ["python3", Qt.resolvedUrl("../backend/modems.py").toString().replace(/^file:\/\//, "")]
stdout: StdioCollector {
onStreamFinished: {
try {
const result = JSON.parse(text);
root.backend = result.backend;
root.devices = result.modems || [];
root.error = result.error || "";
} catch (e) { root.backend = "error"; root.error = String(e); }
}
}
onExited: root.busy = false
}
// ModemManager can appear after boot or USB hotplug. A modest interval
// avoids a permanent high-frequency poll on battery-powered devices.
Timer { interval: 15000; repeat: true; running: true; triggeredOnStart: true; onTriggered: root.refresh() }
}
+65
View File
@@ -0,0 +1,65 @@
pragma ComponentBehavior: Bound
import QtQuick
import Quickshell.Networking
QtObject {
id: root
property var device: null
property var pendingNetwork: null
property string operation: ""
property bool busy: false
property string error: ""
property int timeoutMs: 45000
signal needsSecret(var network)
signal succeeded(string action)
function fail(message) { busy = false; pendingNetwork = null; error = message; }
function checkResult() {
if (!busy) return;
if (!device || device.nmManaged !== true) { fail("Интерфейс недоступен для управления"); return; }
if ((operation === "connect" && pendingNetwork?.connected) || (operation === "disconnect" && !device.connected)) {
const action = operation;
busy = false; pendingNetwork = null; succeeded(action);
}
}
function requestConnect(network, psk) {
if (busy) return false;
if (!device || !device.nmManaged || !network || network.device !== device) { error = "Подключение недоступно"; return false; }
error = ""; operation = "connect"; pendingNetwork = network; busy = true;
try {
if (psk !== undefined && psk !== "") network.connectWithPsk(psk);
else network.connect();
checkResult();
return true;
} catch (e) { fail(String(e)); return false; }
}
function requestDisconnect() {
if (busy) return false;
if (!device || !device.nmManaged || !device.connected) { error = "Интерфейс уже отключён или недоступен"; return false; }
error = ""; operation = "disconnect"; pendingNetwork = null; busy = true;
try { device.disconnect(); checkResult(); return true; }
catch (e) { fail(String(e)); return false; }
}
onDeviceChanged: if (busy) fail("Интерфейс был отключён")
onPendingNetworkChanged: if (busy && operation === "connect" && !pendingNetwork) fail("Сеть больше недоступна")
property Connections deviceEvents: Connections {
target: root.device
function onConnectedChanged() { root.checkResult(); }
function onStateChanged() { root.checkResult(); }
function onNmManagedChanged() { root.checkResult(); }
}
property Connections networkEvents: Connections {
target: root.pendingNetwork
function onConnectedChanged() { root.checkResult(); }
function onStateChanged() { root.checkResult(); }
function onConnectionFailed(reason) {
const network = root.pendingNetwork;
root.fail("Не удалось подключиться: " + ConnectionFailReason.toString(reason));
if (reason === ConnectionFailReason.NoSecrets) root.needsSecret(network);
}
}
property Timer watchdog: Timer {
interval: root.timeoutMs
running: root.busy
onTriggered: root.fail("Время ожидания истекло. Результат подключения не подтверждён.")
}
}
+48
View File
@@ -0,0 +1,48 @@
pragma ComponentBehavior: Bound
import QtQuick
import "NotificationPolicy.js" as Policy
QtObject {
id: entry
required property var notification
property bool closed: false
property bool firstUpdate: true
// Coalesce replacement property signals: backend updates several fields in one turn.
property Timer changed: Timer {
interval: 0
onTriggered: if (!entry.closed) {
const resumed = entry.firstUpdate && entry.notification.lastGeneration;
entry.expiry.stop();
const duration = Policy.timeoutMs(entry.notification.expireTimeout, entry.notification.urgency);
const deadlines = Object.assign({}, Notifications.deadlines);
const id = entry.notification.id;
const restored = resumed ? Notifications.restoredDeadline(entry.notification) : undefined;
const deadline = restored !== undefined ? restored : duration > 0 ? Date.now() + duration : 0;
Notifications.setDeadline(id, deadline);
Notifications.received(entry.notification, resumed);
entry.firstUpdate = false;
if (deadline > 0) { entry.expiry.interval = Math.max(1, deadline - Date.now()); entry.expiry.start(); }
}
}
property Timer expiry: Timer { onTriggered: if (!entry.closed) entry.notification.expire() }
property Connections events: Connections {
target: entry.notification
function onSummaryChanged() { entry.changed.restart(); }
function onBodyChanged() { entry.changed.restart(); }
function onAppNameChanged() { entry.changed.restart(); }
function onExpireTimeoutChanged() { entry.changed.restart(); }
function onUrgencyChanged() { entry.changed.restart(); }
function onActionsChanged() { entry.changed.restart(); }
function onHintsChanged() { entry.changed.restart(); }
function onTransientChanged() { entry.changed.restart(); }
function onImageChanged() { entry.changed.restart(); }
function onClosed(reason) {
entry.closed = true;
entry.changed.stop();
entry.expiry.stop();
Notifications.recordClose(entry.notification.id, reason);
}
}
Component.onCompleted: changed.start()
}
+38
View File
@@ -0,0 +1,38 @@
.pragma library
function timeoutMs(milliseconds, urgency) {
// Critical notifications require an explicit dismissal.
if (urgency === 2 || milliseconds === 0) return 0;
if (milliseconds < 0) return urgency === 0 ? 3000 : 6000;
return Math.max(1, Math.min(2147483647, Math.round(milliseconds)));
}
function upsert(history, entry) {
return [entry].concat(history.filter(old => old.key !== entry.key)).slice(0, 100);
}
function validate(document) {
if (!document || document.version !== 1 || !Array.isArray(document.entries) || document.entries.length > 100)
throw new Error("Invalid notification history schema");
const keys = [];
document.entries.forEach(entry => {
if (!entry || typeof entry.key !== "string" || !entry.key || entry.key.length > 128 || keys.includes(entry.key))
throw new Error("Invalid history key");
keys.push(entry.key);
for (const field of ["appName", "summary", "body", "state"]) {
if (typeof entry[field] !== "string" || entry[field].length > 8192)
throw new Error("Invalid history field: " + field);
}
if (entry.desktopEntry !== undefined && (typeof entry.desktopEntry !== "string" || entry.desktopEntry.length > 512))
throw new Error("Invalid desktop entry id");
if (entry.session !== undefined && (typeof entry.session !== "string" || !/^[0-9]+$/.test(entry.session)))
throw new Error("Invalid notification session");
if (entry.notificationId !== undefined && (!Number.isInteger(entry.notificationId) || entry.notificationId < 1))
throw new Error("Invalid backend id");
if (entry.deadline !== undefined && (!Number.isFinite(entry.deadline) || entry.deadline < 0))
throw new Error("Invalid deadline");
if (!Number.isFinite(entry.time) || ![0, 1, 2].includes(entry.urgency))
throw new Error("Invalid history metadata");
});
return document.entries;
}
+150
View File
@@ -0,0 +1,150 @@
pragma Singleton
import QtQuick
import QtQml.Models
import Quickshell
import Quickshell.Io
import Quickshell.Services.Notifications
import "NotificationPolicy.js" as Policy
Singleton {
id: root
readonly property bool dnd: Preferences.data.notificationDnd === true || Preferences.error !== ""
readonly property bool saveHistory: Preferences.data.notificationHistory !== false
readonly property bool enabled: Quickshell.env("ADAPTIVE_NOTIFICATIONS") !== "0"
readonly property var items: serverLoader.item ? serverLoader.item.trackedNotifications.values : []
readonly property bool ready: enabled && historyReady && serverLoader.item !== null
property var history: []
property var keys: ({})
property var deadlines: ({})
property int sequence: 0
property bool historyReady: false
property bool historyWritable: false
property string error: ""
readonly property string historyDirectory: Quickshell.statePath("notification-history")
readonly property string historyPath: historyDirectory + "/notifications.json"
property bool storagePrepared: false
signal present(var notification)
signal removed(int id)
function setDnd(value) { Preferences.setValue("notificationDnd", value); }
function setSaveHistory(value) {
Preferences.setValue("notificationHistory", value);
if (!value && Preferences.data.notificationHistory === false) clearHistory();
}
function persist() {
if (historyReady && historyWritable) historyFile.setText(JSON.stringify({version: 1, entries: history}));
}
function previous(n) {
return history.find(e => e.session === String(Quickshell.processId) && e.notificationId === n.id);
}
function restoredDeadline(n) { return previous(n)?.deadline; }
function received(n, resumed) {
if (!keys[n.id]) {
const next = Object.assign({}, keys);
const old = resumed ? previous(n) : null;
next[n.id] = old ? old.key : Date.now().toString(36) + "-" + (++sequence);
keys = next;
}
if (!n.transient && saveHistory && historyReady) {
const old = resumed ? history.find(e => e.key === keys[n.id]) : null;
history = Policy.upsert(history, {key: keys[n.id], appName: n.appName.slice(0, 512),
desktopEntry: n.desktopEntry.slice(0, 512), summary: n.summary.slice(0, 2048), body: n.body.slice(0, 8192), urgency: n.urgency,
time: old ? old.time : Date.now(), state: "received", session: String(Quickshell.processId), notificationId: n.id, deadline: deadlines[n.id] || 0});
persist();
} else if (n.transient && history.some(e => e.key === keys[n.id])) {
history = history.filter(e => e.key !== keys[n.id]);
persist();
}
if (!dnd && !resumed) present(n);
}
function recordClose(id, reason) {
const key = keys[id];
history = history.map(e => e.key === key ? Object.assign({}, e, {state: String(reason)}) : e);
persist();
const next = Object.assign({}, keys);
delete next[id];
keys = next;
const timers = Object.assign({}, deadlines);
delete timers[id];
deadlines = timers;
removed(id);
}
function setDeadline(id, deadline) {
const next = Object.assign({}, deadlines);
next[id] = deadline;
deadlines = next;
}
function dismiss(id) { const n = items.find(n => n.id === id); if (n) n.dismiss(); }
function invoke(id, action) {
const n = items.find(n => n.id === id);
const a = n?.actions.find(a => a.identifier === action);
if (a) a.invoke();
}
function clear() { items.slice().forEach(n => n.dismiss()); clearHistory(); }
function clearHistory() { history = []; persist(); }
function removeHistory(key) { history = history.filter(e => e.key !== key); persist(); }
readonly property var archived: history.filter(e => !Object.values(keys).includes(e.key))
readonly property var groups: {
const result = [];
const add = (entry, notification) => {
const key = entry.desktopEntry || entry.appName || "Приложение";
let group = result.find(g => g.key === key);
if (!group) { group = {key: key, name: entry.appName || key, entries: []}; result.push(group); }
group.entries.push(notification ? {notification: entry} : {record: entry});
};
items.slice().reverse().filter(n => !n.transient).forEach(n => add(n, true));
archived.forEach(e => add(e, false));
return result;
}
// The history file is bounded. Images and client actions are intentionally not serialized.
Process {
command: ["install", "-d", "-m", "700", root.historyDirectory]
running: root.enabled
onExited: (code, status) => {
if (code === 0) root.storagePrepared = true;
else {
root.error = "Не удалось подготовить приватное хранилище истории";
root.historyReady = true;
}
}
}
FileView {
id: historyFile
path: root.enabled && root.storagePrepared ? root.historyPath : ""
atomicWrites: true
printErrors: false
onLoaded: {
if (!root.storagePrepared) return;
try {
root.history = Policy.validate(JSON.parse(text()));
root.historyWritable = true;
} catch (e) { root.error = "История не загружена: " + String(e) + ". Файл сохранён: " + root.historyPath; }
root.historyReady = true;
}
onLoadFailed: error => {
if (!root.storagePrepared) return;
root.historyReady = true;
root.historyWritable = error === FileViewError.FileNotFound;
if (!root.historyWritable) root.error = "Не удалось прочитать историю: " + root.historyPath;
}
onSaveFailed: root.error = "Не удалось сохранить историю: " + root.historyPath
}
Instantiator {
model: root.items
delegate: NotificationEntry { required property var modelData; notification: modelData }
}
LazyLoader {
id: serverLoader
active: root.enabled === true && root.historyReady === true && Preferences.initialized === true
component: NotificationServer {
bodySupported: true
actionsSupported: true
imageSupported: true
keepOnReload: true
onNotification: n => {
n.tracked = true;
if (trackedNotifications.values.length >= 100)
trackedNotifications.values[0].expire();
}
}
}
}
+86
View File
@@ -0,0 +1,86 @@
.pragma library
.import "WallpaperPolicy.js" as WallpaperPolicy
function modeFor(preferred, width, touch) {
if (["phone", "tablet", "desktop"].indexOf(preferred) >= 0)
return preferred;
// Width is logical pixels; a narrow desktop output stays a desktop.
if (!touch) return "desktop";
return width < 600 ? "phone" : width < 1000 ? "tablet" : "desktop";
}
function validate(value) {
if (!value || value.version !== 1) throw new Error("Unsupported preferences schema");
if (["auto", "phone", "tablet", "desktop"].indexOf(value.mode) < 0)
throw new Error("Invalid layout mode");
if (["dark", "light", "amoled"].indexOf(value.theme) < 0)
throw new Error("Invalid theme");
if (typeof value.reducedMotion !== "boolean" || typeof value.touch !== "boolean")
throw new Error("Invalid input or motion preferences");
if (!value.outputs || Array.isArray(value.outputs) || typeof value.outputs !== "object")
throw new Error("Invalid output preferences");
Object.keys(value.outputs).forEach(function(name) {
if (["auto", "phone", "tablet", "desktop"].indexOf(value.outputs[name]) < 0)
throw new Error("Invalid output mode");
});
["notificationDnd", "notificationHistory"].forEach(function(key) {
if (value[key] !== undefined && typeof value[key] !== "boolean")
throw new Error("Invalid notification preference: " + key);
});
["favorites", "appHistory"].forEach(function(key) {
if (value[key] === undefined) return; // Existing v1 files remain compatible.
const list = value[key];
if (!Array.isArray(list) || list.length > 50 || list.some(id => typeof id !== "string" || id.length === 0 || id.length > 512))
throw new Error("Invalid application list: " + key);
if (list.some((id, index) => list.indexOf(id) !== index))
throw new Error("Duplicate application id: " + key);
});
if (value.wallpapers !== undefined) WallpaperPolicy.validate(value.wallpapers);
return value;
}
function recordLaunch(history, id) {
return [id].concat((history || []).filter(entry => entry !== id)).slice(0, 50);
}
function toggleFavorite(favorites, id) {
const list = favorites || [];
return list.indexOf(id) >= 0 ? list.filter(entry => entry !== id) : list.concat([id]).slice(0, 50);
}
function rankApps(apps, favorites, history) {
favorites = favorites || [];
history = history || [];
return apps.slice().sort(function(a, b) {
const af = favorites.indexOf(a.id), bf = favorites.indexOf(b.id);
if (af >= 0 || bf >= 0) {
if (af < 0) return 1;
if (bf < 0) return -1;
return af - bf;
}
const ah = history.indexOf(a.id), bh = history.indexOf(b.id);
if (ah >= 0 || bh >= 0) {
if (ah < 0) return 1;
if (bh < 0) return -1;
return ah - bh;
}
return a.name.localeCompare(b.name);
});
}
// Stable ordering for home-screen tiles; persist IDs rather than model indices.
function moveFavorite(favorites, id, direction) {
const list = (favorites || []).slice();
const from = list.indexOf(id);
const to = from + direction;
if (!Number.isInteger(direction) || Math.abs(direction) !== 1 || from < 0 || to < 0 || to >= list.length)
return list;
const tmp = list[to]; list[to] = list[from]; list[from] = tmp;
return list;
}
function homePages(favorites, pageSize) {
if (!Number.isInteger(pageSize) || pageSize < 1) throw new Error("Invalid page size");
const ids = favorites || [], pages = [];
for (let i = 0; i < ids.length; i += pageSize) pages.push(ids.slice(i, i + pageSize));
return pages.length ? pages : [[]];
}
+64
View File
@@ -0,0 +1,64 @@
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;
}
}
}
+45
View File
@@ -0,0 +1,45 @@
pragma Singleton
import QtQuick
import Quickshell
import Quickshell.Io
Singleton {
id: root
property string profile: ""
property string error: ""
property bool busy: false
property string requested: ""
readonly property var profiles: ["power-saver", "balanced", "performance"]
function request(profileName) {
if (busy || !profiles.includes(profileName)) return false;
requested = profileName;
busy = true;
error = "";
worker.command = ["python3", Quickshell.shellPath("backend/power_profiles.py"), "set", profileName];
worker.running = true;
return true;
}
function refresh() {
if (busy) return;
requested = "";
busy = true;
worker.command = ["python3", Quickshell.shellPath("backend/power_profiles.py"), "get"];
worker.running = true;
}
Process {
id: worker
stdout: StdioCollector { id: output }
stderr: StdioCollector { id: errors }
onExited: (code, status) => {
root.busy = false;
try {
const data = JSON.parse(output.text);
if (code !== 0 || !data.ok || !root.profiles.includes(data.profile))
throw new Error(data.error || errors.text || "Не удалось изменить профиль");
root.profile = data.profile;
root.error = "";
} catch (e) { root.error = String(e); }
}
}
Timer { interval: 30000; repeat: true; running: true; triggeredOnStart: true; onTriggered: root.refresh() }
}
+60
View File
@@ -0,0 +1,60 @@
pragma Singleton
import QtQuick
import Quickshell
import Quickshell.Io
import "Policy.js" as Policy
Singleton {
id: root
property var data: ({version: 1, mode: "auto", theme: "dark", reducedMotion: false, touch: false, outputs: {}})
property string error: ""
property bool writable: false
property bool initialized: false
readonly property string path: Quickshell.statePath("preferences.json")
function modeFor(screen) {
return Policy.modeFor(data.outputs[screen.name] || data.mode, screen.width, data.touch);
}
function setValue(key, value) {
if (!writable) return;
try {
const next = Object.assign({}, data);
next[key] = value;
Policy.validate(next);
data = next;
file.setText(JSON.stringify(next, null, 2));
} catch (e) { error = String(e); }
}
function recordLaunch(id) { setValue("appHistory", Policy.recordLaunch(data.appHistory, id)); }
function toggleFavorite(id) { setValue("favorites", Policy.toggleFavorite(data.favorites, id)); }
function moveFavorite(id, direction) { setValue("favorites", Policy.moveFavorite(data.favorites, id, direction)); }
function setOutput(name, mode) {
const outputs = Object.assign({}, data.outputs);
outputs[name] = mode;
setValue("outputs", outputs);
}
FileView {
id: file
path: root.path
watchChanges: true
atomicWrites: true
printErrors: false
onFileChanged: reload()
onLoaded: {
try {
root.data = Policy.validate(JSON.parse(text()));
root.writable = true;
root.error = "";
} catch (e) {
root.writable = false;
root.error = "Настройки не загружены: " + String(e) + ". Исходный файл сохранён: " + root.path;
}
root.initialized = true;
}
onLoadFailed: error => {
if (error === FileViewError.FileNotFound) root.writable = true;
else root.error = "Не удалось прочитать " + root.path;
root.initialized = true;
}
onSaveFailed: root.error = "Не удалось сохранить " + root.path
}
}
+28
View File
@@ -0,0 +1,28 @@
pragma Singleton
import QtQuick
import Quickshell
import Quickshell.Io
Singleton {
id: root
property var details: ({})
property string error: ""
property bool busy: false
function refresh() {
if (busy) return;
busy = true;
probe.running = true;
}
Process {
id: probe
command: ["python3", Qt.resolvedUrl("../backend/system_info.py").toString().replace(/^file:\/\//, "")]
stdout: StdioCollector {
onStreamFinished: {
try { root.details = JSON.parse(text); root.error = ""; }
catch (e) { root.error = "Не удалось получить сведения о системе: " + String(e); }
}
}
onExited: root.busy = false
}
Timer { interval: 60000; repeat: true; running: true; triggeredOnStart: true; onTriggered: root.refresh() }
}
+26
View File
@@ -0,0 +1,26 @@
pragma Singleton
import QtQuick
import Quickshell
Singleton {
// Material 3 Expressive tonal surfaces, shared across all form factors.
readonly property bool dark: Preferences.data.theme !== "light"
readonly property bool oled: Preferences.data.theme === "amoled"
readonly property color background: oled ? "#000000" : dark ? "#141218" : "#fdf7ff"
readonly property color surface: oled ? "#101014" : dark ? "#211f26" : "#f3edf7"
readonly property color surfaceHigh: oled ? "#202026" : dark ? "#36343b" : "#e7e0ec"
readonly property color surfaceLow: oled ? "#09090c" : dark ? "#1d1b20" : "#f7f2fa"
readonly property color foreground: dark ? "#e6e0e9" : "#1d1b20"
readonly property color primary: dark ? "#d0bcff" : "#6750a4"
readonly property color onPrimary: dark ? "#381e72" : "#ffffff"
readonly property color primaryContainer: dark ? "#4f378b" : "#eaddff"
readonly property color onPrimaryContainer: dark ? "#eaddff" : "#21005d"
readonly property color secondaryContainer: dark ? "#4a4458" : "#e8def8"
readonly property color outline: dark ? "#938f99" : "#79747e"
readonly property int touchSize: 48
readonly property int radius: 24
readonly property int radiusLarge: 32
readonly property int duration: Preferences.data.reducedMotion ? 0 : 240
function isCompact(mode) { return mode === "phone"; }
function cardRadius(mode) { return mode === "desktop" ? 28 : 32; }
}
+32
View File
@@ -0,0 +1,32 @@
.pragma library
function localUrl(value) {
if (typeof value !== "string" || value.length > 16384 || value.includes("\u0000"))
throw new Error("Invalid wallpaper path");
if (value === "") return "";
let path = value;
if (value.startsWith("file://")) {
try { path = decodeURIComponent(value.slice(7)); }
catch (e) { throw new Error("Invalid file URL"); }
}
if (!path.startsWith("/") || path.startsWith("//") || path.includes("\u0000"))
throw new Error("Choose an absolute local file path");
return "file://" + path.split("/").map(segment => encodeURIComponent(segment)).join("/");
}
function validate(wallpapers) {
if (!wallpapers || Array.isArray(wallpapers) || typeof wallpapers !== "object")
throw new Error("Invalid wallpaper preferences");
const outputs = Object.keys(wallpapers);
if (outputs.length > 64) throw new Error("Too many wallpaper overrides");
outputs.forEach(name => {
if (!name || name.length > 256) throw new Error("Invalid output name");
localUrl(wallpapers[name]);
});
return wallpapers;
}
function sourceFor(wallpapers, output) {
wallpapers = wallpapers || {};
return localUrl(Object.prototype.hasOwnProperty.call(wallpapers, output) ? wallpapers[output] : wallpapers["*"] || "");
}
+44
View File
@@ -0,0 +1,44 @@
pragma Singleton
import QtQuick
import Quickshell
import "WallpaperPolicy.js" as Policy
Singleton {
id: root
property var states: ({})
property string error: ""
Connections {
target: Quickshell
function onScreensChanged() {
const names = Quickshell.screens.map(s => s.name);
Object.keys(root.states).filter(name => !names.includes(name)).forEach(name => root.forget(name));
}
}
function sourceFor(output) { return Policy.sourceFor(Preferences.data.wallpapers, output); }
function set(output, path) {
if (!Preferences.writable) { error = Preferences.error || "Настройки пока недоступны"; return false; }
try {
const next = Object.assign({}, Preferences.data.wallpapers || {});
next[output] = Policy.localUrl(path);
Policy.validate(next);
Preferences.setValue("wallpapers", next);
error = "";
return true;
} catch (e) { error = String(e); return false; }
}
function inherit(output) {
const next = Object.assign({}, Preferences.data.wallpapers || {});
delete next[output];
Preferences.setValue("wallpapers", next);
}
function report(output, source, state, displayed) {
const next = Object.assign({}, states);
next[output] = {source: source, state: state, displayed: displayed};
states = next;
}
function forget(output) {
const next = Object.assign({}, states);
delete next[output];
states = next;
}
}
+15
View File
@@ -0,0 +1,15 @@
.pragma library
// Pure window ordering helpers; no compositor operations in this module.
function ordered(windows) {
return (windows || []).filter(w => w && typeof w.activate === "function");
}
function cycle(windows, currentIndex, direction) {
const list = ordered(windows);
if (!list.length) return null;
if (direction !== 1 && direction !== -1) return null;
const index = Number.isInteger(currentIndex) && currentIndex >= 0 && currentIndex < list.length ? currentIndex : (direction === 1 ? -1 : 0);
return list[(index + direction + list.length) % list.length];
}
function shouldDismissSwipe(dx, dy, width) {
return dy < -Math.max(64, Math.min(130, width * 0.2)) && Math.abs(dy) > Math.abs(dx) * 1.2;
}
+24
View File
@@ -0,0 +1,24 @@
singleton Preferences 1.0 Preferences.qml
singleton Hardware 1.0 Hardware.qml
singleton Theme 1.0 Theme.qml
singleton Notifications 1.0 Notifications.qml
NotificationEntry 1.0 NotificationEntry.qml
singleton Wallpapers 1.0 Wallpapers.qml
PowerController 1.0 PowerController.qml
NetworkController 1.0 NetworkController.qml
BluetoothController 1.0 BluetoothController.qml
BluetoothDiscovery 1.0 BluetoothDiscovery.qml
singleton Modems 1.0 Modems.qml
singleton MobileConnections 1.0 MobileConnections.qml
singleton SystemInfo 1.0 SystemInfo.qml
BrightnessController 1.0 BrightnessController.qml
DisplayController 1.0 DisplayController.qml
DisplayPreview 1.0 DisplayPreview.qml