added adaptive quickshell
This commit is contained in:
1 parent
6eb56d2065
commit
5b33a73fd8
189 files changed
+8678
-15
No files matched your search
@@ -0,0 +1,2 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
@@ -0,0 +1,69 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import QtQuick.Controls.Material
|
||||
import QtQuick.Controls
|
||||
import QtQuick.Layouts
|
||||
import Quickshell
|
||||
import "services"
|
||||
import "components"
|
||||
|
||||
ScrollView {
|
||||
id: settings
|
||||
signal navigate(string name)
|
||||
Material.theme: Theme.dark ? Material.Dark : Material.Light
|
||||
Material.accent: Theme.primary
|
||||
clip: true
|
||||
contentWidth: availableWidth
|
||||
ColumnLayout {
|
||||
width: settings.availableWidth
|
||||
spacing: 16
|
||||
Label { text: "Оболочка и внешний вид"; font.pixelSize: 22; color: Theme.primary }
|
||||
Label { text: Preferences.error; visible: text !== ""; wrapMode: Text.Wrap; Layout.fillWidth: true; color: Theme.foreground }
|
||||
Label { text: "Общий режим"; color: Theme.foreground }
|
||||
ComboBox {
|
||||
model: ["auto", "desktop", "tablet", "phone"]
|
||||
currentIndex: model.indexOf(Preferences.data.mode)
|
||||
enabled: Preferences.writable
|
||||
onActivated: Preferences.setValue("mode", currentText)
|
||||
}
|
||||
Switch {
|
||||
text: "Сенсорный ввод"
|
||||
checked: Preferences.data.touch
|
||||
enabled: Preferences.writable
|
||||
onClicked: Preferences.setValue("touch", checked)
|
||||
}
|
||||
Label { text: "Сенсорный ввод пока задаётся вручную; разрешение экрана не определяет тип устройства."; color: Theme.outline; wrapMode: Text.Wrap; Layout.fillWidth: true }
|
||||
Repeater {
|
||||
model: Quickshell.screens
|
||||
RowLayout {
|
||||
required property var modelData
|
||||
Label { text: modelData.name; color: Theme.foreground }
|
||||
ComboBox {
|
||||
model: ["auto", "desktop", "tablet", "phone"]
|
||||
currentIndex: model.indexOf(Preferences.data.outputs[modelData.name] || "auto")
|
||||
enabled: Preferences.writable
|
||||
onActivated: Preferences.setOutput(modelData.name, currentText)
|
||||
}
|
||||
}
|
||||
}
|
||||
Label { text: "Цветовая схема"; color: Theme.foreground }
|
||||
ComboBox {
|
||||
model: ["dark", "light", "amoled"]
|
||||
currentIndex: model.indexOf(Preferences.data.theme)
|
||||
enabled: Preferences.writable
|
||||
onActivated: Preferences.setValue("theme", currentText)
|
||||
}
|
||||
Switch { text: "Уменьшить движение"; checked: Preferences.data.reducedMotion; enabled: Preferences.writable; onClicked: Preferences.setValue("reducedMotion", checked) }
|
||||
Label { text: "Безопасность"; font.pixelSize: 22; color: Theme.primary }
|
||||
Label { text: "Блокировка: Hyprlock. Управление бездействием: Hypridle."; color: Theme.foreground; wrapMode: Text.Wrap; Layout.fillWidth: true }
|
||||
ActionButton { text: "Блокировка и питание…"; onClicked: settings.navigate("power") }
|
||||
Label { text: "Hardware Capabilities"; font.pixelSize: 22; color: Theme.primary }
|
||||
Label {
|
||||
Layout.fillWidth: true
|
||||
text: "Wi-Fi: " + Hardware.wifiState + "\nСетевые интерфейсы: " + Hardware.networks.length + "\nBluetooth-контроллеры: " + Hardware.bluetoothAdapters.length + "\nPipeWire: " + (Hardware.audioReady ? "available" : "unavailable") + "\nАудиовыход: " + (Hardware.sink ? "available" : "unavailable") + "\nМикрофон: " + (Hardware.source ? "available" : "unavailable") + "\nАккумуляторы: " + Hardware.batteries.length
|
||||
color: Theme.foreground
|
||||
wrapMode: Text.Wrap
|
||||
}
|
||||
Label { Layout.fillWidth: true; text: "Другие возможности оборудования ещё не проверяются. Отсутствие backend не означает отсутствие устройства."; color: Theme.outline; wrapMode: Text.Wrap }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import QtQuick.Controls.Material
|
||||
import QtQuick.Controls
|
||||
import QtQuick.Layouts
|
||||
import Quickshell.Services.Pipewire
|
||||
import "services"
|
||||
import "components"
|
||||
|
||||
ScrollView {
|
||||
id: page
|
||||
Material.theme: Theme.dark ? Material.Dark : Material.Light
|
||||
Material.accent: Theme.primary
|
||||
clip: true
|
||||
contentWidth: availableWidth
|
||||
ColumnLayout {
|
||||
width: page.availableWidth
|
||||
spacing: 16
|
||||
Label { text: "Звук"; font.pixelSize: 24; color: Theme.primary }
|
||||
Label {
|
||||
visible: !Hardware.audioReady
|
||||
text: "Аудиосервис недоступен. Проверьте PipeWire и WirePlumber."
|
||||
Layout.fillWidth: true; wrapMode: Text.Wrap; color: Theme.foreground
|
||||
}
|
||||
Repeater {
|
||||
model: [{title: "Вывод", nodes: Hardware.outputs, selected: Hardware.sink, sink: true},
|
||||
{title: "Ввод", nodes: Hardware.inputs, selected: Hardware.source, sink: false}]
|
||||
ColumnLayout {
|
||||
id: group
|
||||
required property var modelData
|
||||
Layout.fillWidth: true
|
||||
Label { text: group.modelData.title; font.pixelSize: 20; color: Theme.foreground }
|
||||
Label { visible: group.modelData.nodes.length === 0; text: "Нет доступных устройств"; color: Theme.outline }
|
||||
Repeater {
|
||||
model: group.modelData.nodes
|
||||
ColumnLayout {
|
||||
id: device
|
||||
required property var modelData
|
||||
Layout.fillWidth: true
|
||||
ActionButton {
|
||||
Layout.fillWidth: true
|
||||
text: (group.modelData.selected === device.modelData ? "✓ " : "") + (device.modelData.description || device.modelData.name)
|
||||
checked: group.modelData.selected === device.modelData
|
||||
enabled: device.modelData.ready
|
||||
onClicked: {
|
||||
if (group.modelData.sink) Pipewire.preferredDefaultAudioSink = device.modelData;
|
||||
else Pipewire.preferredDefaultAudioSource = device.modelData;
|
||||
}
|
||||
}
|
||||
RowLayout {
|
||||
Layout.fillWidth: true
|
||||
enabled: device.modelData.ready && device.modelData.audio !== null
|
||||
ActionButton {
|
||||
text: device.modelData.audio?.muted ? "Включить" : "Заглушить"
|
||||
onClicked: device.modelData.audio.muted = !device.modelData.audio.muted
|
||||
}
|
||||
Slider {
|
||||
Layout.fillWidth: true
|
||||
from: 0; to: 1
|
||||
value: device.modelData.audio?.volume || 0
|
||||
onMoved: device.modelData.audio.volume = value
|
||||
Accessible.name: group.modelData.title + ": громкость " + device.modelData.description
|
||||
}
|
||||
Label { text: Math.round((device.modelData.audio?.volume || 0) * 100) + "%"; color: Theme.foreground; Layout.preferredWidth: 48 }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
# Исправление загрузки BrightnessController
|
||||
|
||||
Ошибка `BrightnessController is not a type` вызвана отсутствием регистрации компонента в `services/qmldir`. Добавлена строка `BrightnessController 1.0 BrightnessController.qml`.
|
||||
|
||||
Перезапустите `./hypr/bin/adaptive-shell start`. Если появится следующая ошибка, приложите новый журнал: она может относиться к иной QML-зависимости.
|
||||
@@ -0,0 +1,138 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import QtQuick.Layouts
|
||||
import Quickshell
|
||||
import Quickshell.Hyprland
|
||||
import Quickshell.Wayland
|
||||
import Quickshell.Services.SystemTray
|
||||
import "services"
|
||||
import "components"
|
||||
|
||||
PanelWindow {
|
||||
id: bar
|
||||
signal navigate(string name)
|
||||
readonly property string mode: Preferences.modeFor(screen)
|
||||
anchors { top: true; left: true; right: true }
|
||||
implicitHeight: mode === "desktop" ? 56 : 52
|
||||
color: Theme.surfaceLow
|
||||
WlrLayershell.namespace: "adaptive-bar"
|
||||
SystemClock { id: clock; precision: SystemClock.Minutes }
|
||||
RowLayout {
|
||||
anchors.fill: parent
|
||||
anchors.leftMargin: 8
|
||||
anchors.rightMargin: 8
|
||||
spacing: 4
|
||||
ActionButton { text: bar.mode === "phone" ? "☰" : "◈ Приложения"; onClicked: bar.navigate("launcher") }
|
||||
Repeater {
|
||||
model: bar.mode === "desktop" ? Hyprland.workspaces : null
|
||||
ActionButton {
|
||||
required property var modelData
|
||||
visible: modelData.id > 0 && (!modelData.monitor || modelData.monitor.name === bar.screen.name)
|
||||
text: modelData.name
|
||||
checked: modelData.active
|
||||
onClicked: modelData.activate()
|
||||
}
|
||||
}
|
||||
Text {
|
||||
Layout.fillWidth: true
|
||||
visible: bar.mode === "desktop"
|
||||
text: Hyprland.activeToplevel?.title || ""
|
||||
color: Theme.foreground
|
||||
elide: Text.ElideRight
|
||||
textFormat: Text.PlainText
|
||||
}
|
||||
Item { Layout.fillWidth: true; visible: bar.mode !== "desktop" }
|
||||
Repeater {
|
||||
model: bar.mode === "desktop" ? SystemTray.items : null
|
||||
ActionButton {
|
||||
required property var modelData
|
||||
implicitWidth: 48
|
||||
text: ""
|
||||
Image { anchors.centerIn: parent; width: 24; height: 24; source: modelData.icon }
|
||||
onClicked: modelData.onlyMenu ? modelData.display(bar, 0, bar.height) : modelData.activate()
|
||||
onPressAndHold: modelData.display(bar, 0, bar.height)
|
||||
}
|
||||
}
|
||||
// One unified status surface, not a pill containing multiple pill buttons.
|
||||
// The previous nested ActionButtons caused overlapping circles at small widths.
|
||||
Rectangle {
|
||||
id: statusSurface
|
||||
visible: bar.mode === "desktop"
|
||||
Layout.alignment: Qt.AlignVCenter
|
||||
Layout.preferredHeight: 38
|
||||
Layout.preferredWidth: statusContent.implicitWidth + 24
|
||||
radius: 19
|
||||
color: statusMouse.containsMouse ? Theme.surfaceHigh : Theme.surface
|
||||
border.width: 1
|
||||
border.color: Theme.outline
|
||||
|
||||
Behavior on color { ColorAnimation { duration: Theme.duration } }
|
||||
RowLayout {
|
||||
id: statusContent
|
||||
anchors.centerIn: parent
|
||||
spacing: 10
|
||||
Text {
|
||||
visible: Hardware.wiredPresent || Hardware.wifiPresent
|
||||
text: Hardware.wiredPresent ? "⇄" : "◉"
|
||||
font.pixelSize: 16
|
||||
color: Theme.foreground
|
||||
Accessible.name: Hardware.wiredPresent ? Hardware.ethernetSummary : "Wi-Fi"
|
||||
}
|
||||
Text {
|
||||
visible: Hardware.sink !== null
|
||||
text: Hardware.sink?.audio?.muted ? "◌" : "♫"
|
||||
font.pixelSize: 15
|
||||
color: Theme.foreground
|
||||
}
|
||||
Repeater {
|
||||
model: Hardware.batteries
|
||||
Text {
|
||||
required property var modelData
|
||||
text: Math.round(modelData.percentage * 100) + "%"
|
||||
color: Theme.foreground
|
||||
font.pixelSize: 12
|
||||
}
|
||||
}
|
||||
Rectangle {
|
||||
visible: Hardware.wiredPresent || Hardware.wifiPresent || Hardware.sink !== null || Hardware.batteries.length > 0
|
||||
width: 1
|
||||
height: 18
|
||||
color: Theme.outline
|
||||
opacity: 0.45
|
||||
}
|
||||
Text {
|
||||
text: Qt.formatDateTime(clock.date, "HH:mm")
|
||||
color: Theme.foreground
|
||||
font.pixelSize: 14
|
||||
font.weight: Font.DemiBold
|
||||
}
|
||||
}
|
||||
MouseArea {
|
||||
id: statusMouse
|
||||
anchors.fill: parent
|
||||
hoverEnabled: true
|
||||
cursorShape: Qt.PointingHandCursor
|
||||
onClicked: bar.navigate("quick")
|
||||
}
|
||||
}
|
||||
ActionButton {
|
||||
visible: bar.mode !== "desktop" && (Hardware.wiredPresent || Hardware.wifiPresent)
|
||||
text: "◉"
|
||||
onClicked: bar.navigate("quick")
|
||||
}
|
||||
ActionButton {
|
||||
visible: bar.mode !== "desktop"
|
||||
text: Qt.formatDateTime(clock.date, "HH:mm")
|
||||
onClicked: bar.navigate("quick")
|
||||
}
|
||||
ActionButton {
|
||||
implicitWidth: 42
|
||||
implicitHeight: 38
|
||||
text: Notifications.items.length > 0 ? "● " + Notifications.items.length : "◌"
|
||||
Accessible.name: "Уведомления"
|
||||
onClicked: bar.navigate("notifications")
|
||||
}
|
||||
ActionButton { visible: bar.mode === "desktop"; implicitWidth: 42; implicitHeight: 38; text: "⚙"; Accessible.name: "Настройки"; onClicked: bar.navigate("settings") }
|
||||
ActionButton { visible: bar.mode === "desktop"; implicitWidth: 42; implicitHeight: 38; text: "⏻"; Accessible.name: "Питание"; onClicked: bar.navigate("power") }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import QtQuick.Controls
|
||||
import QtQuick.Controls.Material
|
||||
import QtQuick.Layouts
|
||||
import "services"
|
||||
|
||||
ScrollView {
|
||||
id: root
|
||||
contentWidth: availableWidth
|
||||
clip: true
|
||||
BrightnessController { id: brightness }
|
||||
ColumnLayout {
|
||||
width: root.availableWidth
|
||||
spacing: 16
|
||||
Label { text: "Батарея и питание"; font.pixelSize: 24; font.bold: true; color: Theme.primary }
|
||||
Label {
|
||||
Layout.fillWidth: true
|
||||
text: "Данные поступают от UPower. На устройствах без аккумулятора раздел скрыт."
|
||||
wrapMode: Text.Wrap
|
||||
color: Theme.outline
|
||||
}
|
||||
Label { text: "Яркость экрана"; font.bold: true; color: Theme.foreground }
|
||||
Label { text: "Управление подсветкой через brightnessctl"; color: Theme.outline }
|
||||
Repeater {
|
||||
model: brightness.devices
|
||||
ColumnLayout {
|
||||
required property var modelData
|
||||
Layout.fillWidth: true
|
||||
Label { text: modelData.name + " · " + modelData.percent + "%"; color: Theme.foreground }
|
||||
Slider {
|
||||
Layout.fillWidth: true
|
||||
from: 1; to: 100; stepSize: 1
|
||||
value: modelData.percent
|
||||
enabled: !brightness.busy
|
||||
onMoved: brightness.setBrightness(modelData.name, Math.round(value))
|
||||
}
|
||||
}
|
||||
}
|
||||
Label { visible: brightness.devices.length === 0; text: "Подсветка не обнаружена"; color: Theme.outline }
|
||||
Label { visible: brightness.error !== ""; text: brightness.error; wrapMode: Text.Wrap; color: "#d04040" }
|
||||
Repeater {
|
||||
model: Hardware.batteries
|
||||
ColumnLayout {
|
||||
id: batteryCard
|
||||
required property var modelData
|
||||
required property int index
|
||||
Layout.fillWidth: true
|
||||
spacing: 8
|
||||
Label { text: "Аккумулятор " + (index + 1); font.bold: true; color: Theme.foreground }
|
||||
RowLayout {
|
||||
Layout.fillWidth: true
|
||||
Label {
|
||||
text: Math.round(batteryCard.modelData.percentage * 100) + "%"
|
||||
font.pixelSize: 22
|
||||
font.bold: true
|
||||
color: Theme.primary
|
||||
}
|
||||
Item { Layout.fillWidth: true }
|
||||
}
|
||||
ProgressBar {
|
||||
Layout.fillWidth: true
|
||||
from: 0
|
||||
to: 1
|
||||
value: Math.max(0, Math.min(1, batteryCard.modelData.percentage || 0))
|
||||
}
|
||||
Label {
|
||||
Layout.fillWidth: true
|
||||
text: "Уровень заряда обновляется автоматически при изменении состояния устройства."
|
||||
color: Theme.outline
|
||||
wrapMode: Text.Wrap
|
||||
}
|
||||
}
|
||||
}
|
||||
Label {
|
||||
Layout.fillWidth: true
|
||||
visible: Hardware.batteries.length === 0
|
||||
text: "Аккумулятор не обнаружен."
|
||||
color: Theme.outline
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import QtQuick.Controls
|
||||
import QtQuick.Controls.Material
|
||||
import QtQuick.Layouts
|
||||
import Quickshell
|
||||
import Quickshell.Bluetooth
|
||||
import "services"
|
||||
import "components"
|
||||
|
||||
ScrollView {
|
||||
id: page
|
||||
property bool active: false
|
||||
Material.theme: Theme.dark ? Material.Dark : Material.Light
|
||||
Material.accent: Theme.primary
|
||||
clip: true
|
||||
contentWidth: availableWidth
|
||||
BluetoothController { id: backend }
|
||||
onActiveChanged: if (active) backend.refresh()
|
||||
ColumnLayout {
|
||||
width: page.availableWidth
|
||||
spacing: 16
|
||||
Label { text: "Bluetooth"; font.pixelSize: 24; color: Theme.primary }
|
||||
Label {
|
||||
visible: Hardware.bluetoothAdapters.length === 0
|
||||
text: backend.readiness === "unavailable" ? "Сервис Bluetooth недоступен" : backend.readiness === "ready" && backend.adapterCount === 0 ? "Bluetooth-адаптеры не обнаружены" : "Ожидание списка адаптеров…"
|
||||
Layout.fillWidth: true; wrapMode: Text.Wrap; color: Theme.foreground
|
||||
}
|
||||
Label { visible: backend.error !== ""; text: backend.error; Layout.fillWidth: true; wrapMode: Text.Wrap; textFormat: Text.PlainText; color: "#ffb4ab" }
|
||||
BusyIndicator { visible: backend.busy; running: visible }
|
||||
Repeater {
|
||||
model: Hardware.bluetoothAdapters
|
||||
Rectangle {
|
||||
id: adapterCard
|
||||
required property var modelData
|
||||
property bool confirmPowerOff: false
|
||||
Layout.fillWidth: true
|
||||
implicitHeight: adapterContent.implicitHeight + 32
|
||||
color: Theme.surface; radius: 20
|
||||
BluetoothDiscovery { id: discovery; adapter: adapterCard.modelData; active: page.active }
|
||||
Connections { target: page; function onActiveChanged() { if (!page.active) adapterCard.confirmPowerOff = false; } }
|
||||
ColumnLayout {
|
||||
id: adapterContent
|
||||
anchors { top: parent.top; left: parent.left; right: parent.right; margins: 16 }
|
||||
spacing: 12
|
||||
Label { text: adapterCard.modelData?.name || "Bluetooth"; font.pixelSize: 20; color: Theme.primary; textFormat: Text.PlainText }
|
||||
Label { text: adapterCard.modelData ? BluetoothAdapterState.toString(adapterCard.modelData.state) : ""; color: Theme.foreground }
|
||||
ActionButton {
|
||||
text: adapterCard.modelData?.enabled ? "Выключить Bluetooth…" : "Включить Bluetooth"
|
||||
enabled: !!adapterCard.modelData && adapterCard.modelData.state !== BluetoothAdapterState.Blocked && !backend.busy
|
||||
onClicked: {
|
||||
if (adapterCard.modelData.enabled) adapterCard.confirmPowerOff = true;
|
||||
else backend.start("power-on", adapterCard.modelData.dbusPath);
|
||||
}
|
||||
}
|
||||
Label { visible: adapterCard.confirmPowerOff; text: "Выключить адаптер? Его текущие соединения будут прерваны."; Layout.fillWidth: true; wrapMode: Text.Wrap; color: Theme.foreground }
|
||||
RowLayout {
|
||||
visible: adapterCard.confirmPowerOff
|
||||
ActionButton { text: "Выключить"; enabled: !backend.busy; onClicked: { discovery.stop(); adapterCard.confirmPowerOff = false; backend.start("power-off", adapterCard.modelData.dbusPath); } }
|
||||
ActionButton { text: "Отмена"; onClicked: adapterCard.confirmPowerOff = false }
|
||||
}
|
||||
ActionButton {
|
||||
text: discovery.stopping ? "Остановка поиска…" : discovery.starting ? "Начало поиска…" : discovery.owned ? "Остановить поиск" : adapterCard.modelData?.discovering ? "Поиск уже выполняется" : "Найти устройства"
|
||||
enabled: adapterCard.modelData?.enabled === true && !backend.busy && !discovery.starting && !discovery.stopping && (discovery.owned || !adapterCard.modelData.discovering)
|
||||
onClicked: discovery.owned ? discovery.stop() : discovery.start()
|
||||
}
|
||||
Label { visible: discovery.error !== ""; text: discovery.error; wrapMode: Text.Wrap; Layout.fillWidth: true; color: "#ffb4ab" }
|
||||
Repeater {
|
||||
model: adapterCard.modelData?.devices || []
|
||||
ColumnLayout {
|
||||
id: deviceCard
|
||||
required property var modelData
|
||||
property string confirmation: ""
|
||||
Layout.fillWidth: true
|
||||
Label { text: (deviceCard.modelData?.name || deviceCard.modelData?.address || "Устройство") + (deviceCard.modelData?.paired ? " · Сопряжено" : ""); color: Theme.foreground; textFormat: Text.PlainText; Layout.fillWidth: true; wrapMode: Text.Wrap }
|
||||
Label { text: deviceCard.modelData ? BluetoothDeviceState.toString(deviceCard.modelData.state) : ""; color: Theme.outline }
|
||||
Label { visible: deviceCard.modelData?.blocked === true; text: "Устройство заблокировано"; color: Theme.outline }
|
||||
ActionButton {
|
||||
visible: deviceCard.modelData?.paired === true
|
||||
text: deviceCard.modelData?.connected ? "Отключить…" : "Подключить"
|
||||
enabled: adapterCard.modelData?.enabled === true && deviceCard.modelData?.blocked === false && !backend.busy
|
||||
onClicked: {
|
||||
if (deviceCard.modelData.connected) deviceCard.confirmation = "disconnect";
|
||||
else backend.start("connect", deviceCard.modelData.dbusPath);
|
||||
}
|
||||
}
|
||||
ActionButton { visible: deviceCard.modelData?.paired === true; text: "Забыть устройство…"; enabled: !backend.busy; onClicked: deviceCard.confirmation = "forget" }
|
||||
Label { visible: deviceCard.confirmation !== ""; text: deviceCard.confirmation === "forget" ? "Удалить сопряжение? Для следующего подключения понадобится сопряжение заново." : "Отключить устройство?"; color: Theme.foreground; Layout.fillWidth: true; wrapMode: Text.Wrap }
|
||||
RowLayout {
|
||||
visible: deviceCard.confirmation !== ""
|
||||
ActionButton { text: "Подтвердить"; enabled: !backend.busy && !!deviceCard.modelData; onClicked: { backend.start(deviceCard.confirmation, deviceCard.modelData.dbusPath); deviceCard.confirmation = ""; } }
|
||||
ActionButton { text: "Отмена"; onClicked: deviceCard.confirmation = "" }
|
||||
}
|
||||
Connections { target: page; function onActiveChanged() { if (!page.active) deviceCard.confirmation = ""; } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ActionButton { text: "Сопряжение через системный диалог…"; visible: Hardware.bluetoothAdapters.length > 0; onClicked: Quickshell.execDetached(["blueman-manager"]) }
|
||||
ActionButton { text: "Обновить доступность Bluetooth"; enabled: !backend.busy; onClicked: backend.refresh() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
# Продолжение разработки (17 ноября 2026)
|
||||
|
||||
## Реализовано в этом изменении
|
||||
|
||||
- Добавлена чистая модель `services/HardwarePolicy.js` для различения отсутствующих и отключённых сетевых устройств.
|
||||
- В `Hardware.qml` добавлены реактивные свойства `wiredDevices`, `wiredPresent`, `ethernetSummary`.
|
||||
- `QuickSettings.qml` показывает отдельные плитки каждого обнаруженного Ethernet-интерфейса; Wi-Fi остаётся скрытым при отсутствии адаптера.
|
||||
- `Bar.qml` отображает только доступные Ethernet/Wi-Fi индикаторы; проводные сети показывают количество подключённых интерфейсов.
|
||||
- Добавлены QML unit-тесты на Ethernet-only, несколько адаптеров, выключенный Wi-Fi и hotplug-пересчёт.
|
||||
|
||||
## Проверки
|
||||
|
||||
QML-тесты требуют Qt Test runner и Quickshell на целевой машине:
|
||||
|
||||
```sh
|
||||
cd ~/dotfiles/quickshell
|
||||
qmltestrunner -input tests/tst_hardware_policy.qml
|
||||
```
|
||||
|
||||
В этой среде `qmltestrunner` и `quickshell` отсутствуют, поэтому runtime-тесты не выполнены.
|
||||
|
||||
## Дальнейшая работа
|
||||
|
||||
- Добавить ModemManager capabilities и реальную мобильную сеть.
|
||||
- Подключить единый список доступных разделов в Settings (сейчас политика подготовлена, но список ещё статический).
|
||||
- Реализовать защищённый lock screen только после проверки `ext-session-lock-v1` и PAM; до этого оставить Hyprlock.
|
||||
- Проверить глобальные сенсорные жесты на реальном телефоне; UI-жесты сами по себе не обеспечивают compositor-level interception.
|
||||
- Измерить PSS/CPU и плавность на ARM64.
|
||||
|
||||
Существующие конфигурации Hyprland, hypridle и hyprlock не изменялись этим этапом.
|
||||
|
||||
## Следующий проверенный этап: адаптивная навигация Settings
|
||||
|
||||
- `Settings.qml`: вместо фиксированного списка разделов используется реактивная политика аппаратных возможностей; отсутствующие Wi-Fi/Bluetooth/аудио не создают неработающие разделы.
|
||||
- Навигация использует стабильные идентификаторы (`appearance`, `audio`, `network`, `wallpaper`, `bluetooth`), поэтому hotplug не перепутает страницы.
|
||||
- `SettingsWindow.qml` и `shell.qml` согласованы с новой адресацией, в том числе для прямых переходов из панели и быстрых настроек.
|
||||
- Добавлены QML-тесты и независимый Node.js-тест `node tests/hardware_policy_node.cjs`.
|
||||
- Локально пройдено 29 Python unit-тестов и тест JS-политики. QML runtime и реальное оборудование здесь недоступны.
|
||||
|
||||
### Ограничения текущей реализации
|
||||
|
||||
Это не завершение всего проекта: требуется полноценная проверка в Hyprland/Quickshell, реализация ModemManager, надёжных глобальных жестов, полного приложения системных настроек и защищённой замены Hyprlock. **Hyprlock и hypridle оставлены без изменений.**
|
||||
@@ -0,0 +1,11 @@
|
||||
# Mobile data / APN stage
|
||||
|
||||
Added a constrained NetworkManager GSM profile backend (`backend/mobile_connections.py`), a singleton (`services/MobileConnections.qml`) and a profile editor in `ModemSettings.qml`.
|
||||
|
||||
Capabilities: create a GSM profile with a validated APN and name, list GSM/CDMA profiles, activate/deactivate a profile by UUID, and delete it after confirmation. Operations are restricted to mobile profiles; no arbitrary shell execution or PIN/PUK storage. NetworkManager/Polkit determines authorization. `nmcli` and NetworkManager must be installed.
|
||||
|
||||
Tests: `cd quickshell && python -m unittest discover -s tests -p 'test_*.py' -v`.
|
||||
|
||||
On the target system, check `nmcli -g UUID,TYPE,NAME connection show` and the mobile Settings page. Test activation with an actual SIM only after configuring your operator's APN. ModemManager and NetworkManager integration, Qt QML runtime, modem hotplug and user-visible auth prompts require testing on the device. A valid APN alone does not guarantee cellular connectivity.
|
||||
|
||||
Not yet implemented: SIM PIN/PUK management, multi-SIM selection, roaming policy, cellular usage metering, global compositor gestures, and secure Quickshell session lock/fprintd. Keep hyprlock enabled until the replacement is security-audited.
|
||||
@@ -0,0 +1,11 @@
|
||||
# Battery settings stage
|
||||
|
||||
Added `BatterySettings.qml` using existing Quickshell UPower hardware discovery. The Battery and Power page appears only when `Hardware.batteries` is nonempty. Battery level is read-only; no privileged or potentially disruptive power operations are performed. The page has a fixed StackLayout index (7) so hotplug cannot redirect navigation to another page.
|
||||
|
||||
## Validation
|
||||
|
||||
Run `python3 -m unittest discover -s quickshell/tests -p "test_*.py"` and `node quickshell/tests/hardware_policy_node.cjs`. On an actual phone or laptop verify battery percentage, charging state updates, and that the page disappears when no battery is present. Note that a QML runtime test was not possible in the build container.
|
||||
|
||||
## Remaining
|
||||
|
||||
System power profiles, suspend policies, global gestures, SIM PIN/PUK and secure session locking/fingerprint authentication still require implementation and hardware validation. Keep hyprlock enabled.
|
||||
@@ -0,0 +1,7 @@
|
||||
# Brightness stage
|
||||
|
||||
Added `backend/brightness.py`, `services/BrightnessController.qml` and backlight sliders to `BatterySettings.qml`.
|
||||
|
||||
Requires `brightnessctl` and permission to change `/sys/class/backlight` (typically udev/logind ACL or a suitable group). No sudo or shell invocation is used. Only devices reported as `backlight` by brightnessctl are offered; brightness is clamped to 1–100% to avoid an accidentally black display. Backend validates device identifiers and current enumerated devices before writes. Hardware changes refresh every 10 seconds. Multiple backlights are displayed separately.
|
||||
|
||||
Known limitations: power settings remain hidden on desktops without a battery, so this brightness UI is not accessible there; backlight controls do not apply to external DDC/CI monitors. QML was not runtime-tested in Hyprland. Test with `brightnessctl -m -l`, adjust slider, verify with `brightnessctl -m -l` and restore original brightness. Hyprlock/hypridle unchanged.
|
||||
@@ -0,0 +1,7 @@
|
||||
# Desktop shelf — next stage
|
||||
|
||||
Added `DesktopShelf.qml`, a desktop-only floating bottom shelf inspired by ChromeOS/Material 3 Expressive. It shows an app launcher, live Wayland toplevel buttons (activate on click), and an overview entry. It is instantiated per screen in `shell.qml` and hidden in tablet/phone mode. Existing top bar, notifications, quick settings, and Hyprlock remain unchanged.
|
||||
|
||||
Test on desktop: start adaptive-shell; check bottom shelf; open two windows; click their shelf entries; click launcher and overview. Switch output to tablet/phone mode and verify shelf is hidden. Verify multi-monitor behavior.
|
||||
|
||||
Limitations: labels are text (not application icons); shelf has no pinned apps or task grouping, and QML runtime was not available in the build environment. On narrow desktops many windows may overflow; no auto-hide yet.
|
||||
@@ -0,0 +1,12 @@
|
||||
# Desktop Launcher · Material 3 Expressive
|
||||
|
||||
- Desktop launcher widened to 580 px, keeping the existing left/top alignment.
|
||||
- Added All, Favorites and Recent chips, app counts, selected tonal tile backgrounds and hover affordances.
|
||||
- Existing application execution, keyboard navigation, favorites, search and phone/tablet views remain.
|
||||
- No bottom dock; no change to Hyprlock or Hypridle.
|
||||
|
||||
## Test
|
||||
|
||||
Run `./hypr/bin/adaptive-shell start` in Hyprland. Open the launcher from the top bar, filter by category, type a query, launch an app and pin/unpin favorites. Verify the phone/tablet launcher still works.
|
||||
|
||||
QML runtime validation was unavailable in the build environment.
|
||||
@@ -0,0 +1,12 @@
|
||||
# Desktop without dock
|
||||
|
||||
- Removed `DesktopShelf` entirely and its `Variants` instantiation.
|
||||
- The existing top bar remains the sole desktop navigation surface.
|
||||
- Desktop system indicators are grouped in a tonal capsule: wired/Wi-Fi, audio, battery and time; clicking opens Quickshell quick settings.
|
||||
- Notification count opens the Quickshell notification center.
|
||||
- The desktop launcher is anchored near the upper-left, while quick settings and notifications remain near the upper-right.
|
||||
- Phone/tablet layout retains its prior navigation controls.
|
||||
- No changes to Hyprland, hypridle or hyprlock.
|
||||
|
||||
## Verification
|
||||
Run `./hypr/bin/adaptive-shell start` and verify desktop launcher, notifications, quick settings, settings and power buttons. Verify no bottom shelf appears. QML runtime validation must be performed on a machine with Quickshell and Hyprland.
|
||||
@@ -0,0 +1,16 @@
|
||||
# Desktop status bar polish
|
||||
|
||||
- Replaced nested pill-shaped ActionButtons in the desktop status area with a single compact surface and text/icons.
|
||||
- Removed overlapping inner backgrounds, reduced height to 38px and spaced network, sound, battery and time consistently.
|
||||
- Unified hover and click target for Quick Settings.
|
||||
- Kept the desktop free of a bottom dock; phone/tablet behavior unchanged.
|
||||
- No changes to hyprlock, hypridle or Hyprland configuration.
|
||||
|
||||
## Manual checks
|
||||
|
||||
1. Launch `./hypr/bin/adaptive-shell start`.
|
||||
2. Confirm the right-hand cluster has a single rounded outline, without overlapping circles.
|
||||
3. Click anywhere in the cluster and confirm Quick Settings opens.
|
||||
4. Test network, audio and battery presence/absence, and narrow desktop outputs.
|
||||
|
||||
QML runtime validation requires the user's Hyprland session.
|
||||
@@ -0,0 +1,7 @@
|
||||
# Desktop Material 3 Expressive quick settings
|
||||
|
||||
Desktop Quick Settings now uses `DesktopQuickSettings.qml`, a compact dashboard with two-column tonal tiles, brightness and volume controls, and links to existing settings. Phone and tablet still use the original `QuickSettings.qml`. No dock has been added.
|
||||
|
||||
Test on desktop: open the system area; verify Wi-Fi/Bluetooth toggles, brightness, volume and navigation. Test tablet/phone separately to ensure original layout remains. Brightness depends on `brightnessctl` and available backlight devices.
|
||||
|
||||
Known limits: controls for Cast, Quick Share, auto-rotate and camera privacy are intentionally not fabricated; these require actual system backends. QML runtime validation requires Quickshell/Hyprland on target hardware.
|
||||
@@ -0,0 +1,8 @@
|
||||
# Display Settings stage
|
||||
|
||||
- Added an always-accessible Display and brightness section on desktop, tablet and phone, including machines without batteries.
|
||||
- Moved the existing brightnessctl UI out of BatterySettings to avoid duplication.
|
||||
- Preserved battery/UPower functionality and all existing page indices; new page index is 8.
|
||||
- DDC/CI, display modes, scale and orientation are not implemented in this stage.
|
||||
- Verify by opening Settings → Дисплей и яркость, checking brightnessctl, and verifying battery section only appears when UPower reports a battery.
|
||||
- Existing hyprlock/hypridle are unchanged.
|
||||
@@ -0,0 +1,15 @@
|
||||
# Продолжение: мобильная навигация и Recent Apps
|
||||
|
||||
- Горизонтальный свайп **по нижней навигационной полоске** переключает окна через `ToplevelManager`.
|
||||
- Вертикальный свайп по карточке Recent Apps вверх запрашивает закрытие окна.
|
||||
- Логика выбора окна и порога закрытия вынесена в `services/WindowPolicy.js` и проверяется Node.js.
|
||||
- **Ограничение:** свайпы работают на соответствующих поверхностях Quickshell; глобальные свайпы поверх сторонних приложений требуют интеграции с Hyprland/композитором.
|
||||
- `lastCycledWindow` отслеживает индекс только для последовательных переключений. Если список окон изменился, последовательность может начать с другого окна.
|
||||
- `Hyprlock` и `Hypridle` не изменены.
|
||||
|
||||
## Проверка на устройстве
|
||||
|
||||
1. Откройте минимум три приложения, выполните горизонтальный свайп по нижней полоске в обе стороны.
|
||||
2. Откройте Recent Apps и свайпните карточку вверх; убедитесь, что закрыто только нужное окно.
|
||||
3. Проверьте на реальном touchscreen: касания кнопок «Открыть» и «Закрыть» не должны перехватываться DragHandler.
|
||||
4. Проверьте вертикальный свайп снизу: короткий — Home, с удержанием — Recent Apps.
|
||||
@@ -0,0 +1,27 @@
|
||||
# Продолжение: домашний экран и многозадачность
|
||||
|
||||
## Изменения
|
||||
- `Home.qml`: страницы избранных приложений (12 плиток в узком режиме, 24 в широком), переход между страницами, режим редактирования, перестановка закреплённых приложений и удаление из избранного. Долгое нажатие включает редактирование; также есть кнопка «Изменить». Список и порядок сохраняются в существующем `Preferences.data.favorites`.
|
||||
- `services/Policy.js`: чистые функции `moveFavorite` и `homePages`, не зависящие от Quickshell.
|
||||
- `services/Preferences.qml`: `moveFavorite` через существующий атомарно сохраняемый файл настроек.
|
||||
- `Recent.qml`: карточки окон с заголовком, appId, поиском, активацией и закрытием через ToplevelManager.
|
||||
- `tests/home_policy_node.cjs`: тесты страниц и перестановки.
|
||||
|
||||
## Проверено в среде разработки
|
||||
- Node.js: home policy и hardware policy — PASS.
|
||||
- Python unittest: 33 теста — PASS.
|
||||
- QML/Wayland: не запускались, Quickshell отсутствует в окружении.
|
||||
|
||||
## Ограничения
|
||||
- Это НЕ полноценные глобальные жесты: `MobileNavigation.qml` всё ещё получает только события в своей панели. Для глобальных жестов требуется интеграция с Hyprland/compositor.
|
||||
- Recent Apps пока показывает карточки без живых превью, использует ToplevelManager; swipe-to-close ещё не реализован.
|
||||
- Home Screen пока не поддерживает папки, drag-and-drop и виджеты. Избранное управляется из Launcher.
|
||||
- Не менялись Hyprlock, Hypridle, PAM и запуск из TTY. Экран блокировки на Quickshell не реализован.
|
||||
|
||||
## Проверка на машине пользователя
|
||||
```
|
||||
node ~/.config/quickshell/tests/home_policy_node.cjs
|
||||
node ~/.config/quickshell/tests/hardware_policy_node.cjs
|
||||
python -m unittest discover -s ~/.config/quickshell/tests -p 'test_*.py' -q
|
||||
```
|
||||
Откройте Home, закрепите несколько приложений звёздочкой в Launcher, переключите страницы, переставьте плитки в режиме редактирования. Откройте Recent и проверьте поиск, активацию и закрытие окон.
|
||||
@@ -0,0 +1,21 @@
|
||||
# ModemManager control stage
|
||||
|
||||
- Added `backend/modem_control.py`, a strict allowlist of `enable` and `disable` operations using `mmcli` argument vectors (no shell interpolation).
|
||||
- Added a Modems service action state and refreshed modem inventory after each operation.
|
||||
- Added enable/disable buttons and a confirmation dialog before disabling a modem.
|
||||
- Added backend unit tests for argument validation and command construction.
|
||||
|
||||
## Safety and limits
|
||||
|
||||
- ModemManager/polkit performs authorization; this code does not bypass it.
|
||||
- Disabling a modem can terminate mobile connectivity.
|
||||
- SIM PIN/PUK, APN, and connection management are **not** implemented.
|
||||
- Hyprlock and hypridle are unchanged. This is not a secure Quickshell lock screen.
|
||||
- The QML UI has not been run in a Hyprland session in this environment.
|
||||
|
||||
## User verification
|
||||
|
||||
1. On a phone with ModemManager, open Settings → Mobile network and SIM.
|
||||
2. Confirm the modem ID, state and signal. Test enable and disable only when loss of mobile connectivity is acceptable.
|
||||
3. Verify the confirmation dialog cancels correctly and errors are visible.
|
||||
4. On desktop without modem, verify the mobile settings section stays hidden.
|
||||
@@ -0,0 +1,11 @@
|
||||
# Мониторы Hyprland
|
||||
|
||||
Добавлен безопасный read-only backend `backend/displays.py`, контроллер `services/DisplayController.qml` и карточки мониторов в `DisplaySettings.qml`.
|
||||
|
||||
Показываются имя, описание, разрешение, частота, масштаб, позиция, ориентация и активный монитор. Состояние обновляется каждые пять секунд; подключение/отключение монитора отражается автоматически. Backend не меняет конфигурацию мониторов.
|
||||
|
||||
Тесты: `cd quickshell && python -m unittest discover -s tests -p 'test_*.py' -q` (52 passed).
|
||||
|
||||
Проверить на компьютере: `hyprctl -j monitors all`, открыть Settings → Дисплей и яркость, сравнить значения; подключить внешний монитор и проверить обновление. На телефоне проверить в nested Hyprland/Quickshell и на устройстве. Тесты QML на настоящем compositor здесь не выполнялись.
|
||||
|
||||
Следующий этап: изменение разрешения/масштаба с безопасным откатом и подтверждением, глобальные жесты, SIM PIN/PUK, безопасный session lock.
|
||||
@@ -0,0 +1,7 @@
|
||||
# Monitor preview with automatic rollback
|
||||
|
||||
Settings → Дисплей и яркость now offers mode and scale choices sourced from Hyprland. Preview uses `hyprctl keyword monitor` and starts a detached 20-second rollback watcher. Confirm within 20 seconds or the previous monitor rule is restored. Changes are session-only; `hypr/monitors.lua` and `hypr/monitors.conf` are untouched.
|
||||
|
||||
**Limitations:** the preview currently restores resolution, refresh rate, scale, and position, but not all advanced monitor properties (e.g. transform, VRR, bit depth). Avoid using the preview on rotated displays until the rollback path supports those properties. A compositor crash or process termination can defeat rollback. External testing is required. Changing a mode may cause the UI to move to another monitor. If that happens, wait 20 seconds. The mode selector is populated from Hyprland `availableModes`.
|
||||
|
||||
Tests: `cd quickshell && python3 -m unittest discover -s tests -p 'test_*.py' -q`.
|
||||
@@ -0,0 +1,8 @@
|
||||
# Display positioning stage
|
||||
|
||||
- Settings → Дисплей и яркость: X/Y position controls for each output.
|
||||
- Coordinates are passed as separate arguments (no shell interpolation), validated in the backend.
|
||||
- Existing 20-second confirmation and rollback include original X/Y and transform.
|
||||
- Changes are session-only; persistent Hyprland monitor rules are not edited.
|
||||
- Test negative coordinates carefully on multi-monitor setups. Do not reposition the only monitor without an available recovery path.
|
||||
- Existing limitation: rollback watcher relies on a running Hyprland session; multi-monitor topology changes during the countdown are not handled transactionally.
|
||||
@@ -0,0 +1,9 @@
|
||||
# Этап: профили энергопотребления
|
||||
|
||||
Добавлен backend `backend/power_profiles.py`, сервис `services/PowerProfiles.qml` и кнопки в `BatterySettings.qml`.
|
||||
|
||||
Требуется `powerprofilesctl` и работающий системный сервис, предоставляющий профили питания. Доступность `performance` зависит от оборудования и драйверов. Если команда не установлена или профиль не поддерживается, интерфейс покажет ошибку; для применения могут потребоваться системные разрешения. Команды запускаются без shell и только с разрешёнными значениями.
|
||||
|
||||
Проверка: открыть Settings → Батарея и питание; выбрать «Экономия», «Баланс» или «Производительность»; проверить `powerprofilesctl get`. На устройствах без аккумулятора раздел пока скрыт — даже если профили питания поддерживаются. Это ограничение предстоит исправить.
|
||||
|
||||
Python unit tests: `python -m pytest -q tests` (47 passed в среде разработки). QML/Hyprland не запускались. Hyprlock и hypridle не изменены.
|
||||
@@ -0,0 +1,15 @@
|
||||
# Quick Settings: hardware-aware brightness
|
||||
|
||||
The Quickshell Quick Settings shade now includes one brightness slider per backlight exposed by `brightnessctl`. The controls disappear on systems without a supported backlight. Changes are applied on pointer release, not continuously, to avoid spawning many subprocesses. The existing Display Settings page remains the full-featured view.
|
||||
|
||||
## Verify
|
||||
|
||||
1. Open Quick Settings on the phone/laptop; compare brightness with `brightnessctl -m -l`.
|
||||
2. Drag a slider and release; confirm brightness changes once.
|
||||
3. On a desktop with no `/sys/class/backlight` device, no brightness control should appear.
|
||||
4. Click Display Settings and confirm navigation.
|
||||
5. Check that audio, Wi-Fi, Ethernet, Bluetooth, modem and notifications still work.
|
||||
|
||||
Note: powerprofilesctl support is **not present** in this archive's BatterySettings.qml, despite an earlier development-stage claim. It has not been represented as implemented here. Hyprlock and hypridle remain unchanged.
|
||||
|
||||
Restored DisplaySettings integration: registered the three QML controllers in qmldir, added a stable `display` settings section/page, and enabled routing from Quick Settings.
|
||||
@@ -0,0 +1,16 @@
|
||||
# Desktop Quick Settings — layout correction
|
||||
|
||||
The Desktop-only panel is now a compact, consistently spaced Material 3 dashboard:
|
||||
- One header, not duplicated by Overlay.
|
||||
- 48 px pill sliders for supported backlight and PipeWire audio.
|
||||
- 2-column, 46 px tonal tiles with consistent icon and label alignment.
|
||||
- Hardware-aware Wi-Fi and Bluetooth visibility.
|
||||
- Panel reduced to 420 px high on desktop; internal scrolling remains available.
|
||||
- All buttons use existing functional navigation/actions; no mock toggles.
|
||||
|
||||
Phone/tablet QuickSettings.qml is unchanged. Hyprlock, hypridle and Hyprland configuration are unchanged.
|
||||
|
||||
Run: ./hypr/bin/adaptive-shell start
|
||||
Check desktop right-side Quick Settings, both dark/light themes, no backlight, Wi-Fi absent, and Bluetooth absent.
|
||||
|
||||
QML runtime is unavailable in the build environment, so these changes have not been visually validated on a running compositor.
|
||||
@@ -0,0 +1,8 @@
|
||||
# Desktop UI — Android/ChromeOS reference pass
|
||||
|
||||
- Desktop launcher is now a compact floating search-and-app grid, with 5-ish columns on typical widths and no bottom dock.
|
||||
- Desktop Quick Settings is a narrow top-right panel with a condensed header and connection controls.
|
||||
- Desktop overlays use a light dim rather than a heavy full-screen veil; mobile and tablet retain their previous full-screen behavior.
|
||||
- Existing hardware-bound controls (Wi-Fi, Bluetooth, brightness, volume, media, modem) remain functional.
|
||||
- Desktop screenshots supplied by the user are design references, not pixel-identical output.
|
||||
- Validate visually on Hyprland; no Quickshell runtime is available in the build environment.
|
||||
@@ -0,0 +1,9 @@
|
||||
# Display orientation and rollback — 2026-11-17
|
||||
|
||||
- Settings → Display & Brightness: choose 0°, 90°, 180°, 270° alongside resolution and scale.
|
||||
- Backend `display_preview.py` accepts an optional transform (0–7), validates it, and preserves current monitor coordinates rather than using `auto`.
|
||||
- Rollback restores original resolution, refresh rate, position, scale **and transform**.
|
||||
- Existing 4-argument preview invocation remains supported.
|
||||
- No persistent Hyprland config changes. The 20-second watcher remains best-effort if the compositor/session crashes.
|
||||
- Test with `python3 -m unittest discover -s quickshell/tests -p 'test_*.py'` from dotfiles root.
|
||||
- Important: do not use rotation preview on the only display during critical work until tested on your machine. Hyprland transforms 4–7 (flipped variants) are preserved on rollback but not exposed in the UI.
|
||||
@@ -0,0 +1,5 @@
|
||||
# System information settings
|
||||
|
||||
Read-only system information page added to Material 3 Settings (desktop, tablet, phone). Shows OS, kernel, architecture, hostname, memory and uptime. Refreshes every 60 seconds, with manual refresh. Reads `/etc/os-release`, `/proc/meminfo`, `/proc/uptime` and Python platform. No privileged actions.
|
||||
|
||||
Tests: `python3 -m unittest discover -s tests -p 'test_*.py' -q` and `node tests/*node.cjs` individually. Quickshell runtime testing unavailable in build environment. Hyprlock/hypridle unchanged. Future work includes global gestures, secure session lock and SIM PIN/PUK.
|
||||
@@ -0,0 +1,197 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import QtQuick.Controls
|
||||
import QtQuick.Controls.Material
|
||||
import QtQuick.Layouts
|
||||
import Quickshell
|
||||
import Quickshell.Networking
|
||||
import "services"
|
||||
|
||||
// Compact ChromeOS/Android-inspired desktop dashboard. Real actions only.
|
||||
ScrollView {
|
||||
id: dashboard
|
||||
signal navigate(string name)
|
||||
clip: true
|
||||
contentWidth: availableWidth
|
||||
ScrollBar.horizontal.policy: ScrollBar.AlwaysOff
|
||||
Material.theme: Theme.dark ? Material.Dark : Material.Light
|
||||
Material.accent: Theme.primary
|
||||
|
||||
BrightnessController { id: brightness }
|
||||
readonly property bool hasBacklight: brightness.devices.length > 0
|
||||
readonly property bool hasAudio: Hardware.sink !== null && Hardware.sink.audio !== null
|
||||
readonly property bool hasBluetooth: Hardware.bluetoothAdapters.length > 0
|
||||
|
||||
component Tile: Rectangle {
|
||||
id: tile
|
||||
property string title: ""
|
||||
property string symbol: ""
|
||||
property bool selected: false
|
||||
property bool usable: true
|
||||
signal activated()
|
||||
Layout.fillWidth: true
|
||||
Layout.preferredHeight: 46
|
||||
radius: 23
|
||||
color: selected ? Theme.primaryContainer : Theme.surfaceHigh
|
||||
opacity: usable ? 1 : 0.45
|
||||
Behavior on color { ColorAnimation { duration: Theme.duration } }
|
||||
RowLayout {
|
||||
anchors.fill: parent
|
||||
anchors.leftMargin: 12
|
||||
anchors.rightMargin: 10
|
||||
spacing: 9
|
||||
Text {
|
||||
text: tile.symbol
|
||||
font.pixelSize: 16
|
||||
color: tile.selected ? Theme.onPrimaryContainer : Theme.foreground
|
||||
Layout.preferredWidth: 19
|
||||
horizontalAlignment: Text.AlignHCenter
|
||||
}
|
||||
Text {
|
||||
text: tile.title
|
||||
font.pixelSize: 12
|
||||
font.weight: Font.DemiBold
|
||||
color: tile.selected ? Theme.onPrimaryContainer : Theme.foreground
|
||||
Layout.fillWidth: true
|
||||
elide: Text.ElideRight
|
||||
}
|
||||
}
|
||||
MouseArea {
|
||||
anchors.fill: parent
|
||||
enabled: tile.usable
|
||||
cursorShape: Qt.PointingHandCursor
|
||||
onClicked: tile.activated()
|
||||
}
|
||||
}
|
||||
|
||||
ColumnLayout {
|
||||
width: dashboard.availableWidth
|
||||
spacing: 10
|
||||
|
||||
RowLayout {
|
||||
Layout.fillWidth: true
|
||||
Layout.preferredHeight: 36
|
||||
spacing: 8
|
||||
Text {
|
||||
text: "▦"
|
||||
color: Theme.primary
|
||||
font.pixelSize: 19
|
||||
}
|
||||
Text {
|
||||
text: "Быстрые настройки"
|
||||
color: Theme.foreground
|
||||
font.pixelSize: 16
|
||||
font.weight: Font.DemiBold
|
||||
Layout.fillWidth: true
|
||||
elide: Text.ElideRight
|
||||
}
|
||||
ToolButton {
|
||||
text: "⚙"
|
||||
Accessible.name: "Открыть настройки"
|
||||
onClicked: dashboard.navigate("settings")
|
||||
}
|
||||
}
|
||||
|
||||
// Material 3 Expressive pill-shaped sliders. Do not show unsupported hardware.
|
||||
Rectangle {
|
||||
visible: dashboard.hasBacklight
|
||||
Layout.fillWidth: true
|
||||
Layout.preferredHeight: visible ? 48 : 0
|
||||
radius: 24
|
||||
color: Theme.secondaryContainer
|
||||
RowLayout {
|
||||
anchors.fill: parent
|
||||
anchors.leftMargin: 14
|
||||
anchors.rightMargin: 12
|
||||
spacing: 8
|
||||
Text { text: "☀"; color: Theme.foreground; font.pixelSize: 18 }
|
||||
Slider {
|
||||
Layout.fillWidth: true
|
||||
from: 1; to: 100; stepSize: 1
|
||||
value: dashboard.hasBacklight ? brightness.devices[0].percent : 50
|
||||
enabled: dashboard.hasBacklight && !brightness.busy
|
||||
Accessible.name: "Яркость"
|
||||
onPressedChanged: {
|
||||
if (!pressed && dashboard.hasBacklight)
|
||||
brightness.setBrightness(brightness.devices[0].name, Math.round(value))
|
||||
}
|
||||
}
|
||||
Text { text: dashboard.hasBacklight ? brightness.devices[0].percent + "%" : ""; color: Theme.foreground; font.pixelSize: 11 }
|
||||
}
|
||||
}
|
||||
Rectangle {
|
||||
visible: dashboard.hasAudio
|
||||
Layout.fillWidth: true
|
||||
Layout.preferredHeight: visible ? 48 : 0
|
||||
radius: 24
|
||||
color: Theme.surfaceHigh
|
||||
RowLayout {
|
||||
anchors.fill: parent
|
||||
anchors.leftMargin: 12
|
||||
anchors.rightMargin: 12
|
||||
spacing: 8
|
||||
ToolButton {
|
||||
text: dashboard.hasAudio && Hardware.sink.audio.muted ? "♩" : "♫"
|
||||
Accessible.name: "Включить или выключить звук"
|
||||
onClicked: if (dashboard.hasAudio) Hardware.sink.audio.muted = !Hardware.sink.audio.muted
|
||||
}
|
||||
Slider {
|
||||
Layout.fillWidth: true
|
||||
from: 0; to: 1
|
||||
value: dashboard.hasAudio ? Hardware.sink.audio.volume : 0
|
||||
enabled: dashboard.hasAudio
|
||||
Accessible.name: "Громкость"
|
||||
onMoved: if (dashboard.hasAudio) Hardware.sink.audio.volume = value
|
||||
}
|
||||
Text { text: dashboard.hasAudio ? Math.round(Hardware.sink.audio.volume * 100) + "%" : ""; color: Theme.foreground; font.pixelSize: 11 }
|
||||
}
|
||||
}
|
||||
|
||||
GridLayout {
|
||||
Layout.fillWidth: true
|
||||
columns: 2
|
||||
columnSpacing: 8
|
||||
rowSpacing: 8
|
||||
Tile {
|
||||
visible: Hardware.wifiPresent
|
||||
title: "Wi-Fi"; symbol: "◉"
|
||||
selected: Networking.wifiEnabled
|
||||
usable: Networking.wifiHardwareEnabled
|
||||
onActivated: Networking.wifiEnabled = !Networking.wifiEnabled
|
||||
}
|
||||
Tile {
|
||||
visible: dashboard.hasBluetooth
|
||||
title: "Bluetooth"; symbol: "ᛒ"
|
||||
selected: dashboard.hasBluetooth && Hardware.bluetoothAdapters[0].enabled
|
||||
onActivated: if (dashboard.hasBluetooth) Hardware.bluetoothAdapters[0].enabled = !Hardware.bluetoothAdapters[0].enabled
|
||||
}
|
||||
Tile {
|
||||
title: "Интернет"; symbol: "⌁"
|
||||
selected: Hardware.networkReady
|
||||
onActivated: dashboard.navigate("network")
|
||||
}
|
||||
Tile {
|
||||
title: "Звук"; symbol: "♫"
|
||||
selected: dashboard.hasAudio
|
||||
usable: dashboard.hasAudio
|
||||
onActivated: dashboard.navigate("audio")
|
||||
}
|
||||
Tile {
|
||||
title: "Уведомления"; symbol: "◌"
|
||||
onActivated: dashboard.navigate("notifications")
|
||||
}
|
||||
Tile {
|
||||
title: "Дисплей"; symbol: "▣"
|
||||
onActivated: dashboard.navigate("display")
|
||||
}
|
||||
}
|
||||
Text {
|
||||
visible: brightness.error !== ""
|
||||
Layout.fillWidth: true
|
||||
text: brightness.error
|
||||
color: Theme.foreground
|
||||
wrapMode: Text.Wrap
|
||||
font.pixelSize: 12
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import QtQuick.Controls
|
||||
import QtQuick.Layouts
|
||||
import Quickshell
|
||||
import Quickshell.Wayland
|
||||
import "services"
|
||||
import "components"
|
||||
|
||||
// Desktop-only floating shelf. Window activation uses Wayland toplevel handles.
|
||||
PanelWindow {
|
||||
id: shelf
|
||||
signal navigate(string page)
|
||||
readonly property string mode: Preferences.modeFor(screen)
|
||||
visible: mode === "desktop"
|
||||
anchors { bottom: true; left: true; right: true }
|
||||
implicitHeight: 76
|
||||
color: "transparent"
|
||||
WlrLayershell.namespace: "adaptive-desktop-shelf"
|
||||
WlrLayershell.layer: WlrLayer.Top
|
||||
Rectangle {
|
||||
anchors.horizontalCenter: parent.horizontalCenter
|
||||
anchors.bottom: parent.bottom
|
||||
anchors.bottomMargin: 8
|
||||
width: Math.min(shelf.width - 24, Math.max(330, content.implicitWidth + 28))
|
||||
height: 60
|
||||
radius: 30
|
||||
color: Theme.surface
|
||||
border.color: Theme.outline
|
||||
border.width: 1
|
||||
RowLayout {
|
||||
id: content
|
||||
anchors.centerIn: parent
|
||||
spacing: 6
|
||||
ActionButton { text: "◈"; ToolTip.text: "Все приложения"; ToolTip.visible: hovered; onClicked: shelf.navigate("launcher") }
|
||||
Rectangle { width: 1; height: 28; color: Theme.outline; opacity: 0.5 }
|
||||
Repeater {
|
||||
model: ToplevelManager.toplevels.values
|
||||
ActionButton {
|
||||
required property var modelData
|
||||
readonly property var window: modelData
|
||||
text: window.appId ? window.appId.split(".").pop().slice(0, 14) : "Окно"
|
||||
ToolTip.text: window.title || window.appId || "Приложение"
|
||||
ToolTip.visible: hovered
|
||||
onClicked: window.activate()
|
||||
}
|
||||
}
|
||||
Rectangle { width: 1; height: 28; color: Theme.outline; opacity: 0.5 }
|
||||
ActionButton { text: "▣"; ToolTip.text: "Обзор окон"; ToolTip.visible: hovered; onClicked: shelf.navigate("recent") }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import QtQuick.Controls
|
||||
import QtQuick.Controls.Material
|
||||
import QtQuick.Layouts
|
||||
import "services"
|
||||
|
||||
ScrollView {
|
||||
id: root
|
||||
contentWidth: availableWidth
|
||||
clip: true
|
||||
BrightnessController { id: brightness }
|
||||
DisplayController { id: displays }
|
||||
DisplayPreview { id: preview }
|
||||
ColumnLayout {
|
||||
width: root.availableWidth
|
||||
spacing: 16
|
||||
Label { text: "Дисплей и яркость"; font.pixelSize: 24; font.bold: true; color: Theme.primary }
|
||||
Label {
|
||||
Layout.fillWidth: true
|
||||
text: "Управление подсветкой встроенных дисплеев через brightnessctl. Внешние мониторы DDC/CI пока не поддерживаются."
|
||||
wrapMode: Text.Wrap
|
||||
color: Theme.outline
|
||||
}
|
||||
Label { text: "Подключённые мониторы"; font.pixelSize: 20; font.bold: true; color: Theme.foreground }
|
||||
Label {
|
||||
Layout.fillWidth: true
|
||||
text: "Изменения разрешения, масштаба, ориентации и позиции применяются временно. Если не подтвердить их за 20 секунд, исходные параметры будут восстановлены. Постоянные правила Hyprland не изменяются."
|
||||
wrapMode: Text.Wrap
|
||||
color: Theme.outline
|
||||
}
|
||||
Repeater {
|
||||
model: displays.monitors
|
||||
ColumnLayout {
|
||||
id: monitorCard
|
||||
required property var modelData
|
||||
Layout.fillWidth: true
|
||||
spacing: 4
|
||||
Label {
|
||||
Layout.fillWidth: true
|
||||
text: monitorCard.modelData.name + (monitorCard.modelData.focused ? " · активный" : "")
|
||||
font.bold: true
|
||||
color: Theme.foreground
|
||||
}
|
||||
Label {
|
||||
Layout.fillWidth: true
|
||||
text: monitorCard.modelData.description
|
||||
wrapMode: Text.Wrap
|
||||
color: Theme.outline
|
||||
}
|
||||
Label {
|
||||
text: monitorCard.modelData.width + " × " + monitorCard.modelData.height + " · " + monitorCard.modelData.refreshRate + " Гц · масштаб " + monitorCard.modelData.scale
|
||||
color: Theme.foreground
|
||||
}
|
||||
Label {
|
||||
text: "Позиция: " + monitorCard.modelData.x + ", " + monitorCard.modelData.y + " · transform: " + monitorCard.modelData.transform
|
||||
color: Theme.outline
|
||||
}
|
||||
RowLayout {
|
||||
Layout.fillWidth: true
|
||||
Label { text: "Позиция X:"; color: Theme.foreground }
|
||||
SpinBox {
|
||||
id: posX
|
||||
from: -100000; to: 100000
|
||||
value: monitorCard.modelData.x
|
||||
editable: true
|
||||
enabled: !preview.busy && preview.token === ""
|
||||
}
|
||||
Label { text: "Y:"; color: Theme.foreground }
|
||||
SpinBox {
|
||||
id: posY
|
||||
from: -100000; to: 100000
|
||||
value: monitorCard.modelData.y
|
||||
editable: true
|
||||
enabled: !preview.busy && preview.token === ""
|
||||
}
|
||||
}
|
||||
RowLayout {
|
||||
Layout.fillWidth: true
|
||||
ComboBox {
|
||||
id: modePicker
|
||||
Layout.fillWidth: true
|
||||
model: monitorCard.modelData.availableModes
|
||||
enabled: !preview.busy && preview.token === "" && count > 0
|
||||
}
|
||||
ComboBox {
|
||||
id: scalePicker
|
||||
model: ["1", "1.25", "1.5", "1.75", "2", "2.5", "3"]
|
||||
Component.onCompleted: currentIndex = Math.max(0, model.indexOf(String(monitorCard.modelData.scale)))
|
||||
enabled: !preview.busy && preview.token === ""
|
||||
}
|
||||
ComboBox {
|
||||
id: rotationPicker
|
||||
model: ["0°", "90°", "180°", "270°"]
|
||||
Component.onCompleted: currentIndex = Math.max(0, Math.min(3, Number(monitorCard.modelData.transform)))
|
||||
enabled: !preview.busy && preview.token === ""
|
||||
}
|
||||
Button {
|
||||
text: "Применить"
|
||||
enabled: modePicker.currentText !== "" && !preview.busy && preview.token === ""
|
||||
onClicked: preview.preview(monitorCard.modelData.name, modePicker.currentText.replace("Hz", ""), scalePicker.currentText, rotationPicker.currentIndex, posX.value, posY.value)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Label {
|
||||
Layout.fillWidth: true
|
||||
visible: preview.token !== ""
|
||||
text: "Подтвердите новые параметры дисплея: осталось " + preview.secondsRemaining + " с"
|
||||
wrapMode: Text.Wrap
|
||||
color: Theme.foreground
|
||||
}
|
||||
Button {
|
||||
text: "Сохранить текущие параметры"
|
||||
visible: preview.token !== ""
|
||||
enabled: !preview.busy && preview.secondsRemaining > 0
|
||||
onClicked: preview.confirm()
|
||||
}
|
||||
Label { Layout.fillWidth: true; visible: preview.error !== ""; text: preview.error; wrapMode: Text.Wrap; color: "#d04040" }
|
||||
Label { visible: displays.monitors.length === 0 && displays.error === ""; text: "Мониторы не обнаружены"; color: Theme.outline }
|
||||
Label { Layout.fillWidth: true; visible: displays.error !== ""; text: displays.error; wrapMode: Text.Wrap; color: "#d04040" }
|
||||
Button { text: "Обновить дисплеи"; enabled: !displays.busy; onClicked: displays.refresh() }
|
||||
Label { text: "Яркость"; font.pixelSize: 20; font.bold: true; color: Theme.foreground }
|
||||
Repeater {
|
||||
model: brightness.devices
|
||||
ColumnLayout {
|
||||
id: displayCard
|
||||
required property var modelData
|
||||
Layout.fillWidth: true
|
||||
Label { text: displayCard.modelData.name + " · " + displayCard.modelData.percent + "%"; color: Theme.foreground }
|
||||
Slider {
|
||||
Layout.fillWidth: true
|
||||
from: 1; to: 100; stepSize: 1
|
||||
value: displayCard.modelData.percent
|
||||
enabled: !brightness.busy
|
||||
onMoved: brightness.setBrightness(displayCard.modelData.name, Math.round(value))
|
||||
}
|
||||
}
|
||||
}
|
||||
Label {
|
||||
visible: brightness.devices.length === 0
|
||||
text: "Управляемая подсветка не обнаружена."
|
||||
color: Theme.outline
|
||||
}
|
||||
Label {
|
||||
Layout.fillWidth: true
|
||||
visible: brightness.error !== ""
|
||||
text: brightness.error
|
||||
wrapMode: Text.Wrap
|
||||
color: "#d04040"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
# Material 3 Expressive UI integration
|
||||
|
||||
Desktop uses a ChromeOS-inspired Material 3 Expressive panel, tonal controls and compact right-side notifications/quick settings. Tablet and phone use Android-inspired larger surfaces and full-screen sheets on phone. This is an original adaptation, not an assertion of pixel-perfect Android 17 or GooglebookOS parity.
|
||||
|
||||
The existing Quickshell `NotificationServer` is the sole notifications owner when `ADAPTIVE_SHELL=1` (unless `ADAPTIVE_NOTIFICATIONS=0` explicitly opts out). Hyprland startup does not launch SwayNC in that mode. Do not run SwayNC and Quickshell's notification server together; only one can own `org.freedesktop.Notifications`. In an already-running session, stop SwayNC before starting the Quickshell notification server, then reload Quickshell.
|
||||
|
||||
`ADAPTIVE_SHELL=1 Hyprland` starts the adaptive shell. The original TTY login and Hypridle/Hyprlock are unchanged. If Quickshell fails, launch the legacy session without ADAPTIVE_SHELL.
|
||||
|
||||
Desktop: compact top bar and right-aligned notification/quick-setting cards. Tablet: centered wider sheets. Phone: full-width, full-height sheets. Hardware-driven controls remain governed by existing Hardware/Modems services.
|
||||
|
||||
Runtime validation requires a Hyprland + Quickshell environment. Static checks cannot prove Android 17 visual parity or notification D-Bus ownership in a live session.
|
||||
@@ -0,0 +1,109 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import QtQuick.Controls
|
||||
import QtQuick.Layouts
|
||||
import Quickshell
|
||||
import "services"
|
||||
import "services/Policy.js" as Policy
|
||||
|
||||
Item {
|
||||
id: home
|
||||
signal launchRequested()
|
||||
signal openLauncher()
|
||||
property int pageIndex: 0
|
||||
property bool editing: false
|
||||
readonly property int pageSize: width < 600 ? 12 : 24
|
||||
readonly property var installed: DesktopEntries.applications.values.filter(app => !app.noDisplay)
|
||||
readonly property var favoriteIds: Preferences.data.favorites || []
|
||||
readonly property var pages: Policy.homePages(favoriteIds, pageSize)
|
||||
readonly property var currentIds: pages[Math.min(pageIndex, pages.length - 1)] || []
|
||||
readonly property var currentApps: currentIds.map(id => installed.find(app => app.id === id)).filter(app => app !== undefined)
|
||||
onPagesChanged: if (pageIndex >= pages.length) pageIndex = Math.max(0, pages.length - 1)
|
||||
ColumnLayout {
|
||||
anchors.fill: parent
|
||||
anchors.margins: 16
|
||||
spacing: 14
|
||||
Item { Layout.fillHeight: true }
|
||||
Label {
|
||||
Layout.fillWidth: true
|
||||
horizontalAlignment: Text.AlignHCenter
|
||||
text: "Главный экран"
|
||||
font.pixelSize: 28
|
||||
font.weight: Font.DemiBold
|
||||
color: Theme.foreground
|
||||
}
|
||||
GridView {
|
||||
id: grid
|
||||
Layout.fillWidth: true
|
||||
Layout.preferredHeight: Math.min(540, Math.max(120, Math.ceil(home.currentApps.length / Math.max(1, Math.floor(width / 94))) * 112))
|
||||
clip: true
|
||||
model: home.currentApps
|
||||
cellWidth: width / Math.max(1, Math.floor(width / 94))
|
||||
cellHeight: 112
|
||||
delegate: Item {
|
||||
id: tile
|
||||
required property var modelData
|
||||
width: grid.cellWidth
|
||||
height: grid.cellHeight
|
||||
Column {
|
||||
anchors.centerIn: parent
|
||||
spacing: 7
|
||||
Image {
|
||||
anchors.horizontalCenter: parent.horizontalCenter
|
||||
width: 52; height: 52
|
||||
source: Quickshell.iconPath(tile.modelData.icon, "application-x-executable")
|
||||
fillMode: Image.PreserveAspectFit
|
||||
}
|
||||
Label {
|
||||
width: grid.cellWidth - 8
|
||||
horizontalAlignment: Text.AlignHCenter
|
||||
elide: Text.ElideRight
|
||||
text: tile.modelData.name
|
||||
color: Theme.foreground
|
||||
}
|
||||
}
|
||||
MouseArea {
|
||||
anchors.fill: parent
|
||||
onPressAndHold: home.editing = true
|
||||
onClicked: {
|
||||
if (home.editing) return;
|
||||
tile.modelData.execute();
|
||||
Preferences.recordLaunch(tile.modelData.id);
|
||||
home.launchRequested();
|
||||
}
|
||||
}
|
||||
Row {
|
||||
visible: home.editing
|
||||
anchors.top: parent.top
|
||||
anchors.horizontalCenter: parent.horizontalCenter
|
||||
spacing: 2
|
||||
Button { text: "←"; enabled: Preferences.writable; onClicked: Preferences.moveFavorite(tile.modelData.id, -1) }
|
||||
Button { text: "×"; enabled: Preferences.writable; onClicked: Preferences.toggleFavorite(tile.modelData.id) }
|
||||
Button { text: "→"; enabled: Preferences.writable; onClicked: Preferences.moveFavorite(tile.modelData.id, 1) }
|
||||
}
|
||||
}
|
||||
}
|
||||
RowLayout {
|
||||
Layout.alignment: Qt.AlignHCenter
|
||||
Button { text: "‹"; enabled: home.pageIndex > 0; onClicked: home.pageIndex-- }
|
||||
Label { text: (home.pageIndex + 1) + " / " + home.pages.length; color: Theme.foreground }
|
||||
Button { text: "›"; enabled: home.pageIndex + 1 < home.pages.length; onClicked: home.pageIndex++ }
|
||||
}
|
||||
RowLayout {
|
||||
Layout.alignment: Qt.AlignHCenter
|
||||
Button { text: "Все приложения"; onClicked: home.openLauncher() }
|
||||
Button {
|
||||
text: home.editing ? "Готово" : "Изменить"
|
||||
onClicked: home.editing = !home.editing
|
||||
}
|
||||
}
|
||||
Label {
|
||||
visible: home.favoriteIds.length === 0
|
||||
Layout.alignment: Qt.AlignHCenter
|
||||
text: "Закрепите приложения через ☆ в списке приложений"
|
||||
color: Theme.outline
|
||||
wrapMode: Text.Wrap
|
||||
}
|
||||
Item { Layout.fillHeight: true }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
# Implementation status — 2026-11-17
|
||||
|
||||
## Implemented in this iteration
|
||||
- Read-only ModemManager discovery via `mmcli --output-json`; missing backend and no-modem are distinct.
|
||||
- Dynamic SIM/mobile-network settings section, modem information, and Quick Settings entry.
|
||||
- Basic phone home view with favorites, application launching and App Drawer entry.
|
||||
- Bottom navigation pill with local swipe/hold recognition (NOT global compositor gestures).
|
||||
- Unit tests for modem parser and existing hardware policy.
|
||||
|
||||
## Not implemented / not validated
|
||||
- Full ModemManager controls (APN, PIN, eSIM, data connection), requires authorization and D-Bus integration.
|
||||
- Global left/right back gesture, gestures over fullscreen applications, bottom pill application cycling.
|
||||
- Complete persistent home-screen grids, folders, widgets, multi-page drag/drop.
|
||||
- Recent Apps thumbnails and card swipe interactions, compositor-aware window overview.
|
||||
- Full Settings modules for displays, input, security, power, notifications.
|
||||
- Quickshell secure session lock and fingerprint authentication: current Hyprlock + Hypridle remain untouched.
|
||||
- Real Quickshell/Hyprland runtime testing, ARM device testing and hardware integration.
|
||||
|
||||
## Security
|
||||
Do not replace Hyprlock with a fullscreen QML overlay. Any future locker must implement ext-session-lock-v1 with verified PAM authorization, crash recovery, and robust suspend handling. fprintd enrollment/verification must be performed by a trusted backend, not by the UI.
|
||||
|
||||
## Local tests
|
||||
`cd quickshell && python -m unittest discover -s tests -p 'test_*.py'`
|
||||
`cd quickshell && node tests/hardware_policy_node.cjs`
|
||||
|
||||
The shell still needs manual Quickshell/QML runtime validation before deployment.
|
||||
@@ -0,0 +1,138 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import QtQuick.Controls.Material
|
||||
import QtQuick.Controls
|
||||
import QtQuick.Layouts
|
||||
import Quickshell
|
||||
import "services"
|
||||
import "services/Policy.js" as Policy
|
||||
import "components"
|
||||
|
||||
FocusScope {
|
||||
id: launcher
|
||||
Material.theme: Theme.dark ? Material.Dark : Material.Light
|
||||
Material.accent: Theme.primary
|
||||
signal done()
|
||||
property string category: "all"
|
||||
readonly property bool desktop: width >= 400 && height >= 360
|
||||
readonly property var categories: [
|
||||
{ key: "all", label: "Все" },
|
||||
{ key: "favorites", label: "Избранное" },
|
||||
{ key: "recent", label: "Недавние" }
|
||||
]
|
||||
readonly property var rankedApps: Policy.rankApps(DesktopEntries.applications.values.filter(app => !app.noDisplay && (app.name + " " + app.genericName + " " + app.keywords.join(" ")).toLowerCase().includes(search.text.toLowerCase())), Preferences.data.favorites, Preferences.data.appHistory)
|
||||
readonly property var apps: rankedApps.filter(app => category === "all" ||
|
||||
(category === "favorites" && (Preferences.data.favorites || []).includes(app.id)) ||
|
||||
(category === "recent" && (Preferences.data.appHistory || []).some(entry => (typeof entry === "string" ? entry : entry.id) === app.id)))
|
||||
onVisibleChanged: if (visible) { search.forceActiveFocus(); grid.currentIndex = 0; }
|
||||
function launch(app) {
|
||||
if (app) {
|
||||
app.execute();
|
||||
Preferences.recordLaunch(app.id);
|
||||
done();
|
||||
}
|
||||
}
|
||||
Rectangle {
|
||||
anchors.fill: parent
|
||||
radius: 26
|
||||
color: Theme.surfaceLow
|
||||
}
|
||||
ColumnLayout {
|
||||
anchors.fill: parent
|
||||
anchors.margins: launcher.desktop ? 12 : 0
|
||||
spacing: 10
|
||||
TextField {
|
||||
id: search
|
||||
Layout.fillWidth: true
|
||||
placeholderText: "Поиск в приложениях и интернете"
|
||||
font.pixelSize: 15
|
||||
leftPadding: 18
|
||||
background: Rectangle { radius: 24; color: Theme.surfaceHigh; border.color: Theme.outline; border.width: 1 }
|
||||
focus: true
|
||||
onTextChanged: grid.currentIndex = 0
|
||||
onAccepted: launcher.launch(launcher.apps[Math.max(0, grid.currentIndex)])
|
||||
Keys.onDownPressed: grid.forceActiveFocus()
|
||||
}
|
||||
RowLayout {
|
||||
Layout.fillWidth: true
|
||||
visible: launcher.desktop
|
||||
spacing: 6
|
||||
Repeater {
|
||||
model: launcher.categories
|
||||
delegate: Rectangle {
|
||||
id: chip
|
||||
required property var modelData
|
||||
implicitWidth: chipLabel.implicitWidth + 30
|
||||
implicitHeight: 36
|
||||
radius: 18
|
||||
color: launcher.category === modelData.key ? Theme.secondaryContainer : Theme.surfaceHigh
|
||||
border.width: launcher.category === modelData.key ? 1 : 0
|
||||
border.color: Theme.primary
|
||||
Text {
|
||||
id: chipLabel
|
||||
anchors.centerIn: parent
|
||||
text: chip.modelData.label
|
||||
color: Theme.foreground
|
||||
font.pixelSize: 13
|
||||
font.weight: launcher.category === chip.modelData.key ? Font.DemiBold : Font.Normal
|
||||
}
|
||||
MouseArea {
|
||||
anchors.fill: parent
|
||||
cursorShape: Qt.PointingHandCursor
|
||||
onClicked: { launcher.category = chip.modelData.key; grid.currentIndex = 0; }
|
||||
}
|
||||
}
|
||||
}
|
||||
Item { Layout.fillWidth: true }
|
||||
Text {
|
||||
text: launcher.apps.length + " приложений"
|
||||
color: Theme.outline
|
||||
font.pixelSize: 12
|
||||
}
|
||||
}
|
||||
GridView {
|
||||
id: grid
|
||||
Layout.fillWidth: true
|
||||
Layout.fillHeight: true
|
||||
clip: true
|
||||
model: launcher.visible ? launcher.apps : []
|
||||
cellWidth: width / Math.max(1, Math.floor(width / (launcher.desktop ? 82 : 140)))
|
||||
cellHeight: launcher.desktop ? 90 : 120
|
||||
keyNavigationEnabled: true
|
||||
highlight: Rectangle { color: Theme.surface; radius: 16; border.color: Theme.primary }
|
||||
Keys.onSpacePressed: if (launcher.apps[currentIndex]) Preferences.toggleFavorite(launcher.apps[currentIndex].id)
|
||||
Keys.onReturnPressed: launcher.launch(launcher.apps[currentIndex])
|
||||
delegate: Item {
|
||||
id: tile
|
||||
required property var modelData
|
||||
required property int index
|
||||
width: grid.cellWidth
|
||||
height: grid.cellHeight
|
||||
Rectangle {
|
||||
anchors.fill: parent
|
||||
anchors.margins: 4
|
||||
radius: 18
|
||||
color: tile.index === grid.currentIndex ? Theme.secondaryContainer : "transparent"
|
||||
Behavior on color { ColorAnimation { duration: Theme.duration } }
|
||||
}
|
||||
Column {
|
||||
anchors.centerIn: parent
|
||||
spacing: 8
|
||||
Image { anchors.horizontalCenter: parent.horizontalCenter; width: launcher.desktop ? 40 : 48; height: launcher.desktop ? 40 : 48; fillMode: Image.PreserveAspectFit; source: Quickshell.iconPath(tile.modelData.icon, "application-x-executable") }
|
||||
Text { width: grid.cellWidth - 16; text: tile.modelData.name; font.pixelSize: launcher.desktop ? 11 : 14; color: Theme.foreground; horizontalAlignment: Text.AlignHCenter; elide: Text.ElideRight; textFormat: Text.PlainText }
|
||||
}
|
||||
MouseArea { anchors.fill: parent; cursorShape: Qt.PointingHandCursor; onClicked: { grid.currentIndex = tile.index; launcher.launch(tile.modelData); } }
|
||||
ActionButton {
|
||||
anchors { top: parent.top; right: parent.right }
|
||||
text: (Preferences.data.favorites || []).includes(tile.modelData.id) ? "★" : "☆"
|
||||
enabled: Preferences.writable
|
||||
Accessible.name: "Избранное: " + tile.modelData.name
|
||||
onClicked: Preferences.toggleFavorite(tile.modelData.id)
|
||||
}
|
||||
}
|
||||
ScrollBar.vertical: ScrollBar {}
|
||||
}
|
||||
Label { visible: !launcher.desktop; text: "★ — избранное · Пробел — закрепить выбранное приложение"; Layout.fillWidth: true; wrapMode: Text.Wrap; color: Theme.outline }
|
||||
Label { visible: launcher.apps.length === 0; text: "Приложения не найдены"; color: Theme.foreground }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import QtQuick.Layouts
|
||||
import Quickshell
|
||||
import Quickshell.Wayland
|
||||
import "services"
|
||||
import "components"
|
||||
|
||||
PanelWindow {
|
||||
id: navigation
|
||||
signal navigate(string name)
|
||||
signal cycleApplication(int direction)
|
||||
required property var output
|
||||
screen: output
|
||||
visible: Preferences.modeFor(output) !== "desktop"
|
||||
anchors { left: true; right: true; bottom: true }
|
||||
implicitHeight: 38
|
||||
color: Theme.background
|
||||
WlrLayershell.namespace: "adaptive-navigation"
|
||||
Rectangle {
|
||||
id: pill
|
||||
anchors.centerIn: parent
|
||||
width: 108; height: 5; radius: 3
|
||||
color: Theme.foreground
|
||||
}
|
||||
MouseArea {
|
||||
anchors.fill: parent
|
||||
property real startY: 0
|
||||
property real startX: 0
|
||||
property double startAt: 0
|
||||
onPressed: mouse => { startX = mouse.x; startY = mouse.y; startAt = Date.now(); }
|
||||
onReleased: mouse => {
|
||||
const dy = startY - mouse.y;
|
||||
const dx = mouse.x - startX;
|
||||
// Only gestures that reach this panel are captured. Global edge
|
||||
// interception requires explicit compositor support.
|
||||
const elapsed = Date.now() - startAt;
|
||||
// A horizontal swipe on the navigation handle cycles open windows.
|
||||
if (Math.abs(dx) > 55 && Math.abs(dx) > Math.abs(dy) * 1.3)
|
||||
navigation.cycleApplication(dx < 0 ? 1 : -1);
|
||||
else if (dy > 14 && elapsed >= 450)
|
||||
navigation.navigate("recent");
|
||||
else if (dy > 14)
|
||||
navigation.navigate("home");
|
||||
else if (Math.abs(dx) < 12 && Math.abs(dy) < 12)
|
||||
navigation.navigate("home");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import QtQuick.Controls
|
||||
import QtQuick.Controls.Material
|
||||
import QtQuick.Layouts
|
||||
import "services"
|
||||
|
||||
ScrollView {
|
||||
id: root
|
||||
contentWidth: availableWidth
|
||||
clip: true
|
||||
ColumnLayout {
|
||||
width: root.availableWidth
|
||||
spacing: 14
|
||||
Label { text: "Мобильная сеть и SIM"; font.pixelSize: 22; color: Theme.primary }
|
||||
Label { visible: Modems.error !== ""; text: Modems.error; wrapMode: Text.Wrap; color: Theme.outline; Layout.fillWidth: true }
|
||||
Label { visible: Modems.actionError !== ""; text: Modems.actionError; wrapMode: Text.Wrap; color: Theme.outline; Layout.fillWidth: true }
|
||||
Repeater {
|
||||
model: Modems.devices
|
||||
ColumnLayout {
|
||||
required property var modelData
|
||||
Layout.fillWidth: true
|
||||
Label { text: (modelData.manufacturer || "Модем") + " " + (modelData.model || modelData.id); color: Theme.foreground; font.bold: true }
|
||||
Label { text: "Состояние: " + modelData.state + (modelData.simPresent ? " · SIM обнаружена" : " · SIM не обнаружена"); color: Theme.foreground }
|
||||
Label { text: "Оператор: " + (modelData.operator || "неизвестен") + " · Сигнал: " + modelData.signal + "%"; color: Theme.foreground }
|
||||
RowLayout {
|
||||
Button {
|
||||
text: "Включить модем"
|
||||
enabled: !Modems.actionBusy && modelData.state !== "error"
|
||||
onClicked: Modems.setEnabled(modelData.id, true)
|
||||
}
|
||||
Button {
|
||||
text: "Отключить модем"
|
||||
enabled: !Modems.actionBusy && modelData.state !== "error"
|
||||
onClicked: confirmDisable.open()
|
||||
}
|
||||
Dialog {
|
||||
id: confirmDisable
|
||||
title: "Отключить модем?"
|
||||
modal: true
|
||||
standardButtons: Dialog.Yes | Dialog.Cancel
|
||||
onAccepted: Modems.setEnabled(modelData.id, false)
|
||||
Label { text: "Мобильное соединение может прерваться." }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Label { text: "Мобильные подключения (NetworkManager)"; font.pixelSize: 19; color: Theme.primary }
|
||||
Label { visible: MobileConnections.error !== ""; text: MobileConnections.error; wrapMode: Text.Wrap; color: Theme.outline; Layout.fillWidth: true }
|
||||
TextField { id: profileName; Layout.fillWidth: true; placeholderText: "Имя подключения"; text: "Мобильный интернет"; maximumLength: 64 }
|
||||
TextField { id: apnField; Layout.fillWidth: true; placeholderText: "APN оператора (например, internet)"; maximumLength: 100 }
|
||||
Button {
|
||||
text: "Создать профиль APN"
|
||||
enabled: !MobileConnections.busy && profileName.text.trim().length > 0 && /^[a-zA-Z0-9][a-zA-Z0-9.-]{0,99}$/.test(apnField.text)
|
||||
onClicked: MobileConnections.perform("create", profileName.text.trim(), apnField.text)
|
||||
}
|
||||
Repeater {
|
||||
model: MobileConnections.profiles
|
||||
RowLayout {
|
||||
required property var modelData
|
||||
Layout.fillWidth: true
|
||||
Label { text: modelData.name; color: Theme.foreground; Layout.fillWidth: true; elide: Text.ElideRight }
|
||||
Button { text: "Подключить"; enabled: !MobileConnections.busy; onClicked: MobileConnections.perform("activate", modelData.uuid) }
|
||||
Button { text: "Отключить"; enabled: !MobileConnections.busy; onClicked: MobileConnections.perform("deactivate", modelData.uuid) }
|
||||
Button { text: "Удалить"; enabled: !MobileConnections.busy; onClicked: deleteConfirm.open() }
|
||||
Dialog {
|
||||
id: deleteConfirm
|
||||
title: "Удалить профиль мобильной сети?"
|
||||
modal: true
|
||||
standardButtons: Dialog.Yes | Dialog.Cancel
|
||||
onAccepted: MobileConnections.perform("delete", modelData.uuid)
|
||||
Label { text: "Профиль будет удалён из NetworkManager." }
|
||||
}
|
||||
}
|
||||
}
|
||||
Label { text: "PIN/PUK не запрашиваются и не сохраняются. Подключение выполняется NetworkManager с системной авторизацией; наличие SIM и поддержка модема обязательны."; wrapMode: Text.Wrap; color: Theme.outline; Layout.fillWidth: true }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import QtQuick.Controls
|
||||
import QtQuick.Controls.Material
|
||||
import QtQuick.Layouts
|
||||
import Quickshell
|
||||
import Quickshell.Networking
|
||||
import "services"
|
||||
import "components"
|
||||
|
||||
ScrollView {
|
||||
id: page
|
||||
property bool active: false
|
||||
Material.theme: Theme.dark ? Material.Dark : Material.Light
|
||||
Material.accent: Theme.primary
|
||||
clip: true
|
||||
contentWidth: availableWidth
|
||||
ColumnLayout {
|
||||
width: page.availableWidth
|
||||
spacing: 20
|
||||
Label { text: "Сеть"; font.pixelSize: 24; color: Theme.primary }
|
||||
Label {
|
||||
Layout.fillWidth: true; wrapMode: Text.Wrap; color: Theme.foreground
|
||||
text: Networking.backend === NetworkBackendType.None ? "Сетевой сервис недоступен" : !Networking.canCheckConnectivity ? "Проверка Интернета недоступна" : !Networking.connectivityCheckEnabled ? "Проверка Интернета отключена" : ({0: "Состояние Интернета неизвестно", 1: "Нет подключения к Интернету", 2: "Нужен вход в сеть", 3: "Ограниченное подключение", 4: "Есть доступ к Интернету"})[Networking.connectivity] || "Состояние Интернета неизвестно"
|
||||
}
|
||||
Switch {
|
||||
visible: Hardware.wifiPresent
|
||||
text: Networking.wifiHardwareEnabled ? "Wi-Fi" : "Wi-Fi заблокирован оборудованием"
|
||||
enabled: Networking.wifiHardwareEnabled
|
||||
checked: Networking.wifiEnabled
|
||||
onClicked: Networking.wifiEnabled = checked
|
||||
}
|
||||
Label { visible: Networking.backend !== NetworkBackendType.None && Hardware.networks.length === 0; text: "Сетевые интерфейсы не обнаружены"; color: Theme.outline }
|
||||
Repeater {
|
||||
model: Hardware.networks
|
||||
Rectangle {
|
||||
id: adapter
|
||||
required property var modelData
|
||||
property bool confirmDisconnect: false
|
||||
readonly property bool wifi: modelData?.type === DeviceType.Wifi
|
||||
readonly property bool wired: modelData?.type === DeviceType.Wired
|
||||
Layout.fillWidth: true
|
||||
implicitHeight: content.implicitHeight + 32
|
||||
color: Theme.surface; radius: 20
|
||||
NetworkController { id: networkController; device: adapter.modelData }
|
||||
Binding {
|
||||
target: adapter.wifi ? adapter.modelData : null
|
||||
property: "scannerEnabled"
|
||||
when: adapter.wifi
|
||||
value: page.active && Networking.wifiEnabled && Networking.wifiHardwareEnabled
|
||||
restoreMode: Binding.RestoreBindingOrValue
|
||||
}
|
||||
ColumnLayout {
|
||||
id: content
|
||||
anchors { top: parent.top; left: parent.left; right: parent.right; margins: 16 }
|
||||
spacing: 12
|
||||
Label { text: (adapter.modelData?.name || "") + " · " + (adapter.wifi ? "Wi-Fi" : adapter.wired ? "Ethernet" : "Другой интерфейс"); font.pixelSize: 20; color: Theme.primary; textFormat: Text.PlainText }
|
||||
Label { text: adapter.modelData ? ConnectionState.toString(adapter.modelData.state) : ""; color: Theme.foreground }
|
||||
Label { visible: !!adapter.modelData?.address; text: "MAC: " + adapter.modelData?.address; color: Theme.outline; textFormat: Text.PlainText }
|
||||
Label { visible: !adapter.modelData?.nmManaged; text: "Интерфейс не управляется NetworkManager"; color: Theme.outline; Layout.fillWidth: true; wrapMode: Text.Wrap }
|
||||
Label { visible: adapter.wired; text: adapter.wired ? (adapter.modelData?.hasLink ? "Кабель подключён" : "Кабель не подключён") : ""; color: Theme.foreground }
|
||||
Label { visible: adapter.wired && adapter.modelData?.linkSpeed > 0; text: adapter.wired ? "Скорость линии: " + adapter.modelData?.linkSpeed + " Мбит/с" : ""; color: Theme.outline }
|
||||
Repeater {
|
||||
model: adapter.modelData?.networks || []
|
||||
NetworkCard {
|
||||
required property var modelData
|
||||
Layout.fillWidth: true
|
||||
network: modelData; device: adapter.modelData; controller: networkController
|
||||
active: page.active
|
||||
onEditRequested: Quickshell.execDetached(["nm-connection-editor"])
|
||||
}
|
||||
}
|
||||
BusyIndicator { visible: networkController.busy; running: visible }
|
||||
Label { Layout.fillWidth: true; wrapMode: Text.Wrap; visible: networkController.error !== ""; text: networkController.error; color: "#ffb4ab"; textFormat: Text.PlainText }
|
||||
ActionButton {
|
||||
visible: adapter.modelData?.connected && !adapter.confirmDisconnect
|
||||
text: "Отключить интерфейс…"
|
||||
enabled: adapter.modelData?.nmManaged && !networkController.busy
|
||||
onClicked: adapter.confirmDisconnect = true
|
||||
}
|
||||
Label { visible: adapter.confirmDisconnect; text: "Подтвердите отключение. Соединения через этот интерфейс будут прерваны."; Layout.fillWidth: true; wrapMode: Text.Wrap; color: Theme.foreground }
|
||||
RowLayout {
|
||||
visible: adapter.confirmDisconnect
|
||||
ActionButton { text: "Отключить"; enabled: !networkController.busy; onClicked: { adapter.confirmDisconnect = false; networkController.requestDisconnect(); } }
|
||||
ActionButton { text: "Отмена"; onClicked: adapter.confirmDisconnect = false }
|
||||
}
|
||||
}
|
||||
Connections { target: page; function onActiveChanged() { if (!page.active) adapter.confirmDisconnect = false; } }
|
||||
}
|
||||
}
|
||||
ActionButton { text: "Профили, IP, DNS и VPN…"; onClicked: Quickshell.execDetached(["nm-connection-editor"]) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import QtQuick.Controls.Material
|
||||
import QtQuick.Controls
|
||||
import QtQuick.Layouts
|
||||
import "services"
|
||||
import "components"
|
||||
|
||||
ScrollView {
|
||||
id: center
|
||||
Material.theme: Theme.dark ? Material.Dark : Material.Light
|
||||
Material.accent: Theme.primary
|
||||
contentWidth: availableWidth
|
||||
clip: true
|
||||
ColumnLayout {
|
||||
width: center.availableWidth
|
||||
spacing: 14
|
||||
Label { text: "Центр уведомлений"; font.pixelSize: 24; font.weight: Font.DemiBold; color: Theme.foreground; Layout.fillWidth: true }
|
||||
Switch { text: "Не беспокоить"; checked: Notifications.dnd; enabled: Preferences.writable; onClicked: Notifications.setDnd(checked) }
|
||||
Switch { text: "Сохранять историю уведомлений"; checked: Notifications.saveHistory; enabled: Preferences.writable; onClicked: Notifications.setSaveHistory(checked) }
|
||||
ActionButton { text: "Очистить всё"; enabled: Notifications.items.length + Notifications.history.length > 0; onClicked: Notifications.clear() }
|
||||
Label { visible: Notifications.error !== ""; text: Notifications.error; color: Theme.outline; Layout.fillWidth: true; wrapMode: Text.Wrap }
|
||||
Repeater {
|
||||
model: Notifications.groups
|
||||
ColumnLayout {
|
||||
id: group
|
||||
required property var modelData
|
||||
Layout.fillWidth: true
|
||||
spacing: 8
|
||||
Label { Layout.fillWidth: true; text: group.modelData.name + " · " + group.modelData.entries.length; font.pixelSize: 20; color: Theme.primary; textFormat: Text.PlainText }
|
||||
Repeater {
|
||||
model: group.modelData.entries
|
||||
NotificationCard {
|
||||
required property var modelData
|
||||
Layout.fillWidth: true
|
||||
notification: modelData.notification || null
|
||||
record: modelData.record || null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Label { visible: Notifications.groups.length === 0; text: "Всё чисто — новых уведомлений нет"; color: Theme.foreground }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import QtQuick.Controls
|
||||
import QtQuick.Controls.Material
|
||||
import QtQuick.Layouts
|
||||
import Quickshell
|
||||
import Quickshell.Wayland
|
||||
import "services"
|
||||
import "components"
|
||||
|
||||
PanelWindow {
|
||||
id: overlay
|
||||
property string page: ""
|
||||
signal closeRequested()
|
||||
signal navigate(string name)
|
||||
readonly property string mode: screen ? Preferences.modeFor(screen) : "desktop"
|
||||
visible: page !== ""
|
||||
anchors { top: true; bottom: true; left: true; right: true }
|
||||
exclusionMode: ExclusionMode.Ignore
|
||||
WlrLayershell.layer: WlrLayer.Overlay
|
||||
WlrLayershell.keyboardFocus: WlrKeyboardFocus.Exclusive
|
||||
WlrLayershell.namespace: "adaptive-overlay"
|
||||
color: overlay.mode === "desktop" ? "#22000000" : "#80000000"
|
||||
Material.theme: Theme.dark ? Material.Dark : Material.Light
|
||||
Material.accent: Theme.primary
|
||||
MouseArea { anchors.fill: parent; onClicked: overlay.closeRequested() }
|
||||
Rectangle {
|
||||
id: card
|
||||
anchors.centerIn: parent
|
||||
anchors.horizontalCenterOffset: overlay.mode === "desktop" && (overlay.page === "notifications" || overlay.page === "quick") ? Math.max(0, (overlay.width - width) / 2 - 20) : overlay.mode === "desktop" && overlay.page === "launcher" ? -Math.max(0, (overlay.width - width) / 2 - 20) : 0
|
||||
anchors.verticalCenterOffset: overlay.mode === "desktop" && (["notifications", "quick", "launcher"].includes(overlay.page)) ? -Math.max(0, (overlay.height - height) / 2 - 64) : 0
|
||||
width: overlay.mode === "phone" ? parent.width : Math.min(parent.width - 32, overlay.mode === "tablet" ? 900 : (overlay.page === "launcher" ? 420 : (["notifications", "quick"].includes(overlay.page) ? 390 : 760)))
|
||||
height: overlay.mode === "phone" ? parent.height : Math.min(parent.height - 64, overlay.mode === "desktop" && overlay.page === "quick" ? 420 : overlay.mode === "desktop" && overlay.page === "notifications" ? 680 : (overlay.mode === "desktop" && overlay.page === "launcher" ? 560 : 780))
|
||||
radius: overlay.mode === "phone" ? 0 : 28
|
||||
color: Theme.surfaceLow
|
||||
MouseArea { anchors.fill: parent }
|
||||
ColumnLayout {
|
||||
anchors.fill: parent
|
||||
anchors.margins: overlay.mode === "desktop" ? 14 : 20
|
||||
RowLayout {
|
||||
visible: overlay.mode !== "desktop" || !["launcher", "quick"].includes(overlay.page)
|
||||
Layout.fillWidth: true
|
||||
Text {
|
||||
Layout.fillWidth: true
|
||||
text: ({launcher: "Приложения", settings: "Settings", quick: "Быстрые настройки", recent: "Открытые окна", home: "Главный экран", notifications: "Уведомления", power: "Питание"})[overlay.page] || ""
|
||||
color: Theme.foreground
|
||||
font.pixelSize: overlay.mode === "desktop" ? 25 : 30
|
||||
font.weight: Font.DemiBold
|
||||
}
|
||||
ActionButton { text: "Закрыть"; onClicked: overlay.closeRequested() }
|
||||
}
|
||||
StackLayout {
|
||||
id: content
|
||||
Layout.fillWidth: true
|
||||
Layout.fillHeight: true
|
||||
currentIndex: ["launcher", "settings", "quick", "recent", "power", "notifications", "home"].indexOf(overlay.page)
|
||||
Launcher { onDone: overlay.closeRequested() }
|
||||
Item {}
|
||||
Item {
|
||||
QuickSettings {
|
||||
anchors.fill: parent
|
||||
visible: overlay.mode !== "desktop"
|
||||
onNavigate: name => overlay.navigate(name)
|
||||
}
|
||||
DesktopQuickSettings {
|
||||
anchors.fill: parent
|
||||
visible: overlay.mode === "desktop"
|
||||
onNavigate: name => overlay.navigate(name)
|
||||
}
|
||||
}
|
||||
Recent { onDone: overlay.closeRequested() }
|
||||
Power { onDone: overlay.closeRequested() }
|
||||
NotificationCenter {}
|
||||
Home { onLaunchRequested: overlay.closeRequested(); onOpenLauncher: overlay.navigate("launcher") }
|
||||
}
|
||||
}
|
||||
}
|
||||
Shortcut { sequence: "Escape"; enabled: overlay.visible; onActivated: overlay.closeRequested() }
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import QtQuick.Controls.Material
|
||||
import QtQuick.Controls
|
||||
import QtQuick.Layouts
|
||||
import "services"
|
||||
import "components"
|
||||
|
||||
ColumnLayout {
|
||||
id: power
|
||||
Material.theme: Theme.dark ? Material.Dark : Material.Light
|
||||
Material.accent: Theme.primary
|
||||
signal done()
|
||||
property string pending: ""
|
||||
readonly property var actions: [
|
||||
{id: "lock", title: "Заблокировать", question: ""},
|
||||
{id: "suspend", title: "Сон", question: "Заблокировать компьютер и перейти в сон?"},
|
||||
{id: "logout", title: "Выйти из сессии", question: "Завершить сессию? Несохранённые изменения могут быть потеряны."},
|
||||
{id: "reboot", title: "Перезагрузка", question: "Перезагрузить компьютер?"},
|
||||
{id: "poweroff", title: "Выключение", question: "Выключить компьютер?"}
|
||||
]
|
||||
PowerController {
|
||||
id: controller
|
||||
onSucceeded: action => { power.pending = ""; if (power.visible) power.done(); }
|
||||
}
|
||||
onVisibleChanged: {
|
||||
if (visible) controller.refresh();
|
||||
else pending = "";
|
||||
}
|
||||
spacing: 12
|
||||
Repeater {
|
||||
model: power.actions
|
||||
ColumnLayout {
|
||||
id: row
|
||||
required property var modelData
|
||||
Layout.fillWidth: true
|
||||
ActionButton {
|
||||
text: row.modelData.title + (controller.capabilities[row.modelData.id]?.state === "challenge" ? " · Авторизация" : "")
|
||||
enabled: !controller.busy && controller.available(row.modelData.id)
|
||||
onClicked: {
|
||||
if (row.modelData.id === "lock") controller.start("lock");
|
||||
else power.pending = row.modelData.id;
|
||||
}
|
||||
}
|
||||
Label {
|
||||
visible: !controller.available(row.modelData.id) && !controller.busy
|
||||
text: controller.capabilities[row.modelData.id]?.reason || "Недоступно в текущей сессии"
|
||||
Layout.fillWidth: true; wrapMode: Text.Wrap; color: Theme.outline; textFormat: Text.PlainText
|
||||
}
|
||||
}
|
||||
}
|
||||
Label {
|
||||
Layout.fillWidth: true; wrapMode: Text.Wrap; color: Theme.foreground
|
||||
visible: power.pending !== ""
|
||||
text: power.actions.find(a => a.id === power.pending)?.question || ""
|
||||
}
|
||||
RowLayout {
|
||||
visible: power.pending !== ""
|
||||
ActionButton { text: "Подтвердить"; enabled: !controller.busy; onClicked: controller.start(power.pending) }
|
||||
ActionButton { text: "Отмена"; enabled: !controller.busy; onClicked: power.pending = "" }
|
||||
}
|
||||
BusyIndicator { visible: controller.busy; running: visible }
|
||||
Label { visible: controller.busy; text: "Ожидание ответа системы…"; color: Theme.foreground }
|
||||
Label { Layout.fillWidth: true; wrapMode: Text.Wrap; text: controller.error || controller.capabilityError; visible: text !== ""; color: "#ffb4ab"; textFormat: Text.PlainText }
|
||||
ActionButton { text: "Обновить доступность действий"; enabled: !controller.busy; onClicked: controller.refresh() }
|
||||
Item { Layout.fillHeight: true }
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import QtQuick.Controls.Material
|
||||
import QtQuick.Controls
|
||||
import QtQuick.Layouts
|
||||
import Quickshell
|
||||
import Quickshell.Networking
|
||||
import Quickshell.Bluetooth
|
||||
import "services"
|
||||
import "components"
|
||||
|
||||
ScrollView {
|
||||
id: quick
|
||||
Material.theme: Theme.dark ? Material.Dark : Material.Light
|
||||
Material.accent: Theme.primary
|
||||
signal navigate(string name)
|
||||
clip: true
|
||||
contentWidth: availableWidth
|
||||
BrightnessController { id: brightnessControl }
|
||||
readonly property bool desktop: width >= 350
|
||||
ColumnLayout {
|
||||
width: quick.availableWidth
|
||||
spacing: 10
|
||||
RowLayout {
|
||||
visible: quick.desktop
|
||||
Layout.fillWidth: true
|
||||
Label { text: "Быстрые настройки"; font.pixelSize: 17; font.bold: true; color: Theme.foreground; Layout.fillWidth: true }
|
||||
ActionButton { text: "⚙"; onClicked: quick.navigate("settings") }
|
||||
}
|
||||
Rectangle {
|
||||
visible: quick.desktop
|
||||
Layout.fillWidth: true
|
||||
implicitHeight: 8
|
||||
radius: 4
|
||||
color: Theme.secondaryContainer
|
||||
}
|
||||
Label { visible: quick.desktop; text: "Подключения"; font.pixelSize: 13; color: Theme.outline }
|
||||
Label { visible: !quick.desktop; text: "Сеть"; color: Theme.primary; font.pixelSize: 20 }
|
||||
Rectangle {
|
||||
visible: quick.desktop && (Hardware.wifiPresent || Hardware.bluetoothAdapters.length > 0)
|
||||
Layout.fillWidth: true
|
||||
implicitHeight: 1
|
||||
color: Theme.outline
|
||||
opacity: 0.25
|
||||
}
|
||||
Switch {
|
||||
visible: Hardware.wifiPresent
|
||||
text: Hardware.wifiState === "blocked" ? "Wi-Fi заблокирован оборудованием" : "Wi-Fi"
|
||||
checked: Networking.wifiEnabled
|
||||
enabled: Networking.wifiHardwareEnabled
|
||||
onClicked: Networking.wifiEnabled = checked
|
||||
}
|
||||
Repeater {
|
||||
model: Hardware.wiredDevices
|
||||
ActionButton {
|
||||
required property var modelData
|
||||
Layout.fillWidth: true
|
||||
text: "Ethernet · " + modelData.name + (modelData.connected ? " · подключено" : modelData.hasLink ? " · кабель подключён" : " · нет кабеля")
|
||||
onClicked: quick.navigate("network")
|
||||
}
|
||||
}
|
||||
ActionButton {
|
||||
visible: Hardware.networkReady && (Hardware.networks.length > 0 || Networking.canCheckConnectivity)
|
||||
text: "Сетевые подключения…"
|
||||
onClicked: quick.navigate("network")
|
||||
}
|
||||
ActionButton { visible: Modems.present; text: "Мобильная сеть · " + Modems.devices.length + " модем(ов)"; onClicked: quick.navigate("modem") }
|
||||
Repeater {
|
||||
model: Hardware.bluetoothAdapters
|
||||
Switch {
|
||||
required property var modelData
|
||||
text: "Bluetooth · " + modelData.name
|
||||
checked: modelData.enabled
|
||||
onClicked: modelData.enabled = checked
|
||||
}
|
||||
}
|
||||
ActionButton { visible: Hardware.bluetoothAdapters.length > 0; text: "Устройства Bluetooth"; onClicked: quick.navigate("bluetooth") }
|
||||
// Brightness is hardware-dependent: no dead slider on desktop monitors
|
||||
// without a kernel backlight. Changes are committed on release, avoiding
|
||||
// a burst of brightnessctl processes while dragging.
|
||||
Label {
|
||||
visible: brightnessControl.devices.length > 0
|
||||
text: "Яркость экрана"
|
||||
color: Theme.primary
|
||||
font.pixelSize: 20
|
||||
}
|
||||
Repeater {
|
||||
model: brightnessControl.devices
|
||||
ColumnLayout {
|
||||
id: backlightRow
|
||||
required property var modelData
|
||||
Layout.fillWidth: true
|
||||
spacing: 4
|
||||
Label {
|
||||
Layout.fillWidth: true
|
||||
text: backlightRow.modelData.name + " · " + backlightRow.modelData.percent + "%"
|
||||
color: Theme.foreground
|
||||
elide: Text.ElideRight
|
||||
}
|
||||
Slider {
|
||||
id: brightnessSlider
|
||||
Layout.fillWidth: true
|
||||
from: 1
|
||||
to: 100
|
||||
stepSize: 1
|
||||
value: backlightRow.modelData.percent
|
||||
enabled: !brightnessControl.busy
|
||||
onPressedChanged: {
|
||||
if (!pressed)
|
||||
brightnessControl.setBrightness(backlightRow.modelData.name, Math.round(value))
|
||||
}
|
||||
Accessible.name: "Яркость " + backlightRow.modelData.name
|
||||
}
|
||||
}
|
||||
}
|
||||
Label {
|
||||
visible: brightnessControl.error !== ""
|
||||
Layout.fillWidth: true
|
||||
text: brightnessControl.error
|
||||
wrapMode: Text.Wrap
|
||||
color: Theme.outline
|
||||
}
|
||||
ActionButton {
|
||||
visible: brightnessControl.devices.length > 0
|
||||
text: "Настройки дисплея…"
|
||||
onClicked: quick.navigate("display")
|
||||
}
|
||||
Label { visible: Hardware.sink !== null; text: "Громкость"; color: Theme.primary; font.pixelSize: quick.desktop ? 14 : 20 }
|
||||
RowLayout {
|
||||
visible: Hardware.sink !== null
|
||||
Layout.fillWidth: true
|
||||
ActionButton {
|
||||
text: Hardware.sink?.audio?.muted ? "Включить звук" : "Без звука"
|
||||
onClicked: if (Hardware.sink?.audio) Hardware.sink.audio.muted = !Hardware.sink.audio.muted
|
||||
}
|
||||
Slider {
|
||||
Layout.fillWidth: true
|
||||
from: 0; to: 1
|
||||
value: Hardware.sink?.audio?.volume || 0
|
||||
onMoved: if (Hardware.sink?.audio) Hardware.sink.audio.volume = value
|
||||
}
|
||||
}
|
||||
Switch {
|
||||
visible: Hardware.source !== null
|
||||
text: "Микрофон"
|
||||
checked: Hardware.source?.audio ? !Hardware.source.audio.muted : false
|
||||
onClicked: if (Hardware.source?.audio) Hardware.source.audio.muted = !checked
|
||||
}
|
||||
ActionButton { visible: Hardware.audioReady; text: "Аудиоустройства"; onClicked: quick.navigate("audio") }
|
||||
Repeater {
|
||||
model: Hardware.players
|
||||
ColumnLayout {
|
||||
required property var modelData
|
||||
Layout.fillWidth: true
|
||||
Label { Layout.fillWidth: true; text: modelData.trackTitle || modelData.identity; color: Theme.foreground; elide: Text.ElideRight; textFormat: Text.PlainText }
|
||||
RowLayout {
|
||||
ActionButton { text: "Назад"; enabled: modelData.canGoPrevious; onClicked: modelData.previous() }
|
||||
ActionButton { text: modelData.isPlaying ? "Пауза" : "Играть"; enabled: modelData.canTogglePlaying; onClicked: modelData.togglePlaying() }
|
||||
ActionButton { text: "Далее"; enabled: modelData.canGoNext; onClicked: modelData.next() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import QtQuick.Controls.Material
|
||||
import QtQuick.Controls
|
||||
import QtQuick.Layouts
|
||||
import Quickshell.Wayland
|
||||
import "services"
|
||||
import "services/WindowPolicy.js" as WindowPolicy
|
||||
import "components"
|
||||
|
||||
Item {
|
||||
id: recent
|
||||
Material.theme: Theme.dark ? Material.Dark : Material.Light
|
||||
Material.accent: Theme.primary
|
||||
signal done()
|
||||
readonly property var windows: ToplevelManager.toplevels.values
|
||||
readonly property var filtered: windows.filter(window =>
|
||||
((window.title || "") + " " + (window.appId || "")).toLowerCase().includes(search.text.toLowerCase()))
|
||||
ColumnLayout {
|
||||
anchors.fill: parent
|
||||
spacing: 12
|
||||
Label {
|
||||
Layout.fillWidth: true
|
||||
text: "Открытые приложения · " + recent.windows.length
|
||||
font.pixelSize: 20
|
||||
color: Theme.foreground
|
||||
}
|
||||
TextField {
|
||||
id: search
|
||||
Layout.fillWidth: true
|
||||
placeholderText: "Поиск среди открытых окон"
|
||||
}
|
||||
ScrollView {
|
||||
Layout.fillWidth: true
|
||||
Layout.fillHeight: true
|
||||
contentWidth: availableWidth
|
||||
ColumnLayout {
|
||||
width: parent.width
|
||||
spacing: 10
|
||||
Repeater {
|
||||
model: recent.filtered
|
||||
Rectangle {
|
||||
id: windowCard
|
||||
required property var modelData
|
||||
Layout.fillWidth: true
|
||||
implicitHeight: actions.implicitHeight + 24
|
||||
radius: Theme.radius
|
||||
color: Theme.surfaceHigh
|
||||
// Gesture recognition does not steal taps from the action buttons.
|
||||
DragHandler {
|
||||
id: dismissDrag
|
||||
target: null
|
||||
xAxis.enabled: false
|
||||
onActiveChanged: {
|
||||
if (!active && WindowPolicy.shouldDismissSwipe(activeTranslation.x, activeTranslation.y, windowCard.width))
|
||||
windowCard.modelData.close();
|
||||
}
|
||||
}
|
||||
RowLayout {
|
||||
id: actions
|
||||
anchors.fill: parent
|
||||
anchors.margins: 12
|
||||
spacing: 8
|
||||
ColumnLayout {
|
||||
Layout.fillWidth: true
|
||||
Label {
|
||||
Layout.fillWidth: true
|
||||
text: windowCard.modelData.title || windowCard.modelData.appId || "Окно"
|
||||
color: Theme.foreground
|
||||
elide: Text.ElideRight
|
||||
}
|
||||
Label {
|
||||
Layout.fillWidth: true
|
||||
text: windowCard.modelData.appId || ""
|
||||
color: Theme.outline
|
||||
font.pixelSize: 12
|
||||
elide: Text.ElideRight
|
||||
}
|
||||
}
|
||||
ActionButton { text: "Открыть"; onClicked: { windowCard.modelData.activate(); recent.done(); } }
|
||||
ActionButton { text: "Закрыть"; onClicked: windowCard.modelData.close() }
|
||||
}
|
||||
}
|
||||
}
|
||||
Label {
|
||||
visible: recent.filtered.length === 0
|
||||
text: search.text ? "Окна не найдены" : "Нет открытых окон"
|
||||
color: Theme.foreground
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import QtQuick.Controls.Material
|
||||
import QtQuick.Controls
|
||||
import QtQuick.Layouts
|
||||
import "services"
|
||||
import "services/HardwarePolicy.js" as HardwarePolicy
|
||||
import "components"
|
||||
|
||||
Item {
|
||||
id: settings
|
||||
signal navigate(string name)
|
||||
Material.theme: Theme.dark ? Material.Dark : Material.Light
|
||||
Material.accent: Theme.primary
|
||||
property bool active: visible
|
||||
readonly property bool wide: width >= 700
|
||||
// Keep a stable identifier when devices appear/disappear. Never persist a
|
||||
// numeric index: hotplug would otherwise open an unrelated settings page.
|
||||
property string selectedSection: "appearance"
|
||||
readonly property var sections: HardwarePolicy.visibleSettingsSections(
|
||||
Hardware.outputs.length > 0 || Hardware.inputs.length > 0 || Hardware.sink !== null || Hardware.source !== null,
|
||||
Hardware.networkReady && (Hardware.networks.length > 0 || Hardware.wifiPresent),
|
||||
Hardware.bluetoothAdapters.length > 0, Modems.present, Hardware.batteries.length > 0)
|
||||
readonly property int selectedIndex: HardwarePolicy.sectionIndex(sections, selectedSection)
|
||||
readonly property string currentSection: selectedIndex >= 0 ? selectedSection : "appearance"
|
||||
readonly property int currentPage: HardwarePolicy.pageIndex(currentSection)
|
||||
|
||||
RowLayout {
|
||||
anchors.fill: parent
|
||||
spacing: 24
|
||||
ColumnLayout {
|
||||
visible: settings.wide
|
||||
Layout.preferredWidth: 190
|
||||
Layout.fillHeight: true
|
||||
Repeater {
|
||||
model: settings.sections
|
||||
ActionButton {
|
||||
required property var modelData
|
||||
Layout.fillWidth: true
|
||||
text: modelData.title
|
||||
checked: settings.currentSection === modelData.id
|
||||
onClicked: settings.selectedSection = modelData.id
|
||||
}
|
||||
}
|
||||
Item { Layout.fillHeight: true }
|
||||
}
|
||||
ColumnLayout {
|
||||
Layout.fillWidth: true
|
||||
Layout.fillHeight: true
|
||||
ComboBox {
|
||||
visible: !settings.wide
|
||||
Layout.fillWidth: true
|
||||
textRole: "title"
|
||||
model: settings.sections
|
||||
currentIndex: settings.selectedIndex >= 0 ? settings.selectedIndex : 0
|
||||
onActivated: index => settings.selectedSection = settings.sections[index].id
|
||||
}
|
||||
StackLayout {
|
||||
Layout.fillWidth: true
|
||||
Layout.fillHeight: true
|
||||
currentIndex: settings.currentPage
|
||||
AppearanceSettings { onNavigate: name => settings.navigate(name) }
|
||||
AudioSettings {}
|
||||
NetworkSettings { active: settings.active && settings.currentSection === "network" }
|
||||
WallpaperSettings {}
|
||||
BluetoothSettings { active: settings.active && settings.currentSection === "bluetooth" }
|
||||
ModemSettings {}
|
||||
SystemSettings {}
|
||||
BatterySettings {}
|
||||
DisplaySettings {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import QtQuick.Controls.Material
|
||||
import QtQuick.Layouts
|
||||
import Quickshell
|
||||
import "services"
|
||||
import "components"
|
||||
|
||||
FloatingWindow {
|
||||
id: window
|
||||
signal closeRequested()
|
||||
signal navigate(string name)
|
||||
property alias section: settings.selectedSection
|
||||
title: "Settings"
|
||||
implicitWidth: 1000
|
||||
implicitHeight: 760
|
||||
minimumSize: Qt.size(360, 400)
|
||||
color: Theme.background
|
||||
Material.theme: Theme.dark ? Material.Dark : Material.Light
|
||||
Material.accent: Theme.primary
|
||||
onClosed: closeRequested()
|
||||
ColumnLayout {
|
||||
anchors.fill: parent
|
||||
anchors.margins: 24
|
||||
spacing: 20
|
||||
RowLayout {
|
||||
Layout.fillWidth: true
|
||||
Text { text: "Settings"; color: Theme.foreground; font.pixelSize: 28; Layout.fillWidth: true }
|
||||
ActionButton { text: "Закрыть"; onClicked: window.closeRequested() }
|
||||
}
|
||||
Settings { id: settings; active: window.visible; Layout.fillWidth: true; Layout.fillHeight: true; onNavigate: name => window.navigate(name) }
|
||||
}
|
||||
Shortcut { sequence: "Escape"; onActivated: window.closeRequested() }
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import QtQuick.Controls
|
||||
import QtQuick.Controls.Material
|
||||
import QtQuick.Layouts
|
||||
import "services"
|
||||
|
||||
ScrollView {
|
||||
id: root
|
||||
contentWidth: availableWidth
|
||||
clip: true
|
||||
ColumnLayout {
|
||||
width: root.availableWidth
|
||||
spacing: 12
|
||||
Label { text: "О системе"; font.pixelSize: 24; font.bold: true; color: Theme.primary }
|
||||
Label { text: "Сведения обновляются автоматически. Изменение параметров системы здесь не выполняется."; wrapMode: Text.Wrap; Layout.fillWidth: true; color: Theme.outline }
|
||||
Label { visible: SystemInfo.error.length > 0; text: SystemInfo.error; wrapMode: Text.Wrap; Layout.fillWidth: true }
|
||||
Repeater {
|
||||
model: [
|
||||
{label: "Операционная система", value: SystemInfo.details.os || "—"},
|
||||
{label: "Ядро Linux", value: SystemInfo.details.kernel || "—"},
|
||||
{label: "Архитектура", value: SystemInfo.details.architecture || "—"},
|
||||
{label: "Имя устройства", value: SystemInfo.details.hostname || "—"},
|
||||
{label: "Оперативная память", value: SystemInfo.details.memoryTotalMiB ? (Math.round(SystemInfo.details.memoryTotalMiB / 102.4) / 10) + " ГиБ" : "—"},
|
||||
{label: "Доступная память", value: SystemInfo.details.memoryAvailableMiB ? (Math.round(SystemInfo.details.memoryAvailableMiB / 102.4) / 10) + " ГиБ" : "—"},
|
||||
{label: "Время работы", value: SystemInfo.details.uptimeSeconds !== undefined ? Math.floor(SystemInfo.details.uptimeSeconds / 3600) + " ч " + Math.floor(SystemInfo.details.uptimeSeconds % 3600 / 60) + " мин" : "—"}
|
||||
]
|
||||
ColumnLayout {
|
||||
required property var modelData
|
||||
Layout.fillWidth: true
|
||||
spacing: 2
|
||||
Label { text: modelData.label; font.pixelSize: 12; color: Theme.outline }
|
||||
Label { text: modelData.value; font.pixelSize: 16; color: Theme.foreground; wrapMode: Text.Wrap; Layout.fillWidth: true }
|
||||
}
|
||||
}
|
||||
Button { text: "Обновить"; enabled: !SystemInfo.busy; onClicked: SystemInfo.refresh() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import QtQuick.Controls
|
||||
import Quickshell
|
||||
import Quickshell.Wayland
|
||||
import "services"
|
||||
import "services/NotificationPolicy.js" as Policy
|
||||
import "components"
|
||||
|
||||
PanelWindow {
|
||||
id: toast
|
||||
property var notification: null
|
||||
visible: notification !== null && !Notifications.dnd
|
||||
anchors { top: true; right: true }
|
||||
margins { top: 64; right: 12 }
|
||||
implicitWidth: Math.min(360, screen.width - 24)
|
||||
implicitHeight: labels.implicitHeight + 32
|
||||
exclusionMode: ExclusionMode.Ignore
|
||||
WlrLayershell.layer: WlrLayer.Overlay
|
||||
WlrLayershell.namespace: "adaptive-notification"
|
||||
color: "transparent"
|
||||
Connections {
|
||||
target: Notifications
|
||||
function onPresent(n) {
|
||||
toast.notification = n;
|
||||
hide.stop();
|
||||
const duration = Policy.timeoutMs(n.expireTimeout, n.urgency);
|
||||
// Persistent normal notifications stay in the center, but their popup is bounded.
|
||||
if (n.urgency !== 2) { hide.interval = duration || 6000; hide.start(); }
|
||||
}
|
||||
function onRemoved(id) { if (toast.notification?.id === id) toast.notification = null; }
|
||||
function onDndChanged() { if (Notifications.dnd) { toast.notification = null; hide.stop(); } }
|
||||
}
|
||||
Timer { id: hide; onTriggered: toast.notification = null }
|
||||
|
||||
Rectangle {
|
||||
anchors.fill: parent
|
||||
color: Theme.surfaceHigh
|
||||
radius: Theme.radiusLarge
|
||||
Column {
|
||||
id: labels
|
||||
anchors { left: parent.left; right: parent.right; top: parent.top; margins: 16 }
|
||||
spacing: 8
|
||||
Text { width: parent.width; text: toast.notification?.appName || ""; color: Theme.primary; textFormat: Text.PlainText; elide: Text.ElideRight }
|
||||
ActionButton { text: "Убрать"; onClicked: if (toast.notification) Notifications.dismiss(toast.notification.id) }
|
||||
Text { width: parent.width; text: toast.notification?.summary || ""; color: Theme.foreground; textFormat: Text.PlainText; wrapMode: Text.Wrap; maximumLineCount: 3; elide: Text.ElideRight }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import Quickshell
|
||||
import Quickshell.Wayland
|
||||
import "services"
|
||||
|
||||
PanelWindow {
|
||||
id: wallpaper
|
||||
required property var output
|
||||
readonly property string requested: output ? Wallpapers.sourceFor(output.name) : ""
|
||||
property string committed: ""
|
||||
readonly property size decodeSize: Qt.size(Math.min(4096, (output?.width || 1) * (output?.devicePixelRatio || 1)), Math.min(4096, (output?.height || 1) * (output?.devicePixelRatio || 1)))
|
||||
screen: output
|
||||
anchors { top: true; bottom: true; left: true; right: true }
|
||||
exclusionMode: ExclusionMode.Ignore
|
||||
WlrLayershell.layer: WlrLayer.Background
|
||||
WlrLayershell.keyboardFocus: WlrKeyboardFocus.None
|
||||
WlrLayershell.namespace: "adaptive-wallpaper"
|
||||
color: "transparent"
|
||||
visible: requested !== "" && displayed.status === Image.Ready
|
||||
function report() {
|
||||
if (!output) return;
|
||||
Wallpapers.report(output.name, requested,
|
||||
requested === "" ? "disabled" : candidate.status === Image.Error ? "error" : candidate.status === Image.Ready && displayed.status === Image.Ready ? "ready" : "loading",
|
||||
displayed.status === Image.Ready ? committed : "");
|
||||
}
|
||||
onRequestedChanged: { if (requested === "") committed = ""; report(); }
|
||||
Component.onCompleted: report()
|
||||
Component.onDestruction: if (output) Wallpapers.forget(output.name)
|
||||
// Decode before committing: a missing or unreadable new image preserves the last good image.
|
||||
Image {
|
||||
id: candidate
|
||||
source: wallpaper.requested
|
||||
asynchronous: true
|
||||
visible: false
|
||||
sourceSize: wallpaper.decodeSize
|
||||
onStatusChanged: {
|
||||
if (status === Image.Ready) wallpaper.committed = wallpaper.requested;
|
||||
wallpaper.report();
|
||||
}
|
||||
}
|
||||
Image {
|
||||
id: displayed
|
||||
anchors.fill: parent
|
||||
source: wallpaper.committed
|
||||
sourceSize: wallpaper.decodeSize
|
||||
fillMode: Image.PreserveAspectCrop
|
||||
onStatusChanged: wallpaper.report()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import QtQuick.Controls
|
||||
import QtQuick.Controls.Material
|
||||
import QtQuick.Dialogs
|
||||
import QtQuick.Layouts
|
||||
import Quickshell
|
||||
import "services"
|
||||
import "services/WallpaperPolicy.js" as Policy
|
||||
import "components"
|
||||
|
||||
ScrollView {
|
||||
id: page
|
||||
Material.theme: Theme.dark ? Material.Dark : Material.Light
|
||||
Material.accent: Theme.primary
|
||||
contentWidth: availableWidth
|
||||
clip: true
|
||||
readonly property var outputs: ["*"].concat(Array.from(new Set(Quickshell.screens.map(s => s.name).concat(Object.keys(Preferences.data.wallpapers || {}).filter(name => name !== "*")))))
|
||||
property string output: "*"
|
||||
onOutputsChanged: if (!outputs.includes(output)) output = "*"
|
||||
onOutputChanged: if (initialized) loadSelection()
|
||||
property string selected: ""
|
||||
property string loadedSelection: ""
|
||||
property bool initialized: false
|
||||
function loadSelection() { loadedSelection = Wallpapers.sourceFor(output); choose(loadedSelection); }
|
||||
Connections {
|
||||
target: Preferences
|
||||
function onDataChanged() { if (page.initialized && path.text === page.loadedSelection) page.loadSelection(); }
|
||||
}
|
||||
function choose(value) { selected = value; path.text = value; }
|
||||
FileDialog {
|
||||
id: picker
|
||||
title: "Выбрать обои"
|
||||
nameFilters: ["Изображения (*.png *.jpg *.jpeg *.webp *.bmp *.avif)", "Все файлы (*)"]
|
||||
onAccepted: page.choose(selectedFile.toString())
|
||||
}
|
||||
ColumnLayout {
|
||||
width: page.availableWidth
|
||||
spacing: 16
|
||||
Label { text: "Обои"; font.pixelSize: 24; color: Theme.primary }
|
||||
ComboBox {
|
||||
id: monitor
|
||||
Layout.fillWidth: true
|
||||
model: page.outputs.map(name => name === "*" ? "Общие обои для мониторов" : name + (Quickshell.screens.some(s => s.name === name) ? "" : " (не подключён)"))
|
||||
currentIndex: page.outputs.indexOf(page.output)
|
||||
onActivated: page.output = page.outputs[currentIndex] || "*"
|
||||
Component.onCompleted: { page.initialized = true; page.loadSelection(); }
|
||||
}
|
||||
TextField {
|
||||
id: path
|
||||
Layout.fillWidth: true
|
||||
placeholderText: "Абсолютный путь к изображению"
|
||||
selectByMouse: true
|
||||
onEditingFinished: page.selected = text
|
||||
}
|
||||
ActionButton { text: "Выбрать файл…"; onClicked: picker.open() }
|
||||
Image {
|
||||
id: preview
|
||||
Layout.fillWidth: true
|
||||
Layout.preferredHeight: 220
|
||||
source: {
|
||||
try { return Policy.localUrl(page.selected); } catch (e) { return ""; }
|
||||
}
|
||||
asynchronous: true
|
||||
sourceSize: Qt.size(720, 440)
|
||||
fillMode: Image.PreserveAspectFit
|
||||
visible: source !== ""
|
||||
}
|
||||
Label { visible: preview.status === Image.Error; text: "Не удалось открыть изображение для предпросмотра"; color: "#ffb4ab"; Layout.fillWidth: true; wrapMode: Text.Wrap }
|
||||
ActionButton {
|
||||
text: "Применить"
|
||||
enabled: Preferences.writable
|
||||
onClicked: if (Wallpapers.set(page.output, path.text)) page.loadedSelection = Wallpapers.sourceFor(page.output)
|
||||
}
|
||||
ActionButton {
|
||||
text: "Использовать общие обои"
|
||||
visible: page.output !== "*"
|
||||
enabled: Preferences.writable
|
||||
onClicked: { Wallpapers.inherit(page.output); page.choose(Wallpapers.sourceFor(page.output)); }
|
||||
}
|
||||
ActionButton {
|
||||
text: "Использовать прежний фон"
|
||||
enabled: Preferences.writable
|
||||
onClicked: { Wallpapers.set(page.output, ""); page.choose(""); }
|
||||
}
|
||||
Label { Layout.fillWidth: true; wrapMode: Text.Wrap; visible: (Wallpapers.error || Preferences.error) !== ""; text: Wallpapers.error || Preferences.error; color: Theme.outline }
|
||||
Repeater {
|
||||
model: Quickshell.screens
|
||||
Label {
|
||||
required property var modelData
|
||||
Layout.fillWidth: true
|
||||
wrapMode: Text.Wrap
|
||||
color: Wallpapers.states[modelData.name]?.state === "error" ? "#ffb4ab" : Theme.outline
|
||||
text: modelData.name + ": " + ({ready: "Обои загружены", loading: "Загрузка…", disabled: "Обои оболочки не заданы", error: "Не удалось загрузить изображение. Сохранены последние загруженные обои, если они были."})[Wallpapers.states[modelData.name]?.state || "disabled"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One-shot BlueZ calls with structured errors; no pairing agent or discovery lease."""
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
|
||||
ADAPTER = re.compile(r'/org/bluez/hci[0-9]+')
|
||||
DEVICE = re.compile(r'/org/bluez/hci[0-9]+/dev_(?:[0-9A-Fa-f]{2}_){5}[0-9A-Fa-f]{2}')
|
||||
|
||||
|
||||
class Bluez:
|
||||
def __init__(self):
|
||||
from gi.repository import Gio, GLib
|
||||
self.Gio, self.GLib = Gio, GLib
|
||||
self.bus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None)
|
||||
|
||||
def call(self, path, interface, method, signature=None, args=(), timeout=45000):
|
||||
params = self.GLib.Variant(signature, args) if signature else None
|
||||
return self.bus.call_sync('org.bluez', path, interface, method, params, None,
|
||||
self.Gio.DBusCallFlags.NO_AUTO_START, timeout, None).unpack()
|
||||
|
||||
def status(self):
|
||||
objects = self.call('/', 'org.freedesktop.DBus.ObjectManager', 'GetManagedObjects', timeout=5000)[0]
|
||||
return {'adapterCount': sum('org.bluez.Adapter1' in interfaces for interfaces in objects.values())}
|
||||
|
||||
def power(self, path, enabled):
|
||||
self.call(path, 'org.freedesktop.DBus.Properties', 'Set', '(ssv)',
|
||||
('org.bluez.Adapter1', 'Powered', self.GLib.Variant('b', enabled)))
|
||||
|
||||
def discover(self, path):
|
||||
import signal
|
||||
loop = self.GLib.MainLoop()
|
||||
# GLib delivers these signals without polling while the lease is held.
|
||||
self.GLib.unix_signal_add(self.GLib.PRIORITY_DEFAULT, signal.SIGTERM, lambda: (loop.quit(), False)[1])
|
||||
self.GLib.timeout_add_seconds(60, lambda: (loop.quit(), False)[1])
|
||||
started = False
|
||||
try:
|
||||
self.call(path, 'org.bluez.Adapter1', 'StartDiscovery', timeout=5000)
|
||||
started = True
|
||||
print(json.dumps({'ok': True, 'event': 'started'}), flush=True)
|
||||
loop.run()
|
||||
finally:
|
||||
if started:
|
||||
self.call(path, 'org.bluez.Adapter1', 'StopDiscovery', timeout=5000)
|
||||
|
||||
def connect(self, path): self.call(path, 'org.bluez.Device1', 'Connect')
|
||||
def disconnect(self, path): self.call(path, 'org.bluez.Device1', 'Disconnect')
|
||||
def forget(self, path): self.call(path.rsplit('/', 1)[0], 'org.bluez.Adapter1', 'RemoveDevice', '(o)', (path,))
|
||||
|
||||
|
||||
def execute(action, path='', factory=Bluez):
|
||||
if action == 'status':
|
||||
if path: raise ValueError('status does not accept a device path')
|
||||
return factory().status()
|
||||
if action == 'discover':
|
||||
if not ADAPTER.fullmatch(path): raise ValueError('Invalid BlueZ adapter path')
|
||||
factory().discover(path)
|
||||
elif action in {'power-on', 'power-off'}:
|
||||
|
||||
if not ADAPTER.fullmatch(path): raise ValueError('Invalid BlueZ adapter path')
|
||||
factory().power(path, action == 'power-on')
|
||||
elif action in {'connect', 'disconnect', 'forget'}:
|
||||
if not DEVICE.fullmatch(path): raise ValueError('Invalid BlueZ device path')
|
||||
getattr(factory(), action)(path)
|
||||
else:
|
||||
raise ValueError('Unsupported Bluetooth action')
|
||||
return {}
|
||||
|
||||
|
||||
def main():
|
||||
try:
|
||||
if len(sys.argv) not in {2, 3}: raise ValueError('Expected action and optional BlueZ path')
|
||||
result = execute(sys.argv[1], sys.argv[2] if len(sys.argv) == 3 else '')
|
||||
print(json.dumps({'ok': True, **result}))
|
||||
return 0
|
||||
except Exception as error:
|
||||
print(json.dumps({'ok': False, 'error': str(error)}))
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == '__main__': sys.exit(main())
|
||||
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Unprivileged brightnessctl adapter; never invokes a shell or sudo."""
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
DEVICE = re.compile(r'^[A-Za-z0-9_.:-]{1,128}$')
|
||||
|
||||
|
||||
def run(args):
|
||||
return subprocess.run(['brightnessctl', '--machine-readable', *args], capture_output=True, text=True, timeout=8, check=True).stdout
|
||||
|
||||
|
||||
def parse_devices(output):
|
||||
devices = []
|
||||
for line in output.splitlines():
|
||||
fields = line.split(',')
|
||||
if len(fields) < 5:
|
||||
continue
|
||||
name, kind, current, maximum, percent = (x.strip() for x in fields[:5])
|
||||
if kind != 'backlight' or not DEVICE.fullmatch(name):
|
||||
continue
|
||||
try:
|
||||
current, maximum = int(current), int(maximum)
|
||||
except ValueError:
|
||||
continue
|
||||
if maximum <= 0:
|
||||
continue
|
||||
devices.append({'name': name, 'current': current, 'maximum': maximum,
|
||||
'percent': round(100 * current / maximum)})
|
||||
return devices
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) < 2 or argv[1] not in ('list', 'set'):
|
||||
raise ValueError('Expected list or set')
|
||||
if argv[1] == 'list':
|
||||
return {'ok': True, 'devices': parse_devices(run(['--list']))}
|
||||
if len(argv) != 4 or not DEVICE.fullmatch(argv[2]):
|
||||
raise ValueError('Invalid device')
|
||||
try:
|
||||
value = int(argv[3])
|
||||
except ValueError:
|
||||
raise ValueError('Invalid percentage') from None
|
||||
if not 1 <= value <= 100:
|
||||
raise ValueError('Percentage must be 1..100')
|
||||
known = {item['name'] for item in parse_devices(run(['--list']))}
|
||||
if argv[2] not in known:
|
||||
raise ValueError('Unknown backlight device')
|
||||
run(['--device', argv[2], 'set', f'{value}%'])
|
||||
return {'ok': True, 'devices': parse_devices(run(['--list']))}
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
print(json.dumps(main(sys.argv), ensure_ascii=False))
|
||||
except (ValueError, subprocess.SubprocessError, OSError) as exc:
|
||||
print(json.dumps({'ok': False, 'error': str(exc)}, ensure_ascii=False))
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,142 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Temporary Hyprland monitor changes with fail-safe rollback.
|
||||
|
||||
A detached watcher restores the original monitor rule unless confirmed within 20s.
|
||||
The preview never modifies the user's persistent Hyprland configuration.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
DURATION = 20
|
||||
NAME = re.compile(r'^[A-Za-z0-9_.:-]{1,128}$')
|
||||
MODE = re.compile(r'^(?:preferred|[1-9][0-9]{2,4}x[1-9][0-9]{2,4}@[0-9]{1,3}(?:\.[0-9]{1,3})?)$')
|
||||
SCALE = re.compile(r'^(?:0\.[5-9][0-9]?|[1-3](?:\.[0-9]{1,2})?)$')
|
||||
TOKEN = re.compile(r'^[a-f0-9]{32}$')
|
||||
TRANSFORMS = frozenset(range(8))
|
||||
|
||||
|
||||
def state_dir():
|
||||
base = Path(os.environ.get('XDG_RUNTIME_DIR', '/tmp'))
|
||||
directory = base / f'adaptive-display-{os.getuid()}'
|
||||
directory.mkdir(mode=0o700, exist_ok=True)
|
||||
return directory
|
||||
|
||||
|
||||
def monitor_rule(name, mode, position, scale, transform=None):
|
||||
if not NAME.fullmatch(name) or not MODE.fullmatch(mode) or not SCALE.fullmatch(str(scale)):
|
||||
raise ValueError('Недопустимые параметры монитора')
|
||||
if position != 'auto' and not re.fullmatch(r'-?[0-9]{1,6}x-?[0-9]{1,6}', position):
|
||||
raise ValueError('Недопустимая позиция монитора')
|
||||
if transform is not None:
|
||||
if isinstance(transform, bool) or not isinstance(transform, int) or transform not in TRANSFORMS:
|
||||
raise ValueError('Недопустимая ориентация монитора')
|
||||
return f'{name},{mode},{position},{scale},transform,{transform}'
|
||||
return f'{name},{mode},{position},{scale}'
|
||||
|
||||
|
||||
def run_hypr(rule):
|
||||
subprocess.run(['hyprctl', 'keyword', 'monitor', rule], check=True, capture_output=True, text=True, timeout=8)
|
||||
|
||||
|
||||
def current(name):
|
||||
output = subprocess.run(['hyprctl', '-j', 'monitors', 'all'], check=True, capture_output=True, text=True, timeout=8)
|
||||
for item in json.loads(output.stdout):
|
||||
if item.get('name') == name:
|
||||
return item
|
||||
raise ValueError('Монитор не найден')
|
||||
|
||||
|
||||
def original_rule(item):
|
||||
rate = float(item.get('refreshRate') or 60)
|
||||
mode = f"{int(item['width'])}x{int(item['height'])}@{rate:.2f}"
|
||||
position = f"{int(item.get('x', 0))}x{int(item.get('y', 0))}"
|
||||
return monitor_rule(item['name'], mode, position, str(float(item.get('scale') or 1)), int(item.get('transform') or 0))
|
||||
|
||||
|
||||
def preview(name, mode, scale, transform=None, x=None, y=None):
|
||||
item = current(name)
|
||||
# Preserve physical layout: using "auto" here can unexpectedly move other screens.
|
||||
if (x is None) != (y is None):
|
||||
raise ValueError('Координаты необходимо задавать вместе')
|
||||
if x is None:
|
||||
x, y = int(item.get('x', 0)), int(item.get('y', 0))
|
||||
else:
|
||||
for value in (x, y):
|
||||
if not re.fullmatch(r'-?[0-9]{1,6}', str(value)) or abs(int(value)) > 100000:
|
||||
raise ValueError('Недопустимые координаты монитора')
|
||||
x, y = int(x), int(y)
|
||||
position = f"{x}x{y}"
|
||||
if transform is None:
|
||||
transform = int(item.get('transform') or 0)
|
||||
else:
|
||||
if not re.fullmatch(r'[0-7]', str(transform)):
|
||||
raise ValueError('Недопустимая ориентация монитора')
|
||||
transform = int(transform)
|
||||
rule = monitor_rule(name, mode, position, scale, transform)
|
||||
directory = state_dir()
|
||||
lock = directory / 'active.json'
|
||||
if lock.exists():
|
||||
raise ValueError('Сначала подтвердите или дождитесь отката предыдущего изменения')
|
||||
before = original_rule(item)
|
||||
token = uuid.uuid4().hex
|
||||
# Exclusive create ensures two concurrent previews cannot overwrite the same state.
|
||||
with lock.open('x', encoding='utf-8') as handle:
|
||||
json.dump({'token': token, 'before': before, 'name': name}, handle)
|
||||
try:
|
||||
watcher = subprocess.Popen([sys.executable, str(Path(__file__).resolve()), 'watch', token],
|
||||
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL, start_new_session=True)
|
||||
run_hypr(rule)
|
||||
except Exception:
|
||||
lock.unlink(missing_ok=True)
|
||||
raise
|
||||
return {'ok': True, 'token': token, 'seconds': DURATION, 'watcherPid': watcher.pid}
|
||||
|
||||
|
||||
def confirm(token):
|
||||
if not TOKEN.fullmatch(token):
|
||||
raise ValueError('Недопустимый токен')
|
||||
lock = state_dir() / 'active.json'
|
||||
state = json.loads(lock.read_text(encoding='utf-8'))
|
||||
if state['token'] != token:
|
||||
raise ValueError('Неверный токен подтверждения')
|
||||
lock.unlink()
|
||||
return {'ok': True}
|
||||
|
||||
|
||||
def watch(token):
|
||||
lock = state_dir() / 'active.json'
|
||||
time.sleep(DURATION)
|
||||
try:
|
||||
state = json.loads(lock.read_text(encoding='utf-8'))
|
||||
if state['token'] != token:
|
||||
return {'ok': True}
|
||||
run_hypr(state['before'])
|
||||
lock.unlink(missing_ok=True)
|
||||
except FileNotFoundError:
|
||||
pass # Confirmed before timeout.
|
||||
return {'ok': True}
|
||||
|
||||
|
||||
def main(args):
|
||||
if len(args) in (4, 5, 7) and args[0] == 'preview':
|
||||
return preview(*args[1:])
|
||||
if len(args) == 2 and args[0] == 'confirm':
|
||||
return confirm(args[1])
|
||||
if len(args) == 2 and args[0] == 'watch':
|
||||
return watch(args[1])
|
||||
raise ValueError('Неизвестная операция')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
print(json.dumps(main(sys.argv[1:]), ensure_ascii=False))
|
||||
except (ValueError, OSError, KeyError, subprocess.SubprocessError, json.JSONDecodeError) as error:
|
||||
print(json.dumps({'ok': False, 'error': str(error)}, ensure_ascii=False))
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read-only Hyprland display inventory. No shell, privilege escalation or writes."""
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
def normalize(monitors):
|
||||
if not isinstance(monitors, list):
|
||||
raise ValueError('Expected monitor array')
|
||||
result = []
|
||||
for monitor in monitors:
|
||||
if not isinstance(monitor, dict) or not isinstance(monitor.get('name'), str):
|
||||
continue
|
||||
name = monitor['name']
|
||||
if not name or len(name) > 128:
|
||||
continue
|
||||
result.append({
|
||||
'name': name,
|
||||
'description': str(monitor.get('description') or name)[:256],
|
||||
'width': int(monitor.get('width') or 0),
|
||||
'height': int(monitor.get('height') or 0),
|
||||
'refreshRate': round(float(monitor.get('refreshRate') or 0), 2),
|
||||
'scale': float(monitor.get('scale') or 1),
|
||||
'transform': int(monitor.get('transform') or 0),
|
||||
'focused': bool(monitor.get('focused', False)),
|
||||
'x': int(monitor.get('x') or 0),
|
||||
'y': int(monitor.get('y') or 0),
|
||||
'availableModes': [str(mode)[:80] for mode in monitor.get('availableModes', []) if isinstance(mode, str)][:128],
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
def main(args):
|
||||
if args != ['list']:
|
||||
raise ValueError('Only list is supported')
|
||||
output = subprocess.run(['hyprctl', '-j', 'monitors', 'all'], capture_output=True, text=True, timeout=8, check=True)
|
||||
return {'ok': True, 'monitors': normalize(json.loads(output.stdout))}
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
print(json.dumps(main(sys.argv[1:]), ensure_ascii=False))
|
||||
except (ValueError, OSError, subprocess.SubprocessError, json.JSONDecodeError) as error:
|
||||
print(json.dumps({'ok': False, 'error': str(error)}, ensure_ascii=False))
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Observe compositor-confirmed locks; never acquire or release a session lock itself."""
|
||||
import select
|
||||
import shutil
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
|
||||
class LockObserver:
|
||||
def __init__(self):
|
||||
from pywayland.client import Display
|
||||
from protocols.hyprland_lock_notify_v1 import HyprlandLockNotifierV1
|
||||
self.display = Display()
|
||||
self.manager = None
|
||||
self.notification = None
|
||||
self.locked = False
|
||||
try:
|
||||
self.display.connect()
|
||||
self.registry = self.display.get_registry()
|
||||
def global_found(registry, name, interface, version):
|
||||
if interface == HyprlandLockNotifierV1.name:
|
||||
self.manager = registry.bind(name, HyprlandLockNotifierV1, 1)
|
||||
self.registry.dispatcher['global'] = global_found
|
||||
self.display.roundtrip()
|
||||
if self.manager is None:
|
||||
raise RuntimeError('Hyprland lock-notify is unavailable')
|
||||
self.notification = self.manager.get_lock_notification()
|
||||
self.notification.dispatcher['locked'] = lambda _: self._set_locked(True)
|
||||
self.notification.dispatcher['unlocked'] = lambda _: self._set_locked(False)
|
||||
self.display.roundtrip()
|
||||
except BaseException:
|
||||
self.display.disconnect()
|
||||
raise
|
||||
|
||||
def _set_locked(self, value):
|
||||
self.locked = value
|
||||
|
||||
def ensure_locked(self, timeout=12):
|
||||
if self.locked:
|
||||
self.display.roundtrip()
|
||||
if self.locked:
|
||||
return
|
||||
locker = shutil.which('hyprlock')
|
||||
if not locker:
|
||||
raise RuntimeError('Hyprlock is not installed')
|
||||
# Closing this helper never terminates the independent lock client.
|
||||
child = subprocess.Popen([locker, '--grace', '0'], stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
start_new_session=True)
|
||||
deadline = time.monotonic() + timeout
|
||||
while not self.locked:
|
||||
self.display.dispatch(block=False)
|
||||
if self.locked:
|
||||
break
|
||||
if child.poll() is not None:
|
||||
raise RuntimeError('Hyprlock exited before the compositor confirmed a lock')
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise RuntimeError('Timed out waiting for a compositor-confirmed lock')
|
||||
if select.select([self.display.get_fd()], [], [], min(remaining, .25))[0]:
|
||||
self.display.dispatch(block=True)
|
||||
self.display.roundtrip()
|
||||
if not self.locked:
|
||||
raise RuntimeError('Session unlocked before the power request')
|
||||
|
||||
def close(self):
|
||||
if self.notification:
|
||||
self.notification.destroy()
|
||||
if self.manager:
|
||||
self.manager.destroy()
|
||||
self.display.disconnect()
|
||||
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Constrained NetworkManager GSM profile management; no shell or SIM secrets."""
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
UUID = re.compile(r'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$')
|
||||
APN = re.compile(r'^[a-zA-Z0-9][a-zA-Z0-9.-]{0,99}$')
|
||||
NAME = re.compile(r'^[^\x00-\x1f\x7f]{1,64}$')
|
||||
|
||||
|
||||
def execute(args, runner=subprocess.run):
|
||||
try:
|
||||
proc = runner(['nmcli', '--wait', '15', *args], capture_output=True, text=True, timeout=22, check=False)
|
||||
return {'ok': proc.returncode == 0, 'error': '' if proc.returncode == 0 else (proc.stderr.strip() or 'NetworkManager rejected request')[:300], 'output': proc.stdout}
|
||||
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||
return {'ok': False, 'error': str(exc)[:300], 'output': ''}
|
||||
|
||||
|
||||
def list_profiles(runner=subprocess.run):
|
||||
if not shutil.which('nmcli'):
|
||||
return {'ok': False, 'profiles': [], 'error': 'nmcli not installed'}
|
||||
result = execute(['-g', 'UUID,TYPE,NAME', 'connection', 'show'], runner)
|
||||
if not result['ok']:
|
||||
return {'ok': False, 'profiles': [], 'error': result['error']}
|
||||
profiles = []
|
||||
# UUID and type are ASCII and fixed width; name may contain colons.
|
||||
for line in result['output'].splitlines():
|
||||
parts = line.split(':', 2)
|
||||
if len(parts) != 3 or not UUID.fullmatch(parts[0]) or parts[1] not in ('gsm', 'cdma'):
|
||||
continue
|
||||
profiles.append({'uuid': parts[0], 'name': parts[2], 'type': parts[1]})
|
||||
return {'ok': True, 'profiles': profiles, 'error': ''}
|
||||
|
||||
|
||||
def manage(action, value='', apn='', runner=subprocess.run):
|
||||
if action not in ('create', 'activate', 'deactivate', 'delete'):
|
||||
return {'ok': False, 'error': 'Unsupported action'}
|
||||
if not shutil.which('nmcli'):
|
||||
return {'ok': False, 'error': 'nmcli not installed'}
|
||||
if action == 'create':
|
||||
if not NAME.fullmatch(value) or not APN.fullmatch(apn):
|
||||
return {'ok': False, 'error': 'Invalid profile name or APN'}
|
||||
args = ['connection', 'add', 'type', 'gsm', 'con-name', value, 'apn', apn, 'connection.autoconnect', 'no']
|
||||
else:
|
||||
if not UUID.fullmatch(value):
|
||||
return {'ok': False, 'error': 'Invalid connection UUID'}
|
||||
# Restrict operations to mobile profiles, not arbitrary network connections.
|
||||
profiles = list_profiles(runner)
|
||||
if not profiles['ok']:
|
||||
return {'ok': False, 'error': profiles['error']}
|
||||
if value.lower() not in {p['uuid'].lower() for p in profiles['profiles']}:
|
||||
return {'ok': False, 'error': 'Not a mobile connection'}
|
||||
if action == 'activate':
|
||||
args = ['connection', 'up', 'uuid', value]
|
||||
elif action == 'deactivate':
|
||||
args = ['connection', 'down', 'uuid', value]
|
||||
else:
|
||||
args = ['connection', 'delete', 'uuid', value]
|
||||
result = execute(args, runner)
|
||||
return {'ok': result['ok'], 'error': result['error']}
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if len(sys.argv) < 2:
|
||||
response = {'ok': False, 'error': 'Missing action'}
|
||||
elif sys.argv[1] == 'list' and len(sys.argv) == 2:
|
||||
response = list_profiles()
|
||||
elif len(sys.argv) == 4 and sys.argv[1] == 'create':
|
||||
response = manage('create', sys.argv[2], sys.argv[3])
|
||||
elif len(sys.argv) == 3:
|
||||
response = manage(sys.argv[1], sys.argv[2])
|
||||
else:
|
||||
response = {'ok': False, 'error': 'Invalid arguments'}
|
||||
print(json.dumps(response, ensure_ascii=False))
|
||||
sys.exit(0 if response['ok'] else 1)
|
||||
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Narrow, non-shell ModemManager control surface.
|
||||
|
||||
Only enable/disable is supported. Never accepts PIN/PUK or arbitrary mmcli flags.
|
||||
Authorization is delegated to ModemManager/polkit.
|
||||
"""
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
ID = re.compile(r'^(?:[0-9]{1,5}|/org/freedesktop/ModemManager1/Modem/[0-9]{1,5})$')
|
||||
|
||||
|
||||
def control(modem_id, action, runner=subprocess.run):
|
||||
if not ID.fullmatch(modem_id):
|
||||
return {'ok': False, 'error': 'Invalid modem identifier'}
|
||||
if action not in ('enable', 'disable'):
|
||||
return {'ok': False, 'error': 'Unsupported modem action'}
|
||||
if not shutil.which('mmcli'):
|
||||
return {'ok': False, 'error': 'mmcli not installed'}
|
||||
try:
|
||||
result = runner(['mmcli', '-m', modem_id, '--' + action], capture_output=True,
|
||||
text=True, timeout=25, check=False)
|
||||
return {'ok': result.returncode == 0,
|
||||
'error': '' if result.returncode == 0 else (result.stderr.strip() or 'ModemManager rejected request')[:300]}
|
||||
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||
return {'ok': False, 'error': str(exc)[:300]}
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if len(sys.argv) != 3:
|
||||
result = {'ok': False, 'error': 'Usage: modem_control.py MODEM_ID enable|disable'}
|
||||
else:
|
||||
result = control(sys.argv[1], sys.argv[2])
|
||||
print(json.dumps(result, ensure_ascii=False))
|
||||
sys.exit(0 if result['ok'] else 1)
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read-only ModemManager inventory for the adaptive shell.
|
||||
|
||||
No SIM secrets are read, no privileged actions are attempted. JSON is stable
|
||||
across a missing mmcli, an empty device list, and transient modem removal.
|
||||
"""
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
|
||||
def run(*args):
|
||||
proc = subprocess.run(['mmcli', *args, '--output-json'], capture_output=True,
|
||||
text=True, timeout=8, check=False)
|
||||
if proc.returncode:
|
||||
raise RuntimeError(proc.stderr.strip()[:240] or 'ModemManager unavailable')
|
||||
return json.loads(proc.stdout)
|
||||
|
||||
|
||||
def modem_paths(payload):
|
||||
value = payload.get('modem-list', [])
|
||||
if isinstance(value, dict):
|
||||
value = value.get('modems', [])
|
||||
return [p for p in value if isinstance(p, str) and re.fullmatch(r'/org/freedesktop/ModemManager1/Modem/\d+', p)]
|
||||
|
||||
|
||||
def describe(payload, path):
|
||||
modem = payload.get('modem', {})
|
||||
generic = modem.get('generic', {})
|
||||
threegpp = modem.get('3gpp', {})
|
||||
signal = generic.get('signal-quality', {})
|
||||
if isinstance(signal, dict):
|
||||
signal = signal.get('value', 0)
|
||||
sim = generic.get('sim', '')
|
||||
return {
|
||||
'id': path.rsplit('/', 1)[-1],
|
||||
'manufacturer': str(generic.get('manufacturer', '')),
|
||||
'model': str(generic.get('model', '')),
|
||||
'state': str(generic.get('state', 'unknown')),
|
||||
'signal': signal if isinstance(signal, (int, float)) else 0,
|
||||
'simPresent': isinstance(sim, str) and bool(sim) and sim != '--',
|
||||
'operator': str(threegpp.get('operator-name', '')),
|
||||
}
|
||||
|
||||
|
||||
def snapshot():
|
||||
if not shutil.which('mmcli'):
|
||||
return {'backend': 'unavailable', 'modems': [], 'error': 'mmcli not installed'}
|
||||
try:
|
||||
paths = modem_paths(run('-L'))
|
||||
devices = []
|
||||
for path in paths:
|
||||
try:
|
||||
devices.append(describe(run('-m', path), path))
|
||||
except (RuntimeError, ValueError, subprocess.TimeoutExpired) as exc:
|
||||
devices.append({'id': path.rsplit('/', 1)[-1], 'state': 'error', 'error': str(exc)})
|
||||
return {'backend': 'available', 'modems': devices, 'error': ''}
|
||||
except (RuntimeError, ValueError, subprocess.TimeoutExpired, OSError) as exc:
|
||||
return {'backend': 'error', 'modems': [], 'error': str(exc)}
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print(json.dumps(snapshot(), ensure_ascii=False))
|
||||
@@ -0,0 +1,134 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One-shot desktop power backend. Only `capabilities` is read-only."""
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
METHODS = {'suspend': 'Suspend', 'reboot': 'Reboot', 'poweroff': 'PowerOff'}
|
||||
|
||||
|
||||
class Logind:
|
||||
def __init__(self):
|
||||
from gi.repository import Gio, GLib
|
||||
self.Gio, self.GLib = Gio, GLib
|
||||
self.bus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None)
|
||||
|
||||
def call(self, method, interactive=None):
|
||||
args = None if interactive is None else self.GLib.Variant('(b)', (interactive,))
|
||||
result = self.bus.call_sync('org.freedesktop.login1', '/org/freedesktop/login1',
|
||||
'org.freedesktop.login1.Manager', method, args, None,
|
||||
self.Gio.DBusCallFlags.NONE, 5000 if interactive is None else 60000, None)
|
||||
return result.unpack()
|
||||
|
||||
def can(self, action):
|
||||
return self.call('Can' + METHODS[action])[0]
|
||||
|
||||
def perform(self, action):
|
||||
self.call(METHODS[action], action != "suspend")
|
||||
|
||||
|
||||
def compositor():
|
||||
if not shutil.which('hyprctl') or not os.environ.get('HYPRLAND_INSTANCE_SIGNATURE'):
|
||||
raise RuntimeError('Hyprland session is unavailable')
|
||||
result = subprocess.run(['hyprctl', '-j', 'status'], capture_output=True, text=True, timeout=5, check=True)
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def lock_observer():
|
||||
from lock_observer import LockObserver
|
||||
return LockObserver()
|
||||
|
||||
|
||||
def capabilities(logind_factory=Logind, observer_factory=lock_observer, compositor_query=compositor):
|
||||
result = {'lock': {'state': 'unavailable'}, 'logout': {'state': 'unavailable'}}
|
||||
try:
|
||||
compositor_query()
|
||||
result['logout'] = {'state': 'yes'}
|
||||
except Exception as error:
|
||||
result['logout']['reason'] = str(error)
|
||||
try:
|
||||
observer = observer_factory()
|
||||
try:
|
||||
if shutil.which('hyprlock'):
|
||||
result['lock'] = {'state': 'yes'}
|
||||
else:
|
||||
result['lock']['reason'] = 'Hyprlock is not installed'
|
||||
finally:
|
||||
observer.close()
|
||||
except Exception as error:
|
||||
result['lock']['reason'] = str(error)
|
||||
try:
|
||||
logind = logind_factory()
|
||||
for action in METHODS:
|
||||
try:
|
||||
state = logind.can(action)
|
||||
if state not in {'yes', 'no', 'na', 'challenge'}:
|
||||
raise RuntimeError('Unknown logind capability: ' + str(state))
|
||||
result[action] = {'state': state}
|
||||
if action == 'suspend' and (state == 'challenge' or result['lock']['state'] != 'yes'):
|
||||
result[action]['state'] = 'unavailable'
|
||||
result[action]['reason'] = 'Lock confirmation or pre-lock authorization is unavailable'
|
||||
except Exception as error:
|
||||
result[action] = {'state': 'error', 'reason': str(error)}
|
||||
except Exception as error:
|
||||
for action in METHODS:
|
||||
result[action] = {'state': 'error', 'reason': str(error)}
|
||||
return result
|
||||
|
||||
|
||||
def execute(action, logind_factory=Logind, observer_factory=lock_observer, compositor_query=compositor, run=subprocess.run):
|
||||
if action == 'logout':
|
||||
info = compositor_query()
|
||||
command = ['hyprctl', 'eval', 'hl.dispatch(hl.dsp.exit())'] if info.get('configProvider') == 'lua' else ['hyprctl', 'dispatch', 'exit']
|
||||
run(command, check=True, capture_output=True, text=True, timeout=5)
|
||||
return
|
||||
if action == 'lock':
|
||||
observer = observer_factory()
|
||||
try: observer.ensure_locked()
|
||||
finally: observer.close()
|
||||
return
|
||||
if action not in METHODS:
|
||||
raise ValueError('Unknown power action')
|
||||
logind = logind_factory()
|
||||
state = logind.can(action)
|
||||
if state not in {'yes', 'challenge'}:
|
||||
raise RuntimeError('Power action is unavailable: ' + str(state))
|
||||
if action == 'suspend':
|
||||
if state != 'yes':
|
||||
raise RuntimeError('Suspend requires authorization before locking')
|
||||
observer = observer_factory()
|
||||
try:
|
||||
observer.ensure_locked()
|
||||
logind.perform(action)
|
||||
finally:
|
||||
observer.close()
|
||||
else:
|
||||
logind.perform(action)
|
||||
|
||||
|
||||
def main():
|
||||
# Bound compositor roundtrips and authorization; a failed helper never forces an action.
|
||||
def timed_out(*_):
|
||||
raise TimeoutError('Power request timed out')
|
||||
signal.signal(signal.SIGALRM, timed_out)
|
||||
signal.alarm(85)
|
||||
try:
|
||||
if len(sys.argv) != 2:
|
||||
raise ValueError('Expected capabilities, lock, logout, suspend, reboot or poweroff')
|
||||
if sys.argv[1] == 'capabilities':
|
||||
output = {'ok': True, 'capabilities': capabilities()}
|
||||
else:
|
||||
execute(sys.argv[1])
|
||||
output = {'ok': True}
|
||||
print(json.dumps(output))
|
||||
return 0
|
||||
except Exception as error:
|
||||
print(json.dumps({'ok': False, 'error': str(error)}))
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Strict JSON interface to powerprofilesctl, without shell execution."""
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
PROFILES = ('power-saver', 'balanced', 'performance')
|
||||
|
||||
|
||||
def execute(argv, runner=subprocess.run, which=shutil.which):
|
||||
if not which('powerprofilesctl'):
|
||||
return {'ok': False, 'error': 'powerprofilesctl не установлен'}
|
||||
if len(argv) == 1 and argv[0] == 'get':
|
||||
args = ['powerprofilesctl', 'get']
|
||||
elif len(argv) == 2 and argv[0] == 'set' and argv[1] in PROFILES:
|
||||
args = ['powerprofilesctl', 'set', argv[1]]
|
||||
else:
|
||||
return {'ok': False, 'error': 'Недопустимая команда или профиль'}
|
||||
try:
|
||||
result = runner(args, capture_output=True, text=True, timeout=12, check=False)
|
||||
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||
return {'ok': False, 'error': str(exc)[:300]}
|
||||
if result.returncode:
|
||||
return {'ok': False, 'error': (result.stderr or result.stdout or 'Команда завершилась с ошибкой').strip()[:300]}
|
||||
if argv[0] == 'get':
|
||||
profile = result.stdout.strip()
|
||||
if profile not in PROFILES:
|
||||
return {'ok': False, 'error': 'Неизвестный профиль: ' + profile[:100]}
|
||||
return {'ok': True, 'profile': profile}
|
||||
return {'ok': True, 'profile': argv[1]}
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
response = execute(sys.argv[1:])
|
||||
print(json.dumps(response, ensure_ascii=False))
|
||||
sys.exit(0 if response['ok'] else 1)
|
||||
@@ -0,0 +1,16 @@
|
||||
# Hyprland lock-notify bindings
|
||||
|
||||
Protocol source: https://github.com/hyprwm/hyprland-protocols/blob/main/protocols/hyprland-lock-notify-v1.xml
|
||||
|
||||
Retrieved 2026-11-17. Vendored XML SHA-256: `360589bc58a0a82768b477564f429dc4a8c016ae8311efad12e03f249ac704fc`.
|
||||
The XML and generated Python retain the upstream copyright and BSD license.
|
||||
Only this protocol is generated; the system pywayland package supplies the Wayland core.
|
||||
|
||||
Regenerate from the checked-in XML, without a network request:
|
||||
|
||||
```sh
|
||||
python -m pywayland.scanner -i quickshell/backend/protocols/hyprland-lock-notify-v1.xml -o quickshell/backend/protocols
|
||||
```
|
||||
|
||||
The observer never requests `ext_session_lock_v1` and cannot unlock the session.
|
||||
It observes the compositor's notification after a lock client establishes the lock.
|
||||
@@ -0,0 +1,99 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<protocol name="hyprland_lock_notify_v1">
|
||||
<copyright>
|
||||
Copyright © 2025 Maximilian Seidler
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
3. Neither the name of the copyright holder nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
</copyright>
|
||||
|
||||
<interface name="hyprland_lock_notifier_v1" version="1">
|
||||
<description summary="lock notification manager">
|
||||
This interface allows clients to monitor whether the wayland session is
|
||||
locked or unlocked.
|
||||
</description>
|
||||
|
||||
<request name="destroy" type="destructor">
|
||||
<description summary="destroy the manager">
|
||||
Destroy the manager object. All objects created via this interface
|
||||
remain valid.
|
||||
</description>
|
||||
</request>
|
||||
|
||||
<request name="get_lock_notification">
|
||||
<description summary="create a notification object">
|
||||
Create a new lock notification object.
|
||||
|
||||
If the session is already locked when calling this method,
|
||||
the locked event shall be sent immediately.
|
||||
</description>
|
||||
<arg name="id" type="new_id" interface="hyprland_lock_notification_v1"/>
|
||||
</request>
|
||||
</interface>
|
||||
|
||||
<interface name="hyprland_lock_notification_v1" version="1">
|
||||
<description summary="lock notification">
|
||||
This interface is used by the compositor to send lock notification events
|
||||
to clients.
|
||||
|
||||
Typically the "locked" and "unlocked" events are emitted when a client
|
||||
locks/unlocks the session via ext-session-lock, but the compositor may
|
||||
choose to send notifications for any other locking mechanisms.
|
||||
|
||||
The compositor must notfiy after possible transition periods
|
||||
between locked and unlocked states of the session.
|
||||
In the context of ext-session-lock, that means the "locked" event is
|
||||
expected to be sent after the session-lock client has presented
|
||||
a lock screen frame on every output, which corresponds to the "locked"
|
||||
event of ext-session-lock.
|
||||
</description>
|
||||
|
||||
<request name="destroy" type="destructor">
|
||||
<description summary="destroy the notification object">
|
||||
Destroy the notification object.
|
||||
</description>
|
||||
</request>
|
||||
|
||||
<event name="locked">
|
||||
<description summary="session is locked">
|
||||
This event is sent when the wayland session is locked.
|
||||
|
||||
It's a compositor protocol error to send this event twice without an
|
||||
unlock event in-between.
|
||||
</description>
|
||||
</event>
|
||||
|
||||
<event name="unlocked">
|
||||
<description summary="session is no longer locked">
|
||||
This event is sent when the wayland session is unlocked.
|
||||
|
||||
It's a compositor protocol error to send this event twice without an
|
||||
locked event in-between. It's a compositor protocol error to send this
|
||||
event prior to any locked event.
|
||||
</description>
|
||||
</event>
|
||||
</interface>
|
||||
</protocol>
|
||||
@@ -0,0 +1,160 @@
|
||||
# This file has been autogenerated by the pywayland scanner
|
||||
|
||||
# Copyright © 2025 Maximilian Seidler
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are met:
|
||||
#
|
||||
# 1. Redistributions of source code must retain the above copyright notice, this
|
||||
# list of conditions and the following disclaimer.
|
||||
#
|
||||
# 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
# this list of conditions and the following disclaimer in the documentation
|
||||
# and/or other materials provided with the distribution.
|
||||
#
|
||||
# 3. Neither the name of the copyright holder nor the names of its
|
||||
# contributors may be used to endorse or promote products derived from
|
||||
# this software without specific prior written permission.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pywayland.protocol_core import Argument, ArgumentType, Global, Interface, Proxy, Resource
|
||||
|
||||
|
||||
class HyprlandLockNotificationV1(Interface):
|
||||
"""Lock notification
|
||||
|
||||
This interface is used by the compositor to send lock notification events
|
||||
to clients.
|
||||
|
||||
Typically the "locked" and "unlocked" events are emitted when a client
|
||||
locks/unlocks the session via ext-session-lock, but the compositor may
|
||||
choose to send notifications for any other locking mechanisms.
|
||||
|
||||
The compositor must notfiy after possible transition periods between locked
|
||||
and unlocked states of the session. In the context of ext-session-lock,
|
||||
that means the "locked" event is expected to be sent after the session-lock
|
||||
client has presented a lock screen frame on every output, which corresponds
|
||||
to the "locked" event of ext-session-lock.
|
||||
"""
|
||||
|
||||
name = "hyprland_lock_notification_v1"
|
||||
version = 1
|
||||
|
||||
|
||||
class HyprlandLockNotifierV1(Interface):
|
||||
"""Lock notification manager
|
||||
|
||||
This interface allows clients to monitor whether the wayland session is
|
||||
locked or unlocked.
|
||||
"""
|
||||
|
||||
name = "hyprland_lock_notifier_v1"
|
||||
version = 1
|
||||
|
||||
|
||||
class HyprlandLockNotificationV1Resource(Resource[HyprlandLockNotificationV1]):
|
||||
interface = HyprlandLockNotificationV1
|
||||
|
||||
@HyprlandLockNotificationV1.event()
|
||||
def locked(self) -> None:
|
||||
"""Session is locked
|
||||
|
||||
This event is sent when the wayland session is locked.
|
||||
|
||||
It's a compositor protocol error to send this event twice without an
|
||||
unlock event in-between.
|
||||
"""
|
||||
self._post_event(0)
|
||||
|
||||
@HyprlandLockNotificationV1.event()
|
||||
def unlocked(self) -> None:
|
||||
"""Session is no longer locked
|
||||
|
||||
This event is sent when the wayland session is unlocked.
|
||||
|
||||
It's a compositor protocol error to send this event twice without an
|
||||
locked event in-between. It's a compositor protocol error to send this
|
||||
event prior to any locked event.
|
||||
"""
|
||||
self._post_event(1)
|
||||
|
||||
|
||||
class HyprlandLockNotifierV1Resource(Resource[HyprlandLockNotifierV1]):
|
||||
interface = HyprlandLockNotifierV1
|
||||
|
||||
|
||||
class HyprlandLockNotificationV1Proxy(Proxy[HyprlandLockNotificationV1]):
|
||||
interface = HyprlandLockNotificationV1
|
||||
|
||||
@HyprlandLockNotificationV1.request()
|
||||
def destroy(self) -> None:
|
||||
"""Destroy the notification object
|
||||
|
||||
Destroy the notification object.
|
||||
"""
|
||||
self._marshal(0)
|
||||
self._destroy()
|
||||
|
||||
|
||||
class HyprlandLockNotifierV1Proxy(Proxy[HyprlandLockNotifierV1]):
|
||||
interface = HyprlandLockNotifierV1
|
||||
|
||||
@HyprlandLockNotifierV1.request()
|
||||
def destroy(self) -> None:
|
||||
"""Destroy the manager
|
||||
|
||||
Destroy the manager object. All objects created via this interface
|
||||
remain valid.
|
||||
"""
|
||||
self._marshal(0)
|
||||
self._destroy()
|
||||
|
||||
@HyprlandLockNotifierV1.request(
|
||||
Argument(ArgumentType.NewId, interface=HyprlandLockNotificationV1),
|
||||
)
|
||||
def get_lock_notification(self) -> HyprlandLockNotificationV1Proxy:
|
||||
"""Create a notification object
|
||||
|
||||
Create a new lock notification object.
|
||||
|
||||
If the session is already locked when calling this method, the locked
|
||||
event shall be sent immediately.
|
||||
|
||||
:returns:
|
||||
:class:`~pywayland.protocol.hyprland_lock_notify_v1.HyprlandLockNotificationV1`
|
||||
"""
|
||||
id = self._marshal_constructor(1, HyprlandLockNotificationV1)
|
||||
return id
|
||||
|
||||
|
||||
class HyprlandLockNotificationV1Global(Global[HyprlandLockNotificationV1]):
|
||||
interface = HyprlandLockNotificationV1
|
||||
|
||||
|
||||
class HyprlandLockNotifierV1Global(Global[HyprlandLockNotifierV1]):
|
||||
interface = HyprlandLockNotifierV1
|
||||
|
||||
|
||||
HyprlandLockNotificationV1._gen_c()
|
||||
HyprlandLockNotificationV1.proxy_class = HyprlandLockNotificationV1Proxy
|
||||
HyprlandLockNotificationV1.resource_class = HyprlandLockNotificationV1Resource
|
||||
HyprlandLockNotificationV1.global_class = HyprlandLockNotificationV1Global
|
||||
|
||||
|
||||
HyprlandLockNotifierV1._gen_c()
|
||||
HyprlandLockNotifierV1.proxy_class = HyprlandLockNotifierV1Proxy
|
||||
HyprlandLockNotifierV1.resource_class = HyprlandLockNotifierV1Resource
|
||||
HyprlandLockNotifierV1.global_class = HyprlandLockNotifierV1Global
|
||||
@@ -0,0 +1,57 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read-only system overview. Never execute user-provided commands."""
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def os_release(path='/etc/os-release'):
|
||||
result = {}
|
||||
try:
|
||||
for line in Path(path).read_text(encoding='utf-8').splitlines():
|
||||
if '=' not in line or line.startswith('#'):
|
||||
continue
|
||||
key, value = line.split('=', 1)
|
||||
if key in ('PRETTY_NAME', 'NAME', 'VERSION_ID'):
|
||||
result[key] = value.strip().strip('"')
|
||||
except OSError:
|
||||
pass
|
||||
return result
|
||||
|
||||
|
||||
def memory_kib(path='/proc/meminfo'):
|
||||
values = {}
|
||||
try:
|
||||
for line in Path(path).read_text(encoding='utf-8').splitlines():
|
||||
key, _, val = line.partition(':')
|
||||
if key in ('MemTotal', 'MemAvailable'):
|
||||
values[key] = int(val.strip().split()[0])
|
||||
except (OSError, ValueError, IndexError):
|
||||
pass
|
||||
return values
|
||||
|
||||
|
||||
def uptime_seconds(path='/proc/uptime'):
|
||||
try:
|
||||
return max(0, int(float(Path(path).read_text().split()[0])))
|
||||
except (OSError, ValueError, IndexError):
|
||||
return 0
|
||||
|
||||
|
||||
def snapshot():
|
||||
release = os_release()
|
||||
memory = memory_kib()
|
||||
return {
|
||||
'os': release.get('PRETTY_NAME') or release.get('NAME') or 'Linux',
|
||||
'kernel': platform.release(),
|
||||
'architecture': platform.machine(),
|
||||
'hostname': platform.node(),
|
||||
'memoryTotalMiB': memory.get('MemTotal', 0) // 1024,
|
||||
'memoryAvailableMiB': memory.get('MemAvailable', 0) // 1024,
|
||||
'uptimeSeconds': uptime_seconds(),
|
||||
}
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print(json.dumps(snapshot(), ensure_ascii=False))
|
||||
@@ -0,0 +1,31 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import QtQuick.Controls
|
||||
import "../services"
|
||||
|
||||
Button {
|
||||
id: control
|
||||
implicitHeight: 48
|
||||
implicitWidth: Math.max(48, label.implicitWidth + leftPadding + rightPadding)
|
||||
leftPadding: 14
|
||||
rightPadding: 14
|
||||
topInset: 0
|
||||
bottomInset: 0
|
||||
hoverEnabled: true
|
||||
contentItem: Text {
|
||||
id: label
|
||||
text: control.text
|
||||
color: control.enabled ? (control.checked ? Theme.onPrimaryContainer : Theme.foreground) : Theme.outline
|
||||
font.pixelSize: 14
|
||||
horizontalAlignment: Text.AlignHCenter
|
||||
verticalAlignment: Text.AlignVCenter
|
||||
elide: Text.ElideRight
|
||||
textFormat: Text.PlainText
|
||||
}
|
||||
background: Rectangle {
|
||||
radius: control.checked ? 16 : 24
|
||||
color: control.checked ? Theme.primaryContainer : control.down ? Theme.secondaryContainer : control.hovered ? Theme.surfaceHigh : Theme.surfaceLow
|
||||
border.width: control.activeFocus || control.checked ? 2 : 0
|
||||
border.color: Theme.primary
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import QtQuick.Controls
|
||||
import QtQuick.Layouts
|
||||
import Quickshell.Networking
|
||||
import "../services"
|
||||
|
||||
ColumnLayout {
|
||||
id: card
|
||||
required property var network
|
||||
required property var device
|
||||
required property var controller
|
||||
property bool active: false
|
||||
property bool credentials: false
|
||||
readonly property bool wifi: device?.type === DeviceType.Wifi
|
||||
readonly property bool pskSupported: wifi && [WifiSecurityType.WpaPsk, WifiSecurityType.Wpa2Psk, WifiSecurityType.Sae].includes(network?.security)
|
||||
readonly property bool directConnect: !wifi || network?.known === true || pskSupported || [WifiSecurityType.Open, WifiSecurityType.Owe].includes(network?.security)
|
||||
signal editRequested()
|
||||
function clearSecret() { if (password) password.clear(); credentials = false; }
|
||||
onActiveChanged: if (!active) clearSecret()
|
||||
Connections {
|
||||
target: card.controller
|
||||
function onNeedsSecret(network) { if (network === card.network && card.pskSupported && card.active) card.credentials = true; }
|
||||
}
|
||||
Connections {
|
||||
target: card.network
|
||||
function onConnectedChanged() { if (card.network?.connected) card.clearSecret(); }
|
||||
}
|
||||
Label {
|
||||
Layout.fillWidth: true
|
||||
text: (card.network?.name || "") + (card.network?.connected ? " · Подключено" : "") + (card.wifi ? " · " + Math.round(card.network?.signalStrength * 100) + "%" : "")
|
||||
wrapMode: Text.Wrap; color: Theme.foreground; textFormat: Text.PlainText
|
||||
}
|
||||
Label { visible: card.wifi && !!card.network; text: card.wifi && card.network ? WifiSecurityType.toString(card.network.security) : ""; color: Theme.outline }
|
||||
ActionButton {
|
||||
visible: !!card.network && !card.network.connected
|
||||
text: card.directConnect ? "Подключиться" : "Настроить подключение…"
|
||||
enabled: card.controller?.busy === false && card.device?.nmManaged === true
|
||||
onClicked: {
|
||||
if (!card.directConnect) card.editRequested();
|
||||
else if (!card.network?.known && card.pskSupported) card.credentials = true;
|
||||
else card.controller.requestConnect(card.network);
|
||||
}
|
||||
}
|
||||
TextField {
|
||||
id: password
|
||||
objectName: "networkPassword"
|
||||
visible: card.credentials
|
||||
Layout.fillWidth: true
|
||||
placeholderText: "Пароль Wi-Fi"
|
||||
echoMode: TextInput.Password
|
||||
inputMethodHints: Qt.ImhSensitiveData | Qt.ImhNoPredictiveText | Qt.ImhNoAutoUppercase
|
||||
selectByMouse: false
|
||||
onAccepted: if (text.length && card.controller?.busy === false) {
|
||||
card.controller.requestConnect(card.network, text);
|
||||
clear(); card.credentials = false;
|
||||
}
|
||||
}
|
||||
RowLayout {
|
||||
visible: card.credentials
|
||||
ActionButton {
|
||||
text: "Подключить"
|
||||
enabled: password.text.length > 0 && card.controller?.busy === false
|
||||
onClicked: { card.controller.requestConnect(card.network, password.text); card.clearSecret(); }
|
||||
}
|
||||
ActionButton { text: "Отмена"; onClicked: card.clearSecret() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import QtQuick.Controls
|
||||
import QtQuick.Layouts
|
||||
import "../services"
|
||||
|
||||
Rectangle {
|
||||
id: card
|
||||
property var notification: null
|
||||
property var record: null
|
||||
readonly property var entry: notification || record
|
||||
implicitHeight: content.implicitHeight + 28
|
||||
color: Theme.surfaceHigh
|
||||
radius: Theme.radius
|
||||
ColumnLayout {
|
||||
id: content
|
||||
anchors { top: parent.top; left: parent.left; right: parent.right; margins: 14 }
|
||||
spacing: 8
|
||||
Label {
|
||||
Layout.fillWidth: true
|
||||
visible: card.record !== null
|
||||
text: card.record ? Qt.formatDateTime(new Date(card.record.time), "dd.MM HH:mm") + " · История" : ""
|
||||
color: Theme.outline
|
||||
}
|
||||
Label { Layout.fillWidth: true; text: card.entry?.summary || ""; color: Theme.foreground; wrapMode: Text.Wrap; font.bold: true; textFormat: Text.PlainText }
|
||||
Label { Layout.fillWidth: true; text: card.entry?.body || ""; color: Theme.foreground; wrapMode: Text.Wrap; textFormat: Text.PlainText }
|
||||
Image {
|
||||
source: card.notification?.image || ""
|
||||
visible: source !== ""
|
||||
Layout.preferredWidth: 160; Layout.preferredHeight: 100
|
||||
sourceSize: Qt.size(512, 512)
|
||||
fillMode: Image.PreserveAspectFit
|
||||
}
|
||||
Flow {
|
||||
Layout.fillWidth: true
|
||||
spacing: 8
|
||||
Repeater {
|
||||
model: card.notification?.actions || []
|
||||
ActionButton { required property var modelData; text: modelData.text; onClicked: modelData.invoke() }
|
||||
}
|
||||
ActionButton {
|
||||
text: "Удалить"
|
||||
onClicked: card.notification ? Notifications.dismiss(card.notification.id) : Notifications.removeHistory(card.record.key)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Install only the launcher and Settings entry, with backups; no packages/session changes."""
|
||||
import argparse
|
||||
from datetime import datetime
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import shutil
|
||||
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--apply', action='store_true', help='write files (default: show plan)')
|
||||
args = parser.parse_args()
|
||||
repo = Path(__file__).resolve().parent.parent
|
||||
home = Path.home()
|
||||
data = Path(os.environ.get('XDG_DATA_HOME', home / '.local/share'))
|
||||
state = Path(os.environ.get('XDG_STATE_HOME', home / '.local/state'))
|
||||
launcher = home / '.local/bin/adaptive-shell'
|
||||
exec_path = str(launcher).replace('\\', '\\\\').replace('"', '\\"').replace('`', '\\`').replace('$', '\\$').replace('%', '%%')
|
||||
files = {
|
||||
launcher: '#!/bin/sh\nexec ' + shlex.quote(str(repo / 'hypr/bin/adaptive-shell')) + ' "$@"\n',
|
||||
data / 'applications/adaptive-settings.desktop': '[Desktop Entry]\nType=Application\nName=Settings\nComment=Adaptive shell settings\nExec="' + exec_path + '" settings\nIcon=preferences-system\nTerminal=false\nCategories=Settings;DesktopSettings;\n',
|
||||
}
|
||||
backup = state / 'adaptive-shell/backups' / datetime.now().strftime('%Y%m%d-%H%M%S-%f')
|
||||
for i, (path, contents) in enumerate(files.items()):
|
||||
print(('WRITE ' if args.apply else 'PLAN ') + str(path))
|
||||
if args.apply:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if path.exists() or path.is_symlink():
|
||||
backup.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(path, backup / (str(i) + '-' + path.name), follow_symlinks=True)
|
||||
temporary = path.with_name(path.name + '.adaptive-tmp')
|
||||
with temporary.open('x') as stream:
|
||||
stream.write(contents)
|
||||
temporary.chmod(0o755 if path == launcher else 0o644)
|
||||
temporary.replace(path)
|
||||
if args.apply:
|
||||
print('Backups (if needed):', backup)
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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 = "";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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) }
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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() }
|
||||
}
|
||||
@@ -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() }
|
||||
}
|
||||
@@ -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("Время ожидания истекло. Результат подключения не подтверждён.")
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 : [[]];
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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() }
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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() }
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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["*"] || "");
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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
|
||||
@@ -0,0 +1,113 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import Quickshell
|
||||
import Quickshell.Io
|
||||
import Quickshell.Hyprland
|
||||
import Quickshell.Wayland
|
||||
import "services/WindowPolicy.js" as WindowPolicy
|
||||
import "services"
|
||||
|
||||
ShellRoot {
|
||||
id: shell
|
||||
property string page: ""
|
||||
property bool settingsVisible: false
|
||||
property int lastCycledWindow: -1
|
||||
function cycleApplication(direction) {
|
||||
const windows = WindowPolicy.ordered(ToplevelManager.toplevels.values);
|
||||
const target = WindowPolicy.cycle(windows, lastCycledWindow, direction);
|
||||
if (!target) return;
|
||||
lastCycledWindow = windows.indexOf(target);
|
||||
target.activate();
|
||||
page = "";
|
||||
}
|
||||
property var targetScreen: Quickshell.screens[0] || null
|
||||
function openPage(name, screen) {
|
||||
targetScreen = screen || Quickshell.screens.find(s => s.name === Hyprland.focusedMonitor?.name) || targetScreen || Quickshell.screens[0];
|
||||
if (name === "settings" || name === "audio" || name === "wallpapers" || name === "network" || name === "bluetooth" || name === "modem" || name === "system" || name === "display") {
|
||||
page = "";
|
||||
settingsWindow.section = name === "wallpapers" ? "wallpaper" : name === "settings" ? "appearance" : name;
|
||||
settingsVisible = true;
|
||||
return;
|
||||
}
|
||||
page = page === name ? "" : name;
|
||||
}
|
||||
Connections {
|
||||
target: Quickshell
|
||||
function onScreensChanged() {
|
||||
if (Quickshell.screens.indexOf(shell.targetScreen) < 0) {
|
||||
shell.page = "";
|
||||
shell.targetScreen = Quickshell.screens[0] || null;
|
||||
}
|
||||
}
|
||||
}
|
||||
IpcHandler {
|
||||
target: "shell"
|
||||
function status(): string {
|
||||
return JSON.stringify({page: shell.page, settingsVisible: shell.settingsVisible,
|
||||
targetScreen: shell.targetScreen?.name || "", preferencesWritable: Preferences.writable,
|
||||
preferencesError: Preferences.error, favorites: Preferences.data.favorites || [],
|
||||
notificationsReady: Notifications.ready, notificationGroups: Notifications.groups.length, notificationDnd: Notifications.dnd, notificationPopup: notificationToast.notification?.id || 0,
|
||||
notifications: Notifications.items.map(n => ({id: n.id, summary: n.summary, urgency: n.urgency})),
|
||||
notificationHistoryCount: Notifications.history.length, notificationHistoryError: Notifications.error,
|
||||
wallpapers: Wallpapers.states, wallpaperError: Wallpapers.error,
|
||||
networkBackend: Hardware.networkBackend, networkInterfaces: Hardware.networks.length,
|
||||
audioReady: Hardware.audioReady, outputs: Hardware.outputs.length, inputs: Hardware.inputs.length});
|
||||
}
|
||||
function dnd(value: bool): void { Notifications.setDnd(value); }
|
||||
function dismissNotification(id: int): void { Notifications.dismiss(id); }
|
||||
function notificationAction(id: int, action: string): void { Notifications.invoke(id, action); }
|
||||
function notificationHistory(value: bool): void { Notifications.setSaveHistory(value); }
|
||||
function reload(): void { Quickshell.reload(false); }
|
||||
function clearNotifications(): void { Notifications.clear(); }
|
||||
function launcher(): void { shell.openPage("launcher"); }
|
||||
function audio(): void { shell.openPage("audio"); }
|
||||
function wallpapers(): void { shell.openPage("wallpapers"); }
|
||||
function setWallpaper(output: string, source: string): void { Wallpapers.set(output, source); }
|
||||
function inheritWallpaper(output: string): void { Wallpapers.inherit(output); }
|
||||
function network(): void { shell.openPage("network"); }
|
||||
function bluetooth(): void { shell.openPage("bluetooth"); }
|
||||
function settings(): void { shell.openPage("settings"); }
|
||||
function quickSettings(): void { shell.openPage("quick"); }
|
||||
function notifications(): void { shell.openPage("notifications"); }
|
||||
function recent(): void { shell.openPage("recent"); }
|
||||
function home(): void { shell.openPage("home"); }
|
||||
function power(): void { shell.openPage("power"); }
|
||||
function mode(value: string): void { Preferences.setValue("mode", value); }
|
||||
function theme(value: string): void { Preferences.setValue("theme", value); }
|
||||
function close(): void { shell.page = ""; shell.settingsVisible = false; }
|
||||
}
|
||||
Variants {
|
||||
model: Quickshell.screens
|
||||
Bar {
|
||||
required property var modelData
|
||||
screen: modelData
|
||||
onNavigate: (name) => shell.openPage(name, modelData)
|
||||
}
|
||||
}
|
||||
Variants {
|
||||
model: Quickshell.screens
|
||||
MobileNavigation {
|
||||
required property var modelData
|
||||
output: modelData
|
||||
onNavigate: name => shell.openPage(name, modelData)
|
||||
onCycleApplication: direction => shell.cycleApplication(direction)
|
||||
}
|
||||
}
|
||||
Variants {
|
||||
model: Quickshell.screens
|
||||
Wallpaper { required property var modelData; output: modelData }
|
||||
}
|
||||
SettingsWindow {
|
||||
id: settingsWindow
|
||||
visible: shell.settingsVisible
|
||||
onCloseRequested: shell.settingsVisible = false
|
||||
onNavigate: name => shell.openPage(name)
|
||||
}
|
||||
Toast { id: notificationToast; screen: shell.targetScreen }
|
||||
Overlay {
|
||||
screen: shell.targetScreen
|
||||
page: shell.page
|
||||
onNavigate: name => shell.openPage(name)
|
||||
onCloseRequested: shell.page = ""
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Real controllers and Process, fake helper only; no production Bluetooth singleton."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
with tempfile.TemporaryDirectory(prefix='adaptive-bluetooth-controller-') as tmp:
|
||||
runtime = Path(tmp, 'runtime')
|
||||
runtime.mkdir(mode=0o700)
|
||||
config = Path(tmp, 'config')
|
||||
config.mkdir()
|
||||
shutil.copyfile(root / 'tests/fixtures/bluetooth.qml', config / 'shell.qml')
|
||||
shutil.copyfile(root / 'tests/bluetooth_fake.py', config / 'bluetooth_fake.py')
|
||||
for name in ['BluetoothController.qml', 'BluetoothDiscovery.qml']:
|
||||
shutil.copyfile(root / 'services' / name, config / name)
|
||||
env = dict(os.environ, QT_QPA_PLATFORM='offscreen', XDG_RUNTIME_DIR=str(runtime),
|
||||
XDG_STATE_HOME=tmp, XDG_CACHE_HOME=tmp)
|
||||
result = subprocess.run(['quickshell', '-p', str(config), '--no-color'], env=env,
|
||||
capture_output=True, text=True, timeout=23)
|
||||
logs = result.stdout + result.stderr
|
||||
print(logs)
|
||||
assert result.returncode == 0 and 'BLUETOOTH_TEST_PASS: 14 scenarios' in logs, logs
|
||||
for marker in ['BLUETOOTH_TEST_FAIL', 'Failed to load configuration', 'ReferenceError', 'TypeError', 'Binding loop']:
|
||||
assert marker not in logs, marker
|
||||
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Explicit test command, never a production backend mode."""
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
|
||||
mode, action, *args = sys.argv[1:]
|
||||
if mode == 'stall': time.sleep(10)
|
||||
if mode == 'malformed':
|
||||
print('not json', flush=True)
|
||||
sys.exit(0)
|
||||
if mode == 'failure':
|
||||
print(json.dumps({'ok': False, 'error': 'Mock BlueZ NotReady'}), flush=True)
|
||||
sys.exit(1)
|
||||
if action == 'status':
|
||||
print(json.dumps({'ok': True, 'adapterCount': 2}), flush=True)
|
||||
elif action == 'discover':
|
||||
print(json.dumps({'ok': True, 'event': 'started'}), flush=True)
|
||||
time.sleep(10)
|
||||
else:
|
||||
print(json.dumps({'ok': True}), flush=True)
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import Quickshell
|
||||
import "."
|
||||
|
||||
ShellRoot {
|
||||
id: test
|
||||
property var controller: null
|
||||
property var discovery: null
|
||||
property var adapter: null
|
||||
property int scenario: -1
|
||||
property int step: 0
|
||||
property int successes: 0
|
||||
property bool finished: false
|
||||
readonly property var names: ["status and exact action", "BlueZ error", "malformed response", "watchdog", "invalid action", "close stops own search", "discovery deadline", "foreign search untouched", "disabled adapter", "discovery startup error", "adapter change stops lease", "startup timeout", "close before startup", "missing discovery executable"]
|
||||
Component { id: controls; BluetoothController { backendCommand: ["python3", Quickshell.shellPath("bluetooth_fake.py"), "success"]; timeoutMs: 2000 } }
|
||||
Component { id: scans; BluetoothDiscovery { backendCommand: ["python3", Quickshell.shellPath("bluetooth_fake.py"), "success"]; active: true; startTimeoutMs: 1000 } }
|
||||
Component { id: adapters; QtObject { property bool enabled: true; property bool discovering: false; property string dbusPath: "/org/bluez/hci1" } }
|
||||
Connections {
|
||||
target: test.controller
|
||||
function onSucceeded(action) { test.successes++; }
|
||||
function onBusyChanged() { if (!test.controller.busy) Qt.callLater(test.advance); }
|
||||
}
|
||||
Connections {
|
||||
target: test.discovery
|
||||
function onOwnedChanged() { if (test.discovery.owned) Qt.callLater(test.advance); }
|
||||
function onBusyChanged() { if (!test.discovery.busy) Qt.callLater(test.advance); }
|
||||
function onStoppingChanged() { if (!test.discovery.stopping) Qt.callLater(test.advance); }
|
||||
}
|
||||
function check(value, message) { if (!value) { finished = true; console.error("BLUETOOTH_TEST_FAIL: " + message); Qt.exit(1); throw new Error(message); } }
|
||||
function complete() { console.log("PASS Bluetooth: " + names[scenario]); Qt.callLater(next); }
|
||||
function next() {
|
||||
if (controller) controller.destroy();
|
||||
if (discovery) discovery.destroy();
|
||||
if (adapter) adapter.destroy();
|
||||
controller = null; discovery = null; adapter = null;
|
||||
scenario++; step = 0; successes = 0;
|
||||
if (scenario === names.length) { finished = true; console.log("BLUETOOTH_TEST_PASS: 14 scenarios"); Qt.quit(); return; }
|
||||
if (scenario <= 4) {
|
||||
controller = controls.createObject(test);
|
||||
const mode = ["success", "failure", "malformed", "stall", "success"][scenario];
|
||||
controller.backendCommand = ["python3", Quickshell.shellPath("bluetooth_fake.py"), mode];
|
||||
if (scenario === 3) controller.timeoutMs = 100;
|
||||
if (scenario === 4) { check(!controller.start("bad command", ""), "unknown action accepted"); complete(); return; }
|
||||
check(controller.refresh(), "refresh rejected");
|
||||
} else {
|
||||
adapter = adapters.createObject(test);
|
||||
discovery = scans.createObject(test, {adapter: adapter});
|
||||
if (scenario === 7) {
|
||||
adapter.discovering = true;
|
||||
check(!discovery.start(), "foreign search joined unexpectedly");
|
||||
discovery.active = false;
|
||||
check(adapter.discovering, "foreign search stopped"); complete(); return;
|
||||
}
|
||||
if (scenario === 8) {
|
||||
adapter.enabled = false;
|
||||
check(!discovery.start() && !discovery.busy, "disabled adapter searched"); complete(); return;
|
||||
}
|
||||
if (scenario === 9) discovery.backendCommand = ["python3", Quickshell.shellPath("bluetooth_fake.py"), "failure"];
|
||||
if (scenario === 6) discovery.durationMs = 100;
|
||||
if (scenario === 11 || scenario === 12) {
|
||||
discovery.backendCommand = ["python3", Quickshell.shellPath("bluetooth_fake.py"), "stall"];
|
||||
discovery.startTimeoutMs = 100;
|
||||
}
|
||||
if (scenario === 13) { discovery.backendCommand = ["adaptive-nonexistent-executable"]; discovery.startTimeoutMs = 100; }
|
||||
check(discovery.start(), "discovery rejected");
|
||||
check(!discovery.start(), "duplicate discovery accepted");
|
||||
if (scenario === 12) discovery.active = false;
|
||||
}
|
||||
}
|
||||
function advance() {
|
||||
if (finished) return;
|
||||
if (scenario <= 4) {
|
||||
if (!controller || controller.busy) return;
|
||||
if (scenario === 0) {
|
||||
if (step === 0) {
|
||||
check(controller.readiness === "ready" && controller.adapterCount === 2, "status lost");
|
||||
step = 1;
|
||||
check(controller.start("connect", "/org/bluez/hci1/dev_AA_BB_CC_DD_EE_FF"), "connect rejected");
|
||||
check(!controller.refresh(), "duplicate command accepted"); return;
|
||||
}
|
||||
check(successes === 1 && controller.error === "", "action failed");
|
||||
} else if (scenario === 1) check(controller.error.includes("Mock BlueZ NotReady") && controller.readiness === "unavailable", "backend failure lost");
|
||||
else if (scenario === 2) check(controller.error !== "" && controller.readiness === "unavailable", "invalid response accepted");
|
||||
else if (scenario === 3) check(controller.timedOut && controller.error !== "", "watchdog failed");
|
||||
} else {
|
||||
if (!discovery) return;
|
||||
if (discovery.owned && step === 0) {
|
||||
step = 1;
|
||||
if (scenario === 5) discovery.active = false;
|
||||
else if (scenario === 10) discovery.adapter = null;
|
||||
return;
|
||||
}
|
||||
if (discovery.busy || discovery.stopping) return;
|
||||
if (scenario === 9) check(discovery.error.includes("Mock BlueZ NotReady"), "discovery error lost");
|
||||
else if (scenario === 11 || scenario === 13) check(!discovery.owned && discovery.error !== "", "startup failure not handled");
|
||||
else check(!discovery.owned && discovery.error === "", "discovery cleanup failed");
|
||||
}
|
||||
complete();
|
||||
}
|
||||
Component.onCompleted: Qt.callLater(next)
|
||||
Timer { interval: 18000; running: !test.finished; onTriggered: test.check(false, "harness timeout") }
|
||||
}
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import Quickshell
|
||||
import Quickshell.Networking
|
||||
import "."
|
||||
import "components"
|
||||
|
||||
ShellRoot {
|
||||
id: test
|
||||
property var device: null
|
||||
property var network: null
|
||||
property var controller: null
|
||||
property var card: null
|
||||
property int scenario: -1
|
||||
property int successes: 0
|
||||
property int secretRequests: 0
|
||||
property bool finished: false
|
||||
readonly property var names: ["connect and duplicate prevention", "failure and credentials request", "device removal", "disconnect", "timeout", "unmanaged device", "PSK forwarding", "wrong adapter", "credential field lifecycle"]
|
||||
Component {
|
||||
id: devices
|
||||
QtObject {
|
||||
property bool connected: false
|
||||
property bool nmManaged: true
|
||||
property int type: DeviceType.Wifi
|
||||
property int state: 0
|
||||
property int disconnects: 0
|
||||
function disconnect() { disconnects++; connected = false; }
|
||||
}
|
||||
}
|
||||
Component {
|
||||
id: networks
|
||||
QtObject {
|
||||
property var device: null
|
||||
property bool connected: false
|
||||
property int state: 0
|
||||
property int connects: 0
|
||||
property string name: "Test network"
|
||||
property bool known: false
|
||||
property real signalStrength: 0.8
|
||||
property int security: WifiSecurityType.Wpa2Psk
|
||||
property int pskConnects: 0
|
||||
property string captured: ""
|
||||
signal connectionFailed(int reason)
|
||||
function connect() { connects++; }
|
||||
function connectWithPsk(value) { pskConnects++; captured = value; }
|
||||
}
|
||||
}
|
||||
Component { id: cards; NetworkCard { width: 400; active: true; network: test.network; device: test.device; controller: test.controller } }
|
||||
Component { id: controllers; NetworkController { timeoutMs: 1000 } }
|
||||
Connections {
|
||||
target: test.controller
|
||||
function onSucceeded(action) { test.successes++; }
|
||||
function onNeedsSecret(network) { test.secretRequests++; }
|
||||
function onBusyChanged() { if (test.scenario === 4 && !test.controller.busy) Qt.callLater(test.finishTimeout); }
|
||||
}
|
||||
function check(value, message) { if (!value) { finished = true; console.error("NETWORK_TEST_FAIL: " + message); Qt.exit(1); throw new Error(message); } }
|
||||
function complete() { console.log("PASS network controller: " + names[scenario]); Qt.callLater(next); }
|
||||
function finishTimeout() {
|
||||
check(controller.error !== "", "timeout error missing");
|
||||
check(successes === 0 && device.disconnects === 0, "timeout triggered a mutation or success");
|
||||
complete();
|
||||
}
|
||||
function next() {
|
||||
if (card) { card.destroy(); card = null; }
|
||||
if (controller) controller.destroy();
|
||||
if (network) network.destroy();
|
||||
if (device) device.destroy();
|
||||
controller = null; network = null; device = null;
|
||||
scenario++; successes = 0; secretRequests = 0;
|
||||
if (scenario === names.length) { finished = true; console.log("NETWORK_TEST_PASS: 9 scenarios"); Qt.quit(); return; }
|
||||
device = devices.createObject(test);
|
||||
network = networks.createObject(test, {device: device});
|
||||
controller = controllers.createObject(test, {device: device});
|
||||
if (scenario === 0) {
|
||||
check(controller.requestConnect(network), "connect rejected");
|
||||
check(controller.busy && network.connects === 1, "connect not sent");
|
||||
check(!controller.requestConnect(network), "duplicate request accepted");
|
||||
network.connected = true;
|
||||
check(!controller.busy && successes === 1, "connected state did not complete request");
|
||||
} else if (scenario === 1) {
|
||||
controller.requestConnect(network);
|
||||
network.connectionFailed(ConnectionFailReason.NoSecrets);
|
||||
check(!controller.busy && controller.error !== "", "failure lost");
|
||||
check(secretRequests === 1 && successes === 0, "wrong failure result");
|
||||
} else if (scenario === 2) {
|
||||
controller.requestConnect(network);
|
||||
controller.device = null;
|
||||
check(!controller.busy && controller.error !== "" && successes === 0, "removed device not handled");
|
||||
} else if (scenario === 3) {
|
||||
device.connected = true;
|
||||
check(controller.requestDisconnect(), "disconnect rejected");
|
||||
check(device.disconnects === 1 && !controller.busy && successes === 1, "disconnect did not complete");
|
||||
} else if (scenario === 4) {
|
||||
controller.timeoutMs = 30;
|
||||
controller.requestConnect(network);
|
||||
return;
|
||||
} else if (scenario === 5) {
|
||||
device.nmManaged = false;
|
||||
check(!controller.requestConnect(network) && network.connects === 0, "unmanaged device mutated");
|
||||
} else if (scenario === 6) {
|
||||
check(controller.requestConnect(network, "synthetic-test-key"), "PSK request rejected");
|
||||
check(network.pskConnects === 1 && network.connects === 0 && network.captured === "synthetic-test-key", "PSK not forwarded correctly");
|
||||
network.connectionFailed(ConnectionFailReason.NoSecrets);
|
||||
check(!controller.error.includes("synthetic-test-key"), "PSK leaked into error");
|
||||
} else if (scenario === 7) {
|
||||
network.device = null;
|
||||
check(!controller.requestConnect(network) && network.connects === 0, "wrong adapter accepted");
|
||||
} else if (scenario === 8) {
|
||||
card = cards.createObject(test);
|
||||
const password = findItem(card, "networkPassword");
|
||||
check(password !== null, "credential field not found");
|
||||
card.credentials = true; password.text = "synthetic-test-key";
|
||||
check(password.echoMode === TextInput.Password, "password is not masked");
|
||||
card.active = false;
|
||||
check(password.text === "" && !card.credentials, "password survived page close");
|
||||
card.active = true;
|
||||
controller.requestConnect(network);
|
||||
network.connectionFailed(ConnectionFailReason.NoSecrets);
|
||||
check(card.credentials, "credential prompt not opened");
|
||||
password.text = "synthetic-test-key";
|
||||
network.connected = true;
|
||||
check(password.text === "" && !card.credentials, "password survived connection");
|
||||
}
|
||||
complete();
|
||||
}
|
||||
function findItem(parent, name) {
|
||||
if (parent.objectName === name) return parent;
|
||||
for (const child of parent.children || []) { const found = findItem(child, name); if (found) return found; }
|
||||
return null;
|
||||
}
|
||||
Component.onCompleted: Qt.callLater(next)
|
||||
Timer { interval: 15000; running: !test.finished; onTriggered: test.check(false, "harness timeout") }
|
||||
}
|
||||
Vendored
+69
@@ -0,0 +1,69 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import Quickshell
|
||||
import "."
|
||||
|
||||
ShellRoot {
|
||||
id: test
|
||||
property var instance: null
|
||||
property int scenario: -1
|
||||
property int step: 0
|
||||
property int successes: 0
|
||||
property bool finished: false
|
||||
readonly property var names: ["success and duplicate prevention", "denied capability", "backend error", "malformed response", "watchdog", "invalid action", "missing helper"]
|
||||
Component {
|
||||
id: factory
|
||||
PowerController { backendCommand: ["python3", Quickshell.shellPath("power_fake.py"), "success"]; timeoutMs: 3000 }
|
||||
}
|
||||
Connections {
|
||||
target: test.instance
|
||||
function onBusyChanged() { if (!test.instance.busy) Qt.callLater(test.advance); }
|
||||
function onSucceeded(action) { test.successes++; }
|
||||
}
|
||||
function check(value, message) { if (!value) { finished = true; console.error("POWER_TEST_FAIL: " + message); Qt.exit(1); throw new Error(message); } }
|
||||
function next() {
|
||||
if (instance) instance.destroy();
|
||||
instance = null;
|
||||
scenario++;
|
||||
if (scenario === names.length) { finished = true; console.log("POWER_TEST_PASS: 7 scenarios"); Qt.quit(); return; }
|
||||
step = 0; successes = 0;
|
||||
instance = factory.createObject(test);
|
||||
const mode = ["success", "denied", "failure", "malformed", "stall", "success", "success"][scenario];
|
||||
instance.backendCommand = ["python3", Quickshell.shellPath("power_fake.py"), mode];
|
||||
if (scenario === 4) instance.timeoutMs = 150;
|
||||
if (scenario === 5) {
|
||||
check(!instance.start("bad command"), "invalid action accepted");
|
||||
check(instance.error !== "", "invalid action error missing");
|
||||
complete(); return;
|
||||
}
|
||||
if (scenario === 6) instance.backendCommand = ["python3", "/nonexistent/adaptive-power.py"];
|
||||
check(instance.refresh(), "refresh rejected");
|
||||
}
|
||||
function complete() { console.log("PASS power controller: " + names[scenario]); Qt.callLater(next); }
|
||||
function advance() {
|
||||
if (finished || !instance || instance.busy) return;
|
||||
if (scenario === 0 || scenario === 2) {
|
||||
if (step === 0) {
|
||||
check(instance.available("reboot"), "capability not loaded");
|
||||
step = 1;
|
||||
check(instance.start("reboot"), "action rejected");
|
||||
check(!instance.start("poweroff"), "concurrent action accepted");
|
||||
return;
|
||||
}
|
||||
if (scenario === 0) { check(successes === 1, "success not emitted"); check(instance.error === "", "unexpected error"); }
|
||||
else { check(successes === 0, "error reported as success"); check(instance.error.includes("Mock authorization denied"), "backend error lost"); }
|
||||
} else if (scenario === 1) {
|
||||
check(!instance.available("suspend"), "denied action available");
|
||||
check(!instance.start("suspend"), "denied action started");
|
||||
} else if (scenario === 3 || scenario === 6) {
|
||||
check(instance.capabilityError !== "", "capability error missing");
|
||||
check(!instance.available("reboot"), "action available after backend failure");
|
||||
} else if (scenario === 4) {
|
||||
check(instance.timedOut, "watchdog did not fire");
|
||||
check(instance.error !== "", "watchdog error missing");
|
||||
}
|
||||
complete();
|
||||
}
|
||||
Component.onCompleted: Qt.callLater(next)
|
||||
Timer { interval: 20000; running: !test.finished; onTriggered: test.check(false, "harness timeout") }
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// Pure JavaScript policy tests, runnable without a Wayland session or Qt.
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const vm = require('node:vm');
|
||||
const path = require('node:path');
|
||||
const source = fs.readFileSync(path.join(__dirname, '../services/HardwarePolicy.js'), 'utf8').replace(/^\.pragma library\s*\n/, '');
|
||||
const ctx = vm.createContext({});
|
||||
vm.runInContext(source, ctx);
|
||||
const caps = ctx.networkCapabilities([{type: 2, name: 'enp1s0', connected: true}, {type: 2, name: 'enp2s0', connected: false}], 1, 2);
|
||||
assert.equal(caps.wifi, false);
|
||||
assert.equal(caps.wired.length, 2);
|
||||
assert.equal(ctx.ethernetSummary(caps.wired), 'Ethernet · 1/2');
|
||||
assert.equal(ctx.networkCapabilities([{type: 1, enabled: false}], 1, 2).wifi, true);
|
||||
const full = ctx.visibleSettingsSections(true, true, true);
|
||||
assert.equal(full.map(x => x.id).join(','), 'appearance,audio,network,wallpaper,bluetooth,system');
|
||||
const reduced = ctx.visibleSettingsSections(false, true, false);
|
||||
assert.equal(reduced.map(x => x.id).join(','), 'appearance,network,wallpaper,system');
|
||||
assert.equal(ctx.sectionIndex(reduced, 'bluetooth'), -1);
|
||||
assert.equal(ctx.pageIndex('network'), 2);
|
||||
assert.equal(ctx.pageIndex('bluetooth'), 4);
|
||||
assert.equal(ctx.pageIndex('invalid'), 0);
|
||||
const battery = ctx.visibleSettingsSections(false, false, false, false, true);
|
||||
assert.equal(battery.map(x => x.id).join(','), 'appearance,wallpaper,battery,system');
|
||||
assert.equal(ctx.pageIndex('battery'), 7);
|
||||
assert.equal(ctx.visibleSettingsSections(false, false, false, false, false).some(x => x.id === 'battery'), false);
|
||||
console.log('PASS: hardware policy, section visibility, hotplug and stable page IDs');
|
||||
@@ -0,0 +1,17 @@
|
||||
const fs = require('fs');
|
||||
const vm = require('vm');
|
||||
const assert = require('node:assert/strict');
|
||||
const path = require('path');
|
||||
const source = fs.readFileSync(path.join(__dirname, '../services/Policy.js'), 'utf8')
|
||||
.replace(/^\.pragma.*$/gm, '').replace(/^\.import.*$/gm, '');
|
||||
const ctx = {WallpaperPolicy: {validate: () => {}}};
|
||||
vm.createContext(ctx);
|
||||
vm.runInContext(source, ctx);
|
||||
function plain(value) { return JSON.parse(JSON.stringify(value)); }
|
||||
assert.deepEqual(plain(ctx.homePages([], 12)), [[]]);
|
||||
assert.deepEqual(plain(ctx.homePages(['a','b','c'], 2)), [['a','b'],['c']]);
|
||||
assert.deepEqual(plain(ctx.moveFavorite(['a','b','c'], 'b', 1)), ['a','c','b']);
|
||||
assert.deepEqual(plain(ctx.moveFavorite(['a','b','c'], 'a', -1)), ['a','b','c']);
|
||||
assert.deepEqual(plain(ctx.moveFavorite(['a','b','c'], 'missing', 1)), ['a','b','c']);
|
||||
assert.throws(() => ctx.homePages(['a'], 0));
|
||||
console.log('PASS home pages and favorite reordering');
|
||||
@@ -0,0 +1,33 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run the actual NetworkController with QML fake devices; never instantiate Networking."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
with tempfile.TemporaryDirectory(prefix='adaptive-network-controller-') as tmp:
|
||||
runtime = Path(tmp, 'runtime')
|
||||
runtime.mkdir(mode=0o700)
|
||||
config = Path(tmp, 'config')
|
||||
config.mkdir()
|
||||
shutil.copyfile(root / 'tests/fixtures/network.qml', config / 'shell.qml')
|
||||
shutil.copyfile(root / 'services/NetworkController.qml', config / 'NetworkController.qml')
|
||||
components = config / 'components'
|
||||
components.mkdir()
|
||||
for name in ['NetworkCard.qml', 'ActionButton.qml']:
|
||||
shutil.copyfile(root / 'components' / name, components / name)
|
||||
services = config / 'services'
|
||||
services.mkdir()
|
||||
(services / 'qmldir').write_text('singleton Theme 1.0 Theme.qml\n')
|
||||
(services / 'Theme.qml').write_text('pragma Singleton\nimport QtQuick\nQtObject { property color foreground: "white"; property color outline: "gray"; property color background: "black"; property color surface: "#222222"; property color primary: "#d0bcff" }\n')
|
||||
env = dict(os.environ, QT_QPA_PLATFORM='offscreen', XDG_RUNTIME_DIR=str(runtime),
|
||||
XDG_STATE_HOME=tmp, XDG_CACHE_HOME=tmp)
|
||||
result = subprocess.run(['quickshell', '-p', str(config), '--no-color'], env=env,
|
||||
capture_output=True, text=True, timeout=20)
|
||||
logs = result.stdout + result.stderr
|
||||
print(logs)
|
||||
assert result.returncode == 0 and 'NETWORK_TEST_PASS: 9 scenarios' in logs, logs
|
||||
for marker in ['NETWORK_TEST_FAIL', 'Failed to load configuration', 'ReferenceError', 'TypeError', 'Binding loop']:
|
||||
assert marker not in logs, marker
|
||||
Loaded 100 of 189 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user