diff --git a/bin/checkUpdates.sh b/bin/checkUpdates.sh old mode 100755 new mode 100644 diff --git a/bin/checktraffic b/bin/checktraffic old mode 100755 new mode 100644 diff --git a/bin/diskspeedtest b/bin/diskspeedtest old mode 100755 new mode 100644 diff --git a/bin/fet.sh b/bin/fet.sh old mode 100755 new mode 100644 diff --git a/bin/fff b/bin/fff old mode 100755 new mode 100644 diff --git a/bin/fontcharlist b/bin/fontcharlist old mode 100755 new mode 100644 diff --git a/bin/linux-chroot.sh b/bin/linux-chroot.sh old mode 100755 new mode 100644 diff --git a/bin/lroot b/bin/lroot deleted file mode 120000 index 74980a5..0000000 --- a/bin/lroot +++ /dev/null @@ -1 +0,0 @@ -linux-chroot.sh \ No newline at end of file diff --git a/bin/lroot b/bin/lroot new file mode 100644 index 0000000..e1612a9 --- /dev/null +++ b/bin/lroot @@ -0,0 +1,56 @@ +#!/bin/sh +PATH=$1 +SHELL=$2 + +check_root() { + if [ $(/usr/bin/id -u) -ne 0 ]; then + printf "** You must be root\n" + exit 1 + fi +} + +check_or_mkdir() { + [ ! -d $PATH/dev ] && mkdir -pv $PATH/dev + [ ! -d $PATH/proc ] && mkdir -pv $PATH/proc + [ ! -d $PATH/sys ] && mkdir -pv $PATH/sys + [ ! -d $PATH/run ] && mkdir -pv $PATH/run +} + +mount_virtual() { + /usr/bin/mount -v --bind /dev $PATH/dev + /usr/bin/mount -vt devpts devpts -o gid=5,mode=0620 $PATH/dev/pts + /usr/bin/mount -vt proc proc $PATH/proc + /usr/bin/mount -vt sysfs sysfs $PATH/sys + /usr/bin/mount -vt tmpfs tmpfs $PATH/run + if [ -h $PATH/dev/shm ]; then + /usr/bin/install -v -d -m 1777 $PATH$(/usr/bin/realpath /dev/shm) + else + /usr/bin/mount -vt tmpfs -o nosuid,nodev tmpfs $PATH/dev/shm + fi + /usr/bin/cp -v /etc/resolv.conf $PATH/etc/resolv.conf +} + +umount_virtual() { + /usr/bin/mountpoint -q $PATH/dev/shm && /usr/bin/umount $PATH/dev/shm + /usr/bin/umount $PATH/dev/pts + /usr/bin/umount $PATH/{sys,proc,run,dev} +} + +get_shell() { + if [[ "$SHELL" != "" ]]; then + echo $SHELL + fi + echo "/bin/sh" +} + +check_root +check_or_mkdir +mount_virtual + +/usr/bin/chroot \ + $PATH \ + /usr/bin/env -i \ + PATH=/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin \ + $(get_shell) + +umount_virtual diff --git a/bin/netdevlist b/bin/netdevlist old mode 100755 new mode 100644 diff --git a/bin/pfetch b/bin/pfetch old mode 100755 new mode 100644 diff --git a/bin/rtp-receiver.sh b/bin/rtp-receiver.sh old mode 100755 new mode 100644 diff --git a/bin/rtp-sender.sh b/bin/rtp-sender.sh old mode 100755 new mode 100644 diff --git a/bin/run_ftpd b/bin/run_ftpd old mode 100755 new mode 100644 diff --git a/bin/shfm b/bin/shfm old mode 100755 new mode 100644 diff --git a/bin/speedtest b/bin/speedtest old mode 100755 new mode 100644 diff --git a/bin/sysfetch b/bin/sysfetch old mode 100755 new mode 100644 diff --git a/bin/tux.sh b/bin/tux.sh old mode 100755 new mode 100644 diff --git a/bin/updatepacmanrepo b/bin/updatepacmanrepo old mode 100755 new mode 100644 diff --git a/bin/worknet b/bin/worknet old mode 100755 new mode 100644 diff --git a/docs/prompt/hyprland_quickshell_adaptive_shell.md b/docs/prompt/hyprland_quickshell_adaptive_shell.md new file mode 100644 index 0000000..744919b --- /dev/null +++ b/docs/prompt/hyprland_quickshell_adaptive_shell.md @@ -0,0 +1,1530 @@ +# MASTER PROMPT — Adaptive Material 3 Linux Shell + +## Полная адаптивная оболочка Hyprland + Quickshell для Desktop, Tablet и Phone + +Ты — senior Linux systems engineer, Wayland compositor developer, Qt 6/QML architect, Rust developer и специалист по мобильным Linux-окружениям. + +Твоя задача — превратить мою **существующую конфигурацию Hyprland** в полноценное конвергентное Linux-окружение на базе **Quickshell и Google Material Design 3**, одинаково пригодное для компьютеров, планшетов и телефонов. + +Требуется не прототип, не набор демонстрационных QML-экранов, а работоспособная, оптимизированная, интегрированная оболочка. + +**Главное требование: не создавай новую конфигурацию Hyprland вместо существующей. Изучи мои текущие настройки и аккуратно модифицируй их, сохранив всю функциональность, которую я уже использую.** + +Продолжай реализацию по этапам, проверяй результат, исправляй ошибки и документируй технические ограничения. + +--- + +# 1. Исходная система + +Документ — задание на будущую реализацию, а не описание готовой Quickshell-оболочки. Срез рабочего дерева репозитория обновлён **17 ноября 2026 года**. Перед реализацией повторно сверь его с файлами: локальные изменения могут отличаться от последнего коммита. + +Заявленные целевые платформы: + +- Arch Linux на desktop, архитектура x86_64. +- Arch Linux ARM на телефоне, архитектура aarch64. +- Сенсорный ввод на телефоне, внешние мониторы и отпечаток пальца на поддерживаемом оборудовании. +- Ручной запуск desktop-сессии из TTY без обязательного Display Manager. + +Наличие телефона, датчиков, сканера, конкретного аудиосервера и установленные версии компонентов нельзя установить по одним dotfiles. Подтверди их отдельным аудитом целевой машины. + +## 1.1. Фактическая структура репозитория + +Основная конфигурация композитора — **`hypr/hyprland.lua`**, использующая API `hl.*`. Не создавай вместо неё новый `hyprland.conf` и не переноси настройки обратно в conf-синтаксис без обоснованной необходимости. + +| Файлы | Текущее назначение | +| --- | --- | +| `hypr/hyprland.lua` | Подключает `keybinds`, `windowrules`, `startup`, `monitors`, `environment`, `keyboard`, `gestures`, `decoration`, `animation`; задаёт общие параметры композитора | +| `hypr/keybinds.lua`, `hypr/programs.lua` | Привязки клавиш и команды приложений; `programs` подключается из `keybinds` | +| `hypr/startup.lua` | Автозапуск через обработчик `hl.on("hyprland.start", ...)` | +| `hypr/monitors.lua` | В текущем рабочем дереве: `DP-1`, `3440x1440@165.00Hz`, позиция `0x0`, scale `1`; это профиль desktop, а не универсальная настройка | +| `hypr/keyboard.lua`, `hypr/gestures.lua` | Раскладки, устройства ввода и трёхпальцевые жесты тачпада | +| `hypr/decoration.lua`, `hypr/animation.lua`, `hypr/windowrules.lua` | Оформление, анимации, правила окон и слоёв | +| `hypr/hypridle.conf`, `hypr/hyprlock.conf`, `hypr/hyprpaper.conf` | Отдельные конфигурации соответствующих демонов; выясни реальные пути загрузки в сессии | +| `hypr/hypridle.lua`, `hypr/hyprlock.lua`, `hypr/hyprpaper.lua` | Результаты `hyprconf2lua` с предупреждениями/TODO; основной `hyprland.lua` их не подключает. Не считай их рабочей заменой `.conf` | +| `hypr/monitors.conf`, `hypr/workspaces.conf` | В текущем рабочем дереве пустые; основной Lua entrypoint их не подключает | +| `waybar/config.jsonc`, `waybar/style.css`, `waybar/scripts/` | Текущая панель и вспомогательные скрипты | +| `swaync/config.json`, `swaync/style.css` | Центр уведомлений | +| `rofi/launcher/`, `rofi/powermenu/`, `rofi/emoji/`, `rofi/clipboard/` | Лаунчер, питание, emoji и отдельный clipboard-сценарий | +| `hypr/bin/` | Скрипты обоев, блокировки, экранной клавиатуры, обновления и перезапуска компонентов | +| `shell/source.sh` | PATH, Flatpak XDG data paths, alias `H='start-hyprland'` | + +**Каталога `quickshell/`, реализации Material 3 Settings и общего HardwareCapabilityService пока нет.** Их нужно создать в рамках будущей реализации. Конфигурации `niri/` и `mako/` также присутствуют, но текущий Hyprland startup запускает SwayNC; наличие каталога не доказывает запуск сервиса. + +## 1.2. Автозапуск и интеграции, которые нужно сохранить + +`hypr/startup.lua` запускает: + +- `hyprpaper`, затем с задержкой `hypr/bin/background.sh`. +- `waybar`, `swaync`, `hypridle`, `swayosd-server`. +- `lxpolkit`, `nm-applet --indicator`, `uxplay`, `unclutter`, `clipse -listen`. +- Настройку GTK-темы `MacTahoe-Dark`, icon theme `MacTahoe-dark`, курсора `Bibata-Modern-Ice` размера 24 и тёмной цветовой схемы. +- Импорт `WAYLAND_DISPLAY` и `XDG_CURRENT_DESKTOP` через `dbus-update-activation-environment --systemd` и `systemctl --user import-environment`. + +Сохраняй polkit agent, clipboard manager и пользовательские приложения. SwayOSD, сетевой апплет и прежние визуальные компоненты отключай только после проверки соответствующей замены. Проверь отсутствие дублирования OSD и конкуренции за D-Bus notifications name. Не запускай Quickshell одновременно из Lua startup и нового systemd unit; выбери один способ с корректным завершением вместе с сессией. + +## 1.3. Существующие сценарии управления + +- Основной модификатор — **Alt**, не Super. Сохрани привязки и их привычные действия. +- `Alt+Return` — Kitty, `Alt+T` — Thunar, `Alt+D` и `XF86LaunchB` — Rofi launcher. +- `Alt+Space` — отдельный лаунчер `sherlock`; не удаляй его при замене Rofi без согласованной замены сценария. +- `Alt+B` — `hypr/bin/hyprlock-background.sh`; `Alt+Shift+P` — Rofi power menu. +- `Alt+Z` — открыть SwayNC, `Alt+Shift+R` — перечитать его конфигурацию. При миграции перенаправь эти действия на эквиваленты оболочки. +- `Alt+C` — `kitty clipse`; `Alt+E` — Rofimoji. Скрипт `rofi/clipboard/clipboard.sh` использует Greenclip, но это отдельный сценарий, не текущий clipboard bind. +- `Alt+Shift+O` — переключение `wvkbd-mobintl` через `hypr/bin/toggle_keyboard.sh`. +- Громкость, mute, микрофон, яркость и media keys используют `swayosd-client`; клавиатурная подсветка — `brightnessctl` с устройством `smc::kbd_backlight`. Не переноси это имя на все устройства. +- Сохрани скриншоты через Grim/Slurp/wl-copy, запуск обновлений, навигацию и перемещение окон, workspaces 1–10, special workspace `magic` и resize submap. +- Ввод: `us,ru`, переключение `grp:win_space_toggle`, repeat rate 50, delay 500; touchpad natural scroll и scroll factor 0.2. +- Текущие жесты: три пальца horizontal → workspace, up → fullscreen, pinchout → float. Это не реализация глобальных touchscreen-жестов. +- Исходное desktop-оформление: dwindle, gaps 5/5, border 1, rounding 20, blur и shadow выключены. При возврате из мобильного режима восстанавливай пользовательские значения. + +## 1.4. Что перенести из панели и уведомлений + +Waybar сейчас показывает launcher, CPU/RAM/temperature/disk, заголовок окна, workspaces, звук/микрофон, MPRIS, подсветку, состояния клавиатуры, язык, батареи, часы, tray и питание. Часы настроены на `Asia/Tomsk`: сохрани настройку как пользовательское предпочтение. + +Сохрани возможность просмотра обновлений и запуска `hypr/bin/startupdate.sh` (Kitty + `sudo pacman -Syu`). Не запускай обновления из UI без пользовательского действия и не выдавай успех при ошибке команды. + +Различай объявления модулей и их включение в `modules-left/center/right`: `network`, `bluetooth`, `privacy`, `custom/onscreenkeyboard`, `cava` и `custom/spotify` описаны, но в текущие списки не включены. `custom/weather` включён в список, но его определения закомментированы. Не считай эти функции подтверждённо работающими. Две записи батарей, включая `BAT2`, не доказывают наличие двух аккумуляторов. + +В SwayNC включены title/clear all, DND, MPRIS, volume, backlight и notifications; тайм-ауты 6 секунд для обычных, 3 для low, 0 для critical. Есть настройки inline replies и 2FA actions. `buttons-grid` описан, но не включён в `widgets`; старый путь `/home/alien/...` не является зависимостью новой оболочки. + +## 1.5. Известные места для проверки при реализации + +Это наблюдения по исходникам, а не результаты проверки работающей сессии: + +- `hypr/hypridle.conf`: lock command `pidof hyprlock || hyprlock`, перед сном `loginctl lock-session`, после сна DPMS on. Тайм-ауты: 150 — приглушение подсветки, 6000 — lock, 7200 — DPMS off, 8000 — suspend (секунды). В командах подсветки написано `brightnesctl`; проверь и исправь опечатку при реализации, сохранив осознанно выбранные интервалы. +- Ручной lock bind использует wrapper со случайными обоями, idle lock запускает Hyprlock напрямую. Объедини поведение через проверенную точку входа, сохранив защиту от повторного запуска и блокировку перед сном. +- `hypr/bin/hyprlock-background.sh` меняет `hypr/hyprlock.conf` через широкий `sed` по строкам `Pictures`. Для новой реализации не используй изменение отслеживаемого конфига как хранилище runtime-состояния. +- `hypr/bin/background.sh` выбирает случайные обои из `~/Pictures/wallpaper` для мониторов и вызывает Hyprpaper IPC. Учти пустой каталог, пути с пробелами, hotplug и независимые обои выходов. +- `hypr/bin/toggle_keyboard.sh` хранит флаг в `~/.keyboard_started`; он может расходиться с состоянием процесса. Сохрани возможность ручного вызова клавиатуры, добавь проверку реального состояния и совместимости с полями ввода/lock screen. +- В Waybar MPRIS есть ссылка на `~/dotfiles/ags/media/toggle_media`, но каталога `ags/` в репозитории нет. Не делай отсутствующий AGS обязательной зависимостью. +- `README.md` и `INSTALL.md` содержат старые пути `.conf`, упоминания Mako/Greenclip/PulseAudio, отсутствующего `install_scripts/install.sh` и инструкции Display Manager. При расхождении опирайся на текущий код и аудит сессии; обнови инструкции в ходе миграции. +- Реальный `install_scripts/install-arch.sh` устанавливает ОС с разметкой/форматированием диска; это не установщик оболочки. Для миграции создай отдельный безопасный механизм установки dotfiles и зависимостей. + +Цель — единая оболочка для всех устройств с сохранением этих сценариев, а не три независимых окружения. + +## Обязательный предварительный аудит + +Сначала изучи исходники в корне этого репозитория, затем сопоставь их с реально загруженными файлами и симлинками в пользовательской сессии. Проверь также `git status`: сохраняй существующие локальные изменения, включая неотслеживаемые файлы; не выполняй автоматический reset/checkout и не включай посторонние правки в свои коммиты. + +Перед изменениями изучи: + +- `~/.config/hypr/` +- `~/.config/waybar/` +- `~/.config/swaync/` +- `~/.config/rofi/` +- `~/.config/quickshell/` +- `~/.config/hypr/hypridle.conf` +- `~/.config/hypr/hyprlock.conf` +- пользовательские скрипты +- systemd user services +- PAM-конфигурацию, относящуюся к блокировке +- текущие способы запуска Hyprland +- установленные версии Hyprland, Quickshell и Qt +- существующие правила окон, рабочих пространств и мониторов + +Не предполагай, что конфигурационные файлы находятся только в стандартных местах. Проверь реальные пути и подключаемые конфигурации. + +Сделай резервные копии изменяемых файлов. + +Если проект находится под Git, используй существующую структуру и сохраняй понятную историю изменений. + +Не удаляй существующие пакеты и конфигурации до успешного завершения миграции. + +--- + +# 2. Целевая архитектура + +Создай одну оболочку Quickshell с общей системой сервисов и адаптивными представлениями. + +Архитектура: + +```text +Hyprland +│ +├── Quickshell +│ ├── Adaptive Shell +│ │ ├── Desktop UI +│ │ ├── Tablet UI +│ │ └── Phone UI +│ │ +│ ├── Material 3 Design System +│ │ ├── Colors +│ │ ├── Typography +│ │ ├── Shapes +│ │ ├── Motion +│ │ └── Components +│ │ +│ ├── System Bar +│ ├── Quick Settings +│ ├── Notification Center +│ ├── Application Launcher +│ ├── Home Screen +│ ├── Recent Apps +│ ├── Navigation Gestures +│ ├── Wallpaper Engine +│ ├── Secure Lock Screen +│ ├── Power Menu +│ └── Settings Application +│ +├── Hypridle +├── NetworkManager +├── BlueZ +├── PipeWire / WirePlumber +├── UPower +├── systemd-logind +├── fprintd / libfprint +└── Linux kernel device interfaces +``` + +Quickshell должен быть основным процессом визуальной оболочки. + +Не создавай отдельные постоянно работающие приложения там, где функциональность может быть реализована внутри Quickshell. + +Допускается небольшой вспомогательный сервис на Rust, если он действительно необходим для безопасного доступа к системным API, обработки жестов или интеграции с аппаратным обеспечением. + +Не дублируй сервисы между режимами. + +--- + +# 3. Полный Google Material Design 3 + +Весь интерфейс должен быть выполнен в стиле Google Material Design 3 / Material You. + +Официальные ориентиры: + +https://m3.material.io/ + +https://m3.material.io/styles/color/system/overview + +https://m3.material.io/foundations/layout/understanding-layout/overview + +https://fonts.google.com/icons + +Требования: + +- Полноценная система Material 3 design tokens. +- Dynamic Color на основе обоев. +- Светлая тема. +- Тёмная тема. +- Системная тема. +- AMOLED-тема с настоящим чёрным фоном. +- Ручной выбор accent color. +- Material Symbols. +- Material 3 typography. +- Material 3 switches, sliders, buttons, menus и dialogs. +- Material 3 cards, navigation rail, navigation drawer и bottom navigation. +- Корректные состояния hover, pressed, focused, disabled. +- Плавные, но оптимизированные анимации. +- Поддержка reduced motion. +- Доступность и клавиатурная навигация. +- Корректное масштабирование интерфейса. + +Используй единый набор компонентов. + +Не создавай три разные темы для телефона, планшета и компьютера. Меняться должны layout, размеры, плотность и способы взаимодействия, а дизайн-система должна оставаться общей. + +--- + +# 4. Адаптивная система режимов + +Реализуй: + +- `auto` +- `phone` +- `tablet` +- `desktop` + +Режим должен определяться по сочетанию: + +- размера доступной рабочей области +- масштаба дисплея +- наличия сенсорного ввода +- типа устройства +- пользовательских предпочтений + +Не определяй режим исключительно по CPU architecture или физическому разрешению экрана. + +Поддержи разные режимы на разных мониторах одновременно. + +Например: + +- Экран телефона: phone mode. +- Внешний монитор: desktop mode. + +При подключении и отключении мониторов оболочка должна перестраиваться без перезапуска пользовательских приложений. + +Добавь ручное переключение режима в Settings. + +--- + +# 5. Замена Waybar + +Полностью реализуй верхнюю системную панель в Quickshell. + +Desktop: + +- Верхняя панель. +- Часы и календарь. +- Рабочие пространства. +- Индикаторы приложений. +- Системный трей. +- Wi-Fi и Ethernet. +- Bluetooth. +- Громкость. +- Микрофон. +- Батарея. +- Яркость. +- Медиаплеер. +- Уведомления. +- Режим «Не беспокоить». +- Меню питания. +- Кнопка запуска приложений. + +Tablet: + +- Адаптивная системная панель. +- Сенсорные элементы. +- Упрощённые индикаторы. +- Быстрый доступ к многозадачности. + +Phone: + +- Компактная status bar. +- Время. +- Сигнал сети, если доступен соответствующий backend. +- Wi-Fi. +- Bluetooth при необходимости. +- Батарея. +- Индикаторы состояния. +- Поддержка вырезов и безопасных областей экрана, если информация о них доступна. + +Не используй фиктивные значения сигналов, батареи или сети. + +--- + +# 6. Замена SwayNC + +Реализуй собственный сервер уведомлений через Freedesktop Notifications D-Bus API. + +Обязательно: + +- Получение уведомлений. +- Уведомления с иконками и изображениями. +- Action buttons. +- Замена уведомлений по ID. +- Группировка по приложениям. +- История уведомлений. +- Удаление свайпом. +- Очистка всех уведомлений. +- Приоритеты. +- Тайм-ауты. +- Do Not Disturb. +- Уведомления на экране блокировки с настройками приватности. +- Ограничение размера истории. +- Сохранение состояния. +- Корректная обработка закрытия и сигналов D-Bus. + +В desktop mode используй компактный Notification Center. + +В phone mode уведомления должны находиться в единой шторке с быстрыми настройками. + +При переходе на новый сервер уведомлений не допускай одновременного запуска SwayNC. + +--- + +# 7. Material 3 Quick Settings + +Создай полноценный центр управления. + +Функции: + +- Wi-Fi. +- Ethernet. +- Bluetooth. +- Громкость. +- Выбор аудиоустройств. +- Яркость. +- Батарея. +- Энергосбережение. +- Do Not Disturb. +- Фонарик при наличии. +- Автоповорот при наличии датчиков. +- Медиаплеер через MPRIS. +- Настройки экрана. +- Быстрый переход в Settings. + +Используй реальные системные интерфейсы: + +- NetworkManager D-Bus. +- BlueZ D-Bus. +- PipeWire / WirePlumber. +- UPower. +- MPRIS. +- power-profiles-daemon или совместимый backend. +- iio-sensor-proxy при наличии. + +Не создавай отдельные shell-скрипты для каждого переключателя, если доступен нормальный API. + +Все переключатели должны показывать реальное состояние системы. + +--- + +# 8. Замена Rofi + +Реализуй собственный Application Launcher. + +Desktop: + +- Material 3 search popup. +- Поиск приложений. +- Клавиатурная навигация. +- Избранное. +- История запуска. +- Поиск файлов через доступный backend. +- Настраиваемые действия. + +Tablet: + +- Адаптивная сетка приложений. +- Поиск. +- Сенсорное управление. + +Phone: + +- Полноэкранный App Drawer. +- Сетка иконок. +- Поиск. +- Категории. +- Избранное. +- Поддержка экранной клавиатуры. + +Используй XDG Desktop Entries. + +Поддерживай Flatpak. + +Корректно обрабатывай Desktop Entry `Exec`, `TryExec`, `NoDisplay`, `OnlyShowIn`, `NotShowIn` и Desktop Actions. + +Не выполняй непроверенные строки поиска как shell-команды. + +--- + +# 9. Домашний экран телефона + +Реализуй настоящий Home Screen. + +Функциональность: + +- Сетка приложений. +- Перемещение иконок. +- Папки. +- Dock. +- Несколько страниц. +- Настраиваемые обои. +- Поиск. +- Виджеты при наличии backend. +- Контекстные меню. +- Сохранение состояния. +- Адаптация к повороту экрана. + +Домашний экран должен оставаться доступным независимо от того, какие приложения открыты. + +Не реализуй его обычным окном, которое случайно может оказаться поверх активных приложений или нарушить фокус. + +Используй корректную интеграцию с композитором и слоями Wayland. + +--- + +# 10. Recent Apps и многозадачность + +Создай мобильный переключатель запущенных приложений. + +Функции: + +- Карточки открытых окон. +- Иконки приложений. +- Названия. +- Переключение на выбранное окно. +- Закрытие окна свайпом вверх. +- Закрытие нескольких окон. +- Поддержка полноэкранных приложений. +- Корректное восстановление фокуса. +- Поддержка нескольких окон одного приложения. + +Для desktop реализуй обзор окон, если это возможно через поддерживаемые API Hyprland. + +Для миниатюр используй реальный compositor-compatible механизм. + +Не показывай поддельные скриншоты приложений. + +Если миниатюры недоступны, используй карточки с иконками и названиями. + +--- + +# 11. Мобильная жестовая навигация + +Это критически важная функциональность. + +Реализуй системные жесты, работающие поверх обычных и полноэкранных приложений. + +| Жест | Действие | +| ------------------------------------ | ------------------------------------- | +| Свайп снизу вверх | Сразу домашний экран | +| Свайп снизу вверх с удержанием | Recent Apps | +| Свайп от левого края вправо | Назад | +| Свайп от правого края влево | Назад | +| Свайп сверху вниз | Шторка уведомлений и быстрых настроек | +| Свайп по нижней полоске влево/вправо | Переключение приложений | +| Свайп карточки вверх в Recent Apps | Закрытие окна | +| Свайп вверх по открытой шторке | Закрытие шторки | + +## Особые требования + +**Выход домой — простым свайпом снизу вверх, без удержания.** + +Для открытия Recent Apps нужно сделать свайп снизу вверх и удержать палец. + +Оба боковых края должны поддерживать жест «Назад». + +Реализуй: + +- Пороги распознавания. +- Настраиваемую чувствительность. +- Визуальную обратную связь. +- Отмену жеста. +- Защиту от ложных срабатываний. +- Поддержку landscape. +- Учёт DPI и масштабирования. +- Приоритет жестов на границах экрана. +- Поддержку настоящего touchscreen input. + +Учитывай, что Linux-приложения не имеют универсального действия «Назад». + +Создай маршрутизацию действия с учётом активного приложения, поддерживаемых API и настраиваемых fallback-клавиш. + +Не отправляй произвольные сочетания клавиш в приложения, где это может привести к потере данных. + +Не считай обычный QML MouseArea достаточной реализацией глобальных жестов. + +Проверь возможности Hyprland и при необходимости реализуй отдельную compositor-level интеграцию. + +--- + +# 12. Динамическая конфигурация Hyprland + +Реализуй автоматическое переключение параметров композитора. + +Phone: + +- Нулевые отступы. +- Нулевые рамки. +- Без скруглений. +- Без размытия. +- Минимальные анимации. +- Одно основное приложение на экране. + +Tablet: + +- Небольшие отступы. +- Адаптивная многозадачность. +- Сенсорное управление. + +Desktop: + +- Настраиваемые gaps. +- Настраиваемые borders. +- Скругления. +- Анимации. +- Tiling и floating. + +Не перезаписывай исходные пользовательские значения. + +Сохраняй их как базовый профиль. + +Применяй изменения через поддерживаемые API текущей версии Hyprland. + +Учитывай, что глобальные параметры Hyprland могут влиять сразу на несколько мониторов. Для независимых режимов используй доступные правила рабочих пространств и окон, а ограничения документируй. + +--- + +# 13. Замена Hyprpaper + +Перенеси управление обоями в Quickshell. + +Реализуй Wallpaper Engine. + +Поддерживаемые форматы: + +- JPG. +- JPEG. +- PNG. +- WebP. +- SVG. +- GIF. +- Видеообои через поддерживаемый мультимедийный backend. + +Функциональность: + +- Отдельные обои для разных мониторов. +- Отдельные обои Home Screen. +- Отдельные обои Lock Screen. +- Crop / Fit / Fill. +- Слайд-шоу. +- Автоматическая смена. +- Динамическая цветовая палитра Material You. +- Предпросмотр. +- Выбор из файлов. +- Настройка через Settings. + +Для видеообоев реализуй приостановку декодирования, когда поверхность не видна или устройство переходит в энергосберегающий режим. + +Не запускай тяжёлые видеообои на слабом ARM без возможности отключения. + +Отключай Hyprpaper только после проверки корректного отображения новых обоев. + +--- + +# 14. Замена Hyprlock + +Создай собственный Material 3 Lock Screen в Quickshell. + +Используй настоящий Wayland Session Lock Protocol `ext-session-lock-v1`. + +Не используй обычное полноэкранное окно как механизм безопасности. + +Lock Screen должен поддерживать: + +- Часы. +- Дату. +- Обои. +- Батарею. +- Статус зарядки. +- Уведомления с настройками приватности. +- Поле пароля. +- PIN при наличии безопасного механизма проверки. +- Отпечаток пальца. +- Анимации разблокировки. +- Разные layout для desktop, tablet и phone. +- Корректную работу после suspend/resume. + +Используй PAM для проверки учётных данных. + +Не сохраняй пароль или PIN в конфигурации Quickshell. + +Не реализуй собственную криптографию хранения паролей. + +Обеспечь защиту от обхода блокировки при: + +- Перезапуске Quickshell. +- Отключении монитора. +- Подключении нового монитора. +- Изменении разрешения. +- Сбое UI. +- Переключении TTY и возвращении в сессию. +- Suspend/resume. + +Если безопасная реализация не готова, продолжай использовать Hyprlock. + +Не отключай рабочий блокировщик до успешных проверок нового. + +--- + +# 15. Touch ID / Fingerprint Unlock + +Реализуй разблокировку по отпечатку пальца на телефоне и desktop. + +Используй: + +- fprintd. +- libfprint. +- PAM. +- Поддерживаемые аппаратные драйверы. + +Требования: + +- Разблокировка одним прикосновением. +- Без необходимости предварительно вводить пароль. +- Без необходимости нажимать Enter. +- Визуальный индикатор сканирования. +- Отображение ошибок. +- Повторная попытка. +- Возможность переключиться на пароль. +- Ограничение попыток согласно политике аутентификации. +- Безопасная обработка отсутствия устройства. + +Создай раздел Fingerprint в Settings. + +Функции: + +- Проверка доступности сканера. +- Регистрация отпечатка через доверенный системный backend. +- Просмотр зарегистрированных отпечатков, если backend поддерживает. +- Удаление отпечатков после надлежащей авторизации. +- Включение/отключение разблокировки отпечатком. +- Диагностика устройства. + +Не создавай собственную базу биометрических шаблонов. + +Не считай успешное получение события от датчика подтверждением личности. + +Разблокировка разрешена только после успешной проверки доверенным backend. + +Если сканер телефона не поддерживается libfprint/fprintd, не имитируй поддержку. Документируй необходимые драйверы и возможные способы интеграции. + +--- + +# 16. Сохранение Hypridle + +Я уже использую Hypridle. + +Не заменяй его без необходимости. + +Изучи текущую конфигурацию и интегрируй с новым экраном блокировки. + +Обеспечь: + +- Блокировку по тайм-ауту. +- Блокировку перед suspend. +- Корректную работу после resume. +- Выключение дисплея. +- Настраиваемые интервалы. +- Отдельные профили desktop и phone. +- Настройки через Material 3 Settings. + +Используй `loginctl`, systemd-logind и поддерживаемые интерфейсы там, где это необходимо. + +Не допускай ситуации, когда устройство засыпает до установки безопасной блокировки. + +Сохрани рабочую интеграцию Hypridle + Hyprlock до проверки нового Lock Screen. + +--- + +# 17. Запуск из TTY без Display Manager + +На desktop я не использую Display Manager. + +Я вручную вхожу в TTY и запускаю Hyprland. В `shell/source.sh` для этого есть alias `H='start-hyprland'`; сохрани его и проверь фактический механизм запуска на целевой машине. + +**Сохрани этот способ запуска.** + +Не устанавливай SDDM, GDM, LightDM или другой Display Manager. + +После запуска Hyprland должен автоматически запускаться Quickshell. + +Проверь: + +- Правильную пользовательскую сессию. +- D-Bus user session. +- XDG_RUNTIME_DIR. +- systemd user services. +- Переменные Wayland. +- Корректное завершение оболочки при выходе из Hyprland. + +На телефоне разрешается отдельный механизм автозапуска, но он не должен ослаблять безопасность входа. + +Не настраивай автоматический вход без явного подтверждения пользователя. + +--- + +# 18. Полноценное приложение Settings + +Создай отдельное, реально работающее приложение настроек, тесно интегрированное с Quickshell и Hyprland. + +Название приложения: **Settings**. + +Дизайн: Google Material Design 3. + +Settings должно быть доступно: + +- Через лаунчер. +- Через Quick Settings. +- Через Home Screen. +- Через меню приложений. +- Через отдельный `.desktop` файл. + +Допускается реализация отдельным QML-приложением или выделенным окном Quickshell, если выбранная архитектура обеспечивает правильную работу, независимое открытие, фокус и безопасность. + +## Адаптивный дизайн Settings + +### Phone + +Используй стиль Android Material 3 Settings: + +- Вертикальный список разделов. +- Крупные сенсорные элементы. +- Поиск настроек. +- Вложенные страницы. +- Кнопка «Назад». +- Поддержка боковых жестов. +- Корректная работа экранной клавиатуры. + +### Tablet + +- Navigation Rail. +- Двухпанельный интерфейс. +- Список разделов слева. +- Содержимое справа. + +### Desktop + +- Боковая навигация. +- Поиск. +- Настройки в основной области. +- Поддержка мыши и клавиатуры. +- Изменение размера окна. +- Многомониторность. + +## Разделы Settings + +### 18.1. Главная страница + +Показывай: + +- Название устройства. +- Версию Linux. +- Версию ядра. +- Архитектуру CPU. +- Версию Hyprland. +- Версию Quickshell. +- Состояние сети. +- Состояние батареи, если доступна. + +### 18.2. Wi-Fi и сеть + +- Wi-Fi on/off. +- Список доступных сетей. +- Подключение к сети. +- Сохранённые подключения. +- Ethernet. +- IP-адреса. +- DNS. +- Настройки прокси, если реализован соответствующий backend. +- VPN через NetworkManager, если поддерживается. + +### 18.3. Bluetooth + +- Включение. +- Поиск устройств. +- Сопряжение. +- Подключение. +- Отключение. +- Удаление сопряжения. +- Информация об устройстве. + +### 18.4. Звук + +- Громкость. +- Микрофон. +- Устройства вывода. +- Устройства ввода. +- Баланс при поддержке backend. +- Звуки уведомлений. +- Звук блокировки. +- Звуки интерфейса. + +### 18.5. Дисплей + +- Разрешение. +- Частота обновления. +- Масштабирование. +- Яркость. +- Поворот. +- Расположение мониторов. +- Основной монитор. +- Включение/отключение дисплеев. +- Автоматический поворот при наличии датчиков. + +Не применяй неподдерживаемые режимы мониторов. + +Предусмотри подтверждение опасных изменений с автоматическим откатом. + +### 18.6. Обои и стиль + +- Выбор обоев. +- Отдельные обои для Home Screen и Lock Screen. +- Видеообои. +- Слайд-шоу. +- Dynamic Color. +- Accent Color. +- Светлая/тёмная/системная тема. +- AMOLED. +- Размеры элементов. +- Шрифты. +- Анимации. +- Reduced Motion. + +### 18.7. Home Screen + +- Сетка приложений. +- Размер иконок. +- Dock. +- Количество страниц. +- Папки. +- Виджеты. +- Скрытие приложений из домашней сетки. +- Настройки App Drawer. + +### 18.8. Жесты и навигация + +- Включение жестовой навигации. +- Чувствительность. +- Зоны распознавания. +- Свайп домой. +- Recent Apps. +- Назад с левого края. +- Назад с правого края. +- Переключение приложений. +- Анимации. +- Тактильная отдача при наличии. +- Режим трёх навигационных кнопок как опциональная альтернатива, если реализован. + +### 18.9. Уведомления + +- Разрешения по приложениям. +- История. +- Группировка. +- Do Not Disturb. +- Звуки. +- Отображение на Lock Screen. +- Скрытие чувствительного содержимого. +- Всплывающие уведомления. + +### 18.10. Панель и Quick Settings + +- Положение панели. +- Высота. +- Автоскрытие. +- Состав индикаторов. +- Порядок Quick Settings. +- Размер переключателей. +- Состав быстрых действий. +- Поведение шторки. + +### 18.11. Многозадачность + +- Настройки Recent Apps. +- Анимации. +- Поведение окон. +- Tiling/Floating. +- Gaps. +- Borders. +- Скругления. +- Рабочие пространства. +- Правила отдельных приложений. + +### 18.12. Блокировка и безопасность + +- Способ блокировки. +- Время автоматической блокировки. +- Блокировка при suspend. +- Настройки Hypridle. +- Отпечатки пальцев. +- Приватность уведомлений. +- Настройки экрана блокировки. + +Не позволяй отключать обязательную проверку личности без соответствующей авторизации. + +### 18.13. Питание и батарея + +- Процент заряда. +- Состояние зарядки. +- Профиль энергопотребления. +- Тайм-аут дисплея. +- Тайм-аут блокировки. +- Suspend. +- Настройки энергосбережения. +- Статистика батареи, если данные доступны. + +### 18.14. Клавиатура и ввод + +- Раскладки клавиатуры. +- Переключение языка. +- Повтор клавиш. +- Настройки мыши. +- Настройки тачпада. +- Сенсорный ввод. +- Экранная клавиатура. +- Скорость указателя. +- Жесты тачпада, если поддерживаются. + +### 18.15. Приложения + +- Список установленных приложений. +- Информация о приложениях. +- Настройки отображения в лаунчере. +- Приложения по умолчанию через XDG. +- Автозапуск пользовательских приложений. +- Разрешения Flatpak через подходящие системные инструменты, если доступны. + +Не обещай универсальное управление разрешениями для обычных несандбоксированных Linux-приложений. + +### 18.16. Система + +- Информация об устройстве. +- CPU. +- RAM. +- GPU. +- Версия ядра. +- Версия Hyprland. +- Версия Quickshell. +- Информация о дисплеях. +- Диагностика оболочки. +- Экспорт конфигурации. +- Импорт конфигурации. +- Сброс настроек оболочки с подтверждением. + +### 18.17. Developer Options + +- Принудительный phone/tablet/desktop mode. +- Отображение FPS, если доступно. +- Отображение нагрузки CPU. +- Отображение RAM. +- Отладка жестов. +- Логи Quickshell. +- Логи интеграции Hyprland. +- Диагностика D-Bus. +- Проверка системных сервисов. +- Перезапуск пользовательской оболочки. +- Безопасный возврат к предыдущей конфигурации. + +--- + +# 19. Настройки должны реально работать + +Не создавай декоративное приложение Settings. + +Каждый переключатель должен: + +1. Читать реальное состояние. +2. Показывать его пользователю. +3. Изменять соответствующую настройку через поддерживаемый API. +4. Обрабатывать ошибки. +5. Сохранять пользовательские предпочтения там, где это необходимо. +6. Обновлять UI после изменения состояния извне. + +Если функция не поддерживается устройством, скрывай её или показывай понятное состояние «Не поддерживается». + +Не используй фиктивные данные. + +Для операций, требующих привилегий, используй стандартные механизмы авторизации Linux, включая polkit, если это применимо. + +Не запускай весь Settings от root. + +--- + +# 20. Единое хранилище настроек + +Создай общую систему конфигурации для Quickshell и Settings. + +Требования: + +- Сохранение настроек. +- Валидация значений. +- Версионирование схемы. +- Миграции. +- Атомарная запись. +- Защита от повреждения файла. +- Синхронизация между открытыми окнами Settings и оболочкой. +- Отдельные настройки дисплеев. +- Общие настройки темы. +- Профили phone/tablet/desktop. +- Экспорт и импорт. +- Сброс настроек. + +Используй XDG Base Directory Specification. + +Не храни секреты Wi-Fi, VPN, пароли или биометрические данные в обычном JSON-файле оболочки. + +Для секретов используй соответствующие системные хранилища и сервисы. + +--- + +# 21. Производительность + +Целевые устройства включают слабые ARM64-телефоны с 4 ГБ RAM и GPU Mali-G52 MC2 под Mesa/Panfrost. + +Оптимизируй: + +- Потребление RAM. +- CPU в простое. +- Количество QML-объектов. +- Перерисовку. +- Загрузку иконок. +- Обработку изображений. +- Анимации. +- Видеообои. +- Работу с D-Bus. +- Обработку событий Hyprland. + +Не создавай постоянный polling там, где доступны события. + +Используй ленивую загрузку. + +Не допускай, чтобы закрытый Settings продолжал выполнять тяжёлые операции. + +Добавь режим снижения визуальных эффектов для слабых устройств. + +Сравни фактические показатели с исходной конфигурацией Waybar + SwayNC + Rofi + Hyprpaper. + +Не придумывай результаты бенчмарков. + +--- + +# 22. Тестирование на компьютере + +Обязательно реализуй возможность тестирования phone и tablet mode на desktop. + +Создай скрипты: + +```text +scripts/test-desktop.sh +scripts/test-tablet.sh +scripts/test-phone.sh +scripts/test-settings.sh +``` + +Используй вложенную тестовую сессию Hyprland, если она поддерживается установленной системой. + +Примерные размеры: + +- Phone: 390×844. +- Tablet: 768×1024. +- Desktop: 1920×1080. + +Тестовая сессия не должна менять основную конфигурацию Hyprland. + +Поддержи эмуляцию сенсорных жестов мышью для UI-тестов. + +Отдельно документируй, какие проверки требуют настоящего сенсорного экрана. + +--- + +# 23. Тестирование на телефоне + +Проверь: + +- Arch Linux ARM aarch64. +- Запуск Hyprland. +- Запуск Quickshell. +- Status Bar. +- Home Screen. +- App Drawer. +- Recent Apps. +- Свайп домой. +- Свайп назад с обоих краёв. +- Уведомления. +- Quick Settings. +- Settings. +- Экранную клавиатуру. +- Блокировку. +- Fingerprint Unlock, если драйвер поддерживается. +- Suspend/resume. +- Поворот экрана. +- Управление яркостью. +- Управление громкостью. +- Батарею. +- Производительность. + +Не заявляй об успешном аппаратном тестировании без реального запуска на устройстве. + +--- + +# 24. Безопасная миграция + +Переход должен происходить постепенно. + +Порядок: + +1. Сохрани резервную копию. +2. Проверь зависимости. +3. Реализуй Quickshell. +4. Запусти его в тестовом режиме. +5. Проверь панель. +6. Проверь уведомления. +7. Проверь лаунчер. +8. Проверь Settings. +9. Проверь обои. +10. Проверь мобильную навигацию. +11. Проверь новый Lock Screen. +12. Проверь fingerprint authentication. +13. Проверь Hypridle. +14. Проверь suspend/resume. +15. Только после успешных проверок отключи старые компоненты. + +Сохрани возможность отката к: + +- Waybar. +- SwayNC. +- Rofi. +- Hyprpaper. +- Hyprlock. + +Особенно важно: не отключай Hyprlock, пока новый блокировщик не прошёл проверки безопасности и восстановления после сбоев. + +--- + +# 25. Документация + +Создай: + +```text +README.md +AGENTS.md +ARCHITECTURE.md +IMPLEMENTATION_STATUS.md +TESTING.md +MIGRATION.md +ROLLBACK.md +``` + +README должен содержать: + +- Установку на Arch Linux. +- Установку на Arch Linux ARM. +- Зависимости. +- Запуск из TTY. +- Автозапуск Quickshell. +- Запуск Settings. +- Переключение режимов. +- Настройку жестов. +- Настройку отпечатка пальца. +- Проверку блокировки. +- Тестирование мобильного интерфейса на ПК. +- Диагностику проблем. +- Возврат к исходной конфигурации. + +В `IMPLEMENTATION_STATUS.md` отмечай для каждого компонента: + +- Реализовано. +- Протестировано на desktop. +- Протестировано на ARM64. +- Требует проверки на устройстве. +- Имеет технические ограничения. + +Не называй непроверенную функцию полностью готовой. + +--- + +# 26. Порядок разработки + +Работай последовательно: + +1. Аудит существующей конфигурации. +2. Резервное копирование. +3. Архитектура Quickshell. +4. Material 3 Design System. +5. Общие системные сервисы. +6. Desktop Panel. +7. Notification Center. +8. Quick Settings. +9. Application Launcher. +10. Home Screen. +11. Recent Apps. +12. Gesture Navigation. +13. Tablet Layout. +14. Phone Layout. +15. Wallpaper Engine. +16. Settings Application. +17. Secure Lock Screen. +18. Fingerprint Authentication. +19. Hypridle Integration. +20. Multi-monitor Convergence. +21. ARM64 Optimization. +22. End-to-end Testing. +23. Исправление ошибок. +24. Документация и миграция. + +После каждого этапа выполняй доступные тесты. + +Не переходи к опасной замене механизма блокировки, пока не готовы проверки и откат. + +--- + +# 27. Критерии завершения + +Проект считается завершённым, когда: + +- Существующая конфигурация Hyprland сохранена и адаптирована. +- Quickshell заменяет Waybar. +- Quickshell заменяет SwayNC. +- Quickshell заменяет Rofi в согласованных сценариях. +- Quickshell заменяет Hyprpaper. +- Hypridle продолжает работать. +- Экран блокировки безопасен. +- Отпечаток пальца работает на поддерживаемом оборудовании. +- Домашний экран работает. +- App Drawer работает. +- Recent Apps работает. +- Жесты работают на настоящем сенсорном экране. +- Назад работает с обоих боковых краёв там, где приложение поддерживает соответствующее действие. +- Свайп снизу вверх возвращает домой без удержания. +- Свайп сверху вниз открывает шторку. +- Настройки доступны через полноценное Material 3 Settings. +- Настройки действительно изменяют систему. +- Поддерживаются desktop, tablet и phone. +- Есть тесты для мобильного режима на ПК. +- Есть инструкции для ARM64. +- Нет необходимости устанавливать Display Manager. +- Нет ненужных постоянно работающих процессов. +- Есть безопасный механизм отката. + +--- + +# 28. Финальные инструкции агенту + +Начни с повторной сверки раздела 1 с рабочим деревом: `hypr/hyprland.lua`, его Lua-модули, конфигурации отдельных демонов и скрипты. Затем проверь реально загруженную конфигурацию и установленные версии компонентов. Отделяй проверенное по коду, проверенное в сессии и ещё не проверенное на оборудовании. + +Не переписывай всё с нуля. + +Не ограничивайся генерацией примеров кода. + +Изменяй реальные файлы. + +Если в существующей конфигурации уже есть нужная функциональность, сохрани её и интегрируй с новой оболочкой. + +Не делай предположений о поддержке конкретного API без проверки. + +Не придумывай команды Hyprland, Quickshell или системных сервисов. + +Не создавай фиктивные UI-элементы. + +Не отключай действующие средства безопасности без полноценной проверенной замены. + +Продолжай разработку и исправление ошибок до максимально полного рабочего результата. + +Если некоторые возможности требуют реального телефона, аппаратного драйвера или дополнительной интеграции с композитором, реализуй всё, что возможно в доступной среде, и документируй оставшиеся проверки. + +**Начинай с аудита. Затем переходи к реализации, тестированию и интеграции. Главная цель — единая, быстрая, безопасная и адаптивная Material 3 оболочка для Hyprland на desktop, tablet и phone, полностью управляемая через собственное приложение Settings.** + +# Дополнение: Dynamic Hardware Capability Detection & Adaptive UI + +## 1. Основная задача + +Реализуй динамическую систему обнаружения аппаратных и программных возможностей устройства для всей оболочки Hyprland + Quickshell и приложения Material 3 Settings. + +**Главное правило: отображай только те элементы управления, для которых существует реальное поддерживаемое оборудование или доступная системная функция.** + +Не показывай несуществующие переключатели и не создавай фиктивные устройства. + +Это правило должно действовать во всех интерфейсах: + +- Desktop Panel. +- Phone Status Bar. +- Tablet Status Bar. +- Quick Settings. +- Notification Shade. +- Settings Application. +- Lock Screen. +- Power Management. +- Device Management. + +## 2. Обнаружение оборудования + +Создай единый `HardwareCapabilityService`, который отслеживает доступные возможности через системные API. + +Используй: + +- NetworkManager D-Bus — сетевые интерфейсы и подключения. +- ModemManager D-Bus — мобильные модемы, SIM, мобильная передача данных. +- BlueZ D-Bus — Bluetooth-контроллеры. +- PipeWire/WirePlumber — аудиоустройства. +- UPower — аккумуляторы и питание. +- sysfs и udev — аппаратные устройства. +- iio-sensor-proxy — датчики ориентации. +- Hyprland IPC — мониторы и устройства ввода. +- fprintd — поддерживаемые сканеры отпечатков. +- Поддерживаемые интерфейсы управления подсветкой. +- Доступные интерфейсы управления фонариком. + +Не выполняй непрерывный polling, если можно подписаться на события D-Bus, udev или композитора. + +## 3. Динамические сетевые элементы + +### Wi-Fi + +Если Wi-Fi-адаптер отсутствует: + +- Не показывай Wi-Fi в Quick Settings. +- Не показывай индикатор Wi-Fi в системной панели. +- Не показывай переключатель Wi-Fi в Settings. +- Не отображай пустой список беспроводных сетей. + +Если адаптер подключён, соответствующие элементы должны появиться автоматически. + +Если адаптер существует, но Wi-Fi выключен, показывай переключатель в состоянии Off, а не скрывай его. + +### Ethernet + +Если существует один или несколько проводных интерфейсов: + +- Показывай Ethernet в Quick Settings. +- Показывай соответствующий сетевой статус в системной панели. +- Показывай раздел проводных сетей в Settings. +- Поддерживай несколько физических и виртуальных интерфейсов. +- Отображай реальное состояние каждого интерфейса. +- Показывай IP, скорость соединения и другие параметры, если они доступны. +- Поддерживай DHCP и статическую конфигурацию через NetworkManager. +- Не объединяй разные Ethernet-интерфейсы в одно фиктивное устройство. + +Если Ethernet-интерфейсов несколько, показывай компактную сводку и раскрываемый список интерфейсов. + +### Mobile Data / SIM + +Если в системе отсутствует поддерживаемый мобильный модем: + +- Не показывай Mobile Data. +- Не показывай SIM Settings. +- Не показывай индикатор сотового сигнала. +- Не показывай настройки APN. +- Не показывай переключатель мобильной передачи данных. + +Если модем обнаружен, но SIM отсутствует, показывай состояние «Нет SIM» в соответствующем разделе, а не скрывай модем полностью. + +Если есть несколько SIM или eSIM-профилей, поддерживай их в пределах возможностей ModemManager и оборудования. + +Не путай отсутствие модема с отключённой мобильной передачей данных. + +## 4. Пример поведения + +| Оборудование | Видимые сетевые элементы | +| ----------------------------- | --------------------------------------------------- | +| Desktop с одним Ethernet | Ethernet | +| Desktop с двумя Ethernet | Ethernet 1, Ethernet 2 | +| Desktop с Ethernet + Wi-Fi | Ethernet, Wi-Fi | +| Ноутбук с Wi-Fi | Wi-Fi | +| Телефон с Wi-Fi + LTE | Wi-Fi, Mobile Data, SIM | +| Телефон без доступного модема | Wi-Fi, если адаптер обнаружен | +| ПК без сетевых устройств | Общий статус сети без несуществующих переключателей | + +Общий раздел «Сеть» в Settings можно сохранять для диагностики и настройки будущих подключений, даже если сейчас нет доступных адаптеров. + +## 5. Обнаружение других компонентов + +Применяй ту же логику ко всем аппаратным функциям. + +| Возможность | Когда показывать | +| --------------------- | -------------------------------------------- | +| Bluetooth | Есть поддерживаемый контроллер | +| Батарея | Есть доступный аккумулятор | +| Яркость | Есть управляемая подсветка дисплея | +| Микрофон | Есть доступный источник аудиоввода | +| Динамики / аудиовыход | Есть доступный аудиовыход | +| Отпечаток пальца | Есть поддерживаемый сканер | +| Фонарик | Есть доступный и управляемый LED | +| Автоповорот | Есть поддерживаемые датчики ориентации | +| Камера | Есть доступное устройство камеры | +| Внешние мониторы | Hyprland обнаруживает соответствующие выходы | +| Power Profiles | Есть поддерживаемый backend | +| NFC | Есть поддерживаемый NFC-контроллер | + +Не считай наличие устройства доказательством того, что все его функции поддерживаются. Проверяй конкретные операции. + +## 6. Различай состояния оборудования + +Для каждой возможности реализуй состояния: + +- `unavailable` — оборудование отсутствует. +- `available` — оборудование обнаружено. +- `disabled` — оборудование есть, но функция отключена. +- `blocked` — аппаратная или программная блокировка. +- `unsupported` — устройство обнаружено, но необходимый backend не поддерживает функцию. +- `error` — ошибка доступа или инициализации. + +Не скрывай устройство только потому, что оно временно отключено, не подключено к сети или заблокировано через rfkill. + +Если устройство поддерживается, но действие требует дополнительных разрешений, показывай его и корректно запрашивай авторизацию. + +## 7. Горячее подключение оборудования + +Поддерживай изменения без перезапуска Quickshell: + +- Подключение USB Wi-Fi. +- Отключение Wi-Fi. +- Подключение Ethernet. +- Подключение USB Ethernet. +- Подключение Bluetooth-адаптера. +- Подключение внешнего аудиоустройства. +- Подключение внешнего монитора. +- Подключение или отключение зарядки. +- Появление и исчезновение модема. + +Используй событийную модель. + +Обновляй состояние и доступные элементы интерфейса автоматически. + +## 8. Адаптивная компоновка + +При исчезновении недоступного элемента остальные элементы должны занимать освободившееся место. + +Не оставляй пустые плитки, разделители или пробелы. + +Desktop: + +- Компактная системная панель. +- Только реальные индикаторы. +- Quick Settings без несуществующих устройств. + +Tablet: + +- Адаптивная сетка переключателей. +- Перестройка при изменении доступных функций. + +Phone: + +- Только доступные плитки. +- Компактная status bar. +- Корректная компоновка при повороте дисплея. + +Сохраняй пользовательский порядок плиток даже при временном исчезновении оборудования. + +## 9. Settings Application + +Все разделы Settings должны использовать общий `HardwareCapabilityService`. + +Не создавай отдельную несовместимую логику определения устройств для каждого экрана. + +Например: + +- Если Wi-Fi отсутствует, скрывай Wi-Fi-настройки из обычного пользовательского интерфейса. +- Если обнаружен только Ethernet, показывай настройки Ethernet. +- Если есть несколько Ethernet, показывай каждый интерфейс отдельно. +- Если нет Bluetooth-контроллера, скрывай обычные Bluetooth-переключатели. +- Если нет аккумулятора, не показывай фиктивный процент заряда. +- Если нет сканера отпечатка, не предлагай регистрацию отпечатка. + +Добавь в Developer Options отдельный раздел **Hardware Capabilities**, где можно увидеть все обнаруженные и отсутствующие возможности, причины недоступности и ошибки backend. + +## 10. Тестирование + +Реализуй автоматические тесты со смоделированными состояниями оборудования: + +1. Только Ethernet. +2. Несколько Ethernet-интерфейсов. +3. Только Wi-Fi. +4. Ethernet + Wi-Fi. +5. Wi-Fi + LTE. +6. Модем без SIM. +7. Отсутствие Bluetooth. +8. Отсутствие батареи. +9. Отсутствие датчика яркости или управляемой подсветки. +10. Отсутствие сканера отпечатка. +11. Подключение USB-адаптера во время работы. +12. Отключение устройства во время открытых Settings. + +Проверь, что пользовательский интерфейс обновляется корректно, не падает и не отображает фиктивные элементы. + +Для тестов используй mock-backend, но никогда не подменяй реальные данные mock-значениями в обычном режиме. + +## 11. Критерии готовности + +- Система определяет реальные аппаратные возможности. +- Не показывает несуществующие переключатели. +- Сохраняет элементы для существующих, но отключённых устройств. +- Поддерживает несколько Ethernet-интерфейсов. +- Поддерживает появление и исчезновение устройств. +- Корректно перестраивает Material 3 интерфейс. +- Использует единый backend для Shell и Settings. +- Работает на x86_64 и aarch64. +- Не требует перезапуска Quickshell при hotplug. +- Не создаёт дополнительную постоянную нагрузку на CPU. + +**Интегрируй эту систему в существующую архитектуру Quickshell + Hyprland + Material 3 Settings. Не реализуй её как отдельное приложение. Все компоненты оболочки должны использовать единый источник информации об аппаратных возможностях.** diff --git a/docs/quickshell/README.md b/docs/quickshell/README.md new file mode 100644 index 0000000..0db235d --- /dev/null +++ b/docs/quickshell/README.md @@ -0,0 +1,403 @@ +# Adaptive Shell: состояние реализации + +Desktop-этап реализации задания из `docs/prompt/hyprland_quickshell_adaptive_shell.md`. +Проверено 17 ноября 2026 на Quickshell 0.3.2, Qt 6.12 и работающей Wayland-сессии Hyprland. +Это ещё не завершённая конвергентная оболочка по всем критериям мастер-промпта. + +## Реализовано + +- `quickshell/shell.qml`: один процесс, общий набор сервисов, IPC для открытия экранов. +- Панель на каждом выходе, рабочие пространства, заголовок активного окна, часы, + системный трей и реальные аккумуляторы через UPower; доступ к аудиоустройствам, + состоянию/заглушению микрофона и меню питания. IPC открывает панели на мониторе + с фокусом Hyprland; физическая проверка нескольких мониторов ещё предстоит. +- Launcher: XDG DesktopEntries, фильтрация, сетка, клавиатурная навигация, + выполнение через DesktopEntry.execute(), без исполнения поисковой строки. + Избранное сохраняется по Desktop Entry ID, история ограничена 50 записями; + в выдаче сначала избранное, затем последние запуски, затем алфавит. + Кнопка ★ и Пробел на выбранном приложении переключают закрепление. +- Desktop Settings — отдельное управляемое окно с изменяемым размером, боковой + навигацией и компактным переключателем разделов при узком окне. Повторный вызов + открывает то же окно. Секция звука доступна также из панели и Quick Settings. +- Quick Settings: NetworkManager через Quickshell.Networking, отдельные интерфейсы, + Wi-Fi с учётом аппаратной блокировки; адаптеры BlueZ; PipeWire volume/mute, + микрофон; MPRIS. Для расширенного редактирования подключений и сопряжения + открываются nm-connection-editor и blueman-manager. Это временные внешние инструменты, + а не собственные страницы Settings. Выбор устройства ввода/вывода, mute и громкость + каждого устройства уже реализованы внутри Settings через PipeWire/WirePlumber. + Изменения устройств отслеживаются общей моделью без polling. +- Статические обои: отдельный Background-слой на каждом мониторе без захвата ввода + и резервирования рабочей области. Выбор через FileDialog/локальный путь, предпросмотр, + общий фон и отдельные настройки выходов, включая сохранённые отключённые мониторы. + При ошибке декодирования новый файл не подменяет последние загруженные обои. + Есть отключение слоя и возврат к общему фону; настройки переживают restart и QML reload. + Без выбора обоев фоновые поверхности не создаются. Hyprpaper пока сохранён для отката. +- Отдельная страница «Сеть»: каждый интерфейс отдельно, MAC, состояние управления, + Ethernet carrier/link speed, Wi-Fi сети/уровень сигнала/защита. Native connect для + сохранённых, открытых/OWE и PSK-сетей, подтверждение disconnect интерфейса, + ошибки/тайм-ауты и защита от повторного запроса. PSK-поле очищается при отправке, + закрытии страницы и успешном подключении; секреты не пишутся в preferences JSON. + Сканирование Wi-Fi включено только при активной странице с доступным radio. +- Отдельная Bluetooth-страница: адаптеры, реальные устройства/состояния, + включение/выключение radio, connect/disconnect и удаление сопряжения с подтверждением. + Discovery — явный поиск до минуты, прекращающийся при закрытии страницы; + helper удерживает собственную BlueZ discovery session. Ошибки возвращаются в UI. + Сопряжение с PIN/passkey пока выполняется через системный диалог Blueman. +- Settings: общая и индивидуальная для мониторов компоновка, light/dark/AMOLED, + ручное указание сенсорного режима, reduced motion и диагностика доступных backend. +- Настройки в `Quickshell.statePath("preferences.json")`: схема v1, проверка значений, + атомарная запись и наблюдение за внешними изменениями. Повреждённый или более новый + файл не перезаписывается; Settings показывает его путь. Хранение секретов отсутствует. +- Desktop/tablet/phone layout по логической ширине и ручной настройке touch; + нижняя кнопочная навигация в мобильных режимах. Автообнаружение touchscreen пока отсутствует. +- Recent: настоящие окна через Wayland ToplevelManager, переключение и закрытие. + Миниатюры не имитируются. +- Экспериментальный Notifications backend: получение, изображения, actions, + удаление, clear all, группировка по desktop entry/имени приложения, всплывающая карточка, + сохранённый DND без повторного показа старых всплывающих карточек, лимит 100 текущих уведомлений. + История на диске ограничена 100 записями, доступна после перезапуска, имеет отключение + и очистку; transient-уведомления не сохраняются и не появляются в центре. + Изображения и клиентские actions не записываются в историю. Архивные карточки + не восстанавливают мёртвые D-Bus-действия. + Тайм-ауты: клиентское положительное значение в миллисекундах, 0 — без автоистечения, + default — 3 с для low и 6 с для normal; critical требует явного закрытия. + Изменившаяся replacement-посылка перезапускает таймер и обновляет существующую запись. + Мягкий QML reload не дублирует историю и не воспроизводит старую всплывающую карточку. + По умолчанию выключен, SwayNC продолжает работать. +- Меню питания: доступность действий через logind, явное подтверждение выхода, + перезагрузки, выключения и сна; ожидание, ошибки backend и блокировка повторных запросов. + Перед сном backend ожидает compositor-confirmed lock через Hyprland lock-notify. + Settings использует то же меню вместо отдельной detached-команды блокировки. +- Опциональное подключение из существующего Lua startup; старые команды сохранены + как профиль по умолчанию. Установщик Settings entry не меняет сессию и пакеты. + +Цвета основаны на фиксированной палитре Material 3; Dynamic Color, полная типографика +и полный набор Material-компонентов пока не реализованы. QtQuick Controls запускаются +со стилем Material через wrapper. Reduced motion сохранён в настройках; текущие экраны +не используют собственные анимации. + +## Запуск и возврат + +Из корня репозитория, внутри Wayland-сессии: + +```sh +./hypr/bin/adaptive-shell start +``` + +Это предварительный запуск рядом с действующей панелью, без отключения Waybar/SwayNC. +В другом терминале: + +```sh +./hypr/bin/adaptive-shell settings +./hypr/bin/adaptive-shell launcher +./hypr/bin/adaptive-shell recent +./hypr/bin/adaptive-shell stop +``` + +Wrapper для открытия страницы запускает процесс, если он отсутствует. + +Для подключения вместо Waybar в **следующей сессии** запусти из TTY: + +```sh +ADAPTIVE_SHELL=1 start-hyprland +``` + +Привязки Alt+D, XF86LaunchB, Alt+Shift+P и Alt+Z используют новую оболочку. +SwayNC остаётся сервером уведомлений, Hyprpaper — исходным/резервным фоном, SwayOSD — OSD. +При выборе обоев в Settings новый Background-слой Quickshell отображается поверх прежнего фона. +Hyprlock, Hypridle, lxpolkit, Clipse, Sherlock и пользовательские приложения сохраняются. +Переменная должна быть установлена при запуске композитора, а не только Quickshell. + +Возврат: выйди из сессии и запусти `start-hyprland` без `ADAPTIVE_SHELL`. +При аварии оболочки внутри активного нового профиля можно вручную запустить `waybar`, +а приложения открывать из терминала; постоянные настройки Hyprland профилем не меняются. + +Notifications backend пока остаётся экспериментальным: ещё нужны проверки приватности +при lock/suspend, inline replies, поведения нескольких одновременных всплывающих карточек +и безопасной миграции владельца D-Bus. SwayNC по умолчанию сохранён. В тесте эта переменная используется с отдельной +D-Bus-шиной. При включении в новом профиле startup не запускает SwayNC; уже запущенный +SwayNC автоматически не завершается. Не запускай два notification server на одной шине. + +Установка команды и `.desktop` файла Settings (с резервными копиями существующих файлов): + +```sh +python quickshell/install.py # показать пути +python quickshell/install.py --apply # записать launcher и desktop entry +``` + +Установщик не устанавливает пакеты, не создаёт автологин, не включает systemd services, +не запускает `install_scripts/install-arch.sh`. Конфигурация запускается прямо из репозитория, +поэтому перемещение репозитория требует повторной установки launcher. + +## Проверки + +```sh +QT_QPA_PLATFORM=offscreen /usr/lib/qt6/bin/qmltestrunner -input quickshell/tests -o -,txt +lua quickshell/tests/test_lua.lua 0 0 +lua quickshell/tests/test_lua.lua 1 0 +lua quickshell/tests/test_lua.lua 1 1 +python quickshell/tests/smoke.py +python quickshell/tests/notifications.py +python quickshell/tests/wallpapers.py +python -m unittest discover -s quickshell/tests -p 'test_power_backend.py' -v +python quickshell/tests/power_controller.py +python quickshell/tests/network_controller.py +python -m unittest discover -s quickshell/tests -p 'test_bluetooth_backend.py' -v +python quickshell/tests/bluetooth_controller.py +``` + +QtTest: 27 успешных проверок, включая границы режимов, отбрасывание некорректной схемы, +ранжирование приложений, лимит/уникальность истории и избранное, notification timeout policy +и валидацию notification history, локальные file URL, наследование обоев и совместимость схемы. +Lua: проверены три комбинации старого/нового профиля и notifications без исполнения команд. +Wayland smoke: загрузка всех страниц, включая native audio, IPC, проверка Settings +в списке управляемых окон Hyprland, смена трёх режимов, темы, запись JSON, +подхват внешних настроек, защита повреждённого JSON от перезаписи и восстановление, +отправка уведомления на частной D-Bus-шине. Тест временно показывает панель и экраны, +не останавливает текущие компоненты, использует временное хранилище. + +Python-тесты сами создают частную D-Bus-шину, даже при прямом запуске, и используют +временное хранилище. Lifecycle-тест требует PyGObject (`python-gobject` на Arch). +Он проверяет replacement, причины закрытия 1/2/3, ActionInvoked, DND, critical/transient, +группировку, сохранение/очистку/отключение истории, права каталога, QML reload, +перезапуск процесса и продолжение доставки при повреждённом файле истории. +Wallpaper-тест проверяет загрузку PNG с Unicode/пробелами/спецсимволами в пути, +настоящие Background-слои через Hyprland IPC, переопределение выхода, запрет удалённых URL, +сохранение прежнего изображения при отсутствующем файле, отключение слоя, наследование, +сохранение настройки отключённого выхода и восстановление после restart/QML reload. +Тест не останавливает Hyprpaper и в конце снимает свои фоновые поверхности. + +Используй Qt 6 tools: `/usr/bin/qmllint` на этой машине относится к Qt 5. +Qt 6 qmllint сообщает предупреждения о метаданных Quickshell PanelWindow и динамических +моделях, а также о неквалифицированных обращениях в delegates; чистый lint пока не заявлен. +При runtime-проверке остаются предупреждения внешних SVG-иконок и Wayland text input. +BlueZ на этой машине не предоставляет доступный object manager; отсутствие контроллера +обработано, но реальное Bluetooth-сопряжение не проверено. +Изолированный headless Hyprland здесь не запускается: отсутствует `/dev/dri`, +Aquamarine сообщает `CBackend::create() failed`. Smoke проверен в существующей сессии. + +## Следующие обязательные этапы + +1. Полноценная дизайн-система: токены, шрифты, Material Symbols, Dynamic Color, + системная тема, motion, доступность и адаптивная навигация Settings. +2. Собственные расширенные страницы профилей сети/IP/DNS/VPN и pairing-agent Bluetooth, обработка + оставшихся ошибок/авторизации (базовая native страница сети уже реализована), + яркость, power profiles, модемы/SIM и расширенные состояния HardwareCapabilityService. + Сейчас отсутствие backend и отсутствие оборудования не везде различимы. +3. Уведомления: inline replies, privacy lock/suspend, очередь всплывающих карточек, + безопасное переключение владельца D-Bus и оставшиеся ограничения reload/replacement, + перечисленные ниже. Базовые history/grouping/timeout/close/action тесты уже реализованы. +4. Home Screen с папками, dock, drag-and-drop, избранным и сохранением состояния; + Desktop Actions и тесты всех полей Desktop Entry в launcher (история и избранное уже есть). +5. Глобальные touchscreen-жесты через проверенную интеграцию с композитором; + маршрутизация Back, удержание для Recent, safe areas, экранная клавиатура, landscape. + Нижние кнопки текущей реализации не считаются реализацией этих жестов. +6. Slideshow, видеообои, отдельные lock-screen обои и аппаратные проверки multi-output/hotplug + (статический Wallpaper engine с per-output настройками уже реализован); + расширенные страницы мониторов с подтверждением/откатом и политики композитора. + Глобальные gaps/borders нельзя менять независимо для мониторов без проверки API. +7. Безопасная блокировка ext-session-lock-v1, PAM/fprintd и аппаратная проверка. + До этого Hyprlock остаётся обязательным блокировщиком. Новый helper `lock-session` + не меняет обои/конфиг, но действующие lock bindings и idle-конфигурация не переписаны. + Сохранение Hyprlock не доказывает выполнение всех требований fail-closed/suspend. +8. Исправление существующей опечатки `brightnesctl` в Hypridle после проверки реального + пути конфигурации, единый lock entrypoint, проверка inhibitor перед suspend/resume. +9. Безопасные backup/import/export/reset/migrations, автоматический rollback, + обновлённые общие инструкции установки и окончательная миграция компонентов. +10. Mock-тесты hotplug и всех комбинаций оборудования, реальные multi-monitor, + touchscreen, ARM64/телефон, suspend/resume, fingerprint и замеры CPU/RAM/энергии. + +До завершения этих этапов критерии готовности раздела 27 мастер-промпта не выполнены. + +## Порядок дальнейшей разработки + +Приоритет — завершить и стабилизировать desktop. Phone сохраняется как архитектурная +цель, но физические проверки телефона начнутся после desktop-этапа. Переключение +layout на desktop в smoke-тесте не считается проверкой phone, touchscreen или ARM64. + +На текущем desktop обнаружены два устройства вывода и одно устройство ввода. Проверены +построение native audio UI и подписка на модель; автоматический тест не меняет громкость, +mute и выбранные устройства пользователя. Переключение/отключение физических устройств +и реальное Bluetooth-сопряжение остаются ручными проверками. + +## История уведомлений и ограничения Quickshell + +История хранится в `Quickshell.statePath("notification-history/notifications.json")`. +Подкаталог создаётся с правами `0700` через одноразовый вызов GNU `install`; периодического +опроса и постоянно работающего вспомогательного процесса нет. Это локальный JSON с текстом +уведомлений. Переключатель «Сохранять историю» позволяет прекратить запись и очистить её. +Повреждённый файл не перезаписывается автоматически: ошибка отображается в центре, +новые уведомления продолжают поступать. Для восстановления после остановки оболочки +перенеси повреждённый файл в резервную копию и запусти оболочку снова. + +Для Quickshell 0.3.2 тайм-аут проверен прямым D-Bus-вызовом с 250 мс. Реальный backend +передаёт миллисекунды; описание `expireTimeout` в онлайн-документации на момент работы +указывает секунды. При обновлении Quickshell повторяй lifecycle-тест, не меняй единицы +только по тексту документации. Использованы [Notification API](https://quickshell.org/docs/v0.3.2/types/Quickshell.Services.Notifications/Notification/) +и [исходники backend](https://github.com/quickshell-mirror/quickshell/blob/master/src/services/notifications/notification.cpp). + +У Quickshell 0.3.2 новый `notification` signal не приходит для replacement существующего +объекта; оболочка отслеживает изменения его свойств. Полностью идентичная replacement-посылка +без изменений свойств пока не обнаруживается и не сбрасывает таймер. Это ограничение API +нужно закрыть upstream-хуком или отдельной проверенной интеграцией перед окончательной миграцией. +Для transient-уведомлений оставшееся время после QML reload может отсчитываться заново: +намеренно не сохраняются их данные на диск. История обычных уведомлений сохраняет deadline +для восстановления при мягком reload. Полный перезапуск процесса восстанавливает только +архивный текст, а не активные уведомления/клиентские actions. + +## Статические обои на desktop + +Открыть страницу можно из Settings → «Обои» или командой: + +```sh +./hypr/bin/adaptive-shell wallpapers +``` + +Выбери общий фон или конкретный выход, затем файл и «Применить». Имя монитора хранится +как ключ настройки, поэтому порядок подключённых выходов не влияет на выбор. +Для отключённого выхода доступна настройка будущего подключения; фиктивное окно для него +не создаётся. «Использовать общие обои» удаляет override, а «Использовать прежний фон» +отключает слой для выбранного выхода (или общий фон, если выбран общий пункт). + +Принимаются только абсолютные локальные пути и локальные `file:///` URL. Текст пути +не передаётся shell-команде. Новые поля `wallpapers` необязательны в прежней схеме v1. +Предпросмотр и рендер используют Qt Image; доступность формата зависит от Qt-плагинов. +Декодирование фонового изображения ограничено 4096 пикселями по каждой оси, crop сохраняет +соотношение сторон. Dynamic Color, slideshow и видео этим этапом не реализованы. + +Последнее успешное изображение удерживается в памяти текущего процесса, пока грузится +новое или показывается ошибка. Если ошибочный путь сохранён и процесс перезапущен, +прежнее изображение из памяти не восстанавливается: остаётся исходный фон Hyprpaper. +Полное отключение Hyprpaper и гарантированный fallback без него требуют отдельного этапа +миграции. Физическое подключение/отключение нескольких мониторов пока не проверено; +на текущем desktop проверен один реальный выход и сохранение настройки отключённого. +FileDialog загружается вместе со страницей; ручной выбор файла через системный диалог +пока не входит в автоматический smoke-тест. + +## Меню питания desktop + +Меню доступно из панели, Alt+Shift+P в новом профиле и Settings → «Оболочка» → +«Блокировка и питание…». В нём есть lock, suspend, logout, reboot и poweroff. +Возможности перечитываются при открытии и по кнопке обновления; постоянного опроса нет. +Неизвестные/недоступные действия отключены с причиной, а состояние `challenge` для +reboot/poweroff обозначено как требующее авторизации. Меню не закрывается при ошибке. +Ожидание имеет тайм-аут, но его сообщение не утверждает, что уже отправленное действие +обязательно отменено. Закрытие меню сбрасывает неподтверждённый выбор. + +Одноразовый `backend/power.py` использует системную D-Bus-шину logind, не root-shell. +Вызовы CanSuspend/CanReboot/CanPowerOff предшествуют действиям. Reboot/poweroff разрешают +обычную авторизацию polkit. Для suspend требуется `CanSuspend=yes`; `challenge` пока +отключает этот пункт: полноценная авторизация до блокировки — отдельная будущая работа. +После подтверждения блокировки Suspend вызывается без интерактивной авторизации, +чтобы не открывать скрытый polkit-диалог под lock screen. Force/ignore-inhibitors флаги +не используются. Logout отправляет фиксированный IPC-dispatch текущему Hyprland, +не вызывает killall и не завершает остальные пользовательские сессии. + +LockObserver сначала подписывается на `hyprland-lock-notify-v1`, затем при необходимости +запускает Hyprlock с `--grace 0` и ждёт `locked`. Наличие процесса или logind LockedHint +не считается подтверждением. При отсутствующем протоколе, завершившемся locker, тайм-ауте +или полученном unlock запрос Suspend не отправляется. Helper не владеет session lock +и не уничтожает lock client при ошибке/завершении наблюдения. Существующие Hypridle, +Alt+B, PAM и настройки Hyprlock этим этапом не переписаны. + +Зависимости runtime для меню: Python 3, `python-gobject`, `python-pywayland`, Hyprlock, +Hyprland с lock-notify и logind. Если зависимость недоступна, это отражается в меню. +Vendored XML и сгенерированные bindings находятся в `backend/protocols/`; сохранены +исходная лицензия, URL и hash XML. Повторная генерация не требует сетевого доступа. +Ориентиры: [logind API](https://www.freedesktop.org/software/systemd/man/latest/org.freedesktop.login1.html) +и [исходный протокол Hyprland](https://github.com/hyprwm/hyprland-protocols/blob/main/protocols/hyprland-lock-notify-v1.xml). + +Проверки: 19 Python unit-тестов с внедрёнными backend/observer, 7 сценариев настоящего +Quickshell Process-controller с явно переданным fake-helper (success, denied, ошибка, +повреждённый ответ, watchdog, неверное действие, отсутствующий helper). Они не вызывают +реальных действий питания. Offscreen fixture запускается отдельно от production shell, +не имеет power IPC и не выбирается через переменную окружения обычного пользователя. +QtTest не загружает статически встроенные плагины Quickshell, поэтому controller проверяется +отдельным runner `power_controller.py`, а не имитацией Process в QtTest. + +В текущей desktop-сессии выполнено только чтение возможностей: logind и lock-notify доступны. +Реальные lock/suspend/resume, logout, reboot/poweroff и интерактивный polkit ещё не проверены. +Проверка порядка вызовов на mock-backend не заменяет проверку блокировки на всех физических +выходах и сна/пробуждения на реальном оборудовании. + +## Сетевые подключения desktop + +```sh +./hypr/bin/adaptive-shell network +``` + +Раздел также доступен в Settings и из Quick Settings. Состояния берутся из общей +модели Quickshell.Networking/NetworkManager, без shell-парсинга `nmcli` и без таймерного +опроса. Отсутствующий backend отличается от пустого списка адаптеров; Wi-Fi switch +не появляется без адаптера и сохраняется для существующего выключенного/blocked устройства. +IP/DNS/VPN, выбор между несколькими сохранёнными профилями, enterprise/EAP/WEP и сертификаты +пока открываются через `nm-connection-editor`. Bluetooth доступен в Quick Settings и отдельной странице Settings; +собственный pairing agent ещё не готов. + +WPA/WPA2-Personal и SAE используют native `connectWithPsk`; пароль передаётся непосредственно +API, не попадает в argv, preferences, диагностический текст или собственный файл оболочки. +NetworkManager может сохранить его в своём хранилище профилей. Поле скрывает ввод и +запрещает предиктивный ввод. Новая enterprise-сеть не получает неподходящий PSK-переключатель. +Для сохранённых сетей сначала пробуется подключение без повторного запроса пароля. +При NoSecrets поле появляется только для поддерживаемых PSK-типов и активной страницы. + +Операция остаётся ожидающей до обновления реального состояния или ошибки. Disconnect +требует подтверждения; 45-секундный timeout сообщает о неподтверждённом результате и +не пытается отключить/отменить соединение автоматически. Удаление интерфейса и потеря +управления учитываются контроллером. Отключённая/скрытая страница не продолжает сканирование. +Сложные случаи polkit/secret agent и ошибки radio toggle ещё требуют доработки и ручной проверки. + +`network_controller.py`: 9 сценариев с явно переданными QML fake-устройствами и реальным +NetworkController, включая правильный адаптер, connect/disconnect, duplicate prevention, +NoSecrets, timeout, удаление/неуправляемое устройство, передачу синтетического PSK и очистку +настоящего TextField при закрытии/подключении. Fixture изолирована от production entrypoint +и не создаёт Networking singleton. На desktop smoke-тесте проверена загрузка страницы +с реальными интерфейсами; connect/disconnect и Wi-Fi switch тестом не вызываются. +Открытие страницы может включать обновление списка сетей, если доступен Wi-Fi-адаптер. +Реальное WPA/EAP-подключение, ввод credentials через OSK и USB-hotplug ещё не проверены. + +API сверено с [Quickshell Network](https://quickshell.org/docs/v0.3.2/types/Quickshell.Networking/Network/), +[WifiNetwork](https://quickshell.org/docs/v0.3.2/types/Quickshell.Networking/WifiNetwork/) +и установленными qmltypes 0.3.2. Скорость Ethernet — физический link speed, не измерение +скорости доступа к Интернету. + +## Bluetooth desktop + +```sh +./hypr/bin/adaptive-shell bluetooth +``` + +Страница показывает адаптеры из общей Quickshell.Bluetooth модели и не создаёт mock-устройств +при отсутствии оборудования. Состояние заблокированного/выключенного адаптера не скрывает +сам адаптер. Включение, выключение, connect/disconnect и forget используют одноразовый +`backend/bluetooth.py` с BlueZ D-Bus, проверкой object paths и структурированными ошибками. +Выключение адаптера, отключение устройства и удаление сопряжения требуют подтверждения. +UI ждёт ответ backend, повторные запросы блокируются; состояние устройства читается из BlueZ, +а не устанавливается оптимистично. Страница не меняет Discoverable, Pairable и Trusted. + +«Найти устройства» запускает временный helper с собственной системной D-Bus connection, +вызывает StartDiscovery и удерживает discovery session. StopDiscovery вызывается тем же +клиентом после закрытия страницы, остановки или тайм-аута до 60 секунд. При зависшем старте +или завершении helper принудительно закрывается; соединение не остаётся живым после процесса. +Поиск, уже выполняющийся другим клиентом, не останавливается. В простое отдельного Bluetooth +процесса нет. Readiness перечитывается при открытии страницы и явном обновлении, без polling. + +Первичное сопряжение, PIN/passkey, Numeric Comparison и подтверждение доверия пока делегированы +`blueman-manager`: оболочка не регистрирует агент, который автоматически принимает запросы. +Встроенный connect предназначен для уже сопряжённых устройств. Дополнительный Quick Settings +switch пока остаётся прямым API Quickshell; полная обработка его отказов ещё предстоит. +Зависимости helper: Python 3, `python-gobject` и работающий BlueZ. Тестовые backend явно +передаются отдельным fixtures и не выбираются через переменную обычной сессии. + +Проверки: 10 Python unit-тестов (пути, маршрутизация, ошибки, lifetime discovery), 14 сценариев +настоящих QML/Process controllers с fake helper (включая watchdog, закрытие до старта, +неудачный старт, отсутствие executable, ограничение времени, смену адаптера и чужой поиск), +desktop smoke с загрузкой Bluetooth-страницы без изменения radio и без реального сопряжения. +В текущей системе read-only вызов BlueZ вернул NameHasNoOwner: проверен экран недоступного +сервиса. Реальные adapter hotplug, поиск, power/rfkill, профили connect/disconnect и pairing +на оборудовании ещё не проверены. Доступного через BlueZ контроллера для этих проверок пока нет; отсутствие самого оборудования +этим не доказано. + +Семантика discovery сверена с [официальным BlueZ Adapter API](https://github.com/bluez/bluez/blob/master/doc/org.bluez.Adapter.rst): +StartDiscovery/StopDiscovery относятся к сессии конкретного клиента, а общий поиск может +продолжаться, пока его используют другие клиенты. diff --git a/fastfetch/config.jsonc b/fastfetch/config.jsonc index a1f72a5..4c13ddc 100644 --- a/fastfetch/config.jsonc +++ b/fastfetch/config.jsonc @@ -1,5 +1,4 @@ { - "$schema": "https://github.com/fastfetch-cli/fastfetch/raw/dev/doc/json_schema.json", "display": { "separator": " ─▶ " }, @@ -207,11 +206,11 @@ "type": "custom", "format": "└────────────────────────────────┘" }, - { - "type": "weather", - "key": "├▶ ", - "keyColor": "white" - }, + // { + // "type": "weather", + // "key": "├▶ ", + // "keyColor": "white" + // }, { "type": "player", "key": "", diff --git a/hypr/bin/adaptive-shell b/hypr/bin/adaptive-shell new file mode 100755 index 0000000..06307a4 --- /dev/null +++ b/hypr/bin/adaptive-shell @@ -0,0 +1,16 @@ +#!/bin/sh +set -eu +export QT_QUICK_CONTROLS_STYLE=Material +# Quickshell owns org.freedesktop.Notifications when the adaptive shell runs. +export ADAPTIVE_NOTIFICATIONS="${ADAPTIVE_NOTIFICATIONS:-1}" +repo=$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd) +case "${1:-start}" in + start) exec quickshell --no-duplicate --path "$repo/quickshell" ;; + reload|status|launcher|settings|bluetooth|network|wallpapers|audio|quickSettings|recent|power|notifications|close) + if ! quickshell ipc --path "$repo/quickshell" show >/dev/null 2>&1; then + quickshell --daemonize --no-duplicate --path "$repo/quickshell" + fi + exec quickshell ipc --path "$repo/quickshell" call shell "$1" ;; + stop) exec quickshell kill --path "$repo/quickshell" ;; + *) printf '%s\n' 'Usage: adaptive-shell [start|stop|reload|status|launcher|settings|bluetooth|network|wallpapers|audio|quickSettings|recent|power|notifications|close]' >&2; exit 2 ;; +esac diff --git a/hypr/bin/background.sh b/hypr/bin/background.sh old mode 100755 new mode 100644 diff --git a/hypr/bin/bluetooth-blueman-applet b/hypr/bin/bluetooth-blueman-applet old mode 100755 new mode 100644 diff --git a/hypr/bin/hyprlock-background.sh b/hypr/bin/hyprlock-background.sh old mode 100755 new mode 100644 diff --git a/hypr/bin/hyprlock-music.sh b/hypr/bin/hyprlock-music.sh old mode 100755 new mode 100644 diff --git a/hypr/bin/hyprlock/battery-status b/hypr/bin/hyprlock/battery-status old mode 100755 new mode 100644 diff --git a/hypr/bin/hyprlock/layout-status b/hypr/bin/hyprlock/layout-status old mode 100755 new mode 100644 diff --git a/hypr/bin/hyprlock/network-status b/hypr/bin/hyprlock/network-status old mode 100755 new mode 100644 diff --git a/hypr/bin/hyprlock/song-status b/hypr/bin/hyprlock/song-status old mode 100755 new mode 100644 diff --git a/hypr/bin/lock-session b/hypr/bin/lock-session new file mode 100644 index 0000000..d0b7d98 --- /dev/null +++ b/hypr/bin/lock-session @@ -0,0 +1,5 @@ +#!/bin/sh +# Do not mutate wallpaper/configuration while establishing the security boundary. +set -eu +if pgrep -x hyprlock >/dev/null; then exit 0; fi +exec hyprlock diff --git a/hypr/bin/restart-swayosd b/hypr/bin/restart-swayosd old mode 100755 new mode 100644 diff --git a/hypr/bin/restart_ags b/hypr/bin/restart_ags old mode 100755 new mode 100644 diff --git a/hypr/bin/restart_hypridle b/hypr/bin/restart_hypridle old mode 100755 new mode 100644 diff --git a/hypr/bin/restart_lxpolkit b/hypr/bin/restart_lxpolkit old mode 100755 new mode 100644 diff --git a/hypr/bin/restart_swaync b/hypr/bin/restart_swaync old mode 100755 new mode 100644 diff --git a/hypr/bin/restart_unclutter b/hypr/bin/restart_unclutter old mode 100755 new mode 100644 diff --git a/hypr/bin/restart_waybar b/hypr/bin/restart_waybar old mode 100755 new mode 100644 diff --git a/hypr/bin/songdetail.sh b/hypr/bin/songdetail.sh old mode 100755 new mode 100644 diff --git a/hypr/bin/startupdate.sh b/hypr/bin/startupdate.sh old mode 100755 new mode 100644 diff --git a/hypr/bin/toggle_keyboard.sh b/hypr/bin/toggle_keyboard.sh old mode 100755 new mode 100644 diff --git a/hypr/hyprlock.conf b/hypr/hyprlock.conf index 6ac6b15..e15b886 100644 --- a/hypr/hyprlock.conf +++ b/hypr/hyprlock.conf @@ -1,6 +1,6 @@ background { monitor = - path = /home/tola/Pictures/wallpaper/photo_2025-11-04_16-15-57.jpg + path = /home/tola/Pictures/wallpaper/crafted-for-cuteness-3840x2160-v0-d8u3ac79b94e1.png color = rgba(25, 20, 20, 1.0) blur_passes = 3 blur_size = 3 diff --git a/hypr/monitors.conf b/hypr/monitors.conf new file mode 100644 index 0000000..e69de29 diff --git a/hypr/monitors.lua b/hypr/monitors.lua index 167ccaf..52dfcd1 100644 --- a/hypr/monitors.lua +++ b/hypr/monitors.lua @@ -1,5 +1 @@ -hl.monitor({output = "", mode = "preferred", position = "auto", scale = "auto"}) -hl.monitor({output = "DVI-I-1", mode = "1920x1200", position = "0x0", scale = 1}) -hl.monitor({output = "HEADLESS-2", mode = "2048x1538", position = "0x0", scale = 2}) -hl.monitor({output = "vnc", mode = "1280x720", position = "0x0", scale = 1}) -hl.monitor({output = "DP-1", mode = "3440x1440@165", position = "0x0", scale = 1}) +hl.monitor({ output = "DP-1", mode = "3440x1440@165.00Hz", position = "0x0", scale = 1 }) diff --git a/hypr/programs.lua b/hypr/programs.lua index b4db7c5..3b5040f 100644 --- a/hypr/programs.lua +++ b/hypr/programs.lua @@ -26,3 +26,11 @@ keyboard_brightness_lower = "brightnessctl --device smc::kbd_backlight s 10%-" music_toggle = "swayosd-client --playerctl play-pause" music_next = "swayosd-client --playerctl next" music_prev = "swayosd-client --playerctl previous" + +-- Optional migration profile. Keep the legacy commands above as rollback defaults. +if os.getenv("ADAPTIVE_SHELL") == "1" then + local shell = "~/dotfiles/hypr/bin/adaptive-shell " + launcher = shell .. "launcher" + powermenu = shell .. "power" + swaync_toggle = shell .. "notifications" +end diff --git a/hypr/startup.lua b/hypr/startup.lua index 0fdb721..ee2d894 100644 --- a/hypr/startup.lua +++ b/hypr/startup.lua @@ -1,7 +1,11 @@ hl.on("hyprland.start", function() hl.exec_cmd("hyprpaper") hl.exec_cmd("sleep 0.3 && ~/dotfiles/hypr/bin/background.sh") - hl.exec_cmd("waybar") + if os.getenv("ADAPTIVE_SHELL") == "1" then + hl.exec_cmd("~/dotfiles/hypr/bin/adaptive-shell start") + else + hl.exec_cmd("waybar") + end hl.exec_cmd("lxpolkit") hl.exec_cmd("gsettings set org.gnome.desktop.interface gtk-theme 'MacTahoe-Dark'") hl.exec_cmd("gsettings set org.gnome.desktop.interface color-scheme 'prefer-dark'") @@ -10,7 +14,9 @@ hl.on("hyprland.start", function() hl.exec_cmd("hyprctl setcursor Bibata-Modern-Ice 24") hl.exec_cmd("dbus-update-activation-environment --systemd WAYLAND_DISPLAY XDG_CURRENT_DESKTOP") hl.exec_cmd("systemctl --user import-environment WAYLAND_DISPLAY XDG_CURRENT_DESKTOP") - hl.exec_cmd("swaync") + if os.getenv("ADAPTIVE_SHELL") ~= "1" or os.getenv("ADAPTIVE_NOTIFICATIONS") == "0" then + hl.exec_cmd("swaync") + end hl.exec_cmd("nm-applet --indicator") hl.exec_cmd("uxplay") hl.exec_cmd("hypridle") diff --git a/hypr/workspaces.conf b/hypr/workspaces.conf new file mode 100644 index 0000000..e69de29 diff --git a/install_scripts/install-arch.sh b/install_scripts/install-arch.sh old mode 100755 new mode 100644 diff --git a/kitty/kitty.conf b/kitty/kitty.conf index d63bcf8..649816f 100644 --- a/kitty/kitty.conf +++ b/kitty/kitty.conf @@ -5,3 +5,5 @@ bold_italic_font JetBrainsMono window_padding_width 5 background_blur 10 scrollback_lines 1000000 +map ctrl+shift+a launch --stdin-source=@screen_scrollback --type=clipboard + diff --git a/nfs/exports b/nfs/exports index 6235465..de2f4a7 100644 --- a/nfs/exports +++ b/nfs/exports @@ -2,3 +2,4 @@ /media *(rw,insecure) /dotfiles *(ro) /sshkeys *(ro) +/music *(ro,insecure) diff --git a/quickshell/.gitignore b/quickshell/.gitignore new file mode 100644 index 0000000..7a60b85 --- /dev/null +++ b/quickshell/.gitignore @@ -0,0 +1,2 @@ +__pycache__/ +*.pyc diff --git a/quickshell/AppearanceSettings.qml b/quickshell/AppearanceSettings.qml new file mode 100644 index 0000000..e332f96 --- /dev/null +++ b/quickshell/AppearanceSettings.qml @@ -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 } + } +} diff --git a/quickshell/AudioSettings.qml b/quickshell/AudioSettings.qml new file mode 100644 index 0000000..926be41 --- /dev/null +++ b/quickshell/AudioSettings.qml @@ -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 } + } + } + } + } + } + } +} diff --git a/quickshell/BRIGHTNESS_FIX.md b/quickshell/BRIGHTNESS_FIX.md new file mode 100644 index 0000000..a07ba88 --- /dev/null +++ b/quickshell/BRIGHTNESS_FIX.md @@ -0,0 +1,5 @@ +# Исправление загрузки BrightnessController + +Ошибка `BrightnessController is not a type` вызвана отсутствием регистрации компонента в `services/qmldir`. Добавлена строка `BrightnessController 1.0 BrightnessController.qml`. + +Перезапустите `./hypr/bin/adaptive-shell start`. Если появится следующая ошибка, приложите новый журнал: она может относиться к иной QML-зависимости. diff --git a/quickshell/Bar.qml b/quickshell/Bar.qml new file mode 100644 index 0000000..d1b0f6f --- /dev/null +++ b/quickshell/Bar.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") } + } +} diff --git a/quickshell/BatterySettings.qml b/quickshell/BatterySettings.qml new file mode 100644 index 0000000..a508498 --- /dev/null +++ b/quickshell/BatterySettings.qml @@ -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 + } + } +} diff --git a/quickshell/BluetoothSettings.qml b/quickshell/BluetoothSettings.qml new file mode 100644 index 0000000..d9afdc9 --- /dev/null +++ b/quickshell/BluetoothSettings.qml @@ -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() } + } +} diff --git a/quickshell/CONTINUATION.md b/quickshell/CONTINUATION.md new file mode 100644 index 0000000..b7cc019 --- /dev/null +++ b/quickshell/CONTINUATION.md @@ -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 оставлены без изменений.** diff --git a/quickshell/CONTINUATION_APN.md b/quickshell/CONTINUATION_APN.md new file mode 100644 index 0000000..541de51 --- /dev/null +++ b/quickshell/CONTINUATION_APN.md @@ -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. diff --git a/quickshell/CONTINUATION_BATTERY.md b/quickshell/CONTINUATION_BATTERY.md new file mode 100644 index 0000000..16da0ee --- /dev/null +++ b/quickshell/CONTINUATION_BATTERY.md @@ -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. diff --git a/quickshell/CONTINUATION_BRIGHTNESS.md b/quickshell/CONTINUATION_BRIGHTNESS.md new file mode 100644 index 0000000..dad5ac6 --- /dev/null +++ b/quickshell/CONTINUATION_BRIGHTNESS.md @@ -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. diff --git a/quickshell/CONTINUATION_DESKTOP.md b/quickshell/CONTINUATION_DESKTOP.md new file mode 100644 index 0000000..fe3be09 --- /dev/null +++ b/quickshell/CONTINUATION_DESKTOP.md @@ -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. diff --git a/quickshell/CONTINUATION_DESKTOP_LAUNCHER.md b/quickshell/CONTINUATION_DESKTOP_LAUNCHER.md new file mode 100644 index 0000000..36d953e --- /dev/null +++ b/quickshell/CONTINUATION_DESKTOP_LAUNCHER.md @@ -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. diff --git a/quickshell/CONTINUATION_DESKTOP_NO_DOCK.md b/quickshell/CONTINUATION_DESKTOP_NO_DOCK.md new file mode 100644 index 0000000..f557b23 --- /dev/null +++ b/quickshell/CONTINUATION_DESKTOP_NO_DOCK.md @@ -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. diff --git a/quickshell/CONTINUATION_DESKTOP_POLISH.md b/quickshell/CONTINUATION_DESKTOP_POLISH.md new file mode 100644 index 0000000..89888d3 --- /dev/null +++ b/quickshell/CONTINUATION_DESKTOP_POLISH.md @@ -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. diff --git a/quickshell/CONTINUATION_DESKTOP_QUICK_SETTINGS.md b/quickshell/CONTINUATION_DESKTOP_QUICK_SETTINGS.md new file mode 100644 index 0000000..d5d90e1 --- /dev/null +++ b/quickshell/CONTINUATION_DESKTOP_QUICK_SETTINGS.md @@ -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. diff --git a/quickshell/CONTINUATION_DISPLAY.md b/quickshell/CONTINUATION_DISPLAY.md new file mode 100644 index 0000000..321d134 --- /dev/null +++ b/quickshell/CONTINUATION_DISPLAY.md @@ -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. diff --git a/quickshell/CONTINUATION_GESTURES.md b/quickshell/CONTINUATION_GESTURES.md new file mode 100644 index 0000000..da81506 --- /dev/null +++ b/quickshell/CONTINUATION_GESTURES.md @@ -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. diff --git a/quickshell/CONTINUATION_HOME.md b/quickshell/CONTINUATION_HOME.md new file mode 100644 index 0000000..466cb78 --- /dev/null +++ b/quickshell/CONTINUATION_HOME.md @@ -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 и проверьте поиск, активацию и закрытие окон. diff --git a/quickshell/CONTINUATION_MODEM.md b/quickshell/CONTINUATION_MODEM.md new file mode 100644 index 0000000..1e0c097 --- /dev/null +++ b/quickshell/CONTINUATION_MODEM.md @@ -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. diff --git a/quickshell/CONTINUATION_MONITORS.md b/quickshell/CONTINUATION_MONITORS.md new file mode 100644 index 0000000..656e988 --- /dev/null +++ b/quickshell/CONTINUATION_MONITORS.md @@ -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. diff --git a/quickshell/CONTINUATION_MONITOR_PREVIEW.md b/quickshell/CONTINUATION_MONITOR_PREVIEW.md new file mode 100644 index 0000000..9a151e9 --- /dev/null +++ b/quickshell/CONTINUATION_MONITOR_PREVIEW.md @@ -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`. diff --git a/quickshell/CONTINUATION_POSITION.md b/quickshell/CONTINUATION_POSITION.md new file mode 100644 index 0000000..532ab1c --- /dev/null +++ b/quickshell/CONTINUATION_POSITION.md @@ -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. diff --git a/quickshell/CONTINUATION_POWER_PROFILES.md b/quickshell/CONTINUATION_POWER_PROFILES.md new file mode 100644 index 0000000..2a64477 --- /dev/null +++ b/quickshell/CONTINUATION_POWER_PROFILES.md @@ -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 не изменены. diff --git a/quickshell/CONTINUATION_QUICK_BRIGHTNESS.md b/quickshell/CONTINUATION_QUICK_BRIGHTNESS.md new file mode 100644 index 0000000..69c2beb --- /dev/null +++ b/quickshell/CONTINUATION_QUICK_BRIGHTNESS.md @@ -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. diff --git a/quickshell/CONTINUATION_QUICK_SETTINGS_FIX.md b/quickshell/CONTINUATION_QUICK_SETTINGS_FIX.md new file mode 100644 index 0000000..9606a77 --- /dev/null +++ b/quickshell/CONTINUATION_QUICK_SETTINGS_FIX.md @@ -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. diff --git a/quickshell/CONTINUATION_REFERENCE_UI.md b/quickshell/CONTINUATION_REFERENCE_UI.md new file mode 100644 index 0000000..d085c12 --- /dev/null +++ b/quickshell/CONTINUATION_REFERENCE_UI.md @@ -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. diff --git a/quickshell/CONTINUATION_ROTATION.md b/quickshell/CONTINUATION_ROTATION.md new file mode 100644 index 0000000..3d5de9b --- /dev/null +++ b/quickshell/CONTINUATION_ROTATION.md @@ -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. diff --git a/quickshell/CONTINUATION_SYSTEM.md b/quickshell/CONTINUATION_SYSTEM.md new file mode 100644 index 0000000..a0831d8 --- /dev/null +++ b/quickshell/CONTINUATION_SYSTEM.md @@ -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. diff --git a/quickshell/DesktopQuickSettings.qml b/quickshell/DesktopQuickSettings.qml new file mode 100644 index 0000000..1724f66 --- /dev/null +++ b/quickshell/DesktopQuickSettings.qml @@ -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 + } + } +} diff --git a/quickshell/DesktopShelf.qml b/quickshell/DesktopShelf.qml new file mode 100644 index 0000000..5330e6f --- /dev/null +++ b/quickshell/DesktopShelf.qml @@ -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") } + } + } +} diff --git a/quickshell/DisplaySettings.qml b/quickshell/DisplaySettings.qml new file mode 100644 index 0000000..3f5ee84 --- /dev/null +++ b/quickshell/DisplaySettings.qml @@ -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" + } + } +} diff --git a/quickshell/EXPRESSIVE_UI.md b/quickshell/EXPRESSIVE_UI.md new file mode 100644 index 0000000..e141ec4 --- /dev/null +++ b/quickshell/EXPRESSIVE_UI.md @@ -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. diff --git a/quickshell/Home.qml b/quickshell/Home.qml new file mode 100644 index 0000000..728f224 --- /dev/null +++ b/quickshell/Home.qml @@ -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 } + } +} diff --git a/quickshell/IMPLEMENTATION_STATUS.md b/quickshell/IMPLEMENTATION_STATUS.md new file mode 100644 index 0000000..c2adeb4 --- /dev/null +++ b/quickshell/IMPLEMENTATION_STATUS.md @@ -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. diff --git a/quickshell/Launcher.qml b/quickshell/Launcher.qml new file mode 100644 index 0000000..b0b9330 --- /dev/null +++ b/quickshell/Launcher.qml @@ -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 } + } +} diff --git a/quickshell/MobileNavigation.qml b/quickshell/MobileNavigation.qml new file mode 100644 index 0000000..c87cb49 --- /dev/null +++ b/quickshell/MobileNavigation.qml @@ -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"); + } + } +} diff --git a/quickshell/ModemSettings.qml b/quickshell/ModemSettings.qml new file mode 100644 index 0000000..a35dad8 --- /dev/null +++ b/quickshell/ModemSettings.qml @@ -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 } + } +} diff --git a/quickshell/NetworkSettings.qml b/quickshell/NetworkSettings.qml new file mode 100644 index 0000000..d6f2726 --- /dev/null +++ b/quickshell/NetworkSettings.qml @@ -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"]) } + } +} diff --git a/quickshell/NotificationCenter.qml b/quickshell/NotificationCenter.qml new file mode 100644 index 0000000..665d63f --- /dev/null +++ b/quickshell/NotificationCenter.qml @@ -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 } + } +} diff --git a/quickshell/Overlay.qml b/quickshell/Overlay.qml new file mode 100644 index 0000000..685a451 --- /dev/null +++ b/quickshell/Overlay.qml @@ -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() } +} diff --git a/quickshell/Power.qml b/quickshell/Power.qml new file mode 100644 index 0000000..86734ac --- /dev/null +++ b/quickshell/Power.qml @@ -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 } +} diff --git a/quickshell/QuickSettings.qml b/quickshell/QuickSettings.qml new file mode 100644 index 0000000..75306b3 --- /dev/null +++ b/quickshell/QuickSettings.qml @@ -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() } + } + } + } + } +} diff --git a/quickshell/Recent.qml b/quickshell/Recent.qml new file mode 100644 index 0000000..cc1a674 --- /dev/null +++ b/quickshell/Recent.qml @@ -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 + } + } + } + } +} diff --git a/quickshell/Settings.qml b/quickshell/Settings.qml new file mode 100644 index 0000000..139fc4c --- /dev/null +++ b/quickshell/Settings.qml @@ -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 {} + } + } + } +} diff --git a/quickshell/SettingsWindow.qml b/quickshell/SettingsWindow.qml new file mode 100644 index 0000000..61d6b44 --- /dev/null +++ b/quickshell/SettingsWindow.qml @@ -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() } +} diff --git a/quickshell/SystemSettings.qml b/quickshell/SystemSettings.qml new file mode 100644 index 0000000..a663d63 --- /dev/null +++ b/quickshell/SystemSettings.qml @@ -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() } + } +} diff --git a/quickshell/Toast.qml b/quickshell/Toast.qml new file mode 100644 index 0000000..9688810 --- /dev/null +++ b/quickshell/Toast.qml @@ -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 } + } + } +} diff --git a/quickshell/Wallpaper.qml b/quickshell/Wallpaper.qml new file mode 100644 index 0000000..dcaedce --- /dev/null +++ b/quickshell/Wallpaper.qml @@ -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() + } +} diff --git a/quickshell/WallpaperSettings.qml b/quickshell/WallpaperSettings.qml new file mode 100644 index 0000000..2f63164 --- /dev/null +++ b/quickshell/WallpaperSettings.qml @@ -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"] + } + } + } +} diff --git a/quickshell/backend/bluetooth.py b/quickshell/backend/bluetooth.py new file mode 100644 index 0000000..318908a --- /dev/null +++ b/quickshell/backend/bluetooth.py @@ -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()) diff --git a/quickshell/backend/brightness.py b/quickshell/backend/brightness.py new file mode 100644 index 0000000..d0ed62f --- /dev/null +++ b/quickshell/backend/brightness.py @@ -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) diff --git a/quickshell/backend/display_preview.py b/quickshell/backend/display_preview.py new file mode 100644 index 0000000..3cb4293 --- /dev/null +++ b/quickshell/backend/display_preview.py @@ -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) diff --git a/quickshell/backend/displays.py b/quickshell/backend/displays.py new file mode 100644 index 0000000..874e63d --- /dev/null +++ b/quickshell/backend/displays.py @@ -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) diff --git a/quickshell/backend/lock_observer.py b/quickshell/backend/lock_observer.py new file mode 100644 index 0000000..ea7ad20 --- /dev/null +++ b/quickshell/backend/lock_observer.py @@ -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() diff --git a/quickshell/backend/mobile_connections.py b/quickshell/backend/mobile_connections.py new file mode 100644 index 0000000..889ea84 --- /dev/null +++ b/quickshell/backend/mobile_connections.py @@ -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) diff --git a/quickshell/backend/modem_control.py b/quickshell/backend/modem_control.py new file mode 100644 index 0000000..596dc71 --- /dev/null +++ b/quickshell/backend/modem_control.py @@ -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) diff --git a/quickshell/backend/modems.py b/quickshell/backend/modems.py new file mode 100644 index 0000000..71c8eb4 --- /dev/null +++ b/quickshell/backend/modems.py @@ -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)) diff --git a/quickshell/backend/power.py b/quickshell/backend/power.py new file mode 100644 index 0000000..a3ff0a5 --- /dev/null +++ b/quickshell/backend/power.py @@ -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()) diff --git a/quickshell/backend/power_profiles.py b/quickshell/backend/power_profiles.py new file mode 100644 index 0000000..cc6bc5e --- /dev/null +++ b/quickshell/backend/power_profiles.py @@ -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) diff --git a/quickshell/backend/protocols/README.md b/quickshell/backend/protocols/README.md new file mode 100644 index 0000000..844a959 --- /dev/null +++ b/quickshell/backend/protocols/README.md @@ -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. diff --git a/quickshell/backend/protocols/hyprland-lock-notify-v1.xml b/quickshell/backend/protocols/hyprland-lock-notify-v1.xml new file mode 100644 index 0000000..c407fd8 --- /dev/null +++ b/quickshell/backend/protocols/hyprland-lock-notify-v1.xml @@ -0,0 +1,99 @@ + + + + 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. + + + + + This interface allows clients to monitor whether the wayland session is + locked or unlocked. + + + + + Destroy the manager object. All objects created via this interface + remain valid. + + + + + + Create a new lock notification object. + + If the session is already locked when calling this method, + the locked event shall be sent immediately. + + + + + + + + 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. + + + + + Destroy the notification object. + + + + + + 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. + + + + + + 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. + + + + diff --git a/quickshell/backend/protocols/hyprland_lock_notify_v1.py b/quickshell/backend/protocols/hyprland_lock_notify_v1.py new file mode 100644 index 0000000..bfbfd34 --- /dev/null +++ b/quickshell/backend/protocols/hyprland_lock_notify_v1.py @@ -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 diff --git a/quickshell/backend/system_info.py b/quickshell/backend/system_info.py new file mode 100644 index 0000000..db6fbb3 --- /dev/null +++ b/quickshell/backend/system_info.py @@ -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)) diff --git a/quickshell/components/ActionButton.qml b/quickshell/components/ActionButton.qml new file mode 100644 index 0000000..606edd5 --- /dev/null +++ b/quickshell/components/ActionButton.qml @@ -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 + } +} diff --git a/quickshell/components/NetworkCard.qml b/quickshell/components/NetworkCard.qml new file mode 100644 index 0000000..1aedca5 --- /dev/null +++ b/quickshell/components/NetworkCard.qml @@ -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() } + } +} diff --git a/quickshell/components/NotificationCard.qml b/quickshell/components/NotificationCard.qml new file mode 100644 index 0000000..fca05c8 --- /dev/null +++ b/quickshell/components/NotificationCard.qml @@ -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) + } + } + } +} diff --git a/quickshell/install.py b/quickshell/install.py new file mode 100644 index 0000000..97a3921 --- /dev/null +++ b/quickshell/install.py @@ -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) diff --git a/quickshell/services/BluetoothController.qml b/quickshell/services/BluetoothController.qml new file mode 100644 index 0000000..4c28fd3 --- /dev/null +++ b/quickshell/services/BluetoothController.qml @@ -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; + } + } +} diff --git a/quickshell/services/BluetoothDiscovery.qml b/quickshell/services/BluetoothDiscovery.qml new file mode 100644 index 0000000..208f2c3 --- /dev/null +++ b/quickshell/services/BluetoothDiscovery.qml @@ -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; } } +} diff --git a/quickshell/services/BrightnessController.qml b/quickshell/services/BrightnessController.qml new file mode 100644 index 0000000..126ef24 --- /dev/null +++ b/quickshell/services/BrightnessController.qml @@ -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() + } +} diff --git a/quickshell/services/DisplayController.qml b/quickshell/services/DisplayController.qml new file mode 100644 index 0000000..84eb7f3 --- /dev/null +++ b/quickshell/services/DisplayController.qml @@ -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() + } +} diff --git a/quickshell/services/DisplayPreview.qml b/quickshell/services/DisplayPreview.qml new file mode 100644 index 0000000..4804a91 --- /dev/null +++ b/quickshell/services/DisplayPreview.qml @@ -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 = ""; + } + } + } +} diff --git a/quickshell/services/Hardware.qml b/quickshell/services/Hardware.qml new file mode 100644 index 0000000..6205734 --- /dev/null +++ b/quickshell/services/Hardware.qml @@ -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) } +} diff --git a/quickshell/services/HardwarePolicy.js b/quickshell/services/HardwarePolicy.js new file mode 100644 index 0000000..d242c0a --- /dev/null +++ b/quickshell/services/HardwarePolicy.js @@ -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; +} diff --git a/quickshell/services/MobileConnections.qml b/quickshell/services/MobileConnections.qml new file mode 100644 index 0000000..f0ee649 --- /dev/null +++ b/quickshell/services/MobileConnections.qml @@ -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() } +} diff --git a/quickshell/services/Modems.qml b/quickshell/services/Modems.qml new file mode 100644 index 0000000..7b4750b --- /dev/null +++ b/quickshell/services/Modems.qml @@ -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() } +} diff --git a/quickshell/services/NetworkController.qml b/quickshell/services/NetworkController.qml new file mode 100644 index 0000000..f811af6 --- /dev/null +++ b/quickshell/services/NetworkController.qml @@ -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("Время ожидания истекло. Результат подключения не подтверждён.") + } +} diff --git a/quickshell/services/NotificationEntry.qml b/quickshell/services/NotificationEntry.qml new file mode 100644 index 0000000..49791a6 --- /dev/null +++ b/quickshell/services/NotificationEntry.qml @@ -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() +} diff --git a/quickshell/services/NotificationPolicy.js b/quickshell/services/NotificationPolicy.js new file mode 100644 index 0000000..7e99368 --- /dev/null +++ b/quickshell/services/NotificationPolicy.js @@ -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; +} diff --git a/quickshell/services/Notifications.qml b/quickshell/services/Notifications.qml new file mode 100644 index 0000000..8e34184 --- /dev/null +++ b/quickshell/services/Notifications.qml @@ -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(); + } + } + } +} diff --git a/quickshell/services/Policy.js b/quickshell/services/Policy.js new file mode 100644 index 0000000..0061674 --- /dev/null +++ b/quickshell/services/Policy.js @@ -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 : [[]]; +} diff --git a/quickshell/services/PowerController.qml b/quickshell/services/PowerController.qml new file mode 100644 index 0000000..e7cb133 --- /dev/null +++ b/quickshell/services/PowerController.qml @@ -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; + } + } +} diff --git a/quickshell/services/PowerProfiles.qml b/quickshell/services/PowerProfiles.qml new file mode 100644 index 0000000..c9d6885 --- /dev/null +++ b/quickshell/services/PowerProfiles.qml @@ -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() } +} diff --git a/quickshell/services/Preferences.qml b/quickshell/services/Preferences.qml new file mode 100644 index 0000000..9de3377 --- /dev/null +++ b/quickshell/services/Preferences.qml @@ -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 + } +} diff --git a/quickshell/services/SystemInfo.qml b/quickshell/services/SystemInfo.qml new file mode 100644 index 0000000..1f968cf --- /dev/null +++ b/quickshell/services/SystemInfo.qml @@ -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() } +} diff --git a/quickshell/services/Theme.qml b/quickshell/services/Theme.qml new file mode 100644 index 0000000..0813772 --- /dev/null +++ b/quickshell/services/Theme.qml @@ -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; } +} diff --git a/quickshell/services/WallpaperPolicy.js b/quickshell/services/WallpaperPolicy.js new file mode 100644 index 0000000..5a656eb --- /dev/null +++ b/quickshell/services/WallpaperPolicy.js @@ -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["*"] || ""); +} diff --git a/quickshell/services/Wallpapers.qml b/quickshell/services/Wallpapers.qml new file mode 100644 index 0000000..0a32b8d --- /dev/null +++ b/quickshell/services/Wallpapers.qml @@ -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; + } +} diff --git a/quickshell/services/WindowPolicy.js b/quickshell/services/WindowPolicy.js new file mode 100644 index 0000000..6881ace --- /dev/null +++ b/quickshell/services/WindowPolicy.js @@ -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; +} diff --git a/quickshell/services/qmldir b/quickshell/services/qmldir new file mode 100644 index 0000000..f1bdae4 --- /dev/null +++ b/quickshell/services/qmldir @@ -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 diff --git a/quickshell/shell.qml b/quickshell/shell.qml new file mode 100644 index 0000000..e9d4ba1 --- /dev/null +++ b/quickshell/shell.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 = "" + } +} diff --git a/quickshell/tests/bluetooth_controller.py b/quickshell/tests/bluetooth_controller.py new file mode 100644 index 0000000..fe5b7e7 --- /dev/null +++ b/quickshell/tests/bluetooth_controller.py @@ -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 diff --git a/quickshell/tests/bluetooth_fake.py b/quickshell/tests/bluetooth_fake.py new file mode 100644 index 0000000..3c878ee --- /dev/null +++ b/quickshell/tests/bluetooth_fake.py @@ -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) diff --git a/quickshell/tests/fixtures/bluetooth.qml b/quickshell/tests/fixtures/bluetooth.qml new file mode 100644 index 0000000..cc06138 --- /dev/null +++ b/quickshell/tests/fixtures/bluetooth.qml @@ -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") } +} diff --git a/quickshell/tests/fixtures/network.qml b/quickshell/tests/fixtures/network.qml new file mode 100644 index 0000000..aed106c --- /dev/null +++ b/quickshell/tests/fixtures/network.qml @@ -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") } +} diff --git a/quickshell/tests/fixtures/power.qml b/quickshell/tests/fixtures/power.qml new file mode 100644 index 0000000..3c95bc2 --- /dev/null +++ b/quickshell/tests/fixtures/power.qml @@ -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") } +} diff --git a/quickshell/tests/hardware_policy_node.cjs b/quickshell/tests/hardware_policy_node.cjs new file mode 100644 index 0000000..a929ef4 --- /dev/null +++ b/quickshell/tests/hardware_policy_node.cjs @@ -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'); diff --git a/quickshell/tests/home_policy_node.cjs b/quickshell/tests/home_policy_node.cjs new file mode 100644 index 0000000..560ace7 --- /dev/null +++ b/quickshell/tests/home_policy_node.cjs @@ -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'); diff --git a/quickshell/tests/network_controller.py b/quickshell/tests/network_controller.py new file mode 100644 index 0000000..6757c17 --- /dev/null +++ b/quickshell/tests/network_controller.py @@ -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 diff --git a/quickshell/tests/notifications.py b/quickshell/tests/notifications.py new file mode 100644 index 0000000..c841aa8 --- /dev/null +++ b/quickshell/tests/notifications.py @@ -0,0 +1,177 @@ +#!/usr/bin/env python3 +"""Exercise real notification D-Bus lifecycle in a private session and temporary state.""" +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import time + +# Isolation is enforced even when the test is run without dbus-run-session. +if os.environ.get('ADAPTIVE_NOTIFICATION_TEST_BUS') != '1': + env = dict(os.environ, ADAPTIVE_NOTIFICATION_TEST_BUS='1') + os.execvpe('dbus-run-session', ['dbus-run-session', '--', sys.executable, __file__], env) + +from gi.repository import Gio, GLib +ROOT = Path(__file__).resolve().parents[1] +connection = Gio.bus_get_sync(Gio.BusType.SESSION, None) +events = [] +connection.signal_subscribe(None, 'org.freedesktop.Notifications', None, + '/org/freedesktop/Notifications', None, Gio.DBusSignalFlags.NONE, + lambda conn, sender, path, interface, name, params: events.append((name, params.unpack()))) + +def call(method, signature, values): + return connection.call_sync('org.freedesktop.Notifications', '/org/freedesktop/Notifications', + 'org.freedesktop.Notifications', method, + GLib.Variant(signature, values), None, + Gio.DBusCallFlags.NONE, 5000, None).unpack() + +def notify(title, replace=0, timeout=0, urgency=1, transient=False, actions=None): + return call('Notify', '(susssasa{sv}i)', ('Adaptive Test', replace, '', title, 'Body plain', + actions or [], {'urgency': GLib.Variant('y', urgency), 'transient': GLib.Variant('b', transient)}, timeout))[0] + +def pump(): + context = GLib.MainContext.default() + while context.pending(): context.iteration(False) + +def wait_for(predicate, description, timeout=8): + end = time.monotonic() + timeout + while time.monotonic() < end: + pump() + if predicate(): return + time.sleep(.05) + raise AssertionError(description) + +with tempfile.TemporaryDirectory(prefix='adaptive-notifications-') as tmp: + env = dict(os.environ, QT_QPA_PLATFORM='wayland', QT_QUICK_CONTROLS_STYLE='Material', + XDG_STATE_HOME=tmp, XDG_CACHE_HOME=tmp, ADAPTIVE_NOTIFICATIONS='1') + log_path = Path(tmp, 'shell.log') + log = log_path.open('w') + process = None + def start(): + return subprocess.Popen(['quickshell', '-p', str(ROOT), '--no-color'], env=env, + stdout=log, stderr=subprocess.STDOUT) + def ipc(*args): + result = subprocess.run(['quickshell', 'ipc', '--pid', str(process.pid), 'call', 'shell', *args], + env=env, capture_output=True, text=True, timeout=30) + if result.returncode: raise RuntimeError(result.stderr) + return result.stdout + def status(): return json.loads(ipc('status')) + def ready(): + if process.poll() is not None: raise RuntimeError(log_path.read_text()) + try: return status()['preferencesWritable'] and status()['notificationsReady'] + except (RuntimeError, ValueError): return False + def stop(): + process.terminate() + try: process.wait(timeout=3) + except subprocess.TimeoutExpired: process.kill(); process.wait() + try: + process = start() + wait_for(ready, 'shell readiness', 60) + call('GetServerInformation', '()', ()) + persistent = notify('original') + wait_for(lambda: len(status()['notifications']) == 1, 'first notification') + assert notify('updated', replace=persistent) == persistent + wait_for(lambda: status()['notifications'][0]['summary'] == 'updated', 'replacement') + assert status()['notificationHistoryCount'] == 1 + count = status()['notificationHistoryCount'] + ipc('reload') + time.sleep(.5) + wait_for(ready, 'reloaded shell readiness', 60) + wait_for(lambda: len(status()['notifications']) == 1, 'live notification restored after reload') + assert status()['notificationHistoryCount'] == count, 'QML reload must not duplicate history' + assert status()['notificationPopup'] == 0, 'QML reload must not replay popups' + timed_reload = notify('reload deadline', timeout=10000) + reload_history_path = next(Path(tmp).rglob('notifications.json')) + def recorded_deadline(): + return next((e['deadline'] for e in json.loads(reload_history_path.read_text())['entries'] if e['summary'] == 'reload deadline'), None) + wait_for(lambda: recorded_deadline() is not None, 'deadline recorded') + deadline = recorded_deadline() + ipc('reload') + time.sleep(.5) + wait_for(ready, 'second reload readiness', 60) + wait_for(lambda: len(status()['notifications']) == 2, 'timed notification restored') + assert recorded_deadline() == deadline, 'Reload must preserve the absolute deadline' + ipc('dismissNotification', str(timed_reload)) + print('PASS replacement and QML reload preserve history and timer deadline', flush=True) + + expiring = notify('short timeout', timeout=250) + wait_for(lambda: ('NotificationClosed', (expiring, 1)) in events, 'expired close reason') + ipc('dismissNotification', str(persistent)) + wait_for(lambda: ('NotificationClosed', (persistent, 2)) in events, 'dismissed close reason') + closing = notify('client close') + call('CloseNotification', '(u)', (closing,)) + wait_for(lambda: ('NotificationClosed', (closing, 3)) in events, 'client close reason') + resetting = notify('timer before replacement', timeout=1600) + time.sleep(.8) + notify('timer after replacement', replace=resetting, timeout=1600) + time.sleep(1) + assert any(n['id'] == resetting for n in status()['notifications']), 'Replacement must restart timeout' + wait_for(lambda: ('NotificationClosed', (resetting, 1)) in events, 'replacement expiration') + print('PASS timeout, replacement timer reset and close reasons 1/2/3', flush=True) + + action_id = notify('action', actions=['open', 'Open']) + wait_for(lambda: any(n['id'] == action_id for n in status()['notifications']), 'action notification') + ipc('notificationAction', str(action_id), 'open') + wait_for(lambda: ('ActionInvoked', (action_id, 'open')) in events, 'ActionInvoked') + print('PASS notification actions', flush=True) + + ipc('dnd', 'true') + quiet = notify('quiet') + wait_for(lambda: any(n['id'] == quiet for n in status()['notifications']), 'DND retains notification') + assert status()['notificationPopup'] == 0, status() + ipc('dnd', 'false') + assert status()['notificationPopup'] == 0, 'DND must not replay popups' + print('PASS DND suppresses popups without dropping notifications', flush=True) + + critical = notify('critical', timeout=100, urgency=2) + time.sleep(.35) + assert any(n['id'] == critical for n in status()['notifications']) + assert status()['notificationPopup'] == critical + before = status()['notificationHistoryCount'] + transient_id = notify('transient', transient=True) + wait_for(lambda: any(n['id'] == transient_id for n in status()['notifications']), 'transient notification') + assert status()['notificationHistoryCount'] == before + print('PASS critical stays live and transient skips history', flush=True) + + history_path = next(Path(tmp).rglob('notifications.json')) + wait_for(lambda: len(json.loads(history_path.read_text())['entries']) == before, 'history written') + assert history_path.parent.stat().st_mode & 0o777 == 0o700 + history = json.loads(history_path.read_text()) + assert not any(e['summary'] == 'transient' for e in history['entries']) + assert len([e for e in history['entries'] if e['summary'] == 'updated']) == 1 + ipc('dnd', 'true') + stop() + process = start() + wait_for(ready, 'restarted shell readiness', 60) + wait_for(lambda: status()['notificationHistoryCount'] == before, 'history restored') + assert status()['notificationDnd'] is True + assert not status()['notifications'], 'Archived notifications cannot restore live actions' + assert status()['notificationGroups'] == 1, 'One application must form one group' + ipc('notifications') + ipc('clearNotifications') + wait_for(lambda: not json.loads(history_path.read_text())['entries'], 'history cleared') + assert status()['notificationGroups'] == 0 + ipc('notificationHistory', 'false') + notify('history disabled') + time.sleep(.2) + assert status()['notificationHistoryCount'] == 0 + ipc('clearNotifications') + print('PASS grouping, private history, restart, clear-all and history opt-out', flush=True) + stop() + history_path.write_text('{invalid history') + process = start() + wait_for(ready, 'shell with invalid history', 60) + assert status()['notificationHistoryError'] + notify('corrupt file must survive') + time.sleep(.2) + assert history_path.read_text() == '{invalid history' + print('PASS corrupt history preserved while delivery continues', flush=True) + finally: + if process and process.poll() is None: stop() + log.close() + logs = log_path.read_text() + print(logs) + for marker in ['Failed to load configuration', 'ReferenceError', 'TypeError', 'Binding loop', 'Cannot assign', 'Cannot create delegate']: + assert marker not in logs, marker diff --git a/quickshell/tests/power_controller.py b/quickshell/tests/power_controller.py new file mode 100644 index 0000000..e412b0a --- /dev/null +++ b/quickshell/tests/power_controller.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python3 +"""Run Quickshell's real Process-backed controller exclusively against a fake helper.""" +import os +from pathlib import Path +import subprocess +import tempfile +import shutil + +fixture = Path(__file__).resolve().parent / 'fixtures/power.qml' +with tempfile.TemporaryDirectory(prefix='adaptive-power-controller-') as tmp: + runtime = Path(tmp, 'runtime') + runtime.mkdir(mode=0o700) + env = dict(os.environ, QT_QPA_PLATFORM='offscreen', XDG_RUNTIME_DIR=str(runtime), + XDG_STATE_HOME=tmp, XDG_CACHE_HOME=tmp) + # Quickshell resolves directory imports inside its config root: stage the exact controller + # source beside the fixture so the offscreen shell has no access to production entrypoints. + config = Path(tmp, 'config') + config.mkdir() + shutil.copyfile(fixture, config / 'shell.qml') + shutil.copyfile(fixture.parents[2] / 'services/PowerController.qml', config / 'PowerController.qml') + shutil.copyfile(fixture.parents[1] / 'power_fake.py', config / 'power_fake.py') + result = subprocess.run(['quickshell', '-p', str(config), '--no-color'], env=env, + capture_output=True, text=True, timeout=25) + logs = result.stdout + result.stderr + print(logs) + assert result.returncode == 0 and 'POWER_TEST_PASS: 7 scenarios' in logs, logs + for marker in ['POWER_TEST_FAIL', 'Failed to load configuration', 'ReferenceError', 'TypeError', 'Binding loop']: + assert marker not in logs, marker diff --git a/quickshell/tests/power_fake.py b/quickshell/tests/power_fake.py new file mode 100644 index 0000000..34de45e --- /dev/null +++ b/quickshell/tests/power_fake.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python3 +"""Explicitly injected by tst_power.qml; never selected by production configuration.""" +import json +import sys +import time + +mode, action = sys.argv[1:] +if mode == 'stall': time.sleep(5) +if mode == 'malformed': + print('not json') + sys.exit(0) +if action == 'capabilities': + print(json.dumps({'ok': True, 'capabilities': {name: {'state': 'no' if mode == 'denied' else 'yes'} + for name in ['lock', 'logout', 'suspend', 'reboot', 'poweroff']}})) +elif mode == 'failure': + print(json.dumps({'ok': False, 'error': 'Mock authorization denied'})) + sys.exit(1) +else: + print(json.dumps({'ok': True})) diff --git a/quickshell/tests/smoke.py b/quickshell/tests/smoke.py new file mode 100644 index 0000000..a82f2b2 --- /dev/null +++ b/quickshell/tests/smoke.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +"""Wayland integration test. Uses private state and D-Bus, never stops legacy daemons.""" +import json +import os +from pathlib import Path +import subprocess +import tempfile +import time +import sys + +if os.environ.get("ADAPTIVE_SMOKE_TEST_BUS") != "1": + os.execvpe("dbus-run-session", ["dbus-run-session", "--", sys.executable, __file__], dict(os.environ, ADAPTIVE_SMOKE_TEST_BUS="1")) + +ROOT = Path(__file__).resolve().parents[1] +with tempfile.TemporaryDirectory(prefix="adaptive-test-") as tmp: + env = dict(os.environ, QT_QPA_PLATFORM="wayland", QT_QUICK_CONTROLS_STYLE="Material", + XDG_STATE_HOME=tmp, XDG_CACHE_HOME=tmp, ADAPTIVE_NOTIFICATIONS="1") + log_path = Path(tmp, "shell.log") + with log_path.open("w") as log: + process = subprocess.Popen(["quickshell", "-p", str(ROOT), "--no-color"], env=env, + stdout=log, stderr=subprocess.STDOUT) + def ipc(*args): + return subprocess.run(["quickshell", "ipc", "--pid", str(process.pid), + "call", "shell", *args], env=env, capture_output=True, text=True, timeout=30) + try: + for _ in range(50): + if process.poll() is not None: raise RuntimeError(log_path.read_text()) + if ipc("close").returncode == 0: break + time.sleep(.1) + else: raise RuntimeError("IPC did not become ready") + def status(): + result = ipc("status") + assert result.returncode == 0, result.stderr + return json.loads(result.stdout) + for page in ["launcher", "settings", "audio", "network", "bluetooth", "wallpapers", "quickSettings", "recent", "power"]: + result = ipc(page) + assert result.returncode == 0, result.stderr + time.sleep(1) + print("PASS", page) + clients = subprocess.run(["hyprctl", "-j", "clients"], env=env, capture_output=True, text=True, check=True) + windows = json.loads(clients.stdout) + assert any(w.get("pid") == process.pid and w.get("title") == "Settings" for w in windows), "Settings must be a managed desktop window" + assert status()["settingsVisible"] is True + capture = os.environ.get("ADAPTIVE_CAPTURE_DIR") + if capture: + assert ipc("audio").returncode == 0 + time.sleep(.5) + window = next(w for w in windows if w.get("pid") == process.pid and w.get("title") == "Settings") + x, y = window["at"] + width, height = window["size"] + subprocess.run(["grim", "-g", f"{x},{y} {width}x{height}", str(Path(capture, "adaptive-audio.png"))], env=env, check=True) + print("PASS managed Settings window", status()) + for mode in ["phone", "tablet", "desktop"]: + assert ipc("mode", mode).returncode == 0 + time.sleep(.3) + assert ipc("theme", "light").returncode == 0 + time.sleep(.3) + configs = list(Path(tmp).rglob("preferences.json")) + assert len(configs) == 1, configs + data = json.loads(configs[0].read_text()) + assert data["mode"] == "desktop" and data["theme"] == "light", data + data["favorites"] = ["test.desktop"] + configs[0].write_text(json.dumps(data)) + time.sleep(.4) + assert status()["favorites"] == ["test.desktop"], status() + configs[0].write_text("{broken json") + time.sleep(.4) + assert status()["preferencesWritable"] is False, status() + ipc("theme", "dark") + time.sleep(.2) + assert configs[0].read_text() == "{broken json", "Corrupt preferences must not be overwritten" + configs[0].write_text(json.dumps(data)) + time.sleep(.4) + assert status()["preferencesWritable"] is True and not status()["preferencesError"], status() + print("PASS external preferences, corruption protection and recovery") + subprocess.run(["notify-send", "--app-name=Adaptive Test", "Shell smoke test", "Plain text body"], env=env, check=True) + assert ipc("notifications").returncode == 0 + time.sleep(1) + assert ipc("close").returncode == 0 + print("PASS modes, persistence, notification delivery") + finally: + process.terminate() + try: process.wait(timeout=3) + except subprocess.TimeoutExpired: process.kill(); process.wait() + logs = log_path.read_text() + print(logs) + for marker in ["Failed to load configuration", "ReferenceError", "TypeError", "Binding loop", "Cannot assign", "is not a type", "Cannot create delegate"]: + assert marker not in logs, marker diff --git a/quickshell/tests/test_bluetooth_backend.py b/quickshell/tests/test_bluetooth_backend.py new file mode 100644 index 0000000..a8959e3 --- /dev/null +++ b/quickshell/tests/test_bluetooth_backend.py @@ -0,0 +1,84 @@ +"""Never uses the real system bus: all BlueZ calls are injected.""" +import importlib.util +from pathlib import Path +import unittest +import io +from contextlib import redirect_stdout +from unittest.mock import Mock + +spec = importlib.util.spec_from_file_location('bluetooth_backend', Path(__file__).resolve().parents[1] / 'backend/bluetooth.py') +backend = importlib.util.module_from_spec(spec) +spec.loader.exec_module(backend) +ADAPTER = '/org/bluez/hci1' +DEVICE = ADAPTER + '/dev_AA_BB_CC_DD_EE_FF' + + +class BluetoothTests(unittest.TestCase): + def setUp(self): + self.bluez = Mock() + self.factory = Mock(return_value=self.bluez) + + def test_status_is_read_only(self): + self.bluez.status.return_value = {'adapterCount': 2} + self.assertEqual(backend.execute('status', factory=self.factory), {'adapterCount': 2}) + self.bluez.power.assert_not_called() + self.bluez.connect.assert_not_called() + + def test_power_paths_and_values(self): + for action, enabled in [('power-on', True), ('power-off', False)]: + backend.execute(action, ADAPTER, self.factory) + self.bluez.power.assert_called_with(ADAPTER, enabled) + + def test_device_actions_route_to_exact_device(self): + for action in ['connect', 'disconnect', 'forget']: + backend.execute(action, DEVICE, self.factory) + getattr(self.bluez, action).assert_called_once_with(DEVICE) + + def test_discovery_uses_adapter(self): + backend.execute('discover', ADAPTER, self.factory) + self.bluez.discover.assert_called_once_with(ADAPTER) + + def test_invalid_paths_never_create_backend(self): + for path in ['', '/org/bluez/hci1/extra', '/org/bluez/hci1; command', '../hci1', DEVICE]: + with self.assertRaises(ValueError): backend.execute('power-on', path, self.factory) + for path in [ADAPTER, DEVICE + '/extra', '/org/bluez/hci1/dev_wrong']: + with self.assertRaises(ValueError): backend.execute('connect', path, self.factory) + self.factory.assert_not_called() + + def test_unknown_action_and_status_arguments_rejected(self): + with self.assertRaises(ValueError): backend.execute('pair', DEVICE, self.factory) + with self.assertRaises(ValueError): backend.execute('status', DEVICE, self.factory) + self.factory.assert_not_called() + + def test_errors_propagate_without_success(self): + self.bluez.connect.side_effect = RuntimeError('org.bluez.Error.NotReady') + with self.assertRaisesRegex(RuntimeError, 'NotReady'): + backend.execute('connect', DEVICE, self.factory) + + def test_forget_uses_the_owning_adapter(self): + bluez = object.__new__(backend.Bluez) + bluez.call = Mock() + bluez.forget(DEVICE) + bluez.call.assert_called_once_with(ADAPTER, 'org.bluez.Adapter1', 'RemoveDevice', '(o)', (DEVICE,)) + + +class DiscoveryLeaseTests(unittest.TestCase): + def setUp(self): + self.bluez = object.__new__(backend.Bluez) + self.bluez.GLib = Mock() + self.bluez.call = Mock() + + def test_started_lease_is_released_by_same_connection(self): + with redirect_stdout(io.StringIO()): self.bluez.discover(ADAPTER) + self.assertEqual(self.bluez.call.call_args_list[0].args, (ADAPTER, 'org.bluez.Adapter1', 'StartDiscovery')) + self.assertEqual(self.bluez.call.call_args_list[1].args, (ADAPTER, 'org.bluez.Adapter1', 'StopDiscovery')) + self.bluez.GLib.MainLoop.return_value.run.assert_called_once() + + def test_failed_start_never_sends_stop(self): + self.bluez.call.side_effect = RuntimeError('NotReady') + with self.assertRaisesRegex(RuntimeError, 'NotReady'): self.bluez.discover(ADAPTER) + self.bluez.call.assert_called_once() + self.bluez.GLib.MainLoop.return_value.run.assert_not_called() + + +if __name__ == '__main__': unittest.main() diff --git a/quickshell/tests/test_brightness.py b/quickshell/tests/test_brightness.py new file mode 100644 index 0000000..0814733 --- /dev/null +++ b/quickshell/tests/test_brightness.py @@ -0,0 +1,33 @@ +import importlib.util +import pathlib +import unittest +from unittest.mock import patch + +PATH = pathlib.Path(__file__).resolve().parents[1] / 'backend' / 'brightness.py' +spec = importlib.util.spec_from_file_location('brightness', PATH) +brightness = importlib.util.module_from_spec(spec) +spec.loader.exec_module(brightness) + + +class BrightnessTests(unittest.TestCase): + def test_parse_only_backlights(self): + data = 'intel_backlight,backlight,400,800,50%\nled0,leds,1,2,50%\n' + self.assertEqual(brightness.parse_devices(data), [{'name': 'intel_backlight', 'current': 400, 'maximum': 800, 'percent': 50}]) + + def test_reject_invalid_percent(self): + with self.assertRaises(ValueError): + brightness.main(['brightness.py', 'set', 'intel_backlight', '0']) + + def test_reject_unlisted_device(self): + with patch.object(brightness, 'run', return_value='intel_backlight,backlight,50,100,50%'): + with self.assertRaises(ValueError): + brightness.main(['brightness.py', 'set', 'unknown', '40']) + + def test_set_uses_argument_vector(self): + with patch.object(brightness, 'run', side_effect=['intel_backlight,backlight,50,100,50%', '', 'intel_backlight,backlight,60,100,60%']) as call: + self.assertEqual(brightness.main(['brightness.py', 'set', 'intel_backlight', '60'])['devices'][0]['percent'], 60) + self.assertEqual(call.call_args_list[1].args[0], ['--device', 'intel_backlight', 'set', '60%']) + + +if __name__ == '__main__': + unittest.main() diff --git a/quickshell/tests/test_display_position.py b/quickshell/tests/test_display_position.py new file mode 100644 index 0000000..0d4709b --- /dev/null +++ b/quickshell/tests/test_display_position.py @@ -0,0 +1,25 @@ +import importlib.util +from pathlib import Path +from unittest.mock import patch +import unittest + +spec = importlib.util.spec_from_file_location('display_preview', Path(__file__).resolve().parents[1] / 'backend/display_preview.py') +module = importlib.util.module_from_spec(spec) +spec.loader.exec_module(module) + +class PositionTests(unittest.TestCase): + def test_negative_coordinates(self): + self.assertIn(',-1920x0,', module.monitor_rule('DP-1', '1920x1080@60', '-1920x0', '1', 1)) + + def test_invalid_position(self): + with self.assertRaises(ValueError): + module.monitor_rule('DP-1', 'preferred', 'left', '1') + + def test_preview_validates_coordinate_pair(self): + with patch.object(module, 'current', return_value={'name':'DP-1','x':0,'y':0,'width':1920,'height':1080,'refreshRate':60,'scale':1,'transform':0}): + with self.assertRaisesRegex(ValueError, 'вместе'): + module.preview('DP-1', 'preferred', '1', '0', '10') + with self.assertRaisesRegex(ValueError, 'координаты'): + module.preview('DP-1', 'preferred', '1', '0', '999999', '0') + +if __name__ == '__main__': unittest.main() diff --git a/quickshell/tests/test_display_preview.py b/quickshell/tests/test_display_preview.py new file mode 100644 index 0000000..1d32633 --- /dev/null +++ b/quickshell/tests/test_display_preview.py @@ -0,0 +1,59 @@ +import importlib.util +from pathlib import Path +import unittest +from unittest.mock import patch + +path = Path(__file__).resolve().parents[1] / 'backend' / 'display_preview.py' +spec = importlib.util.spec_from_file_location('display_preview', path) +mod = importlib.util.module_from_spec(spec) +spec.loader.exec_module(mod) + +class DisplayPreviewTests(unittest.TestCase): + def test_valid_rule(self): + self.assertEqual(mod.monitor_rule('eDP-1', '1920x1080@60.00', '0x0', '1.25'), 'eDP-1,1920x1080@60.00,0x0,1.25') + + def test_reject_injection(self): + for value in ('eDP-1;rm -rf /', 'eDP-1,disable', '../monitor'): + with self.assertRaises(ValueError): + mod.monitor_rule(value, 'preferred', 'auto', '1') + with self.assertRaises(ValueError): + mod.monitor_rule('eDP-1', '1920x1080;bad', 'auto', '1') + + def test_original_rule(self): + data = {'name':'eDP-1','width':1920,'height':1080,'refreshRate':60,'x':-1920,'y':0,'scale':1.5} + self.assertEqual(mod.original_rule(data), 'eDP-1,1920x1080@60.00,-1920x0,1.5,transform,0') + + def test_transform_and_position(self): + self.assertEqual(mod.monitor_rule('DP-1', 'preferred', '-1200x0', '1.5', 3), + 'DP-1,preferred,-1200x0,1.5,transform,3') + with self.assertRaises(ValueError): + mod.monitor_rule('DP-1', 'preferred', 'auto', '1', 8) + with self.assertRaises(ValueError): + mod.monitor_rule('DP-1', 'preferred', 'auto', '1', True) + + def test_preview_keeps_position_and_rotation(self): + monitor = {'name':'eDP-1', 'width':1080, 'height':2400, 'refreshRate':60, + 'x':-1080, 'y':200, 'scale':1.5, 'transform':1} + with patch.object(mod, 'current', return_value=monitor), \ + patch.object(mod, 'state_dir') as directory, \ + patch.object(mod, 'run_hypr') as run, \ + patch.object(mod.subprocess, 'Popen') as popen: + import tempfile + with tempfile.TemporaryDirectory() as tmp: + directory.return_value = Path(tmp) + popen.return_value.pid = 123 + result = mod.preview('eDP-1', 'preferred', '2', '3') + self.assertTrue(result['ok']) + run.assert_called_once_with('eDP-1,preferred,-1080x200,2,transform,3') + + def test_unknown_command(self): + with self.assertRaises(ValueError): + mod.main(['delete', 'eDP-1']) + + def test_hyprctl_no_shell(self): + with patch.object(mod.subprocess, 'run') as run: + mod.run_hypr('eDP-1,preferred,auto,1') + self.assertEqual(run.call_args.args[0], ['hyprctl','keyword','monitor','eDP-1,preferred,auto,1']) + +if __name__ == '__main__': + unittest.main() diff --git a/quickshell/tests/test_displays.py b/quickshell/tests/test_displays.py new file mode 100644 index 0000000..72a85b9 --- /dev/null +++ b/quickshell/tests/test_displays.py @@ -0,0 +1,39 @@ +import importlib.util +import pathlib +import unittest +from unittest.mock import patch + +PATH = pathlib.Path(__file__).resolve().parents[1] / 'backend' / 'displays.py' +spec = importlib.util.spec_from_file_location('displays', PATH) +displays = importlib.util.module_from_spec(spec) +spec.loader.exec_module(displays) + + +class DisplayTests(unittest.TestCase): + def test_normalize(self): + monitor = {'name': 'eDP-1', 'width': 1920, 'height': 1080, 'refreshRate': 59.999, 'scale': 1.25, 'focused': True, 'availableModes': ['1920x1080@60.00Hz']} + result = displays.normalize([monitor])[0] + self.assertEqual((result['width'], result['height']), (1920, 1080)) + self.assertEqual(result['refreshRate'], 60.0) + self.assertEqual(result['availableModes'], ['1920x1080@60.00Hz']) + + def test_invalid_list(self): + with self.assertRaises(ValueError): + displays.normalize({}) + + def test_missing_name_skipped(self): + self.assertEqual(displays.normalize([{}, None]), []) + + def test_read_only_command(self): + with patch.object(displays.subprocess, 'run') as run: + run.return_value.stdout = '[]' + self.assertEqual(displays.main(['list'])['monitors'], []) + self.assertEqual(run.call_args.args[0], ['hyprctl', '-j', 'monitors', 'all']) + + def test_mutating_command_rejected(self): + with self.assertRaises(ValueError): + displays.main(['set', 'eDP-1', '1920x1080']) + + +if __name__ == '__main__': + unittest.main() diff --git a/quickshell/tests/test_lua.lua b/quickshell/tests/test_lua.lua new file mode 100644 index 0000000..12a8172 --- /dev/null +++ b/quickshell/tests/test_lua.lua @@ -0,0 +1,21 @@ +-- Exercise startup selection without executing commands or changing the session. +local profile, notification_profile = arg[1], arg[2] +local original_getenv = os.getenv +os.getenv = function(name) + if name == "ADAPTIVE_SHELL" then return profile end + if name == "ADAPTIVE_NOTIFICATIONS" then return notification_profile end + return original_getenv(name) +end +local commands = {} +hl = { + on = function(event, callback) assert(event == "hyprland.start"); callback() end, + exec_cmd = function(command) commands[command] = true end, +} +dofile("hypr/startup.lua") +dofile("hypr/programs.lua") +assert(commands["hypridle"] and commands["lxpolkit"] and commands["clipse -listen"]) +assert(commands["waybar"] == (profile ~= "1" and true or nil)) +assert(commands["~/dotfiles/hypr/bin/adaptive-shell start"] == (profile == "1" and true or nil)) +assert(commands["swaync"] == ((profile ~= "1" or notification_profile ~= "1") and true or nil)) +assert((launcher:find("adaptive-shell", 1, true) ~= nil) == (profile == "1")) +print("PASS startup and command routing", profile, notification_profile) diff --git a/quickshell/tests/test_mobile_connections.py b/quickshell/tests/test_mobile_connections.py new file mode 100644 index 0000000..1a18326 --- /dev/null +++ b/quickshell/tests/test_mobile_connections.py @@ -0,0 +1,39 @@ +import importlib.util +from pathlib import Path +from unittest import TestCase +from unittest.mock import patch + +path = Path(__file__).resolve().parents[1] / 'backend' / 'mobile_connections.py' +spec = importlib.util.spec_from_file_location('mobile_connections', path) +module = importlib.util.module_from_spec(spec) +spec.loader.exec_module(module) + +UID = '12345678-1234-1234-1234-123456789abc' + +class MobileConnectionsTests(TestCase): + @patch.object(module.shutil, 'which', return_value='/usr/bin/nmcli') + def test_create_argument_vector(self, _): + calls = [] + def runner(args, **kwargs): + calls.append(args) + return type('R', (), {'returncode': 0, 'stdout': '', 'stderr': ''})() + self.assertTrue(module.manage('create', 'Mobile internet', 'internet', runner)['ok']) + self.assertEqual(calls[0][-9:], ['connection', 'add', 'type', 'gsm', 'con-name', 'Mobile internet', 'apn', 'internet', 'connection.autoconnect', 'no'][-9:]) + + @patch.object(module.shutil, 'which', return_value='/usr/bin/nmcli') + def test_rejects_injection(self, _): + for apn in ('bad;echo', '--help', 'foo bar', ''): + self.assertFalse(module.manage('create', 'internet', apn)['ok']) + self.assertFalse(module.manage('delete', '--all')['ok']) + + @patch.object(module.shutil, 'which', return_value='/usr/bin/nmcli') + def test_only_mobile_uuid_allowed(self, _): + def runner(args, **kwargs): + return type('R', (), {'returncode': 0, 'stdout': UID + ':802-3-ethernet:Wired\n', 'stderr': ''})() + self.assertFalse(module.manage('delete', UID, runner=runner)['ok']) + + @patch.object(module.shutil, 'which', return_value='/usr/bin/nmcli') + def test_lists_mobile_only(self, _): + def runner(args, **kwargs): + return type('R', (), {'returncode': 0, 'stdout': UID + ':gsm:Mobile\n' + UID + ':wifi:Wifi\n', 'stderr': ''})() + self.assertEqual(len(module.list_profiles(runner)['profiles']), 1) diff --git a/quickshell/tests/test_modem_control.py b/quickshell/tests/test_modem_control.py new file mode 100644 index 0000000..029fc97 --- /dev/null +++ b/quickshell/tests/test_modem_control.py @@ -0,0 +1,27 @@ +import importlib.util +from pathlib import Path +from unittest import TestCase +from unittest.mock import patch + +path = Path(__file__).resolve().parents[1] / 'backend' / 'modem_control.py' +spec = importlib.util.spec_from_file_location('modem_control', path) +module = importlib.util.module_from_spec(spec) +spec.loader.exec_module(module) + + +class ModemControlTests(TestCase): + def test_rejects_invalid_ids(self): + for value in ('-1', '1;touch /tmp/foo', '../../etc/passwd', '999999'): + self.assertFalse(module.control(value, 'enable')['ok']) + + def test_rejects_arbitrary_actions(self): + self.assertFalse(module.control('0', 'reset')['ok']) + + @patch.object(module.shutil, 'which', return_value='/usr/bin/mmcli') + def test_uses_argument_vector(self, _): + calls = [] + def runner(args, **kwargs): + calls.append(args) + return type('Result', (), {'returncode': 0, 'stderr': ''})() + self.assertTrue(module.control('7', 'disable', runner)['ok']) + self.assertEqual(calls, [['mmcli', '-m', '7', '--disable']]) diff --git a/quickshell/tests/test_modems.py b/quickshell/tests/test_modems.py new file mode 100644 index 0000000..b6c4d79 --- /dev/null +++ b/quickshell/tests/test_modems.py @@ -0,0 +1,29 @@ +import importlib.util +import pathlib +import unittest + +MODULE = pathlib.Path(__file__).resolve().parents[1] / 'backend' / 'modems.py' +spec = importlib.util.spec_from_file_location('modems', MODULE) +modems = importlib.util.module_from_spec(spec) +spec.loader.exec_module(modems) + + +class ModemTests(unittest.TestCase): + def test_empty_inventory(self): + self.assertEqual(modems.modem_paths({'modem-list': []}), []) + + def test_reject_invalid_paths(self): + self.assertEqual(modems.modem_paths({'modem-list': ['/tmp/evil', '/org/freedesktop/ModemManager1/Modem/3']}), ['/org/freedesktop/ModemManager1/Modem/3']) + + def test_modem_without_sim(self): + item = modems.describe({'modem': {'generic': {'model': 'LTE', 'sim': '--', 'signal-quality': {'value': 55}}}}, '/org/freedesktop/ModemManager1/Modem/2') + self.assertFalse(item['simPresent']) + self.assertEqual(item['signal'], 55) + + def test_modem_with_sim(self): + item = modems.describe({'modem': {'generic': {'sim': '/org/freedesktop/ModemManager1/SIM/0'}}}, '/org/freedesktop/ModemManager1/Modem/0') + self.assertTrue(item['simPresent']) + + +if __name__ == '__main__': + unittest.main() diff --git a/quickshell/tests/test_power_backend.py b/quickshell/tests/test_power_backend.py new file mode 100644 index 0000000..e68b89f --- /dev/null +++ b/quickshell/tests/test_power_backend.py @@ -0,0 +1,164 @@ +"""All mutation tests use injected objects. No real logind or Wayland calls.""" +import importlib.util +from pathlib import Path +import subprocess +import unittest +import sys +from unittest.mock import Mock, patch + +spec = importlib.util.spec_from_file_location('power_backend', Path(__file__).resolve().parents[1] / 'backend/power.py') +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'backend')) +backend = importlib.util.module_from_spec(spec) +spec.loader.exec_module(backend) + + +class PowerTests(unittest.TestCase): + def setUp(self): + self.events = [] + self.logind = Mock() + self.logind.can.side_effect = lambda action: self.events.append('can:' + action) or 'yes' + self.logind.perform.side_effect = lambda action: self.events.append('perform:' + action) + self.observer = Mock() + self.observer.ensure_locked.side_effect = lambda: self.events.append('locked') + self.observer.close.side_effect = lambda: self.events.append('observer closed') + self.factory = Mock(return_value=self.logind) + self.observer_factory = Mock(return_value=self.observer) + + def execute(self, action): + backend.execute(action, logind_factory=self.factory, observer_factory=self.observer_factory) + + def test_authorization_is_not_interactive_after_lock(self): + logind = object.__new__(backend.Logind) + logind.call = Mock() + logind.perform('suspend') + logind.call.assert_called_with('Suspend', False) + logind.perform('reboot') + logind.call.assert_called_with('Reboot', True) + + def test_suspend_waits_for_lock(self): + self.execute('suspend') + self.assertEqual(self.events, ['can:suspend', 'locked', 'perform:suspend', 'observer closed']) + + def test_lock_failure_prevents_suspend(self): + self.observer.ensure_locked.side_effect = RuntimeError('no lock confirmation') + with self.assertRaisesRegex(RuntimeError, 'no lock confirmation'): self.execute('suspend') + self.logind.perform.assert_not_called() + self.observer.close.assert_called_once() + + def test_unavailable_protocol_prevents_suspend(self): + self.observer_factory.side_effect = ImportError('no protocol') + with self.assertRaises(ImportError): self.execute('suspend') + self.logind.perform.assert_not_called() + + def test_suspend_challenge_never_locks_or_sleeps(self): + self.logind.can.side_effect = None + self.logind.can.return_value = 'challenge' + with self.assertRaisesRegex(RuntimeError, 'before locking'): self.execute('suspend') + self.observer_factory.assert_not_called() + self.logind.perform.assert_not_called() + + def test_reboot_challenge_uses_logind(self): + self.logind.can.side_effect = None + self.logind.can.return_value = 'challenge' + self.execute('reboot') + self.logind.perform.assert_called_once_with('reboot') + self.observer_factory.assert_not_called() + + def test_denied_actions_never_execute(self): + for state in ['no', 'na', 'unknown']: + self.logind.can.side_effect = None + self.logind.can.return_value = state + with self.assertRaises(RuntimeError): self.execute('poweroff') + self.logind.perform.assert_not_called() + + def test_lock_only_never_uses_logind(self): + self.execute('lock') + self.factory.assert_not_called() + self.observer.ensure_locked.assert_called_once() + self.observer.close.assert_called_once() + + def test_unknown_action_never_executes(self): + with self.assertRaises(ValueError): self.execute('reboot; command') + self.factory.assert_not_called() + self.observer_factory.assert_not_called() + + def test_logout_dispatch_is_fixed_and_session_scoped(self): + for provider, expected in [('lua', ['hyprctl', 'eval', 'hl.dispatch(hl.dsp.exit())']), ('conf', ['hyprctl', 'dispatch', 'exit'])]: + run = Mock() + backend.execute('logout', compositor_query=lambda: {'configProvider': provider}, run=run) + self.assertEqual(run.call_args.args[0], expected) + + def test_logout_error_propagates(self): + run = Mock(side_effect=subprocess.TimeoutExpired('hyprctl', 5)) + with self.assertRaises(subprocess.TimeoutExpired): + backend.execute('logout', compositor_query=lambda: {'configProvider': 'lua'}, run=run) + + @patch.object(backend.shutil, 'which', return_value='/test/hyprlock') + def test_capabilities_are_real_states(self, which): + result = backend.capabilities(self.factory, self.observer_factory, lambda: {}) + self.assertEqual(result['lock']['state'], 'yes') + self.assertEqual(result['suspend']['state'], 'yes') + self.logind.perform.assert_not_called() + self.observer.ensure_locked.assert_not_called() + + def test_unavailable_backend_never_reports_yes(self): + fail = Mock(side_effect=RuntimeError('unavailable')) + result = backend.capabilities(fail, fail, fail) + self.assertFalse(any(action['state'] == 'yes' for action in result.values())) + + +from lock_observer import LockObserver + + +class LockObserverTests(unittest.TestCase): + def setUp(self): + self.observer = object.__new__(LockObserver) + self.observer.locked = False + self.observer.display = Mock() + self.child = Mock() + self.child.poll.return_value = None + + def test_existing_lock_is_rechecked(self): + self.observer.locked = True + with patch('lock_observer.subprocess.Popen') as popen: + self.observer.ensure_locked() + self.observer.display.roundtrip.assert_called_once() + popen.assert_not_called() + + def test_missing_locker_cannot_confirm_lock(self): + with patch('lock_observer.shutil.which', return_value=None): + with self.assertRaisesRegex(RuntimeError, 'not installed'): self.observer.ensure_locked() + + @patch('lock_observer.shutil.which', return_value='/test/hyprlock') + def test_locker_exit_is_not_confirmation(self, which): + self.child.poll.return_value = 1 + with patch('lock_observer.subprocess.Popen', return_value=self.child): + with self.assertRaisesRegex(RuntimeError, 'before the compositor'): self.observer.ensure_locked() + + @patch('lock_observer.shutil.which', return_value='/test/hyprlock') + def test_lock_timeout_is_not_confirmation(self, which): + with patch('lock_observer.subprocess.Popen', return_value=self.child), patch('lock_observer.time.monotonic', side_effect=[0, 20]): + with self.assertRaisesRegex(RuntimeError, 'Timed out'): self.observer.ensure_locked() + self.child.terminate.assert_not_called() + + @patch('lock_observer.shutil.which', return_value='/test/hyprlock') + def test_compositor_event_confirms_lock(self, which): + def ready(*args): + self.observer.locked = True + return ([1], [], []) + with patch('lock_observer.subprocess.Popen', return_value=self.child) as popen, patch('lock_observer.select.select', side_effect=ready): + self.observer.ensure_locked() + self.assertEqual(popen.call_args.args[0], ['/test/hyprlock', '--grace', '0']) + self.observer.display.roundtrip.assert_called_once() + + @patch('lock_observer.shutil.which', return_value='/test/hyprlock') + def test_unlock_before_action_is_rejected(self, which): + def ready(*args): + self.observer.locked = True + return ([1], [], []) + self.observer.display.roundtrip.side_effect = lambda: setattr(self.observer, 'locked', False) + with patch('lock_observer.subprocess.Popen', return_value=self.child), patch('lock_observer.select.select', side_effect=ready): + with self.assertRaisesRegex(RuntimeError, 'unlocked'): self.observer.ensure_locked() + + +if __name__ == '__main__': unittest.main() diff --git a/quickshell/tests/test_power_profiles.py b/quickshell/tests/test_power_profiles.py new file mode 100644 index 0000000..eecfb98 --- /dev/null +++ b/quickshell/tests/test_power_profiles.py @@ -0,0 +1,31 @@ +import importlib.util +from pathlib import Path +from types import SimpleNamespace + +path = Path(__file__).resolve().parents[1] / 'backend' / 'power_profiles.py' +spec = importlib.util.spec_from_file_location('power_profiles', path) +module = importlib.util.module_from_spec(spec) +spec.loader.exec_module(module) + + +def test_get(): + def runner(args, **kwargs): + assert args == ['powerprofilesctl', 'get'] + return SimpleNamespace(returncode=0, stdout='balanced\n', stderr='') + assert module.execute(['get'], runner=runner, which=lambda _: '/bin/powerprofilesctl')['profile'] == 'balanced' + + +def test_invalid_profile_never_invokes_command(): + def runner(*args, **kwargs): + raise AssertionError('must not run') + assert not module.execute(['set', ';reboot'], runner=runner, which=lambda _: '/bin/powerprofilesctl')['ok'] + + +def test_missing_utility(): + assert not module.execute(['get'], which=lambda _: None)['ok'] + + +def test_backend_failure(): + def runner(args, **kwargs): + return SimpleNamespace(returncode=1, stdout='', stderr='denied') + assert 'denied' in module.execute(['set', 'balanced'], runner=runner, which=lambda _: '/bin/powerprofilesctl')['error'] diff --git a/quickshell/tests/test_system_info.py b/quickshell/tests/test_system_info.py new file mode 100644 index 0000000..e81ea2e --- /dev/null +++ b/quickshell/tests/test_system_info.py @@ -0,0 +1,24 @@ +import importlib.util +from pathlib import Path +import tempfile +import unittest + +spec = importlib.util.spec_from_file_location('system_info', Path(__file__).resolve().parents[1] / 'backend/system_info.py') +module = importlib.util.module_from_spec(spec) +spec.loader.exec_module(module) + +class SystemInfoTests(unittest.TestCase): + def test_os_release(self): + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / 'os-release' + path.write_text('PRETTY_NAME="Arch Linux ARM"\nIGNORED=secret\n') + self.assertEqual(module.os_release(path), {'PRETTY_NAME': 'Arch Linux ARM'}) + def test_memory(self): + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / 'meminfo' + path.write_text('MemTotal: 4096000 kB\nMemAvailable: 1024000 kB\n') + self.assertEqual(module.memory_kib(path)['MemTotal'], 4096000) + def test_uptime_invalid(self): + self.assertEqual(module.uptime_seconds('/nonexistent/uptime'), 0) + +if __name__ == '__main__': unittest.main() diff --git a/quickshell/tests/tst_hardware_policy.qml b/quickshell/tests/tst_hardware_policy.qml new file mode 100644 index 0000000..a085c2f --- /dev/null +++ b/quickshell/tests/tst_hardware_policy.qml @@ -0,0 +1,51 @@ +import QtQuick +import QtTest +import "../services/HardwarePolicy.js" as Policy + +TestCase { + name: "HardwarePolicy" + function test_ethernet_only() { + const devices = [{type: 2, name: "enp3s0", connected: true}, {type: 2, name: "enp4s0", connected: false}]; + const caps = Policy.networkCapabilities(devices, 1, 2); + compare(caps.wifi, false); + compare(caps.wired.length, 2); + compare(Policy.ethernetSummary(caps.wired), "Ethernet · 1/2"); + } + function test_disabled_wifi_remains_visible() { + const caps = Policy.networkCapabilities([{type: 1, enabled: false}], 1, 2); + compare(caps.wifi, true); + compare(caps.wired.length, 0); + } + function test_hotplug_recomputed() { + const initial = Policy.networkCapabilities([], 1, 2); + const plugged = Policy.networkCapabilities([{type: 2, connected: false}], 1, 2); + compare(initial.hasNetworkDevices, false); + compare(plugged.hasNetworkDevices, true); + compare(Policy.ethernetSummary(plugged.wired), "Ethernet · нет подключения"); + } + function test_battery_hotplug() { + const withBattery = Policy.visibleSettingsSections(false, false, false, false, true); + compare(withBattery.map(s => s.id).join(","), "appearance,wallpaper,battery,system"); + compare(Policy.pageIndex("battery"), 7); + compare(Policy.visibleSettingsSections(false, false, false, false, false).some(s => s.id === "battery"), false); + } + function test_settings_capabilities() { + const sections = Policy.visibleSettingsSections(false, true, false); + compare(sections.map(s => s.id).join(","), "appearance,network,wallpaper,system"); + } + function test_settings_order_and_pages() { + const sections = Policy.visibleSettingsSections(true, true, true); + compare(sections.map(s => s.id).join(","), "appearance,audio,network,wallpaper,bluetooth,system"); + compare(Policy.sectionIndex(sections, "bluetooth"), 4); + compare(Policy.pageIndex("bluetooth"), 4); + compare(Policy.pageIndex("network"), 2); + } + function test_hotplug_removes_section_without_reindexing_page() { + const plugged = Policy.visibleSettingsSections(false, true, true); + const unplugged = Policy.visibleSettingsSections(false, true, false); + compare(Policy.sectionIndex(plugged, "bluetooth"), 3); + compare(Policy.sectionIndex(unplugged, "bluetooth"), -1); + compare(Policy.pageIndex("network"), 2); + compare(Policy.pageIndex("missing"), 0); + } +} diff --git a/quickshell/tests/tst_notifications.qml b/quickshell/tests/tst_notifications.qml new file mode 100644 index 0000000..0565642 --- /dev/null +++ b/quickshell/tests/tst_notifications.qml @@ -0,0 +1,34 @@ +import QtQuick +import QtTest +import "../services/NotificationPolicy.js" as Policy + +TestCase { + name: "NotificationPolicy" + function test_timeout() { + compare(Policy.timeoutMs(-1, 0), 3000); + compare(Policy.timeoutMs(-1, 1), 6000); + compare(Policy.timeoutMs(250, 1), 250); + compare(Policy.timeoutMs(0, 1), 0); + compare(Policy.timeoutMs(1, 2), 0); + compare(Policy.timeoutMs(1e20, 1), 2147483647); + } + function entry(key) { return {key: key, appName: "Test", summary: "Summary", body: "Body", state: "received", urgency: 1, time: 100}; } + function test_history_limit_and_replace() { + let history = []; + for (let i = 0; i < 110; i++) history = Policy.upsert(history, entry(String(i))); + compare(history.length, 100); + compare(history[0].key, "109"); + const replacement = entry("109"); replacement.summary = "Updated"; + history = Policy.upsert(history, replacement); + compare(history.length, 100); + compare(history[0].summary, "Updated"); + } + function test_validation() { + compare(Policy.validate({version: 1, entries: [entry("a")]}).length, 1); + for (const invalid of [{version: 2, entries: []}, {version: 1, entries: [entry("a"), entry("a")]}, {version: 1, entries: [{key: "bad"}]}, {version: 1, entries: [Object.assign(entry("a"), {deadline: "soon"})]}]) { + let rejected = false; + try { Policy.validate(invalid); } catch(e) { rejected = true; } + verify(rejected); + } + } +} diff --git a/quickshell/tests/tst_policy.qml b/quickshell/tests/tst_policy.qml new file mode 100644 index 0000000..a8812af --- /dev/null +++ b/quickshell/tests/tst_policy.qml @@ -0,0 +1,50 @@ +import QtQuick +import QtTest +import "../services/Policy.js" as Policy + +TestCase { + name: "AdaptivePolicy" + function verifyExceptionThrown(fn) { + let threw = false; + try { fn(); } catch (e) { threw = true; } + verify(threw, "Invalid preferences must be rejected"); + } + function defaults() { return {version: 1, mode: "auto", theme: "dark", touch: false, reducedMotion: false, outputs: {}}; } + function test_modes_data() { + return [ + {tag: "narrow desktop", preference: "auto", width: 400, touch: false, expected: "desktop"}, + {tag: "phone", preference: "auto", width: 390, touch: true, expected: "phone"}, + {tag: "tablet boundary", preference: "auto", width: 600, touch: true, expected: "tablet"}, + {tag: "external monitor", preference: "auto", width: 1920, touch: true, expected: "desktop"}, + {tag: "manual phone on PC", preference: "phone", width: 3440, touch: false, expected: "phone"} + ]; + } + function test_modes(data) { compare(Policy.modeFor(data.preference, data.width, data.touch), data.expected); } + function test_valid() { compare(Policy.validate(defaults()).version, 1); } + function test_reject_schema() { const d = defaults(); d.version = 2; verifyExceptionThrown(() => Policy.validate(d)); } + function test_reject_mode() { const d = defaults(); d.mode = "watch"; verifyExceptionThrown(() => Policy.validate(d)); } + function test_reject_output() { const d = defaults(); d.outputs = {"DP-1": "invalid"}; verifyExceptionThrown(() => Policy.validate(d)); } + function test_reject_flags() { const d = defaults(); d.touch = "yes"; verifyExceptionThrown(() => Policy.validate(d)); } + function test_launcher_rank() { + const apps = [{id: "a", name: "Alpha"}, {id: "b", name: "Beta"}, {id: "c", name: "Charlie"}]; + compare(Policy.rankApps(apps, ["c"], ["b"]).map(a => a.id).join(","), "c,b,a"); + compare(apps[0].id, "a"); // Ranking must not mutate the model. + } + function test_history_bounded() { + const history = Array.from({length: 50}, (_, i) => String(i)); + const next = Policy.recordLaunch(history, "new"); + compare(next.length, 50); + compare(next[0], "new"); + compare(Policy.recordLaunch(next, "1").filter(id => id === "1").length, 1); + } + function test_favorite_toggle() { + compare(Policy.toggleFavorite(["a"], "a").length, 0); + compare(Policy.toggleFavorite([], "a")[0], "a"); + } + function test_invalid_application_lists() { + for (const invalid of [["a", "a"], [""], [42], "a"]) { + const data = defaults(); data.favorites = invalid; + verifyExceptionThrown(() => Policy.validate(data)); + } + } +} diff --git a/quickshell/tests/tst_wallpaper.qml b/quickshell/tests/tst_wallpaper.qml new file mode 100644 index 0000000..0d6a719 --- /dev/null +++ b/quickshell/tests/tst_wallpaper.qml @@ -0,0 +1,41 @@ +import QtQuick +import QtTest +import "../services/WallpaperPolicy.js" as Policy +import "../services/Policy.js" as PreferencesPolicy + +TestCase { + name: "WallpaperPolicy" + function test_local_paths() { + const path = "/tmp/обои a '#%?.png"; + const url = Policy.localUrl(path); + verify(url.startsWith("file:///tmp/")); + verify(url.includes("%20")); + verify(url.includes("%23")); + compare(Policy.localUrl(url), url); + compare(decodeURIComponent(url.slice(7)), path); + compare(Policy.localUrl(""), ""); + } + function test_reject_nonlocal() { + for (const path of ["https://example.com/a.png", "../a.png", "~/a.png", "file://host/a.png", "file:///%GG", "file:///tmp/a%00b", "/tmp/a\u0000b", null]) { + let rejected = false; + try { Policy.localUrl(path); } catch(e) { rejected = true; } + verify(rejected, String(path)); + } + } + function test_override_and_disable() { + const wallpapers = {"*": "/tmp/all.png", "DP-1": ""}; + compare(Policy.sourceFor(wallpapers, "DP-1"), ""); + compare(Policy.sourceFor(wallpapers, "HDMI-A-1"), "file:///tmp/all.png"); + compare(Policy.sourceFor(undefined, "DP-1"), ""); + } + function test_schema_compatibility() { + const prefs = {version: 1, mode: "auto", theme: "dark", touch: false, reducedMotion: false, outputs: {}}; + compare(PreferencesPolicy.validate(prefs).version, 1); + prefs.wallpapers = {"*": "/tmp/a.png"}; + compare(PreferencesPolicy.validate(prefs).wallpapers["*"], "/tmp/a.png"); + prefs.wallpapers = {"*": "https://example.com/a.png"}; + let rejected = false; + try { PreferencesPolicy.validate(prefs); } catch(e) { rejected = true; } + verify(rejected); + } +} diff --git a/quickshell/tests/wallpapers.py b/quickshell/tests/wallpapers.py new file mode 100644 index 0000000..63a6ae0 --- /dev/null +++ b/quickshell/tests/wallpapers.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +"""Static wallpaper integration on desktop; never stops the existing wallpaper daemon.""" +import json +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile +import time +from urllib.parse import quote +import zlib + +if os.environ.get('ADAPTIVE_WALLPAPER_TEST_BUS') != '1': + os.execvpe('dbus-run-session', ['dbus-run-session', '--', sys.executable, __file__], + dict(os.environ, ADAPTIVE_WALLPAPER_TEST_BUS='1')) + +ROOT = Path(__file__).resolve().parents[1] + +def image(path, color): + def chunk(kind, data): + return struct.pack('!I', len(data)) + kind + data + struct.pack('!I', zlib.crc32(kind + data)) + raw = (b'\x00' + bytes(color) * 64) * 64 + path.write_bytes(b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('!2I5B', 64, 64, 8, 2, 0, 0, 0)) + + chunk(b'IDAT', zlib.compress(raw)) + chunk(b'IEND', b'')) + +def url(path): return 'file://' + quote(str(path), safe="/!~*'()") + +def wait_for(predicate, description, timeout=10): + end = time.monotonic() + timeout + while time.monotonic() < end: + if predicate(): return + time.sleep(.1) + raise AssertionError(description) + +with tempfile.TemporaryDirectory(prefix='adaptive-wallpaper-') as tmp: + tmp = Path(tmp) + first = tmp / "обои a '#%.png" + second = tmp / 'second.png' + image(first, (35, 45, 65)) + image(second, (65, 45, 35)) + env = dict(os.environ, QT_QPA_PLATFORM='wayland', QT_QUICK_CONTROLS_STYLE='Material', + XDG_STATE_HOME=str(tmp), XDG_CACHE_HOME=str(tmp), ADAPTIVE_NOTIFICATIONS='0') + log_path = tmp / 'shell.log' + log = log_path.open('w') + process = None + def start(): + return subprocess.Popen(['quickshell', '-p', str(ROOT), '--no-color'], env=env, + stdout=log, stderr=subprocess.STDOUT) + def ipc(*args): + result = subprocess.run(['quickshell', 'ipc', '--pid', str(process.pid), 'call', 'shell', *args], + env=env, text=True, capture_output=True, timeout=30) + if result.returncode: raise RuntimeError(result.stderr) + return result.stdout + def status(): return json.loads(ipc('status')) + def ready(): + if process.poll() is not None: raise RuntimeError(log_path.read_text()) + try: return status()['preferencesWritable'] + except (ValueError, RuntimeError): return False + def stop(): + process.terminate() + try: process.wait(timeout=3) + except subprocess.TimeoutExpired: process.kill(); process.wait() + def layers(): + result = subprocess.run(['hyprctl', '-j', 'layers'], env=env, capture_output=True, text=True, check=True, timeout=10) + def walk(node): + if isinstance(node, dict): + if node.get('namespace') == 'adaptive-wallpaper' and node.get('pid') == process.pid: yield node + for child in node.values(): yield from walk(child) + elif isinstance(node, list): + for child in node: yield from walk(child) + return list(walk(json.loads(result.stdout))) + try: + process = start() + wait_for(ready, 'shell readiness', 60) + monitors = json.loads(subprocess.run(['hyprctl', '-j', 'monitors'], env=env, capture_output=True, text=True, check=True, timeout=10).stdout) + monitor = next((m for m in monitors if m.get('focused')), monitors[0])['name'] + ipc('wallpapers') + assert all(s['state'] == 'disabled' for s in status()['wallpapers'].values()) + assert not layers(), 'Unconfigured wallpapers must not map a surface' + ipc('setWallpaper', '*', str(first)) + wait_for(lambda: len(status()['wallpapers']) == len(monitors) and all(s['state'] == 'ready' and s['displayed'] == url(first) for s in status()['wallpapers'].values()), 'common wallpaper ready') + wait_for(lambda: len(layers()) == len(monitors), 'background layer on each monitor') + ipc('reload') + time.sleep(.5) + wait_for(ready, 'reload readiness', 60) + wait_for(lambda: len(status()['wallpapers']) == len(monitors) and all(s['state'] == 'ready' and s['displayed'] == url(first) for s in status()['wallpapers'].values()), 'wallpaper ready after QML reload') + print('PASS common wallpaper, special paths, background layers and QML reload', flush=True) + + ipc('setWallpaper', monitor, str(second)) + wait_for(lambda: status()['wallpapers'][monitor]['displayed'] == url(second), 'per-output override') + assert all(s['displayed'] == url(first) for name, s in status()['wallpapers'].items() if name != monitor) + ipc('setWallpaper', monitor, 'https://example.com/image.png') + assert status()['wallpaperError'], 'Remote source must be rejected' + assert status()['wallpapers'][monitor]['displayed'] == url(second) + ipc('setWallpaper', monitor, str(tmp / 'missing.png')) + wait_for(lambda: status()['wallpapers'][monitor]['state'] == 'error', 'invalid file reported') + assert status()['wallpapers'][monitor]['displayed'] == url(second), 'Keep last good wallpaper' + print('PASS output override, remote rejection and missing-file fallback', flush=True) + + ipc('setWallpaper', monitor, '') + wait_for(lambda: status()['wallpapers'][monitor]['state'] == 'disabled', 'override disabled') + wait_for(lambda: len(layers()) == len(monitors) - 1, 'disabled surface removed') + ipc('inheritWallpaper', monitor) + wait_for(lambda: status()['wallpapers'][monitor]['displayed'] == url(first), 'inherit common wallpaper') + ipc('setWallpaper', 'TEST-DISCONNECTED', str(second)) + prefs = next(tmp.rglob('preferences.json')) + wait_for(lambda: json.loads(prefs.read_text()).get('wallpapers', {}).get('TEST-DISCONNECTED') == url(second), 'disconnected output preference saved') + stop() + process = start() + wait_for(ready, 'restarted shell readiness', 60) + wait_for(lambda: status()['wallpapers'][monitor]['displayed'] == url(first), 'wallpaper restored') + assert json.loads(prefs.read_text())['wallpapers']['TEST-DISCONNECTED'] == url(second) + ipc('setWallpaper', '*', '') + wait_for(lambda: not layers(), 'all test backgrounds removed') + print('PASS disable, inherit, disconnected preference and restart persistence', flush=True) + finally: + if process and process.poll() is None: + print('Final wallpaper state:', status(), flush=True) + stop() + log.close() + logs = log_path.read_text() + print(logs) + for marker in ['Failed to load configuration', 'ReferenceError', 'TypeError', 'Binding loop', 'Cannot assign', 'Cannot create delegate']: + assert marker not in logs, marker diff --git a/quickshell/tests/window_policy_node.cjs b/quickshell/tests/window_policy_node.cjs new file mode 100644 index 0000000..d7038f4 --- /dev/null +++ b/quickshell/tests/window_policy_node.cjs @@ -0,0 +1,16 @@ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const vm = require('node:vm'); +const source = fs.readFileSync(__dirname + '/../services/WindowPolicy.js', 'utf8').replace(/^\.pragma library\s*/m, ''); +const ctx = vm.createContext({}); +vm.runInContext(source, ctx); +const windows = [{activate(){}}, {activate(){}}, {activate(){}}]; +assert.equal(ctx.cycle(windows, -1, 1), windows[0]); +assert.equal(ctx.cycle(windows, 0, 1), windows[1]); +assert.equal(ctx.cycle(windows, 0, -1), windows[2]); +assert.equal(ctx.cycle([], 0, 1), null); +assert.equal(ctx.cycle(windows, 0, 3), null); +assert.equal(ctx.shouldDismissSwipe(0, -90, 300), true); +assert.equal(ctx.shouldDismissSwipe(90, -40, 300), false); +assert.equal(ctx.shouldDismissSwipe(0, 30, 300), false); +console.log('WindowPolicy tests passed'); diff --git a/rofi/clipboard/clipboard.sh b/rofi/clipboard/clipboard.sh old mode 100755 new mode 100644 diff --git a/rofi/emoji/rofimoji.sh b/rofi/emoji/rofimoji.sh old mode 100755 new mode 100644 diff --git a/rofi/launcher/launcher.sh b/rofi/launcher/launcher.sh old mode 100755 new mode 100644 diff --git a/rofi/powermenu/powermenu.sh b/rofi/powermenu/powermenu.sh old mode 100755 new mode 100644 diff --git a/templates/file.txt b/templates/file.txt old mode 100755 new mode 100644 diff --git a/templates/index.html b/templates/index.html old mode 100755 new mode 100644 diff --git a/templates/index.js b/templates/index.js old mode 100755 new mode 100644 diff --git a/templates/main.c b/templates/main.c old mode 100755 new mode 100644 diff --git a/templates/main.cpp b/templates/main.cpp old mode 100755 new mode 100644 diff --git a/templates/main.py b/templates/main.py old mode 100755 new mode 100644 diff --git a/templates/shell b/templates/shell old mode 100755 new mode 100644 diff --git a/templates/shell.sh b/templates/shell.sh old mode 100755 new mode 100644 diff --git a/templates/styles.css b/templates/styles.css old mode 100755 new mode 100644 diff --git a/waybar/scripts/get-weather.sh b/waybar/scripts/get-weather.sh old mode 100755 new mode 100644 diff --git a/waybar/scripts/spotify.sh b/waybar/scripts/spotify.sh old mode 100755 new mode 100644 diff --git a/waybar/scripts/waybar-wttr.py b/waybar/scripts/waybar-wttr.py old mode 100755 new mode 100644