commit 99e64a7713b8f65f486d7c1849d7299eac1ad16b Author: mx Date: Wed Oct 7 22:36:17 2026 +0200 Add glassMxrph shell sources Initial commit of the Quickshell desktop suite: bar, dock, launcher, settings, Control Center, dashboard, OSD, lock screen, desktop widgets, plugin host with the vendored Noctalia/Omarchy compatibility layer, helpers, packaging, tests and phase documentation. Includes the optimization work so far: usage widgets and dashboard gauges no longer animate continuously, desktop widgets pause while covered, system controls stop flickering on background polls, dock app matching uses an indexed catalog, and workspace ghosts are created only for occupied slots. Co-Authored-By: Claude Opus 5.5 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..b428705 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Unified patches contain intentional context prefixes before source whitespace. +packaging/patches/*.patch -whitespace diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..410f755 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +result +result-* +*.log +.cache/ +__pycache__/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..a104451 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,16 @@ +# Contributing + +Use the repository as the standalone project root. Keep distro-specific code in +`packaging/` and host-specific configuration outside this repository. + +Run `scripts/validate` with matching Qt/Quickshell import paths (or `nix develop`). +Run a real Wayland session test: lint alone cannot validate layer-shell behavior. +Keep shared state in services, semantic tokens in Theme, and reusable controls in +components. Do not add duplicate daemons or per-widget polling. + +Implementation proceeds in phases: foundation, tray, dock, launcher, settings and +theming, media, Control Center, metrics, polish. Each phase must pass runtime checks +before the next begins. Include missing-provider and multi-monitor cases. + +Licensing is pending the repository owner's choice. Do not copy third-party source +or assets without compatible licensing and attribution. diff --git a/README.md b/README.md new file mode 100644 index 0000000..2c2c195 --- /dev/null +++ b/README.md @@ -0,0 +1,213 @@ +# glassMxrph + +A portable, modular Quickshell desktop suite for Hyprland. Neutral glass surfaces, +configurable accents, and shared services. **Source implementation through Phase 9**, including foundation, tray, dock, launcher, settings, media, Control Center, metrics and polish. Host integration remains separate. + +## Run on Linux + +Install **Quickshell 0.3.1**, its matching Qt 6.8+ QML modules (`QtQuick`, +`QtQuick.Controls`, `QtQuick.Layouts`), Python 3, and Hyprland through your distribution. +The verified compositor is **Hyprland 0.56.2**. Distribution package names vary; +this project does not run package-manager installation scripts. + +From a clone, inside an existing Hyprland session: + +```sh +./scripts/glassmxrph run +``` + +In another terminal: + +```sh +./scripts/glassmxrph settings +./scripts/glassmxrph launcher +./scripts/glassmxrph status +./scripts/glassmxrph close +``` + +The runner is independent of the clone location and prevents duplicate instances +of this configuration. The preview uses no exclusive bar reservation, so it is a +preview and may overlap your current bar. Stop it with Ctrl+C in its launch terminal. +Do not add it to autostart until you are ready to replace your current shell. + +## Reproducible Nix package (optional, including non-NixOS Linux) + +Nix integration/build validation is deferred through Phase 9; use the source runner above. +The existing Phase 2 packaging is retained unchanged. + +The committed lock file pins nixpkgs and therefore Quickshell/Qt dependencies. +With Nix and flakes enabled: + +```sh +nix build +nix run +nix develop +./scripts/validate +# Optional, inside a real Hyprland session with no glassMxrph instance running: +python3 tests/runtime.py +``` + +A graphical session and working graphics drivers remain host prerequisites. +The package does not install or configure a compositor, modify user keybinds, +or depend on ZaneyOS. Non-NixOS graphics integration may require the host's +usual Nix graphics setup. Only x86_64-linux has been tested locally; aarch64-linux +is a packaging target, not a verified platform. + +The pinned Quickshell includes a small tray lifecycle compatibility patch. Native +Quickshell 0.3.1 packages need the same fix for applications registering multiple +tray objects on one DBus connection; see [compatibility](docs/compatibility.md). + +Native distribution installations are portable but are not identical builds +unless they provide the tested dependencies. Newer versions must be validated; +"any distro" does not mean any compositor or arbitrarily old Qt/Quickshell. + +## Current features + +- Floating, configurable left/center/right bar on each screen. +- Cog and centered settings surface, active-monitor selection, Escape/outside dismissal. +- Workspaces 1–9, occupied/urgent states and animated active indicator. +- Clock, shared glass controls, custom/system accent, watched Matugen palette input. +- Actual StatusNotifier tray entries with glass DBusMenu menus and recursive submenus. +- 400 ms hover intent, immediate right-click, left/middle activation and scroll forwarding. +- Application menu icons, separators, disabled entries, checks/radio states and keyboard navigation. +- Settings → Bar / Tray: enabled, hover menus/delay, icon size, spacing and background. +- Configurable floating dock: pins, running/focused windows, chooser, native app actions and drag reorder. +- Settings → Dock: app picker, monitor/edge, auto/intelligent hide, magnification and appearance. +- Centered active-monitor launcher with fuzzy app search, keyboard navigation and `>` commands. +- Shared Settings destinations and launcher preferences; IPC toggle without duplicate instances. +- Atomic configuration saves, validation, preserved unknown keys and default merging. +- Reduced motion, opacity and radius settings; IPC and duplicate prevention. +- macOS-style lock screen (ext-session-lock + PAM) with in-shader liquid glass matching your HyprGlass values; `glassmxrph lock`. Preview and test your password under Settings → Lock screen first. +- Plugins (Settings → Plugins, or `glassmxrph plugin install `): Omarchy shell plugins (plugins.omarchy.org) and Noctalia v4 plugins through compatibility layers in `quickshell/compat/omarchy` and `quickshell/compat/noctalia` (both MIT). Bar widgets live in glassMxrph pills, panels open as bar drawers, controls use the glassMxrph style; plugin options appear on the module cog. The Browse tab searches plugins.omarchy.org (cached, refreshed every six hours) and installs at the marketplace's validated commit after a confirmation showing the source and the review's flags. Plugins are stored in `~/.local/share/glassMxrph/plugins` and run unsandboxed in the shell, as in Omarchy. +- Per-screen bars: Settings → Bar → pick a screen and turn on Separate layout to give that monitor its own modules (`bar.screens`); other screens keep the shared layout. +- OSD animations (Settings → On-screen display): slide out of the bar, drop, fade or shrink. +- Caelestia-style drawers: the Control Center, dashboard (top placements), tray menus, bar hover previews, OSD (top positions) and wallpaper picker grow out of the bar as one continuous glass shape, joined by concave corners, and slide back into it. +- Dashboard (Caelestia-style, click the bar clock or `glassmxrph dashboard [tab]`): Dashboard, Media with an EasyEffects 10-band equalizer and presets, Performance, and Power (lock, restart, shut down). Settings → Dashboard sets placement, tab order and visibility. +- Active window bar module (`activeWindow`, add it under Settings → Bar): the focused app's icon and name; hover for a live preview with maximize, fullscreen and close. +- Desktop widgets (clock, calendar, weather, music, visualizer, system usage, network, user, image, note) with an on-desktop editor: drag, resize, snapping guides or grid; right-click a widget or run `glassmxrph widgets`. + +Appearance includes a visual colour picker, live Matugen generation and glass controls. +Wallpaper, bar and dock editors are available; Media provides shared MPRIS playback and player selection. The right-hand system pill opens Control Center with live controls. + +Shared CPU/GPU/RAM/storage/network metrics and the Phase 9 polish pass are available. HyprGlass integration is opt-in. The dock defaults to bottom; +left/right positioning is available only when explicitly selected in Dock settings. + +## Configuration + +Preferences: `$XDG_CONFIG_HOME/glassMxrph/config.json` (default `~/.config`). +Palette: `$XDG_STATE_HOME/glassMxrph/palette.json` (default `~/.local/state`). +Defaults: `quickshell/config/defaults.json`. Preferences are written only when +changed. Invalid input is preserved and editing is blocked until corrected. +No usernames, output names, Nix-store paths or system commands are baked into UI. + +Matugen 4.2.x is optional. Select it in Appearance to generate a palette from the +chosen wallpaper using an isolated template. The executable is configurable. +External palette files shaped like `{"accent":"#45a8bc"}` remain supported. +Missing palette falls back to the system accent. Surfaces remain neutral. +HyprGlass is optional. Appearance offers opt-in global controls for applications and +shell layers, including a Ghostty matching profile and Restore action. + +See [architecture](docs/architecture.md), [compatibility](docs/compatibility.md), +[validation](docs/validation.md), and [contributing](CONTRIBUTING.md). + +## Publishing + +This directory is the repository root: push its contents, not the surrounding +NixOS repository. No remote has been created and nothing has been published. +Choose a project license before public distribution; no license is assumed on +the owner's behalf. Do not include local configuration, generated palettes or logs. + +## Tray interactions and diagnostics + +Left-click activates the application (menu-only items open their menu). Middle-click +sends secondary activation. Right-click opens the exported application menu immediately. +Hover for 400 ms to open, or adjust/disable it under Settings → Bar / Tray. +Moving through the icon/menu/submenu region keeps it open. Hover-opened menus close +after a short exit grace period and never take keyboard focus; click-opened menus close +on outside click or Escape. Once a menu or bar popout is open, hovering another icon +or the active window pill switches to it instantly and the menu glides over. +Arrow keys navigate (click-opened menus); Enter activates; Right/Left enter/leave submenus. +Shift + right-click opens Quickshell's native menu as a compatibility fallback. + +Read-only diagnostics and opening a known item's menu: + +```sh +quickshell ipc --path ./quickshell call tray status +quickshell ipc --path ./quickshell call tray open ITEM_ID "" +quickshell ipc --path ./quickshell call tray close +quickshell ipc --path ./quickshell call shell openSettings tray +``` + +No custom application menus are fabricated. Traditional XEmbed-only tray icons are +not bridged. If an application exports no DBusMenu, hover shows its title. +The Phase 2 migration adds the tray to Phase 1 layouts while preserving existing +module positions, order, disabled states, pinned apps and unknown preferences. + +## Dock interactions and diagnostics + +Click to launch/focus; multiple windows open a chooser. Right-click for actual app +actions, windows, pinning and closing. Drag pinned icons to reorder. The cog → Dock +opens all dock settings, including a visual installed-app picker. + +```sh +quickshell ipc --path ./quickshell call shell openSettings dock +quickshell ipc --path ./quickshell call dock status +``` + +Schema 3 preserves existing pins/settings and adds dock defaults. See +[Phase 3](docs/phase-3.md) for changed files, validation, window matching overrides, +terminal launch configuration and known limitations. + +## Launcher and commands + +Run `./scripts/glassmxrph launcher` to toggle the running shell's launcher. +Search applications, use Up/Down and Enter, or type `>` for Settings commands such +as `>dock`, `>appearance`, `>wallpaper` and `>media`. Escape/outside click closes. +Other future destinations remain explicitly labelled until their phases are implemented. All destinations are also in Settings' page selector. + +[Phase 4](docs/phase-4.md) lists changed files, tests and the Super+D / Super+Space +IPC binding snippets. Bindings are documented only; your existing configuration +has not been changed. Recent-file indexing is deferred. + +See [Phase 5](docs/phase-5.md) for the settings workflow, wallpaper adapters, +validation and integration limitations. Existing Nix packaging still needs the +new Python runtime dependency wired in during the deferred packaging phase. + +## Music and media + +One native MPRIS service is shared by Settings, the Control Center, the Music desktop +widget and the optional `nowPlaying` bar module. Settings → Media controls artwork, +progress, album, player preference and Cava. Settings → Bar can add Now Playing +without replacing your saved layout. Cava is optional and off by default. + +See [Phase 6](docs/phase-6.md) for testing, player selection rules and current limits. + +## Control Center + +Click the right-hand system pill or run `./scripts/glassmxrph controlcenter`. +Control Center opens at the active monitor's upper-right, with configurable modules +for connectivity, audio/microphone, brightness, Night Light, DND, power profiles, +shared media and power actions. Settings → Control Center enables/reorders modules. +Logout, reboot and shutdown require explicit confirmation. + +NetworkManager, BlueZ and PipeWire use native Quickshell models. Other controls reuse +installed services and show unavailable states when the provider is absent. This +phase does not start daemons or install keybinds. See [Phase 7](docs/phase-7.md) for +the Super+X IPC binding, dependencies, provider contracts and exact test limits. + +## System metrics + +One collector is shared by Settings, optional bar pills, the Control Center and the +usage desktop widgets. Settings → System Metrics controls sampling, GPU, network +interface and storage paths. Unsupported sensors show `—`. +The collector stops when no metrics view needs it. See [Phase 8](docs/phase-8.md) +for supported providers, limitations, changed files and testing. + +## Diagnostics and final polish + +Run `./scripts/glassmxrph doctor` for read-only environment diagnostics. Appearance +controls reduced motion, neutral glass highlights and animation intensity. Optional +HyprGlass controls, the native wallpaper picker and drag-and-drop bar editor are +documented in [customization](docs/customization.md). Global glass settings apply +only after opting in; saved choices then reapply on shell startup/compositor reload. Nix packaging, host keybinds and autostart remain +separate integration work. See that guide for validation and outstanding host tests. diff --git a/dependencies.json b/dependencies.json new file mode 100644 index 0000000..736aa92 --- /dev/null +++ b/dependencies.json @@ -0,0 +1,51 @@ +{ + "schemaVersion": 1, + "tested": { + "quickshell": "0.3.1", + "hyprland": "0.56.2", + "matugen": "4.2.0", + "cava": "1.0.0" + }, + "required": [ + "quickshell", + "Hyprland", + "QtQuick (Qt 6.8+)", + "QtQuick.Controls", + "QtQuick.Layouts", + "Python 3 (wallpaper adapters, palette generation, system controls and shared metrics)", + "Quickshell.Networking (NetworkManager backend)", + "Quickshell.Bluetooth", + "Quickshell.Services.Pipewire" + ], + "optional": { + "matugen": "4.2.x: verified isolated wallpaper palette generation", + "hyprglass": "Compositor refraction; never required", + "cava": "System-audio visualizer; starts only for playing media with visible enabled views", + "NetworkManager": "Native network state, Wi-Fi power and connections", + "BlueZ": "Native Bluetooth adapters and paired-device connections", + "PipeWire/WirePlumber": "Native audio state, volume, mute and device selection", + "busctl + logind": "Power capabilities and confirmed system power actions", + "power-profiles-daemon": "Power profile enumeration and selection", + "brightnessctl": "Existing backlight devices; custom providers can handle external displays", + "wl-gammarelay": "Reuse an already running gamma service for Night Light", + "nm-connection-editor": "Advanced network/VPN/enterprise settings", + "blueman-manager": "Existing Bluetooth pairing/PIN UI", + "SwayNC + busctl": "DND through non-activating calls to the existing daemon", + "grim": "Lock screen screenshot backdrop only (lock.backdrop = screenshot)", + "easyeffects": "Dashboard Media tab equalizer only; writes the glassmxrph_eq output preset and starts EasyEffects in service mode on apply", + "wttr.in (network)": "Weather desktop widget only; fetched every 30 minutes while a weather widget exists", + "Nerd Font": "Icon glyphs in Settings (any installed Nerd Font, e.g. Symbols Nerd Font); letters are used otherwise", + "nvidia-smi": "Read-only NVIDIA GPU telemetry through the host driver tool; other metrics do not require it" + }, + "development": [ + "qmllint", + "qsb from Qt Shader Tools (only to rebuild lock/shaders/*.qsb: scripts/build-shaders)", + "node (configuration, dock and launcher logic tests)", + "QtTest (tray, dock, launcher, settings, media and Control Center input tests only)", + "Python 3 with dbus-python and PyGObject (isolated tray and MPRIS fixtures)", + "dbus-run-session" + ], + "compatibilityPatches": [ + "packaging/patches/quickshell-0.3.1-sni-unregister.patch" + ] +} diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..254e486 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,134 @@ +# Architecture + +`shell.qml` composes modules and exposes IPC; it contains no feature layout. +Directory singletons use explicit `qmldir` registration. + +- `services/ConfigService.qml`: XDG persistence, defaults and validation. +- `services/ConfigLogic.js`: pure merge/validation/update functions, tested separately. +- `theme/ThemeManager.qml`: resolves custom, Qt system and Matugen accent sources. +- `theme/Theme.qml`: semantic color, shape and motion tokens. Literal theme colors live here. +- `theme/MatugenService.qml`: watches validated JSON; retains the last valid palette. +- `core/ShellState.qml`: settings routing and active-monitor selection. +- `core/ModuleRegistry.qml`: allowlisted bar component URLs; configuration cannot load arbitrary QML. +- `components/`: reusable glass primitives. +- `bar/`: ordered modules, assigned through configuration to left/center/right. +- `settings/`: appearance, tray, dock and about pages. + +Phase 1 directly consumes the single native Hyprland model: no subprocess polling. +Later services encapsulate media, applications, networking and metrics for all views. +Desktop widgets are user-placed (`widgets/`); none are shown by default. Dock defaults to bottom. + +Unknown configuration keys survive saves. Arrays preserve user order rather than +index-merging defaults. Future schema migrations must be explicit, tested and must +not silently replace pinned apps or configured module arrays. Unknown future schema +versions are rejected without overwriting the file. + +Distribution boundaries: QML contains no package manager, host name, monitor name, +or machine path. Packaging lives under `packaging/`; ZaneyOS selection belongs in +the user's external repository. Optional capabilities must degrade visibly and safely. + +Future palette generation: wallpaper event → debounced Matugen job → validate staging +JSON → atomic promotion → FileView reload → ThemeManager. One global palette follows +a configured monitor. Job generations prevent stale jobs replacing newer requests. +Current music artwork must never change the global accent. + +## Phase 2 tray + +`TrayService` owns the one native `SystemTray` model, active icon/menu, hover dismissal +and popup registry. `TrayModule` renders only registered SNI items on each bar. +`TrayMenus` owns one root popup and a Hyprland focus grab for outside dismissal. +Each submenu uses a lazily instantiated `QsMenuOpener` and an anchored popup; dormant +menus do not retain openers or animation timers. Compositor constraints flip/slide +popups at screen edges. The menu stack is closed when its tray delegate disappears +or Settings opens. Tray clicks never call the system-area action. + +`GlassMenu` and `GlassMenuItem` are shared presentation components. `TrayMenuItem` +adapts real `QsMenuEntry` state; triggering calls the entry's actual `triggered()` +signal. The app remains authoritative for checked state. Empty/asynchronous menus +show status text, not made-up application actions. + +The optional `GLASSMXRPH_TESTING=1` driver imports QtTest for event simulation on +fixture icons. It is unloaded in normal operation; QtTest is not a runtime dependency. +The fixture runs in a private DBus session and never activates real user applications. + +## Phase 3 dock + +`ApplicationsService` owns the shared native desktop-entry catalog and launches. +`HyprlandService` adapts the one native toplevel model; focus/close use Wayland +handles with validated Hyprland address dispatch as fallback. +`AppMatching.js` and `DockGeometry.js` contain independently tested pure logic. +`DockModel` groups windows and saved pins; keyed ScriptModel delegates preserve +icon identity when focus or geometry changes. `DockState` owns the single chooser/ +context popup and coordinates exclusivity with tray menus and Settings. + +`ScreenService` resolves configured outputs in logical per-screen coordinates. +`Dock` manages placement, edge input and hide transitions. Intelligent mode alone +enables a shared 500 ms native geometry refresh; there is no subprocess polling. +`DockItem` handles pointer interactions, neighbour magnification and indicators. +`DockContextMenu` and `WindowChooser` use the shared glass menu presentation. + +Config schema 3 adds defaults without replacing saved pins, module arrays or +unknown keys. Invalid object/array types are rejected instead of reset silently. +QtTest is loaded only with `GLASSMXRPH_DOCK_TESTING=1`. The disposable fixture +uses Quickshell's [AppId pragma](https://quickshell.org/docs/v0.3.0/guide/advanced/) +and [FloatingWindow API](https://quickshell.org/docs/v0.3.1/types/Quickshell/FloatingWindow/). + +## Phase 4 launcher + +`Launcher` owns only presentation, input and selection. `AppSearch` consumes the +existing shared ApplicationsService; `CommandSearch` consumes CommandRegistry. +Both use pure SearchLogic scoring over pre-normalized catalog fields. Result work +stops while the launcher is closed; no subprocess or duplicate application scan +is introduced. Launches go through ApplicationsService. + +`SettingsRegistry` defines canonical page IDs, command aliases, labels and phase +availability. Settings and CommandRegistry share it, so palette destinations are +also reachable normally. Code-owned command extensions may register callbacks; +query text is never shell-evaluated. Future pages are explicitly labelled. + +`LauncherState` supplies IPC and owns the window reference. ShellState coordinates +opening/closing and captures ScreenService's active output. ScreenService consumes +native monitor-focus events eagerly; no focus polling is needed. Dock/tray popups +and Settings are dismissed when opening the launcher. Appearance and search +preferences are shared ConfigService/Theme values. Width and delayed height +animations form the opening search pill and respect reduced motion. + +## Phase 5 providers + +WallpaperService owns discovery, gallery and wallpaper changes. MatugenService observes the selected palette output and serializes generation through ProviderJob, discarding stale results. A short-lived Python helper handles filesystem/provider operations and generated palette files. Settings controls share ConfigService and Theme; Media preferences are ready for the next phase. + +## Phase 6 media + +`MediaService` is the sole owner of the native MPRIS model, player selection, guarded +actions and a shared 500 ms position sampler. It reads Quickshell's locally extrapolated +position; it does not poll DBus or spawn playerctl. Sampling stops without visible progress +consumers or when paused. `MediaCard` is shared by Settings and +`controlcenter/modules/Media.qml`; Now Playing uses the same service. + +`CavaService` runs one optional process for all visualizer consumers. The bundled raw +configuration leaves audio input selection to Cava, emits 24 bars at 30 fps, and never +alters the user's Cava configuration. Its Python launcher execs Cava in place and reports +missing executables. Playback pause, hidden views or disabling Cava stop the process; +failures do not cause restart loops. Song artwork never changes the global accent. + +## Phase 7 system controls + +`ControlCenter` is an active-monitor overlay with a registry-driven module layout. +`ShellState` coordinates its visibility with existing shell popups. `AudioService`, +`NetworkService` and `BluetoothService` adapt native Quickshell event-driven models. +`SystemService` serializes one-shot JSON provider jobs for visible display/DND/power +controls, polling every five seconds only while needed. `PowerService` owns pending +confirmation; it exposes no direct destructive IPC action. The helper also enforces +confirmation before logout/reboot/shutdown and uses argv arrays with timeouts. + +The same modules are reused by detailed Settings pages. Wi-Fi credentials pass to +NetworkManager's native API, not subprocess arguments or shell preferences. BlueZ +pairing uses the existing manager. No notification or pairing daemon is registered. + +## Phase 8 telemetry + +MetricsService owns a single demand-driven streaming Python collector. MetricsCard, bar MetricsModule and Settings share its snapshot; no UI component polls sensors. The collector owns monotonic CPU/network deltas and rate-limited GPU/storage reads. A bounded CPU history is kept by the service; missing and stale values remain explicit. See [Phase 8](phase-8.md). + +## Phase 9 polish + +Theme owns contrast selection and reduced-motion intensity. Shared glass components add inexpensive highlights and reversible motion without per-panel blur effects. ScreenService validates captured output references. MetricsService owns bounded restart backoff. The optional compositor example and read-only doctor keep host integration separate from UI state. See [Phase 9](phase-9.md). diff --git a/docs/compatibility.md b/docs/compatibility.md new file mode 100644 index 0000000..147accf --- /dev/null +++ b/docs/compatibility.md @@ -0,0 +1,87 @@ +# Compatibility and dependencies + +Tested base: Quickshell 0.3.1 (Qt APIs verified from installed qmltypes), +Hyprland 0.56.2, Linux x86_64, Wayland. See `dependencies.json` and `flake.lock`. + +Supported target: Linux distributions able to supply compatible dependencies. +The suite is Hyprland-specific; portability is across distributions, not compositors. +Nix is optional. Home Manager and ZaneyOS are not runtime dependencies. + +QtQuick software surfaces provide transparency, borders, highlights and shadows. +Real background blur and refraction require compositor support. Without configured +blur rules, Phase 1 is translucent glass without backdrop blur. This is intentional: +the preview must not modify the compositor. HyprGlass is neither bundled nor enabled. +Its binary must match the host compositor ABI; never copy a plugin between versions. + +Matugen 4.2.0 is the verified generator. Its CLI supports scheme types and contrast +-1..1. The current settings integration executes it asynchronously. System accent comes from Qt's SystemPalette and +may be a Qt fallback on desktops without a configured palette provider. + +Integrated providers include: PipeWire/WirePlumber, NetworkManager, BlueZ, MPRIS, SwayNC or a +validated notification adapter, UPower/logind. Existing daemons remain owners; +missing providers disable associated controls instead of starting duplicate services. +External-display brightness is hardware-dependent (DDC/CI), not guaranteed by +brightnessctl. Night Light requires a separately verified provider. + +Nix pins the user-space package closure; it cannot pin another distro's kernel, +graphics driver, active compositor or session services. Native package-manager installs +are reproducible only to the extent their dependency versions are pinned externally. + +## Quickshell 0.3.1 tray compatibility fix + +The upstream watcher removes every object of an exiting service internally, but +emits `StatusNotifierItemUnregistered` only for the last object. This leaves stale +icons for applications exporting multiple SNI objects on one connection. Its prefix +comparison can also match a different service name. The project-scoped patch emits +one signal per removed object and requires the service/path separator when matching. + +- Source: [Quickshell v0.3.1 watcher.cpp](https://github.com/quickshell-mirror/quickshell/blob/v0.3.1/src/services/status_notifier/watcher.cpp) +- Patch: `packaging/patches/quickshell-0.3.1-sni-unregister.patch` +- Nix applies it to the project Quickshell only, with an explicit 0.3.1 version guard. +- Native distro builds can apply the same patch to Quickshell 0.3.1 source with + `patch -p1 < /path/to/glassMxrph/packaging/patches/quickshell-0.3.1-sni-unregister.patch`, + then use their normal Quickshell build/package workflow. +- When another shell owns the session's StatusNotifierWatcher, that watcher's + correctness also matters. Testing glassMxrph beside an unpatched watcher cannot + repair that other process. The isolated regression test makes glassMxrph own + its test watcher. Normal standalone operation uses the patched watcher. + +No system package, compositor, daemon, notification owner or shell service is changed. +AppIndicator implementations exporting SNI/DBusMenu work through the same APIs. +XEmbed-only applications need an external bridge, which is not installed by this suite. +An application exiting during a pending DBus call can still produce a transient +upstream transport diagnostic; no action is retried and the UI must discard the item. + +## Phase 5 + +Python 3 is required for wallpaper/palette helpers. Matugen 4.2.0 and the 4.2.x CLI contract are verified. Wallpaper adapters target Serpantinum 2.2.0 and awww 0.12.1, with a configurable argv fallback. See [Phase 5](phase-5.md) for provider testing limits. Nix packaging integration is deferred. + +## Phase 6 MPRIS and Cava + +MPRIS properties/methods and position-in-seconds semantics were checked against the +installed Quickshell 0.3.1 qmltypes and source. The Margins value type is incompletely +resolved by qmllint in that version; a narrow annotation covers the verified runtime +grouped property. Cava 1.0.0 raw ASCII output was tested with the existing audio server. +Cava input support depends on the distribution build. No audio daemon is installed. + +## Phase 7 + +The installed 0.3.1 build includes `Quickshell.Networking`, `Quickshell.Bluetooth` +and `Quickshell.Services.Pipewire`; native distribution builds must include them. +Command-backed controls require their listed providers and degrade when unavailable. +Power profiles use the verified `net.hadess.PowerProfiles` compatibility interface; +Night Light uses the running `rs.wl-gammarelay` service. No compositor configuration +is modified. The runner can derive an unset TZDIR from `/etc/localtime` to support +nonstandard timezone database locations. See [Phase 7](phase-7.md) for exact limits. + +## Phase 8 metrics + +Linux procfs/sysfs and Python 3 provide baseline telemetry; optional nvidia-smi comes from the host driver. AMD DRM/hwmon is read directly. Driver-specific unavailable fields are explicit; privileged Intel tracing and CPU package power are not implemented. Use local storage paths only. No Nix packaging or system changes were made. See [Phase 8](phase-8.md). + +## Phase 9 + +Artwork retention requires Qt 6.8+ (`Image.retainWhileLoading`), verified in the +installed Qt QML metadata. The host's HyprGlass revision supports alpha-masked layers, +but its layer effects are currently disabled. The example is unapplied; advanced +effects and distribution portability need host validation. `scripts/glassmxrph doctor` +provides read-only dependency/session diagnostics. See [Phase 9](phase-9.md). diff --git a/docs/customization.md b/docs/customization.md new file mode 100644 index 0000000..a292b8d --- /dev/null +++ b/docs/customization.md @@ -0,0 +1,54 @@ +# Desktop customization + +All implementation lives in glassMxrph. Host Nix configuration, existing bindings and autostart are separate integration work. + +## Bar editor + +Open Settings → Bar. Drag a module by its grip to reorder it or move it between Left, Center and Right, including empty lanes. Changes persist on drop. Toggle cards to disable modules; use the available-module buttons to add them. + +Keyboard alternative: focus a grip, use Ctrl+Up/Down to reorder or Alt+Left/Right to change lanes. Escape cancels a drag. + +## Native wallpaper picker + +Open Settings → Wallpaper → Open wallpaper picker, or run: + +```sh +./scripts/glassmxrph wallpaper +``` + +The centered carousel follows the current Super+Shift+W picker's visual concept and runs entirely inside glassMxrph. Search local images, select an output, browse with arrow keys and apply with Enter or double-click. History records the last 50 selections. Escape or an outside click closes it. + +Configure image directories in Wallpaper settings; the default search directory is ~/Pictures/Wallpapers. Select the Native backend when replacing Serpantinum. New configurations default to Native; existing explicit backend preferences are preserved. + +Native wallpapers use one background layer per configured output and need no external wallpaper daemon. Images are decoded before committing the selection. The existing shared wallpaper/Matugen pipeline regenerates enabled automatic palettes and updates the theme live. Wallpapers last while glassMxrph runs. Existing wallpaper services are not stopped automatically; decommission them during host integration. + +This picker currently supports local still images, search and history. Serpantinum's online downloads, video wallpapers and additional filters are not included. Existing Super+Shift+W remains untouched until host integration. + +## Global HyprGlass controls + +In Settings → Appearance, choose **Match Ghostty’s liquid glass**, then **Apply to desktop and apps**. The matching profile uses the inspected Ghostty liquid preset: blur 0.45, two iterations, refraction 3, chromatic aberration 0.45, Fresnel 0.5, specular 0.8, rim 0.065, lens distortion 0.25 and its dark color adjustments. Shell surface opacity becomes 0.3. + +The global effect toggle and layer toggle control ordinary application windows and shell layers. Sliders save draft values; Apply changes the loaded plugin. Explicit app presets and existing layer mappings/exclusions retain priority, so those surfaces may override global values. + +After Apply, ownership is saved and the chosen settings reapply on shell startup and Hyprland configuration reload. **Restore previous glass** restores captured values that have not subsequently been changed externally and disables automatic reapplication. Stopping the shell alone does not restore compositor preferences. + +The implementation requires a loaded compatible HyprGlass plugin and hyprctl. It is verified against revision [77636c5711ed572ca199a84d06146ccac0951786](https://github.com/hyprnux/hyprglass/tree/77636c5711ed572ca199a84d06146ccac0951786). No plugin is installed or loaded by the shell. Without it, neutral QML glass remains usable. + +This revision commits custom preset declarations and namespace mappings only on configuration reload. Live controls therefore use verified scalar options with the default fallback preset, preparing values before activating them. They do not pretend to update cached preset declarations. Blur resampling may wait for background changes. Avoid conflicting per-layer preset mappings from the older Phase 9 example when expecting global sliders to control those layers. + +Apply checks option readback and rolls back failed writes. A session-scoped restore journal lives under XDG_STATE_HOME/glassMxrph. No Nix or Hyprland files are rewritten. + +## Validation and changed areas + +- Bar: settings/controls/BarEditor.qml, settings/pages/Bar.qml and services/SettingsLogic.js. +- Wallpapers: wallpaper/WallpaperPicker.qml, wallpaper/WallpaperBackground.qml, WallpaperService, desktop helper, shell state/entry point, settings page and runner IPC. +- Glass: helpers/glass.py, services/GlassService.qml, controls/GlassSettings.qml and Appearance. +- Shared configuration defaults/validation, slider precision and test drivers were updated. + +Run scripts/validate with installed Quickshell QML imports available. tests/customization_runtime.py exercises real drag input, picker search/apply/history and native background creation, plus global Apply/update/off/Restore against a recording compositor adapter. tests/settings_runtime.py checks settings and real Matugen generation. Both use disposable preferences and stop their preview. + +A separate live check against the loaded HyprGlass plugin successfully applied the matching global profile, checked readback and restored every controlled option to its original value. + +## Tray menu refraction + +Tray hover/context menus and nested submenus use small overlay layer windows with the glassMxrph-tray namespace. This lets the installed HyprGlass layer renderer process them; ordinary xdg popup windows bypass that renderer. They inherit the global layer glass settings. If you maintain a namespace whitelist, include glassMxrph-tray and avoid a conflicting preset mapping. The supplied optional example includes it. Native application fallback menus (Shift+right-click) remain application-owned. diff --git a/docs/phase-2.md b/docs/phase-2.md new file mode 100644 index 0000000..79452dd --- /dev/null +++ b/docs/phase-2.md @@ -0,0 +1,63 @@ +# Phase 2 — real system tray + +Completed and validated on Linux x86_64 / Hyprland 0.56.2 with Quickshell 0.3.1 +plus the project-scoped SNI lifecycle fix. Other distributions remain untested. + +## New files + +- `.gitattributes` (preserve unified-patch context whitespace) + +- `quickshell/services/TrayService.qml` +- `quickshell/bar/modules/TrayModule.qml` +- `quickshell/menus/TrayIcon.qml` +- `quickshell/menus/TrayMenus.qml` +- `quickshell/menus/TrayMenu.qml` +- `quickshell/menus/TrayMenuItem.qml` +- `quickshell/menus/TraySubMenu.qml` +- `quickshell/settings/pages/Tray.qml` +- `quickshell/testing/TrayDriver.qml` (opt-in test driver) +- `tests/tray_fixture.py` +- `tests/tray_runtime.py` +- `packaging/nix/quickshell.nix` +- `packaging/patches/quickshell-0.3.1-sni-unregister.patch` +- `docs/phase-2.md` + +## Updated files + +- `quickshell/shell.qml`: menu composition and optional test driver. +- `quickshell/core/ModuleRegistry.qml`: tray registration. +- `quickshell/services/qmldir`: shared tray singleton. +- `quickshell/services/ConfigLogic.js`, `quickshell/config/defaults.json`: schema 2 migration and validated tray preferences. +- `quickshell/components/GlassMenu.qml`, `quickshell/components/GlassMenuItem.qml`: shared menu presentation and accessible state. +- `quickshell/settings/Settings.qml`: normal navigation and tray deep link. +- `tests/config.test.cjs`: preservation and migration regression tests. +- `flake.nix`, `packaging/nix/package.nix`: patched runtime, test dependencies and version 0.2.0. +- `README.md`, `dependencies.json`, `docs/architecture.md`, `docs/compatibility.md`, `docs/validation.md`: usage, dependencies and test evidence. + +## Verification + +Passed: configuration tests, QML lint, foundation runtime regression, isolated +SNI/DBusMenu integration, per-monitor menu placement, and locked package build. +The documented `nix develop` environment passed lint and the isolated tray tests +without ad hoc dependency paths. Test menus include two nested submenu levels, +checked/unchecked radio and checkbox states, disabled/hidden entries, icons, +separators, and service exit while a menu is open. + +Read-only testing against the live desktop discovered NetworkManager, Blueman +and OpenDeck; NetworkManager's exported menu rendered correctly. No application +actions were triggered against real providers. No system configuration, services +or keybinds changed. Temporary shell instances were stopped after testing. + +## Try it + +From the project directory, use `nix run .` for the compatibility-patched package. +Hover a tray icon for 400 ms, right-click for an immediate menu, and use the cog +→ Bar / Tray to change preferences. Escape closes a menu. Shift + right-click +requests the native menu fallback. Stop the preview with Ctrl+C. + +For source development use `nix develop`, then `./scripts/glassmxrph run`. +See validation.md for the exact automated commands and remaining manual checks. +The preview can overlap the existing shell; it does not replace or stop it. + +Remaining manual coverage includes physical outside-click routing, native fallback, +hotplug/fractional scaling and other distributions. Phase 3 (dock) is not included. diff --git a/docs/phase-3.md b/docs/phase-3.md new file mode 100644 index 0000000..6f37ddb --- /dev/null +++ b/docs/phase-3.md @@ -0,0 +1,126 @@ +# Phase 3 — configurable dock + +Implemented and tested from source on Quickshell 0.3.1 (existing Phase 2 SNI +compatibility patch), Qt 6 and Hyprland 0.56.2. No Nix files, system configuration, +autostart entries, keybinds, services or installed packages were changed. + +## Behaviour + +One floating dock defaults to the bottom of the primary output. No applications +are hardcoded or pinned automatically. Running applications appear dynamically; +Settings → Dock provides an installed-app picker and saved pin order. + +- Closed pinned entry: click launches its native desktop entry. +- One running window: click focuses it. +- Multiple windows: click opens a glass window chooser. Arrow keys / Enter work; + Escape or an outside click dismisses the popup. +- Right-click: Open, individual windows, actual desktop-entry actions, Pin/Unpin, + and Close for each window. New Window appears only when advertised by the app. +- Drag a pinned icon onto another pinned icon to reorder; settings also has arrows. +- Running and focused indicators, neighbour magnification, press feedback and tooltips. +- Dynamic width with scrolling for overflow; configurable icon size, spacing, + margin, motion speed, monitor, edge and visibility. Reduced motion is respected. +- Always visible, Auto Hide and Intelligent Hide. Hidden input is restricted to a + 3 px edge strip; menus and pointer interaction hold the dock open. + +Bottom is the default. Left/right are opt-in positions of the same dock, not +additional side docks. No screen coordinates or application IDs are host-specific. + +## Files + +New: + +- `quickshell/services/ApplicationsService.qml`, `AppMatching.js`, `HyprlandService.qml` +- `quickshell/core/ScreenService.qml` +- `quickshell/dock/Dock.qml`, `DockItem.qml`, `DockModel.qml`, `DockState.qml`, + `DockContextMenu.qml`, `WindowChooser.qml`, `DockGeometry.js`, `qmldir` +- `quickshell/settings/pages/Dock.qml` +- `quickshell/testing/DockDriver.qml` (opt-in QtTest driver) +- `tests/dock.test.cjs`, `tests/dock_runtime.py`, `tests/dock-fixture/shell.qml` +- `docs/phase-3.md` + +Updated: + +- `quickshell/shell.qml`: dock composition and opt-in test driver. +- `quickshell/services/qmldir`, `quickshell/core/qmldir`: shared service registration. +- `quickshell/services/ConfigLogic.js`, `quickshell/config/defaults.json`: schema 3, + validated dock preferences, migration preserving old settings and unknown keys. +- `quickshell/settings/Settings.qml`: Dock navigation, lazy page loading, About. +- `tests/config.test.cjs`, `scripts/validate`: migration and dock logic checks. +- `README.md`, `dependencies.json`, `docs/architecture.md`, `docs/validation.md`. + +## Matching and platform limits + +Matching uses desktop IDs, then unique StartupWMClass values, with explicit +`dock.appOverrides` taking precedence. Ambiguous matches remain separate running +entries instead of focusing a guessed app. Browser web apps, Wine and unusual +XWayland classes may require an override, for example: + +```json +{"dock":{"appOverrides":{"actual-window-class":"installed-entry.desktop"}}} +``` + +Unknown running entries can be focused/closed, but cannot be pinned until matched. +Missing installed entries remain in the pinned list and can be removed there. + +Desktop launches use Quickshell's native DesktopEntry/DesktopAction execution. +Its 0.3.1 API is not a full desktop portal/DBus activation implementation, and does +not expand every desktop Exec field code. Terminal=true apps require a configured +`dock.terminalCommand` argument array, including the terminal's execute flag. +Settings exposes this array; no terminal executable is guessed or installed. + +Hyprland has no universal primary-output flag: `primary` resolves to the output at +logical (0,0), or the first available output. Selecting an explicit output is best +for other arrangements; a disconnected selection falls back to primary. + +Intelligent hide samples native Hyprland geometry every 500 ms only while enabled. +It considers visible workspaces and windows on the dock's own output. It detects +rectangle overlap/fullscreen, not pixel occlusion, transparent regions or rounded +corners. Normal window matching is event-driven. No `hyprctl` subprocess polling. + +## Validation + +Passed QML lint, config migration/preservation tests, matching/ambiguity/grouping +and geometry tests, foundation runtime regression, private-DBus tray regression, +and live dock tests. Runtime logs were free of QML warnings and DBus errors. + +The dock test launches temporary fixture windows and desktop entries. It verifies +native desktop/action execution, actual pointer drag reorder and persisted order, +window matching/focus/chooser/close, Escape, settings loading, auto hide/edge reveal, +fullscreen overlap, restoration to the existing-window baseline, both available +outputs and all supported edges, enable/disable, and menu-based unpinning. +It never closes or launches real user applications. Geometry logic additionally +checks off-output and inactive-workspace exclusion. The glass dock was inspected +from a rendered capture. Nix builds were deliberately deferred as requested. + +Still requiring manual acceptance: physical pointer routing to the hidden edge, +long overflowing docks and drag during scrolling, compositor outside-click routing, +monitor hotplug, fractional scaling, app-specific launch behaviour, and other distros. +Synthetic input does not prove physical Wayland input routing. Blur/refraction +still depends on external compositor setup; this phase does not change it. + +## Try it + +From the project root, in your Hyprland session: + +```sh +./scripts/glassmxrph run +quickshell ipc --path ./quickshell call shell openSettings dock +quickshell ipc --path ./quickshell call dock status +``` + +The cog → Dock opens the same settings. Pin two apps, drag to reorder, open two +windows of an app and try the chooser. Test auto/intelligent hide and your selected +monitor. Existing source previews hot-reload; the runner prevents duplicate instances +of the same source path. Use the standalone source runner for this phase. + +Automated checks require matching Qt imports, Node, Python 3 and QtTest: + +```sh +./scripts/validate +python3 tests/dock_runtime.py +``` + +Do not run the runtime test against a path already in use. It refuses to replace +that shell; use an isolated source copy when keeping your normal preview running. +`GLASSMXRPH_DOCK_TESTING=1` loads the input driver only for testing. diff --git a/docs/phase-4.md b/docs/phase-4.md new file mode 100644 index 0000000..f148e54 --- /dev/null +++ b/docs/phase-4.md @@ -0,0 +1,166 @@ +# Phase 4 — launcher and command palette + +Implemented and tested from source on the existing Quickshell 0.3.1 runtime, +Qt 6 and Hyprland 0.56.2. All changes are inside this project. Nix files, +Hyprland configuration, installed packages and existing keybinds are unchanged. + +## Try it + +Start the shell from its project root: + +```sh +./scripts/glassmxrph run +``` + +In another terminal, toggle the running launcher's IPC endpoint: + +```sh +./scripts/glassmxrph launcher +``` + +Or use the endpoint directly: + +```sh +quickshell ipc --path ./quickshell call launcher toggle +quickshell ipc --path ./quickshell call launcher open +quickshell ipc --path ./quickshell call launcher close +quickshell ipc --path ./quickshell call launcher status +``` + +The launcher is centered within the active monitor. Search names, desktop IDs, +generic names, keywords or descriptions. Exact/prefix matches rank above substring +and fuzzy matches; accents and case are normalized. Multiple words must all match. +Only launchable entries appear; NoDisplay entries are excluded. Hover highlights do not override keyboard selection. Results are a +scrollable icon list, backed by the same application service as the dock. + +Up/Down (or Tab/Shift+Tab) select; Enter launches; Escape closes. Left/Right remain +text cursor keys, with Ctrl+Left/Right also navigating results. Clicking a result +launches it; clicking outside dismisses the surface. Search resets when reopened. +Terminal applications use the existing configured terminal argument array; a missing +terminal configuration leaves the launcher open with a visible explanation. +Search text is never executed as a shell command. + +Opening expands a centered search pill horizontally, then grows the results area. +Closing reverses the dimensions. Theme motion duration and reduced motion apply. +Settings → Launcher controls width, result limit and descriptions. Settings is also +reachable from `>launcher`. Recent files remain optional future work: this phase +neither indexes nor displays a user's recent documents. + +## Commands and Settings + +Type `>` to list commands; fuzzy prefixes such as `>wall` are supported. + +| Command | Settings destination | Current status | +| --- | --- | --- | +| `>appearance` | Appearance | Existing accent/glass/motion controls | +| `>wallpaper` | Wallpaper | Labelled future page; Phase 5 picker | +| `>bar` | Bar | Tray controls; full bar editor in Phase 5 | +| `>tray` | Bar / Tray | Existing tray controls | +| `>dock` | Dock | Complete Phase 3 controls | +| `>media` | Media | Labelled future page; media work in Phases 5–6 | +| `>controlcenter` | Control Center | Labelled future page; Phase 7 | +| `>launcher` | Launcher | Search preferences | +| `>display` | Displays | Labelled future page | +| `>audio` | Audio | Labelled future page | +| `>network` | Network | Labelled future page | +| `>bluetooth` | Bluetooth | Labelled future page | +| `>notifications` | Notifications | Labelled future page | +| `>power` | Power | Labelled future page; no power action executes | +| `>about` | About | Project information | + +Every destination is available through the Settings page selector. Later-phase +pages explicitly say their controls are not implemented. Commands do not fabricate +system state or launch substitute external control applications. + +`SettingsRegistry` supplies the shared route metadata. `CommandRegistry` can accept +trusted QML extensions with a unique ID, title, description and `run` function via +`registerCommand()`, and remove them with `unregisterCommand()`. Preferences and +search input cannot inject QML or executable command text. + +## Keybinds — documented, not installed + +Review your existing Super+D and Super+Space bindings first. When ready to integrate, +replace `/absolute/path/to/glassMxrph` below with the clone's real absolute path and +add these through your existing Hyprland/ZaneyOS workflow: + +```ini +bind = SUPER, D, exec, quickshell ipc --path /absolute/path/to/glassMxrph/quickshell call launcher toggle +bind = SUPER, SPACE, exec, quickshell ipc --path /absolute/path/to/glassMxrph/quickshell call launcher toggle +``` + +Quote a path containing spaces. These commands only contact the running shell; +they do not start another Quickshell instance. The source runner remains the launch +entry point until Nix/autostart integration is handled later. No existing bind was +removed or replaced in this phase. Super+X belongs to the later Control Center phase. + +## Files + +New: + +- `quickshell/launcher/Launcher.qml`, `LauncherState.qml`, `AppSearch.qml`, + `CommandSearch.qml`, `CommandRegistry.qml`, `SearchLogic.js`, `qmldir` +- `quickshell/core/SettingsRegistry.qml` +- `quickshell/settings/pages/Launcher.qml` +- `quickshell/testing/LauncherDriver.qml` (opt-in QtTest input) +- `tests/launcher.test.cjs`, `tests/launcher_runtime.py` +- `docs/phase-4.md` + +Updated: + +- `quickshell/shell.qml`: composition, optional driver and routing diagnostics. +- `quickshell/core/ShellState.qml`, `ScreenService.qml`, `qmldir`: active-output + state, launcher/settings exclusivity and registered settings routes. +- `quickshell/services/TrayService.qml`, `quickshell/dock/DockState.qml`: popup coordination. +- `quickshell/config/defaults.json`, `quickshell/services/ConfigLogic.js`: additive, + validated launcher defaults under schema 3; existing pins/options remain intact. +- `quickshell/settings/Settings.qml`: page selector, launcher controls and future destinations. +- `scripts/glassmxrph`, `scripts/validate`: IPC toggle and search tests. +- `tests/config.test.cjs`, `tests/dock_runtime.py`, `tests/tray_runtime.py`: preservation + and popup-coordination regressions. +- `README.md`, `dependencies.json`, `docs/architecture.md`, `docs/validation.md`. + +## API and monitor handling + +The installed DesktopEntry metadata provides name, genericName, comment, keywords, +noDisplay and native execution; the existing shared launch service owns execution. +No second desktop-entry parser, application daemon or background subprocess was added. + +`ScreenService` eagerly tracks active output state using Quickshell's native +[Hyprland rawEvent API](https://quickshell.org/docs/v0.3.1/types/Quickshell.Hyprland/Hyprland/) +and the documented [focusedmon/focusedmonv2 events](https://wiki.hypr.land/IPC/). +This avoids stale cached focus during IPC monitor changes without a polling timer. +The output is captured when opening, so typing does not move the launcher between +monitors. Settings uses the same active-output resolver. No virtual-desktop centering. + +## Validation and limits + +Passed QML lint, search ranking and configuration tests, plus live launcher, +foundation, dock and private-DBus tray suites. Runtime logs contained no QML warnings +or DBus errors. The launcher was visually inspected from a rendered capture. + +The launcher test verifies centering on both available outputs, real keyboard/text +and pointer input, stationary-pointer keyboard selection during animation, fuzzy/keyword matching, hidden-entry exclusion, actual execution +of temporary desktop entries, visible terminal errors, all 15 command destinations, +extension registration/removal, Escape/outside dismissal, reduced motion and rapid +toggles. Dock/tray suites verify the launcher dismisses their menus. Existing +configuration persistence, palette reload and duplicate prevention still pass. + +```sh +./scripts/validate +python3 tests/launcher_runtime.py +python3 tests/dock_runtime.py +dbus-run-session -- python3 tests/tray_runtime.py +python3 tests/runtime.py +``` + +Use matching installed QML imports and the existing patched runtime for the tray +suite. QtTest is a development dependency only; the launcher driver loads solely +with `GLASSMXRPH_LAUNCHER_TESTING=1`. Tests refuse to run against a source path already +in use. Use a separate source copy if retaining a running preview. Run graphical +suites sequentially. The launcher test temporarily focuses each output and restores +the original output; it launches only temporary helper entries, not real apps. + +Remaining manual acceptance: physical keybind routing once integrated, compositor +pointer behaviour, fractional scaling, hotplug, input methods, app-specific desktop +entry field-code limitations inherited from Quickshell, and other distributions. +Nix builds/integration remain deferred. No recent-files provider is implemented. diff --git a/docs/phase-5.md b/docs/phase-5.md new file mode 100644 index 0000000..03ad810 --- /dev/null +++ b/docs/phase-5.md @@ -0,0 +1,94 @@ +# Phase 5 — Settings and theming + +Implemented native settings pages for Appearance, Wallpaper, Bar, Dock and Media preferences. Shared themed inputs, an HSV/hex colour picker, neutral panel controls, reduced motion and animated accent updates replace the earlier minimal settings surface. Bar modules can be enabled, moved between lanes and reordered with buttons; clock format and workspace count are configurable. Dock retains its visual pinned-app editor. + +## Try it + +Run `./scripts/glassmxrph run`, then open the cog or `./scripts/glassmxrph settings`. + +1. Appearance → Custom: pick a colour; adjust opacity, radius or animation settings. +2. Appearance → Matugen: configure a Matugen 4.2.x executable if it is not on PATH, then check it. Choose a supported scheme and contrast. +3. Wallpaper: choose an output, backend and directories, refresh the gallery, select an image and Apply. Choose which output supplies the global palette. +4. Bar: move, reorder or disable modules. Dock: edit pins and presentation. +5. Media: save preferences for the Phase 6 player/widget implementation. + +Settings persist through ConfigService; additive defaults preserve unknown preferences and existing layout/pins. Generated colours are written atomically to `$XDG_STATE_HOME/glassMxrph/palette.json`. Errors retain the last good palette; stale asynchronous results are discarded. All UI consumes the shared Theme, while glass surfaces remain neutral. + +## Providers and limits + +Python 3 is a runtime dependency for one-shot JSON helpers. Matugen 4.2.x is the verified CLI/template contract; unsupported versions produce an explicit error. Generation uses a temporary dedicated configuration and generated JSON file, without reading user Matugen hooks. No persistent helper daemon is installed. + +Wallpaper adapters support an existing Serpantinum instance, an existing awww daemon, or a custom argument array using `{path}` and `{monitor}` placeholders. Auto detection prefers Serpantinum. Custom commands are executed as argument arrays, never shell strings. No wallpaper daemon is started. Serpantinum receives a cached, safely named copy because its upstream implementation interpolates paths; Serpantinum may still execute its own wallpaper/theme hooks. Those external hooks are outside this shell's control. + +Gallery scanning is nonrecursive, capped at 1,000 images, and supports PNG, JPEG, WebP and BMP. Images use asynchronous, bounded-size thumbnails. External wallpaper changes require Refresh or an integration hook: + +```sh +quickshell ipc --path ./quickshell call wallpaper changed OUTPUT /absolute/image.jpg +quickshell ipc --path ./quickshell call theme regenerate +quickshell ipc --path ./quickshell call theme status +``` + +There is no continuous filesystem/provider polling. One selected output supplies the global palette. Media preferences are implemented; MPRIS playback, player discovery and Cava remain Phase 6. Bar reordering uses buttons, not drag-and-drop. Blur/refraction remain compositor-owned; this phase does not modify HyprGlass, Hyprland or Nix configuration. Packaging integration, including Python's runtime closure, is deferred. + +## Validation + +QML validation and configuration, dock, launcher and provider unit tests pass. Real Wayland tests cover foundation persistence/live palette reload/corrupt-file protection, launcher, dock and StatusNotifier/DBusMenu regressions. Settings tests exercise the colour picker, gallery selection, recording-backend apply, real Matugen generation, automatic/manual regeneration, failure recovery, stale in-flight results, bar editing and media preference persistence. Runtime logs are checked for warnings/errors. + +The settings test uses disposable images and isolated XDG paths. It does not change the user's wallpaper. Actual Serpantinum apply and awww rendering were not exercised: Serpantinum discovery was checked read-only, and awww's CLI was inspected while no daemon was running. Matugen 4.2.0 was tested directly. One foundation startup timeout cleared on rerun; the passing run had clean logs. + +```sh +./scripts/validate +# With tested Quickshell and Matugen on PATH; use an isolated clone if already running: +python3 tests/settings_runtime.py +``` + +QtTest is needed only for input-driving tests. See the Phase 2–4 documents for their fixture dependencies. No Nix build or system rebuild was performed. + +## Changed files + +- `README.md` +- `dependencies.json` +- `docs/architecture.md` +- `docs/compatibility.md` +- `docs/phase-5.md` +- `docs/validation.md` +- `quickshell/bar/modules/ClockModule.qml` +- `quickshell/bar/modules/WorkspacesModule.qml` +- `quickshell/components/GlassButton.qml` +- `quickshell/components/GlassColorPicker.qml` +- `quickshell/components/GlassComboBox.qml` +- `quickshell/components/GlassPanel.qml` +- `quickshell/components/GlassPopup.qml` +- `quickshell/components/GlassTextArea.qml` +- `quickshell/components/GlassTextField.qml` +- `quickshell/config/defaults.json` +- `quickshell/core/SettingsRegistry.qml` +- `quickshell/core/ShellState.qml` +- `quickshell/dock/DockItem.qml` +- `quickshell/helpers/desktop.py` +- `quickshell/services/ConfigLogic.js` +- `quickshell/services/ConfigService.qml` +- `quickshell/services/ProviderJob.qml` +- `quickshell/services/SettingsLogic.js` +- `quickshell/services/WallpaperService.qml` +- `quickshell/services/qmldir` +- `quickshell/settings/Settings.qml` +- `quickshell/settings/controls/PreferenceChoice.qml` +- `quickshell/settings/controls/PreferenceSlider.qml` +- `quickshell/settings/controls/PreferenceToggle.qml` +- `quickshell/settings/controls/SettingsPage.qml` +- `quickshell/settings/pages/Appearance.qml` +- `quickshell/settings/pages/Bar.qml` +- `quickshell/settings/pages/Dock.qml` +- `quickshell/settings/pages/Launcher.qml` +- `quickshell/settings/pages/Media.qml` +- `quickshell/settings/pages/Wallpaper.qml` +- `quickshell/shell.qml` +- `quickshell/testing/SettingsDriver.qml` +- `quickshell/theme/MatugenService.qml` +- `quickshell/theme/Theme.qml` +- `quickshell/theme/ThemeManager.qml` +- `scripts/validate` +- `tests/config.test.cjs` +- `tests/providers_test.py` +- `tests/settings_runtime.py` diff --git a/docs/phase-6.md b/docs/phase-6.md new file mode 100644 index 0000000..677a1ff --- /dev/null +++ b/docs/phase-6.md @@ -0,0 +1,85 @@ +# Phase 6 — Media + +## Implemented + +- One shared native MPRIS service with dynamic discovery, metadata and capability-aware controls. +- Large floating music widget: artwork, title, artist, album, seeking, elapsed/remaining time and player selector. +- Optional `nowPlaying` bar module, added through Settings → Bar without changing saved module arrays. +- Shared compact media card in Settings and a tested component for Phase 7 Control Center. +- Media preferences now drive real views: visibility, artwork/progress/album, preferred player, monitor, corner, scale and optional Cava. +- Restrained artwork fade and track-content motion honoring reduced motion. +- One optional Cava process shared across views, stopped on pause or when no visible view needs it. + +The global accent remains independent of song artwork. Glass uses the existing neutral Theme. No new compositor, media daemon, audio daemon, system keybind or Nix configuration is introduced. + +## Try it + +```sh +./scripts/glassmxrph run +quickshell ipc --path ./quickshell call shell openSettings media +quickshell ipc --path ./quickshell call media status +``` + +Play a track in an MPRIS-capable app. Click previous/play/next, scrub a seekable track and switch players when multiple are available. Change monitor, corner and scale in Media settings. Add `nowPlaying` through the Bar editor. Enable Cava to visualize existing system audio. + +Selection order is explicit session selection, saved preferred DBus name or desktop-entry ID, a playing player, then the first available player. A disconnected player falls back immediately. Automatic ordering among several playing players follows the native model. Saved per-instance DBus names may change between app launches; a desktop-entry preference is more stable. + +```sh +quickshell ipc --path ./quickshell call media toggle +quickshell ipc --path ./quickshell call media next +quickshell ipc --path ./quickshell call media previous +quickshell ipc --path ./quickshell call media seek 30 +quickshell ipc --path ./quickshell call media select org.mpris.MediaPlayer2.PLAYER +quickshell ipc --path ./quickshell call media select '' +quickshell ipc --path ./quickshell call cava status +``` + +Commands act on the selected player. Unsupported actions return false. An empty selection restores preference/automatic selection. Durationless streams omit progress; absent artwork shows a music placeholder. Artwork is loaded asynchronously from the player-provided URL, which can require network access. Metadata quality and browser support depend on the application. + +## Cava and layout limits + +Cava is optional, off by default and visualizes system audio rather than isolating the selected player. Its compiled default input backend must work with the existing audio server. The supplied config uses [upstream raw ASCII output options](https://github.com/karlstav/cava/blob/master/example_files/config); installed version 1.0.0 was exercised. Failures produce an inline message; toggle Cava off/on after fixing the underlying problem. No automatic installation or repeated crash restart is attempted. + +The music widget is a bottom-layer desktop surface: normal application windows can cover it. It uses the selected output's logical coordinates, falls back when that output is absent, and supports four corners. Margins currently leave room for the bar and bottom dock but do not perform general collision avoidance. Scaling is constrained by output size. Blur/refraction remains compositor-owned for Phase 9. + +Control Center itself is Phase 7: this phase supplies and validates its shared media component, not a new Control Center window. No metrics widget is added yet. Nix packaging/build integration remains deferred as requested. + +## Validation + +QML and shared logic/provider tests pass. Private-DBus MPRIS fixtures cover two-player discovery, automatic/manual/preferred selection, removal/fallback, live metadata and artwork, capability guards, actual widget clicks, playback calls and seconds-to-microseconds seeking. Tests exercise unknown-duration streams, the bar and compact card, Cava frames, stop/resume/visibility behavior and failure/recovery, both connected outputs and missing-output fallback. Runtime logs are checked for warnings/errors. No real player's playback is changed. + +```sh +./scripts/validate +# Private DBus; needs Python dbus-python/PyGObject, QtTest, Cava and a real Wayland session: +dbus-run-session -- python3 tests/media_runtime.py +``` + +Use an isolated project copy if an instance already uses this source path. Existing foundation/settings/launcher/dock/tray tests are also run before promotion. Screenshots and logs are ignored `.cache/` artifacts; they are not shipped or published. + +## Changed files + +- `README.md` +- `dependencies.json` +- `docs/architecture.md` +- `docs/compatibility.md` +- `docs/phase-6.md` +- `docs/validation.md` +- `quickshell/bar/modules/NowPlayingModule.qml` +- `quickshell/config/cava.conf` +- `quickshell/controlcenter/modules/Media.qml` +- `quickshell/core/ModuleRegistry.qml` +- `quickshell/core/ShellState.qml` +- `quickshell/helpers/cava.py` +- `quickshell/media/CavaView.qml` +- `quickshell/media/MediaCard.qml` +- `quickshell/services/CavaService.qml` +- `quickshell/services/ConfigLogic.js` +- `quickshell/services/MediaService.qml` +- `quickshell/services/qmldir` +- `quickshell/settings/pages/Media.qml` +- `quickshell/shell.qml` +- `quickshell/testing/MediaDriver.qml` +- `quickshell/widgets/MusicWidget.qml` +- `tests/config.test.cjs` +- `tests/media_runtime.py` +- `tests/mpris_fixture.py` diff --git a/docs/phase-7.md b/docs/phase-7.md new file mode 100644 index 0000000..8188b07 --- /dev/null +++ b/docs/phase-7.md @@ -0,0 +1,127 @@ +# Phase 7 — Control Center + +## Implemented + +The right-hand system pill and running-shell IPC open Control Center at the active monitor's upper-right. The glass surface expands in width and height, reverses on closing and honors reduced motion. Escape/outside click dismiss it. Launcher, Settings, dock menus and tray menus coordinate visibility; tray activation never opens Control Center. + +Modules are registered separately and can be enabled, disabled and reordered in Settings → Control Center. The current modules are connectivity, audio/microphone, brightness, Night Light, Do Not Disturb, power profiles, shared MPRIS media and power actions. Detailed Audio, Network, Bluetooth, Displays, Notifications and Power settings are now reachable through the sidebar and command palette. + +- PipeWire: live default output/input, volume and mute; device selection under Audio. +- NetworkManager: live Wi-Fi radio state and connections; saved/open/PSK network connection UI. PSKs pass directly to the native API, are cleared from the field and are never stored in shell preferences. NetworkManager may store credentials in its own profiles. Enterprise/hidden networks and VPN management use the existing network editor. +- BlueZ: adapter selection, radio state and paired-device connect/disconnect. Pairing and PIN confirmation use the existing Bluetooth manager rather than registering a competing pairing agent. +- Brightness: actual backlight devices via brightnessctl, with configurable status/set command adapters for other providers. +- Night Light: the running wl-gammarelay DBus Temperature property, or a configured provider. No gamma daemon is started. Existing schedules may subsequently change temperature. +- Notifications: live SwayNC DND state through non-activating DBus calls; no replacement notification daemon is registered. +- Power: supported power profiles, detected lock command, Hyprland logout and logind suspend/reboot/shutdown. Logout, reboot and shutdown first present explicit confirmation. Escape cancels a pending confirmation before closing the panel. + +Unknown or unavailable capabilities produce disabled controls and explanatory text. Requests do not optimistically fabricate provider state; command adapters refresh state after success. Native services report through their live models. + +## Run and test manually + +```sh +./scripts/glassmxrph run +# In another terminal: +./scripts/glassmxrph controlcenter +quickshell ipc --path ./quickshell call controlcenter status +quickshell ipc --path ./quickshell call shell openSettings controlcenter +``` + +Try opening/closing repeatedly, Escape/outside dismissal, both monitors, module order and reduced motion. Audio device selectors live under Settings → Audio. Check unavailable brightness/Night Light providers under Displays. Power confirmation can be tested safely by choosing Reboot and then Cancel. + +The optional Hyprland binding is: + +```ini +bind = SUPER, X, exec, /absolute/path/to/glassMxrph/scripts/glassmxrph controlcenter +``` + +This is documentation only. The existing Super+X Serpantinum binding and all Nix/Hyprland configuration remain unchanged. Replace conflicting bindings only during the later integration step. The command toggles an existing instance; it never launches duplicate Quickshell processes. + +## Provider configuration + +Preferences are under `system` in the existing XDG configuration: + +```json +{ + "brightness": {"device":"auto", "statusCommand":[], "setCommand":[]}, + "nightLight": {"temperature":4000, "statusCommand":[], "setCommand":[]}, + "power": {"lockCommand":[]} +} +``` + +These are also editable in Displays and Power settings. Commands are JSON argument arrays, never shell-evaluated strings. Both status and set commands are needed for a custom display provider. Brightness status returns `{"available":true,"value":50}` (percent); Night Light status returns `{"available":true,"enabled":false}`. Set arguments support `{value}` (brightness percent or Kelvin) and `{enabled}` (Night Light boolean). Do not return optimistic state before the provider has applied a change. + +An empty lock command detects installed Serpantinum (`serpantinum lock`) first, then hyprlock. A configured argument array overrides that choice. Lock dispatch indicates the command was launched; locking/authentication remain the existing locker's responsibility. Power actions use existing logind/polkit policy and do not bypass inhibitors or authorization. + +The CLI adapters use structured busctl JSON for profile/capability data and `/sys/class/backlight` for device enumeration. Native NetworkManager/BlueZ/PipeWire models are event-driven. One shared asynchronous job refreshes only relevant visible command-backed controls every five seconds; polling stops when those views close. Wi-Fi scanning is enabled only while the Network page is open. No duplicate daemons are installed or started. + +`controlCenter.version: 1` marks a one-time migration of the unused Phase 1–6 empty module list. Nonempty layouts and unknown metadata survive; intentional empty layouts after migration stay empty. Malformed configuration remains blocked for correction. The runner derives `TZDIR` from an existing `/etc/localtime` zoneinfo symlink when unset, avoiding Qt timezone lookup warnings without hardcoded distribution paths. + +## Validation and limits + +Quickshell 0.3.1 native APIs were checked against installed qmltypes/source. Actual provider discovery was read-only: PipeWire/WirePlumber, NetworkManager, BlueZ, SwayNC, power-profiles-daemon and logind are present. This desktop has no backlight device and no running gamma relay; those controls remain unavailable until appropriate existing providers are configured. No DDC utility or gamma daemon was installed. Serpantinum's installed Night Light script supplied the verified wl-gammarelay DBus interface; its script is not invoked because it can start/manage daemons. + +Control Center runtime tests inspect native state, then substitute test-only recording models/adapters before any write. They exercise real Qt input for volume/microphone, Wi-Fi/Bluetooth, brightness, DND, Night Light, power confirmation/cancel, visual module reorder/toggle, both monitors, outside/Escape, reduced motion, reopen behavior and Settings routes. Provider unit tests check argv boundaries, numeric/type validation, unavailable providers, JSON errors and rejection of destructive actions without confirmation. A private-bus regression caught SwayNC client auto-activation; the final adapter uses `busctl --auto-start=no` instead, with a test that no notification daemon appears. Physical volume/radio/display changes and actual power actions were deliberately not executed; real hardware acknowledgements, credentials, pairing and polkit remain integration checks. + +```sh +./scripts/validate +# Real Hyprland session; QtTest required. Use an isolated project copy if already running: +python3 tests/controlcenter_runtime.py +``` + +Runtime logs are checked for QML warnings, errors and DBus failures. Earlier-phase regression scripts are also run, including media fixtures and tray/Control Center exclusivity on a private session bus. Screenshots/logs stay under ignored `.cache/`; nothing is published. Nix files are hash-checked unchanged and no package/system rebuild is performed. + +Advanced compositor blur/refraction remains Phase 9. Display mode editing, a native pairing agent, additional notification backends, dark-mode synchronization and native VPN controls are not included in this phase. The existing external tools remain available for advanced network and Bluetooth management. + +## Changed files + +- `README.md` +- `dependencies.json` +- `docs/architecture.md` +- `docs/compatibility.md` +- `docs/phase-7.md` +- `docs/validation.md` +- `quickshell/bar/modules/SystemModule.qml` +- `quickshell/config/defaults.json` +- `quickshell/controlcenter/ControlCard.qml` +- `quickshell/controlcenter/ControlCenter.qml` +- `quickshell/controlcenter/ControlRegistry.qml` +- `quickshell/controlcenter/SystemTile.qml` +- `quickshell/controlcenter/modules/Audio.qml` +- `quickshell/controlcenter/modules/Brightness.qml` +- `quickshell/controlcenter/modules/Connectivity.qml` +- `quickshell/controlcenter/modules/Dnd.qml` +- `quickshell/controlcenter/modules/NightLight.qml` +- `quickshell/controlcenter/modules/Power.qml` +- `quickshell/controlcenter/modules/Profiles.qml` +- `quickshell/controlcenter/qmldir` +- `quickshell/core/SettingsRegistry.qml` +- `quickshell/core/ShellState.qml` +- `quickshell/dock/DockState.qml` +- `quickshell/helpers/system.py` +- `quickshell/services/AudioService.qml` +- `quickshell/services/BluetoothService.qml` +- `quickshell/services/ConfigLogic.js` +- `quickshell/services/NetworkService.qml` +- `quickshell/services/PowerService.qml` +- `quickshell/services/ProviderJob.qml` +- `quickshell/services/SystemService.qml` +- `quickshell/services/TrayService.qml` +- `quickshell/services/qmldir` +- `quickshell/settings/Settings.qml` +- `quickshell/settings/controls/CommandPreference.qml` +- `quickshell/settings/pages/Audio.qml` +- `quickshell/settings/pages/Bluetooth.qml` +- `quickshell/settings/pages/ControlCenter.qml` +- `quickshell/settings/pages/Displays.qml` +- `quickshell/settings/pages/Network.qml` +- `quickshell/settings/pages/Notifications.qml` +- `quickshell/settings/pages/Power.qml` +- `quickshell/shell.qml` +- `quickshell/testing/ControlDriver.qml` +- `quickshell/testing/recording_system.py` +- `scripts/glassmxrph` +- `scripts/validate` +- `tests/config.test.cjs` +- `tests/controlcenter_runtime.py` +- `tests/system_providers_test.py` +- `tests/tray_runtime.py` diff --git a/docs/phase-8.md b/docs/phase-8.md new file mode 100644 index 0000000..4bf4d27 --- /dev/null +++ b/docs/phase-8.md @@ -0,0 +1,81 @@ +# Phase 8 — System Metrics + +One `MetricsService` feeds the desktop widget, seven optional bar pills, an optional Control Center card and Settings → System Metrics (`>metrics`). No Nix configuration, packages, keybinds or system services were changed. + +## What is available + +- CPU utilization, hottest supported CPU temperature, average reported frequency, and a bounded 60-sample CPU graph. +- GPU selection, utilization, temperature, VRAM used/total, frequency and power where the driver exposes them. +- RAM used/total/percentage, calculated from MemTotal minus MemAvailable. +- Configurable local storage paths with used/free/total and usage bars. +- Upload/download rates, interface selection and automatic physical-interface totals. +- Neutral glass desktop widget with configurable monitor, corner and scale. The default is the primary monitor's upper-right; only Music and System Metrics are desktop widgets. + +Settings → Bar offers `cpu`, `cpuTemperature`, `gpu`, `gpuTemperature`, `ram`, `storage` and `networkThroughput`. Click a pill to open metrics settings. The storage pill displays the first configured path. Settings → Control Center can add `metrics`. Existing bar/Control Center layouts remain intact; modules are not inserted into saved arrays. + +## Collection and portability + +A single Python standard-library streaming process owns the counters, elapsed-time calculations and sensor reads. It reads Linux `/proc` and `/sys` without sudo, writes no hardware state and installs no daemon. Views register with the singleton; the process stops when no metrics view exists. Multiple monitors and multiple bar pills do not add collectors. The desktop counts as a consumer while enabled, including when covered by an application. + +The default interval is two seconds, configurable from 1–30 seconds. NVIDIA is queried with the installed `nvidia-smi` at most once per five seconds, with a two-second command timeout. AMD uses DRM/hwmon sysfs. Storage updates at most every 15 seconds. These are minimum cadences: a slower configured interval also slows GPU/storage sampling. Sampling uses monotonic time; new/reset network counters cannot produce negative rates, and the first CPU/network sample is unavailable until a delta exists. + +GPU support depends on the driver: NVIDIA and AMD paths were checked on this machine; AMD units and missing values also have fixture coverage. Intel/other DRM devices are discovered but utilization is unavailable unless the driver exposes the supported sysfs counter. NVIDIA requires `nvidia-smi` on PATH; there is no fallback requiring privileged tracing. No CPU package-power backend is enabled. Missing values display `—`, never invented zero readings. GPU Auto picks the first discovered device (NVIDIA first); an explicitly selected missing GPU stays unavailable. + +Auto network sums interfaces with a physical sysfs device, excluding loopback and virtual bridges/VPN interfaces to reduce double counting. Select a named virtual interface explicitly to measure it. No traffic is generated. Storage free includes filesystem-reserved blocks; the snapshot separately supplies user-available bytes. Use **local paths only**: a stuck remote mount can block statvfs. Old values are marked stale after the greater of 10 seconds or three sample intervals; stopped/crashed collectors restart while a consumer remains. Permissions, missing hardware and mount failures remain unavailable. + +The collector follows the documented [Linux proc interfaces](https://docs.kernel.org/filesystems/proc.html) and [AMDGPU monitoring interfaces](https://docs.kernel.org/gpu/amdgpu/thermal.html). Quickshell Process/SplitParser and layer-window APIs reuse the installed 0.3.1 patterns already used by Cava and the Music widget. + +## Try it + +```sh +./scripts/glassmxrph run +# In another terminal: +quickshell ipc --path ./quickshell call shell openSettings metrics +quickshell ipc --path ./quickshell call metrics status +``` + +Try a different monitor/corner, disable the desktop widget, and add metrics pills from Settings → Bar. Add System Metrics in Control Center. With every metrics view disabled/closed, IPC reports `running: false`. Preferences merge with existing configurations and preserve unknown settings. + +## Validation + +```sh +./scripts/validate +# Existing Hyprland session, no running instance of this project: +python3 tests/metrics_runtime.py +``` + +Validation covers CPU guest accounting and counter resets, cache-aware RAM, network elapsed time/reset/new-interface handling, NVIDIA unsupported fields, AMD unit conversion, unavailable sources and config preservation/rejection. Live Wayland tests cover both connected outputs, monitor/corner changes, shared bar/settings/Control Center consumers, idle process shutdown/restart, live source changes, unavailable paths/interfaces, persistence and clean QML/DBus logs. Screenshots and logs stay under ignored `.cache/`; no user screenshots are published. Real telemetry is read-only. Foundation and Control Center runtime regressions also passed; the full metrics card was visually inspected using an isolated QML capture. + +Nix packaging remains deferred as requested. The source runner still requires the existing Python 3 dependency; NVIDIA telemetry additionally benefits from the host's own driver tool. Phase 9 remains compositor effects, animation/performance polish and final error handling. + +## Changed files +- `README.md` +- `dependencies.json` +- `docs/architecture.md` +- `docs/compatibility.md` +- `docs/phase-8.md` +- `docs/validation.md` +- `quickshell/bar/ModuleLoader.qml` +- `quickshell/bar/modules/MetricsModule.qml` +- `quickshell/config/defaults.json` +- `quickshell/controlcenter/ControlRegistry.qml` +- `quickshell/controlcenter/modules/Metrics.qml` +- `quickshell/core/ModuleRegistry.qml` +- `quickshell/core/SettingsRegistry.qml` +- `quickshell/core/ShellState.qml` +- `quickshell/helpers/metrics.py` +- `quickshell/metrics/MetricGauge.qml` +- `quickshell/metrics/MetricsCard.qml` +- `quickshell/services/ConfigLogic.js` +- `quickshell/services/MetricsService.qml` +- `quickshell/services/qmldir` +- `quickshell/settings/Settings.qml` +- `quickshell/settings/pages/Bar.qml` +- `quickshell/settings/pages/Metrics.qml` +- `quickshell/shell.qml` +- `quickshell/testing/MetricsDriver.qml` +- `quickshell/widgets/SystemMetrics.qml` +- `scripts/validate` +- `tests/config.test.cjs` +- `tests/metrics_runtime.py` +- `tests/metrics_test.py` diff --git a/docs/phase-9.md b/docs/phase-9.md new file mode 100644 index 0000000..878f9b7 --- /dev/null +++ b/docs/phase-9.md @@ -0,0 +1,87 @@ +# Phase 9 — Polish and recovery + +Later [customization work](customization.md) adds native wallpaper handling and opt-in global HyprGlass controls, superseding the documentation-only integration below. + +This phase changes only the portable project. It does not apply Nix/Hyprland configuration, alter bindings, load/unload plugins, install services or publish a repository. + +## Changes + +- Neutral, low-opacity gradient highlights add depth to shared glass surfaces. Hover lift, press compression and popup translation use the existing centralized duration/intensity controls; no new blur passes or background animation loops were added. +- Reduced motion now suppresses spatial intensity as well as duration, including dock magnification/press response and the settings cog. Existing launcher, popup and dock transitions remain interruptible. +- Accent text uses linearized luminance and chooses a contrasting black/white foreground. Matugen's supplied foreground is retained only when it meets 4.5:1 contrast against the current accent. Normal/hover/pressed button states have separate derived foregrounds; glass surfaces remain neutral. +- Media artwork retains the previous image while a new image loads, alongside existing metadata and artwork transitions. This uses the installed Qt Image `retainWhileLoading` API (Qt 6.8+). +- Launcher, Settings and Control Center resolve captured outputs against the current Quickshell screen list, falling back to the active output if the previous output is gone. Widgets/dock retain their existing configured-monitor fallback. +- Metrics failures mark readings stale immediately and retry with a 1–30 second exponential delay. Successful data resets the delay. The collector remains shared and stops without consumers. IPC diagnostics now include its PID and retry delay. +- A successful watched-palette reload clears the prior palette error. Invalid palette files still preserve the last valid colors. +- `./scripts/glassmxrph doctor` reports required command availability, session presence, versions, optional tools and HyprGlass layer status. It only queries; it does not activate services or start the shell. The runner gives a direct error when Python/Quickshell is absent. + +## HyprGlass integration is opt-in + +The running compositor is Hyprland 0.56.2. The host Nix configuration pins HyprGlass revision `77636c5711ed572ca199a84d06146ccac0951786`; the plugin reports runtime version 1.0.0 while the package is labelled 0.8.0, so the source revision is the reliable compatibility reference. Read-only inspection found the plugin loaded, but `plugin:hyprglass:layers:enabled` was false. + +[The project example](../examples/hyprland/glassmxrph-hyprglass.conf) uses option names from the [pinned upstream documentation](https://github.com/hyprnux/hyprglass/blob/77636c5711ed572ca199a84d06146ccac0951786/README.md). It defines a neutral, restrained preset and explicitly lists this project's seven layer namespaces. Alpha masking leaves the transparent regions of fullscreen launcher/settings/Control Center surfaces unglassed. A 0.1 alpha threshold excludes subtle shell shadows. + +**The example has not been applied or visually verified with refraction.** Merge it with existing namespace/preset maps during the later host integration; do not replace existing lists or blindly source it over other applications' configuration. It loads no plugin. Never use a plugin binary built for a different compositor ABI. Keep HyprGlass's existing blur-management defaults; avoid adding a second blur layer or enabling force-live-resample. Tray menus are xdg popups, not independently named layer surfaces, so their compositor treatment may differ. + +The shell remains usable with neutral QML transparency/highlights when HyprGlass is absent. No fake background refraction or global blur-strength slider is presented. Compositor effects remain owned by the compositor. + +## Test and review + +```sh +./scripts/glassmxrph doctor +./scripts/validate +./scripts/glassmxrph run +``` + +Check Appearance → Reduced motion, hover/press feedback, repeated popup opens/closes, track changes, palette updates, monitor selection and dock neighbors. For automated tests, stop only this project's preview first: + +```sh +python3 tests/polish_runtime.py +python3 tests/runtime.py +python3 tests/launcher_runtime.py +python3 tests/dock_runtime.py +python3 tests/settings_runtime.py # Matugen 4.2.x on PATH +python3 tests/controlcenter_runtime.py +python3 tests/metrics_runtime.py +dbus-run-session -- python3 tests/media_runtime.py +dbus-run-session -- python3 tests/tray_runtime.py +``` + +Private-DBus fixtures require the development dependencies listed in `dependencies.json`. The polish test uses isolated XDG configuration, tests synthetic stale-screen references, and deliberately terminates only its own verified metrics-helper PID to check recovery. It does not disconnect monitors or kill other services. Palette and contrast tests also cover an invalid Matugen foreground. A sampled RGB cube verifies at least 4.5:1 black/white contrast mathematically; this is not a claim about every translucent element or accessibility certification. + +Physical output hot-unplug, fractional-scale hardware, other distributions/architectures and actual HyprGlass refraction still require host testing. Two currently connected outputs, normal/reduced motion, native UI interactions, live Matugen generation and provider failures are covered locally. Nix packaging, conflicting host keybinds and autostart remain deferred by request. No source test replaces that deployment work. + +## Recorded validation + +QML validation and configuration/provider/contrast tests passed. The polish, foundation, launcher, dock, settings/Matugen, Control Center, metrics, private-DBus media and private-DBus tray runtime tests all passed with clean QML/DBus logs. Updated launcher and metrics captures were visually reviewed. Nix files match the pre-phase baseline; compositor effects were not applied. + +## Changed files +- `README.md` +- `dependencies.json` +- `docs/architecture.md` +- `docs/compatibility.md` +- `docs/phase-9.md` +- `docs/validation.md` +- `examples/hyprland/glassmxrph-hyprglass.conf` +- `quickshell/bar/modules/SettingsModule.qml` +- `quickshell/components/GlassButton.qml` +- `quickshell/components/GlassPanel.qml` +- `quickshell/components/GlassPopup.qml` +- `quickshell/controlcenter/ControlCenter.qml` +- `quickshell/core/ScreenService.qml` +- `quickshell/dock/DockItem.qml` +- `quickshell/launcher/Launcher.qml` +- `quickshell/media/MediaCard.qml` +- `quickshell/services/MetricsService.qml` +- `quickshell/settings/Settings.qml` +- `quickshell/shell.qml` +- `quickshell/testing/PolishDriver.qml` +- `quickshell/theme/ColorLogic.js` +- `quickshell/theme/MatugenService.qml` +- `quickshell/theme/Theme.qml` +- `scripts/doctor.py` +- `scripts/glassmxrph` +- `scripts/validate` +- `tests/launcher_runtime.py` +- `tests/polish.test.cjs` +- `tests/polish_runtime.py` diff --git a/docs/validation.md b/docs/validation.md new file mode 100644 index 0000000..35dabeb --- /dev/null +++ b/docs/validation.md @@ -0,0 +1,154 @@ +# Validation + +Run `scripts/validate` using matching Qt and Quickshell imports. `nix develop` +provides these. For native packages, set `QML_IMPORT_PATH` to the distribution's +Quickshell and Qt QML module locations. + +Quickshell 0.3.1 marks PanelWindow uncreatable in static metadata because its +implementation is selected at runtime. The validator suppresses this one diagnostic +locally on PanelWindow declarations; all other warnings fail validation. Real Wayland execution +is mandatory to validate those windows. + +Manual Phase 1 checks: + +1. Launch `scripts/glassmxrph run`, check bars on all monitors. +2. Cog opens settings on the active monitor; close button, Escape and outside click dismiss it. +3. Change custom accent/opacity/radius; reopen and restart to verify persistence. +4. Toggle reduced motion and change workspace; inspect occupied/urgent states. +5. Run the launcher command a second time; confirm no second instance starts. +6. Write a valid palette JSON to the documented state path and select Matugen. +7. Inspect `quickshell log --path ./quickshell` for QML/DBus errors. +8. Restore/stop only this configuration; leave unrelated shell processes intact. + +Automated configuration tests verify preservation of custom settings, unknown keys, +pinned applications, validation failures, future versions and immutable updates. + +## Verified Phase 1 results + +On 2026-10-03, using the versions in compatibility.md: + +- Configuration unit tests passed. +- All project QML passed qmllint (with the two documented, line-scoped + PanelWindow metadata exceptions). +- `python3 tests/runtime.py` passed in a real Hyprland session: no QML warnings + or DBus errors; duplicate prevention, atomic preference persistence, live + palette updates, settings IPC, and corrupt-file preservation all passed. +- Both landscape and portrait display bars were created at their own output + coordinates. The settings panel was visually inspected. +- The pinned x86_64-linux Nix package built successfully. + +`tests/runtime.py` is an opt-in graphical test and requires Python 3. It briefly +shows the preview, uses temporary XDG directories and terminates its own process. +Do not run it over an already running glassMxrph instance. + +Not yet verified: another distro, ARM hardware, monitor hotplug, fractional scale, +manual keyboard/outside-click interaction coverage, or HyprGlass effects. They +remain acceptance work for subsequent phases; successful lint is not proof of them. + +## Phase 2 tray validation + +Use the patched runtime supplied by the locked flake: + +```sh +nix develop +./scripts/validate +python3 tests/runtime.py +dbus-run-session -- python3 tests/tray_runtime.py +nix build --no-update-lock-file +``` + +The tray fixture requires Python dbus-python/PyGObject and QtTest, supplied by the +development shell. It registers two SNI objects on one DBus connection and exports +an actual DBusMenu with normal/disabled/hidden items, separators, icons, checkboxes, +radio items and two levels of submenus. QtTest injects input into this shell only; +it does not move the physical mouse or activate another application's menu actions. +Do not run the tests while another glassMxrph instance is running. + +Covered by the isolated tray regression test: + +- Discovery, no fabricated running-app icons, and removal of both tray objects. +- Hover intent delay, leaving before the delay, and icon-to-menu handover. +- Nested menu hover/activation, real DBus event delivery and application activation. +- Disabled actions, hidden entries, separators, icons, checkbox/radio rendering and live updates. +- Escape, disabled hover setting and immediate right-click despite disabled hover. +- Items without exported menus, opening on each available monitor, and closing on service exit. +- Clean QML/DBus logs once asynchronous menu loading has settled. + +The real session separately verified discovery of NetworkManager, Blueman and +OpenDeck, and read-only loading of NetworkManager's actual menu. No real application +menu actions were triggered. The fixture glass menu was visually inspected. + +Manual checks still useful: outside-click dismissal through the compositor, native +Shift-right-click fallback, physical pointer traversal at screen edges, hotplug, +fractional scaling and behavior on other distributions. QtTest input injection does +not prove the compositor's physical pointer routing. + +Static lint also has three line-scoped `missing-type` exceptions for the +PopupAnchor flag properties: Quickshell 0.3.1 exposes the enums but omits their +flags types in qmltypes. The properties and enum values are verified against its +installed metadata and exercised in the real Wayland tests. + +## Phase 3 dock validation + +Use the standalone source runner and installed matching Quickshell/Qt modules. +No Nix rebuild or packaging changes were made in this phase. + +```sh +./scripts/validate +python3 tests/runtime.py +python3 tests/dock_runtime.py +dbus-run-session -- python3 tests/tray_runtime.py +``` + +All four checks passed on 2026-10-03 with clean runtime logs. The existing patched +Quickshell binary was reused for the tray regression. Run graphical tests +sequentially, using a source path with no active instance. The dock test writes its +log/capture under ignored `.cache/`, uses temporary XDG preferences/desktop entries, +and closes only its own disposable fixture processes. It briefly creates/focuses +fixture windows on your desktop. See [Phase 3](phase-3.md) for exact coverage and +remaining physical-input, hotplug, scaling and portability acceptance checks. + +## Phase 4 launcher validation + +On 2026-10-03, QML lint, search/configuration tests, launcher runtime tests and the +foundation/dock/tray regression suites passed with clean logs. Run +`python3 tests/launcher_runtime.py` sequentially with the existing suites, from an +unused source path. It requires Python 3, QtTest and a live Hyprland session, uses +temporary desktop entries/preferences, and restores the originally focused output. +The captured launcher was visually inspected. See [Phase 4](phase-4.md) for exact +coverage, manual acceptance limits and opt-in keybind instructions. Nix integration +remains untouched and no new package build is claimed. + +The launcher keyboard regression also holds the pointer over a result during opening; +hover/layout changes no longer override keyboard selection. The isolated suite passed +after this fix, and the existing source preview was allowed to reload normally. + +## Phase 5 settings + +`python3 tests/providers_test.py` checks filesystem and command argument safety. `python3 tests/settings_runtime.py` uses real Matugen 4.2.x and a recording wallpaper backend, isolated XDG state and QtTest input. It checks live palette updates, stale job suppression, failure recovery and settings editing. Screenshots/logs are saved under ignored `.cache/`. See [Phase 5](phase-5.md). + +## Phase 6 media + +Run `dbus-run-session -- python3 tests/media_runtime.py` with dbus-python, PyGObject, +QtTest and Cava available. It creates two synthetic MPRIS players on a private bus, +uses isolated preferences and checks metadata, capability guards, player selection, +DBus actions, seek units, widget clicks, Cava lifecycle, monitor switching and fallback. +It also instantiates the compact Control Center component. Screenshots and logs live +under ignored `.cache/`. Real applications receive no playback commands. + +## Phase 7 Control Center + +`tests/system_providers_test.py` checks command boundaries, provider failures, +capabilities and confirmation before power commands. `tests/controlcenter_runtime.py` +uses real Wayland and read-only native discovery before injecting recording models +for writes. It verifies Qt input, module editing, both monitors, confirmation and +reopen behavior. No actual power, radio, volume or display change is executed. +The tray test also verifies Control Center/tray exclusivity. See [Phase 7](phase-7.md). + +## Phase 8 + +`./scripts/validate` includes `tests/metrics_test.py`. Run `python3 tests/metrics_runtime.py` in Hyprland with no project instance active for read-only telemetry, two-output placement, consumer lifecycle, live configuration, unavailable sources and clean logs. Uses isolated XDG preferences and a test-only screenshot driver; no hardware writes. See [Phase 8](phase-8.md). + +## Phase 9 + +`tests/polish.test.cjs` checks foreground contrast over a sampled RGB cube. `tests/polish_runtime.py` checks reduced motion, rapid routing, synthetic output fallback, palette error recovery and termination/restart of its own metrics collector. The existing launcher test includes the Phase 8 metrics command. Read-only environment checks are available through `scripts/glassmxrph doctor`. Full interaction regressions and limits are recorded in [Phase 9](phase-9.md). diff --git a/examples/hyprland/glassmxrph-hyprglass.conf b/examples/hyprland/glassmxrph-hyprglass.conf new file mode 100644 index 0000000..1a4c451 --- /dev/null +++ b/examples/hyprland/glassmxrph-hyprglass.conf @@ -0,0 +1,17 @@ +# OPTIONAL: merge these values with your existing HyprGlass layer configuration. +# Never blindly source over an existing namespace whitelist/preset map. +# Verified option names at HyprGlass 77636c5711ed572ca199a84d06146ccac0951786. +# Requires a plugin built for your exact compositor. This file loads no plugin. +plugin:hyprglass { + preset = name:glassmxrph, inherits:subtle, tint_color:0x00000000, blur_strength:1.5, refraction_strength:0.15, chromatic_aberration:0.05, lens_distortion:0.05 + layers { + enabled = 1 + namespaces = glassMxrph-bar, glassMxrph-tray, glassMxrph-popout, glassMxrph-dock, glassMxrph-settings, glassMxrph-launcher, glassMxrph-controlcenter, glassMxrph-dashboard, glassMxrph-music, glassMxrph-metrics + namespace_presets = glassMxrph-bar:glassmxrph, glassMxrph-tray:glassmxrph, glassMxrph-popout:glassmxrph, glassMxrph-dock:glassmxrph, glassMxrph-settings:glassmxrph, glassMxrph-launcher:glassmxrph, glassMxrph-controlcenter:glassmxrph, glassMxrph-dashboard:glassmxrph, glassMxrph-music:glassmxrph, glassMxrph-metrics:glassmxrph + namespace_mask_thresholds = glassMxrph-bar=0.1, glassMxrph-tray=0.1, glassMxrph-popout=0.1, glassMxrph-dock=0.1, glassMxrph-settings=0.1, glassMxrph-launcher=0.1, glassMxrph-controlcenter=0.1, glassMxrph-dashboard=0.1, glassMxrph-music=0.1, glassMxrph-metrics=0.1 + namespace_mask_modes = glassMxrph-bar=alpha, glassMxrph-tray=alpha, glassMxrph-popout=alpha, glassMxrph-dock=alpha, glassMxrph-settings=alpha, glassMxrph-launcher=alpha, glassMxrph-controlcenter=alpha, glassMxrph-dashboard=alpha, glassMxrph-music=alpha, glassMxrph-metrics=alpha + } +} +# Alpha masks avoid glass over transparent portions of fullscreen popup surfaces. +# Threshold 0.1 excludes the shell's subtle shadows. Do not use force_live_resample. +# Tray menus and nested submenus use the glassMxrph-tray layer namespace. diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..0ad6b89 --- /dev/null +++ b/flake.lock @@ -0,0 +1,27 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1790463110, + "narHash": "sha256-hKlVl12B1dF0Q5vd9dY3lIJM5mFGWYSlXwSLAqHZ1+s=", + "owner": "nixos", + "repo": "nixpkgs", + "rev": "e158d9ed9b51c98974c5e66e1ba1c9e0255fecaa", + "type": "github" + }, + "original": { + "owner": "nixos", + "ref": "nixos-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..f92c2dc --- /dev/null +++ b/flake.nix @@ -0,0 +1,26 @@ +{ + description = "glassMxrph — portable Quickshell desktop suite"; + inputs.nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable"; + outputs = { self, nixpkgs }: + let + systems = [ "x86_64-linux" "aarch64-linux" ]; + eachSystem = nixpkgs.lib.genAttrs systems; + in { + packages = eachSystem (system: + let pkgs = import nixpkgs { inherit system; }; + in { + quickshell = pkgs.callPackage ./packaging/nix/quickshell.nix {}; + default = pkgs.callPackage ./packaging/nix/package.nix { + source = self; + quickshell = self.packages.${system}.quickshell; + }; + }); + devShells = eachSystem (system: + let pkgs = import nixpkgs { inherit system; }; + in { default = pkgs.mkShell { + packages = [ self.packages.${system}.quickshell pkgs.qt6.qtdeclarative pkgs.nodejs (pkgs.python3.withPackages (ps: [ ps.dbus-python ps.pygobject3 ])) pkgs.dbus pkgs.matugen ]; + QML_IMPORT_PATH = "${self.packages.${system}.quickshell}/lib/qt-6/qml:${pkgs.qt6.qtdeclarative}/lib/qt-6/qml"; + }; }); + checks = eachSystem (system: { package = self.packages.${system}.default; }); + }; +} diff --git a/packaging/nix/package.nix b/packaging/nix/package.nix new file mode 100644 index 0000000..d5d1bae --- /dev/null +++ b/packaging/nix/package.nix @@ -0,0 +1,21 @@ +{ lib, stdenvNoCC, makeWrapper, quickshell, nodejs, source }: +stdenvNoCC.mkDerivation { + pname = "glassMxrph"; + version = "0.2.0"; + src = source; + nativeBuildInputs = [ makeWrapper nodejs ]; + dontBuild = true; + doCheck = true; + checkPhase = "node tests/config.test.cjs"; + installPhase = '' + mkdir -p $out/share/glassMxrph $out/bin + cp -r quickshell scripts tests docs dependencies.json README.md $out/share/glassMxrph/ + makeWrapper $out/share/glassMxrph/scripts/glassmxrph $out/bin/glassmxrph \ + --prefix PATH : ${lib.makeBinPath [ quickshell ]} + ''; + meta = { + description = "Modular glass desktop shell for Quickshell and Hyprland"; + platforms = lib.platforms.linux; + mainProgram = "glassmxrph"; + }; +} diff --git a/packaging/nix/quickshell.nix b/packaging/nix/quickshell.nix new file mode 100644 index 0000000..95af765 --- /dev/null +++ b/packaging/nix/quickshell.nix @@ -0,0 +1,5 @@ +{ quickshell }: +# Scope the compatibility fix to the verified upstream version. +if quickshell.version == "0.3.1" then quickshell.overrideAttrs (old: { + patches = (old.patches or []) ++ [ ../patches/quickshell-0.3.1-sni-unregister.patch ]; +}) else quickshell diff --git a/packaging/patches/quickshell-0.3.1-sni-unregister.patch b/packaging/patches/quickshell-0.3.1-sni-unregister.patch new file mode 100644 index 0000000..fbcd707 --- /dev/null +++ b/packaging/patches/quickshell-0.3.1-sni-unregister.patch @@ -0,0 +1,28 @@ +--- a/src/services/status_notifier/watcher.cpp ++++ b/src/services/status_notifier/watcher.cpp +@@ -74,19 +74,21 @@ + this->tryRegister(); + return; + } else { +- QString qualifiedItem; ++ QStringList qualifiedItems; + this->items.removeIf([&](const QString& item) { +- if (item.startsWith(service)) { +- qualifiedItem = item; ++ if (item.startsWith(service + "/")) { ++ qualifiedItems.push_back(item); + return true; + } else return false; + }); + +- if (!qualifiedItem.isEmpty()) { ++ if (!qualifiedItems.isEmpty()) { ++ for (const auto& qualifiedItem: qualifiedItems) { + qCDebug(logStatusNotifierWatcher).noquote() + << "Unregistered StatusNotifierItem" << qualifiedItem << "from watcher"; + + emit this->StatusNotifierItemUnregistered(qualifiedItem); ++ } + } else if (this->hosts.removeAll(service) != 0) { + qCDebug(logStatusNotifierWatcher).noquote() + << "Unregistered StatusNotifierHost" << service << "from watcher"; diff --git a/quickshell/assets/glassmxrph-256.png b/quickshell/assets/glassmxrph-256.png new file mode 100644 index 0000000..69f21a8 Binary files /dev/null and b/quickshell/assets/glassmxrph-256.png differ diff --git a/quickshell/bar/Bar.qml b/quickshell/bar/Bar.qml new file mode 100644 index 0000000..3ab8f05 --- /dev/null +++ b/quickshell/bar/Bar.qml @@ -0,0 +1,63 @@ +import QtQuick +import QtQuick.Shapes +import Quickshell +import Quickshell.Wayland +import "../components" +import "../core" +import "../services" +import "../theme" +// Quickshell selects the concrete PanelWindow implementation at runtime. +// qmllint disable uncreatable-type +PanelWindow { + // qmllint enable uncreatable-type + id: root + required property var modelData + screen: modelData + anchors { top: true; left: true; right: true } + readonly property int outerMargin: BarDrawers.margin + // The window reaches below the bar (input is masked to the bar) so the + // HyprGlass layer edge is not on the bar's bottom edge, where drawers join. + implicitHeight: BarDrawers.bottom + BarDrawers.overhang + mask: Region { item: panel } + color: Theme.transparent + exclusionMode: ExclusionMode.Ignore + WlrLayershell.namespace: "glassMxrph-bar" + Component.onCompleted: TrayService.registerBar(root) + Component.onDestruction: TrayService.unregisterBar(root) + GlassPanel { + id: panel + x: root.outerMargin; y: root.outerMargin + width: root.width - 2 * root.outerMargin + height: BarDrawers.height + radius: BarDrawers.radius + border.width: 0 + ModuleRow { position: "left"; barScreen: root.screen; anchors.left: parent.left; anchors.leftMargin: 6; anchors.verticalCenter: parent.verticalCenter } + ModuleRow { position: "center"; barScreen: root.screen; anchors.centerIn: parent } + ModuleRow { position: "right"; barScreen: root.screen; anchors.right: parent.right; anchors.rightMargin: 6; anchors.verticalCenter: parent.verticalCenter } + } + // Outline with openings where drawers hang from the bar. + Shape { + id: outline + x: panel.x + y: panel.y + width: panel.width + height: panel.height + preferredRendererType: Shape.CurveRenderer + readonly property var gaps: BarDrawers.gapsFor(root.screen ? root.screen.name : "").map(g => [g.x0 - panel.x, g.x1 - panel.x]).sort((a, b) => b[0] - a[0]) + ShapePath { + fillColor: "transparent" + strokeColor: Theme.border + strokeWidth: 1 + PathSvg { + path: { + const W = panel.width - 1, H = panel.height - 0.5, r = Math.max(0, panel.radius - 0.5), o = 0.5; + let d = `M ${r + o} ${o} L ${W - r} ${o} A ${r} ${r} 0 0 1 ${W} ${r + o} L ${W} ${H - r} A ${r} ${r} 0 0 1 ${W - r} ${H}`; + // Bottom edge right to left, skipping each drawer's span. + for (const g of outline.gaps) + d += ` L ${Math.min(W - r, Math.max(r, g[1]))} ${H} M ${Math.max(r, Math.min(W - r, g[0]))} ${H}`; + return d + ` L ${r + o} ${H} A ${r} ${r} 0 0 1 ${o} ${H - r} L ${o} ${r + o} A ${r} ${r} 0 0 1 ${r + o} ${o}`; + } + } + } + } +} diff --git a/quickshell/bar/BarPopout.qml b/quickshell/bar/BarPopout.qml new file mode 100644 index 0000000..f51bf0a --- /dev/null +++ b/quickshell/bar/BarPopout.qml @@ -0,0 +1,278 @@ +pragma ComponentBehavior: Bound +import QtQuick +import Quickshell +import Quickshell.Wayland +import Quickshell.Widgets +import "../components" +import "../core" +import "../theme" +// Bar hover popout. HyprGlass shapes glass from the layer box, so the surface is +// sized to the card and its geometry animates to morph between anchors. +// qmllint disable uncreatable-type +PanelWindow { + // qmllint enable uncreatable-type + id: root + readonly property Item anchorItem: PopoutState.anchor + readonly property var anchorWindow: anchorItem ? anchorItem.QsWindow.window : null + readonly property string kind: PopoutState.kind + // The hovered window's Wayland toplevel; falls back to the focused one. + readonly property var toplevel: PopoutState.payload || ToplevelManager.activeToplevel + // Anchors may name a wider placement item (the tray pill, the window list) + // so the drawer stays put while the pointer moves between its entries. + readonly property var anchorObject: anchorItem + readonly property Item placementItem: anchorObject ? (anchorObject.placement || anchorObject) : null + readonly property point anchorPoint: placementItem && anchorWindow ? placementItem.mapToItem(anchorWindow.contentItem, 0, 0) : Qt.point(0, 0) + readonly property real availableWidth: screen ? screen.width : 1280 + readonly property real targetWidth: Math.ceil(root.kind === "window" ? windowCard.implicitWidth : tip.implicitWidth) + readonly property real targetHeight: Math.ceil(root.kind === "window" ? windowCard.implicitHeight : tip.implicitHeight) + readonly property real targetX: BarDrawers.clampX(anchorPoint.x + (placementItem ? placementItem.width / 2 : 0), targetWidth + 2 * BarDrawers.ear, availableWidth) + // Morph only while the drawer is out; a cold open grows in place. + readonly property bool morph: drawer.progress > 0.05 && Theme.duration > 0 + property real animX: targetX + property real animW: targetWidth + property real animH: targetHeight + Behavior on animX { + enabled: root.morph + NumberAnimation { + duration: Theme.duration * 1.4 + easing.type: Easing.BezierSpline + easing.bezierCurve: [0.2, 0, 0, 1, 1, 1] + } + } + Behavior on animW { + enabled: root.morph + NumberAnimation { + duration: Theme.duration * 1.4 + easing.type: Easing.BezierSpline + easing.bezierCurve: [0.2, 0, 0, 1, 1, 1] + } + } + Behavior on animH { + enabled: root.morph + NumberAnimation { + duration: Theme.duration * 1.4 + easing.type: Easing.BezierSpline + easing.bezierCurve: [0.2, 0, 0, 1, 1, 1] + } + } + screen: anchorWindow ? anchorWindow.screen : null + anchors { + top: true + left: true + } + // The layer starts at the screen top so the bar join is inside its box. + // Quickshell 0.3.1 qmllint cannot resolve the exported Margins value type. + // qmllint disable unqualified unresolved-type + margins.left: Math.round(animX) + // qmllint enable unqualified unresolved-type + implicitWidth: Math.max(40, Math.round(drawer.width)) + implicitHeight: Math.max(30, Math.round(BarDrawers.bottom + animH)) + mask: Region { + item: drawer.body + } + exclusionMode: ExclusionMode.Ignore + color: Theme.transparent + readonly property bool active: PopoutState.open || drawer.shown + visible: active + WlrLayershell.namespace: "glassMxrph-popout" + WlrLayershell.layer: WlrLayer.Overlay + WlrLayershell.keyboardFocus: WlrKeyboardFocus.None + Component.onCompleted: PopoutState.window = root + Component.onDestruction: if (PopoutState.window === root) + PopoutState.window = null + BarDrawer { + id: drawer + objectName: "barPopoutSurface" + y: BarDrawers.bottom + open: PopoutState.open + contentWidth: Math.round(root.animW) + contentHeight: Math.round(root.animH) + drawerId: "popout" + screenName: root.screen ? root.screen.name : "" + screenX: root.animX + onHoveredChanged: PopoutState.setPopoutHovered(hovered) + Text { + id: tip + anchors.centerIn: parent + padding: 10 + leftPadding: 14 + rightPadding: 14 + text: PopoutState.text + color: Theme.text + font.pixelSize: 12 + opacity: root.kind === "tooltip" ? 1 : 0 + visible: opacity > 0 + Behavior on opacity { + NumberAnimation { + duration: Theme.duration / 2 + } + } + } + Column { + id: windowCard + objectName: "windowPreview" + anchors.horizontalCenter: parent.horizontalCenter + anchors.top: parent.top + padding: 12 + spacing: 10 + opacity: (root.kind === "window" ? 1 : 0) * contentFade + visible: opacity > 0 + Behavior on opacity { + NumberAnimation { + duration: Theme.duration / 2 + } + } + Connections { + target: root + function onToplevelChanged() { + if (root.kind === "window" && Theme.duration > 0) + swap.restart(); + } + } + NumberAnimation { + id: swap + target: windowCard + property: "contentFade" + from: 0.35 + to: 1 + duration: Theme.duration + easing.type: Easing.OutCubic + } + property real contentFade: 1 + readonly property var entry: root.toplevel && root.toplevel.appId ? DesktopEntries.heuristicLookup(root.toplevel.appId) : null + // Fixed size: hovering between windows swaps the content, not the pane. + readonly property real previewWidth: 480 + Row { + spacing: 10 + width: windowCard.previewWidth + IconImage { + id: appIcon + anchors.verticalCenter: parent.verticalCenter + implicitSize: 32 + source: windowCard.entry && windowCard.entry.icon ? Quickshell.iconPath(windowCard.entry.icon, true) : "" + visible: source.toString() !== "" + // Synchronous on purpose: Quickshell's icon provider loads QPixmaps, + // which crash when built off the GUI thread (Quickshell 0.3.1). + } + Column { + anchors.verticalCenter: parent.verticalCenter + width: parent.width - (appIcon.visible ? appIcon.width + parent.spacing : 0) - actions.width - parent.spacing + Text { + width: parent.width + text: root.toplevel ? root.toplevel.title || "Untitled" : "" + color: Theme.text + font.pixelSize: 13 + font.weight: Font.DemiBold + elide: Text.ElideRight + } + Text { + width: parent.width + text: windowCard.entry && windowCard.entry.name ? windowCard.entry.name + " · " + root.toplevel.appId : root.toplevel ? root.toplevel.appId : "" + color: Theme.textSecondary + font.pixelSize: 11 + elide: Text.ElideRight + } + } + Row { + id: actions + anchors.verticalCenter: parent.verticalCenter + spacing: 4 + WindowAction { + objectName: "previewMaximize" + glyph: root.toplevel && root.toplevel.maximized ? "󰘕" : "󰘖" + fallback: "□" + label: "Maximize" + onActivated: root.toplevel.maximized = !root.toplevel.maximized + } + WindowAction { + objectName: "previewFullscreen" + glyph: "󰊓" + fallback: "⤢" + label: "Fullscreen" + onActivated: root.toplevel.fullscreen = !root.toplevel.fullscreen + } + WindowAction { + objectName: "previewClose" + glyph: "󰅖" + fallback: "×" + label: "Close window" + danger: true + onActivated: { + PopoutState.close(); + root.toplevel.close(); + } + } + } + } + ClippingRectangle { + id: frame + width: windowCard.previewWidth + height: 270 + radius: Math.max(8, Theme.radius * 0.55) + color: Theme.surfaceVariant + border.width: 1 + border.color: Theme.hairline + ScreencopyView { + id: preview + // Letterboxed into the fixed frame, keeping the window's aspect. + readonly property real aspect: sourceSize.width > 0 && sourceSize.height > 0 ? sourceSize.width / sourceSize.height : 16 / 9 + anchors.centerIn: parent + width: Math.min(parent.width, parent.height * aspect) + height: width / aspect + captureSource: root.kind === "window" && root.active && root.toplevel ? root.toplevel : null + live: root.active && root.kind === "window" + constraintSize: Qt.size(windowCard.previewWidth * 2, 540) + opacity: hasContent ? 1 : 0 + Behavior on opacity { + NumberAnimation { + duration: Theme.duration + } + } + } + Text { + anchors.centerIn: parent + visible: !preview.hasContent + text: "Preview unavailable" + color: Theme.textSecondary + font.pixelSize: 12 + } + } + } + } + component WindowAction: Rectangle { + id: action + property string glyph + property string fallback + property string label + property bool danger: false + signal activated + implicitWidth: 26 + implicitHeight: 26 + radius: 13 + color: hover.hovered ? (danger ? Qt.alpha("#ff5f57", 0.85) : Theme.hover) : Theme.surfaceVariant + border.width: 1 + border.color: Theme.hairline + Behavior on color { + ColorAnimation { + duration: Theme.duration / 2 + } + } + Text { + anchors.centerIn: parent + text: Icons.available ? action.glyph : action.fallback + font.family: Icons.available ? Icons.family : "" + font.pixelSize: 13 + color: Theme.text + } + HoverHandler { + id: hover + cursorShape: Qt.PointingHandCursor + } + TapHandler { + onTapped: if (root.toplevel) + action.activated() + } + Accessible.role: Accessible.Button + Accessible.name: label + } +} diff --git a/quickshell/bar/ModuleLoader.qml b/quickshell/bar/ModuleLoader.qml new file mode 100644 index 0000000..d035a6a --- /dev/null +++ b/quickshell/bar/ModuleLoader.qml @@ -0,0 +1,14 @@ +import QtQuick +import "../core" +Loader { + required property string moduleId + property var barScreen + // The module's layout entry ({id, position, enabled, options}). + property var entry: ({}) + source: ModuleRegistry.source(moduleId) + onLoaded: { + if (item && "metric" in item) item.metric = moduleId; + if (item && "barScreen" in item) item.barScreen = Qt.binding(() => barScreen); + if (item && "entry" in item) item.entry = Qt.binding(() => entry); + } +} diff --git a/quickshell/bar/ModuleRow.qml b/quickshell/bar/ModuleRow.qml new file mode 100644 index 0000000..69325b5 --- /dev/null +++ b/quickshell/bar/ModuleRow.qml @@ -0,0 +1,13 @@ +pragma ComponentBehavior: Bound +import QtQuick +import "../core" +Row { + id: root + required property string position + property var barScreen + spacing: 8 + Repeater { + model: BarLayout.modulesFor(root.barScreen ? root.barScreen.name : "").filter(m => m.enabled && m.position === root.position) + ModuleLoader { required property var modelData; moduleId: modelData.id; barScreen: root.barScreen; entry: modelData } + } +} diff --git a/quickshell/bar/modules/ActiveWindowModule.qml b/quickshell/bar/modules/ActiveWindowModule.qml new file mode 100644 index 0000000..bfba4b2 --- /dev/null +++ b/quickshell/bar/modules/ActiveWindowModule.qml @@ -0,0 +1,227 @@ +pragma ComponentBehavior: Bound +import QtQuick +import Quickshell +import Quickshell.Hyprland +import Quickshell.Widgets +import "../../components" +import "../../core" +import "../../services" +import "../../theme" + +// Programs on the focused workspace, left to right. Hover one for a live +// preview, click to focus it, middle-click to close it. +GlassPill { + id: root + objectName: "activeWindowPill" + property var barScreen + // Layout entry; options come from the cog in Settings → Bar. + property var entry: ({ + id: "activeWindow" + }) + readonly property string transition: ModuleRegistry.option(entry, "transition") + readonly property string labels: ModuleRegistry.option(entry, "labels") + readonly property string collapse: ModuleRegistry.option(entry, "collapse") + readonly property int labelWidth: ({ + short: 90, + medium: 150, + long: 230 + })[ModuleRegistry.option(entry, "labelWidth")] || 150 + readonly property bool previews: ModuleRegistry.option(entry, "preview") !== "off" + readonly property int workspace: Hyprland.focusedWorkspace ? Hyprland.focusedWorkspace.id : 0 + // Workspace switches replace the whole list: animate it as one, in the + // switch direction, instead of popping each pill in. + property int previousWorkspace: workspace + property real slideFrom: 0 + property bool switching: false + onWorkspaceChanged: { + slideFrom = workspace > previousWorkspace ? 1 : -1; + previousWorkspace = workspace; + switching = true; + settle.restart(); + if (transition === "fade" || transition === "slide") + switchAnim.restart(); + } + Timer { + id: settle + interval: Theme.duration + 50 + onTriggered: root.switching = false + } + ParallelAnimation { + id: switchAnim + NumberAnimation { + target: row + property: "opacity" + from: 0 + to: 1 + duration: Theme.duration * 1.2 + easing.type: Easing.OutCubic + } + NumberAnimation { + target: slide + property: "x" + from: root.transition === "slide" ? 14 * root.slideFrom * Math.max(0.3, Theme.intensity) : 0 + to: 0 + duration: Theme.duration * 1.4 + easing.type: Easing.OutCubic + } + } + // Left to right by Hyprland's last known position. Positions are not + // refreshed here: Hyprland.refreshToplevels() can crash Quickshell 0.3.1 + // (HyprlandToplevel::updateFromObject), so windows without one go last. + // Read windows only after startup: bindings on Hyprland toplevels during + // Quickshell's initial window parse make its startup crash far likelier. + property bool armed: false + Timer { + interval: 1500 + running: true + onTriggered: root.armed = true + } + readonly property var windows: !armed ? [] : HyprlandService.windows.filter(w => w.workspace === root.workspace && !!w.handle).sort((a, b) => root.order(a) - root.order(b)) + function order(w) { + return w.width > 0 ? w.x * 10000 + w.y : 1e12 + HyprlandService.windows.indexOf(w); + } + // Crowded workspaces show the unfocused programs as icons only. + readonly property bool compact: labels === "icons" || labels === "focused" || (collapse !== "never" && windows.length > Number(collapse)) + function pretty(id) { + const last = String(id || "").split(".").pop().replace(/[-_]+/g, " "); + return last ? last.charAt(0).toUpperCase() + last.slice(1) : "Window"; + } + implicitHeight: ModuleRegistry.pillHeight + implicitWidth: (windows.length ? row.implicitWidth : empty.implicitWidth) + 8 + Behavior on implicitWidth { + enabled: root.transition !== "none" + NumberAnimation { + duration: Theme.duration + easing.type: Easing.OutCubic + } + } + clip: true + Text { + id: empty + anchors.centerIn: parent + visible: root.windows.length === 0 + leftPadding: 12 + rightPadding: 12 + text: "Desktop" + color: Theme.textSecondary + font.pixelSize: 13 + } + Row { + id: row + anchors.centerIn: parent + spacing: 2 + transform: Translate { + id: slide + } + // Single new windows pop in; a workspace switch uses switchAnim. + add: Transition { + enabled: root.transition !== "none" && (root.transition === "pop" || !root.switching) + NumberAnimation { + properties: "opacity,scale" + from: 0 + to: 1 + duration: Theme.duration + easing.type: Easing.OutCubic + } + } + move: Transition { + enabled: root.transition !== "none" + NumberAnimation { + properties: "x" + duration: Theme.duration + easing.type: Easing.OutCubic + } + } + Repeater { + model: ScriptModel { + values: root.windows + objectProp: "address" + } + Rectangle { + id: item + required property var modelData + required property int index + readonly property var toplevel: modelData.handle + // Previews hang under the whole list so the pane stays put. + readonly property Item placement: root + readonly property var entry: modelData.appId ? DesktopEntries.heuristicLookup(modelData.appId) : null + readonly property string name: entry && entry.name ? entry.name : root.pretty(modelData.appId || modelData.title) + readonly property bool focused: !!toplevel && toplevel.activated + readonly property bool previewing: PopoutState.open && PopoutState.anchor === item + readonly property bool labelled: root.labels !== "icons" && (!root.compact || focused) + objectName: "windowItem-" + index + implicitHeight: ModuleRegistry.pillHeight - 6 + implicitWidth: content.implicitWidth + 16 + radius: height / 2 + color: previewing ? Qt.alpha(Theme.accent, 0.28) : focused ? Qt.alpha(Theme.text, 0.13) : hover.hovered ? Theme.hover : Theme.transparent + Behavior on color { + ColorAnimation { + duration: Theme.duration / 2 + } + } + Behavior on implicitWidth { + NumberAnimation { + duration: Theme.duration + easing.type: Easing.OutCubic + } + } + Row { + id: content + anchors.centerIn: parent + spacing: 7 + IconImage { + id: icon + anchors.verticalCenter: parent.verticalCenter + implicitSize: Math.round(ModuleRegistry.pillHeight * 0.5) + source: item.entry && item.entry.icon ? Quickshell.iconPath(item.entry.icon, true) : Quickshell.iconPath("application-x-executable", true) + // Synchronous on purpose: Quickshell's icon provider loads QPixmaps, + // which crash when built off the GUI thread (Quickshell 0.3.1). + } + Text { + anchors.verticalCenter: parent.verticalCenter + visible: item.labelled + width: Math.min(implicitWidth, root.labelWidth) + text: item.name + color: item.focused ? Theme.text : Theme.textSecondary + font.pixelSize: 13 + font.weight: item.focused ? Font.DemiBold : Font.Normal + elide: Text.ElideRight + } + } + // Focused-window underline. + Rectangle { + anchors.bottom: parent.bottom + anchors.horizontalCenter: parent.horizontalCenter + width: item.focused ? 14 : 0 + height: 2 + radius: 1 + color: Theme.accentVivid + Behavior on width { + NumberAnimation { + duration: Theme.duration + easing.type: Easing.OutCubic + } + } + } + HoverHandler { + id: hover + cursorShape: Qt.PointingHandCursor + onHoveredChanged: hovered ? PopoutState.hover(item, root.previews ? "window" : "tooltip", item.modelData.title || item.name, item.toplevel) : PopoutState.unhover(item) + } + TapHandler { + acceptedButtons: Qt.LeftButton + onTapped: { + PopoutState.close(); + HyprlandService.focusWindow(item.modelData.address); + } + } + TapHandler { + acceptedButtons: Qt.MiddleButton + onTapped: HyprlandService.closeWindow(item.modelData.address) + } + Accessible.role: Accessible.Button + Accessible.name: item.name + (item.focused ? ", focused" : "") + } + } + } +} diff --git a/quickshell/bar/modules/CavaModule.qml b/quickshell/bar/modules/CavaModule.qml new file mode 100644 index 0000000..234196c --- /dev/null +++ b/quickshell/bar/modules/CavaModule.qml @@ -0,0 +1,83 @@ +pragma ComponentBehavior: Bound +import QtQuick +import "../../components" +import "../../core" +import "../../services" +import "../../theme" + +// Cava audio visualizer in the bar. Click opens the dashboard's Media tab, +// right-click the Media settings. Cava only runs while something plays. +GlassPill { + id: root + objectName: "cavaPill" + readonly property var options: ConfigService.ready ? ConfigService.data.bar.cava : ({ + bars: 12, + style: "bars", + hideWhenIdle: true + }) + readonly property bool mirror: options.style === "mirror" + readonly property bool shown: !CavaService.failed && (MediaService.playing || !options.hideWhenIdle) + readonly property int barWidth: 3 + readonly property int gap: 2 + implicitHeight: ModuleRegistry.pillHeight + implicitWidth: shown ? options.bars * barWidth + (options.bars - 1) * gap + 22 : 0 + visible: implicitWidth > 0.5 + opacity: shown ? 1 : 0 + clip: true + Behavior on implicitWidth { + NumberAnimation { + duration: Theme.duration * 1.4 + easing.type: Easing.OutCubic + } + } + Behavior on opacity { + NumberAnimation { + duration: Theme.duration + } + } + Component.onCompleted: CavaService.widgetConsumers++ + Component.onDestruction: CavaService.widgetConsumers-- + // Cava emits 24 bands; each pill bar averages its share of them. + function level(index) { + const all = CavaService.bars, n = options.bars, from = Math.floor(index * all.length / n), to = Math.max(from + 1, Math.floor((index + 1) * all.length / n)); + let sum = 0; + for (let i = from; i < to; i++) + sum += all[i] || 0; + return sum / (to - from); + } + Row { + anchors.centerIn: parent + height: parent.height - 12 + spacing: root.gap + Repeater { + model: root.options.bars + Rectangle { + required property int index + readonly property real value: MediaService.playing ? Math.min(1, root.level(index)) : 0 + width: root.barWidth + radius: width / 2 + height: Math.max(width, parent.height * value) + y: root.mirror ? (parent.height - height) / 2 : parent.height - height + color: Theme.accentVivid + opacity: 0.55 + 0.45 * value + Behavior on height { + NumberAnimation { + duration: 80 + } + } + } + } + } + TapHandler { + acceptedButtons: Qt.LeftButton + onTapped: ShellState.toggleDashboard("media") + } + TapHandler { + acceptedButtons: Qt.RightButton + onTapped: ShellState.openSettings("media") + } + HoverHandler { + cursorShape: Qt.PointingHandCursor + } + Accessible.name: "Audio visualizer" +} diff --git a/quickshell/bar/modules/ClockModule.qml b/quickshell/bar/modules/ClockModule.qml new file mode 100644 index 0000000..ba44248 --- /dev/null +++ b/quickshell/bar/modules/ClockModule.qml @@ -0,0 +1,31 @@ +import QtQuick +import Quickshell +import "../../components" +import "../../theme" +import "../../services" +import "../../core" + +GlassPill { + id: root + readonly property var options: ConfigService.data.bar.clock + width: label.implicitWidth + 30 + height: ModuleRegistry.pillHeight + SystemClock { + id: clock + precision: root.options.showSeconds ? SystemClock.Seconds : SystemClock.Minutes + } + Text { + id: label + anchors.centerIn: parent + text: Qt.formatDateTime(clock.date, (root.options.showDate ? "ddd, d MMM " : "") + (root.options.use24Hour ? "HH:mm" : "h:mm") + (root.options.showSeconds ? ":ss" : "") + (root.options.use24Hour ? "" : " AP")) + color: Theme.text + font.pixelSize: 13 + } + // Clicking the clock opens the dashboard (Settings → Dashboard). + MouseArea { + anchors.fill: parent + enabled: ConfigService.ready && ConfigService.data.dashboard.enabled && ConfigService.data.dashboard.openFromClock + cursorShape: enabled ? Qt.PointingHandCursor : Qt.ArrowCursor + onClicked: ShellState.toggleDashboard("") + } +} diff --git a/quickshell/bar/modules/MetricsModule.qml b/quickshell/bar/modules/MetricsModule.qml new file mode 100644 index 0000000..2f108e4 --- /dev/null +++ b/quickshell/bar/modules/MetricsModule.qml @@ -0,0 +1,35 @@ +import QtQuick +import "../../components" +import "../../services" +import "../../core" + +GlassButton { + property string metric: "cpu" + implicitHeight: ModuleRegistry.pillHeight + Component.onCompleted: MetricsService.consumers++ + Component.onDestruction: MetricsService.consumers-- + text: { + switch (metric) { + case "cpu": + return "CPU " + MetricsService.value(MetricsService.cpu.percent, "%"); + case "cpuTemperature": + return "CPU " + MetricsService.value(MetricsService.cpu.temperature, "°C"); + case "gpu": + return "GPU " + MetricsService.value(MetricsService.gpu.percent, "%"); + case "gpuTemperature": + return "GPU " + MetricsService.value(MetricsService.gpu.temperature, "°C"); + case "ram": + return "RAM " + MetricsService.value(MetricsService.ram.percent, "%"); + case "storage": + return "Disk " + MetricsService.value((MetricsService.snapshot.storage || [ + {} + ])[0]?.percent, "%"); + default: + return "↓ " + MetricsService.bytes(MetricsService.network.download) + "/s ↑ " + MetricsService.bytes(MetricsService.network.upload) + "/s"; + } + } + readonly property bool network: metric === "networkThroughput" + accented: network && ShellState.controlCenterOpen + onClicked: network ? ShellState.toggleControlCenter() : ShellState.openSettings("metrics") + Accessible.name: text +} diff --git a/quickshell/bar/modules/NowPlayingModule.qml b/quickshell/bar/modules/NowPlayingModule.qml new file mode 100644 index 0000000..493083c --- /dev/null +++ b/quickshell/bar/modules/NowPlayingModule.qml @@ -0,0 +1,36 @@ +import QtQuick +import QtQuick.Layouts +import "../../components" +import "../../services" +import "../../core" +import "../../theme" + +GlassPill { + implicitWidth: content.implicitWidth + 12 + implicitHeight: ModuleRegistry.pillHeight + RowLayout { + id: content + anchors.centerIn: parent + spacing: 3 + GlassButton { + implicitWidth: ModuleRegistry.pillHeight - 4 + implicitHeight: ModuleRegistry.pillHeight - 4 + text: MediaService.playing ? "Ⅱ" : "▶" + enabled: !!MediaService.player && MediaService.player.canTogglePlaying && MediaService.player.canControl + onClicked: MediaService.toggle() + Accessible.name: "Toggle playback" + } + GlassButton { + implicitWidth: 160 + implicitHeight: ModuleRegistry.pillHeight - 4 + contentItem: Text { + text: MediaService.title + color: Theme.text + elide: Text.ElideRight + verticalAlignment: Text.AlignVCenter + } + onClicked: ShellState.openSettings("media") + Accessible.name: "Media settings" + } + } +} diff --git a/quickshell/bar/modules/PluginModule.qml b/quickshell/bar/modules/PluginModule.qml new file mode 100644 index 0000000..49af3b5 --- /dev/null +++ b/quickshell/bar/modules/PluginModule.qml @@ -0,0 +1,120 @@ +import QtQuick +import Quickshell +import "../../components" +import "../../core" +import "../../services" +import "../../theme" +import "../../compat/omarchy/Ui" as OmarchyUi + +// Hosts an installed plugin's bar widget inside glassMxrph's own pill, so it +// sits in the bar like any built-in module (size, glass, spacing, per-screen +// layouts, cog options). The widget gets a PluginBarApi whose colors, font and +// size come from the glassMxrph theme; tooltips use the shared hover popout. +GlassPill { + id: root + property var barScreen + property var entry: ({}) + readonly property string pluginId: entry.id ? String(entry.id).slice("plugin:".length) : "" + readonly property bool noctalia: PluginService.ecosystem(pluginId) === "noctalia" + readonly property string source: PluginService.entryUrl(pluginId, "bar-widget") + readonly property var settings: PluginService.widgetSettings(pluginId, entry.options) + readonly property Item widget: loader.item as Item + // Not widget.visible: that reads false while this pill is still hidden. + // Omarchy widgets report emptiness through hasVisualContent instead. + readonly property var widgetObject: loader.item + readonly property bool shown: !!widget && (noctalia || widgetObject.hasVisualContent !== false) && widget.implicitWidth > 0 + implicitHeight: ModuleRegistry.pillHeight + implicitWidth: shown ? Math.ceil(widget.implicitWidth) + 8 : 0 + visible: implicitWidth > 0 + Behavior on implicitWidth { + NumberAnimation { + duration: Theme.duration + easing.type: Easing.OutCubic + } + } + + OmarchyUi.PluginBarApi { + id: api + pluginId: root.pluginId + moduleName: root.pluginId + shell: root.pluginId ? PluginService.shellFor(root.pluginId) : null + foreground: Theme.text + barForeground: Theme.text + background: Qt.alpha(Theme.surface, Theme.glassOpacity) + urgent: Theme.urgent + fontFamily: fontProbe.font.family + position: "top" + vertical: false + barSize: ModuleRegistry.pillHeight + transparent: true + foregroundAnimationEnabled: Theme.duration > 0 + activePopout: PluginService.activePopout + layoutConfig: root.settings + // Like Omarchy's bar: only a hovered widget shows its tooltip (plugins + // also call this whenever their data refreshes). + _showTooltip: (target, text) => { + if (text && target && target.tooltipHovered !== false) + PopoutState.hover(target, "tooltip", text); + } + _hideTooltip: target => PopoutState.unhover(target) + _requestPopout: owner => PluginService.requestPopout(owner) + _releasePopout: owner => PluginService.releasePopout(owner) + _switchPanelFrom: (owner, direction) => false + _targetBelongsToWindow: (target, window) => !!target && !!target.QsWindow && target.QsWindow.window === window + _moduleWidgets: id => PluginService.widgets[id] || [] + _run: command => Quickshell.execDetached(Array.isArray(command) ? command : ["sh", "-c", String(command)]) + } + + // The default UI font, which glassMxrph's own text uses. + Text { + id: fontProbe + visible: false + } + // Noctalia widgets get their pluginApi at creation, as in Noctalia, so their + // first bindings already see it. + onSourceChanged: load() + Component.onCompleted: load() + function load() { + if (!source) { + loader.source = ""; + return; + } + if (!noctalia) { + loader.source = source; + return; + } + loader.setSource(source, { + pluginApi: PluginService.noctaliaApi(pluginId), + screen: barScreen, + widgetId: pluginId, + section: entry.position || "right", + sectionWidgetIndex: 0, + sectionWidgetsCount: 1 + }); + } + Loader { + id: loader + anchors.centerIn: parent + height: parent.height + onLoaded: { + if (root.noctalia) { + // Noctalia v4 bar widget contract. + const napi = PluginService.noctaliaApi(root.pluginId); + if ("screen" in item) + item.screen = Qt.binding(() => root.barScreen); + if (napi) + napi.barWidget = item; + } else { + if ("bar" in item) + item.bar = api; + if ("moduleName" in item) + item.moduleName = root.pluginId; + if ("settings" in item) + item.settings = Qt.binding(() => root.settings); + } + PluginService.registerWidget(root.pluginId, item); + } + } + Component.onDestruction: if (loader.item) + PluginService.unregisterWidget(pluginId, loader.item) +} diff --git a/quickshell/bar/modules/SettingsModule.qml b/quickshell/bar/modules/SettingsModule.qml new file mode 100644 index 0000000..f67658f --- /dev/null +++ b/quickshell/bar/modules/SettingsModule.qml @@ -0,0 +1,12 @@ +import QtQuick +import "../../components" +import "../../core" +import "../../theme" +GlassIconButton { + text: "⚙" + implicitWidth: ModuleRegistry.pillHeight + implicitHeight: ModuleRegistry.pillHeight + onClicked: ShellState.toggleSettings() + rotation: ShellState.settingsOpen ? 60 * Theme.intensity : 0 + Behavior on rotation { NumberAnimation { duration: Theme.duration; easing.type: Easing.OutCubic } } +} diff --git a/quickshell/bar/modules/SystemModule.qml b/quickshell/bar/modules/SystemModule.qml new file mode 100644 index 0000000..8141ed1 --- /dev/null +++ b/quickshell/bar/modules/SystemModule.qml @@ -0,0 +1,18 @@ +import QtQuick +import "../../components" +import "../../core" +import "../../services" + +GlassButton { + id: root + property var barScreen + Component.onCompleted: ShellState.systemPills = ShellState.systemPills.concat([root]) + Component.onDestruction: ShellState.systemPills = ShellState.systemPills.filter(p => p !== root) + objectName: "systemPill" + readonly property bool volumeInBar: BarLayout.modulesFor(barScreen ? barScreen.name : "").some(m => m.id === "volume" && m.enabled) + implicitHeight: ModuleRegistry.pillHeight + text: volumeInBar ? "☷" : "☷ " + (AudioService.sink && AudioService.sink.audio ? (AudioService.sink.audio.muted ? "Muted" : Math.round(AudioService.sink.audio.volume * 100) + "%") : "System") + accented: ShellState.controlCenterOpen + onClicked: ShellState.toggleControlCenter() + Accessible.name: "Control Center" +} diff --git a/quickshell/bar/modules/TrayModule.qml b/quickshell/bar/modules/TrayModule.qml new file mode 100644 index 0000000..eca2bae --- /dev/null +++ b/quickshell/bar/modules/TrayModule.qml @@ -0,0 +1,25 @@ +pragma ComponentBehavior: Bound +import QtQuick +import "../../components" +import "../../services" +import "../../menus" +import "../../core" +Item { + id: root + property var barScreen + readonly property bool shown: TrayService.options.enabled && TrayService.items.length > 0 + implicitWidth: shown ? row.implicitWidth + 12 : 0 + implicitHeight: shown ? ModuleRegistry.pillHeight : 0 + visible: shown + // The whole pill is hover space: gaps between icons keep a hover menu open. + readonly property bool hovered: hover.hovered + HoverHandler { id: hover } + GlassPill { anchors.fill: parent; visible: TrayService.options.background === "pill" } + Row { + id: row; anchors.centerIn: parent; spacing: TrayService.options.spacing + Repeater { + model: root.shown ? TrayService.items : [] + TrayIcon { required property var modelData; trayItem: modelData; barScreen: root.barScreen; group: root } + } + } +} diff --git a/quickshell/bar/modules/VolumeModule.qml b/quickshell/bar/modules/VolumeModule.qml new file mode 100644 index 0000000..f1a8637 --- /dev/null +++ b/quickshell/bar/modules/VolumeModule.qml @@ -0,0 +1,70 @@ +import QtQuick +import "../../components" +import "../../core" +import "../../services" +import "../../theme" + +// Output volume: scroll to adjust, click to mute, right-click for audio settings. +GlassButton { + id: root + objectName: "volumePill" + readonly property var audio: AudioService.sink ? AudioService.sink.audio : null + readonly property bool muted: !!audio && audio.muted + readonly property real level: audio ? audio.volume : 0 + readonly property int step: ConfigService.ready ? ConfigService.data.osd.step : 5 + readonly property string glyph: !audio ? "󰖁" : muted || level === 0 ? "󰖁" : level < 0.34 ? "󰕿" : level < 0.67 ? "󰖀" : "󰕾" + enabled: !!audio + accented: false + implicitHeight: ModuleRegistry.pillHeight + // Width comes from the texts directly; the value reserves room for "100%" + // so the pill does not jitter while scrolling. + TextMetrics { + id: widest + font: value.font + text: "100%" + } + contentItem: Item { + implicitWidth: icon.implicitWidth + 6 + valueWidth + implicitHeight: Math.max(icon.implicitHeight, value.implicitHeight) + readonly property real valueWidth: Math.max(widest.advanceWidth, value.implicitWidth) + Text { + id: icon + anchors.left: parent.left + anchors.verticalCenter: parent.verticalCenter + text: Icons.available ? root.glyph : (root.muted ? "×" : "♪") + font.family: Icons.available ? Icons.family : "" + font.pixelSize: 15 + color: root.muted ? Theme.urgent : Theme.text + } + Text { + id: value + anchors.left: icon.right + anchors.leftMargin: 6 + anchors.verticalCenter: parent.verticalCenter + text: !root.audio ? "—" : root.muted ? "Off" : Math.round(root.level * 100) + "%" + font.pixelSize: 13 + font.features: { + "tnum": 1 + } + color: root.muted ? Theme.urgent : Theme.text + } + } + implicitWidth: icon.implicitWidth + 6 + Math.max(widest.advanceWidth, value.implicitWidth) + 28 + onClicked: AudioService.mute(false) + WheelHandler { + acceptedDevices: PointerDevice.Mouse | PointerDevice.TouchPad + onWheel: event => { + if (!root.audio) + return; + const delta = (event.angleDelta.y || -event.angleDelta.x) > 0 ? 1 : -1; + if (delta > 0) + root.audio.muted = false; + AudioService.volume(false, root.level + delta * root.step / 100); + } + } + TapHandler { + acceptedButtons: Qt.RightButton + onTapped: ShellState.openSettings("audio") + } + Accessible.name: "Volume " + (muted ? "muted" : Math.round(level * 100) + "%") +} diff --git a/quickshell/bar/modules/WorkspacesModule.qml b/quickshell/bar/modules/WorkspacesModule.qml new file mode 100644 index 0000000..c62131b --- /dev/null +++ b/quickshell/bar/modules/WorkspacesModule.qml @@ -0,0 +1,281 @@ +pragma ComponentBehavior: Bound +import QtQuick +import Quickshell.Hyprland +import "../../components" +import "../../theme" +import "../../services" +import "../../core" + +// Workspace switcher. Styles (bar.workspaces.style): numbers, roman numerals, +// dots (filled = occupied, ring = empty) and pacman (after Serpantinum: pellets +// for empty workspaces, ghosts for occupied ones, Pac-Man on the active one). +GlassPill { + id: root + property var barScreen + // Every bar follows the globally focused workspace, whichever monitor it is on. + readonly property int activeId: Hyprland.focusedWorkspace ? Hyprland.focusedWorkspace.id : 0 + // Workspaces shown on other monitors get a faint outline. + readonly property var visibleIds: Hyprland.monitors.values.map(m => m.activeWorkspace ? m.activeWorkspace.id : 0).filter(id => id > 0 && id !== activeId) + readonly property int count: ConfigService.data.bar.workspaces.count + readonly property string style: ConfigService.data.bar.workspaces.style || "numbers" + readonly property bool pacman: style === "pacman" + readonly property real pacmanScale: 0.95 + readonly property int slotWidth: style === "roman" ? 38 : style === "dots" ? 22 : style === "pacman" ? 24 : 32 + readonly property int slotHeight: height - 6 + readonly property int activeIndex: activeId >= 1 && activeId <= count ? activeId - 1 : -1 + width: count * slotWidth + 8 + height: ModuleRegistry.pillHeight + + function roman(value) { + const numerals = [[10, "X"], [9, "IX"], [5, "V"], [4, "IV"], [1, "I"]]; + let result = ""; + for (const [n, symbol] of numerals) + while (value >= n) { + result += symbol; + value -= n; + } + return result; + } + + Repeater { + model: root.pacman ? [] : root.visibleIds.filter(id => id <= root.count) + Rectangle { + required property int modelData + x: 4 + (modelData - 1) * root.slotWidth + y: 3 + width: root.slotWidth + height: root.slotHeight + radius: height / 2 + color: Qt.alpha(Theme.accent, 0.18) + border.width: 1 + border.color: Qt.alpha(Theme.accent, 0.6) + } + } + + // Sliding accent highlight (all styles except pacman, whose actor marks the active slot). + Rectangle { + visible: !root.pacman && root.activeIndex >= 0 + x: 4 + Math.max(0, root.activeIndex) * root.slotWidth + y: 3 + width: root.slotWidth + height: root.slotHeight + radius: height / 2 + color: Theme.accent + Behavior on x { + NumberAnimation { + duration: Theme.duration + easing.type: Easing.OutCubic + } + } + } + + Row { + x: 4 + y: 3 + Repeater { + model: root.count + Item { + id: slot + required property int index + readonly property var workspace: Hyprland.workspaces.values.find(w => w.id === index + 1) || null + readonly property bool active: root.activeIndex === index + readonly property bool occupied: !!workspace && workspace.toplevels.values.length > 0 + readonly property bool urgent: !!workspace && workspace.urgent + width: root.slotWidth + height: root.slotHeight + + // Numbers and roman numerals + Text { + visible: root.style === "numbers" || root.style === "roman" + anchors.centerIn: parent + anchors.verticalCenterOffset: slot.occupied && !slot.active ? -2 : 0 + text: root.style === "roman" ? root.roman(slot.index + 1) : slot.index + 1 + font.pixelSize: root.style === "roman" ? 11 : 12 + font.weight: root.style === "roman" ? Font.DemiBold : Font.Normal + font.letterSpacing: root.style === "roman" ? 0.5 : 0 + color: slot.urgent ? Theme.urgent : slot.active ? Theme.accentText : Theme.text + opacity: slot.active || slot.occupied ? 1 : 0.5 + } + Rectangle { + visible: (root.style === "numbers" || root.style === "roman") && slot.occupied && !slot.active + anchors.bottom: parent.bottom + anchors.bottomMargin: 1 + anchors.horizontalCenter: parent.horizontalCenter + width: 3 + height: 3 + radius: 2 + color: Theme.text + } + + // Dots: filled when occupied, ring when empty + Rectangle { + visible: root.style === "dots" + anchors.centerIn: parent + width: slot.active ? 9 : 8 + height: width + radius: width / 2 + color: slot.active ? Theme.accentText : slot.urgent ? Theme.urgent : slot.occupied ? Theme.text : Theme.transparent + border.width: slot.occupied || slot.active ? 0 : 1.5 + border.color: slot.urgent ? Theme.urgent : Qt.alpha(Theme.text, 0.6) + Behavior on width { + NumberAnimation { + duration: Theme.duration / 2 + } + } + } + + // Pacman: pellets (every second one a power pellet) and ghosts + Rectangle { + visible: root.pacman && !slot.occupied + anchors.centerIn: parent + width: Math.round((slot.index % 2 === 1 ? 9 : 6) * root.pacmanScale) + height: width + radius: width / 2 + color: slot.urgent ? Theme.urgent : Qt.alpha(Theme.text, 0.75) + scale: slot.active ? 0 : pelletArea.containsMouse ? 1.25 : 1 + Behavior on scale { + NumberAnimation { + duration: 180 + easing.type: Easing.OutBack + } + } + } + // Created only for occupied slots in pacman style: each Canvas holds + // its own 2D context and texture. + Loader { + active: root.pacman && slot.occupied + anchors.centerIn: parent + sourceComponent: Canvas { + id: ghost + width: Math.round(16 * root.pacmanScale) + height: Math.round(17 * root.pacmanScale) + scale: slot.active ? 0 : pelletArea.containsMouse ? 1.15 : 1 + Behavior on scale { + NumberAnimation { + duration: 220 + easing.type: Easing.OutBack + } + } + // Pupils look towards Pac-Man. + readonly property real look: root.activeIndex > slot.index ? 1 : root.activeIndex < slot.index && root.activeIndex >= 0 ? -1 : 0 + readonly property color body: slot.urgent ? Theme.urgent : Theme.textSecondary + onLookChanged: requestPaint() + onBodyChanged: requestPaint() + onVisibleChanged: if (visible) + requestPaint() + Component.onCompleted: requestPaint() + onPaint: { + const ctx = getContext("2d"); + ctx.reset(); + const w = width - 2, h = height - 2, r = w / 2, x0 = 1, y0 = 1; + const bottom = y0 + h, wave = h * 0.14; + ctx.beginPath(); + ctx.moveTo(x0, y0 + r); + ctx.arc(x0 + r, y0 + r, r, Math.PI, 0, false); + ctx.lineTo(x0 + w, bottom); + ctx.quadraticCurveTo(x0 + w * 5 / 6, bottom - wave, x0 + w * 2 / 3, bottom); + ctx.quadraticCurveTo(x0 + w / 2, bottom - wave, x0 + w / 3, bottom); + ctx.quadraticCurveTo(x0 + w / 6, bottom - wave, x0, bottom); + ctx.closePath(); + ctx.fillStyle = body; + ctx.fill(); + const eye = w * 0.17, ex1 = x0 + w * 0.32, ex2 = x0 + w * 0.68, ey = y0 + r * 0.95; + ctx.beginPath(); + ctx.arc(ex1, ey, eye, 0, 2 * Math.PI); + ctx.arc(ex2, ey, eye, 0, 2 * Math.PI); + ctx.fillStyle = "#ffffff"; + ctx.fill(); + const shift = look * eye * 0.35; + ctx.beginPath(); + ctx.arc(ex1 + shift, ey, eye * 0.55, 0, 2 * Math.PI); + ctx.arc(ex2 + shift, ey, eye * 0.55, 0, 2 * Math.PI); + ctx.fillStyle = "#11111b"; + ctx.fill(); + } + } + } + MouseArea { + id: pelletArea + anchors.fill: parent + hoverEnabled: root.pacman + cursorShape: Qt.PointingHandCursor + onClicked: Hyprland.dispatch("workspace " + (slot.index + 1)) + } + } + } + } + + // Pac-Man glides to the active workspace, chomps, and faces its direction of travel. + Canvas { + id: pac + property int previous: root.activeIndex + property bool facingLeft: false + property real mouth: 0.18 + visible: root.pacman && root.activeIndex >= 0 + width: Math.round(20 * root.pacmanScale) + height: width + y: 3 + (root.slotHeight - height) / 2 + x: 4 + Math.max(0, root.activeIndex) * root.slotWidth + (root.slotWidth - width) / 2 + Behavior on x { + NumberAnimation { + duration: Math.max(Theme.duration, 1) * 1.4 + easing.type: Easing.OutQuint + } + } + transform: Scale { + origin.x: pac.width / 2 + xScale: pac.facingLeft ? -1 : 1 + } + Connections { + target: root + function onActiveIndexChanged() { + if (root.activeIndex < pac.previous) + pac.facingLeft = true; + else if (root.activeIndex > pac.previous) + pac.facingLeft = false; + pac.previous = root.activeIndex; + if (Theme.intensity > 0) + chomp.restart(); + } + } + SequentialAnimation { + id: chomp + loops: 3 + NumberAnimation { + target: pac + property: "mouth" + to: 0.02 + duration: 80 + easing.type: Easing.InOutQuad + } + NumberAnimation { + target: pac + property: "mouth" + to: 0.18 + duration: 80 + easing.type: Easing.InOutQuad + } + } + readonly property color body: Theme.accentVivid + onMouthChanged: requestPaint() + onBodyChanged: requestPaint() + onVisibleChanged: if (visible) + requestPaint() + Component.onCompleted: requestPaint() + onPaint: { + const ctx = getContext("2d"); + ctx.reset(); + const r = width / 2, m = mouth * Math.PI; + ctx.beginPath(); + ctx.moveTo(r, r); + ctx.arc(r, r, r - 0.5, m, 2 * Math.PI - m, false); + ctx.closePath(); + ctx.fillStyle = body; + ctx.fill(); + ctx.beginPath(); + ctx.arc(r + r * 0.12, r - r * 0.46, Math.max(1.5, r * 0.14), 0, 2 * Math.PI); + ctx.fillStyle = "#11111b"; + ctx.fill(); + } + } +} diff --git a/quickshell/compat/noctalia/Assets/Fonts/tabler/noctalia-tabler-icons.ttf b/quickshell/compat/noctalia/Assets/Fonts/tabler/noctalia-tabler-icons.ttf new file mode 100644 index 0000000..1327521 Binary files /dev/null and b/quickshell/compat/noctalia/Assets/Fonts/tabler/noctalia-tabler-icons.ttf differ diff --git a/quickshell/compat/noctalia/Assets/Fonts/tabler/tabler-icons-license.txt b/quickshell/compat/noctalia/Assets/Fonts/tabler/tabler-icons-license.txt new file mode 100644 index 0000000..f08aa1c --- /dev/null +++ b/quickshell/compat/noctalia/Assets/Fonts/tabler/tabler-icons-license.txt @@ -0,0 +1,16 @@ +Tabler Licenses - Detailed Usage Rights and Guidelines + +This is a legal agreement between you, the Purchaser, and Tabler. Purchasing or downloading of any Tabler product (Tabler Admin Template, Tabler Icons, Tabler Emails, Tabler Illustrations), constitutes your acceptance of the terms of this license, Tabler terms of service and Tabler private policy. + +Tabler Admin Template and Tabler Icons License* +Tabler Admin Template and Tabler Icons are available under MIT License. + +Copyright (c) 2018-2025 Tabler + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +See more at Tabler Admin Template MIT License See more at Tabler Icons MIT License \ No newline at end of file diff --git a/quickshell/compat/noctalia/Assets/Translations/en.json b/quickshell/compat/noctalia/Assets/Translations/en.json new file mode 100644 index 0000000..24dca05 --- /dev/null +++ b/quickshell/compat/noctalia/Assets/Translations/en.json @@ -0,0 +1,2265 @@ +{ + "actions": { + "clear-history": "Clear history", + "close-app": "Close {app}", + "connect-vpn": "Connect to {name}", + "cycle-visualizer": "Cycle visualizer", + "disable-bluetooth": "Disable Bluetooth", + "disable-dnd": "Disable Do Not Disturb", + "disable-wifi": "Disable Wi-Fi", + "disconnect-vpn": "Disconnect {name}", + "dock-settings": "Dock settings", + "enable-bluetooth": "Enable Bluetooth", + "enable-dnd": "Enable Do Not Disturb", + "enable-wifi": "Enable Wi-Fi", + "launcher-settings": "Launcher settings", + "lower-to-bottom": "Lower to bottom", + "open-calendar": "Open calendar", + "open-display-settings": "Display settings", + "open-launcher": "Open launcher", + "open-settings": "Open settings", + "raise-to-top": "Raise to top", + "random-wallpaper": "Random wallpaper", + "run-custom-command": "Run custom command", + "show-active-only": "Show active only", + "show-all": "Show all", + "toggle-mute": "Toggle mute", + "widget-settings": "Widget settings" + }, + "authentication": { + "error": "Authentication error", + "failed": "Authentication failed" + }, + "bar": { + "active-window": { + "colorize-icons-description": "Apply theme colors to active window icon.", + "hide-mode-description": "Controls how the widget behaves when no window is active.", + "scrolling-mode-description": "Control when text scrolling is enabled for long window titles.", + "show-app-icon-description": "Display the application icon next to the window title.", + "show-app-icon-label": "Show app icon", + "show-app-text-description": "Display the window title.", + "show-app-text-label": "Show window title" + }, + "audio-visualizer": { + "color-name-description": "Select the color for the visualizer.", + "color-name-label": "Fill color", + "height-description": "Custom component width.", + "hide-when-idle-description": "When enabled, the visualizer is hidden unless a player is actively playing.", + "hide-when-idle-label": "Hide when no media is playing", + "width-description": "Custom component width." + }, + "battery": { + "device-default": "Default (Display Device)", + "device-description": "Select which battery device to display.", + "device-label": "Battery device", + "display-mode-description": "Choose how the battery is displayed in the bar.", + "display-mode-graphic": "Graphical battery", + "display-mode-graphic-clean": "Graphical battery (no %)", + "display-mode-icon-always": "Icon - Always show %", + "display-mode-icon-hover": "Icon - Show on hover", + "display-mode-icon-only": "Icon only", + "hide-if-idle-description": "Hide the widget when the battery is not charging or discharging.", + "hide-if-idle-label": "Hide when idle", + "hide-if-not-detected-description": "Hide the widget when no battery is detected on the system.", + "hide-if-not-detected-label": "Hide when not detected", + "low-battery-threshold-label": "Low battery warning threshold", + "show-noctalia-performance-description": "Display the Noctalia performance mode toggle inside the battery panel.
Disables shadows and animations in Noctalia to reduce resource usage.", + "show-noctalia-performance-label": "Show Noctalia Performance toggle", + "show-power-profile-description": "Display the power profile selection inside the battery panel.", + "show-power-profile-label": "Show power profile controls" + }, + "brightness": { + "apply-all-description": "Change brightness for every monitor when using the scroll wheel.", + "apply-all-label": "Apply scroll changes to all monitors" + }, + "clock": { + "clock-display-description": "Customize your clock's display by adding tokens from the list below. To use the 12-hour format, you must include the 'AP' token.", + "clock-display-label": "Clock display", + "custom-font-description": "Select a custom font for the clock display.", + "custom-font-label": "Custom font", + "custom-font-placeholder": "Select custom font...", + "custom-font-search-placeholder": "Search fonts...", + "horizontal-bar-description": "Tip: Use \\n to create a line break.", + "horizontal-bar-label": "Horizontal bar", + "preview": "Preview", + "tooltip-format-description": "Format string for the tooltip shown when hovering over the clock. Leave empty to use the default tooltip.", + "tooltip-format-label": "Tooltip format", + "use-custom-font-description": "Override the default font selection with a custom font for the clock.", + "use-custom-font-label": "Use custom font", + "use-monospaced-font-description": "When enabled, the clock will use the monospaced font.", + "use-monospaced-font-label": "Use monospaced font", + "vertical-bar-description": "Use a space to separate each part onto a new line.", + "vertical-bar-label": "Vertical bar" + }, + "control-center": { + "browse-file": "Browse File", + "browse-library": "Browse Library", + "color-selection-description": "Apply theme colors to icons.", + "enable-colorization-description": "Enable colorization for icon, applying theme colors.", + "enable-colorization-label": "Enable colorization", + "icon-description": "Select an icon from the library or a custom file.", + "select-custom-icon": "Select a custom icon", + "use-distro-logo-description": "Use your distribution's logo instead of a custom icon.", + "use-distro-logo-label": "Use distro logo instead of icon" + }, + "custom-button": { + "collapse-condition-description": "If the output text matches this value, the button will collapse.", + "collapse-condition-label": "Collapse condition", + "color-selection-description": "Apply theme colors to icon and text.", + "default-tooltip": "Custom button, configure in settings", + "display-command-output-description": "Enter a command to run at a regular interval. The first line of its output will be displayed as text.", + "display-command-output-label": "Display command output", + "display-command-output-stream-description": "Enter a command to run continuously.", + "dynamic-text": "Dynamic text", + "enable-colorization-description": "Enable colorization for the custom button icon and text, applying theme colors.", + "enable-colorization-label": "Enable colorization", + "general-tooltip-text-description": "Custom text to display in the button's tooltip.", + "general-tooltip-text-label": "Custom tooltip text", + "hide-mode-always-expanded": "Always expanded", + "hide-mode-description": "Controls widget visibility when the command has no output.", + "hide-mode-expand-with-output": "Expand when has output", + "hide-mode-label": "Hide mode", + "hide-mode-max-transparent": "Max expanded but transparent", + "icon-color-selection-description": "Apply theme colors to icons.", + "icon-description": "Select an icon from the library.", + "icon-position-bottom": "Bottom", + "icon-position-description": "Select where the icon appears relative to the text.", + "icon-position-label": "Icon position", + "icon-position-left": "Left", + "icon-position-right": "Right", + "icon-position-top": "Top", + "ipc-identifier-description": "Unique identifier for IPC commands. Use this identifier with 'qs -c noctalia-shell ipc call cb [action] [identifier]' to control this button via IPC.", + "ipc-identifier-label": "IPC Identifier", + "left-click-description": "Command to execute when the button is left-clicked.", + "left-click-label": "Left click", + "left-click-update-text": "Update displayed text on left-click", + "max-text-length-horizontal-description": "Maximum number of characters to show in horizontal bar (0 to hide text).", + "max-text-length-horizontal-label": "Max text length (horizontal)", + "max-text-length-vertical-description": "Maximum number of characters to show in vertical bar (0 to hide text).", + "max-text-length-vertical-label": "Max text length (vertical)", + "middle-click-description": "Command to execute when the button is middle-clicked.", + "middle-click-label": "Middle click", + "middle-click-update-text": "Update displayed text on middle-click", + "parse-json-description": "Parse the command output as a JSON object to dynamically set text and icon.", + "parse-json-label": "Parse output as JSON", + "refresh-interval-description": "Interval in milliseconds.", + "refresh-interval-label": "Refresh interval", + "right-click-description": "Command to execute when the button is right-clicked.", + "right-click-label": "Right click", + "right-click-update-text": "Update displayed text on right-click", + "show-exec-tooltip-description": "Show tooltips with command details (left/right/middle click, wheel).", + "show-exec-tooltip-label": "Show command tooltips", + "show-icon-description": "Toggles the visibility of the widget's icon.", + "show-icon-label": "Show icon", + "show-text-tooltip-description": "Show tooltips with the output from the text command.", + "show-text-tooltip-label": "Show dynamic text tooltips", + "tab-actions": "Actions", + "tab-icon": "Icon", + "tab-text": "Text Command", + "text-color-selection-description": "Apply theme colors to text.", + "text-stream-description": "Streamed lines from the command will be displayed as text on the button.", + "text-stream-label": "Stream", + "wheel-description": "Command to execute when the scroll wheel is used.
Use $delta for the scroll wheel delta in the command.", + "wheel-down": "Scroll down", + "wheel-down-description": "Command to execute when the scroll wheel is scrolled down.", + "wheel-down-label": "Wheel down command", + "wheel-label": "Scroll wheel", + "wheel-mode-separate-description": "Enable separate commands for wheel up and down.", + "wheel-mode-separate-label": "Separate wheel commands", + "wheel-up": "Scroll up", + "wheel-up-description": "Command to execute when the scroll wheel is scrolled up.", + "wheel-up-label": "Wheel up command", + "wheel-update-text": "Update displayed text on scroll" + }, + "keyboard-layout": { + "show-icon-description": "Display the keyboard layout icon." + }, + "lock-keys": { + "hide-when-off-description": "Hide the indicator when the key is not active.", + "hide-when-off-label": "Hide when off", + "show-caps-lock-description": "Display Caps Lock status.", + "show-caps-lock-label": "Caps Lock", + "show-num-lock-description": "Display Num Lock status.", + "show-num-lock-label": "Num Lock", + "show-scroll-lock-description": "Display Scroll Lock status.", + "show-scroll-lock-label": "Scroll Lock" + }, + "media-mini": { + "compact-mode-description": "Enable a space-saving layout for the media player panel.", + "compact-mode-label": "Compact mode", + "hide-mode-description": "Controls how the widget behaves when no media is playing.", + "max-width-description": "Sets the maximum horizontal size of the widget. The widget will shrink to fit shorter content.", + "no-active-player": "No active player", + "panel-section-description": "Configure the appearance and behavior of the media player panel.", + "panel-section-label": "Media player panel", + "scrolling-mode-description": "Control when text scrolling is enabled for long track titles.", + "scrolling-mode-label": "Scrolling mode", + "show-album-art-description": "Display the album artwork for the currently playing track.", + "show-album-art-label": "Show album art", + "show-artist-first-description": "Display artist - title instead of title - artist.", + "show-artist-first-label": "Show artist first", + "show-progress-ring-description": "Display a circular progress indicator showing track progress.", + "show-progress-ring-label": "Show progress ring", + "show-visualizer-description": "Display an audio visualizer when music is playing.", + "show-visualizer-label": "Show visualizer", + "use-fixed-width-description": "When enabled, the widget will always use the maximum width instead of dynamically adjusting to content.", + "use-fixed-width-label": "Use fixed width", + "visualizer-type-description": "Choose the style of audio visualizer to display.", + "visualizer-type-label": "Visualizer type" + }, + "notification-history": { + "hide-widget-when-zero-description": "Hide the notification icon when there are no notifications.", + "hide-widget-when-zero-label": "Hide icon when no notifications", + "hide-widget-when-zero-unread-description": "Hide the notification icon when there are no unread notifications.", + "hide-widget-when-zero-unread-label": "Hide icon when no unread notifications", + "show-unread-badge-description": "Display a badge showing the number of unread notifications.", + "show-unread-badge-label": "Show unread badge", + "unread-badge-color-description": "Select the color for the unread notification badge.", + "unread-badge-color-label": "Unread badge color" + }, + "section-editor": { + "placeholder": "Select a widget to add...", + "search-placeholder": "Search widget..." + }, + "spacer": { + "width-description": "Spacing width in pixels." + }, + "system-monitor": { + "compact-mode-description": "Display stats as mini bar charts instead of text values. Prevents layout shifting.", + "compact-mode-label": "Compact mode", + "cpu-cores-description": "Display CPU cores usage individually.", + "cpu-cores-label": "CPU Cores", + "cpu-frequency-description": "Display the current CPU clock speed in GHz.", + "cpu-frequency-label": "Show CPU frequency", + "cpu-temperature-description": "Show CPU temperature readings if available.", + "cpu-temperature-label": "CPU temperature", + "cpu-usage-description": "Display current CPU usage percentage.", + "cpu-usage-label": "CPU usage", + "disk-path-description": "Select which disk mount point to monitor.", + "disk-path-label": "Disk path", + "gpu-temperature-description": "Show GPU temperature readings if available.", + "load-average-description": "Display system load average.", + "load-average-label": "Load average", + "memory-percentage-description": "Show memory usage as a percentage instead of absolute values.", + "memory-percentage-label": "Memory as percentage", + "memory-usage-description": "Display current RAM usage information.", + "memory-usage-label": "Memory usage", + "network-traffic-description": "Display network upload and download speeds.", + "network-traffic-label": "Network traffic", + "storage-as-percentage-description": "Show disk space as percentage instead of absolute values.", + "storage-as-percentage-label": "Disk as percentage", + "storage-available-description": "Shows how much disk space is available instead of how much is used.", + "storage-available-label": "Disk space available", + "storage-usage-description": "Show disk space usage information.", + "storage-usage-label": "Storage usage", + "swap-usage-description": "Show swap memory usage.", + "swap-usage-label": "Swap usage", + "use-monospace-font-description": "Use monospace font for consistent character width.", + "use-monospace-font-label": "Monospace font", + "use-padding-description": "Pads the text values with leading spaces to prevent layout shifting.", + "use-padding-description-disabled-monospace-font": "A monospace font is needed for this feature.", + "use-padding-description-disabled-vertical": "Vertical taskbar does not support padding text.", + "use-padding-label": "Pad text" + }, + "taskbar": { + "colorize-icons-description": "Apply theme colors to taskbar icons.", + "hide-mode-description": "Controls how the widget behaves when there are no matching windows.", + "hide-mode-label": "Hiding mode", + "icon-scale-description": "Sets the scaling factor for taskbar icons.", + "icon-scale-label": "Icon scaling", + "max-width-description": "Maximum width of the taskbar as a percentage of screen width.", + "max-width-label": "Maximum width", + "only-active-workspaces-description": "Show only apps from active workspaces.", + "only-active-workspaces-label": "Only from active workspaces", + "only-same-monitor-description": "Show only apps from the monitor where the bar is located.", + "only-same-monitor-label": "Only from same monitor", + "show-pinned-apps-description": "Show pinned apps from the dock in the taskbar.", + "show-pinned-apps-label": "Show pinned apps", + "show-title-description": "Display window titles in the taskbar.", + "show-title-description-disabled": "Vertical taskbar does not support showing titles.", + "show-title-label": "Show title", + "smart-width-description": "Automatically adjust entry width based on the number of entries.", + "smart-width-label": "Smart width", + "title-width-description": "Set the width of window titles in the taskbar (in pixels).", + "title-width-label": "Title width", + "title-width-reset-tooltip": "Reset title width" + }, + "tray": { + "chevron-color-description": "Apply theme colors to the drawer chevron icon.", + "chevron-color-label": "Chevron color", + "colorize-icons-description": "Apply theme colors to tray icons.", + "colorize-icons-label": "Colorize icons", + "drawer-enabled-description": "When enabled, unpinned tray items are shown in a drawer panel.
When disabled, all tray items are shown inline.", + "drawer-enabled-label": "Enable drawer", + "hide-passive-description": "When enabled, tray items with 'Passive' status will be hidden.", + "hide-passive-label": "Hide passive items" + }, + "volume": { + "display-mode-description": "Choose how you'd like this value to appear." + }, + "workspace": { + "character-count-description": "Number of characters to display from workspace names (1-10).", + "character-count-label": "Character count", + "empty-color-description": "Set the background color for empty workspaces.", + "empty-color-label": "Empty workspace color", + "enable-scrollwheel-description": "Switch between workspaces using the mouse scroll wheel.", + "enable-scrollwheel-label": "Scroll to switch workspaces", + "focused-color-description": "Set the background color for the focused workspace.", + "focused-color-label": "Focused workspace color", + "follow-focused-screen-description": "Display workspaces from the currently focused screen, rather than the screen where the bar is located.", + "follow-focused-screen-label": "Follow focused screen", + "font-weight-description": "Set the visual weight for text within workspace.", + "font-weight-label": "Font weight", + "grouped-border-opacity-description": "Set the opacity level for workspace container borders.", + "grouped-border-opacity-label": "Border opacity", + "hide-unoccupied-description": "Don't display workspaces without windows.", + "hide-unoccupied-label": "Hide unoccupied", + "label-mode-description": "Choose how workspace labels are displayed.", + "label-mode-label": "Label mode", + "occupied-color-description": "Set the background color for occupied workspaces.", + "occupied-color-label": "Occupied workspace color", + "pill-size-description": "Adjust the size of workspace pills.", + "pill-size-label": "Pill size", + "reverse-scrolling-description": "Reverse the direction of workspace switching when scrolling.", + "reverse-scrolling-label": "Reverse scrolling", + "show-applications-description": "Display application icons inside each workspace.", + "show-applications-hover-description": "Display application icons inside each workspace when the workspace is hovered.", + "show-applications-hover-label": "Show applications when hovered", + "show-applications-label": "Show applications", + "show-badge-description": "Show the workspace number badge in grouped mode.", + "show-badge-label": "Show workspace badge", + "show-labels-only-when-occupied-description": "Only show workspace labels when they contain windows.", + "show-labels-only-when-occupied-label": "Show labels only when occupied", + "unfocused-icons-opacity-description": "Set the opacity level for unfocused app icons.", + "unfocused-icons-opacity-label": "Unfocused icons opacity" + } + }, + "battery": { + "all-batteries": "All batteries (combined)", + "battery-health": "Battery health", + "battery-level": "Battery level", + "capacity-level": "Capacity: {level}", + "charging-rate": "Charging rate: {rate} W", + "discharging-rate": "Discharging rate: {rate} W", + "health": "Health: {percent}%", + "inhibit-idle-description": "Keeps the system awake.", + "no-battery-detected": "No battery detected", + "plugged-in": "Plugged in", + "power-profile": "Power profile", + "time-left": "Time left: {time}", + "time-until-full": "Time until full: {time}" + }, + "bluetooth": { + "panel": { + "available-devices": "Available devices", + "blocked": "Blocked", + "connected-devices": "Connected devices", + "device-address": "Device address", + "disabled": "Bluetooth is disabled", + "discoverable": "Discoverable", + "enable-message": "Enable Bluetooth to see available devices.", + "known-devices": "Known devices", + "no-devices": "No devices available", + "paired-devices": "Paired devices", + "pairing-mode": "Make sure your device is in pairing mode.", + "scanning": "Scanning for devices...", + "signal-text-excellent": "Signal: Excellent", + "signal-text-fair": "Signal: Fair", + "signal-text-good": "Signal: Good", + "signal-text-poor": "Signal: Poor", + "signal-text-unknown": "Signal: Unknown", + "signal-text-very-poor": "Signal: Very poor" + } + }, + "changelog": { + "error": { + "fetch-failed": "Unable to load changelog data. Please try again later.", + "rate-limit": "GitHub rate limit exceeded. Please try again in a few minutes." + }, + "panel": { + "buttons-discord": "Join our Discord", + "buttons-dismiss": "OK", + "buttons-feedback": "Give feedback", + "empty": "Release notes are not available yet.", + "highlight-title": "Highlights", + "released": "Released on {date}", + "subtitle-fresh": "Thanks for installing Noctalia! Here is what’s included in this build.", + "subtitle-updated": "Updated from {previousVersion}", + "title": "What's new in {version}", + "version": "Version {version}", + "version-new-user": "Fresh install" + } + }, + "common": { + "actions": "Actions", + "active": "Active", + "add": "Add", + "appearance": "Appearance", + "apply": "Apply", + "auto-connect": "Auto-connect", + "automation": "Automation", + "available": "Available", + "back": "Back", + "battery": "Battery", + "behavior": "Behavior", + "bluetooth": "Bluetooth", + "brightness": "Brightness", + "browse": "Browse", + "calendar": "Calendar", + "calendar-panel": "Calendar Panel", + "cancel": "Cancel", + "cards": "Cards", + "charging": "Charging", + "clear": "Clear", + "clipboard": "Clipboard", + "close": "Close", + "color-muted": "Muted", + "colors": "Colors", + "command": "Command", + "confirm": "Confirm", + "connect": "Connect", + "connected": "Connected", + "connecting": "Connecting...", + "continue": "Continue", + "contributors": "Contributors", + "copied-to-clipboard": "Copied to clipboard", + "countdown": "Countdown", + "customize": "Customize", + "date": "Date", + "default": "Default", + "delete": "Delete", + "devices": "Devices", + "disabled": "Disabled", + "discharging": "Discharging", + "disconnect": "Disconnect", + "disconnected": "Disconnected", + "disconnecting": "Disconnecting...", + "display-mode": "Display mode", + "documentation": "Documentation", + "download": "Download", + "duration": "Duration", + "dysfunctional": "Dysfunctional", + "edit": "Edit", + "enabled": "Enabled", + "error": "Error", + "ethernet": "Ethernet", + "events": "Events", + "execute": "Execute", + "faithful": "Faithful", + "focus": "Focus", + "font-weight-bold": "Bold", + "font-weight-light": "Light", + "font-weight-medium": "Medium", + "font-weight-regular": "Regular", + "font-weight-semibold": "Semi-bold", + "frequency": "Frequency", + "gateway": "Gateway", + "general": "General", + "height": "Height", + "hibernate": "Hibernate", + "history": "History", + "icon": "Icon", + "idle": "Idle", + "info": "Info", + "input": "Input", + "install": "Install", + "installed": "Installed", + "interface": "Interface", + "internet": "Internet", + "keybind": "Keybind", + "language": "Language", + "loading": "Loading...", + "local": "Local", + "location": "Location", + "lock": "Lock", + "logout": "Logout", + "look": "Look", + "margins": "Margins", + "media": "Media", + "media-player": "Media Player", + "memory": "Memory", + "monitors": "Monitors", + "move-down": "Move down", + "move-up": "Move up", + "network": "Network", + "next": "Next", + "night-light": "Night Light", + "no": "No", + "no-results": "No results", + "no-summary": "No summary", + "none": "None", + "not-found": "Not found", + "notifications": "Notifications", + "official": "Official", + "on-surface": "On Surface", + "output": "Output", + "pair": "Pair", + "paired": "Paired", + "pairing": "Pairing...", + "panels": "Panels", + "password": "Password", + "pause": "Pause", + "performance": "Performance", + "pin": "Pin", + "play": "Play", + "polling": "Polling", + "position": "Position", + "previous": "Previous", + "primary": "Primary", + "random": "Random", + "reboot": "Reboot", + "reboot-to-uefi": "Reboot to UEFI", + "record": "Start recording", + "refresh": "Refresh", + "required": "(required)", + "reset": "Reset", + "reset-to-default": "Reset to Default", + "result-count": "{count} result", + "result-count-plural": "{count} results", + "resume": "Resume", + "save": "Save", + "scanning": "Scanning...", + "screen-corners": "Screen Corners", + "search": "Search", + "second": "{count} second", + "second-plural": "{count} seconds", + "secondary": "Secondary", + "security": "Security", + "select": "Select", + "select-color": "Select color", + "select-color-description": "Apply theme colors for emphasis.", + "select-icon-color": "Select icon color", + "select-text-color": "Select text color", + "settings": "Settings", + "shortcuts": "Shortcuts", + "shutdown": "Shutdown", + "signal": "Signal", + "sound": "Sound", + "sources": "Sources", + "start": "Start", + "stop": "Stop", + "supporters": "Supporters", + "suspend": "Suspend", + "templates": "Templates", + "tertiary": "Tertiary", + "test": "Test", + "thresholds": "Thresholds", + "title": "Title", + "toast": "Toast", + "trusted": "Trusted", + "uninstall": "Uninstall", + "unknown": "Unknown", + "unpair": "Unpair", + "unpin": "Unpin", + "update": "Update", + "upload": "Upload", + "username": "Username", + "userspace-reboot": "Userspace Reboot", + "version": "Version", + "vibrant": "Vibrant", + "visualizer": "Visualizer", + "volume": "Volume", + "volumes": "Volumes", + "wallpaper": "Wallpaper", + "weather": "Weather", + "weather-loading": "Loading weather...", + "weather-no-location": "Set a location in Settings to see weather", + "week": "Week", + "widgets": "Widgets", + "width": "Width", + "wifi": "Wi-Fi", + "windows": "Windows", + "yes": "Yes" + }, + "control-center": { + "power-profile": { + "tooltip-action": "Power Profile", + "tooltip-disabled": "Install power-profiles-daemon to use power profiles" + }, + "wifi": { + "label-disconnected": "Wi-Fi disconnected", + "label-ethernet": "Ethernet" + } + }, + "display-modes": { + "always-hide": "Always hide", + "always-show": "Always show", + "force-open": "Force open", + "on-hover": "On hover" + }, + "hide-modes": { + "auto-hide": "Auto-hide", + "hidden": "Hide when empty", + "idle": "Hide when idle", + "non-exclusive": "Non-exclusive", + "transparent": "Transparent when empty", + "visible": "Always visible" + }, + "launcher": { + "categories": { + "all": "All", + "audiovideo": "Audio & Video", + "chat": "Chat", + "development": "Development", + "education": "Education", + "emoji-activity": "Activity", + "emoji-animals": "Animals", + "emoji-flags": "Flags", + "emoji-food": "Food & Drink", + "emoji-nature": "Nature", + "emoji-objects": "Objects", + "emoji-people": "People & Body", + "emoji-recent": "Recent", + "emoji-symbols": "Symbols", + "emoji-travel": "Travel & Places", + "game": "Games", + "graphics": "Graphics", + "misc": "Misc", + "office": "Office", + "pinned": "Pinned", + "system": "System", + "webbrowser": "Web Browser" + }, + "providers": { + "applications": "Applications", + "calculator": "Calculator", + "calculator-deprecated": "The >calc command is deprecated and will be removed soon. Please type math expressions directly in search instead.", + "calculator-description": "Calculator — evaluate mathematical expressions", + "calculator-enter-expression": "Enter a mathematical expression", + "calculator-press-enter-to-copy": "Press Enter to copy result", + "clipboard": "Clipboard history", + "clipboard-clear-description": "Clear all clipboard history", + "clipboard-clear-description-full": "Remove all items from clipboard history", + "clipboard-clear-history": "Clear clipboard history", + "clipboard-delete": "Delete clipboard entry", + "clipboard-history-disabled": "Clipboard history disabled", + "clipboard-history-disabled-description": "Enable clipboard history in settings or install cliphist", + "clipboard-loading": "Loading clipboard history...", + "clipboard-search-description": "Search clipboard history", + "command-description": "Run shell commands", + "emoji": "Emoji picker", + "emoji-loading": "Loading emojis...", + "emoji-loading-description": "Please wait", + "emoji-no-recent": "No recent emojis yet", + "emoji-search-description": "Search and copy emojis", + "settings-search-description": "Search and navigate to settings", + "windows-search-description": "Search and focus open windows" + } + }, + "lock-screen": { + "authenticating": "Authenticating...", + "password": "Enter your password...", + "restart": "Restart", + "shut-down": "Shut down" + }, + "notifications": { + "panel": { + "click-to-collapse": "Click to collapse", + "click-to-expand": "Click to expand", + "description": "Your notifications will show up here as they arrive.", + "no-notifications": "No notifications" + }, + "range": { + "earlier": "Earlier", + "today": "Today", + "yesterday": "Yesterday" + }, + "time": { + "diff-d": "1 day ago", + "diff-dd": "{diff} days ago", + "diff-h": "1 hour ago", + "diff-hh": "{diff} hours ago", + "diff-m": "1 minute ago", + "diff-mm": "{diff} minutes ago", + "now": "now" + } + }, + "options": { + "bar": { + "density-comfortable": "Comfortable", + "density-compact": "Compact", + "density-default": "Default", + "density-mini": "Mini", + "density-spacious": "Spacious", + "display-mode-always-visible": "Always Visible", + "type-floating": "Floating", + "type-framed": "Framed", + "type-simple": "Simple" + }, + "control-center": { + "quick-settings-style-classic": "Classic", + "quick-settings-style-modern": "Modern" + }, + "frame-rates-fps": "{fps} FPS", + "launcher-density": { + "comfortable": "Comfortable", + "compact": "Compact", + "default": "Default" + }, + "launcher-view-mode": { + "grid": "Grid", + "list": "List" + }, + "notification-density": { + "compact": "Compact", + "default": "Default" + }, + "scrolling-modes": { + "always": "Scroll always", + "hover": "Scroll on hover", + "never": "Never scroll" + }, + "session-menu-grid-layout": { + "grid": "Grid", + "single-row": "Single row" + }, + "settings-panel-mode": { + "attached": "Panel attached to bar", + "centered": "Centered panel", + "window": "Separate window" + }, + "visualizer-types": { + "linear": "Linear", + "mirrored": "Mirrored", + "wave": "Wave" + }, + "visualizer-visibility": { + "with-background": "With background only" + }, + "workspace-labels": { + "index": "Index", + "index-and-name": "Index and name", + "name": "Name" + } + }, + "panels": { + "about": { + "become-supporter": "Become a supporter", + "changelog": "View changelog", + "changelog-on-startup": "Show changelog on update", + "changelog-on-startup-desc": "Automatically show the changelog when Noctalia is updated", + "contributors-description": "Shout-out to our {count} awesome contributor!", + "contributors-description-plural": "Shout-out to our {count} awesome contributors!", + "copy-info": "Copy info", + "debug-disabled": "Debug mode disabled", + "debug-enabled": "Debug mode enabled", + "info-copied": "Info copied to clipboard", + "noctalia-available": "Available:", + "noctalia-desc": "A sleek and minimal desktop shell thoughtfully crafted for Wayland, built with Quickshell.", + "noctalia-git-commit": "Git commit:", + "noctalia-installed-version": "Installed version:", + "noctalia-latest-version": "Latest version:", + "noctalia-qs-version": "Noctalia QS version:", + "noctalia-title": "Noctalia Shell", + "privacy-policy": "Privacy policy", + "support": "Support us", + "supporter-badge": "Supporter", + "supporters-desc": "A huge thank you to our amazing supporter!", + "supporters-desc-plural": "A huge thank you to our {count} amazing supporters!", + "supporters-loading": "Loading supporters...", + "system-board": "Board:", + "system-cpu": "CPU:", + "system-disk": "Disk:", + "system-gpu": "GPU:", + "system-host": "Host:", + "system-install-hint": "Install fastfetch to view system information", + "system-kernel": "Kernel:", + "system-loading": "Loading system info...", + "system-memory": "Memory:", + "system-monitor": "Monitor:", + "system-not-installed": "fastfetch is not installed", + "system-os": "OS:", + "system-packages": "Packages:", + "system-product": "Product:", + "system-title": "System Information", + "system-uptime": "Uptime:", + "system-wm": "WM:", + "telemetry-data-copied": "Telemetry data copied to clipboard", + "telemetry-desc": "Help improve Noctalia by sharing anonymous system info (screen resolution, compositor, distro). Sent once at startup, no tracking, data auto-deleted after 30 days.", + "telemetry-enabled": "Send anonymous system information", + "telemetry-show-data": "View data", + "telemetry-title": "Privacy", + "title": "About", + "up-to-date": "You're up to date!", + "update-available": "Update available", + "view-commit": "View commit on GitHub" + }, + "audio": { + "devices-desc": "Configure available audio input and output devices.", + "devices-input-device-description": "Select the desired audio input device.", + "devices-input-device-label": "Input device", + "devices-output-device-description": "Select the desired audio output device.", + "devices-output-device-label": "Output device", + "devices-title": "Audio devices", + "external-mixer-description": "Enter the command or application path to launch when activating the external audio mixer feature.", + "external-mixer-label": "External audio mixer command", + "external-mixer-placeholder": "pwvucontrol || pavucontrol", + "media-desc": "Set your preferred and ignored media applications.", + "media-excluded-player-description": "Add keywords for players you want the system to ignore. Each keyword should be on a new line.", + "media-excluded-player-label": "Excluded player", + "media-excluded-player-placeholder": "type substring and press +", + "media-frame-rate-description": "Higher rates are smoother but use more resources.", + "media-frame-rate-label": "Frame rate", + "media-primary-player-description": "Enter a keyword to identify your main player.", + "media-primary-player-label": "Primary player", + "media-primary-player-placeholder": "e.g. spotify, vlc, mpv", + "media-scrolling-speed-description": "Time in seconds for the title to scroll from start to end.", + "media-scrolling-speed-label": "Scrolling speed", + "media-scrolling-title-description": "Enable continuous scrolling for long media titles.", + "media-scrolling-title-label": "Scrolling title", + "media-title": "Media players", + "on-middle-clicked-description": "Command to execute when the button is middle-clicked.", + "panel-applications-empty": "No applications are currently playing audio", + "spectrum-mirrored-description": "Mirror the spectrum so low frequencies are in the center. When off, low frequencies are on the left and high on the right.", + "spectrum-mirrored-label": "Mirror spectrum", + "title": "Audio", + "visualizer-type-description": "Choose a visualization type for media playback.", + "visualizer-type-label": "Visualization type", + "volumes-desc": "Adjust volume controls and audio levels.", + "volumes-feedback-sound-file-description": "Path to the sound file played when changing volume.", + "volumes-feedback-sound-file-label": "Volume feedback sound file", + "volumes-feedback-sound-file-select-title": "Select volume feedback sound file", + "volumes-input-volume-description": "Microphone input volume level.", + "volumes-mute-input-description": "Mute the default audio input (microphone).", + "volumes-mute-input-label": "Mute audio input", + "volumes-mute-output-description": "Mute the system's main audio output.", + "volumes-mute-output-label": "Mute audio output", + "volumes-output-volume-description": "System-wide volume level.", + "volumes-step-size-description": "Adjust the step size for volume changes (scroll wheel, keyboard shortcuts).", + "volumes-step-size-label": "Volume step size", + "volumes-volume-feedback-description": "Play a feedback sound when adjusting volume.", + "volumes-volume-feedback-label": "Play volume feedback sound", + "volumes-volume-overdrive-description": "Allow raising volume above 100%. May not be supported by all hardware.", + "volumes-volume-overdrive-label": "Allow volume overdrive" + }, + "bar": { + "appearance-auto-hide-delay-description": "Time before bar hides after mouse leaves", + "appearance-auto-hide-delay-label": "Hide Delay", + "appearance-auto-hide-exclusive-note": "Note: Exclusive zone is automatically disabled when auto-hide is active", + "appearance-auto-show-delay-description": "Time before bar shows when mouse enters edge", + "appearance-auto-show-delay-label": "Show Delay", + "appearance-background-opacity-description": "Set the background opacity specifically for the bar.", + "appearance-background-opacity-label": "Bar background opacity", + "appearance-capsule-color-description": "Choose a color for bar capsules, or use none for the default surface color.", + "appearance-capsule-color-label": "Capsule color", + "appearance-capsule-opacity-description": "Set the opacity level for widget backgrounds when capsule is shown.", + "appearance-capsule-opacity-label": "Capsule opacity", + "appearance-content-padding-description": "Adjust the padding between bar edges and widgets.", + "appearance-content-padding-label": "Content padding", + "appearance-density-description": "Adjust the bar's padding for a compact or spacious look.", + "appearance-density-label": "Bar density", + "appearance-desc": "Customize the bar's appearance and position.", + "appearance-display-mode-description": "Choose when the bar is visible.", + "appearance-enable-exclusion-zone-inset-description": "Reduce the exclusion zone by 1 physical pixel so flush windows bleed perfectly under the bar edge.", + "appearance-enable-exclusion-zone-inset-label": "Inset exclusion zone", + "appearance-floating-description": "Display the bar as a floating 'pill'.", + "appearance-floating-label": "Floating bar", + "appearance-font-scale-description": "Adjust the font size scale for text displayed in the bar.", + "appearance-font-scale-label": "Font scale", + "appearance-frame-radius": "Inner Radius", + "appearance-frame-settings-description": "Adjust frame thickness and inner corner radius", + "appearance-frame-settings-label": "Frame Settings", + "appearance-frame-thickness": "Thickness", + "appearance-hide-on-overview-description": "Hide the bar and close panels when the compositor overview is active.", + "appearance-hide-on-overview-label": "Hide bar on overview", + "appearance-margins-description": "Adjust the margins around the floating bar.", + "appearance-margins-horizontal": "Horizontal Margin ", + "appearance-margins-vertical": "Vertical Margin", + "appearance-outer-corners-description": "Display outwardly curved corners on the bar.", + "appearance-outer-corners-label": "Outer corners", + "appearance-position-description": "Choose where to place the bar on the screen.", + "appearance-position-label": "Bar position", + "appearance-show-capsule-description": "Show widget backgrounds.", + "appearance-show-capsule-label": "Show capsule", + "appearance-show-on-workspace-switch-description": "Automatically show the bar briefly when the workspace changes.", + "appearance-show-on-workspace-switch-label": "Show bar on workspace switch", + "appearance-show-outline-description": "Displays a visible border around every widget.", + "appearance-show-outline-label": "Show widget outlines", + "appearance-type-description": "Choose the style of the bar: Simple, Floating or Framed.", + "appearance-type-label": "Bar type", + "appearance-use-separate-opacity-description": "Enable to use a separate opacity value for the bar background.", + "appearance-use-separate-opacity-label": "Use separate bar opacity", + "appearance-widget-spacing-description": "Adjust the spacing between each widget in the bar.", + "appearance-widget-spacing-label": "Widget spacing", + "behavior-middle-click-command-description": "Command to execute on middle click.", + "behavior-middle-click-command-label": "Middle click command", + "behavior-middle-click-command-placeholder": "niri msg action toggle-overview", + "behavior-middle-click-description": "Choose what middle click does on empty areas of the bar.", + "behavior-middle-click-follow-mouse-description": "Open the selected middle-click panel at the cursor position.", + "behavior-middle-click-follow-mouse-label": "Middle click follow mouse", + "behavior-middle-click-label": "Bar middle click action", + "behavior-right-click-command-description": "Command to execute on right click.", + "behavior-right-click-command-label": "Right click command", + "behavior-right-click-command-placeholder": "notify-send \"Right click\"", + "behavior-right-click-description": "Choose what right click does on empty areas of the bar.", + "behavior-right-click-follow-mouse-description": "Open the selected right-click panel at the cursor position.", + "behavior-right-click-follow-mouse-label": "Right click follow mouse", + "behavior-right-click-label": "Bar right click action", + "behavior-wheel-wrap-description": "When enabled, scrolling continues from the last item to the first.", + "behavior-wheel-wrap-label": "Wrap around", + "behavior-workspace-scroll-description": "Choose what the mouse wheel does on empty areas of the bar.", + "behavior-workspace-scroll-label": "Bar mouse wheel action", + "behavior-workspace-scroll-option-content": "Content", + "behavior-workspace-scroll-option-workspace": "Workspace", + "monitor-configure-widgets": "Configure widgets", + "monitor-override-settings": "Override global settings", + "monitor-override-settings-description": "Use custom settings for this monitor.", + "monitor-reset-all": "Reset all", + "monitor-widgets-title": "Widget Configuration - {monitor}", + "monitors-desc": "Show bar on specific monitors. Defaults to all if none are chosen.", + "monitors-desc-new": "Configure which monitors display the bar and customize settings per monitor.", + "monitors-title": "Monitors display", + "title": "Bar", + "tray-blacklist-description": "Add tray exclusion rules, supports wildcards (*).", + "tray-blacklist-label": "Blacklist", + "tray-blacklist-placeholder": "e.g. nm-applet, Fcitx*", + "tray-pin-application": "Pin Application", + "tray-unpin-application": "Unpin Application", + "use-global-widgets": "Use global widgets", + "widgets-desc": "Drag widgets to change their order. Use the right-click menu to transfer widgets between sections or remove them.", + "widgets-title": "Widgets positioning" + }, + "color-scheme": { + "color-source-use-wallpaper-colors-description": "Generate color schemes from your wallpaper. Automatically extracts colors to create a cohesive theme.", + "color-source-use-wallpaper-colors-label": "Use wallpaper colors", + "dark-mode-mode-description": "Enables automatic switching between Light and Dark Mode.", + "dark-mode-mode-label": "Dark Mode schedule", + "dark-mode-mode-manual": "Manual", + "dark-mode-mode-off": "Off", + "dark-mode-switch-description": "Switches to a darker theme for easier viewing at night.", + "delete-error-description": "Failed to delete {scheme}", + "delete-error-title": "Delete failed", + "delete-success-description": "Successfully deleted {scheme}", + "delete-success-title": "Color scheme deleted", + "download-button": "Download more", + "download-downloading": "Downloading...", + "download-empty": "No color schemes available", + "download-error-api-error": "API error: {status}", + "download-error-description": "Failed to download {scheme}", + "download-error-download-failed": "Download failed with exit code: {code}", + "download-error-invalid-response": "Invalid API response format", + "download-error-no-files": "No files found for scheme", + "download-error-parse-failed": "Failed to parse API response: {error}", + "download-error-rate-limit": "GitHub API rate limit exceeded", + "download-error-title": "Download failed", + "download-fetching": "Fetching available color schemes...", + "download-success-description": "Successfully downloaded {scheme}", + "download-success-title": "Color scheme downloaded", + "download-title": "Download Color Schemes", + "method-description": { + "content": "Material Design scheme with high-fidelity color extraction that closely matches the source content's actual colors.", + "dysfunctional": "Like Faithful but picks the second most dominant color family as primary.", + "faithful": "Attempts to stay close to the source color while still generating a harmonious palette.", + "fruit-salad": "Material Design scheme that produces a playful, vibrant palette with diverse and varied hues.", + "monochrome": "Material Design scheme using a single-hue grayscale with minimal chromatic content.", + "muted": "Generates softer, desaturated tones for a calm and understated appearance.", + "rainbow": "Material Design scheme that generates colors across the full spectrum for maximum color diversity.", + "tonal-spot": "Material Design default algorithm. Creates balanced palettes using tonal variations of the source color.", + "vibrant": "Maximizes color saturation for bold, eye-catching palettes with vivid tones." + }, + "predefined-desc": "Choose from a collection of predefined color schemes.", + "predefined-generate-templates-label": "Generate templates for predefined schemes", + "predefined-title": "Predefined color schemes", + "sync-gsettings-description": "Match the system theme to the active light or dark variant.", + "sync-gsettings-label": "Sync system theme", + "templates-desc": "Apply colors to external applications.", + "templates-filter-description": "Show templates from a specific category.", + "templates-filter-label": "Filter by category", + "templates-misc-description": "Create your own templates.", + "templates-misc-label": "Advanced", + "templates-misc-user-templates-description": "Only enable if you know what you are doing — refer to our online documentation.", + "templates-misc-user-templates-label": "Enable user templates", + "templates-none-detected": "None detected", + "templates-write-path": "Writes: {filepath}", + "title": "Color Scheme", + "wallpaper-method-description": "Choose your favorite palette generation method.", + "wallpaper-method-label": "Palette generation method", + "wallpaper-monitor-source-description": "Select which monitor to use for extracting wallpaper colors.", + "wallpaper-monitor-source-label": "Color generation source" + }, + "connections": { + "authentication-required": "Authentication required", + "bluetooth-auto-connect-description": "Automatically connect to trusted paired devices when Bluetooth is enabled.", + "bluetooth-auto-connect-label": "Auto-connect paired devices", + "bluetooth-devices-unnamed": "Unnamed devices are not shown.", + "bluetooth-discoverable": "This device is discoverable as {hostName} while this settings tab is open.", + "bluetooth-rssi-polling-description": "Periodically sample RSSI for connected devices via bluetoothctl. May not be available for all devices; uses minimal resources when enabled.", + "bluetooth-rssi-polling-interval-description": "Configure how often to update signal strength for connected devices.", + "bluetooth-rssi-polling-interval-label": "Polling interval", + "bluetooth-rssi-polling-label": "Bluetooth signal polling", + "disable-discoverability-description": "Hide your device from nearby Bluetooth devices.", + "disable-discoverability-label": "Disable device visibility", + "hide-unnamed-devices-description": "Hide devices that appear only as Bluetooth addresses.", + "hide-unnamed-devices-label": "Hide unnamed devices", + "pin-instructions": "Please enter the PIN code displayed on your device.", + "title": "Connections", + "wifi-header-text": "Use Wi-Fi to see available networks and connect to the internet." + }, + "control-center": { + "cards-desc": "Customize which controls appear in the control center and in what order.", + "desc": "Configure the control center panel positioning and behavior.", + "open-at-mouse-description": "When right-clicking an empty area of the bar, open the control center near the cursor. When disabled, the position setting above is used instead.", + "open-at-mouse-label": "Open at cursor on right-click", + "position-description": "Choose where the control center panel appears when opened.", + "shortcuts-custom-button-command-description": "The command to execute when the button is clicked.", + "shortcuts-custom-button-enable-on-state-logic-description": "Enable a second icon and 'hot' state based on a check command.", + "shortcuts-custom-button-enable-on-state-logic-label": "Enable on-state logic", + "shortcuts-custom-button-icon-description": "Select an icon from the library.", + "shortcuts-custom-button-on-clicked-label": "Left click command", + "shortcuts-custom-button-on-middle-clicked-description": "Command to execute when the button is middle-clicked.", + "shortcuts-custom-button-on-state-command-description": "Command to execute to check if the button should be in the 'on' state. Returns 0 for on, non-zero for off.", + "shortcuts-custom-button-on-state-command-label": "On-state check command", + "shortcuts-custom-button-on-state-icon-description": "The icon for the button when it's in the 'on' state.", + "shortcuts-custom-button-on-state-icon-label": "On-state icon", + "shortcuts-custom-button-state-checks-add": "Add state check", + "shortcuts-custom-button-state-checks-command": "Command to execute for this state check", + "shortcuts-custom-button-state-checks-label": "State checks", + "shortcuts-custom-button-state-checks-remove": "Remove", + "shortcuts-custom-button-tooltip-description": "The tooltip to show when hovering over the button.", + "shortcuts-custom-button-tooltip-label": "Tooltip", + "shortcuts-title": "Shortcuts widgets", + "system-monitor-disk-path-description": "Select which disk mount point the system monitor card in the control center should monitor.", + "system-monitor-disk-path-label": "System monitor disk path", + "title": "Control Center" + }, + "desktop-widgets": { + "clock-enabled-description": "Show a clock widget on the desktop.", + "clock-enabled-label": "Enable clock widget", + "clock-format-label": "Format", + "clock-height-description": "Height of the clock widget in pixels.", + "clock-height-label": "Height", + "clock-minimal-mode-description": "Use a minimal clock display with time and date.", + "clock-minimal-mode-label": "Minimal mode", + "clock-rounded-corners-description": "Use rounded corners for the widget background.", + "clock-rounded-corners-label": "Rounded corners", + "clock-show-background-description": "Show the background container for the clock widget.", + "clock-show-background-label": "Show background", + "clock-show-date-description": "Display the current date below the time.", + "clock-show-date-label": "Show date", + "clock-show-seconds-description": "Display seconds in the time.", + "clock-show-seconds-label": "Show seconds", + "clock-style-analog": "Analog", + "clock-style-binary": "Binary", + "clock-style-description": "Choose the clock display style.", + "clock-style-digital": "Digital", + "clock-style-label": "Clock style", + "clock-style-minimal": "Minimal", + "clock-width-description": "Width of the clock widget in pixels.", + "cpu-intensive-note": "Widgets marked with ! use more CPU and should be enabled mindfully.", + "edit-mode-button-label": "Enter edit mode", + "edit-mode-controls-explanation": "Left-click & drag: Move or resize the widget.\nRight-click: Open the context menu options.", + "edit-mode-description": "Enable edit mode to move and reposition desktop widgets. When enabled, widgets show a drag outline and can be repositioned.", + "edit-mode-exit-button": "Exit edit mode", + "edit-mode-grid-snap-label": "Grid snap", + "edit-mode-grid-snap-scale-label": "Grid snap scale", + "edit-mode-label": "Edit mode", + "enabled-description": "Enable or disable desktop widgets entirely.", + "enabled-label": "Enable desktop widgets", + "general-desc": "Configure widgets that appear on your desktop.", + "general-title": "Desktop widgets", + "media-player-enabled-description": "Show a media player widget on the desktop.", + "media-player-enabled-label": "Enable media player widget", + "media-player-rounded-corners-description": "Enable rounded corners on the widget edges.", + "media-player-show-album-art-description": "Show the album artwork and track information (title and artist).", + "media-player-show-album-art-label": "Show album art & title", + "media-player-show-background-description": "Show the background container.", + "media-player-show-buttons-description": "Show media control buttons (play/pause, previous, next).", + "media-player-show-buttons-label": "Show buttons", + "media-player-show-visualizer-description": "Show the audio visualizer overlay.", + "media-player-visualizer-type-description": "Choose a visualization type.", + "overview-enabled-description": "Show desktop widgets while the compositor overview is open.", + "overview-enabled-label": "Show in overview", + "system-stat-layout-bottom": "Bottom", + "system-stat-layout-description": "Choose how the legend is displayed relative to the graph.", + "system-stat-layout-label": "Layout", + "system-stat-layout-side": "Side", + "system-stat-rounded-corners-description": "Use rounded corners for the widget background.", + "system-stat-rounded-corners-label": "Rounded corners", + "system-stat-show-background-description": "Show the background container for the system stat widget.", + "system-stat-show-background-label": "Show background", + "system-stat-stat-type-description": "Choose which system statistic to display.", + "system-stat-stat-type-label": "Statistic Type", + "title": "Desktop Widgets", + "weather-enabled-description": "Show a weather widget on the desktop.", + "weather-enabled-label": "Enable weather widget", + "weather-show-background-description": "Show the background container for the weather widget." + }, + "display": { + "monitors-backlight-device-auto-option": "Default", + "monitors-backlight-device-description": "Select a backlight device for this output.", + "monitors-backlight-device-label": "Backlight device", + "monitors-brightness-step-description": "Adjust the step size for brightness changes (scroll wheel and keyboard shortcuts).", + "monitors-brightness-step-label": "Brightness step size", + "monitors-brightness-unavailable-ddc-disabled": "Brightness control unavailable. Enable \"External brightness support\" to control this display's brightness.", + "monitors-brightness-unavailable-generic": "Brightness control is not available for this display.", + "monitors-desc": "Adjust settings brightness for each display.", + "monitors-enforce-minimum-description": "Solves the problem of backlight completely turning off on some displays at 0% brightness.", + "monitors-enforce-minimum-label": "Enforce minimum brightness (1%)", + "monitors-external-brightness-description": "Enable DDCUtil support for controlling brightness on external displays via DDC/CI protocol.", + "monitors-external-brightness-label": "External brightness support", + "monitors-global-brightness-description": "Adjust brightness for all monitors at once.", + "monitors-global-brightness-label": "All monitors", + "monitors-title": "Per-monitor settings", + "night-light-auto-schedule-description": "Based on the sunset and sunrise time in {location} — recommended.", + "night-light-auto-schedule-label": "Automatic scheduling", + "night-light-desc": "Reduce blue light emission to help you sleep better and reduce eye strain.", + "night-light-enable-description": "Apply a warm color filter to reduce blue light emission.", + "night-light-enable-label": "Enable Night Light", + "night-light-force-activation-description": "Ignores the schedule and applies the night filter immediately.", + "night-light-force-activation-label": "Force activation", + "night-light-manual-schedule-description": "Set custom times for sunrise and sunset.", + "night-light-manual-schedule-label": "Manual scheduling", + "night-light-manual-schedule-select-start": "Select start time", + "night-light-manual-schedule-select-stop": "Select stop time", + "night-light-manual-schedule-sunrise": "Sunrise time", + "night-light-manual-schedule-sunset": "Sunset time", + "night-light-temperature-day": "Day", + "night-light-temperature-day-description": "Controls the temperature during daytime.", + "night-light-temperature-description": "Set the color warmth for nighttime and daytime.", + "night-light-temperature-label": "Color temperature", + "night-light-temperature-night": "Night", + "night-light-temperature-night-description": "Controls the temperature during nighttime.", + "title": "Display" + }, + "dock": { + "appearance-background-opacity-description": "Adjust the dock's background opacity.", + "appearance-border-radius-description": "Adjust the dock's border radius.", + "appearance-border-radius-label": "Border radius", + "appearance-colorize-icons-description": "Apply theme colors to dock app icons (non-focused apps only).", + "appearance-colorize-icons-label": "Colorize icons", + "appearance-dead-opacity-description": "Adjust the opacity of app icons that are not running.", + "appearance-dead-opacity-label": "Dead opacity", + "appearance-desc": "Customize the dock's behavior and appearance.", + "appearance-display-auto-hide": "Auto hide", + "appearance-display-description": "Choose how the dock behaves.", + "appearance-display-exclusive": "Exclusive", + "appearance-dock-indicator-description": "Show a small indicator when the dock is hidden.", + "appearance-dock-indicator-label": "Dock indicator", + "appearance-floating-distance-description": "Set the distance between the dock and the edge of the screen.", + "appearance-floating-distance-label": "Dock floating distance", + "appearance-group-apps-description": "Group multiple windows from the same app into one dock entry.", + "appearance-group-apps-label": "Group same apps", + "appearance-group-click-action-cycle": "Cycle windows", + "appearance-group-click-action-description": "Choose what left-click does for grouped apps.", + "appearance-group-click-action-label": "Grouped app click action", + "appearance-group-click-action-list": "Open window list", + "appearance-group-context-menu-mode-description": "Choose how the context menu behaves for grouped apps.", + "appearance-group-context-menu-mode-extended": "Extended", + "appearance-group-context-menu-mode-label": "Grouped app menu mode", + "appearance-group-context-menu-mode-list": "Window list", + "appearance-group-indicator-style-description": "Choose how grouped running indicators display focused window state.", + "appearance-group-indicator-style-dots": "Dots", + "appearance-group-indicator-style-label": "Grouped indicator style", + "appearance-group-indicator-style-number": "Number", + "appearance-hide-show-speed-description": "Adjust the speed of the dock hide/show animation.", + "appearance-hide-show-speed-label": "Hide/show speed", + "appearance-icon-size-description": "Adjust the overall size of the dock.", + "appearance-icon-size-label": "Dock size", + "appearance-inactive-indicators-description": "Display indicator pills for all apps, not just the currently active one.", + "appearance-inactive-indicators-label": "Running indicators", + "appearance-indicator-color-description": "Choose the color of the hidden dock indicator.", + "appearance-indicator-color-label": "Indicator color", + "appearance-indicator-opacity-description": "Adjust the opacity of the hidden dock indicator.", + "appearance-indicator-opacity-label": "Indicator opacity", + "appearance-indicator-thickness-description": "Toggle a thicker hidden dock indicator (6px instead of 3px).", + "appearance-indicator-thickness-label": "Thicker indicator", + "appearance-launcher-icon-description": "Choose the icon used for the dock launcher.", + "appearance-launcher-icon-label": "Launcher icon", + "appearance-launcher-position-description": "Choose where the launcher icon appears in the dock.", + "appearance-launcher-position-end": "End", + "appearance-launcher-position-label": "Launcher position", + "appearance-launcher-position-start": "Start", + "appearance-launcher-use-distro-logo-description": "Use your distribution logo as the dock launcher icon.", + "appearance-launcher-use-distro-logo-label": "Use distro logo instead of icon", + "appearance-pinned-static-description": "Always push pinned app icons to the left in static order.", + "appearance-pinned-static-label": "Static pinned apps", + "appearance-position-description": "Choose where the dock appears on screen.", + "appearance-position-label": "Position", + "appearance-show-launcher-icon-description": "Show the application launcher icon in the dock.", + "appearance-show-launcher-icon-label": "Show app launcher", + "appearance-sit-on-frame-description": "Align the dock inside the frame border instead of sitting on top.", + "appearance-sit-on-frame-label": "Dock sits on frame", + "appearance-type-attached": "Attached", + "appearance-type-description": "Choose between a floating pill or a static bar attached to the edge.", + "appearance-type-floating": "Floating", + "appearance-type-label": "Dock style", + "enabled-description": "Show or hide the dock entirely.", + "enabled-label": "Enable dock", + "monitors-desc": "Show dock on specific monitors. Defaults to all if none are chosen.", + "monitors-only-same-monitor-description": "Show only apps from the monitor where the dock is located.", + "monitors-only-same-monitor-label": "Only apps from same monitor", + "monitors-title": "Monitor display", + "title": "Dock" + }, + "general": { + "copy-settings": "Copy settings", + "fonts-default-description": "Main font used throughout the interface.", + "fonts-default-label": "Default font", + "fonts-default-placeholder": "Select default font...", + "fonts-default-scale-description": "Increase or decrease the size of the standard text.", + "fonts-default-scale-label": "Default font size", + "fonts-default-search-placeholder": "Search font...", + "fonts-desc": "Choose the fonts used throughout the interface.", + "fonts-monospace-description": "Monospaced font used for numbers and stats display.", + "fonts-monospace-label": "Monospaced font", + "fonts-monospace-placeholder": "Select monospace font...", + "fonts-monospace-scale-description": "Increase or decrease the size of the monospaced text.", + "fonts-monospace-scale-label": "Monospaced font size", + "fonts-monospace-search-placeholder": "Search monospace font...", + "fonts-title": "Fonts", + "keybinds-conflict-description": "The key combination is already assigned to {action}.", + "keybinds-conflict-title": "Keybind conflict", + "keybinds-description": "Configure global navigation keys for panels and launcher.", + "keybinds-down": "Move down", + "keybinds-enter": "Confirm / Action", + "keybinds-escape": "Close / Back", + "keybinds-left": "Move left", + "keybinds-modifier-description": "Shortcuts must include a modifier key (Ctrl or Alt).", + "keybinds-modifier-title": "Modifier required", + "keybinds-remove": "Remove / Delete", + "keybinds-right": "Move right", + "keybinds-title": "Navigation keybinds", + "keybinds-up": "Move up", + "language-desc": "Choose your preferred language for the application.", + "language-select-auto-detect": "Automatic", + "language-select-description": "Select the language used in the application's interface.", + "language-select-label": "Application language", + "launch-setup-wizard": "Setup wizard", + "profile-desc": "Edit your user details and avatar.", + "profile-picture-description": "Your profile picture that appears throughout the interface.", + "profile-picture-label": "Profile picture", + "profile-select-avatar": "Select avatar image", + "profile-title": "Profile", + "profile-tooltip": "Profile picture", + "reverse-scrolling-description": "Reverse the interpreted scroll direction", + "reverse-scrolling-label": "Reverse scrolling", + "screen-corners-desc": "Customize screen corner rounding and visual effects.", + "screen-corners-radius-description": "Adjust the rounded corners of the screen.", + "screen-corners-radius-label": "Screen corners radius", + "screen-corners-radius-reset": "Reset screen corners radius", + "screen-corners-show-corners-description": "Display rounded corners on the edge of the screen.", + "screen-corners-show-corners-label": "Show screen corners", + "screen-corners-solid-black-description": "Use solid black instead of the bar background color.", + "screen-corners-solid-black-label": "Solid black corners", + "screen-corners-title": "Screen corners", + "settings-copied": "Settings copied to clipboard", + "smooth-scrolling-description": "Animate list scrolling for a smoother wheel experience.", + "smooth-scrolling-label": "Smooth scrolling", + "tab-basics": "Basics", + "tab-keybinds": "Keybinds" + }, + "hooks": { + "color-generation-description": "Command to be executed when color generation completes (e.g. after wallpaper-based theming).", + "color-generation-label": "Colors generated", + "color-generation-placeholder": "e.g. notify-send \"Colors\" \"Generated\"", + "info-command-info-description": "• Commands are executed via shell (sh -lc)
• Commands run in background (detached)
• Test buttons execute with current values", + "info-parameters-description": "• Wallpaper hook: $1 = wallpaper path, $2 = screen name, $3 = theme (dark/light)
• Color generation hook: $1 = theme (dark/light)
• Theme toggle hook: $1 = true/false (Dark Mode state)
• Screen lock/unlock hooks: $1 = lock/unlock (screen lock state)
• Performance mode hooks: No parameters
• Session hook: $1 = action (shutdown/reboot)", + "info-parameters-label": "Available parameters", + "noctalia-started-description": "Command to execute when Noctalia has finished loading.", + "noctalia-started-label": "Noctalia started", + "noctalia-started-placeholder": "e.g. notify-send 'Noctalia Loaded'", + "performance-mode-disabled-description": "Command to be executed when Noctalia performance mode is disabled.", + "performance-mode-disabled-label": "Performance mode disabled", + "performance-mode-disabled-placeholder": "e.g. notify-send \"Performance\" \"Mode disabled\"", + "performance-mode-enabled-description": "Command to be executed when Noctalia performance mode is enabled.", + "performance-mode-enabled-label": "Performance mode enabled", + "performance-mode-enabled-placeholder": "e.g., notify-send \"Performance\" \"Mode enabled\"", + "screen-lock-description": "Command to be executed when the screen is locked.", + "screen-lock-label": "Screen locked", + "screen-lock-placeholder": "e.g. notify-send \"Screen\" \"Locked\"", + "screen-unlock-description": "Command to be executed when the lock screen is unlocked.", + "screen-unlock-label": "Screen unlocked", + "screen-unlock-placeholder": "e.g. notify-send \"Screen\" \"Unlocked\"", + "session-description": "Command to be executed before shutdown or reboot. Receives action type as $1 (shutdown/reboot).", + "session-label": "Session end", + "session-placeholder": "e.g. notify-send \"Session\" \"$1\"", + "system-hooks-desc": "Configure commands to be executed when system events occur.", + "system-hooks-enable-description": "Enable or disable all hook commands.", + "system-hooks-enable-label": "Enable hooks", + "system-hooks-title": "System hooks", + "theme-changed-description": "Command to be executed when theme toggles between Dark and Light Mode.", + "theme-changed-label": "Theme changed", + "theme-changed-placeholder": "e.g. notify-send \"Theme\" \"Toggled\"", + "title": "Hooks", + "wallpaper-changed-description": "Command to be executed when wallpaper changes.", + "wallpaper-changed-label": "Wallpaper changed", + "wallpaper-changed-placeholder": "e.g. notify-send \"Wallpaper\" \"Changed\"" + }, + "idle": { + "custom-add": "Add command", + "custom-description": "Run a shell command after a period of inactivity.", + "custom-entry-command": "Command", + "custom-entry-delete": "Delete", + "custom-entry-edit": "Edit Custom Command", + "custom-entry-name": "Name", + "custom-entry-name-placeholder": "e.g. Turn off lights", + "custom-entry-new": "New Custom Command", + "custom-entry-timeout": "Inactivity time", + "custom-entry-timeout-format": "{count} second", + "custom-entry-timeout-format-plural": "{count} seconds", + "custom-entry-unnamed": "Unnamed command", + "custom-label": "Custom idle commands", + "enable-description": "Automatically turn off the screen, lock, or suspend after a period of inactivity.", + "enable-label": "Enable idle management", + "fade-duration-description": "Seconds for the fade-to-black animation before each action fires. Any mouse movement cancels the fade.", + "fade-duration-label": "Fade duration", + "lock-description": "Seconds of inactivity before the lock screen activates.", + "lock-label": "Lock screen", + "resume-command-label": "Resume command", + "screen-off-description": "Seconds of inactivity before monitors are turned off.", + "screen-off-label": "Turn off screen", + "status-description": "Idle time as reported by the compositor.", + "status-label": "Idle time", + "suspend-description": "Seconds of inactivity before the system suspends.", + "tab-behavior": "Behavior", + "tab-custom": "Custom", + "timeouts-description": "Set to 0 to disable a stage. Timeouts are paused while Keep Awake is active.", + "timeouts-label": "Timeouts", + "title": "Idle", + "unavailable": "Native idle monitoring is not available on this compositor." + }, + "indicator": { + "default-value": "Default: {value}", + "system-default": "System Default" + }, + "launcher": { + "clipboard-desc": "Access and manage your clipboard history from the launcher.", + "execute-desc": "Configure how applications are launched.", + "execute-title": "Execution", + "settings-annotation-tool-description": "Command to run when clicking the annotate button in clipboard history. The image will be piped to this command.", + "settings-annotation-tool-label": "Annotation tool", + "settings-annotation-tool-placeholder": "e.g. 'gradia', 'satty -f -'", + "settings-auto-paste-description": "Automatically paste the selected clipboard item. Requires wtype.", + "settings-auto-paste-label": "Auto paste", + "settings-clip-chips-description": "Show a tab bar to filter clipboard history by type (Images, Links, Files, Code, etc).", + "settings-clip-chips-label": "Enable Category Chips", + "settings-clip-preview-description": "Show a preview of the clipboard content when using the >clip command.", + "settings-clip-preview-label": "Enable clip preview", + "settings-clip-smart-icons-description": "Show specific icons for links, files, colors, and code instead of a generic clipboard icon.", + "settings-clip-smart-icons-label": "Enable Smart Icons", + "settings-clip-wrap-text-description": "Wrap text in the clipboard list instead of truncating it.", + "settings-clip-wrap-text-label": "Wrap clipboard text", + "settings-clipboard-history-description": "Access previously copied items from the launcher.", + "settings-clipboard-history-label": "Enable clipboard history", + "settings-clipboard-watch-image-description": "Full command string passed to wl-paste for image changes. (requires restart)", + "settings-clipboard-watch-image-label": "Image watch command", + "settings-clipboard-watch-text-description": "Full command string passed to wl-paste for text changes. (requires restart)", + "settings-clipboard-watch-text-label": "Text watch command", + "settings-custom-launch-prefix-description": "Prefix commands with a custom launcher (e.g. 'runapp' for systemd integration).", + "settings-custom-launch-prefix-enabled-description": "Use a custom prefix for launching applications instead of the default method.", + "settings-custom-launch-prefix-enabled-label": "Enable custom launch prefix", + "settings-custom-launch-prefix-label": "Custom launch prefix", + "settings-density-description": "Adjust the size of application icons and the density of the launcher.", + "settings-density-label": "Density", + "settings-desc": "Customize the launcher's behavior and appearance.", + "settings-enable-session-search-description": "Show session actions (lock, shutdown, reboot, etc.) when searching in the launcher.", + "settings-enable-session-search-label": "Enable session search", + "settings-enable-settings-search-description": "Show settings results when searching in the launcher.", + "settings-enable-settings-search-label": "Enable settings search", + "settings-enable-windows-search-description": "Search and focus active windows.", + "settings-enable-windows-search-label": "Enable windows search", + "settings-grid-view-description": "Display items in a grid layout instead of a list.", + "settings-icon-mode-description": "Use native system icons instead of Tabler icons.", + "settings-icon-mode-label": "Use native icons", + "settings-ignore-mouse-input-description": "Disable mouse interaction and scrollwheel in the launcher.", + "settings-ignore-mouse-input-label": "Ignore mouse input", + "settings-overlay-layer-description": "Display the launcher on the overlay layer, above fullscreen windows. When enabled, the launcher will not attach to the bar.", + "settings-overlay-layer-label": "Show above fullscreen", + "settings-position-description": "Choose where the launcher panel appears.", + "settings-show-categories-description": "Show category tabs for filtering applications.", + "settings-show-categories-label": "Show categories", + "settings-show-icon-background-description": "Show a rounded rectangle background behind icons.", + "settings-show-icon-background-label": "Show icon background", + "settings-sort-by-usage-description": "When enabled, frequently launched apps appear first in the list.", + "settings-sort-by-usage-label": "Sort by most used", + "settings-terminal-command-description": "Command to launch a terminal. E.g. 'kitty -e' or 'gnome-terminal --'.", + "settings-terminal-command-label": "Terminal command", + "settings-use-app2unit-description": "Uses an alternative launch method to better manage app processes and prevent issues.", + "settings-use-app2unit-label": "Use App2Unit to launch applications", + "settings-view-mode-description": "Choose the layout for the launcher entries.", + "settings-view-mode-label": "View mode", + "title": "Launcher" + }, + "location": { + "auto-locate-description": "Automatically detect your location periodically using your IP address.", + "auto-locate-label": "Auto-locate", + "calendar-cards-desc": "Organize and enable/disable cards in the calendar panel.", + "calendar-cards-title": "Calendar cards", + "calendar-header-label": "Calendar Header", + "calendar-month-label": "Calendar Month", + "date-time-12hour-format-description": "Display time in 12-hour format on the lock screen and calendar. The bar clock has its own settings.", + "date-time-12hour-format-label": "Use 12-hour time format", + "date-time-desc": "Customize how date and time appear.", + "date-time-first-day-of-week-automatic": "Automatic (use system locale)", + "date-time-first-day-of-week-description": "Choose which day starts the week in the calendar.", + "date-time-first-day-of-week-label": "First day of week", + "date-time-show-events-description": "Display events in the calendar panel.", + "date-time-show-events-label": "Show calendar events", + "date-time-title": "Date & time", + "date-time-use-analog-description": "Show an analog style clock on the calendar window.", + "date-time-use-analog-label": "Use analog style clock", + "date-time-week-numbers-description": "Display the week of the year (e.g. week 38) in the calendar.", + "date-time-week-numbers-label": "Show week numbers", + "geolocate-now-button": "Locate now", + "location-desc": "Get accurate weather and Night Light scheduling by setting your location.", + "location-search-description": "e.g. Toronto, ON", + "location-search-label": "Search for a location", + "location-search-placeholder": "Enter the location name", + "location-title": "Your location", + "weather-desc": "Choose your preferred temperature unit.", + "weather-enabled-description": "Show weather information throughout the interface and fetch weather data. When disabled, all weather elements will be hidden and no network requests will be made.", + "weather-enabled-label": "Enable weather", + "weather-fahrenheit-description": "Display temperature in Fahrenheit instead of Celsius.", + "weather-fahrenheit-label": "Display temperature in Fahrenheit (°F)", + "weather-hide-city-description": "Hide the city name from weather displays throughout the interface.", + "weather-hide-city-label": "Hide city name", + "weather-hide-timezone-description": "Hide the timezone abbreviation from weather displays throughout the interface.", + "weather-hide-timezone-label": "Hide timezone", + "weather-show-effects-description": "Show additional visual effects (like rain, snow, or lightning) on the weather card.", + "weather-show-effects-label": "Display weather effects", + "weather-show-in-calendar-description": "Show the daily weather forecast directly in your calendar view.", + "weather-show-in-calendar-label": "Display weather in calendar", + "weather-talia-mascot-always-description": "Always use Talia emojis instead of tabler icons.", + "weather-talia-mascot-always-label": "Always show Talia weather emojis" + }, + "lock-screen": { + "allow-password-with-fprintd-description": "When fprintd (fingerprint authentication) is active, this option lets you still login using your password instead of a fingerprint", + "allow-password-with-fprintd-label": "Allow password login with fprintd", + "auto-start-auth-description": "Automatically starts fingerprint authentication without requiring a key press or button click.", + "auto-start-auth-label": "Auto-start authentication", + "clock-format-description": "Customize the clock format using date/time syntax tokens.", + "clock-format-label": "Clock format", + "clock-style-analog": "Analog", + "clock-style-custom": "Custom", + "clock-style-description": "Choose the visual style of the clock on the lock screen.", + "clock-style-digital": "Digital", + "clock-style-label": "Clock style", + "compact-lockscreen-description": "Show only the login input and system controls, hiding weather and media widgets.", + "compact-lockscreen-label": "Compact lock screen", + "enable-lockscreen-media-controls-description": "Show interactive media playback controls on the lock screen.", + "enable-lockscreen-media-controls-label": "Lock screen media controls", + "lock-on-suspend-description": "Automatically lock the screen when suspending the system.", + "lock-on-suspend-label": "Lock on suspend", + "lock-screen-animations-description": "Enable or disable lockscreen animations.", + "lock-screen-animations-label": "Lockscreen animations", + "lock-screen-blur-strength-description": "Applies a blur effect to the lock screen wallpaper.", + "lock-screen-blur-strength-label": "Lock screen blur strength", + "lock-screen-tint-strength-description": "Applies a tint overlay to the lock screen wallpaper.", + "lock-screen-tint-strength-label": "Lock screen tint strength", + "monitors-desc": "Show lock screen on specific monitors. Defaults to all if none are chosen.", + "password-chars-description": "Cute icons used to hide your password.", + "password-chars-label": "Random password icons", + "show-hibernate-description": "Show the option 'hibernate' in the power controls.", + "show-hibernate-label": "Show hibernate", + "show-session-buttons-description": "Allow access to power settings from the lock screen.", + "show-session-buttons-label": "Power controls", + "title": "Lock Screen" + }, + "network": { + "bluetooth-description": "Activate Bluetooth management.", + "bluetooth-rssi-polling-description": "Periodically sample RSSI for connected devices via bluetoothctl. May not be available for all devices; uses minimal resources when enabled.", + "bluetooth-rssi-polling-label": "Bluetooth signal polling", + "desc": "Manage Wi-Fi and Bluetooth connections.", + "wifi-description": "Manage wireless networks (requires NetworkManager)." + }, + "notifications": { + "duration-critical-urgency-description": "How long critical priority notifications stay visible.", + "duration-critical-urgency-label": "Critical urgency", + "duration-desc": "Configure how long notifications stay visible based on their urgency level.", + "duration-low-urgency-description": "How long low priority notifications stay visible.", + "duration-low-urgency-label": "Low urgency", + "duration-normal-urgency-description": "How long normal priority notifications stay visible.", + "duration-normal-urgency-label": "Normal urgency", + "duration-respect-expire-description": "Use the expire timeout set in the notification.", + "duration-respect-expire-label": "Respect expire timeout", + "duration-title": "Notification duration", + "history-clear-dismiss-description": "Clear notification from history when dismissed.", + "history-clear-dismiss-label": "Clear on dismissed", + "history-critical-urgency-description": "Save critical priority notifications to history.", + "history-critical-urgency-label": "Save critical urgency to history", + "history-desc": "Control which notifications are saved to history based on their urgency level.", + "history-low-urgency-description": "Save low priority notifications to history.", + "history-low-urgency-label": "Save low urgency to history", + "history-normal-urgency-description": "Save normal priority notifications to history.", + "history-normal-urgency-label": "Save normal urgency to history", + "monitors-desc": "Show notification on specific monitors. Defaults to all if none are chosen.", + "rules-action-block": "Block", + "rules-action-block-desc": "Skips completely.", + "rules-action-hide": "Hide", + "rules-action-hide-desc": "No popup, no sound, adds to history.", + "rules-action-label": "Action", + "rules-action-mute": "Mute", + "rules-action-mute-desc": "No sound, still shows popup and in history.", + "rules-add": "Add rule", + "rules-delete": "Delete rule", + "rules-description": "Match app name or content. Rules are checked in order, and the first match is applied.", + "rules-edit": "Edit rule", + "rules-label": "Filter rules", + "rules-pattern-label": "Pattern", + "rules-pattern-placeholder": "firefox, discord, or /regex/", + "rules-tab": "Rules", + "settings-always-on-top-description": "Display notifications above fullscreen windows and other layers.", + "settings-background-opacity-description": "Adjust the opacity of notification backgrounds.", + "settings-density-description": "Choose the notification card density.", + "settings-density-label": "Density", + "settings-desc": "Configure notifications appearance and behavior.", + "settings-do-not-disturb-description": "Disable all notification popups when enabled.", + "settings-enabled-description": "Enable or disable the notification daemon, requires a restart of Noctalia shell.", + "settings-enabled-label": "Enable notifications", + "settings-location-description": "Where notifications appear on screen.", + "settings-markdown-description": "Render notification content using Markdown formatting.", + "settings-markdown-label": "Enable Markdown", + "sounds-desc": "Configure notification sound effects and volume.", + "sounds-enabled-description": "Enable sound effects for incoming notifications.", + "sounds-enabled-label": "Enable notification sounds", + "sounds-excluded-apps-description": "Skip playing the configured notification sound for specific applications that have their own built-in sounds.", + "sounds-excluded-apps-label": "Excluded applications", + "sounds-excluded-apps-placeholder": "discord,firefox,chrome,chromium,edge", + "sounds-files-critical-description": "Path to the sound file played for critical priority notifications.", + "sounds-files-critical-label": "Critical urgency sound", + "sounds-files-critical-select-title": "Select critical urgency sound file", + "sounds-files-desc": "Configure custom sound files for different notification urgency levels.", + "sounds-files-low-description": "Path to the sound file played for low priority notifications.", + "sounds-files-low-label": "Low urgency sound", + "sounds-files-low-select-title": "Select low urgency sound file", + "sounds-files-normal-description": "Path to the sound file played for normal priority notifications.", + "sounds-files-normal-label": "Normal urgency sound", + "sounds-files-normal-select-title": "Select normal urgency sound file", + "sounds-files-placeholder": "Enter path to sound file", + "sounds-files-select-file": "Select sound file", + "sounds-files-title": "Sound files", + "sounds-files-unified-description": "Path to the sound file played for notifications.", + "sounds-files-unified-label": "Notification sound", + "sounds-files-unified-select-title": "Select notification sound file", + "sounds-separate-description": "Use different sound files for low, normal, and critical priority notifications.", + "sounds-separate-label": "Use different sounds per priority", + "sounds-title": "Sound settings", + "sounds-unavailable-description": "Install Qt6 Multimedia to enable notification sounds.", + "sounds-unavailable-label": "Notification sounds unavailable", + "sounds-volume-description": "Adjust the volume level for notification sounds.", + "sounds-volume-label": "Sound volume", + "toast-battery-description": "Show a warning when the battery level falls below this percentage.", + "toast-battery-label": "Battery warning", + "toast-desc": "Configure toast appearance and behavior.", + "toast-keyboard-description": "Show a toast when the keyboard layout changes.", + "toast-keyboard-label": "Keyboard layout", + "toast-media-description": "Show a toast when media playback state changes.", + "toast-media-label": "Media" + }, + "osd": { + "always-on-top-description": "Display OSD above fullscreen windows and other layers.", + "always-on-top-label": "Always on top", + "background-opacity-description": "Controls the transparency of the OSD background.", + "background-opacity-label": "Background opacity", + "description": "Configure on-screen indicators such as volume and brightness overlays.", + "duration-auto-hide-description": "Adjust the time before OSD disappears.", + "duration-auto-hide-label": "Auto-hide after", + "duration-desc": "How long OSD remains visible before hiding automatically.", + "duration-title": "Auto-hide timeout", + "enabled-description": "Show volume and brightness changes in real-time.", + "enabled-label": "Enable on-screen display", + "events-desc": "Select which events trigger the on-screen display.", + "general-desc": "Configure visibility and behavior of OSD.", + "location-description": "Where on-screen displays appear.", + "monitors-desc": "Show OSD on specific monitors. Defaults to all if none are chosen.", + "title": "On-Screen Display", + "types-brightness-description": "Show OSD when screen brightness changes.", + "types-brightness-label": "Brightness", + "types-custom-text-description": "Show OSD for custom text messages from IPC.", + "types-custom-text-label": "Custom Text", + "types-desc": "Select the events that trigger the OSD.", + "types-input-volume-description": "Show OSD when microphone volume changes.", + "types-input-volume-label": "Input volume", + "types-lockkey-description": "Show OSD when Caps Lock, Num Lock, or Scroll Lock are toggled.", + "types-lockkey-label": "Lock keys", + "types-media-description": "Show OSD when media playback state changes (play, pause, skip).", + "types-media-label": "Media playback", + "types-title": "OSD trigger events", + "types-volume-description": "Show OSD when audio output volume changes.", + "types-volume-label": "Output volume" + }, + "plugins": { + "auto-update": "Auto-update plugins", + "auto-update-description": "Automatically update all plugins when the shell starts.", + "available-description": "Browse and install plugins from configured sources.", + "available-label": "Available plugins", + "available-no-plugins-description": "Check your plugin sources or refresh the list.", + "available-no-plugins-label": "No plugins available", + "check-for-updates": "Check for updates", + "checking-for-updates": "Checking for updates...", + "collision-already-installed": "This plugin is already installed", + "collision-custom-version-exists": "A custom version from \"{source}\" is already installed", + "collision-official-version-exists": "The official version of this plugin is already installed", + "development-disable": "Disable development mode for this plugin", + "development-enable": "Enable development mode for this plugin", + "filter-downloaded": "Downloaded", + "filter-not-downloaded": "Not Downloaded", + "filter-tags-description": "Filter plugins by category or download status.", + "filter-tags-label": "Tags", + "hot-reload-description": "Automatically reload plugins when their files change. Useful for plugin development.", + "hot-reload-label": "Hot reload (dev mode)", + "hot-reloaded": "Reloaded plugin: {name}", + "install-error": "Failed to install: {error}", + "install-incompatible": "{plugin} requires Noctalia v{version} or higher", + "install-success": "Successfully installed {plugin}", + "installed-description": "Manage and configure all locally installed plugins.", + "installed-label": "Installed plugins", + "installed-no-plugins-description": "Install plugins from the \"Available\" section.", + "installed-no-plugins-label": "No plugins installed", + "installing": "Installing {plugin}...", + "notify-updates": "Plugin update notifications", + "notify-updates-description": "Show a notification popup when new plugin updates are available.", + "open-plugin-page": "Open plugin page", + "open-plugins-tab": "Open plugins settings", + "plugin-settings-title": "{plugin} Settings", + "refresh-refreshing": "Refreshing plugins list...", + "refresh-tooltip": "Refresh available plugins", + "settings-error-not-loaded": "Plugin not loaded", + "settings-saved": "Plugin settings saved", + "settings-tooltip": "Plugin settings", + "source-custom": "Custom source", + "sources-add-custom": "Add custom repository", + "sources-add-dialog-description": "Add a GitHub repository as a plugin source.", + "sources-add-dialog-error": "Failed to add plugin source", + "sources-add-dialog-name": "Repository name", + "sources-add-dialog-name-placeholder": "My Custom Plugins", + "sources-add-dialog-success": "Plugin source added successfully", + "sources-add-dialog-title": "Add plugin source", + "sources-add-dialog-url": "Repository URL", + "sources-description": "Manage plugin repositories.", + "sources-placeholder": "My cool repository", + "sources-remove-tooltip": "Remove plugin source", + "title": "Plugins", + "translations-reloaded": "Reloaded translations: {name}", + "uninstall-dialog-description": "Are you sure you want to uninstall {plugin}? This will remove all plugin data.", + "uninstall-dialog-title": "Uninstall plugin", + "uninstall-error": "Failed to uninstall: {error}", + "uninstall-success": "Successfully uninstalled {plugin}", + "uninstalling": "Uninstalling {plugin}...", + "update-all": "Update All ({count})", + "update-all-success": "All plugins updated successfully", + "update-available": "New plugin update available", + "update-available-plural": "Plugin updates available ({count})", + "update-error": "Failed to update plugin: {plugin}: {error}", + "update-pending": "v{current} → v{new} (requires Noctalia v{required})", + "update-success": "Updated {plugin} to v{version}", + "update-version": "v{current} → v{new}", + "updating": "Updating..." + }, + "region": { + "title": "Region" + }, + "session-menu": { + "countdown-duration-description": "Set how long the countdown timer lasts before executing power actions.", + "countdown-duration-label": "Countdown duration", + "enable-countdown-description": "Show a countdown timer before executing power actions.", + "enable-countdown-label": "Enable countdown timer", + "entries-desc": "Customize which power actions appear in the session menu and in what order.", + "entries-title": "Power actions", + "entry-settings-command-description": "Custom command to execute for this action. Leave empty to use the default system command.", + "entry-settings-command-placeholder": "e.g. systemctl poweroff", + "entry-settings-default-command-lock": "Internal lock screen (no command)", + "entry-settings-default-command-logout": "Internal logout (no command)", + "entry-settings-default-info-description": "If no custom command is specified, the default system command will be used.", + "entry-settings-default-info-label": "Default command", + "entry-settings-keybind-description": "Assign a key combination to trigger this action when the session menu is open.", + "entry-settings-keybind-placeholder": "Press Record to assign a key...", + "entry-settings-keybind-recording": "Recording... Press any key combination", + "entry-settings-title": "Configure {entry}", + "entry-settings-tooltip": "Configure command", + "general-desc": "Configure the session menu panel behavior and appearance.", + "large-buttons-layout-description": "Choose how session menu buttons are displayed.", + "large-buttons-layout-label": "Large buttons layout", + "large-buttons-style-description": "Display the session menu with large buttons in a grid layout.", + "large-buttons-style-label": "Large buttons style", + "position-description": "Choose where the session menu panel appears when opened.", + "show-header-description": "Display the title and close button at the top of the session menu.", + "show-header-label": "Show header", + "show-keybinds-description": "Display keybind hints on session options.", + "show-keybinds-label": "Show keybinds" + }, + "system": { + "noctalia-performance-disable-desktop-widgets-description": "Keep desktop widgets visible while Noctalia performance mode is enabled.", + "noctalia-performance-disable-desktop-widgets-label": "Enable desktop widgets in performance mode", + "noctalia-performance-disable-wallpaper-description": "Keep desktop, overview, and lock screen wallpapers visible while Noctalia performance mode is enabled.", + "noctalia-performance-disable-wallpaper-label": "Enable wallpaper rendering in performance mode", + "title": "System" + }, + "system-monitor": { + "critical-color-label": "Critical color", + "custom-highlight-colors-title-label": "Custom highlight colors", + "disk-available-label": "Disk available", + "disk-section-label": "Disk usage", + "enable-dgpu-monitoring-description": "Warning: This will wake up your discrete GPU (NVIDIA/AMD), which may significantly impact battery life on laptops with hybrid graphics.", + "enable-dgpu-monitoring-label": "Enable discrete GPU monitoring", + "external-monitor-description": "Enter the command or application path to launch when activating the external system monitor application.", + "external-monitor-label": "External system monitor command", + "external-monitor-placeholder": "resources || missioncenter || jdsystemmonitor || corestats || system-monitoring-center || gnome-system-monitor || plasma-systemmonitor || mate-system-monitor || ukui-system-monitor || deepin-system-monitor || pantheon-system-monitor", + "general-desc": "Configure the system monitor behavior and appearance.", + "gpu-section-label": "GPU temperature", + "highlight-colors-section-label": "Highlight colors", + "polling-interval-label": "Polling interval", + "polling-section-description": "Configure how often each system metric is updated.", + "polling-section-label": "Polling intervals", + "threshold-critical": "Critical threshold", + "threshold-warning": "Warning threshold", + "thresholds-section-description": "Adjust warning/critical thresholds for each system metric.", + "use-custom-highlight-colors-description": "When disabled, theme default highlight colors are used.", + "use-custom-highlight-colors-label": "Use custom highlight colors", + "warning-color-label": "Warning color" + }, + "user-interface": { + "allow-panels-without-bar-description": "When enabled, panels can open on any screen. When disabled, panels will only open on screens that have a bar, which can reduce memory usage.", + "allow-panels-without-bar-label": "Allow panels on screens without a bar", + "animation-disable-description": "Disable all animations for a faster, more responsive experience.", + "animation-disable-label": "Disable UI animations", + "animation-speed-description": "Adjust global animation speed.", + "animation-speed-label": "Animation speed", + "animation-speed-reset": "Reset animation speed", + "appearance-desc": "Customize visual elements like tooltips, borders, and shadows.", + "blur-behind-description": "Blurs the area behind bars and panels using the compositor blur protocol.", + "blur-behind-label": "Blur behind", + "box-border-description": "Display an outline around content areas.", + "box-border-label": "Container outline", + "box-border-radius-description": "Adjusts the corner roundness of major layout sections, such as sidebars, cards, and content panels.", + "box-border-radius-label": "Container radius", + "control-border-radius-description": "Controls the curvature of interactive elements, including buttons, toggles, and text fields.", + "control-border-radius-label": "Input radius", + "desc": "Customize the look, feel, and behavior of the interface.", + "dim-desktop-description": "Dim the desktop when panels or menus are open.", + "dim-desktop-label": "Dim desktop", + "dimmer-opacity-description": "Set the opacity level for desktop dimming.", + "dimmer-opacity-label": "Dimmed desktop opacity", + "panel-background-opacity-description": "Set the background opacity for all panels (bar, launcher, settings, etc...).", + "panel-background-opacity-label": "Panel background opacity", + "panels-attached-to-bar-description": "Panels lock to the bar and screen edges, creating a seamless look with stylish inverted corners.", + "panels-attached-to-bar-label": "Snap panels to edges", + "panels-overlay-description": "Ensures panels and the bar remain visible, even over fullscreen applications.", + "panels-overlay-label": "Keep panels & bar on top", + "scaling-description": "Changes the size of the general user interface, excluding the bar.", + "scaling-label": "Interface scaling", + "scrollbar-always-visible-description": "Keep scrollbars visible whenever content is scrollable, instead of only showing them on hover.", + "scrollbar-always-visible-label": "Always show scrollbars", + "settings-panel-header": "Settings panel", + "settings-panel-mode-description": "Choose settings layout (may require reopening).", + "settings-panel-mode-label": "Settings panel mode", + "settings-panel-sidebar-card-style-description": "Wraps the settings sidebar in a filled background with rounded corners.", + "settings-panel-sidebar-card-style-label": "Sidebar card style", + "shadows-description": "Enables drop shadows under bars and panels.", + "shadows-direction-description": "Choose where the shadow is cast to.", + "shadows-direction-label": "Shadow direction", + "shadows-label": "Drop shadows", + "title": "User Interface", + "tooltips-description": "Enable or disable tooltips throughout the interface.", + "tooltips-label": "Show tooltips", + "translucent-widgets-description": "Make buttons, tabs, and other widgets inside panels semi-transparent.", + "translucent-widgets-label": "Translucent widgets" + }, + "wallpaper": { + "automation-change-mode-alphabetical": "Alphabetical", + "automation-change-mode-description": "Choose how wallpapers are selected when changing automatically.", + "automation-change-mode-label": "Change mode", + "automation-custom-interval-description": "Enter time as HH:MM (e.g. 01:30).", + "automation-custom-interval-label": "Custom interval", + "automation-interval-description": "How often to change wallpapers automatically.", + "automation-interval-label": "Wallpaper interval", + "automation-random-wallpaper-description": "Schedule random wallpaper changes at regular intervals.", + "automation-scheduled-change-description": "Automatically change wallpapers at regular intervals.", + "automation-scheduled-change-label": "Scheduled change", + "look-feel-edge-smoothness-description": "Applies a soft, feathered effect to the edge of transitions.", + "look-feel-edge-smoothness-label": "Soften transition edge", + "look-feel-fill-color-description": "Choose a fill color that may appear behind the wallpaper.", + "look-feel-fill-mode-description": "Select how the image should scale to match your monitor's resolution.", + "look-feel-fill-mode-label": "Fill mode", + "look-feel-skip-startup-transition-description": "Skip the wallpaper animation when the shell starts.", + "look-feel-skip-startup-transition-label": "Skip startup transition", + "look-feel-title": "Look & feel", + "look-feel-transition-duration-description": "Duration of transition animations in seconds.", + "look-feel-transition-duration-label": "Transition duration", + "look-feel-transition-type-description": "Animation type when switching between wallpapers.", + "look-feel-transition-type-label": "Transition type", + "settings-clear-cache-button": "Clear cache", + "settings-clear-cache-description": "Clear cached resized wallpapers to free disk space.", + "settings-clear-cache-label": "Wallpaper cache", + "settings-clear-cache-toast": "Wallpaper cache cleared", + "settings-desc": "Control how wallpapers are managed and displayed.", + "settings-enable-management-description": "Manage wallpapers with Noctalia. Uncheck if you prefer using another application.", + "settings-enable-management-label": "Enable wallpaper management", + "settings-enable-overview-description": "Applies a blurred and dimmed wallpaper to the overview screen.", + "settings-enable-overview-label": "Enable overview wallpaper", + "settings-folder-description": "Path to your main wallpaper folder.", + "settings-folder-label": "Wallpaper folder", + "settings-hide-wallpaper-filenames-tooltip-hide": "Hide filenames", + "settings-hide-wallpaper-filenames-tooltip-show": "Show filenames", + "settings-monitor-specific-description": "Set a different wallpaper folder for each monitor.", + "settings-monitor-specific-label": "Monitor-specific directories", + "settings-monitor-specific-tooltip": "Monitor wallpaper folder", + "settings-overview-blur-strength-description": "Applies the blur strength to the overview.", + "settings-overview-blur-strength-label": "Overview blur strength", + "settings-overview-tint-description": "Applies the tint strength to the overview.", + "settings-overview-tint-label": "Overview tint strength", + "settings-recursive-search-description": "Also search for wallpapers in subfolders of the wallpaper directory.", + "settings-recursive-search-label": "Search subfolders", + "settings-select-monitor-folder": "Select monitor wallpaper folder", + "settings-selector-description": "Choose your wallpaper.", + "settings-selector-position-description": "Choose where the wallpaper selector panel appears.", + "settings-show-hidden-files-tooltip-hide": "Hide hidden files", + "settings-show-hidden-files-tooltip-show": "Show hidden files", + "settings-title": "Wallpaper settings", + "settings-use-original-images-description": "Skip resizing wallpapers before display. Saves disk space and reduces CPU usage during wallpaper changes, but may use more memory for very large images.", + "settings-use-original-images-label": "Use original images", + "settings-view-mode-description": "Choose how wallpapers are displayed from your directory.", + "settings-view-mode-label": "Viewing mode", + "view-mode-browse": "Browse directories", + "view-mode-cycle-tooltip": "View mode: {mode} (click to change)", + "view-mode-recursive": "Flattened subdirectories", + "view-mode-single": "Root directory" + } + }, + "placeholders": { + "add-new-keybind": "Add a new keybind", + "command-example": "echo \"Hello World\"", + "enter-command": "Enter command to execute (app or custom script)", + "enter-ipc-identifier": "Enter unique identifier for IPC commands", + "enter-path": "Enter path...", + "enter-text-to-collapse": "e.g. 'nothing is playing'. Use /regex/ for patterns.", + "enter-tooltip": "Enter tooltip", + "enter-width-pixels": "Enter width in pixels", + "keybind-recording": "Recording keybind...", + "search": "Search...", + "search-icons": "e.g. noctalia, niri, battery, cloud", + "search-launcher": "Search entries... or use > for commands", + "search-wallhaven": "Search Wallhaven...", + "search-wallpapers": "Type to filter wallpapers..." + }, + "positions": { + "bottom": "Bottom", + "bottom-center": "Bottom center", + "bottom-left": "Bottom left", + "bottom-right": "Bottom right", + "center": "Center", + "center-left": "Left center", + "center-right": "Right center", + "close-to-bar": "Close to bar button", + "follow-bar": "Follow bar", + "left": "Left", + "right": "Right", + "top": "Top", + "top-center": "Top center", + "top-left": "Top left", + "top-right": "Top right" + }, + "session-menu": { + "action-in-seconds": "{action} in {seconds} seconds...", + "cancel-timer": "Cancel timer", + "title": "Session Menu" + }, + "setup": { + "all-done": "All Done!", + "appearance": { + "subheader": "Choose Dark Mode and color sources (wallpaper or predefined)." + }, + "customize": { + "header": "Customize your experience", + "subheader": "Adjust bar position, density, scaling and more." + }, + "skip-setup": "Skip Setup", + "telemetry-wizard-done": "Got it!", + "telemetry-wizard-note": "You're in control — enable or disable this anytime in settings", + "telemetry-wizard-subtitle": "We've added anonymous analytics to help improve Noctalia", + "telemetry-wizard-title": "Privacy Update", + "wallpaper": { + "choose-dir": "Choose a directory containing your wallpaper images", + "dir-browse": "Browse for wallpaper folder", + "dir-description": "Choose the folder containing your wallpapers.", + "dir-label": "Wallpaper directory", + "dir-select-title": "Select wallpaper folder", + "header": "Choose your wallpaper", + "no-dir": "No wallpaper directory selected", + "no-valid": "No valid image files found in: {dir}", + "none-in-dir": "No wallpapers found in directory", + "preview-error": "Failed to load image", + "select-prompt": "Select a wallpaper below", + "subheader": "Set the mood with a beautiful background." + }, + "welcome": "Welcome", + "welcome-note": "Just a few basics to get you started — full options are in the settings", + "welcome-subtitle": "Let's make your desktop uniquely yours", + "welcome-title": "Welcome to Noctalia!" + }, + "system": { + "cpu-temperature": "{temp}°C", + "disk-usage": "{percent}%", + "location-display": "{name} ({coordinates})", + "monitor-description": "{model} ({width}x{height} @ {scale}x)", + "no-media-player-detected": "No media player detected", + "scaling-percentage": "{percentage}%", + "signal-strength": "{signal}%", + "unknown-app": "Unknown app", + "uptime": "Uptime: {uptime}", + "user-requested": "User requested", + "welcome-back": "Welcome back,", + "widget-settings-title": "{widget} Settings" + }, + "system-monitor": { + "core-usage": "Core {id} usage", + "cpu-temp": "CPU temp", + "cpu-usage": "CPU usage", + "disk": "Disk", + "download-speed": "Download speed", + "gpu-temp": "GPU temp", + "load-average": "Load average", + "title": "System Monitor", + "upload-speed": "Upload speed" + }, + "toast": { + "airplane-mode": { + "description": "Disable all wireless communications.", + "title": "Airplane Mode" + }, + "battery": { + "critical": "Critical battery", + "critical-desc": "Battery is at {percent}% — please connect the charger immediately", + "low": "Low battery", + "low-desc": "Battery is at {percent}% — please connect the charger" + }, + "bluetooth": { + "address-copied": "Address copied to clipboard", + "auto-connect-disabled": "Auto-connect disabled", + "auto-connect-enabled": "Auto-connect enabled", + "auto-connecting": "Connecting to {count} device(s)...", + "confirm-code": "Confirm code {value} on the other device.", + "connect-failed": "Failed to connect to device", + "disconnect-failed": "Failed to disconnect from device", + "discoverable-change-failed": "Failed to change discoverable state", + "discoverable-disabled": "Discoverable disabled", + "discoverable-enabled": "Discoverable enabled", + "display-code": "Enter code {value} on the other device.", + "forget-failed": "Failed to forget device", + "pair-failed": "Failed to pair device", + "passkey-required": "Passkey required by the device.", + "pincode-required": "PIN code required by the device.", + "state-change-failed": "Failed to change Bluetooth state" + }, + "clipboard": { + "long-text": "Long text", + "unavailable": "Clipboard history unavailable", + "unavailable-desc": "The 'cliphist' application is not installed. Please install it to use clipboard history features" + }, + "custom-command-failed": { + "description": "Command failed: {command}\nExit code: {code}", + "title": "Custom command failed" + }, + "do-not-disturb": { + "disabled": "Do Not Disturb disabled", + "disabled-desc": "Showing all notifications", + "enabled": "Do Not Disturb enabled", + "enabled-desc": "You'll find these notifications in your history" + }, + "donation-opened": "Donation page opened in your browser", + "internet-limited": "Connected without internet", + "keyboard-layout": { + "changed": "Keyboard layout changed to {layout}", + "title": "Keyboard" + }, + "missing-control-center": { + "description": "The control center widget has been removed from the bar. To access it from the bar again, you will need to re-add the widget. You can open it with right clicking on the bar too", + "label": "Last control center widget removed" + }, + "night-light": { + "forced": "Forced activation", + "normal": "Normal mode", + "not-installed": "wlsunset not installed" + }, + "noctalia-performance": { + "disabled": "Performance mode disabled", + "enabled": "Performance mode enabled", + "label": "Noctalia Performance" + }, + "power-profile": { + "changed": "Power profile changed", + "profile-name": "{profile}" + }, + "theming-processor-failed": { + "desc-generic": "Encountered an error while processing templates", + "title": "Templating processing failed" + }, + "vpn": { + "connected": "Connected to '{name}'", + "disconnected": "Disconnected from '{name}'" + }, + "wallpaper-colors": { + "disabled": "Wallpaper colors disabled", + "enabled": "Wallpaper colors enabled", + "label": "Wallpaper colors" + }, + "wifi": { + "connected": "Connected to '{ssid}'", + "connection-failed": "Connection failed", + "connection-timeout": "Connection timeout", + "disconnected": "Disconnected from '{ssid}'", + "incorrect-password": "Incorrect password", + "network-not-found": "Network not found" + } + }, + "tooltips": { + "add-widget": "Add widget", + "auto-connect": "Toggle auto-connection for this device", + "bluetooth-auto-connect-off": "Auto-connect is off", + "bluetooth-auto-connect-on": "Auto-connect is on", + "bluetooth-devices": "Bluetooth devices", + "brightness-at": "Brightness: {brightness}%", + "click-to-start-recording": "Screen recorder (start recording)", + "click-to-stop-recording": "Screen recorder (stop recording)", + "collapse": "Collapse sidebar", + "copy-address": "Copy address", + "delete-notification": "Delete notification", + "dismiss-notification": "Dismiss notification", + "do-not-disturb-enabled": "Do Not Disturb", + "expand": "Expand sidebar", + "forget-network": "Forget network", + "grid-view": "Grid view", + "hidden-files-hide": "Hidden files", + "hide-unnamed-devices": "Hide unnamed devices", + "home": "Home directory", + "input-muted": "Toggle input mute", + "keep-awake": "Keep Awake", + "keyboard-layout": "{layout} keyboard layout", + "list-view": "List view", + "manage-vpn": "VPN connections", + "manage-wifi": "Wi-Fi", + "max-widgets-reached": "Maximum widgets reached", + "microphone-volume-at": "Microphone volume: {volume}%", + "move-to-section": "Move to {section}", + "mute": "Mute", + "next-media": "Next track", + "next-month": "Next month", + "night-light-not-installed": "Night Light (not available)", + "noctalia-performance-enabled": "Noctalia performance mode", + "open-annotation-tool": "Open with annotation tool", + "open-control-center": "Control center", + "open-notification-history-enable-dnd": "Notification history", + "open-settings": "Settings", + "open-tray-dropdown": "System tray", + "output-muted": "Toggle output mute", + "power-profile": "{profile} power profile", + "previous-media": "Previous track", + "previous-month": "Previous month", + "refresh-devices": "Refresh devices", + "refresh-wallhaven": "Refresh Wallhaven results", + "refresh-wallpaper-list": "Refresh wallpaper list", + "remove-widget": "Remove widget", + "search-close": "Close search", + "session-menu": "Session menu", + "show-all-devices": "Show all devices", + "switch-to-dark-mode": "Dark Mode", + "switch-to-light-mode": "Light Mode", + "unmute": "Unmute", + "up": "Parent directory", + "volume-at": "Output volume: {volume}%", + "wallpaper-selector": "Wallpaper selector" + }, + "wallpaper": { + "browse": { + "empty-directory": "This directory is empty.", + "go-root": "Go to wallpaper root", + "go-up": "Go to parent folder", + "go-up-hint": "Use the back button to navigate up." + }, + "configure-directory": "Configure your wallpaper directory with images.", + "fill-modes": { + "crop": "Crop (Fill)", + "fit": "Fit (Contain)", + "repeat": "Repeat (Tile)", + "stretch": "Stretch" + }, + "no-match": "No match found.", + "no-wallpaper": "No wallpaper found.", + "panel": { + "apikey-help": "An API key is required to access NSFW content.", + "apikey-label": "API Key", + "apikey-managed-by-env": "Managed via NOCTALIA_WALLHAVEN_API_KEY environment variable.", + "apikey-placeholder": "Enter your Wallhaven API Key", + "appearance-dark-tab": "Dark", + "appearance-light-tab": "Light", + "categories-anime": "Anime", + "categories-label": "Categories", + "categories-people": "People", + "color-extraction-disabled": "Use wallpaper color extraction", + "color-extraction-enabled": "Use predefined color schemes", + "header-devices-apply-all-tooltip": "Choose wallpaper per monitor", + "header-devices-per-monitor-tooltip": "Apply to all monitors", + "header-link-light-dark-tooltip": "Keep wallpaper when switching theme", + "header-separate-light-dark-tooltip": "Auto-switch wallpaper with theme", + "header-sun-linked-tooltip": "Separate light and dark wallpapers", + "header-sun-separate-tooltip": "Same wallpaper for light and dark", + "order-asc": "Ascending", + "order-desc": "Descending", + "order-label": "Order", + "purity-label": "Content filter", + "purity-nsfw": "NSFW", + "purity-sfw": "SFW", + "purity-sketchy": "Sketchy", + "ratios-all-portrait": "All portrait", + "ratios-all-wide": "All wide", + "ratios-any": "Any", + "ratios-label": "Aspect ratio", + "resolution-atleast": "At least", + "resolution-exact": "Exact", + "resolution-label": "Resolution", + "resolution-mode-label": "Mode", + "solid-color-tooltip": "Solid color background", + "sort-date-asc": "Sort by oldest first", + "sort-date-desc": "Sort by newest first", + "sort-name-asc": "Sort by name (A-Z)", + "sort-name-desc": "Sort by name (Z-A)", + "sort-random": "Sort by random", + "sorting-date-added": "Date added", + "sorting-favorites": "Favorites", + "sorting-label": "Sort by", + "sorting-relevance": "Relevance", + "sorting-toplist": "Toplist", + "sorting-views": "Views", + "source-label": "Source", + "source-wallhaven": "Wallhaven", + "title": "Wallpaper Selector", + "wallhaven-settings-title": "Wallhaven Settings" + }, + "transitions": { + "disc": "Disc", + "fade": "Fade", + "honeycomb": "Honeycomb", + "pixelate": "Pixelate", + "stripes": "Stripes", + "wipe": "Wipe" + }, + "try-different-search": "Try a different search query.", + "wallhaven": { + "loading": "Loading wallpapers...", + "no-results": "No wallpapers found. Try a different search query.", + "page": "{current} of {total}", + "page-prefix": "Page", + "page-suffix": "of {total}" + } + }, + "weather": { + "clear-sky": "Clear sky", + "drizzle": "Drizzle", + "fog": "Fog", + "mainly-clear": "Mainly clear", + "overcast": "Overcast", + "partly-cloudy": "Partly cloudy", + "rain-showers": "Rain showers", + "snow": "Snow", + "thunderstorm": "Thunderstorm" + }, + "widgets": { + "color-picker": { + "palette-description": "Choose from a wide range of predefined colors.", + "palette-label": "Palette", + "palette-theme-colors": "Quick access to your theme's color palette.", + "title": "Color picker" + }, + "datetime-tokens": { + "ampm-lowercase": "am/pm in lowercase", + "ampm-uppercase": "AM/PM in uppercase", + "common-12hour-time-minutes": "12-hour time with minutes", + "common-24hour-time-minutes": "24-hour time with minutes", + "common-24hour-time-seconds": "24-hour time with seconds", + "common-european-date": "European date format", + "common-iso-date": "ISO date format", + "common-us-date": "US date format", + "common-weekday-date": "Weekday with date", + "common-weekday-month-day": "Weekday, month and day", + "day-abbreviated": "Abbreviated day name", + "day-full": "Full day name", + "day-leading-zero": "Day with leading zero (01-31)", + "day-no-leading-zero": "Day without leading zero (1-31)", + "hour-leading-zero": "Hour with leading zero (00-23) — 24-hour format", + "hour-no-leading-zero": "Hour without leading zero (0-23) — 24-hour format", + "minute-leading-zero": "Minute with leading zero (00-59)", + "minute-no-leading-zero": "Minute without leading zero (0-59)", + "month-abbreviated": "Abbreviated month name", + "month-full": "Full month name", + "month-number-leading-zero": "Month as number with leading zero (01-12)", + "month-number-no-zero": "Month as number without leading zero (1-12)", + "second-leading-zero": "Second with leading zero (00-59)", + "second-no-leading-zero": "Second without leading zero (0-59)", + "timezone-abbreviation": "Timezone abbreviation", + "year-four-digit": "Year as four-digit number", + "year-two-digit": "Year as two-digit number (00-99)" + }, + "file-picker": { + "item": "item", + "items": "items", + "search-placeholder": "Search files and folders...", + "select-current": "Select Current", + "select-file": "Select File", + "select-folder": "Select Folder", + "selected": "Selected:", + "title": "File Picker" + }, + "file-picker-title": "Select a file", + "icon-picker": { + "title": "Icon picker" + }, + "tooltip-placeholder": "Placeholder" + }, + "wifi": { + "enterprise": { + "anonymous-identity": "Anonymous Identity", + "ca-cert": "CA Certificate", + "eap-method": "EAP Method", + "password": "User password", + "phase2-auth": "Phase 2 Authentication", + "username": "Identity / Username" + }, + "panel": { + "action-required": "Action required", + "add-hidden-network": "Add hidden network", + "add-network": "Add network", + "available-interfaces": "Available interfaces", + "available-networks": "Available networks", + "disabled": "Wi‑Fi is disabled", + "disconnecting": "Disconnecting...", + "dns": "DNS", + "enable-message": "Enable Wi‑Fi to see available networks.", + "enter-password": "Enter Wi‑Fi password...", + "forget": "Forget", + "forget-network": "Forget this network", + "forgetting": "Forgetting...", + "hidden-network": "Hidden network", + "interface": "Network interface", + "internet-connected": "Internet connected", + "internet-limited": "No internet", + "internet-status": "Internet status", + "ipv4": "IPv4", + "ipv6": "IPv6", + "known-networks": "Known networks", + "link-speed": "Link speed", + "network-name-ssid": "Network name (SSID)", + "no-ethernet-devices": "No Ethernet devices detected", + "no-networks": "No Wi‑Fi networks found", + "saved": "Saved", + "scan-again": "Scan again", + "searching": "Searching for networks...", + "security-open": "Open", + "security-wep": "WEP", + "security-wpa": "WPA", + "security-wpa-ent": "WPA Enterprise", + "security-wpa2-ent": "WPA2 Enterprise", + "security-wpa23": "WPA2/WPA3", + "security-wpa3": "WPA3", + "security-wpa3-ent": "WPA3 Enterprise", + "show-password": "Show password", + "title": "Wi‑Fi" + }, + "signal": { + "excellent": "Excellent", + "fair": "Fair", + "good": "Good", + "poor": "Poor", + "weak": "Weak" + } + } +} diff --git a/quickshell/compat/noctalia/Commons/Color.qml b/quickshell/compat/noctalia/Commons/Color.qml new file mode 100644 index 0000000..4843823 --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Color.qml @@ -0,0 +1,120 @@ +pragma Singleton +import QtQuick +import Quickshell +import "../../../theme" as G + +// glassMxrph replacement for Noctalia's Color singleton. Same Material-style +// roles and helpers, but every role comes from the glassMxrph theme (glass +// tint, accent, text), so Noctalia plugins render in the glassMxrph look. +// Noctalia's colors.json is not read. +Singleton { + id: root + + property bool reloadColors: false + property bool skipTransition: false + property bool isTransitioning: false + function scheduleExternalColorReload() { + } + function startTransition() { + } + + property color mPrimary: G.Theme.accent + property color mOnPrimary: G.Theme.accentText + property color mSecondary: G.Theme.accentVivid + property color mOnSecondary: G.Theme.accentText + property color mTertiary: G.Theme.accentVivid + property color mOnTertiary: G.Theme.accentText + + property color mError: G.Theme.urgent + property color mOnError: "#000000" + + // Panels and cards: the shell's glass tint; widgets sit on surfaceVariant. + property color mSurface: G.Theme.surface + property color mOnSurface: G.Theme.text + property color mSurfaceVariant: G.Theme.surfaceVariant + property color mOnSurfaceVariant: G.Theme.textSecondary + + property color mOutline: G.Theme.border + property color mShadow: "#000000" + + // Noctalia hovers with a solid accent; glassMxrph uses a soft highlight. + property color mHover: Qt.alpha(G.Theme.text, 0.12) + property color mOnHover: G.Theme.text + + function resolveColorKey(key) { + switch (key) { + case "primary": + return root.mPrimary; + case "secondary": + return root.mSecondary; + case "tertiary": + return root.mTertiary; + case "error": + return root.mError; + default: + return root.mOnSurface; + } + } + + function resolveOnColorKey(key) { + switch (key) { + case "primary": + return root.mOnPrimary; + case "secondary": + return root.mOnSecondary; + case "tertiary": + return root.mOnTertiary; + case "error": + return root.mOnError; + default: + return root.mSurface; + } + } + + function resolveColorKeyOptional(key) { + switch (key) { + case "primary": + return root.mPrimary; + case "secondary": + return root.mSecondary; + case "tertiary": + return root.mTertiary; + case "error": + return root.mError; + default: + return "transparent"; + } + } + + // glassMxrph is dark-only; panels follow the shell's glass opacity. + function adaptiveOpacity(baseOpacity) { + return baseOpacity; + } + + function smartAlpha(baseColor, minAlpha = 0.4) { + return Qt.alpha(baseColor, Math.max(minAlpha, Math.min(baseColor.a, G.Theme.glassOpacity))); + } + + readonly property var colorKeyModel: [ + { + "key": "none", + "name": "None" + }, + { + "key": "primary", + "name": "Primary" + }, + { + "key": "secondary", + "name": "Secondary" + }, + { + "key": "tertiary", + "name": "Tertiary" + }, + { + "key": "error", + "name": "Error" + } + ] +} diff --git a/quickshell/compat/noctalia/Commons/FuzzySort.qml b/quickshell/compat/noctalia/Commons/FuzzySort.qml new file mode 100644 index 0000000..d729e2a --- /dev/null +++ b/quickshell/compat/noctalia/Commons/FuzzySort.qml @@ -0,0 +1,883 @@ +pragma Singleton + +import QtQuick +import Quickshell + +Singleton { + id: root + + // Public API + function go(search, targets, options) { + return _go(search, targets, options); + } + + function single(search, target) { + return _single(search, target); + } + + function highlight(result, open, close) { + if (open === undefined) + open = ''; + if (close === undefined) + close = ''; + return _highlight(result, open, close); + } + + function prepare(target) { + return _prepare(target); + } + + function cleanup() { + return _cleanup(); + } + + // Internal implementation + readonly property var _INFINITY: Infinity + readonly property var _NEGATIVE_INFINITY: -Infinity + readonly property var _NULL: null + property var _noResults: { + let r = []; + r.total = 0; + return r; + } + property var _noTarget: _prepare('') + + property var _preparedCache: new Map() + property var _preparedSearchCache: new Map() + + property var _matchesSimple: [] + property var _matchesStrict: [] + property var _nextBeginningIndexesChanges: [] + property var _keysSpacesBestScores: [] + property var _allowPartialMatchScores: [] + property var _tmpTargets: [] + property var _tmpResults: [] + property var _q: _fastpriorityqueue() + + function _fastpriorityqueue() { + var e = [], o = 0, a = {}; + var v = function (r) { + for (var a = 0, vc = e[a], c = 1; c < o; ) { + var s = c + 1; + a = c; + if (s < o && e[s]._score < e[c]._score) + a = s; + e[a - 1 >> 1] = e[a]; + c = 1 + (a << 1); + } + for (var f = a - 1 >> 1; a > 0 && vc._score < e[f]._score; f = (a = f) - 1 >> 1) + e[a] = e[f]; + e[a] = vc; + }; + a.add = function (r) { + var ac = o; + e[o++] = r; + for (var vc = ac - 1 >> 1; ac > 0 && r._score < e[vc]._score; vc = (ac = vc) - 1 >> 1) + e[ac] = e[vc]; + e[ac] = r; + }; + a.poll = function () { + if (o !== 0) { + var ac = e[0]; + e[0] = e[--o]; + v(); + return ac; + } + }; + a.peek = function () { + if (o !== 0) + return e[0]; + }; + a.replaceTop = function (r) { + e[0] = r; + v(); + }; + return a; + } + + function _createResult() { + return { + target: '', + obj: _NULL, + _score: _NEGATIVE_INFINITY, + _indexes: [], + _targetLower: '', + _targetLowerCodes: _NULL, + _nextBeginningIndexes: _NULL, + _bitflags: 0, + get indexes() { + return this._indexes.slice(0, this._indexes.len).sort((a, b) => a - b); + }, + set indexes(idx) { + this._indexes = idx; + }, + highlight: function (open, close) { + return root._highlight(this, open, close); + }, + get score() { + return root._normalizeScore(this._score); + }, + set score(s) { + this._score = root._denormalizeScore(s); + } + }; + } + + function _createKeysResult(len) { + var arr = new Array(len); + arr._score = _NEGATIVE_INFINITY; + arr.obj = _NULL; + Object.defineProperty(arr, 'score', { + get: function () { + return root._normalizeScore(this._score); + }, + set: function (s) { + this._score = root._denormalizeScore(s); + } + }); + return arr; + } + + function _new_result(target, options) { + var result = _createResult(); + result.target = target; + result.obj = options.obj ?? _NULL; + result._score = options._score ?? _NEGATIVE_INFINITY; + result._indexes = options._indexes ?? []; + result._targetLower = options._targetLower ?? ''; + result._targetLowerCodes = options._targetLowerCodes ?? _NULL; + result._nextBeginningIndexes = options._nextBeginningIndexes ?? _NULL; + result._bitflags = options._bitflags ?? 0; + return result; + } + + function _normalizeScore(score) { + if (score === _NEGATIVE_INFINITY) + return 0; + if (score > 1) + return score; + return Math.E ** (((-score + 1) ** 0.04307 - 1) * -2); + } + + function _denormalizeScore(normalizedScore) { + if (normalizedScore === 0) + return _NEGATIVE_INFINITY; + if (normalizedScore > 1) + return normalizedScore; + return 1 - Math.pow((Math.log(normalizedScore) / -2 + 1), 1 / 0.04307); + } + + function _remove_accents(str) { + return str.replace(/\p{Script=Latin}+/gu, match => match.normalize('NFD')).replace(/[\u0300-\u036f]/g, ''); + } + + function _prepareLowerInfo(str) { + str = _remove_accents(str); + var strLen = str.length; + var lower = str.toLowerCase(); + var lowerCodes = []; + var bitflags = 0; + var containsSpace = false; + + for (var i = 0; i < strLen; ++i) { + var lowerCode = lowerCodes[i] = lower.charCodeAt(i); + if (lowerCode === 32) { + containsSpace = true; + continue; + } + var bit = lowerCode >= 97 && lowerCode <= 122 ? lowerCode - 97 : lowerCode >= 48 && lowerCode <= 57 ? 26 : lowerCode <= 127 ? 30 : 31; + bitflags |= 1 << bit; + } + return { + lowerCodes: lowerCodes, + bitflags: bitflags, + containsSpace: containsSpace, + _lower: lower + }; + } + + function _prepareBeginningIndexes(target) { + var targetLen = target.length; + var beginningIndexes = []; + var beginningIndexesLen = 0; + var wasUpper = false; + var wasAlphanum = false; + for (var i = 0; i < targetLen; ++i) { + var targetCode = target.charCodeAt(i); + var isUpper = targetCode >= 65 && targetCode <= 90; + var isAlphanum = isUpper || targetCode >= 97 && targetCode <= 122 || targetCode >= 48 && targetCode <= 57; + var isBeginning = isUpper && !wasUpper || !wasAlphanum || !isAlphanum; + wasUpper = isUpper; + wasAlphanum = isAlphanum; + if (isBeginning) + beginningIndexes[beginningIndexesLen++] = i; + } + return beginningIndexes; + } + + function _prepareNextBeginningIndexes(target) { + target = _remove_accents(target); + var targetLen = target.length; + var beginningIndexes = _prepareBeginningIndexes(target); + var nextBeginningIndexes = []; + var lastIsBeginning = beginningIndexes[0]; + var lastIsBeginningI = 0; + for (var i = 0; i < targetLen; ++i) { + if (lastIsBeginning > i) { + nextBeginningIndexes[i] = lastIsBeginning; + } else { + lastIsBeginning = beginningIndexes[++lastIsBeginningI]; + nextBeginningIndexes[i] = lastIsBeginning === undefined ? targetLen : lastIsBeginning; + } + } + return nextBeginningIndexes; + } + + function _prepareSearch(search) { + if (typeof search === 'number') + search = '' + search; + else if (typeof search !== 'string') + search = ''; + search = search.trim(); + var info = _prepareLowerInfo(search); + + var spaceSearches = []; + if (info.containsSpace) { + var searches = search.split(/\s+/); + searches = [...new Set(searches)]; + for (var i = 0; i < searches.length; i++) { + if (searches[i] === '') + continue; + var _info = _prepareLowerInfo(searches[i]); + spaceSearches.push({ + lowerCodes: _info.lowerCodes, + _lower: searches[i].toLowerCase(), + containsSpace: false + }); + } + } + return { + lowerCodes: info.lowerCodes, + _lower: info._lower, + containsSpace: info.containsSpace, + bitflags: info.bitflags, + spaceSearches: spaceSearches + }; + } + + function _prepare(target) { + if (typeof target === 'number') + target = '' + target; + else if (typeof target !== 'string') + target = ''; + var info = _prepareLowerInfo(target); + return _new_result(target, { + _targetLower: info._lower, + _targetLowerCodes: info.lowerCodes, + _bitflags: info.bitflags + }); + } + + function _cleanup() { + _preparedCache.clear(); + _preparedSearchCache.clear(); + } + + function _isPrepared(x) { + return typeof x === 'object' && typeof x._bitflags === 'number'; + } + + function _getPrepared(target) { + if (target.length > 999) + return _prepare(target); + var targetPrepared = _preparedCache.get(target); + if (targetPrepared !== undefined) + return targetPrepared; + targetPrepared = _prepare(target); + _preparedCache.set(target, targetPrepared); + return targetPrepared; + } + + function _getPreparedSearch(search) { + if (search.length > 999) + return _prepareSearch(search); + var searchPrepared = _preparedSearchCache.get(search); + if (searchPrepared !== undefined) + return searchPrepared; + searchPrepared = _prepareSearch(search); + _preparedSearchCache.set(search, searchPrepared); + return searchPrepared; + } + + function _getValue(obj, prop) { + var tmp = obj[prop]; + if (tmp !== undefined) + return tmp; + if (typeof prop === 'function') + return prop(obj); + var segs = prop; + if (!Array.isArray(prop)) + segs = prop.split('.'); + var len = segs.length; + var i = -1; + while (obj && (++i < len)) + obj = obj[segs[i]]; + return obj; + } + + function _single(search, target) { + if (!search || !target) + return _NULL; + var preparedSearch = _getPreparedSearch(search); + if (!_isPrepared(target)) + target = _getPrepared(target); + var searchBitflags = preparedSearch.bitflags; + if ((searchBitflags & target._bitflags) !== searchBitflags) + return _NULL; + return _algorithm(preparedSearch, target); + } + + function _highlight(result, open, close) { + if (open === undefined) + open = ''; + if (close === undefined) + close = ''; + var callback = typeof open === 'function' ? open : undefined; + + var target = result.target; + var targetLen = target.length; + var indexes = result.indexes; + var highlighted = ''; + var matchI = 0; + var indexesI = 0; + var opened = false; + var parts = []; + + for (var i = 0; i < targetLen; ++i) { + var ch = target[i]; + if (indexes[indexesI] === i) { + ++indexesI; + if (!opened) { + opened = true; + if (callback) { + parts.push(highlighted); + highlighted = ''; + } else { + highlighted += open; + } + } + if (indexesI === indexes.length) { + if (callback) { + highlighted += ch; + parts.push(callback(highlighted, matchI++)); + highlighted = ''; + parts.push(target.substr(i + 1)); + } else { + highlighted += ch + close + target.substr(i + 1); + } + break; + } + } else { + if (opened) { + opened = false; + if (callback) { + parts.push(callback(highlighted, matchI++)); + highlighted = ''; + } else { + highlighted += close; + } + } + } + highlighted += ch; + } + return callback ? parts : highlighted; + } + + function _all(targets, options) { + var results = []; + results.total = targets.length; + var limit = options?.limit || _INFINITY; + + if (options?.key) { + for (var i = 0; i < targets.length; i++) { + var obj = targets[i]; + var target = _getValue(obj, options.key); + if (target == _NULL) + continue; + if (!_isPrepared(target)) + target = _getPrepared(target); + var result = _new_result(target.target, { + _score: target._score, + obj: obj + }); + results.push(result); + if (results.length >= limit) + return results; + } + } else if (options?.keys) { + for (var i = 0; i < targets.length; i++) { + var obj = targets[i]; + var objResults = _createKeysResult(options.keys.length); + for (var keyI = options.keys.length - 1; keyI >= 0; --keyI) { + var target = _getValue(obj, options.keys[keyI]); + if (!target) { + objResults[keyI] = _noTarget; + continue; + } + if (!_isPrepared(target)) + target = _getPrepared(target); + target._score = _NEGATIVE_INFINITY; + target._indexes.len = 0; + objResults[keyI] = target; + } + objResults.obj = obj; + objResults._score = _NEGATIVE_INFINITY; + results.push(objResults); + if (results.length >= limit) + return results; + } + } else { + for (var i = 0; i < targets.length; i++) { + var target = targets[i]; + if (target == _NULL) + continue; + if (!_isPrepared(target)) + target = _getPrepared(target); + target._score = _NEGATIVE_INFINITY; + target._indexes.len = 0; + results.push(target); + if (results.length >= limit) + return results; + } + } + return results; + } + + function _algorithm(preparedSearch, prepared, allowSpaces, allowPartialMatch) { + if (allowSpaces === undefined) + allowSpaces = false; + if (allowPartialMatch === undefined) + allowPartialMatch = false; + + if (allowSpaces === false && preparedSearch.containsSpace) + return _algorithmSpaces(preparedSearch, prepared, allowPartialMatch); + + var searchLower = preparedSearch._lower; + var searchLowerCodes = preparedSearch.lowerCodes; + var searchLowerCode = searchLowerCodes[0]; + var targetLowerCodes = prepared._targetLowerCodes; + var searchLen = searchLowerCodes.length; + var targetLen = targetLowerCodes.length; + var searchI = 0; + var targetI = 0; + var matchesSimpleLen = 0; + + for (; ; ) { + var isMatch = searchLowerCode === targetLowerCodes[targetI]; + if (isMatch) { + _matchesSimple[matchesSimpleLen++] = targetI; + ++searchI; + if (searchI === searchLen) + break; + searchLowerCode = searchLowerCodes[searchI]; + } + ++targetI; + if (targetI >= targetLen) + return _NULL; + } + + searchI = 0; + var successStrict = false; + var matchesStrictLen = 0; + + var nextBeginningIndexes = prepared._nextBeginningIndexes; + if (nextBeginningIndexes === _NULL) + nextBeginningIndexes = prepared._nextBeginningIndexes = _prepareNextBeginningIndexes(prepared.target); + targetI = _matchesSimple[0] === 0 ? 0 : nextBeginningIndexes[_matchesSimple[0] - 1]; + + var backtrackCount = 0; + if (targetI !== targetLen) + for (; ; ) { + if (targetI >= targetLen) { + if (searchI <= 0) + break; + ++backtrackCount; + if (backtrackCount > 200) + break; + --searchI; + var lastMatch = _matchesStrict[--matchesStrictLen]; + targetI = nextBeginningIndexes[lastMatch]; + } else { + var isMatch = searchLowerCodes[searchI] === targetLowerCodes[targetI]; + if (isMatch) { + _matchesStrict[matchesStrictLen++] = targetI; + ++searchI; + if (searchI === searchLen) { + successStrict = true; + break; + } + ++targetI; + } else { + targetI = nextBeginningIndexes[targetI]; + } + } + } + + var substringIndex = searchLen <= 1 ? -1 : prepared._targetLower.indexOf(searchLower, _matchesSimple[0]); + var isSubstring = !!~substringIndex; + var isSubstringBeginning = !isSubstring ? false : substringIndex === 0 || prepared._nextBeginningIndexes[substringIndex - 1] === substringIndex; + + if (isSubstring && !isSubstringBeginning) { + for (var i = 0; i < nextBeginningIndexes.length; i = nextBeginningIndexes[i]) { + if (i <= substringIndex) + continue; + for (var s = 0; s < searchLen; s++) + if (searchLowerCodes[s] !== prepared._targetLowerCodes[i + s]) + break; + if (s === searchLen) { + substringIndex = i; + isSubstringBeginning = true; + break; + } + } + } + + var calculateScore = function (matches) { + var score = 0; + var extraMatchGroupCount = 0; + for (var i = 1; i < searchLen; ++i) { + if (matches[i] - matches[i - 1] !== 1) { + score -= matches[i]; + ++extraMatchGroupCount; + } + } + var unmatchedDistance = matches[searchLen - 1] - matches[0] - (searchLen - 1); + score -= (12 + unmatchedDistance) * extraMatchGroupCount; + if (matches[0] !== 0) + score -= matches[0] * matches[0] * 0.2; + if (!successStrict) { + score *= 1000; + } else { + var uniqueBeginningIndexes = 1; + for (var i = nextBeginningIndexes[0]; i < targetLen; i = nextBeginningIndexes[i]) + ++uniqueBeginningIndexes; + if (uniqueBeginningIndexes > 24) + score *= (uniqueBeginningIndexes - 24) * 10; + } + score -= (targetLen - searchLen) / 2; + if (isSubstring) + score /= 1 + searchLen * searchLen * 1; + if (isSubstringBeginning) + score /= 1 + searchLen * searchLen * 1; + score -= (targetLen - searchLen) / 2; + return score; + }; + + var matchesBest, score; + if (!successStrict) { + if (isSubstring) + for (var i = 0; i < searchLen; ++i) + _matchesSimple[i] = substringIndex + i; + matchesBest = _matchesSimple; + score = calculateScore(matchesBest); + } else { + if (isSubstringBeginning) { + for (var i = 0; i < searchLen; ++i) + _matchesSimple[i] = substringIndex + i; + matchesBest = _matchesSimple; + score = calculateScore(_matchesSimple); + } else { + matchesBest = _matchesStrict; + score = calculateScore(_matchesStrict); + } + } + + prepared._score = score; + for (var i = 0; i < searchLen; ++i) + prepared._indexes[i] = matchesBest[i]; + prepared._indexes.len = searchLen; + + var result = _createResult(); + result.target = prepared.target; + result._score = prepared._score; + result._indexes = prepared._indexes; + return result; + } + + function _algorithmSpaces(preparedSearch, target, allowPartialMatch) { + var seen_indexes = new Set(); + var score = 0; + var result = _NULL; + + var first_seen_index_last_search = 0; + var searches = preparedSearch.spaceSearches; + var searchesLen = searches.length; + var changeslen = 0; + + var resetNextBeginningIndexes = function () { + for (let i = changeslen - 1; i >= 0; i--) + target._nextBeginningIndexes[_nextBeginningIndexesChanges[i * 2 + 0]] = _nextBeginningIndexesChanges[i * 2 + 1]; + }; + + var hasAtLeast1Match = false; + for (var i = 0; i < searchesLen; ++i) { + _allowPartialMatchScores[i] = _NEGATIVE_INFINITY; + var search = searches[i]; + result = _algorithm(search, target); + + if (allowPartialMatch) { + if (result === _NULL) + continue; + hasAtLeast1Match = true; + } else { + if (result === _NULL) { + resetNextBeginningIndexes(); + return _NULL; + } + } + + var isTheLastSearch = i === searchesLen - 1; + if (!isTheLastSearch) { + var indexes = result._indexes; + var indexesIsConsecutiveSubstring = true; + for (let j = 0; j < indexes.len - 1; j++) { + if (indexes[j + 1] - indexes[j] !== 1) { + indexesIsConsecutiveSubstring = false; + break; + } + } + + if (indexesIsConsecutiveSubstring) { + var newBeginningIndex = indexes[indexes.len - 1] + 1; + var toReplace = target._nextBeginningIndexes[newBeginningIndex - 1]; + for (let j = newBeginningIndex - 1; j >= 0; j--) { + if (toReplace !== target._nextBeginningIndexes[j]) + break; + target._nextBeginningIndexes[j] = newBeginningIndex; + _nextBeginningIndexesChanges[changeslen * 2 + 0] = j; + _nextBeginningIndexesChanges[changeslen * 2 + 1] = toReplace; + changeslen++; + } + } + } + + score += result._score / searchesLen; + _allowPartialMatchScores[i] = result._score / searchesLen; + + if (result._indexes[0] < first_seen_index_last_search) { + score -= (first_seen_index_last_search - result._indexes[0]) * 2; + } + first_seen_index_last_search = result._indexes[0]; + + for (var j = 0; j < result._indexes.len; ++j) + seen_indexes.add(result._indexes[j]); + } + + if (allowPartialMatch && !hasAtLeast1Match) + return _NULL; + + resetNextBeginningIndexes(); + + var allowSpacesResult = _algorithm(preparedSearch, target, true); + if (allowSpacesResult !== _NULL && allowSpacesResult._score > score) { + if (allowPartialMatch) { + for (var i = 0; i < searchesLen; ++i) { + _allowPartialMatchScores[i] = allowSpacesResult._score / searchesLen; + } + } + return allowSpacesResult; + } + + if (allowPartialMatch) + result = target; + result._score = score; + + var idx = 0; + for (let index of seen_indexes) + result._indexes[idx++] = index; + result._indexes.len = idx; + + return result; + } + + function _go(search, targets, options) { + if (!search) + return options?.all ? _all(targets, options) : _noResults; + + var preparedSearch = _getPreparedSearch(search); + var searchBitflags = preparedSearch.bitflags; + var containsSpace = preparedSearch.containsSpace; + + var threshold = _denormalizeScore(options?.threshold ?? 0.35); + var limit = options?.limit || _INFINITY; + + var resultsLen = 0; + var limitedCount = 0; + var targetsLen = targets.length; + + function push_result(result) { + if (resultsLen < limit) { + _q.add(result); + ++resultsLen; + } else { + ++limitedCount; + if (result._score > _q.peek()._score) + _q.replaceTop(result); + } + } + + if (options?.key) { + var key = options.key; + for (var i = 0; i < targetsLen; ++i) { + var obj = targets[i]; + var target = _getValue(obj, key); + if (!target) + continue; + if (!_isPrepared(target)) + target = _getPrepared(target); + if ((searchBitflags & target._bitflags) !== searchBitflags) + continue; + var result = _algorithm(preparedSearch, target); + if (result === _NULL) + continue; + if (result._score < threshold) + continue; + result.obj = obj; + push_result(result); + } + } else if (options?.keys) { + var keys = options.keys; + var keysLen = keys.length; + + outer: for (var i = 0; i < targetsLen; ++i) { + var obj = targets[i]; + var keysBitflags = 0; + for (var keyI = 0; keyI < keysLen; ++keyI) { + var key = keys[keyI]; + var target = _getValue(obj, key); + if (!target) { + _tmpTargets[keyI] = _noTarget; + continue; + } + if (!_isPrepared(target)) + target = _getPrepared(target); + _tmpTargets[keyI] = target; + keysBitflags |= target._bitflags; + } + + if ((searchBitflags & keysBitflags) !== searchBitflags) + continue; + + if (containsSpace) + for (let j = 0; j < preparedSearch.spaceSearches.length; j++) + _keysSpacesBestScores[j] = _NEGATIVE_INFINITY; + + for (var keyI = 0; keyI < keysLen; ++keyI) { + target = _tmpTargets[keyI]; + if (target === _noTarget) { + _tmpResults[keyI] = _noTarget; + continue; + } + + _tmpResults[keyI] = _algorithm(preparedSearch, target, false, containsSpace); + if (_tmpResults[keyI] === _NULL) { + _tmpResults[keyI] = _noTarget; + continue; + } + + if (containsSpace) + for (let j = 0; j < preparedSearch.spaceSearches.length; j++) { + if (_allowPartialMatchScores[j] > -1000) { + if (_keysSpacesBestScores[j] > _NEGATIVE_INFINITY) { + var tmp = (_keysSpacesBestScores[j] + _allowPartialMatchScores[j]) / 4; + if (tmp > _keysSpacesBestScores[j]) + _keysSpacesBestScores[j] = tmp; + } + } + if (_allowPartialMatchScores[j] > _keysSpacesBestScores[j]) + _keysSpacesBestScores[j] = _allowPartialMatchScores[j]; + } + } + + if (containsSpace) { + for (let j = 0; j < preparedSearch.spaceSearches.length; j++) + if (_keysSpacesBestScores[j] === _NEGATIVE_INFINITY) + continue outer; + } else { + var hasAtLeast1Match = false; + for (let j = 0; j < keysLen; j++) + if (_tmpResults[j]._score !== _NEGATIVE_INFINITY) { + hasAtLeast1Match = true; + break; + } + if (!hasAtLeast1Match) + continue; + } + + var objResults = _createKeysResult(keysLen); + for (let j = 0; j < keysLen; j++) + objResults[j] = _tmpResults[j]; + + var score; + if (containsSpace) { + score = 0; + for (let j = 0; j < preparedSearch.spaceSearches.length; j++) + score += _keysSpacesBestScores[j]; + } else { + score = _NEGATIVE_INFINITY; + for (let j = 0; j < keysLen; j++) { + var res = objResults[j]; + if (res._score > -1000) { + if (score > _NEGATIVE_INFINITY) { + var tmp = (score + res._score) / 4; + if (tmp > score) + score = tmp; + } + } + if (res._score > score) + score = res._score; + } + } + + objResults.obj = obj; + objResults._score = score; + + if (options?.scoreFn) { + score = options.scoreFn(objResults); + if (!score) + continue; + score = _denormalizeScore(score); + objResults._score = score; + } + + if (score < threshold) + continue; + push_result(objResults); + } + } else { + for (var i = 0; i < targetsLen; ++i) { + var target = targets[i]; + if (!target) + continue; + if (!_isPrepared(target)) + target = _getPrepared(target); + if ((searchBitflags & target._bitflags) !== searchBitflags) + continue; + var result = _algorithm(preparedSearch, target); + if (result === _NULL) + continue; + if (result._score < threshold) + continue; + push_result(result); + } + } + + if (resultsLen === 0) + return _noResults; + var results = new Array(resultsLen); + for (var i = resultsLen - 1; i >= 0; --i) + results[i] = _q.poll(); + results.total = resultsLen + limitedCount; + return results; + } +} diff --git a/quickshell/compat/noctalia/Commons/I18n.qml b/quickshell/compat/noctalia/Commons/I18n.qml new file mode 100644 index 0000000..8df4fcc --- /dev/null +++ b/quickshell/compat/noctalia/Commons/I18n.qml @@ -0,0 +1,375 @@ +pragma Singleton + +import QtQuick +import Quickshell +import Quickshell.Io +import qs.compat.noctalia.Commons + +Singleton { + id: root + + property bool isLoaded: false + property string langCode: "" + property var locale: Qt.locale() + property string systemDetectedLangCode: "" + property string fullLocaleCode: "" // Preserves regional locale variants + property var translations: ({}) + property var fallbackTranslations: ({}) + + // Static list of available translations — update when adding/removing translation files + property var availableLanguages: ["en", "en-GB", "cs", "de", "es", "fr", "hu", "it", "ja", "ko-KR", "ku", "nl", "nn-HN", "nn-NO", "pl", "pt", "ru", "sv", "tr", "uk-UA", "vi", "zh-CN", "zh-TW"] + + // Default date format per language (used by lock screen, etc.) + readonly property var dateFormats: ({ + "cs": "dddd d. MMMM", + "de": "dddd, d. MMMM", + "en": "dddd, MMMM d", + "es": "dddd, d 'de' MMMM", + "fr": "dddd d MMMM", + "hu": "MMMM d., dddd", + "it": "dddd d MMMM", + "ja": "yyyy年M月d日 dddd", + "ko": "yyyy년 M월 d일 dddd", + "ku": "dddd, dê MMMM", + "nl": "dddd d MMMM", + "nn": "dddd d. MMMM", + "pl": "dddd, d MMMM", + "pt": "dddd, d 'de' MMMM", + "ro": "dddd, d MMMM", + "ru": "dddd, d MMMM", + "sv": "dddd d MMMM", + "tr": "dddd, d MMMM", + "uk": "dddd, d MMMM", + "vi": "dddd, d 'tháng' M", + "zh": "yyyy年M月d日 dddd" + }) + + // Signals for reactive updates + signal languageChanged(string newLanguage) + signal translationsLoaded + + // FileView to load translation files + property FileView translationFile: FileView { + id: fileView + printErrors: false + watchChanges: true + onFileChanged: reload() + onLoaded: { + try { + var data = JSON.parse(text()); + root.translations = data; + Logger.i("I18n", `Loaded translations for "${root.langCode}"`); + + root.isLoaded = true; + root.translationsLoaded(); + + // Load English fallback for non-English languages (only after main file succeeds) + if (root.langCode !== "en") { + fallbackFileView.path = `file://${Quickshell.shellDir}/compat/noctalia/Assets/Translations/en.json`; + } + } catch (e) { + Logger.e("I18n", `Failed to parse translation file: ${e}`); + setLanguage("en"); + } + } + onLoadFailed: function (error) { + if (root.langCode === "en") { + Logger.e("I18n", `Failed to load English translation file: ${error}`); + // English also failed - still emit signal to unblock startup + root.isLoaded = true; + root.translationsLoaded(); + return; + } + + // Qt.callLater is needed because FileView doesn't re-trigger when path + // is changed inside its own onLoadFailed handler + var strippedCode = stripScript(root.langCode); + if (strippedCode !== root.langCode) { + Logger.d("I18n", `Translation file for "${root.langCode}" not found, trying "${strippedCode}"`); + root.langCode = strippedCode; + Qt.callLater(loadTranslations); + } else { + // Try language-only code (e.g. "zh-CN" → "zh") + var shortCode = root.langCode.substring(0, 2); + if (shortCode !== root.langCode) { + Logger.d("I18n", `Translation file for "${root.langCode}" not found, trying "${shortCode}"`); + root.langCode = shortCode; + Qt.callLater(loadTranslations); + } else { + Logger.w("I18n", `Translation file for "${root.langCode}" not found, falling back to English`); + root.langCode = "en"; + root.fullLocaleCode = "en"; + root.locale = Qt.locale("en"); + Qt.callLater(loadTranslations); + } + } + } + } + + // FileView to load fallback translation files + property FileView fallbackTranslationFile: FileView { + id: fallbackFileView + watchChanges: true + onFileChanged: reload() + onLoaded: { + try { + var data = JSON.parse(text()); + root.fallbackTranslations = data; + Logger.d("I18n", `Loaded english fallback translations`); + } catch (e) { + Logger.e("I18n", `Failed to parse fallback translation file: ${e}`); + } + } + onLoadFailed: function (error) { + Logger.e("I18n", `Failed to load fallback translation file: ${error}`); + } + } + + // Correct language when settings finish loading from disk (or user changes it) + Connections { + target: Settings.data.general + function onLanguageChanged() { + var userLang = Settings.data.general.language; + if (userLang !== "" && userLang !== root.langCode && availableLanguages.includes(userLang)) { + Logger.i("I18n", `Applying user language preference: "${userLang}"`); + setLanguage(userLang); + } else if (userLang === "" && root.systemDetectedLangCode !== "" && root.systemDetectedLangCode !== root.langCode) { + Logger.i("I18n", `Language reset to default, reverting to system language: "${root.systemDetectedLangCode}"`); + setLanguage(root.systemDetectedLangCode); + } + } + } + + Component.onCompleted: { + Logger.i("I18n", "Service started"); + + var lang = determineFastLanguage(); + langCode = lang.code; + fullLocaleCode = lang.fullLocale; + locale = Qt.locale(lang.fullLocale); + systemDetectedLangCode = lang.code; + Logger.i("I18n", `Loading "${lang.code}" (locale: "${lang.fullLocale}")`); + loadTranslations(); + } + + // Strip 4-letter script subtag from a BCP 47 tag (e.g. "fr-Latn-FR" → "fr-FR") + function stripScript(tag) { + var parts = tag.split("-"); + var result = []; + for (var i = 0; i < parts.length; i++) { + if (parts[i].length === 4 && /^[A-Za-z]{4}$/.test(parts[i])) { + continue; + } + result.push(parts[i]); + } + return result.join("-"); + } + + // Determine the best language match against availableLanguages + function determineFastLanguage() { + // User preference from Settings (defaults to "" if not yet loaded from disk) + var userLang = Settings.data.general.language; + if (userLang !== "" && availableLanguages.includes(userLang)) { + return { + code: userLang, + fullLocale: userLang + }; + } + + // Match system locale against available translations + for (var i = 0; i < Qt.locale().uiLanguages.length; i++) { + var fullLang = Qt.locale().uiLanguages[i]; + + // Exact match (e.g. "zh-CN") + if (availableLanguages.includes(fullLang)) { + return { + code: fullLang, + fullLocale: fullLang + }; + } + + // Script-stripped match (e.g. "zh-Hans-CN" → "zh-CN") + var stripped = stripScript(fullLang); + if (stripped !== fullLang && availableLanguages.includes(stripped)) { + return { + code: stripped, + fullLocale: fullLang + }; + } + + // Language-only match (e.g. "fr-FR" → "fr") + var short_ = fullLang.substring(0, 2); + if (availableLanguages.includes(short_)) { + return { + code: short_, + fullLocale: fullLang + }; + } + } + + return { + code: "en", + fullLocale: "en" + }; + } + + function dateFormat() { + var lang = langCode.split("-")[0]; + return dateFormats[lang] || "dddd, d MMMM"; + } + + // ------------------------------------------- + function setLanguage(newLangCode, fullLocale) { + if (typeof fullLocale === "undefined") { + fullLocale = newLangCode; + } + + if (newLangCode !== langCode && availableLanguages.includes(newLangCode)) { + langCode = newLangCode; + fullLocaleCode = fullLocale; + locale = Qt.locale(fullLocale); + Logger.i("I18n", `Language set to "${langCode}" with locale "${fullLocale}"`); + languageChanged(langCode); + loadTranslations(); + } else if (!availableLanguages.includes(newLangCode)) { + Logger.w("I18n", `Language "${newLangCode}" is not available`); + } + } + + // ------------------------------------------- + function loadTranslations() { + if (langCode === "") + return; + const filePath = `file://${Quickshell.shellDir}/compat/noctalia/Assets/Translations/${langCode}.json`; + fileView.path = filePath; + isLoaded = false; + } + + // ------------------------------------------- + // Check if a translation exists + function hasTranslation(key) { + if (!isLoaded) + return false; + + const keys = key.split("."); + var value = translations; + + for (var i = 0; i < keys.length; i++) { + if (value && typeof value === "object" && keys[i] in value) { + value = value[keys[i]]; + } else { + return false; + } + } + + return typeof value === "string"; + } + + // ------------------------------------------- + // Get all translation keys (useful for debugging) + function getAllKeys(obj, prefix) { + if (typeof obj === "undefined") + obj = translations; + if (typeof prefix === "undefined") + prefix = ""; + + var keys = []; + for (var key in (obj || {})) { + const value = obj[key]; + const fullKey = prefix ? `${prefix}.${key}` : key; + if (typeof value === "object" && value !== null) { + keys = keys.concat(getAllKeys(value, fullKey)); + } else if (typeof value === "string") { + keys.push(fullKey); + } + } + return keys; + } + + // ------------------------------------------- + // Reload translations (useful for development) + function reload() { + Logger.d("I18n", "Reloading translations"); + loadTranslations(); + } + + // ------------------------------------------- + // Main translation function + function tr(key, interpolations) { + if (typeof interpolations === "undefined") + interpolations = {}; + + if (!isLoaded) { + //Logger.d("I18n", "Translations not loaded yet") + return key; + } + + // Navigate nested keys (e.g., "menu.file.open") + const keys = key.split("."); + + // Look-up translation in the active language + var value = translations; + var notFound = false; + for (var i = 0; i < keys.length; i++) { + if (value && typeof value === "object" && keys[i] in value) { + value = value[keys[i]]; + } else { + Logger.d("I18n", `Translation key "${key}" not found at part "${keys[i]}"`); + Logger.d("I18n", `Available keys: ${Object.keys(value || {}).join(", ")}`); + notFound = true; + break; + } + } + + // Fallback to english if not found + if (notFound && availableLanguages.includes("en") && langCode !== "en") { + value = fallbackTranslations; + for (var i = 0; i < keys.length; i++) { + if (value && typeof value === "object" && keys[i] in value) { + value = value[keys[i]]; + } else { + // Indicate this key does not even exists in the english fallback + return `!!${key}!!`; + } + } + } else if (notFound) { + // No fallback available + return `!!${key}!!`; + } + + if (typeof value !== "string") { + Logger.d("I18n", `Translation key "${key}" is not a string`); + return key; + } + + // Handle interpolations (e.g., "Hello {name}!") + var result = value; + for (var placeholder in interpolations) { + const regex = new RegExp(`\\{${placeholder}\\}`, 'g'); + result = result.replace(regex, interpolations[placeholder]); + } + + return result; + } + + // ------------------------------------------- + // Plural translation function + function trp(key, count, interpolations) { + if (typeof interpolations === "undefined") { + interpolations = {}; + } + + // Use key for singular, key-plural for plural + const realKey = count === 1 ? key : `${key}-plural`; + + // Merge interpolations with count + var finalInterpolations = { + "count": count + }; + for (var prop in interpolations) { + finalInterpolations[prop] = interpolations[prop]; + } + + return tr(realKey, finalInterpolations); + } +} diff --git a/quickshell/compat/noctalia/Commons/Icons.qml b/quickshell/compat/noctalia/Commons/Icons.qml new file mode 100644 index 0000000..5e6eaa5 --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Icons.qml @@ -0,0 +1,85 @@ +pragma Singleton + +import QtQuick +import QtQuick.Controls +import Quickshell +import qs.compat.noctalia.Commons + +Singleton { + id: root + + // Expose the font family name for easy access + readonly property string fontFamily: currentFontLoader ? currentFontLoader.name : "" + readonly property string defaultIcon: IconsTabler.defaultIcon + readonly property var icons: IconsTabler.icons + readonly property var aliases: IconsTabler.aliases + readonly property string fontPath: "/compat/noctalia/Assets/Fonts/tabler/noctalia-tabler-icons.ttf" + + // Current active font loader + property FontLoader currentFontLoader: null + property int fontVersion: 0 + + // Create a unique cache-busting path + readonly property string cacheBustingPath: Quickshell.shellDir + fontPath + "?v=" + fontVersion + "&t=" + Date.now() + + // Signal emitted when font is reloaded + signal fontReloaded + + Component.onCompleted: { + Logger.i("Icons", "Service started"); + loadFontWithCacheBusting(); + } + + Connections { + target: Quickshell + function onReloadCompleted() { + Logger.d("Icons", "Quickshell reload completed - forcing font reload"); + reloadFont(); + } + } + + // --------------------------------------- + function get(iconName) { + // Check in aliases first + if (aliases[iconName] !== undefined) { + iconName = aliases[iconName]; + } + + // Find the appropriate codepoint + return icons[iconName]; + } + + function loadFontWithCacheBusting() { + Logger.d("Icons", "Loading font with cache busting"); + + // Destroy old loader first + if (currentFontLoader) { + currentFontLoader.destroy(); + currentFontLoader = null; + } + + // Create new loader with cache-busting URL + currentFontLoader = Qt.createQmlObject(` + import QtQuick + FontLoader { + source: "${cacheBustingPath}" + } + `, root, "dynamicFontLoader_" + fontVersion); + + // Connect to the new loader's status changes + currentFontLoader.statusChanged.connect(function () { + if (currentFontLoader.status === FontLoader.Ready) { + Logger.d("Icons", "Font loaded successfully:", currentFontLoader.name, "(version " + fontVersion + ")"); + fontReloaded(); + } else if (currentFontLoader.status === FontLoader.Error) { + Logger.e("Icons", "Font failed to load (version " + fontVersion + ")"); + } + }); + } + + function reloadFont() { + Logger.d("Icons", "Forcing font reload..."); + fontVersion++; + loadFontWithCacheBusting(); + } +} diff --git a/quickshell/compat/noctalia/Commons/IconsTabler.qml b/quickshell/compat/noctalia/Commons/IconsTabler.qml new file mode 100644 index 0000000..5efc5f5 --- /dev/null +++ b/quickshell/compat/noctalia/Commons/IconsTabler.qml @@ -0,0 +1,6204 @@ +pragma Singleton + +import QtQuick +import Quickshell + +Singleton { + id: root + + readonly property string defaultIcon: "skull" + + readonly property var aliases: { + "close": "x", + "check": "check", + "settings": "settings", + "refresh": "refresh", + "add": "plus", + "trash": "trash", + "menu": "menu-2", + "person": "user", + "folder-open": "folder-open", + "download": "download", + "toast-notice": "circle-check", + "toast-warning": "alert-circle", + "toast-error": "circle-x", + "question-mark": "question-mark", + "search": "search", + "warning": "exclamation-circle", + "stop": "player-stop-filled", + "busy": "hourglass-empty", + "media-pause": "player-pause-filled", + "media-play": "player-play-filled", + "media-prev": "player-skip-back-filled", + "media-next": "player-skip-forward-filled", + "download-speed": "download", + "upload-speed": "upload", + "cpu-intensive": "alert-octagon", + "cpu-usage": "brand-speedtest", + "cpu-temperature": "flame", + "gpu-temperature": "device-desktop", + "memory": "cpu", + "performance": "gauge", + "balanced": "scale", + "powersaver": "leaf", + "storage": "database", + "keyboard": "keyboard", + "shutdown": "power", + "lock": "lock", + "lock-pause": "lock-pause", + "logout": "logout", + "reboot": "refresh", + "suspend": "player-pause", + "hibernate": "zzz", + "nightlight-on": "moon", + "nightlight-off": "moon-off", + "nightlight-forced": "moon-stars", + "bell": "bell", + "bell-off": "bell-off", + "keep-awake-on": "mug", + "keep-awake-off": "mug-off", + "disc": "disc-filled", + "eye": "eye", + "pin": "pin", + "unpin": "pinned-off", + "image": "photo", + "dark-mode": "contrast-filled", + "camera-video": "video", + "wallpaper-selector": "library-photo", + "color-picker": "color-picker", + "chevron-left": "chevron-left", + "chevron-right": "chevron-right", + "chevron-up": "chevron-up", + "chevron-down": "chevron-down", + "caret-up": "caret-up-filled", + "caret-down": "caret-down-filled", + "caret-left": "caret-left-filled", + "caret-right": "caret-right-filled", + "star": "star", + "star-off": "star-off", + "battery-exclamation": "battery-exclamation", + "battery-charging": "battery-charging", + "battery-charging-2": "battery-charging-2", + "battery-4": "battery-4", + "battery-3": "battery-3", + "battery-2": "battery-2", + "battery-1": "battery-1", + "battery": "battery", + "battery-off": "battery-off", + "wifi-0": "wifi-0", + "wifi-1": "wifi-1", + "wifi-2": "wifi-2", + "wifi-off": "wifi-off", + "wifi": "wifi", + "microphone": "microphone", + "microphone-mute": "microphone-off", + "volume-mute": "volume-off", + "volume-x": "volume-3", + "volume-zero": "volume-3", + "volume-low": "volume-2", + "volume-high": "volume", + "weather-sun": "sun", + "weather-moon": "moon", + "weather-moon-stars": "moon-stars", + "weather-cloud-off": "cloud-off", + "weather-cloud": "cloud", + "weather-cloud-haze": "cloud-fog", + "weather-cloud-lightning": "cloud-bolt", + "weather-cloud-rain": "cloud-rain", + "weather-cloud-snow": "cloud-snow", + "weather-cloud-sun": "cloud-sun", + "brightness-low": "brightness-down-filled", + "brightness-high": "brightness-up-filled", + "settings-general": "adjustments-horizontal", + "settings-bar": "crop-16-9", + "settings-user-interface": "layout-board", + "settings-control-center": "adjustments-horizontal", + "settings-dock": "layout-bottombar", + "settings-launcher": "rocket", + "settings-audio": "device-speaker", + "settings-display": "device-desktop", + "settings-network": "circles-relation", + "settings-brightness": "brightness-up", + "settings-location": "world-pin", + "settings-color-scheme": "palette", + "settings-wallpaper": "paint", + "settings-wallpaper-selector": "library-photo", + "settings-hooks": "link", + "settings-notifications": "bell", + "settings-osd": "picture-in-picture", + "settings-about": "info-square-rounded", + "settings-idle": "moon", + "settings-lock-screen": "lock", + "settings-session-menu": "power", + "settings-system-monitor": "activity", + "bluetooth": "bluetooth", + "bt-device-generic": "bluetooth", + "bt-device-gamepad": "device-gamepad-2", + "bt-device-microphone": "microphone", + "bt-device-headset": "headset", + "bt-device-earbuds": "device-airpods", + "bt-device-headphones": "headphones", + "bt-device-mouse": "mouse-2", + "bt-device-keyboard": "bluetooth", + "bt-device-phone": "device-mobile", + "bt-device-watch": "device-watch", + "bt-device-speaker": "device-speaker", + "bt-device-tv": "device-tv", + "antenna-bars-1": "antenna-bars-1", + "antenna-bars-2": "antenna-bars-2", + "antenna-bars-3": "antenna-bars-3", + "antenna-bars-4": "antenna-bars-4", + "antenna-bars-5": "antenna-bars-5", + "antenna-bars-off": "antenna-bars-off", + "noctalia": "noctalia", + "hyprland": "hyprland", + "filepicker-folder": "folder", + "filepicker-refresh": "refresh", + "filepicker-close": "x", + "filepicker-arrow-left": "arrow-left", + "filepicker-arrow-up": "arrow-up", + "filepicker-home": "home", + "filepicker-layout-grid": "layout-grid", + "filepicker-list": "list", + "filepicker-search": "search", + "filepicker-x": "x", + "filepicker-photo": "photo", + "filepicker-check": "check", + "filepicker-file-text": "file-text", + "filepicker-video": "video", + "filepicker-music": "music", + "filepicker-archive": "archive", + "filepicker-table": "table", + "filepicker-presentation": "presentation", + "filepicker-code": "code", + "filepicker-settings": "settings", + "filepicker-file": "file", + "filepicker-text": "file-text", + "filepicker-eye": "eye", + "filepicker-eye-off": "eye-off", + "filepicker-folder-current": "checks", + "plugin": "plug-connected", + "info": "file-description", + "official-plugin": "shield-filled" + } + + // Fonts Codepoints - do not change! + // Some icons have been disabled because Qt's text rendering engine recognizes + // some ranges as special Unicode characters at a very low level. + // ex: fe00-fe2f + readonly property var icons: { + "123": "\u{f554}", + "360": "\u{f62f}", + "12-hours": "\u{fc53}", + "24-hours": "\u{f5e7}", + "2fa": "\u{eca0}", + "360-view": "\u{f566}", + "3d-cube-sphere": "\u{ecd7}", + "3d-cube-sphere-off": "\u{f3b5}", + "3d-rotate": "\u{f020}", + "a-b": "\u{ec36}", + "a-b-2": "\u{f25f}", + "a-b-off": "\u{f0a6}", + "abacus": "\u{f05c}", + "abacus-off": "\u{f3b6}", + "abc": "\u{f567}", + "access-point": "\u{ed1b}", + "access-point-off": "\u{ed1a}", + "accessible": "\u{eba9}", + "accessible-filled": "\u{f6ea}", + "accessible-off": "\u{f0a7}", + "activity": "\u{ed23}", + "activity-heartbeat": "\u{f0db}", + "ad": "\u{ea02}", + "ad-2": "\u{ef1f}", + "ad-circle": "\u{f79e}", + "ad-circle-filled": "\u{f7d3}", + "ad-circle-off": "\u{f79d}", + "ad-filled": "\u{f6eb}", + "ad-off": "\u{f3b7}", + "address-book": "\u{f021}", + "address-book-off": "\u{f3b8}", + "adjustments": "\u{ea03}", + "adjustments-alt": "\u{ec37}", + "adjustments-bolt": "\u{f7fb}", + "adjustments-cancel": "\u{f7fc}", + "adjustments-check": "\u{f7fd}", + "adjustments-code": "\u{f7fe}", + "adjustments-cog": "\u{f7ff}", + "adjustments-dollar": "\u{f800}", + "adjustments-down": "\u{f801}", + "adjustments-exclamation": "\u{f802}", + "adjustments-filled": "\u{f6ec}", + "adjustments-heart": "\u{f803}", + "adjustments-horizontal": "\u{ec38}", + "adjustments-minus": "\u{f804}", + "adjustments-off": "\u{f0a8}", + "adjustments-pause": "\u{f805}", + "adjustments-pin": "\u{f806}", + "adjustments-plus": "\u{f807}", + "adjustments-question": "\u{f808}", + "adjustments-search": "\u{f809}", + "adjustments-share": "\u{f80a}", + "adjustments-spark": "\u{ffbe}", + "adjustments-star": "\u{f80b}", + "adjustments-up": "\u{f80c}", + "adjustments-x": "\u{f80d}", + "aerial-lift": "\u{edfe}", + "aerial-lift-filled": "\u{10101}", + "affiliate": "\u{edff}", + "affiliate-filled": "\u{f6ed}", + "ai": "\u{fee7}", + "air-balloon": "\u{f4a6}", + "air-balloon-filled": "\u{10100}", + "air-conditioning": "\u{f3a2}", + "air-conditioning-disabled": "\u{f542}", + "air-traffic-control": "\u{fb01}", + "alarm": "\u{ea04}", + "alarm-average": "\u{fc9e}", + "alarm-filled": "\u{f709}", + "alarm-minus": "\u{f630}", + "alarm-minus-filled": "\u{f70a}", + "alarm-off": "\u{f0a9}", + "alarm-plus": "\u{f631}", + "alarm-plus-filled": "\u{f70b}", + "alarm-smoke": "\u{100b6}", + "alarm-snooze": "\u{f632}", + "alarm-snooze-filled": "\u{f70c}", + "album": "\u{f022}", + "album-off": "\u{f3b9}", + "alert-circle": "\u{ea05}", + "alert-circle-filled": "\u{f6ee}", + "alert-circle-off": "\u{fc65}", + "alert-hexagon": "\u{f80e}", + "alert-hexagon-filled": "\u{fa34}", + "alert-hexagon-off": "\u{fc66}", + "alert-octagon": "\u{ecc6}", + "alert-octagon-filled": "\u{f6ef}", + "alert-small": "\u{f80f}", + "alert-small-off": "\u{fc67}", + "alert-square": "\u{f811}", + "alert-square-filled": "\u{fa35}", + "alert-square-rounded": "\u{f810}", + "alert-square-rounded-filled": "\u{fa36}", + "alert-square-rounded-off": "\u{fc68}", + "alert-triangle": "\u{ea06}", + "alert-triangle-filled": "\u{f6f0}", + "alert-triangle-off": "\u{fc69}", + "alien": "\u{ebde}", + "alien-filled": "\u{f70d}", + "align-box-bottom-center": "\u{f530}", + "align-box-bottom-center-filled": "\u{f70e}", + "align-box-bottom-left": "\u{f531}", + "align-box-bottom-left-filled": "\u{f70f}", + "align-box-bottom-right": "\u{f532}", + "align-box-bottom-right-filled": "\u{f710}", + "align-box-center-bottom": "\u{facb}", + "align-box-center-middle": "\u{f79f}", + "align-box-center-middle-filled": "\u{f7d4}", + "align-box-center-stretch": "\u{facc}", + "align-box-center-top": "\u{facd}", + "align-box-left-bottom": "\u{f533}", + "align-box-left-bottom-filled": "\u{f711}", + "align-box-left-middle": "\u{f534}", + "align-box-left-middle-filled": "\u{f712}", + "align-box-left-stretch": "\u{face}", + "align-box-left-top": "\u{f535}", + "align-box-left-top-filled": "\u{f713}", + "align-box-right-bottom": "\u{f536}", + "align-box-right-bottom-filled": "\u{f714}", + "align-box-right-middle": "\u{f537}", + "align-box-right-middle-filled": "\u{f7d5}", + "align-box-right-stretch": "\u{facf}", + "align-box-right-top": "\u{f538}", + "align-box-right-top-filled": "\u{f715}", + "align-box-top-center": "\u{f539}", + "align-box-top-center-filled": "\u{f716}", + "align-box-top-left": "\u{f53a}", + "align-box-top-left-filled": "\u{f717}", + "align-box-top-right": "\u{f53b}", + "align-box-top-right-filled": "\u{f718}", + "align-center": "\u{ea07}", + "align-justified": "\u{ea08}", + "align-left": "\u{ea09}", + "align-left-2": "\u{ff00}", + "align-right": "\u{ea0a}", + //"align-right-2": "\u{feff}", + "alpha": "\u{f543}", + "alphabet-arabic": "\u{ff2f}", + "alphabet-bangla": "\u{ff2e}", + "alphabet-cyrillic": "\u{f1df}", + "alphabet-greek": "\u{f1e0}", + "alphabet-hebrew": "\u{ff2d}", + "alphabet-korean": "\u{ff2c}", + "alphabet-latin": "\u{f1e1}", + "alphabet-thai": "\u{ff2b}", + "alt": "\u{fc54}", + "ambulance": "\u{ebf5}", + "ampersand": "\u{f229}", + "analyze": "\u{f3a3}", + "analyze-filled": "\u{f719}", + "analyze-off": "\u{f3ba}", + "anchor": "\u{eb76}", + "anchor-off": "\u{f0f7}", + "angle": "\u{ef20}", + "ankh": "\u{f1cd}", + "antenna": "\u{f094}", + "antenna-bars-1": "\u{ecc7}", + "antenna-bars-2": "\u{ecc8}", + "antenna-bars-3": "\u{ecc9}", + "antenna-bars-4": "\u{ecca}", + "antenna-bars-5": "\u{eccb}", + "antenna-bars-off": "\u{f0aa}", + "antenna-off": "\u{f3bb}", + "aperture": "\u{eb58}", + "aperture-off": "\u{f3bc}", + "api": "\u{effd}", + "api-app": "\u{effc}", + "api-app-off": "\u{f0ab}", + "api-off": "\u{f0f8}", + "app-window": "\u{efe6}", + "app-window-filled": "\u{f71a}", + "apple": "\u{ef21}", + "apple-filled": "\u{10017}", + "apps": "\u{ebb6}", + "apps-filled": "\u{f6f1}", + "apps-off": "\u{f0ac}", + "archery-arrow": "\u{fc55}", + "archive": "\u{ea0b}", + "archive-filled": "\u{fa82}", + "archive-off": "\u{f0ad}", + "armchair": "\u{ef9e}", + "armchair-2": "\u{efe7}", + "armchair-2-off": "\u{f3bd}", + "armchair-off": "\u{f3be}", + "arrow-autofit-content": "\u{ef31}", + "arrow-autofit-content-filled": "\u{f6f2}", + "arrow-autofit-down": "\u{ef32}", + "arrow-autofit-down-filled": "\u{10113}", + "arrow-autofit-height": "\u{ef33}", + "arrow-autofit-height-filled": "\u{10112}", + "arrow-autofit-left": "\u{ef34}", + "arrow-autofit-left-filled": "\u{10111}", + "arrow-autofit-right": "\u{ef35}", + "arrow-autofit-right-filled": "\u{10110}", + "arrow-autofit-up": "\u{ef36}", + "arrow-autofit-up-filled": "\u{1010f}", + "arrow-autofit-width": "\u{ef37}", + "arrow-autofit-width-filled": "\u{1010e}", + "arrow-back": "\u{ea0c}", + "arrow-back-up": "\u{eb77}", + "arrow-back-up-double": "\u{f9ec}", + "arrow-badge-down": "\u{f60b}", + "arrow-badge-down-filled": "\u{f7d6}", + "arrow-badge-left": "\u{f60c}", + "arrow-badge-left-filled": "\u{f7d7}", + "arrow-badge-right": "\u{f60d}", + "arrow-badge-right-filled": "\u{f7d8}", + "arrow-badge-up": "\u{f60e}", + "arrow-badge-up-filled": "\u{f7d9}", + "arrow-bar-both": "\u{fadd}", + "arrow-bar-down": "\u{ea0d}", + "arrow-bar-left": "\u{ea0e}", + "arrow-bar-right": "\u{ea0f}", + "arrow-bar-to-down": "\u{ec88}", + "arrow-bar-to-down-dashed": "\u{10164}", + "arrow-bar-to-left": "\u{ec89}", + "arrow-bar-to-left-dashed": "\u{10163}", + "arrow-bar-to-right": "\u{ec8a}", + "arrow-bar-to-right-dashed": "\u{10162}", + "arrow-bar-to-up": "\u{ec8b}", + "arrow-bar-to-up-dashed": "\u{10161}", + "arrow-bar-up": "\u{ea10}", + "arrow-bear-left": "\u{f045}", + "arrow-bear-left-2": "\u{f044}", + "arrow-bear-right": "\u{f047}", + "arrow-bear-right-2": "\u{f046}", + "arrow-big-down": "\u{edda}", + "arrow-big-down-filled": "\u{f6c6}", + "arrow-big-down-line": "\u{efe8}", + "arrow-big-down-line-filled": "\u{f6c7}", + "arrow-big-down-lines": "\u{efe9}", + "arrow-big-down-lines-filled": "\u{f6c8}", + "arrow-big-left": "\u{eddb}", + "arrow-big-left-filled": "\u{f6c9}", + "arrow-big-left-line": "\u{efea}", + "arrow-big-left-line-filled": "\u{f6ca}", + "arrow-big-left-lines": "\u{efeb}", + "arrow-big-left-lines-filled": "\u{f6cb}", + "arrow-big-right": "\u{eddc}", + "arrow-big-right-filled": "\u{f6cc}", + "arrow-big-right-line": "\u{efec}", + "arrow-big-right-line-filled": "\u{f6cd}", + "arrow-big-right-lines": "\u{efed}", + "arrow-big-right-lines-filled": "\u{f6ce}", + "arrow-big-up": "\u{eddd}", + "arrow-big-up-filled": "\u{f6cf}", + "arrow-big-up-line": "\u{efee}", + "arrow-big-up-line-filled": "\u{f6d0}", + "arrow-big-up-lines": "\u{efef}", + "arrow-big-up-lines-filled": "\u{f6d1}", + "arrow-bounce": "\u{f3a4}", + "arrow-capsule": "\u{fade}", + "arrow-curve-left": "\u{f048}", + "arrow-curve-right": "\u{f049}", + "arrow-down": "\u{ea16}", + "arrow-down-bar": "\u{ed98}", + "arrow-down-circle": "\u{ea11}", + "arrow-down-circle-filled": "\u{1003b}", + "arrow-down-dashed": "\u{1006a}", + "arrow-down-from-arc": "\u{fd86}", + "arrow-down-left": "\u{ea13}", + "arrow-down-left-circle": "\u{ea12}", + "arrow-down-rhombus": "\u{f61d}", + "arrow-down-rhombus-filled": "\u{1003a}", + "arrow-down-right": "\u{ea15}", + "arrow-down-right-circle": "\u{ea14}", + "arrow-down-square": "\u{ed9a}", + "arrow-down-square-filled": "\u{10039}", + "arrow-down-tail": "\u{ed9b}", + "arrow-down-to-arc": "\u{fd87}", + "arrow-elbow-left": "\u{f9ed}", + "arrow-elbow-right": "\u{f9ee}", + "arrow-fork": "\u{f04a}", + "arrow-forward": "\u{ea17}", + "arrow-forward-up": "\u{eb78}", + "arrow-forward-up-double": "\u{f9ef}", + "arrow-guide": "\u{f22a}", + "arrow-guide-filled": "\u{10038}", + "arrow-iteration": "\u{f578}", + "arrow-left": "\u{ea19}", + "arrow-left-bar": "\u{ed9c}", + "arrow-left-circle": "\u{ea18}", + "arrow-left-circle-filled": "\u{10037}", + "arrow-left-dashed": "\u{10069}", + "arrow-left-from-arc": "\u{fd88}", + "arrow-left-rhombus": "\u{f61e}", + "arrow-left-rhombus-filled": "\u{10036}", + "arrow-left-right": "\u{f04b}", + "arrow-left-square": "\u{ed9d}", + "arrow-left-square-filled": "\u{10035}", + "arrow-left-tail": "\u{ed9e}", + "arrow-left-to-arc": "\u{fd89}", + "arrow-loop-left": "\u{ed9f}", + "arrow-loop-left-2": "\u{f04c}", + "arrow-loop-right": "\u{eda0}", + "arrow-loop-right-2": "\u{f04d}", + "arrow-merge": "\u{f04e}", + "arrow-merge-alt-left": "\u{fc9f}", + "arrow-merge-alt-right": "\u{fca0}", + "arrow-merge-both": "\u{f23b}", + "arrow-merge-left": "\u{f23c}", + "arrow-merge-right": "\u{f23d}", + "arrow-move-down": "\u{f2ba}", + "arrow-move-down-filled": "\u{10034}", + "arrow-move-left": "\u{f2bb}", + "arrow-move-left-filled": "\u{10033}", + "arrow-move-right": "\u{f2bc}", + "arrow-move-right-filled": "\u{10032}", + "arrow-move-up": "\u{f2bd}", + "arrow-move-up-filled": "\u{10031}", + "arrow-narrow-down": "\u{ea1a}", + "arrow-narrow-down-dashed": "\u{10068}", + "arrow-narrow-left": "\u{ea1b}", + "arrow-narrow-left-dashed": "\u{10067}", + "arrow-narrow-right": "\u{ea1c}", + "arrow-narrow-right-dashed": "\u{10066}", + "arrow-narrow-up": "\u{ea1d}", + "arrow-narrow-up-dashed": "\u{10065}", + "arrow-ramp-left": "\u{ed3c}", + "arrow-ramp-left-2": "\u{f04f}", + "arrow-ramp-left-3": "\u{f050}", + "arrow-ramp-right": "\u{ed3d}", + "arrow-ramp-right-2": "\u{f051}", + "arrow-ramp-right-3": "\u{f052}", + "arrow-right": "\u{ea1f}", + "arrow-right-bar": "\u{eda1}", + "arrow-right-circle": "\u{ea1e}", + "arrow-right-circle-filled": "\u{10030}", + "arrow-right-dashed": "\u{10064}", + "arrow-right-from-arc": "\u{fd8a}", + "arrow-right-rhombus": "\u{f61f}", + "arrow-right-rhombus-filled": "\u{1002f}", + "arrow-right-square": "\u{eda2}", + "arrow-right-square-filled": "\u{1002e}", + "arrow-right-tail": "\u{eda3}", + "arrow-right-to-arc": "\u{fd8b}", + "arrow-rotary-first-left": "\u{f053}", + "arrow-rotary-first-right": "\u{f054}", + "arrow-rotary-last-left": "\u{f055}", + "arrow-rotary-last-right": "\u{f056}", + "arrow-rotary-left": "\u{f057}", + "arrow-rotary-right": "\u{f058}", + "arrow-rotary-straight": "\u{f059}", + "arrow-roundabout-left": "\u{f22b}", + "arrow-roundabout-right": "\u{f22c}", + "arrow-sharp-turn-left": "\u{f05a}", + "arrow-sharp-turn-right": "\u{f05b}", + "arrow-up": "\u{ea25}", + "arrow-up-bar": "\u{eda4}", + "arrow-up-circle": "\u{ea20}", + "arrow-up-circle-filled": "\u{1002d}", + "arrow-up-dashed": "\u{10063}", + "arrow-up-from-arc": "\u{fd8c}", + "arrow-up-left": "\u{ea22}", + "arrow-up-left-circle": "\u{ea21}", + "arrow-up-rhombus": "\u{f620}", + "arrow-up-rhombus-filled": "\u{1002c}", + "arrow-up-right": "\u{ea24}", + "arrow-up-right-circle": "\u{ea23}", + "arrow-up-square": "\u{eda6}", + "arrow-up-square-filled": "\u{1002b}", + "arrow-up-tail": "\u{eda7}", + "arrow-up-to-arc": "\u{fd8d}", + "arrow-wave-left-down": "\u{eda8}", + "arrow-wave-left-up": "\u{eda9}", + "arrow-wave-right-down": "\u{edaa}", + "arrow-wave-right-up": "\u{edab}", + "arrow-zig-zag": "\u{f4a7}", + "arrows-cross": "\u{effe}", + "arrows-diagonal": "\u{ea27}", + "arrows-diagonal-2": "\u{ea26}", + "arrows-diagonal-minimize": "\u{ef39}", + "arrows-diagonal-minimize-2": "\u{ef38}", + "arrows-diff": "\u{f296}", + "arrows-double-ne-sw": "\u{edde}", + "arrows-double-nw-se": "\u{eddf}", + "arrows-double-se-nw": "\u{ede0}", + "arrows-double-sw-ne": "\u{ede1}", + "arrows-down": "\u{edad}", + "arrows-down-up": "\u{edac}", + "arrows-exchange": "\u{f1f4}", + "arrows-exchange-2": "\u{f1f3}", + "arrows-horizontal": "\u{eb59}", + "arrows-join": "\u{edaf}", + "arrows-join-2": "\u{edae}", + "arrows-left": "\u{edb1}", + "arrows-left-down": "\u{ee00}", + "arrows-left-right": "\u{edb0}", + "arrows-maximize": "\u{ea28}", + "arrows-minimize": "\u{ea29}", + "arrows-move": "\u{f22f}", + "arrows-move-horizontal": "\u{f22d}", + "arrows-move-vertical": "\u{f22e}", + "arrows-random": "\u{f095}", + "arrows-right": "\u{edb3}", + "arrows-right-down": "\u{ee01}", + "arrows-right-left": "\u{edb2}", + "arrows-shuffle": "\u{f000}", + "arrows-shuffle-2": "\u{efff}", + "arrows-sort": "\u{eb5a}", + "arrows-split": "\u{edb5}", + "arrows-split-2": "\u{edb4}", + "arrows-transfer-down": "\u{f2cc}", + "arrows-transfer-up": "\u{f2cd}", + "arrows-transfer-up-down": "\u{ffac}", + "arrows-up": "\u{edb7}", + "arrows-up-down": "\u{edb6}", + "arrows-up-left": "\u{ee02}", + "arrows-up-right": "\u{ee03}", + "arrows-vertical": "\u{eb5b}", + "artboard": "\u{ea2a}", + "artboard-filled": "\u{fa83}", + "artboard-off": "\u{f0ae}", + "article": "\u{f1e2}", + "article-filled": "\u{f7da}", + "article-off": "\u{f3bf}", + "aspect-ratio": "\u{ed30}", + "aspect-ratio-filled": "\u{f7db}", + "aspect-ratio-off": "\u{f0af}", + "assembly": "\u{f24d}", + "assembly-filled": "\u{fe9e}", + "assembly-off": "\u{f3c0}", + "asset": "\u{f1ce}", + "asset-filled": "\u{fe9d}", + "asterisk": "\u{efd5}", + "asterisk-simple": "\u{efd4}", + "at": "\u{ea2b}", + "at-off": "\u{f0b0}", + "atom": "\u{eb79}", + "atom-2": "\u{ebdf}", + "atom-2-filled": "\u{f71b}", + "atom-off": "\u{f0f9}", + "augmented-reality": "\u{f023}", + "augmented-reality-2": "\u{f37e}", + "augmented-reality-off": "\u{f3c1}", + "auth-2fa": "\u{eca0}", + "automatic-gearbox": "\u{fc89}", + "automatic-gearbox-filled": "\u{1002a}", + "automation": "\u{fef8}", + "avocado": "\u{fd8e}", + "award": "\u{ea2c}", + "award-filled": "\u{f71c}", + "award-off": "\u{f0fa}", + "axe": "\u{ef9f}", + "axis-x": "\u{ef45}", + "axis-y": "\u{ef46}", + "baby-bottle": "\u{f5d2}", + "baby-carriage": "\u{f05d}", + "baby-carriage-filled": "\u{fe9c}", + "background": "\u{fd2c}", + "backhoe": "\u{ed86}", + "backpack": "\u{ef47}", + "backpack-off": "\u{f3c2}", + "backslash": "\u{fab9}", + "backspace": "\u{ea2d}", + "backspace-filled": "\u{f7dc}", + "badge": "\u{efc2}", + "badge-2k": "\u{100b5}", + "badge-3d": "\u{f555}", + "badge-3d-filled": "\u{fe9b}", + "badge-3k": "\u{100b4}", + "badge-4k": "\u{f556}", + "badge-4k-filled": "\u{fe9a}", + "badge-5k": "\u{100b3}", + "badge-8k": "\u{f557}", + "badge-8k-filled": "\u{fe99}", + "badge-ad": "\u{f558}", + "badge-ad-filled": "\u{fe98}", + "badge-ad-off": "\u{fd8f}", + "badge-ar": "\u{f559}", + "badge-ar-filled": "\u{fe97}", + "badge-cc": "\u{f55a}", + "badge-cc-filled": "\u{fe96}", + "badge-filled": "\u{f667}", + "badge-hd": "\u{f55b}", + "badge-hd-filled": "\u{fe95}", + "badge-off": "\u{f0fb}", + "badge-sd": "\u{f55c}", + "badge-sd-filled": "\u{fe94}", + "badge-tm": "\u{f55d}", + "badge-tm-filled": "\u{fe93}", + "badge-vo": "\u{f55e}", + "badge-vo-filled": "\u{fe92}", + "badge-vr": "\u{f55f}", + "badge-vr-filled": "\u{fe91}", + "badge-wc": "\u{f560}", + "badge-wc-filled": "\u{fe90}", + "badges": "\u{efc3}", + "badges-filled": "\u{f7dd}", + "badges-off": "\u{f0fc}", + "baguette": "\u{f3a5}", + "ball-american-football": "\u{ee04}", + "ball-american-football-off": "\u{f3c3}", + "ball-baseball": "\u{efa0}", + "ball-basketball": "\u{ec28}", + "ball-bowling": "\u{ec29}", + "ball-football": "\u{ee06}", + "ball-football-off": "\u{ee05}", + "ball-tennis": "\u{ec2a}", + "ball-volleyball": "\u{ec2b}", + "balloon": "\u{ef3a}", + "balloon-filled": "\u{fa84}", + "balloon-off": "\u{f0fd}", + "ballpen": "\u{f06e}", + "ballpen-filled": "\u{fa85}", + "ballpen-off": "\u{f0b1}", + "ban": "\u{ea2e}", + "bandage": "\u{eb7a}", + "bandage-filled": "\u{f7de}", + "bandage-off": "\u{f3c4}", + "barbell": "\u{eff0}", + "barbell-filled": "\u{fe8f}", + "barbell-off": "\u{f0b2}", + "barcode": "\u{ebc6}", + "barcode-off": "\u{f0b3}", + "barrel": "\u{f0b4}", + "barrel-off": "\u{f0fe}", + "barrier-block": "\u{f00e}", + "barrier-block-filled": "\u{fe8e}", + "barrier-block-off": "\u{f0b5}", + "baseline": "\u{f024}", + "baseline-density-large": "\u{f9f0}", + "baseline-density-medium": "\u{f9f1}", + "baseline-density-small": "\u{f9f2}", + "basket": "\u{ebe1}", + "basket-bolt": "\u{fb43}", + "basket-cancel": "\u{fb44}", + "basket-check": "\u{fb45}", + "basket-code": "\u{fb46}", + "basket-cog": "\u{fb47}", + "basket-discount": "\u{fb48}", + "basket-dollar": "\u{fb49}", + "basket-down": "\u{fb4a}", + "basket-exclamation": "\u{fb4b}", + "basket-filled": "\u{f7df}", + "basket-heart": "\u{fb4c}", + "basket-minus": "\u{fb4d}", + "basket-off": "\u{f0b6}", + "basket-pause": "\u{fb4e}", + "basket-pin": "\u{fb4f}", + "basket-plus": "\u{fb50}", + "basket-question": "\u{fb51}", + "basket-search": "\u{fb52}", + "basket-share": "\u{fb53}", + "basket-star": "\u{fb54}", + "basket-up": "\u{fb55}", + "basket-x": "\u{fb56}", + "bat": "\u{f284}", + "bath": "\u{ef48}", + "bath-filled": "\u{f71d}", + "bath-off": "\u{f0ff}", + "battery": "\u{ea34}", + "battery-1": "\u{ea2f}", + "battery-1-filled": "\u{f71e}", + "battery-2": "\u{ea30}", + "battery-2-filled": "\u{f71f}", + "battery-3": "\u{ea31}", + "battery-3-filled": "\u{f720}", + "battery-4": "\u{ea32}", + "battery-4-filled": "\u{f721}", + "battery-automotive": "\u{ee07}", + "battery-automotive-filled": "\u{10029}", + "battery-charging": "\u{ea33}", + "battery-charging-2": "\u{ef3b}", + "battery-eco": "\u{ef3c}", + "battery-exclamation": "\u{ff1d}", + "battery-filled": "\u{f668}", + "battery-off": "\u{ed1c}", + "battery-spark": "\u{ffbd}", + "battery-vertical": "\u{ff13}", + "battery-vertical-1": "\u{ff1c}", + "battery-vertical-1-filled": "\u{10028}", + "battery-vertical-2": "\u{ff1b}", + "battery-vertical-2-filled": "\u{10027}", + "battery-vertical-3": "\u{ff1a}", + "battery-vertical-3-filled": "\u{10026}", + "battery-vertical-4": "\u{ff19}", + "battery-vertical-4-filled": "\u{10025}", + "battery-vertical-charging": "\u{ff17}", + "battery-vertical-charging-2": "\u{ff18}", + "battery-vertical-eco": "\u{ff16}", + "battery-vertical-exclamation": "\u{ff15}", + "battery-vertical-filled": "\u{10024}", + "battery-vertical-off": "\u{ff14}", + "beach": "\u{ef3d}", + "beach-off": "\u{f0b7}", + "bed": "\u{eb5c}", + "bed-filled": "\u{f7e0}", + "bed-flat": "\u{fca1}", + "bed-flat-filled": "\u{fe8d}", + "bed-off": "\u{f100}", + "beer": "\u{efa1}", + "beer-filled": "\u{f7e1}", + "beer-off": "\u{f101}", + "bell": "\u{ea35}", + "bell-bolt": "\u{f812}", + "bell-cancel": "\u{f813}", + "bell-check": "\u{f814}", + "bell-code": "\u{f815}", + "bell-cog": "\u{f816}", + "bell-dollar": "\u{f817}", + "bell-down": "\u{f818}", + "bell-exclamation": "\u{f819}", + "bell-filled": "\u{f669}", + "bell-heart": "\u{f81a}", + "bell-minus": "\u{ede2}", + "bell-minus-filled": "\u{f722}", + "bell-off": "\u{ece9}", + "bell-pause": "\u{f81b}", + "bell-pin": "\u{f81c}", + "bell-plus": "\u{ede3}", + "bell-plus-filled": "\u{f723}", + "bell-question": "\u{f81d}", + "bell-ringing": "\u{ed07}", + "bell-ringing-2": "\u{ede4}", + "bell-ringing-2-filled": "\u{f724}", + "bell-ringing-filled": "\u{f725}", + "bell-school": "\u{f05e}", + "bell-search": "\u{f81e}", + "bell-share": "\u{f81f}", + "bell-star": "\u{f820}", + "bell-up": "\u{f821}", + "bell-x": "\u{ede5}", + "bell-x-filled": "\u{f726}", + "bell-z": "\u{eff1}", + "bell-z-filled": "\u{f727}", + "beta": "\u{f544}", + "bible": "\u{efc4}", + "bike": "\u{ea36}", + "bike-filled": "\u{10023}", + "bike-off": "\u{f0b8}", + "binary": "\u{ee08}", + "binary-off": "\u{f3c5}", + "binary-tree": "\u{f5d4}", + "binary-tree-2": "\u{f5d3}", + "binary-tree-2-filled": "\u{ff65}", + "binary-tree-filled": "\u{ff64}", + "binoculars": "\u{fefe}", + "binoculars-filled": "\u{ff0b}", + "biohazard": "\u{ecb8}", + "biohazard-filled": "\u{fe8c}", + "biohazard-off": "\u{f0b9}", + "blade": "\u{f4bd}", + "blade-filled": "\u{f7e2}", + "bleach": "\u{f2f3}", + "bleach-chlorine": "\u{f2f0}", + "bleach-no-chlorine": "\u{f2f1}", + "bleach-off": "\u{f2f2}", + "blend-mode": "\u{feb0}", + "blender": "\u{fca2}", + "blender-filled": "\u{10022}", + "blob": "\u{feaf}", + "blob-filled": "\u{feb1}", + "blockquote": "\u{ee09}", + "blocks": "\u{100b2}", + "bluetooth": "\u{ea37}", + "bluetooth-connected": "\u{ecea}", + "bluetooth-off": "\u{eceb}", + "bluetooth-x": "\u{f081}", + "blur": "\u{ef8c}", + "blur-off": "\u{f3c6}", + "bmp": "\u{f3a6}", + "body-scan": "\u{fca3}", + "bold": "\u{eb7b}", + "bold-off": "\u{f0ba}", + "bolt": "\u{ea38}", + "bolt-filled": "\u{10021}", + "bolt-off": "\u{ecec}", + "bomb": "\u{f59c}", + "bomb-filled": "\u{fa86}", + "bone": "\u{edb8}", + "bone-filled": "\u{fe8b}", + "bone-off": "\u{f0bb}", + "bong": "\u{f3a7}", + "bong-filled": "\u{10020}", + "bong-off": "\u{f3c7}", + "book": "\u{ea39}", + "book-2": "\u{efc5}", + "book-download": "\u{f070}", + "book-filled": "\u{fa87}", + "book-off": "\u{f0bc}", + "book-upload": "\u{f071}", + "bookmark": "\u{ea3a}", + "bookmark-ai": "\u{fc8a}", + "bookmark-edit": "\u{fa5e}", + "bookmark-filled": "\u{fa88}", + "bookmark-minus": "\u{fa5f}", + "bookmark-off": "\u{eced}", + "bookmark-plus": "\u{fa60}", + "bookmark-question": "\u{fa61}", + "bookmarks": "\u{ed08}", + "bookmarks-filled": "\u{fb1f}", + "bookmarks-off": "\u{f0bd}", + "books": "\u{eff2}", + "books-off": "\u{f0be}", + "boom": "\u{fdbe}", + "boom-filled": "\u{fe8a}", + "border-all": "\u{ea3b}", + "border-bottom": "\u{ea3c}", + "border-bottom-plus": "\u{fdbd}", + "border-corner-ios": "\u{fd98}", + "border-corner-pill": "\u{fd62}", + "border-corner-rounded": "\u{fd63}", + "border-corner-square": "\u{fd64}", + "border-corners": "\u{f7a0}", + "border-horizontal": "\u{ea3d}", + "border-inner": "\u{ea3e}", + "border-left": "\u{ea3f}", + "border-left-plus": "\u{fdbc}", + "border-none": "\u{ea40}", + "border-outer": "\u{ea41}", + "border-radius": "\u{eb7c}", + "border-right": "\u{ea42}", + "border-right-plus": "\u{fdbb}", + "border-sides": "\u{f7a1}", + "border-style": "\u{ee0a}", + "border-style-2": "\u{ef22}", + "border-top": "\u{ea43}", + "border-top-plus": "\u{fdba}", + "border-vertical": "\u{ea44}", + "bottle": "\u{ef0b}", + "bottle-filled": "\u{fa89}", + "bottle-off": "\u{f3c8}", + "bounce-left": "\u{f59d}", + "bounce-left-filled": "\u{fb20}", + "bounce-right": "\u{f59e}", + "bounce-right-filled": "\u{fb21}", + "bow": "\u{f096}", + "bow-filled": "\u{fe89}", + "bowl": "\u{f4fa}", + "bowl-chopsticks": "\u{fd90}", + "bowl-chopsticks-filled": "\u{fe88}", + "bowl-filled": "\u{fb22}", + "bowl-spoon": "\u{fd91}", + "bowl-spoon-filled": "\u{fe87}", + "bowling": "\u{100b1}", + "box": "\u{ea45}", + "box-align-bottom": "\u{f2a8}", + "box-align-bottom-filled": "\u{fa8a}", + "box-align-bottom-left": "\u{f2ce}", + "box-align-bottom-left-filled": "\u{fa8b}", + "box-align-bottom-right": "\u{f2cf}", + "box-align-bottom-right-filled": "\u{fa8c}", + "box-align-left": "\u{f2a9}", + "box-align-left-filled": "\u{fa8d}", + "box-align-right": "\u{f2aa}", + "box-align-right-filled": "\u{fa8e}", + "box-align-top": "\u{f2ab}", + "box-align-top-filled": "\u{fa8f}", + "box-align-top-left": "\u{f2d0}", + "box-align-top-left-filled": "\u{fa90}", + "box-align-top-right": "\u{f2d1}", + "box-align-top-right-filled": "\u{fa91}", + "box-margin": "\u{ee0b}", + "box-model": "\u{ee0c}", + "box-model-2": "\u{ef23}", + "box-model-2-off": "\u{f3c9}", + "box-model-off": "\u{f3ca}", + "box-multiple": "\u{ee17}", + "box-multiple-0": "\u{ee0d}", + "box-multiple-1": "\u{ee0e}", + "box-multiple-2": "\u{ee0f}", + "box-multiple-3": "\u{ee10}", + "box-multiple-4": "\u{ee11}", + "box-multiple-5": "\u{ee12}", + "box-multiple-6": "\u{ee13}", + "box-multiple-7": "\u{ee14}", + "box-multiple-8": "\u{ee15}", + "box-multiple-9": "\u{ee16}", + "box-multiple-filled": "\u{1001f}", + "box-off": "\u{f102}", + "box-padding": "\u{ee18}", + "box-seam": "\u{eaff}", + "braces": "\u{ebcc}", + "braces-off": "\u{f0bf}", + "brackets": "\u{ebcd}", + "brackets-angle": "\u{fcb2}", + "brackets-angle-off": "\u{fcb1}", + "brackets-contain": "\u{f1e5}", + "brackets-contain-end": "\u{f1e3}", + "brackets-contain-start": "\u{f1e4}", + "brackets-off": "\u{f0c0}", + "braille": "\u{f545}", + "brain": "\u{f59f}", + "brand-4chan": "\u{f494}", + "brand-abstract": "\u{f495}", + "brand-adobe": "\u{f0dc}", + "brand-adobe-after-effect": "\u{ff2a}", + "brand-adobe-illustrator": "\u{ff29}", + "brand-adobe-indesign": "\u{ff28}", + "brand-adobe-photoshop": "\u{ff27}", + "brand-adobe-premier": "\u{ff26}", + "brand-adobe-xd": "\u{ff25}", + "brand-adonis-js": "\u{f496}", + "brand-airbnb": "\u{ed68}", + "brand-airtable": "\u{ef6a}", + "brand-algolia": "\u{f390}", + "brand-alipay": "\u{f7a2}", + "brand-alpine-js": "\u{f324}", + "brand-amazon": "\u{f230}", + "brand-amd": "\u{f653}", + "brand-amie": "\u{ffab}", + "brand-amigo": "\u{f5f9}", + "brand-among-us": "\u{f205}", + "brand-android": "\u{ec16}", + "brand-angular": "\u{ef6b}", + "brand-angular-filled": "\u{10095}", + "brand-ansible": "\u{fa70}", + "brand-ao3": "\u{f5e8}", + "brand-appgallery": "\u{f231}", + "brand-apple": "\u{ec17}", + "brand-apple-arcade": "\u{ed69}", + "brand-apple-filled": "\u{fd74}", + "brand-apple-news": "\u{ff24}", + "brand-apple-podcast": "\u{f1e6}", + "brand-appstore": "\u{ed24}", + "brand-arc": "\u{feae}", + "brand-asana": "\u{edc5}", + "brand-astro": "\u{fdb9}", + "brand-auth0": "\u{fcb3}", + "brand-aws": "\u{fa4c}", + "brand-azure": "\u{fa4d}", + "brand-backbone": "\u{f325}", + "brand-badoo": "\u{f206}", + "brand-baidu": "\u{f5e9}", + "brand-bandcamp": "\u{f207}", + "brand-bandlab": "\u{f5fa}", + "brand-beats": "\u{f208}", + "brand-bebo": "\u{ffaa}", + "brand-behance": "\u{ec6e}", + "brand-bilibili": "\u{f6d2}", + "brand-binance": "\u{f5a0}", + "brand-bing": "\u{edc6}", + "brand-bitbucket": "\u{edc7}", + "brand-bitbucket-filled": "\u{100cb}", + "brand-blackberry": "\u{f568}", + "brand-blender": "\u{f326}", + "brand-blogger": "\u{f35a}", + "brand-bluesky": "\u{fd75}", + "brand-booking": "\u{edc8}", + "brand-bootstrap": "\u{ef3e}", + "brand-bulma": "\u{f327}", + "brand-bumble": "\u{f5fb}", + "brand-bunpo": "\u{f4cf}", + "brand-c-sharp": "\u{f003}", + "brand-cake": "\u{f7a3}", + "brand-cakephp": "\u{f7af}", + "brand-campaignmonitor": "\u{f328}", + "brand-carbon": "\u{f348}", + "brand-cashapp": "\u{f391}", + "brand-chrome": "\u{ec18}", + "brand-cinema-4d": "\u{fa71}", + "brand-citymapper": "\u{f5fc}", + "brand-cloudflare": "\u{fa4e}", + "brand-codecov": "\u{f329}", + "brand-codepen": "\u{ec6f}", + "brand-codesandbox": "\u{ed6a}", + "brand-cohost": "\u{f5d5}", + "brand-coinbase": "\u{f209}", + "brand-comedy-central": "\u{f217}", + "brand-coreos": "\u{f5fd}", + "brand-couchdb": "\u{f60f}", + "brand-couchsurfing": "\u{f392}", + "brand-cpp": "\u{f5fe}", + "brand-craft": "\u{fa72}", + "brand-crunchbase": "\u{f7e3}", + "brand-css3": "\u{ed6b}", + "brand-ctemplar": "\u{f4d0}", + "brand-cucumber": "\u{ef6c}", + "brand-cupra": "\u{f4d1}", + "brand-cypress": "\u{f333}", + "brand-d3": "\u{f24e}", + "brand-databricks": "\u{fc41}", + "brand-days-counter": "\u{f4d2}", + "brand-dcos": "\u{f32a}", + "brand-debian": "\u{ef57}", + "brand-deezer": "\u{f78b}", + "brand-deliveroo": "\u{f4d3}", + "brand-deno": "\u{f24f}", + "brand-denodo": "\u{f610}", + "brand-deviantart": "\u{ecfb}", + "brand-digg": "\u{fa73}", + "brand-dingtalk": "\u{f5ea}", + "brand-discord": "\u{ece3}", + "brand-discord-filled": "\u{f7e4}", + "brand-disney": "\u{f20a}", + "brand-disqus": "\u{edc9}", + "brand-django": "\u{f349}", + "brand-docker": "\u{edca}", + "brand-doctrine": "\u{ef6d}", + "brand-dolby-digital": "\u{f4d4}", + "brand-douban": "\u{f5ff}", + "brand-dribbble": "\u{ec19}", + "brand-dribbble-filled": "\u{f7e5}", + "brand-dropbox": "\u{1018a}", + "brand-drops": "\u{f4d5}", + "brand-drupal": "\u{f393}", + "brand-edge": "\u{ecfc}", + "brand-elastic": "\u{f611}", + "brand-electronic-arts": "\u{fa74}", + "brand-ember": "\u{f497}", + "brand-envato": "\u{f394}", + "brand-etsy": "\u{f654}", + "brand-evernote": "\u{f600}", + "brand-facebook": "\u{ec1a}", + "brand-facebook-filled": "\u{f7e6}", + "brand-feedly": "\u{fa75}", + "brand-figma": "\u{ec93}", + "brand-filezilla": "\u{fa76}", + "brand-finder": "\u{f218}", + "brand-firebase": "\u{ef6e}", + "brand-firefox": "\u{ecfd}", + "brand-fiverr": "\u{f7a4}", + "brand-flickr": "\u{ecfe}", + "brand-flightradar24": "\u{f4d6}", + "brand-flipboard": "\u{f20b}", + "brand-flutter": "\u{f395}", + "brand-fortnite": "\u{f260}", + "brand-foursquare": "\u{ecff}", + "brand-framer": "\u{ec1b}", + "brand-framer-motion": "\u{f78c}", + "brand-funimation": "\u{f655}", + "brand-gatsby": "\u{f396}", + "brand-git": "\u{ef6f}", + "brand-github": "\u{ec1c}", + "brand-github-copilot": "\u{f4a8}", + "brand-github-filled": "\u{f7e7}", + "brand-gitlab": "\u{ec1d}", + "brand-gmail": "\u{efa2}", + "brand-golang": "\u{f78d}", + "brand-google": "\u{ec1f}", + "brand-google-analytics": "\u{edcb}", + "brand-google-big-query": "\u{f612}", + "brand-google-drive": "\u{ec1e}", + "brand-google-filled": "\u{fd1a}", + "brand-google-fit": "\u{f297}", + "brand-google-home": "\u{f601}", + "brand-google-maps": "\u{fa4f}", + "brand-google-one": "\u{f232}", + "brand-google-photos": "\u{f20c}", + "brand-google-play": "\u{ed25}", + "brand-google-podcasts": "\u{f656}", + "brand-grammarly": "\u{f32b}", + "brand-graphql": "\u{f32c}", + "brand-gravatar": "\u{edcc}", + "brand-grindr": "\u{f20d}", + "brand-guardian": "\u{f4fb}", + "brand-gumroad": "\u{f5d6}", + "brand-hackerrank": "\u{ff23}", + "brand-hbo": "\u{f657}", + "brand-headlessui": "\u{f32d}", + "brand-hexo": "\u{fa50}", + "brand-hipchat": "\u{edcd}", + "brand-html5": "\u{ed6c}", + "brand-inertia": "\u{f34a}", + "brand-instagram": "\u{ec20}", + "brand-instagram-filled": "\u{10094}", + "brand-intercom": "\u{f1cf}", + "brand-itch": "\u{fa22}", + "brand-javascript": "\u{ef0c}", + "brand-juejin": "\u{f7b0}", + "brand-kako-talk": "\u{fd2d}", + "brand-kbin": "\u{fad0}", + "brand-kick": "\u{fa23}", + "brand-kick-filled": "\u{10093}", + "brand-kickstarter": "\u{edce}", + "brand-kotlin": "\u{ed6d}", + "brand-laravel": "\u{f34b}", + "brand-lastfm": "\u{f001}", + "brand-leetcode": "\u{fa51}", + "brand-letterboxd": "\u{fa24}", + "brand-line": "\u{f7e8}", + "brand-linkedin": "\u{ec8c}", + "brand-linkedin-filled": "\u{10092}", + "brand-linktree": "\u{f1e7}", + "brand-linqpad": "\u{f562}", + "brand-livewire": "\u{fd76}", + "brand-loom": "\u{ef70}", + "brand-mailgun": "\u{f32e}", + "brand-mantine": "\u{f32f}", + "brand-mastercard": "\u{ef49}", + "brand-mastodon": "\u{f250}", + "brand-matrix": "\u{f5eb}", + "brand-mcdonalds": "\u{f251}", + "brand-medium": "\u{ec70}", + "brand-meetup": "\u{fc6a}", + "brand-mercedes": "\u{f072}", + "brand-messenger": "\u{ec71}", + "brand-messenger-filled": "\u{100a7}", + "brand-meta": "\u{efb0}", + "brand-metabrainz": "\u{ff12}", + "brand-minecraft": "\u{faef}", + "brand-miniprogram": "\u{f602}", + "brand-mixpanel": "\u{f397}", + "brand-monday": "\u{f219}", + "brand-mongodb": "\u{f613}", + "brand-my-oppo": "\u{f4d7}", + "brand-mysql": "\u{f614}", + "brand-national-geographic": "\u{f603}", + "brand-nem": "\u{f5a1}", + "brand-netbeans": "\u{ef71}", + "brand-netease-music": "\u{f604}", + "brand-netflix": "\u{edcf}", + "brand-nexo": "\u{f5a2}", + "brand-nextcloud": "\u{f4d8}", + "brand-nextjs": "\u{f0dd}", + "brand-nodejs": "\u{fae0}", + "brand-nord-vpn": "\u{f37f}", + "brand-notion": "\u{ef7b}", + "brand-npm": "\u{f569}", + "brand-nuxt": "\u{f0de}", + "brand-nytimes": "\u{ef8d}", + "brand-oauth": "\u{fa52}", + "brand-office": "\u{f398}", + "brand-ok-ru": "\u{f399}", + "brand-onedrive": "\u{f5d7}", + "brand-onlyfans": "\u{f605}", + "brand-open-source": "\u{edd0}", + "brand-open-source-filled": "\u{10091}", + "brand-openai": "\u{f78e}", + "brand-openvpn": "\u{f39a}", + "brand-opera": "\u{ec21}", + "brand-opera-filled": "\u{10090}", + "brand-pagekit": "\u{edd1}", + "brand-parsinta": "\u{fc42}", + "brand-patreon": "\u{edd2}", + "brand-patreon-filled": "\u{fcff}", + "brand-paypal": "\u{ec22}", + "brand-paypal-filled": "\u{f7e9}", + "brand-paypay": "\u{f5ec}", + "brand-peanut": "\u{f39b}", + "brand-pepsi": "\u{f261}", + "brand-php": "\u{ef72}", + "brand-picsart": "\u{f4d9}", + "brand-pinterest": "\u{ec8d}", + "brand-pinterest-filled": "\u{1008f}", + "brand-planetscale": "\u{f78f}", + "brand-pnpm": "\u{fd77}", + "brand-pocket": "\u{ed00}", + "brand-polymer": "\u{f498}", + "brand-powershell": "\u{f5ed}", + "brand-printables": "\u{fd1b}", + "brand-prisma": "\u{f499}", + "brand-producthunt": "\u{edd3}", + "brand-pushbullet": "\u{f330}", + "brand-pushover": "\u{f20e}", + "brand-python": "\u{ed01}", + "brand-qq": "\u{f606}", + "brand-radix-ui": "\u{f790}", + "brand-react": "\u{f34c}", + "brand-react-native": "\u{ef73}", + "brand-reason": "\u{f49a}", + "brand-reddit": "\u{ec8e}", + "brand-redhat": "\u{f331}", + "brand-redux": "\u{f3a8}", + "brand-revolut": "\u{f4da}", + "brand-rumble": "\u{fad1}", + "brand-rust": "\u{fa53}", + "brand-safari": "\u{ec23}", + "brand-samsungpass": "\u{f4db}", + "brand-sass": "\u{edd4}", + "brand-sentry": "\u{edd5}", + "brand-sharik": "\u{f4dc}", + "brand-shazam": "\u{edd6}", + "brand-shopee": "\u{f252}", + "brand-sketch": "\u{ec24}", + "brand-sketch-filled": "\u{1008e}", + "brand-skype": "\u{ed02}", + "brand-slack": "\u{ec72}", + "brand-snapchat": "\u{ec25}", + "brand-snapchat-filled": "\u{1008d}", + "brand-snapseed": "\u{f253}", + "brand-snowflake": "\u{f615}", + "brand-socket-io": "\u{f49b}", + "brand-solidjs": "\u{f5ee}", + "brand-soundcloud": "\u{ed6e}", + "brand-spacehey": "\u{f4fc}", + "brand-speedtest": "\u{fa77}", + "brand-spotify": "\u{ed03}", + "brand-spotify-filled": "\u{fe86}", + "brand-stackoverflow": "\u{ef58}", + "brand-stackshare": "\u{f607}", + "brand-steam": "\u{ed6f}", + "brand-steam-filled": "\u{1008c}", + "brand-stocktwits": "\u{fd78}", + "brand-storj": "\u{fa54}", + "brand-storybook": "\u{f332}", + "brand-storytel": "\u{f608}", + "brand-strava": "\u{f254}", + "brand-stripe": "\u{edd7}", + "brand-stripe-filled": "\u{1008b}", + "brand-sublime-text": "\u{ef74}", + "brand-sugarizer": "\u{f7a5}", + "brand-supabase": "\u{f6d3}", + "brand-superhuman": "\u{f50c}", + "brand-supernova": "\u{f49c}", + "brand-surfshark": "\u{f255}", + "brand-svelte": "\u{f0df}", + "brand-swift": "\u{fa55}", + "brand-symfony": "\u{f616}", + "brand-tabler": "\u{ec8f}", + "brand-tabler-filled": "\u{1008a}", + "brand-tailwind": "\u{eca1}", + "brand-taobao": "\u{f5ef}", + "brand-teams": "\u{fadf}", + "brand-ted": "\u{f658}", + "brand-telegram": "\u{ec26}", + "brand-terraform": "\u{fa56}", + "brand-tesla": "\u{10099}", + "brand-tether": "\u{f5a3}", + "brand-thingiverse": "\u{fd1c}", + "brand-threads": "\u{fb02}", + "brand-threejs": "\u{f5f0}", + "brand-tidal": "\u{ed70}", + "brand-tiktok": "\u{ec73}", + "brand-tiktok-filled": "\u{f7ea}", + "brand-tinder": "\u{ed71}", + "brand-tinder-filled": "\u{10089}", + "brand-topbuzz": "\u{f50d}", + "brand-torchain": "\u{f5a4}", + "brand-toyota": "\u{f262}", + "brand-trello": "\u{f39d}", + "brand-tripadvisor": "\u{f002}", + "brand-tumblr": "\u{ed04}", + "brand-tumblr-filled": "\u{10088}", + "brand-twilio": "\u{f617}", + "brand-twitch": "\u{ed05}", + "brand-twitter": "\u{ec27}", + "brand-twitter-filled": "\u{f7eb}", + "brand-typescript": "\u{f5f1}", + "brand-uber": "\u{ef75}", + "brand-ubuntu": "\u{ef59}", + "brand-unity": "\u{f49d}", + "brand-unsplash": "\u{edd8}", + "brand-upwork": "\u{f39e}", + "brand-valorant": "\u{f39f}", + "brand-vercel": "\u{ef24}", + "brand-vercel-filled": "\u{10087}", + "brand-vimeo": "\u{ed06}", + "brand-vimeo-filled": "\u{10086}", + "brand-vinted": "\u{f20f}", + "brand-visa": "\u{f380}", + "brand-visual-studio": "\u{ef76}", + "brand-vite": "\u{f5f2}", + "brand-vivaldi": "\u{f210}", + "brand-vk": "\u{ed72}", + "brand-vlc": "\u{fa78}", + "brand-volkswagen": "\u{f50e}", + "brand-vsco": "\u{f334}", + "brand-vscode": "\u{f3a0}", + "brand-vue": "\u{f0e0}", + "brand-walmart": "\u{f211}", + "brand-waze": "\u{f5d8}", + "brand-webflow": "\u{f2d2}", + "brand-wechat": "\u{f5f3}", + "brand-weibo": "\u{f609}", + "brand-weibo-filled": "\u{100a6}", + "brand-whatsapp": "\u{ec74}", + "brand-whatsapp-filled": "\u{10085}", + "brand-wikipedia": "\u{fa79}", + "brand-windows": "\u{ecd8}", + "brand-windows-filled": "\u{10084}", + "brand-windy": "\u{f4dd}", + "brand-wish": "\u{f212}", + "brand-wix": "\u{f3a1}", + "brand-wordpress": "\u{f2d3}", + "brand-x": "\u{fc0f}", + "brand-x-filled": "\u{fc21}", + "brand-xamarin": "\u{fa7a}", + "brand-xbox": "\u{f298}", + "brand-xdeep": "\u{fc10}", + "brand-xing": "\u{f21a}", + "brand-yahoo": "\u{ed73}", + "brand-yandex": "\u{fae1}", + "brand-yarn": "\u{fd79}", + "brand-yatse": "\u{f213}", + "brand-ycombinator": "\u{edd9}", + "brand-youtube": "\u{ec90}", + "brand-youtube-filled": "\u{fc22}", + "brand-youtube-kids": "\u{f214}", + "brand-zalando": "\u{f49e}", + "brand-zapier": "\u{f49f}", + "brand-zeit": "\u{f335}", + "brand-zhihu": "\u{f60a}", + "brand-zoom": "\u{f215}", + "brand-zulip": "\u{f4de}", + "brand-zwift": "\u{f216}", + "bread": "\u{efa3}", + "bread-filled": "\u{fe85}", + "bread-off": "\u{f3cb}", + "briefcase": "\u{ea46}", + "briefcase-2": "\u{fb03}", + "briefcase-2-filled": "\u{fe84}", + "briefcase-filled": "\u{fd00}", + "briefcase-off": "\u{f3cc}", + "brightness": "\u{eb7f}", + "brightness-2": "\u{ee19}", + "brightness-auto": "\u{fd99}", + "brightness-auto-filled": "\u{fe83}", + "brightness-down": "\u{eb7d}", + "brightness-down-filled": "\u{fb23}", + "brightness-filled": "\u{fe82}", + "brightness-half": "\u{ee1a}", + "brightness-off": "\u{f3cd}", + "brightness-up": "\u{eb7e}", + "brightness-up-filled": "\u{fb24}", + "broadcast": "\u{f1e9}", + "broadcast-off": "\u{f1e8}", + "browser": "\u{ebb7}", + "browser-check": "\u{efd6}", + "browser-maximize": "\u{100b0}", + "browser-minus": "\u{100af}", + "browser-off": "\u{f0c1}", + "browser-plus": "\u{efd7}", + "browser-share": "\u{100ae}", + "browser-x": "\u{efd8}", + "brush": "\u{ebb8}", + "brush-off": "\u{f0c2}", + "bubble": "\u{feba}", + "bubble-filled": "\u{fec3}", + "bubble-minus": "\u{febe}", + "bubble-plus": "\u{febd}", + "bubble-tea": "\u{ff51}", + "bubble-tea-2": "\u{ff52}", + "bubble-text": "\u{febc}", + "bubble-text-filled": "\u{100a5}", + "bubble-x": "\u{febb}", + "bucket": "\u{ea47}", + "bucket-droplet": "\u{f56a}", + "bucket-off": "\u{f103}", + "bug": "\u{ea48}", + "bug-filled": "\u{fd01}", + "bug-off": "\u{f0c3}", + "building": "\u{ea4f}", + "building-airport": "\u{ffa9}", + "building-arch": "\u{ea49}", + "building-bank": "\u{ebe2}", + "building-bridge": "\u{ea4b}", + "building-bridge-2": "\u{ea4a}", + "building-bridge-2-filled": "\u{10189}", + "building-broadcast-tower": "\u{f4be}", + "building-broadcast-tower-filled": "\u{fe81}", + "building-burj-al-arab": "\u{ff50}", + "building-carousel": "\u{ed87}", + "building-castle": "\u{ed88}", + "building-church": "\u{ea4c}", + "building-circus": "\u{f4bf}", + "building-cog": "\u{10062}", + "building-community": "\u{ebf6}", + "building-cottage": "\u{ee1b}", + "building-estate": "\u{f5a5}", + "building-factory": "\u{ee1c}", + "building-factory-2": "\u{f082}", + "building-fortress": "\u{ed89}", + "building-hospital": "\u{ea4d}", + "building-lighthouse": "\u{ed8a}", + "building-minus": "\u{10061}", + "building-monument": "\u{ed26}", + "building-mosque": "\u{fa57}", + "building-off": "\u{fefd}", + "building-pavilion": "\u{ebf7}", + "building-plus": "\u{10060}", + "building-skyscraper": "\u{ec39}", + "building-stadium": "\u{f641}", + "building-store": "\u{ea4e}", + "building-tunnel": "\u{f5a6}", + "building-warehouse": "\u{ebe3}", + "building-wind-turbine": "\u{f4c0}", + "buildings": "\u{ff40}", + "bulb": "\u{ea51}", + "bulb-filled": "\u{f66a}", + "bulb-off": "\u{ea50}", + "bulldozer": "\u{ee1d}", + "burger": "\u{fcb4}", + "bus": "\u{ebe4}", + "bus-filled": "\u{100ff}", + "bus-off": "\u{f3ce}", + "bus-stop": "\u{f2d4}", + "businessplan": "\u{ee1e}", + "butterfly": "\u{efd9}", + "butterfly-filled": "\u{10016}", + "cactus": "\u{f21b}", + "cactus-filled": "\u{fb25}", + "cactus-off": "\u{f3cf}", + "cake": "\u{f00f}", + "cake-off": "\u{f104}", + "cake-roll": "\u{100bd}", + "calculator": "\u{eb80}", + "calculator-filled": "\u{fb26}", + "calculator-off": "\u{f0c4}", + "calendar": "\u{ea53}", + "calendar-bolt": "\u{f822}", + "calendar-cancel": "\u{f823}", + "calendar-check": "\u{f824}", + "calendar-clock": "\u{fd2e}", + "calendar-code": "\u{f825}", + "calendar-cog": "\u{f826}", + "calendar-dollar": "\u{f827}", + "calendar-dot": "\u{fd3e}", + "calendar-down": "\u{f828}", + "calendar-due": "\u{f621}", + "calendar-event": "\u{ea52}", + "calendar-event-filled": "\u{100b9}", + "calendar-exclamation": "\u{f829}", + "calendar-filled": "\u{fb27}", + "calendar-heart": "\u{f82a}", + "calendar-minus": "\u{ebb9}", + "calendar-month": "\u{fd2f}", + "calendar-month-filled": "\u{100b8}", + "calendar-off": "\u{ee1f}", + "calendar-pause": "\u{f82b}", + "calendar-pin": "\u{f82c}", + "calendar-plus": "\u{ebba}", + "calendar-question": "\u{f82d}", + "calendar-repeat": "\u{fad2}", + "calendar-sad": "\u{fd1d}", + "calendar-search": "\u{f82e}", + "calendar-share": "\u{f82f}", + "calendar-smile": "\u{fd1e}", + "calendar-star": "\u{f830}", + "calendar-stats": "\u{ee20}", + "calendar-time": "\u{ee21}", + "calendar-up": "\u{f831}", + "calendar-user": "\u{fd1f}", + "calendar-week": "\u{fd30}", + "calendar-week-filled": "\u{100b7}", + "calendar-x": "\u{f832}", + "camera": "\u{ea54}", + "camera-ai": "\u{ffa8}", + "camera-bitcoin": "\u{ffa7}", + "camera-bolt": "\u{f833}", + "camera-cancel": "\u{f834}", + "camera-check": "\u{f835}", + "camera-code": "\u{f836}", + "camera-cog": "\u{f837}", + "camera-dollar": "\u{f838}", + "camera-down": "\u{f839}", + "camera-exclamation": "\u{f83a}", + "camera-filled": "\u{fa37}", + "camera-heart": "\u{f83b}", + "camera-minus": "\u{ec3a}", + "camera-moon": "\u{ffa6}", + "camera-off": "\u{ecee}", + "camera-pause": "\u{f83c}", + "camera-pin": "\u{f83d}", + "camera-plus": "\u{ec3b}", + "camera-question": "\u{f83e}", + "camera-rotate": "\u{ee22}", + "camera-search": "\u{f83f}", + "camera-selfie": "\u{ee23}", + "camera-share": "\u{f840}", + "camera-spark": "\u{ffbc}", + "camera-star": "\u{f841}", + "camera-up": "\u{f842}", + "camera-x": "\u{f843}", + "camper": "\u{fa25}", + "campfire": "\u{f5a7}", + "campfire-filled": "\u{fb28}", + "cancel": "\u{ff11}", + "candle": "\u{efc6}", + "candle-filled": "\u{fc23}", + "candy": "\u{ef0d}", + "candy-off": "\u{f0c5}", + "cane": "\u{f50f}", + "cannabis": "\u{f4c1}", + "cannabis-filled": "\u{10015}", + "cap-projecting": "\u{ff22}", + "cap-rounded": "\u{ff21}", + "cap-straight": "\u{ff20}", + "capsule": "\u{fae3}", + "capsule-filled": "\u{fc24}", + "capsule-horizontal": "\u{fae2}", + "capsule-horizontal-filled": "\u{fc25}", + "capture": "\u{ec3c}", + "capture-filled": "\u{fb29}", + "capture-off": "\u{f0c6}", + "car": "\u{ebbb}", + "car-4wd": "\u{fdb8}", + "car-4wd-filled": "\u{1001e}", + "car-crane": "\u{ef25}", + "car-crane-filled": "\u{100fe}", + "car-crash": "\u{efa4}", + "car-fan": "\u{fdb3}", + "car-fan-1": "\u{fdb7}", + "car-fan-2": "\u{fdb6}", + "car-fan-3": "\u{fdb5}", + "car-fan-auto": "\u{fdb4}", + "car-fan-filled": "\u{1001d}", + "car-filled": "\u{1004c}", + "car-garage": "\u{fc77}", + "car-off": "\u{f0c7}", + "car-suv": "\u{fc8b}", + "car-suv-filled": "\u{1004d}", + "car-turbine": "\u{f4fd}", + "carambola": "\u{feb9}", + "carambola-filled": "\u{10014}", + "caravan": "\u{ec7c}", + "caravan-filled": "\u{100fd}", + "cardboards": "\u{ed74}", + "cardboards-filled": "\u{1001c}", + "cardboards-off": "\u{f0c8}", + "cards": "\u{f510}", + "cards-filled": "\u{fc26}", + "caret-down": "\u{eb5d}", + "caret-down-filled": "\u{fb2a}", + "caret-left": "\u{eb5e}", + "caret-left-filled": "\u{fb2b}", + "caret-left-right": "\u{fc43}", + "caret-left-right-filled": "\u{fd02}", + "caret-right": "\u{eb5f}", + "caret-right-filled": "\u{fb2c}", + "caret-up": "\u{eb60}", + "caret-up-down": "\u{fc44}", + "caret-up-down-filled": "\u{fd03}", + "caret-up-filled": "\u{fb2d}", + "carousel-horizontal": "\u{f659}", + "carousel-horizontal-filled": "\u{fa92}", + "carousel-vertical": "\u{f65a}", + "carousel-vertical-filled": "\u{fa93}", + "carrot": "\u{f21c}", + "carrot-off": "\u{f3d0}", + "cash": "\u{ea55}", + "cash-banknote": "\u{ee25}", + "cash-banknote-edit": "\u{10149}", + "cash-banknote-filled": "\u{fe80}", + "cash-banknote-heart": "\u{10148}", + "cash-banknote-minus": "\u{10147}", + "cash-banknote-move": "\u{10145}", + "cash-banknote-move-back": "\u{10146}", + "cash-banknote-off": "\u{ee24}", + "cash-banknote-plus": "\u{10144}", + "cash-edit": "\u{10143}", + "cash-heart": "\u{10142}", + "cash-minus": "\u{10141}", + "cash-move": "\u{1013f}", + "cash-move-back": "\u{10140}", + "cash-off": "\u{f105}", + "cash-plus": "\u{1013e}", + "cash-register": "\u{fee6}", + "cast": "\u{ea56}", + "cast-off": "\u{f0c9}", + "cat": "\u{f65b}", + "category": "\u{f1f6}", + "category-2": "\u{f1f5}", + "category-filled": "\u{fb2e}", + "category-minus": "\u{fd20}", + "category-plus": "\u{fd21}", + "ce": "\u{ed75}", + "ce-off": "\u{f0ca}", + "cell": "\u{f05f}", + "cell-signal-1": "\u{f083}", + "cell-signal-2": "\u{f084}", + "cell-signal-3": "\u{f085}", + "cell-signal-4": "\u{f086}", + "cell-signal-5": "\u{f087}", + "cell-signal-off": "\u{f088}", + "certificate": "\u{ed76}", + "certificate-2": "\u{f073}", + "certificate-2-off": "\u{f0cb}", + "certificate-off": "\u{f0cc}", + "chair-director": "\u{f2d5}", + "chalkboard": "\u{f34d}", + "chalkboard-off": "\u{f3d1}", + "chalkboard-teacher": "\u{10160}", + "charging-pile": "\u{ee26}", + "charging-pile-filled": "\u{1001b}", + "chart-arcs": "\u{ee28}", + "chart-arcs-3": "\u{ee27}", + "chart-area": "\u{ea58}", + "chart-area-filled": "\u{f66b}", + "chart-area-line": "\u{ea57}", + "chart-area-line-filled": "\u{f66c}", + "chart-arrows": "\u{ee2a}", + "chart-arrows-vertical": "\u{ee29}", + "chart-bar": "\u{ea59}", + "chart-bar-off": "\u{f3d2}", + "chart-bar-popular": "\u{fef7}", + "chart-bubble": "\u{ec75}", + "chart-bubble-filled": "\u{f66d}", + "chart-candle": "\u{ea5a}", + "chart-candle-filled": "\u{f66e}", + "chart-circles": "\u{ee2b}", + "chart-cohort": "\u{fef6}", + "chart-column": "\u{ffa5}", + "chart-covariate": "\u{ffa4}", + "chart-donut": "\u{ea5b}", + "chart-donut-2": "\u{ee2c}", + "chart-donut-3": "\u{ee2d}", + "chart-donut-4": "\u{ee2e}", + "chart-donut-filled": "\u{f66f}", + "chart-dots": "\u{ee2f}", + "chart-dots-2": "\u{f097}", + "chart-dots-2-filled": "\u{100dd}", + "chart-dots-3": "\u{f098}", + "chart-dots-3-filled": "\u{100dc}", + "chart-dots-filled": "\u{fd04}", + "chart-funnel": "\u{fef5}", + "chart-funnel-filled": "\u{100db}", + "chart-grid-dots": "\u{f4c2}", + "chart-grid-dots-filled": "\u{fd05}", + "chart-histogram": "\u{f65c}", + "chart-infographic": "\u{ee30}", + "chart-line": "\u{ea5c}", + "chart-pie": "\u{ea5d}", + "chart-pie-2": "\u{ee31}", + "chart-pie-2-filled": "\u{100da}", + "chart-pie-3": "\u{ee32}", + "chart-pie-3-filled": "\u{100d9}", + "chart-pie-4": "\u{ee33}", + "chart-pie-4-filled": "\u{100d8}", + "chart-pie-filled": "\u{f670}", + "chart-pie-off": "\u{f3d3}", + "chart-ppf": "\u{f618}", + "chart-radar": "\u{ed77}", + "chart-sankey": "\u{f619}", + "chart-scatter": "\u{fd93}", + "chart-scatter-3d": "\u{fd92}", + "chart-treemap": "\u{f381}", + "check": "\u{ea5e}", + "checkbox": "\u{eba6}", + "checklist": "\u{f074}", + "checks": "\u{ebaa}", + "checkup-list": "\u{ef5a}", + "cheese": "\u{ef26}", + "chef-hat": "\u{f21d}", + "chef-hat-filled": "\u{100d7}", + "chef-hat-off": "\u{f3d4}", + "cherry": "\u{f511}", + "cherry-filled": "\u{f728}", + "chess": "\u{f382}", + "chess-bishop": "\u{f56b}", + "chess-bishop-filled": "\u{f729}", + "chess-filled": "\u{f72a}", + "chess-king": "\u{f56c}", + "chess-king-filled": "\u{f72b}", + "chess-knight": "\u{f56d}", + "chess-knight-filled": "\u{f72c}", + "chess-queen": "\u{f56e}", + "chess-queen-filled": "\u{f72d}", + "chess-rook": "\u{f56f}", + "chess-rook-filled": "\u{f72e}", + "chevron-compact-down": "\u{faf0}", + "chevron-compact-left": "\u{faf1}", + "chevron-compact-right": "\u{faf2}", + "chevron-compact-up": "\u{faf3}", + "chevron-down": "\u{ea5f}", + "chevron-down-left": "\u{ed09}", + "chevron-down-right": "\u{ed0a}", + "chevron-left": "\u{ea60}", + "chevron-left-pipe": "\u{fae4}", + "chevron-right": "\u{ea61}", + "chevron-right-pipe": "\u{fae5}", + "chevron-up": "\u{ea62}", + "chevron-up-left": "\u{ed0b}", + "chevron-up-right": "\u{ed0c}", + "chevrons-down": "\u{ea63}", + "chevrons-down-left": "\u{ed0d}", + "chevrons-down-right": "\u{ed0e}", + "chevrons-left": "\u{ea64}", + "chevrons-right": "\u{ea65}", + "chevrons-up": "\u{ea66}", + "chevrons-up-left": "\u{ed0f}", + "chevrons-up-right": "\u{ed10}", + "chisel": "\u{f383}", + "christmas-ball": "\u{fd31}", + "christmas-tree": "\u{ed78}", + "christmas-tree-filled": "\u{1001a}", + "christmas-tree-off": "\u{f3d5}", + "circle": "\u{ea6b}", + "circle-0": "\u{ee34}", + "circle-1": "\u{ee35}", + "circle-2": "\u{ee36}", + "circle-3": "\u{ee37}", + "circle-4": "\u{ee38}", + "circle-5": "\u{ee39}", + "circle-6": "\u{ee3a}", + "circle-7": "\u{ee3b}", + "circle-8": "\u{ee3c}", + "circle-9": "\u{ee3d}", + "circle-arrow-down": "\u{f6f9}", + "circle-arrow-down-filled": "\u{f6f4}", + "circle-arrow-down-left": "\u{f6f6}", + "circle-arrow-down-left-filled": "\u{f6f5}", + "circle-arrow-down-right": "\u{f6f8}", + "circle-arrow-down-right-filled": "\u{f6f7}", + "circle-arrow-left": "\u{f6fb}", + "circle-arrow-left-filled": "\u{f6fa}", + "circle-arrow-right": "\u{f6fd}", + "circle-arrow-right-filled": "\u{f6fc}", + "circle-arrow-up": "\u{f703}", + "circle-arrow-up-filled": "\u{f6fe}", + "circle-arrow-up-left": "\u{f700}", + "circle-arrow-up-left-filled": "\u{f6ff}", + "circle-arrow-up-right": "\u{f702}", + "circle-arrow-up-right-filled": "\u{f701}", + "circle-caret-down": "\u{f4a9}", + "circle-caret-down-filled": "\u{100d6}", + "circle-caret-left": "\u{f4aa}", + "circle-caret-left-filled": "\u{100d5}", + "circle-caret-right": "\u{f4ab}", + "circle-caret-right-filled": "\u{100d4}", + "circle-caret-up": "\u{f4ac}", + "circle-caret-up-filled": "\u{100d3}", + "circle-check": "\u{ea67}", + "circle-check-filled": "\u{f704}", + "circle-chevron-down": "\u{f622}", + "circle-chevron-down-filled": "\u{100d2}", + "circle-chevron-left": "\u{f623}", + "circle-chevron-left-filled": "\u{100d1}", + "circle-chevron-right": "\u{f624}", + "circle-chevron-right-filled": "\u{100d0}", + "circle-chevron-up": "\u{f625}", + "circle-chevron-up-filled": "\u{100cf}", + "circle-chevrons-down": "\u{f642}", + "circle-chevrons-down-filled": "\u{100ef}", + "circle-chevrons-left": "\u{f643}", + "circle-chevrons-left-filled": "\u{100ee}", + "circle-chevrons-right": "\u{f644}", + "circle-chevrons-right-filled": "\u{100ed}", + "circle-chevrons-up": "\u{f645}", + "circle-chevrons-up-filled": "\u{100ec}", + "circle-dashed": "\u{ed27}", + "circle-dashed-check": "\u{feb8}", + "circle-dashed-letter-a": "\u{ff9a}", + "circle-dashed-letter-b": "\u{ff99}", + "circle-dashed-letter-c": "\u{ff98}", + "circle-dashed-letter-d": "\u{ff97}", + "circle-dashed-letter-e": "\u{ff96}", + "circle-dashed-letter-f": "\u{ff95}", + "circle-dashed-letter-g": "\u{ff94}", + "circle-dashed-letter-h": "\u{ff93}", + "circle-dashed-letter-i": "\u{ff92}", + "circle-dashed-letter-j": "\u{ff91}", + "circle-dashed-letter-k": "\u{ff90}", + "circle-dashed-letter-l": "\u{ff8f}", + "circle-dashed-letter-letter-v": "\u{ff84}", + "circle-dashed-letter-m": "\u{ff8d}", + "circle-dashed-letter-n": "\u{ff8c}", + "circle-dashed-letter-o": "\u{ff8b}", + "circle-dashed-letter-p": "\u{ff8a}", + "circle-dashed-letter-q": "\u{ff89}", + "circle-dashed-letter-r": "\u{ff88}", + "circle-dashed-letter-s": "\u{ff87}", + "circle-dashed-letter-t": "\u{ff86}", + "circle-dashed-letter-u": "\u{ff85}", + "circle-dashed-letter-v": "\u{ff84}", + "circle-dashed-letter-w": "\u{ff83}", + "circle-dashed-letter-x": "\u{ff82}", + "circle-dashed-letter-y": "\u{ff81}", + "circle-dashed-letter-z": "\u{ff80}", + "circle-dashed-minus": "\u{feb7}", + "circle-dashed-number-0": "\u{fc6b}", + "circle-dashed-number-1": "\u{fc6c}", + "circle-dashed-number-2": "\u{fc6d}", + "circle-dashed-number-3": "\u{fc6e}", + "circle-dashed-number-4": "\u{fc6f}", + "circle-dashed-number-5": "\u{fc70}", + "circle-dashed-number-6": "\u{fc71}", + "circle-dashed-number-7": "\u{fc72}", + "circle-dashed-number-8": "\u{fc73}", + "circle-dashed-number-9": "\u{fc74}", + "circle-dashed-percentage": "\u{fd7a}", + "circle-dashed-plus": "\u{feb6}", + "circle-dashed-x": "\u{fc75}", + "circle-dot": "\u{efb1}", + "circle-dot-filled": "\u{f705}", + "circle-dotted": "\u{ed28}", + "circle-dotted-letter-a": "\u{ff7f}", + "circle-dotted-letter-b": "\u{ff7e}", + "circle-dotted-letter-c": "\u{ff7d}", + "circle-dotted-letter-d": "\u{ff7c}", + "circle-dotted-letter-e": "\u{ff7b}", + "circle-dotted-letter-f": "\u{ff7a}", + "circle-dotted-letter-g": "\u{ff79}", + "circle-dotted-letter-h": "\u{ff78}", + "circle-dotted-letter-i": "\u{ff77}", + "circle-dotted-letter-j": "\u{ff76}", + "circle-dotted-letter-k": "\u{ff75}", + "circle-dotted-letter-l": "\u{ff74}", + "circle-dotted-letter-m": "\u{ff73}", + "circle-dotted-letter-n": "\u{ff72}", + "circle-dotted-letter-o": "\u{ff71}", + "circle-dotted-letter-p": "\u{ff70}", + "circle-dotted-letter-q": "\u{ff6f}", + "circle-dotted-letter-r": "\u{ff6e}", + "circle-dotted-letter-s": "\u{ff6d}", + "circle-dotted-letter-t": "\u{ff6c}", + "circle-dotted-letter-u": "\u{ff6b}", + "circle-dotted-letter-v": "\u{ff6a}", + "circle-dotted-letter-w": "\u{ff69}", + "circle-dotted-letter-x": "\u{ff68}", + "circle-dotted-letter-y": "\u{ff67}", + "circle-dotted-letter-z": "\u{ff66}", + "circle-filled": "\u{f671}", + "circle-half": "\u{ee3f}", + "circle-half-2": "\u{eff3}", + "circle-half-vertical": "\u{ee3e}", + "circle-key": "\u{f633}", + "circle-key-filled": "\u{f706}", + "circle-letter-a": "\u{f441}", + "circle-letter-a-filled": "\u{fe7f}", + "circle-letter-b": "\u{f442}", + "circle-letter-b-filled": "\u{fe7e}", + "circle-letter-c": "\u{f443}", + "circle-letter-c-filled": "\u{fe7d}", + "circle-letter-d": "\u{f444}", + "circle-letter-d-filled": "\u{fe7c}", + "circle-letter-e": "\u{f445}", + "circle-letter-e-filled": "\u{fe7b}", + "circle-letter-f": "\u{f446}", + "circle-letter-f-filled": "\u{fe7a}", + "circle-letter-g": "\u{f447}", + "circle-letter-g-filled": "\u{fe79}", + "circle-letter-h": "\u{f448}", + "circle-letter-h-filled": "\u{fe78}", + "circle-letter-i": "\u{f449}", + "circle-letter-i-filled": "\u{fe77}", + "circle-letter-j": "\u{f44a}", + "circle-letter-j-filled": "\u{fe76}", + "circle-letter-k": "\u{f44b}", + "circle-letter-k-filled": "\u{fe75}", + "circle-letter-l": "\u{f44c}", + "circle-letter-l-filled": "\u{fe74}", + "circle-letter-m": "\u{f44d}", + "circle-letter-m-filled": "\u{fe73}", + "circle-letter-n": "\u{f44e}", + "circle-letter-n-filled": "\u{fe72}", + "circle-letter-o": "\u{f44f}", + "circle-letter-o-filled": "\u{fe71}", + "circle-letter-p": "\u{f450}", + "circle-letter-p-filled": "\u{fe70}", + "circle-letter-q": "\u{f451}", + "circle-letter-q-filled": "\u{fe6f}", + "circle-letter-r": "\u{f452}", + "circle-letter-r-filled": "\u{fe6e}", + "circle-letter-s": "\u{f453}", + "circle-letter-s-filled": "\u{fe6d}", + "circle-letter-t": "\u{f454}", + "circle-letter-t-filled": "\u{fe6c}", + "circle-letter-u": "\u{f455}", + "circle-letter-u-filled": "\u{fe6b}", + "circle-letter-v": "\u{f4ad}", + "circle-letter-v-filled": "\u{fe6a}", + "circle-letter-w": "\u{f456}", + "circle-letter-w-filled": "\u{fe69}", + "circle-letter-x": "\u{f4ae}", + "circle-letter-x-filled": "\u{fe68}", + "circle-letter-y": "\u{f457}", + "circle-letter-y-filled": "\u{fe67}", + "circle-letter-z": "\u{f458}", + "circle-letter-z-filled": "\u{fe66}", + "circle-minus": "\u{ea68}", + "circle-minus-2": "\u{fc8c}", + "circle-number-0": "\u{ee34}", + "circle-number-0-filled": "\u{f72f}", + "circle-number-1": "\u{ee35}", + "circle-number-1-filled": "\u{f730}", + "circle-number-2": "\u{ee36}", + "circle-number-2-filled": "\u{f731}", + "circle-number-3": "\u{ee37}", + "circle-number-3-filled": "\u{f732}", + "circle-number-4": "\u{ee38}", + "circle-number-4-filled": "\u{f733}", + "circle-number-5": "\u{ee39}", + "circle-number-5-filled": "\u{f734}", + "circle-number-6": "\u{ee3a}", + "circle-number-6-filled": "\u{f735}", + "circle-number-7": "\u{ee3b}", + "circle-number-7-filled": "\u{f736}", + "circle-number-8": "\u{ee3c}", + "circle-number-8-filled": "\u{f737}", + "circle-number-9": "\u{ee3d}", + "circle-number-9-filled": "\u{f738}", + "circle-off": "\u{ee40}", + "circle-percentage": "\u{fd7b}", + "circle-percentage-filled": "\u{fed5}", + "circle-plus": "\u{ea69}", + "circle-plus-2": "\u{fc8d}", + "circle-plus-filled": "\u{fef9}", + "circle-rectangle": "\u{f010}", + "circle-rectangle-filled": "\u{ff63}", + "circle-rectangle-off": "\u{f0cd}", + "circle-square": "\u{ece4}", + "circle-triangle": "\u{f011}", + "circle-x": "\u{ea6a}", + "circle-x-filled": "\u{f739}", + "circles": "\u{ece5}", + "circles-filled": "\u{f672}", + "circles-relation": "\u{f4c3}", + "circuit-ammeter": "\u{f271}", + "circuit-battery": "\u{f272}", + "circuit-bulb": "\u{f273}", + "circuit-capacitor": "\u{f275}", + "circuit-capacitor-polarized": "\u{f274}", + "circuit-cell": "\u{f277}", + "circuit-cell-plus": "\u{f276}", + "circuit-changeover": "\u{f278}", + "circuit-diode": "\u{f27a}", + "circuit-diode-zener": "\u{f279}", + "circuit-ground": "\u{f27c}", + "circuit-ground-digital": "\u{f27b}", + "circuit-inductor": "\u{f27d}", + "circuit-motor": "\u{f27e}", + "circuit-pushbutton": "\u{f27f}", + "circuit-resistor": "\u{f280}", + "circuit-switch-closed": "\u{f281}", + "circuit-switch-open": "\u{f282}", + "circuit-voltmeter": "\u{f283}", + "clear-all": "\u{ee41}", + "clear-formatting": "\u{ebe5}", + "click": "\u{ebbc}", + "cliff-jumping": "\u{fefc}", + "clipboard": "\u{ea6f}", + "clipboard-check": "\u{ea6c}", + "clipboard-check-filled": "\u{100ce}", + "clipboard-copy": "\u{f299}", + "clipboard-data": "\u{f563}", + "clipboard-data-filled": "\u{100eb}", + "clipboard-filled": "\u{100cc}", + "clipboard-heart": "\u{f34e}", + "clipboard-list": "\u{ea6d}", + "clipboard-list-filled": "\u{100ea}", + "clipboard-off": "\u{f0ce}", + "clipboard-plus": "\u{efb2}", + "clipboard-plus-filled": "\u{10176}", + "clipboard-search": "\u{10098}", + "clipboard-smile": "\u{fd9a}", + "clipboard-smile-filled": "\u{10175}", + "clipboard-text": "\u{f089}", + "clipboard-text-filled": "\u{100e9}", + "clipboard-typography": "\u{f34f}", + "clipboard-typography-filled": "\u{100e8}", + "clipboard-x": "\u{ea6e}", + "clipboard-x-filled": "\u{100cd}", + "clock": "\u{ea70}", + "clock-12": "\u{fc56}", + "clock-2": "\u{f099}", + "clock-24": "\u{fc57}", + "clock-bitcoin": "\u{ff3f}", + "clock-bolt": "\u{f844}", + "clock-cancel": "\u{f546}", + "clock-check": "\u{f7c1}", + "clock-code": "\u{f845}", + "clock-cog": "\u{f7c2}", + "clock-dollar": "\u{f846}", + "clock-down": "\u{f7c3}", + "clock-edit": "\u{f547}", + "clock-exclamation": "\u{f847}", + "clock-filled": "\u{f73a}", + "clock-heart": "\u{f7c4}", + "clock-hour-1": "\u{f313}", + "clock-hour-1-filled": "\u{fe65}", + "clock-hour-10": "\u{f314}", + "clock-hour-10-filled": "\u{fe64}", + "clock-hour-11": "\u{f315}", + "clock-hour-11-filled": "\u{fe63}", + "clock-hour-12": "\u{f316}", + "clock-hour-12-filled": "\u{fe62}", + "clock-hour-2": "\u{f317}", + "clock-hour-2-filled": "\u{fe61}", + "clock-hour-3": "\u{f318}", + "clock-hour-3-filled": "\u{fe60}", + "clock-hour-4": "\u{f319}", + "clock-hour-4-filled": "\u{fe5f}", + "clock-hour-5": "\u{f31a}", + "clock-hour-5-filled": "\u{fe5e}", + "clock-hour-6": "\u{f31b}", + "clock-hour-6-filled": "\u{fe5d}", + "clock-hour-7": "\u{f31c}", + "clock-hour-7-filled": "\u{fe5c}", + "clock-hour-8": "\u{f31d}", + "clock-hour-8-filled": "\u{fe5b}", + "clock-hour-9": "\u{f31e}", + "clock-hour-9-filled": "\u{fe5a}", + "clock-minus": "\u{f848}", + "clock-off": "\u{f0cf}", + "clock-pause": "\u{f548}", + "clock-pin": "\u{f849}", + "clock-play": "\u{f549}", + "clock-plus": "\u{f7c5}", + "clock-question": "\u{f7c6}", + "clock-record": "\u{f54a}", + "clock-search": "\u{f7c7}", + "clock-share": "\u{f84a}", + "clock-shield": "\u{f7c8}", + "clock-star": "\u{f7c9}", + "clock-stop": "\u{f54b}", + "clock-up": "\u{f7ca}", + "clock-x": "\u{f7cb}", + "clothes-rack": "\u{f285}", + "clothes-rack-off": "\u{f3d6}", + "cloud": "\u{ea76}", + "cloud-bitcoin": "\u{ff3e}", + "cloud-bolt": "\u{f84b}", + "cloud-cancel": "\u{f84c}", + "cloud-check": "\u{f84d}", + "cloud-code": "\u{f84e}", + "cloud-cog": "\u{f84f}", + "cloud-computing": "\u{f1d0}", + "cloud-computing-filled": "\u{1010d}", + "cloud-data-connection": "\u{f1d1}", + "cloud-data-connection-filled": "\u{1010c}", + "cloud-dollar": "\u{f850}", + "cloud-down": "\u{f851}", + "cloud-download": "\u{ea71}", + "cloud-exclamation": "\u{f852}", + "cloud-filled": "\u{f673}", + "cloud-fog": "\u{ecd9}", + "cloud-heart": "\u{f853}", + "cloud-lock": "\u{efdb}", + "cloud-lock-open": "\u{efda}", + "cloud-minus": "\u{f854}", + "cloud-network": "\u{fc78}", + "cloud-off": "\u{ed3e}", + "cloud-pause": "\u{f855}", + "cloud-pin": "\u{f856}", + "cloud-plus": "\u{f857}", + "cloud-question": "\u{f858}", + "cloud-rain": "\u{ea72}", + "cloud-search": "\u{f859}", + "cloud-share": "\u{f85a}", + "cloud-snow": "\u{ea73}", + "cloud-star": "\u{f85b}", + "cloud-storm": "\u{ea74}", + "cloud-sun": "\u{ec6d}", + "cloud-up": "\u{f85c}", + "cloud-upload": "\u{ea75}", + "cloud-x": "\u{f85d}", + "clover": "\u{f1ea}", + "clover-2": "\u{f21e}", + "clover-filled": "\u{10013}", + "clubs": "\u{eff4}", + "clubs-filled": "\u{f674}", + "code": "\u{ea77}", + "code-asterisk": "\u{f312}", + "code-asterix": "\u{f312}", + "code-circle": "\u{f4ff}", + "code-circle-2": "\u{f4fe}", + "code-circle-2-filled": "\u{fed4}", + "code-circle-filled": "\u{fed3}", + "code-dots": "\u{f61a}", + "code-minus": "\u{ee42}", + "code-off": "\u{f0d0}", + "code-plus": "\u{ee43}", + "code-variable": "\u{100ab}", + "code-variable-minus": "\u{100ad}", + "code-variable-plus": "\u{100ac}", + "coffee": "\u{ef0e}", + "coffee-off": "\u{f106}", + "coffin": "\u{f579}", + "coin": "\u{eb82}", + "coin-bitcoin": "\u{f2be}", + "coin-bitcoin-filled": "\u{fd06}", + "coin-euro": "\u{f2bf}", + "coin-euro-filled": "\u{fd07}", + "coin-filled": "\u{fd08}", + "coin-monero": "\u{f4a0}", + "coin-monero-filled": "\u{fd09}", + "coin-off": "\u{f0d1}", + "coin-pound": "\u{f2c0}", + "coin-pound-filled": "\u{fd0a}", + "coin-rupee": "\u{f2c1}", + "coin-rupee-filled": "\u{fd0b}", + "coin-taka": "\u{fd0d}", + "coin-taka-filled": "\u{fd0c}", + "coin-yen": "\u{f2c2}", + "coin-yen-filled": "\u{fd0e}", + "coin-yuan": "\u{f2c3}", + "coin-yuan-filled": "\u{fd0f}", + "coins": "\u{f65d}", + "color-filter": "\u{f5a8}", + "color-picker": "\u{ebe6}", + "color-picker-off": "\u{f0d2}", + "color-swatch": "\u{eb61}", + "color-swatch-off": "\u{f0d3}", + "column-insert-left": "\u{ee44}", + "column-insert-right": "\u{ee45}", + "column-remove": "\u{faf4}", + "columns": "\u{eb83}", + "columns-1": "\u{f6d4}", + "columns-1-filled": "\u{10188}", + "columns-2": "\u{f6d5}", + "columns-2-filled": "\u{10187}", + "columns-3": "\u{f6d6}", + "columns-3-filled": "\u{10186}", + "columns-off": "\u{f0d4}", + "comet": "\u{ec76}", + "command": "\u{ea78}", + "command-off": "\u{f3d7}", + "compass": "\u{ea79}", + "compass-filled": "\u{fd10}", + "compass-off": "\u{f0d5}", + "components": "\u{efa5}", + "components-off": "\u{f0d6}", + "cone": "\u{efdd}", + "cone-2": "\u{efdc}", + "cone-2-filled": "\u{fe59}", + "cone-filled": "\u{fe58}", + "cone-off": "\u{f3d8}", + "cone-plus": "\u{fa94}", + "confetti": "\u{ee46}", + "confetti-filled": "\u{10185}", + "confetti-off": "\u{f3d9}", + "confucius": "\u{f58a}", + "congruent-to": "\u{ffa3}", + "container": "\u{ee47}", + "container-filled": "\u{10184}", + "container-off": "\u{f107}", + "contract": "\u{fefb}", + "contrast": "\u{ec4e}", + "contrast-2": "\u{efc7}", + "contrast-2-filled": "\u{fe57}", + "contrast-2-off": "\u{f3da}", + "contrast-filled": "\u{fe56}", + "contrast-off": "\u{f3db}", + "cooker": "\u{f57a}", + "cookie": "\u{fdb1}", + "cookie-filled": "\u{fe54}", + "cookie-man": "\u{fdb2}", + "cookie-man-filled": "\u{fe55}", + "cookie-off": "\u{f0d7}", + "copy": "\u{ea7a}", + "copy-check": "\u{fdb0}", + "copy-check-filled": "\u{fe53}", + "copy-minus": "\u{fdaf}", + "copy-minus-filled": "\u{fe52}", + "copy-off": "\u{f0d8}", + "copy-plus": "\u{fdae}", + "copy-plus-filled": "\u{fe51}", + "copy-x": "\u{fdad}", + "copy-x-filled": "\u{fe50}", + "copyleft": "\u{ec3d}", + "copyleft-filled": "\u{f73b}", + "copyleft-off": "\u{f0d9}", + "copyright": "\u{ea7b}", + "copyright-filled": "\u{f73c}", + "copyright-off": "\u{f0da}", + "corner-down-left": "\u{ea7c}", + "corner-down-left-double": "\u{ee48}", + "corner-down-right": "\u{ea7d}", + "corner-down-right-double": "\u{ee49}", + "corner-left-down": "\u{ea7e}", + "corner-left-down-double": "\u{ee4a}", + "corner-left-up": "\u{ea7f}", + "corner-left-up-double": "\u{ee4b}", + "corner-right-down": "\u{ea80}", + "corner-right-down-double": "\u{ee4c}", + "corner-right-up": "\u{ea81}", + "corner-right-up-double": "\u{ee4d}", + "corner-up-left": "\u{ea82}", + "corner-up-left-double": "\u{ee4e}", + "corner-up-right": "\u{ea83}", + "corner-up-right-double": "\u{ee4f}", + "cpu": "\u{ef8e}", + "cpu-2": "\u{f075}", + "cpu-off": "\u{f108}", + "crane": "\u{ef27}", + "crane-off": "\u{f109}", + "creative-commons": "\u{efb3}", + "creative-commons-by": "\u{f21f}", + "creative-commons-nc": "\u{f220}", + "creative-commons-nd": "\u{f221}", + "creative-commons-off": "\u{f10a}", + "creative-commons-sa": "\u{f222}", + "creative-commons-zero": "\u{f223}", + "credit-card": "\u{ea84}", + "credit-card-filled": "\u{fd11}", + "credit-card-off": "\u{ed11}", + "credit-card-pay": "\u{fd32}", + "credit-card-refund": "\u{fd33}", + "cricket": "\u{f09a}", + "crop": "\u{ea85}", + "crop-1-1": "\u{fd50}", + "crop-1-1-filled": "\u{fe4f}", + "crop-16-9": "\u{fd51}", + "crop-16-9-filled": "\u{fe4e}", + "crop-3-2": "\u{fd52}", + "crop-3-2-filled": "\u{fe4d}", + "crop-5-4": "\u{fd53}", + "crop-5-4-filled": "\u{fe4c}", + "crop-7-5": "\u{fd54}", + "crop-7-5-filled": "\u{fe4b}", + "crop-landscape": "\u{fd55}", + "crop-landscape-filled": "\u{fe4a}", + "crop-portrait": "\u{fd56}", + "crop-portrait-filled": "\u{fe49}", + "cross": "\u{ef8f}", + "cross-filled": "\u{f675}", + "cross-off": "\u{f10b}", + "crosshair": "\u{ec3e}", + "crown": "\u{ed12}", + "crown-off": "\u{ee50}", + "crutches": "\u{ef5b}", + "crutches-off": "\u{f10c}", + "crystal-ball": "\u{f57b}", + "csv": "\u{f791}", + "cube": "\u{fa97}", + "cube-3d-sphere": "\u{ecd7}", + "cube-3d-sphere-off": "\u{f3b5}", + "cube-off": "\u{fa95}", + "cube-plus": "\u{fa96}", + "cube-send": "\u{f61b}", + "cube-spark": "\u{ffbb}", + "cube-unfolded": "\u{f61c}", + "cup": "\u{ef28}", + "cup-off": "\u{f10d}", + "curling": "\u{efc8}", + "curly-loop": "\u{ecda}", + "currency": "\u{efa6}", + "currency-afghani": "\u{f65e}", + "currency-bahraini": "\u{ee51}", + "currency-baht": "\u{f08a}", + "currency-bitcoin": "\u{ebab}", + "currency-cent": "\u{ee53}", + "currency-dinar": "\u{ee54}", + "currency-dirham": "\u{ee55}", + "currency-dogecoin": "\u{ef4b}", + "currency-dollar": "\u{eb84}", + "currency-dollar-australian": "\u{ee56}", + "currency-dollar-brunei": "\u{f36c}", + "currency-dollar-canadian": "\u{ee57}", + "currency-dollar-guyanese": "\u{f36d}", + "currency-dollar-off": "\u{f3dc}", + "currency-dollar-singapore": "\u{ee58}", + "currency-dollar-zimbabwean": "\u{f36e}", + "currency-dong": "\u{f36f}", + "currency-dram": "\u{f370}", + "currency-ethereum": "\u{ee59}", + "currency-euro": "\u{eb85}", + "currency-euro-off": "\u{f3dd}", + "currency-florin": "\u{faf5}", + "currency-forint": "\u{ee5a}", + "currency-frank": "\u{ee5b}", + "currency-guarani": "\u{f371}", + "currency-hryvnia": "\u{f372}", + "currency-iranian-rial": "\u{fa58}", + "currency-kip": "\u{f373}", + "currency-krone-czech": "\u{ee5c}", + "currency-krone-danish": "\u{ee5d}", + "currency-krone-swedish": "\u{ee5e}", + "currency-lari": "\u{f374}", + "currency-leu": "\u{ee5f}", + "currency-lira": "\u{ee60}", + "currency-litecoin": "\u{ee61}", + "currency-lyd": "\u{f375}", + "currency-manat": "\u{f376}", + "currency-monero": "\u{f377}", + "currency-naira": "\u{ee62}", + "currency-nano": "\u{f7a6}", + "currency-off": "\u{f3de}", + "currency-paanga": "\u{f378}", + "currency-peso": "\u{f65f}", + "currency-pound": "\u{ebac}", + "currency-pound-off": "\u{f3df}", + "currency-quetzal": "\u{f379}", + "currency-real": "\u{ee63}", + "currency-renminbi": "\u{ee64}", + "currency-ripple": "\u{ee65}", + "currency-riyal": "\u{ee66}", + "currency-rubel": "\u{ee67}", + "currency-rufiyaa": "\u{f37a}", + "currency-rupee": "\u{ebad}", + "currency-rupee-nepalese": "\u{f37b}", + "currency-shekel": "\u{ee68}", + "currency-solana": "\u{f4a1}", + "currency-som": "\u{f37c}", + "currency-taka": "\u{ee69}", + "currency-tenge": "\u{f37d}", + "currency-tugrik": "\u{ee6a}", + "currency-won": "\u{ee6b}", + "currency-xrp": "\u{fd34}", + "currency-yen": "\u{ebae}", + "currency-yen-off": "\u{f3e0}", + "currency-yuan": "\u{f29a}", + "currency-zloty": "\u{ee6c}", + "current-location": "\u{ecef}", + "current-location-filled": "\u{10125}", + "current-location-off": "\u{f10e}", + "cursor-off": "\u{f10f}", + "cursor-text": "\u{ee6d}", + "cut": "\u{ea86}", + "cylinder": "\u{f54c}", + "cylinder-off": "\u{fa98}", + "cylinder-plus": "\u{fa99}", + "dashboard": "\u{ea87}", + "dashboard-filled": "\u{10019}", + "dashboard-off": "\u{f3e1}", + "database": "\u{ea88}", + "database-cog": "\u{fa10}", + "database-dollar": "\u{fa11}", + "database-edit": "\u{fa12}", + "database-exclamation": "\u{fa13}", + "database-export": "\u{ee6e}", + "database-heart": "\u{fa14}", + "database-import": "\u{ee6f}", + "database-leak": "\u{fa15}", + "database-minus": "\u{fa16}", + "database-off": "\u{ee70}", + "database-plus": "\u{fa17}", + "database-search": "\u{fa18}", + "database-share": "\u{fa19}", + "database-smile": "\u{fd9b}", + "database-star": "\u{fa1a}", + "database-x": "\u{fa1b}", + "decimal": "\u{fa26}", + "deer": "\u{f4c5}", + "delta": "\u{f53c}", + "dental": "\u{f025}", + "dental-broken": "\u{f286}", + "dental-off": "\u{f110}", + "deselect": "\u{f9f3}", + "desk": "\u{fd35}", + "details": "\u{ee71}", + "details-off": "\u{f3e2}", + "device-airpods": "\u{f5a9}", + "device-airpods-case": "\u{f646}", + "device-airtag": "\u{fae6}", + "device-analytics": "\u{ee72}", + "device-audio-tape": "\u{ee73}", + "device-camera-phone": "\u{f233}", + "device-cctv": "\u{ee74}", + "device-cctv-filled": "\u{1004b}", + "device-cctv-off": "\u{f3e3}", + "device-computer-camera": "\u{ee76}", + "device-computer-camera-off": "\u{ee75}", + "device-desktop": "\u{ea89}", + "device-desktop-analytics": "\u{ee77}", + "device-desktop-bolt": "\u{f85e}", + "device-desktop-cancel": "\u{f85f}", + "device-desktop-check": "\u{f860}", + "device-desktop-code": "\u{f861}", + "device-desktop-cog": "\u{f862}", + "device-desktop-dollar": "\u{f863}", + "device-desktop-down": "\u{f864}", + "device-desktop-exclamation": "\u{f865}", + "device-desktop-filled": "\u{1004a}", + "device-desktop-heart": "\u{f866}", + "device-desktop-minus": "\u{f867}", + "device-desktop-off": "\u{ee78}", + "device-desktop-pause": "\u{f868}", + "device-desktop-pin": "\u{f869}", + "device-desktop-plus": "\u{f86a}", + "device-desktop-question": "\u{f86b}", + "device-desktop-search": "\u{f86c}", + "device-desktop-share": "\u{f86d}", + "device-desktop-star": "\u{f86e}", + "device-desktop-up": "\u{f86f}", + "device-desktop-x": "\u{f870}", + "device-floppy": "\u{eb62}", + "device-gamepad": "\u{eb63}", + "device-gamepad-2": "\u{f1d2}", + "device-gamepad-3": "\u{fc58}", + "device-gamepad-3-filled": "\u{10049}", + "device-heart-monitor": "\u{f060}", + "device-heart-monitor-filled": "\u{fa38}", + "device-imac": "\u{f7a7}", + "device-imac-bolt": "\u{f871}", + "device-imac-cancel": "\u{f872}", + "device-imac-check": "\u{f873}", + "device-imac-code": "\u{f874}", + "device-imac-cog": "\u{f875}", + "device-imac-dollar": "\u{f876}", + "device-imac-down": "\u{f877}", + "device-imac-exclamation": "\u{f878}", + "device-imac-filled": "\u{10048}", + "device-imac-heart": "\u{f879}", + "device-imac-minus": "\u{f87a}", + "device-imac-off": "\u{f87b}", + "device-imac-pause": "\u{f87c}", + "device-imac-pin": "\u{f87d}", + "device-imac-plus": "\u{f87e}", + "device-imac-question": "\u{f87f}", + "device-imac-search": "\u{f880}", + "device-imac-share": "\u{f881}", + "device-imac-star": "\u{f882}", + "device-imac-up": "\u{f883}", + "device-imac-x": "\u{f884}", + "device-ipad": "\u{f648}", + "device-ipad-bolt": "\u{f885}", + "device-ipad-cancel": "\u{f886}", + "device-ipad-check": "\u{f887}", + "device-ipad-code": "\u{f888}", + "device-ipad-cog": "\u{f889}", + "device-ipad-dollar": "\u{f88a}", + "device-ipad-down": "\u{f88b}", + "device-ipad-exclamation": "\u{f88c}", + "device-ipad-filled": "\u{10047}", + "device-ipad-heart": "\u{f88d}", + "device-ipad-horizontal": "\u{f647}", + "device-ipad-horizontal-bolt": "\u{f88e}", + "device-ipad-horizontal-cancel": "\u{f88f}", + "device-ipad-horizontal-check": "\u{f890}", + "device-ipad-horizontal-code": "\u{f891}", + "device-ipad-horizontal-cog": "\u{f892}", + "device-ipad-horizontal-dollar": "\u{f893}", + "device-ipad-horizontal-down": "\u{f894}", + "device-ipad-horizontal-exclamation": "\u{f895}", + "device-ipad-horizontal-heart": "\u{f896}", + "device-ipad-horizontal-minus": "\u{f897}", + "device-ipad-horizontal-off": "\u{f898}", + "device-ipad-horizontal-pause": "\u{f899}", + "device-ipad-horizontal-pin": "\u{f89a}", + "device-ipad-horizontal-plus": "\u{f89b}", + "device-ipad-horizontal-question": "\u{f89c}", + "device-ipad-horizontal-search": "\u{f89d}", + "device-ipad-horizontal-share": "\u{f89e}", + "device-ipad-horizontal-star": "\u{f89f}", + "device-ipad-horizontal-up": "\u{f8a0}", + "device-ipad-horizontal-x": "\u{f8a1}", + "device-ipad-minus": "\u{f8a2}", + "device-ipad-off": "\u{f8a3}", + "device-ipad-pause": "\u{f8a4}", + "device-ipad-pin": "\u{f8a5}", + "device-ipad-plus": "\u{f8a6}", + "device-ipad-question": "\u{f8a7}", + "device-ipad-search": "\u{f8a8}", + "device-ipad-share": "\u{f8a9}", + "device-ipad-star": "\u{f8aa}", + "device-ipad-up": "\u{f8ab}", + "device-ipad-x": "\u{f8ac}", + "device-landline-phone": "\u{f649}", + "device-laptop": "\u{eb64}", + "device-laptop-off": "\u{f061}", + "device-mobile": "\u{ea8a}", + "device-mobile-bolt": "\u{f8ad}", + "device-mobile-cancel": "\u{f8ae}", + "device-mobile-charging": "\u{f224}", + "device-mobile-check": "\u{f8af}", + "device-mobile-code": "\u{f8b0}", + "device-mobile-cog": "\u{f8b1}", + "device-mobile-dollar": "\u{f8b2}", + "device-mobile-down": "\u{f8b3}", + "device-mobile-exclamation": "\u{f8b4}", + "device-mobile-filled": "\u{fa39}", + "device-mobile-heart": "\u{f8b5}", + "device-mobile-message": "\u{ee79}", + "device-mobile-minus": "\u{f8b6}", + "device-mobile-off": "\u{f062}", + "device-mobile-pause": "\u{f8b7}", + "device-mobile-pin": "\u{f8b8}", + "device-mobile-plus": "\u{f8b9}", + "device-mobile-question": "\u{f8ba}", + "device-mobile-rotated": "\u{ecdb}", + "device-mobile-search": "\u{f8bb}", + "device-mobile-share": "\u{f8bc}", + "device-mobile-star": "\u{f8bd}", + "device-mobile-up": "\u{f8be}", + "device-mobile-vibration": "\u{eb86}", + "device-mobile-x": "\u{f8bf}", + "device-nintendo": "\u{f026}", + "device-nintendo-off": "\u{f111}", + "device-projector": "\u{fc11}", + "device-remote": "\u{f792}", + "device-remote-filled": "\u{10046}", + "device-sd-card": "\u{f384}", + "device-sim": "\u{f4b2}", + "device-sim-1": "\u{f4af}", + "device-sim-2": "\u{f4b0}", + "device-sim-3": "\u{f4b1}", + "device-speaker": "\u{ea8b}", + "device-speaker-filled": "\u{10045}", + "device-speaker-off": "\u{f112}", + "device-tablet": "\u{ea8c}", + "device-tablet-bolt": "\u{f8c0}", + "device-tablet-cancel": "\u{f8c1}", + "device-tablet-check": "\u{f8c2}", + "device-tablet-code": "\u{f8c3}", + "device-tablet-cog": "\u{f8c4}", + "device-tablet-dollar": "\u{f8c5}", + "device-tablet-down": "\u{f8c6}", + "device-tablet-exclamation": "\u{f8c7}", + "device-tablet-filled": "\u{fa3a}", + "device-tablet-heart": "\u{f8c8}", + "device-tablet-minus": "\u{f8c9}", + "device-tablet-off": "\u{f063}", + "device-tablet-pause": "\u{f8ca}", + "device-tablet-pin": "\u{f8cb}", + "device-tablet-plus": "\u{f8cc}", + "device-tablet-question": "\u{f8cd}", + "device-tablet-search": "\u{f8ce}", + "device-tablet-share": "\u{f8cf}", + "device-tablet-star": "\u{f8d0}", + "device-tablet-up": "\u{f8d1}", + "device-tablet-x": "\u{f8d2}", + "device-tv": "\u{ea8d}", + "device-tv-filled": "\u{10043}", + "device-tv-off": "\u{f064}", + "device-tv-old": "\u{f1d3}", + "device-tv-old-filled": "\u{10044}", + "device-unknown": "\u{fef4}", + "device-unknown-filled": "\u{10018}", + "device-usb": "\u{fc59}", + "device-usb-filled": "\u{10042}", + "device-vision-pro": "\u{fae7}", + "device-vision-pro-filled": "\u{10041}", + "device-watch": "\u{ebf9}", + "device-watch-bolt": "\u{f8d3}", + "device-watch-cancel": "\u{f8d4}", + "device-watch-check": "\u{f8d5}", + "device-watch-code": "\u{f8d6}", + "device-watch-cog": "\u{f8d7}", + "device-watch-dollar": "\u{f8d8}", + "device-watch-down": "\u{f8d9}", + "device-watch-exclamation": "\u{f8da}", + "device-watch-filled": "\u{10040}", + "device-watch-heart": "\u{f8db}", + "device-watch-minus": "\u{f8dc}", + "device-watch-off": "\u{f065}", + "device-watch-pause": "\u{f8dd}", + "device-watch-pin": "\u{f8de}", + "device-watch-plus": "\u{f8df}", + "device-watch-question": "\u{f8e0}", + "device-watch-search": "\u{f8e1}", + "device-watch-share": "\u{f8e2}", + "device-watch-star": "\u{f8e3}", + "device-watch-stats": "\u{ef7d}", + "device-watch-stats-2": "\u{ef7c}", + "device-watch-up": "\u{f8e4}", + "device-watch-x": "\u{f8e5}", + "devices": "\u{eb87}", + "devices-2": "\u{ed29}", + "devices-bolt": "\u{f8e6}", + "devices-cancel": "\u{f8e7}", + "devices-check": "\u{f8e8}", + "devices-code": "\u{f8e9}", + "devices-cog": "\u{f8ea}", + "devices-dollar": "\u{f8eb}", + "devices-down": "\u{f8ec}", + "devices-exclamation": "\u{f8ed}", + "devices-heart": "\u{f8ee}", + "devices-minus": "\u{f8ef}", + "devices-off": "\u{f3e4}", + "devices-pause": "\u{f8f0}", + "devices-pc": "\u{ee7a}", + "devices-pc-off": "\u{f113}", + "devices-pin": "\u{f8f1}", + "devices-plus": "\u{f8f2}", + "devices-question": "\u{f8f3}", + "devices-search": "\u{f8f4}", + "devices-share": "\u{f8f5}", + "devices-star": "\u{f8f6}", + "devices-up": "\u{f8f7}", + "devices-x": "\u{f8f8}", + "diabolo": "\u{fa9c}", + "diabolo-off": "\u{fa9a}", + "diabolo-plus": "\u{fa9b}", + "dialpad": "\u{f067}", + "dialpad-filled": "\u{fa3b}", + "dialpad-off": "\u{f114}", + "diamond": "\u{eb65}", + "diamond-filled": "\u{f73d}", + "diamond-off": "\u{f115}", + "diamonds": "\u{eff5}", + "diamonds-filled": "\u{f676}", + "diaper": "\u{ffa2}", + "dice": "\u{eb66}", + "dice-1": "\u{f08b}", + "dice-1-filled": "\u{f73e}", + "dice-2": "\u{f08c}", + "dice-2-filled": "\u{f73f}", + "dice-3": "\u{f08d}", + "dice-3-filled": "\u{f740}", + "dice-4": "\u{f08e}", + "dice-4-filled": "\u{f741}", + "dice-5": "\u{f08f}", + "dice-5-filled": "\u{f742}", + "dice-6": "\u{f090}", + "dice-6-filled": "\u{f743}", + "dice-filled": "\u{f744}", + "dimensions": "\u{ee7b}", + "direction": "\u{ebfb}", + "direction-arrows": "\u{fd36}", + "direction-arrows-filled": "\u{100ca}", + "direction-horizontal": "\u{ebfa}", + "direction-sign": "\u{f1f7}", + "direction-sign-filled": "\u{f745}", + "direction-sign-off": "\u{f3e5}", + "directions": "\u{ea8e}", + "directions-filled": "\u{1003f}", + "directions-off": "\u{f116}", + "disabled": "\u{ea8f}", + "disabled-2": "\u{ebaf}", + "disabled-off": "\u{f117}", + "disc": "\u{ea90}", + "disc-filled": "\u{1003e}", + "disc-golf": "\u{f385}", + "disc-off": "\u{f118}", + "discount": "\u{ebbd}", + "discount-2": "\u{ee7c}", + "discount-2-off": "\u{f3e6}", + "discount-check": "\u{f1f8}", + "discount-check-filled": "\u{f746}", + "discount-filled": "\u{1003d}", + "discount-off": "\u{f3e7}", + "divide": "\u{ed5c}", + "dna": "\u{ee7d}", + "dna-2": "\u{ef5c}", + "dna-2-off": "\u{f119}", + "dna-off": "\u{f11a}", + "dog": "\u{f660}", + "dog-bowl": "\u{ef29}", + "door": "\u{ef4e}", + "door-enter": "\u{ef4c}", + "door-exit": "\u{ef4d}", + "door-off": "\u{f11b}", + "dots": "\u{ea95}", + "dots-circle-horizontal": "\u{ea91}", + "dots-diagonal": "\u{ea93}", + "dots-diagonal-2": "\u{ea92}", + "dots-vertical": "\u{ea94}", + "download": "\u{ea96}", + "download-off": "\u{f11c}", + "drag-drop": "\u{eb89}", + "drag-drop-2": "\u{eb88}", + "drone": "\u{ed79}", + "drone-off": "\u{ee7e}", + "drop-circle": "\u{efde}", + "drop-circle-filled": "\u{10137}", + "droplet": "\u{ea97}", + "droplet-bolt": "\u{f8f9}", + "droplet-cancel": "\u{f8fa}", + "droplet-check": "\u{f8fb}", + "droplet-code": "\u{f8fc}", + "droplet-cog": "\u{f8fd}", + "droplet-dollar": "\u{f8fe}", + "droplet-down": "\u{f8ff}", + "droplet-exclamation": "\u{f900}", + "droplet-filled": "\u{ee80}", + "droplet-half": "\u{ee82}", + "droplet-half-2": "\u{ee81}", + "droplet-half-2-filled": "\u{fb6c}", + "droplet-half-filled": "\u{f6c5}", + "droplet-heart": "\u{f901}", + "droplet-minus": "\u{f902}", + "droplet-off": "\u{ee83}", + "droplet-pause": "\u{f903}", + "droplet-pin": "\u{f904}", + "droplet-plus": "\u{f905}", + "droplet-question": "\u{f906}", + "droplet-search": "\u{f907}", + "droplet-share": "\u{f908}", + "droplet-star": "\u{f909}", + "droplet-up": "\u{f90a}", + "droplet-x": "\u{f90b}", + "droplets": "\u{fc12}", + "droplets-filled": "\u{100c9}", + "dual-screen": "\u{fa59}", + "dual-screen-filled": "\u{10136}", + "dumpling": "\u{feb5}", + "dumpling-filled": "\u{10135}", + "e-passport": "\u{f4df}", + "ear": "\u{ebce}", + "ear-off": "\u{ee84}", + "ear-scan": "\u{fd57}", + "ease-in": "\u{f573}", + "ease-in-control-point": "\u{f570}", + "ease-in-control-point-filled": "\u{10174}", + "ease-in-out": "\u{f572}", + "ease-in-out-control-points": "\u{f571}", + "ease-in-out-control-points-filled": "\u{10173}", + "ease-out": "\u{f575}", + "ease-out-control-point": "\u{f574}", + "ease-out-control-point-filled": "\u{10172}", + "edit": "\u{ea98}", + "edit-circle": "\u{ee85}", + "edit-circle-off": "\u{f11d}", + "edit-off": "\u{f11e}", + "egg": "\u{eb8a}", + "egg-cracked": "\u{f2d6}", + "egg-cracked-filled": "\u{10012}", + "egg-filled": "\u{f678}", + "egg-fried": "\u{f386}", + "egg-fried-filled": "\u{10134}", + "egg-off": "\u{f11f}", + "eggs": "\u{f500}", + "elevator": "\u{efdf}", + "elevator-filled": "\u{1003c}", + "elevator-off": "\u{f3e8}", + "emergency-bed": "\u{ef5d}", + "empathize": "\u{f29b}", + "empathize-off": "\u{f3e9}", + "emphasis": "\u{ebcf}", + "engine": "\u{ef7e}", + "engine-filled": "\u{100fc}", + "engine-off": "\u{f120}", + "equal": "\u{ee87}", + "equal-double": "\u{f4e1}", + "equal-not": "\u{ee86}", + "eraser": "\u{eb8b}", + "eraser-off": "\u{f121}", + "error-404": "\u{f027}", + "error-404-off": "\u{f122}", + "escalator": "\u{fb06}", + "escalator-down": "\u{fb04}", + "escalator-down-filled": "\u{10133}", + "escalator-filled": "\u{10131}", + "escalator-up": "\u{fb05}", + "escalator-up-filled": "\u{10132}", + "ethernet": "\u{eccc}", + "ethernet-off": "\u{eccd}", + "ethernet-exclamation": "\u{ecce}", + "ethernet-question": "\u{eccf}", + "exchange": "\u{ebe7}", + "exchange-filled": "\u{10130}", + "exchange-off": "\u{f123}", + "exclamation-circle": "\u{f634}", + "exclamation-circle-filled": "\u{ff62}", + "exclamation-mark": "\u{efb4}", + "exclamation-mark-off": "\u{f124}", + "explicit": "\u{f256}", + "explicit-filled": "\u{1012f}", + "explicit-off": "\u{f3ea}", + "exposure": "\u{eb8c}", + "exposure-0": "\u{f29c}", + "exposure-filled": "\u{10124}", + "exposure-minus-1": "\u{f29d}", + "exposure-minus-2": "\u{f29e}", + "exposure-off": "\u{f3eb}", + "exposure-plus-1": "\u{f29f}", + "exposure-plus-2": "\u{f2a0}", + "external-link": "\u{ea99}", + "external-link-off": "\u{f125}", + "eye": "\u{ea9a}", + "eye-bitcoin": "\u{ff3d}", + "eye-bolt": "\u{fb6d}", + "eye-cancel": "\u{fb6e}", + "eye-check": "\u{ee88}", + "eye-closed": "\u{f7ec}", + "eye-code": "\u{fb6f}", + "eye-cog": "\u{f7ed}", + "eye-discount": "\u{fb70}", + "eye-dollar": "\u{fb71}", + "eye-dotted": "\u{fead}", + "eye-down": "\u{fb72}", + "eye-edit": "\u{f7ee}", + "eye-exclamation": "\u{f7ef}", + "eye-filled": "\u{f679}", + "eye-heart": "\u{f7f0}", + "eye-minus": "\u{fb73}", + "eye-off": "\u{ecf0}", + "eye-pause": "\u{fb74}", + "eye-pin": "\u{fb75}", + "eye-plus": "\u{fb76}", + "eye-question": "\u{fb77}", + "eye-search": "\u{fb78}", + "eye-share": "\u{fb79}", + "eye-spark": "\u{ffba}", + "eye-star": "\u{fb7a}", + "eye-table": "\u{ef5e}", + "eye-table-filled": "\u{10123}", + "eye-up": "\u{fb7b}", + "eye-x": "\u{f7f1}", + "eyeglass": "\u{ee8a}", + "eyeglass-2": "\u{ee89}", + "eyeglass-2-filled": "\u{10122}", + "eyeglass-filled": "\u{100c8}", + "eyeglass-off": "\u{f126}", + "face-id": "\u{ea9b}", + "face-id-error": "\u{efa7}", + "face-mask": "\u{efb5}", + "face-mask-filled": "\u{10121}", + "face-mask-off": "\u{f127}", + "fall": "\u{ecb9}", + "favicon": "\u{fd65}", + "favicon-filled": "\u{10071}", + "feather": "\u{ee8b}", + "feather-filled": "\u{10011}", + "feather-off": "\u{f128}", + "fence": "\u{ef2a}", + "fence-filled": "\u{10120}", + "fence-off": "\u{f129}", + "ferry": "\u{10074}", + "ferry-filled": "\u{100fb}", + "fidget-spinner": "\u{f068}", + "fidget-spinner-filled": "\u{1011f}", + "file": "\u{eaa4}", + "file-3d": "\u{f032}", + "file-ai": "\u{ffa1}", + "file-alert": "\u{ede6}", + "file-analytics": "\u{ede7}", + "file-analytics-filled": "\u{10171}", + "file-arrow-left": "\u{f033}", + "file-arrow-right": "\u{f034}", + "file-barcode": "\u{f035}", + "file-bitcoin": "\u{ffa0}", + "file-broken": "\u{f501}", + "file-certificate": "\u{ed4d}", + "file-chart": "\u{f036}", + "file-check": "\u{ea9c}", + "file-check-filled": "\u{1012e}", + "file-code": "\u{ebd0}", + "file-code-2": "\u{ede8}", + "file-code-2-filled": "\u{1012d}", + "file-code-filled": "\u{10170}", + "file-cv": "\u{fa5a}", + "file-cv-filled": "\u{1012c}", + "file-database": "\u{f037}", + "file-delta": "\u{f53d}", + "file-delta-filled": "\u{1012b}", + "file-description": "\u{f028}", + "file-description-filled": "\u{1011e}", + "file-diff": "\u{ecf1}", + "file-diff-filled": "\u{1016f}", + "file-digit": "\u{efa8}", + "file-digit-filled": "\u{1011d}", + "file-dislike": "\u{ed2a}", + "file-dollar": "\u{efe0}", + "file-dots": "\u{f038}", + "file-dots-filled": "\u{1016e}", + "file-download": "\u{ea9d}", + "file-download-filled": "\u{1012a}", + "file-euro": "\u{efe1}", + "file-excel": "\u{fef3}", + "file-export": "\u{ede9}", + "file-filled": "\u{f747}", + "file-function": "\u{f53e}", + "file-function-filled": "\u{1016d}", + "file-horizontal": "\u{ebb0}", + "file-horizontal-filled": "\u{1011c}", + "file-import": "\u{edea}", + "file-infinity": "\u{f502}", + "file-info": "\u{edec}", + "file-info-filled": "\u{1016c}", + "file-invoice": "\u{eb67}", + "file-invoice-filled": "\u{1011b}", + "file-isr": "\u{feac}", + "file-lambda": "\u{f53f}", + "file-lambda-filled": "\u{10129}", + "file-like": "\u{ed2b}", + "file-minus": "\u{ea9e}", + "file-minus-filled": "\u{1011a}", + "file-music": "\u{ea9f}", + "file-neutral": "\u{fd22}", + "file-neutral-filled": "\u{10119}", + "file-off": "\u{ecf2}", + "file-orientation": "\u{f2a1}", + "file-pencil": "\u{f039}", + "file-percent": "\u{f540}", + "file-percent-filled": "\u{10128}", + "file-phone": "\u{ecdc}", + "file-phone-filled": "\u{10127}", + "file-plus": "\u{eaa0}", + "file-power": "\u{f03a}", + "file-power-filled": "\u{10118}", + "file-report": "\u{eded}", + "file-rss": "\u{f03b}", + "file-rss-filled": "\u{10126}", + "file-sad": "\u{fd23}", + "file-sad-filled": "\u{10117}", + "file-scissors": "\u{f03c}", + "file-search": "\u{ed5d}", + "file-settings": "\u{f029}", + "file-shredder": "\u{eaa1}", + "file-signal": "\u{f03d}", + "file-smile": "\u{fd24}", + "file-smile-filled": "\u{10116}", + "file-spark": "\u{ffb9}", + "file-spreadsheet": "\u{f03e}", + "file-stack": "\u{f503}", + "file-star": "\u{f03f}", + "file-star-filled": "\u{10115}", + "file-symlink": "\u{ed53}", + "file-text": "\u{eaa2}", + "file-text-ai": "\u{fa27}", + "file-text-filled": "\u{10114}", + "file-text-shield": "\u{100f2}", + "file-text-spark": "\u{ffb8}", + "file-time": "\u{f040}", + "file-type-bmp": "\u{fb07}", + "file-type-css": "\u{fb08}", + "file-type-csv": "\u{fb09}", + "file-type-doc": "\u{fb0a}", + "file-type-docx": "\u{fb0b}", + "file-type-html": "\u{fb0c}", + "file-type-jpg": "\u{fb0d}", + "file-type-js": "\u{fb0e}", + "file-type-jsx": "\u{fb0f}", + "file-type-pdf": "\u{fb10}", + "file-type-php": "\u{fb11}", + "file-type-png": "\u{fb12}", + "file-type-ppt": "\u{fb13}", + "file-type-rs": "\u{fb14}", + "file-type-sql": "\u{fb15}", + "file-type-svg": "\u{fb16}", + "file-type-ts": "\u{fb17}", + "file-type-tsx": "\u{fb18}", + "file-type-txt": "\u{fb19}", + "file-type-vue": "\u{fb1a}", + "file-type-xls": "\u{fb1b}", + "file-type-xml": "\u{fb1c}", + "file-type-zip": "\u{fb1d}", + "file-typography": "\u{f041}", + "file-typography-filled": "\u{1016b}", + "file-unknown": "\u{f042}", + "file-upload": "\u{ec91}", + "file-vector": "\u{f043}", + "file-word": "\u{fef2}", + "file-x": "\u{eaa3}", + "file-x-filled": "\u{f748}", + "file-zip": "\u{ed4e}", + "files": "\u{edef}", + "files-off": "\u{edee}", + "filter": "\u{eaa5}", + "filter-2": "\u{1014b}", + "filter-2-bolt": "\u{1015f}", + "filter-2-cancel": "\u{1015e}", + "filter-2-check": "\u{1015d}", + "filter-2-code": "\u{1015c}", + "filter-2-cog": "\u{1015b}", + "filter-2-discount": "\u{1015a}", + "filter-2-dollar": "\u{10159}", + "filter-2-down": "\u{10158}", + "filter-2-edit": "\u{10157}", + "filter-2-exclamation": "\u{10156}", + "filter-2-minus": "\u{10155}", + "filter-2-pause": "\u{10154}", + "filter-2-pin": "\u{10153}", + "filter-2-plus": "\u{10152}", + "filter-2-question": "\u{10151}", + "filter-2-search": "\u{10150}", + "filter-2-share": "\u{1014f}", + "filter-2-spark": "\u{1014e}", + "filter-2-up": "\u{1014d}", + "filter-2-x": "\u{1014c}", + "filter-bolt": "\u{fb7c}", + "filter-cancel": "\u{fb7d}", + "filter-check": "\u{fb7e}", + "filter-code": "\u{fb7f}", + "filter-cog": "\u{f9fe}", + "filter-discount": "\u{fb80}", + "filter-dollar": "\u{f9ff}", + "filter-down": "\u{fb81}", + "filter-edit": "\u{fa00}", + "filter-exclamation": "\u{fb82}", + "filter-filled": "\u{fc27}", + "filter-heart": "\u{fb83}", + "filter-minus": "\u{fa01}", + "filter-off": "\u{ed2c}", + "filter-pause": "\u{fb84}", + "filter-pin": "\u{fb85}", + "filter-plus": "\u{fa02}", + "filter-question": "\u{fb86}", + "filter-search": "\u{fb87}", + "filter-share": "\u{fb88}", + "filter-spark": "\u{1014a}", + "filter-star": "\u{fa03}", + "filter-up": "\u{fb89}", + "filter-x": "\u{fa04}", + "filters": "\u{f793}", + "filters-filled": "\u{100c7}", + "fingerprint": "\u{ebd1}", + "fingerprint-off": "\u{f12a}", + "fingerprint-scan": "\u{fcb5}", + "fire-extinguisher": "\u{faf6}", + "fire-hydrant": "\u{f3a9}", + "fire-hydrant-off": "\u{f3ec}", + "firetruck": "\u{ebe8}", + "first-aid-kit": "\u{ef5f}", + "first-aid-kit-off": "\u{f3ed}", + "fish": "\u{ef2b}", + "fish-bone": "\u{f287}", + "fish-bone-filled": "\u{1010b}", + "fish-christianity": "\u{f58b}", + "fish-hook": "\u{f1f9}", + "fish-hook-off": "\u{f3ee}", + "fish-off": "\u{f12b}", + "flag": "\u{eaa6}", + "flag-2": "\u{ee8c}", + "flag-2-filled": "\u{f707}", + "flag-2-off": "\u{f12c}", + "flag-3": "\u{ee8d}", + "flag-3-filled": "\u{f708}", + "flag-bitcoin": "\u{ff3c}", + "flag-bolt": "\u{fb8a}", + "flag-cancel": "\u{fb8b}", + "flag-check": "\u{fb8c}", + "flag-code": "\u{fb8d}", + "flag-cog": "\u{fb8e}", + "flag-discount": "\u{fb8f}", + "flag-dollar": "\u{fb90}", + "flag-down": "\u{fb91}", + "flag-exclamation": "\u{fb92}", + "flag-filled": "\u{f67a}", + "flag-heart": "\u{fb93}", + "flag-minus": "\u{fb94}", + "flag-off": "\u{f12d}", + "flag-pause": "\u{fb95}", + "flag-pin": "\u{fb96}", + "flag-plus": "\u{fb97}", + "flag-question": "\u{fb98}", + "flag-search": "\u{fb99}", + "flag-share": "\u{fb9a}", + "flag-spark": "\u{ffb7}", + "flag-star": "\u{fb9b}", + "flag-up": "\u{fb9c}", + "flag-x": "\u{fb9d}", + "flame": "\u{ec2c}", + "flame-filled": "\u{100c6}", + "flame-off": "\u{f12e}", + "flare": "\u{ee8e}", + "flare-filled": "\u{100c5}", + "flask": "\u{ebd2}", + "flask-2": "\u{ef60}", + "flask-2-filled": "\u{fd12}", + "flask-2-off": "\u{f12f}", + "flask-filled": "\u{fd13}", + "flask-off": "\u{f130}", + "flip-flops": "\u{f564}", + "flip-horizontal": "\u{eaa7}", + "flip-vertical": "\u{eaa8}", + "float-center": "\u{ebb1}", + "float-left": "\u{ebb2}", + "float-none": "\u{ed13}", + "float-right": "\u{ebb3}", + "flower": "\u{eff6}", + "flower-filled": "\u{10010}", + "flower-off": "\u{f131}", + "focus": "\u{eb8d}", + "focus-2": "\u{ebd3}", + "focus-auto": "\u{fa62}", + "focus-centered": "\u{f02a}", + "fold": "\u{ed56}", + "fold-down": "\u{ed54}", + "fold-up": "\u{ed55}", + "folder": "\u{eaad}", + "folder-bolt": "\u{f90c}", + "folder-cancel": "\u{f90d}", + "folder-check": "\u{f90e}", + "folder-code": "\u{f90f}", + "folder-cog": "\u{f910}", + "folder-dollar": "\u{f911}", + "folder-down": "\u{f912}", + "folder-exclamation": "\u{f913}", + "folder-filled": "\u{f749}", + "folder-heart": "\u{f914}", + "folder-minus": "\u{eaaa}", + "folder-off": "\u{ed14}", + "folder-open": "\u{faf7}", + "folder-pause": "\u{f915}", + "folder-pin": "\u{f916}", + "folder-plus": "\u{eaab}", + "folder-question": "\u{f917}", + "folder-root": "\u{fd43}", + "folder-search": "\u{f918}", + "folder-share": "\u{f919}", + "folder-star": "\u{f91a}", + "folder-symlink": "\u{f91b}", + "folder-up": "\u{f91c}", + "folder-x": "\u{eaac}", + "folders": "\u{eaae}", + "folders-filled": "\u{100c4}", + "folders-off": "\u{f133}", + "forbid": "\u{ebd5}", + "forbid-2": "\u{ebd4}", + "forbid-2-filled": "\u{fc28}", + "forbid-filled": "\u{fc29}", + "forklift": "\u{ebe9}", + "forms": "\u{ee8f}", + "fountain": "\u{f09b}", + "fountain-filled": "\u{fc2a}", + "fountain-off": "\u{f134}", + "frame": "\u{eaaf}", + "frame-off": "\u{f135}", + "free-rights": "\u{efb6}", + "freeze-column": "\u{fa63}", + "freeze-row": "\u{fa65}", + "freeze-row-column": "\u{fa64}", + "fridge": "\u{f1fa}", + "fridge-off": "\u{f3ef}", + "friends": "\u{eab0}", + "friends-off": "\u{f136}", + "frustum": "\u{fa9f}", + //"frustum-off": "\u{fa9d}", + "frustum-plus": "\u{fa9e}", + "function": "\u{f225}", + "function-filled": "\u{fc2b}", + "function-off": "\u{f3f0}", + "galaxy": "\u{fcb6}", + "garden-cart": "\u{f23e}", + "garden-cart-filled": "\u{100c3}", + "garden-cart-off": "\u{f3f1}", + "gas-station": "\u{ec7d}", + "gas-station-filled": "\u{100fa}", + "gas-station-off": "\u{f137}", + "gauge": "\u{eab1}", + "gauge-filled": "\u{fc2c}", + "gauge-off": "\u{f138}", + "gavel": "\u{ef90}", + "gender-agender": "\u{f0e1}", + "gender-androgyne": "\u{f0e2}", + "gender-bigender": "\u{f0e3}", + "gender-demiboy": "\u{f0e4}", + "gender-demigirl": "\u{f0e5}", + "gender-epicene": "\u{f0e6}", + "gender-female": "\u{f0e7}", + "gender-femme": "\u{f0e8}", + "gender-genderfluid": "\u{f0e9}", + "gender-genderless": "\u{f0ea}", + "gender-genderqueer": "\u{f0eb}", + "gender-hermaphrodite": "\u{f0ec}", + "gender-intergender": "\u{f0ed}", + "gender-male": "\u{f0ee}", + "gender-neutrois": "\u{f0ef}", + "gender-third": "\u{f0f0}", + "gender-transgender": "\u{f0f1}", + "gender-trasvesti": "\u{f0f2}", + "geometry": "\u{ee90}", + "ghost": "\u{eb8e}", + "ghost-2": "\u{f57c}", + "ghost-2-filled": "\u{f74a}", + "ghost-3": "\u{fc13}", + "ghost-3-filled": "\u{100a4}", + "ghost-filled": "\u{f74b}", + "ghost-off": "\u{f3f2}", + "gif": "\u{f257}", + "gift": "\u{eb68}", + "gift-card": "\u{f3aa}", + "gift-card-filled": "\u{fc2d}", + "gift-filled": "\u{fd14}", + "gift-off": "\u{f3f3}", + "git-branch": "\u{eab2}", + "git-branch-deleted": "\u{f57d}", + "git-cherry-pick": "\u{f57e}", + "git-commit": "\u{eab3}", + "git-compare": "\u{eab4}", + "git-fork": "\u{eb8f}", + "git-merge": "\u{eab5}", + "git-pull-request": "\u{eab6}", + "git-pull-request-closed": "\u{ef7f}", + "git-pull-request-draft": "\u{efb7}", + "gizmo": "\u{f02b}", + "glass": "\u{eab8}", + "glass-champagne": "\u{fd9c}", + "glass-cocktail": "\u{fd9d}", + "glass-filled": "\u{1000f}", + "glass-full": "\u{eab7}", + "glass-full-filled": "\u{fc2e}", + "glass-gin": "\u{fd9e}", + "glass-off": "\u{ee91}", + "globe": "\u{eab9}", + "globe-filled": "\u{fc2f}", + "globe-off": "\u{f139}", + "go-game": "\u{f512}", + "golf": "\u{ed8c}", + "golf-filled": "\u{100a3}", + "golf-off": "\u{f13a}", + "gps": "\u{ed7a}", + "gps-filled": "\u{fe48}", + "gradienter": "\u{f3ab}", + "grain": "\u{ee92}", + "graph": "\u{f288}", + "graph-filled": "\u{fd15}", + "graph-off": "\u{f3f4}", + "grave": "\u{f580}", + "grave-2": "\u{f57f}", + "grid-3x3": "\u{fca4}", + "grid-4x4": "\u{fca5}", + "grid-dots": "\u{eaba}", + "grid-goldenratio": "\u{fca6}", + "grid-pattern": "\u{efc9}", + "grid-pattern-filled": "\u{100c2}", + "grid-scan": "\u{fca7}", + "grill": "\u{efa9}", + "grill-fork": "\u{f35b}", + "grill-off": "\u{f3f5}", + "grill-spatula": "\u{f35c}", + "grip-horizontal": "\u{ec00}", + "grip-vertical": "\u{ec01}", + "growth": "\u{ee93}", + "guitar-pick": "\u{f4c6}", + "guitar-pick-filled": "\u{f67b}", + "gymnastics": "\u{fd44}", + "h-1": "\u{ec94}", + "h-2": "\u{ec95}", + "h-3": "\u{ec96}", + "h-4": "\u{ec97}", + "h-5": "\u{ec98}", + "h-6": "\u{ec99}", + "hammer": "\u{ef91}", + "hammer-off": "\u{f13c}", + "hand-click": "\u{ef4f}", + "hand-click-off": "\u{100f1}", + "hand-finger": "\u{ee94}", + "hand-finger-down": "\u{ff4f}", + "hand-finger-left": "\u{ff4e}", + "hand-finger-off": "\u{f13d}", + "hand-finger-right": "\u{ff4d}", + "hand-grab": "\u{f091}", + "hand-little-finger": "\u{ee95}", + "hand-love-you": "\u{ee97}", + "hand-middle-finger": "\u{ec2d}", + "hand-move": "\u{ef50}", + "hand-off": "\u{ed15}", + "hand-ring-finger": "\u{ee96}", + "hand-rock": "\u{ee97}", + "hand-sanitizer": "\u{f5f4}", + "hand-stop": "\u{ec2e}", + "hand-three-fingers": "\u{ee98}", + "hand-two-fingers": "\u{ee99}", + "hanger": "\u{ee9a}", + "hanger-2": "\u{f09c}", + "hanger-2-filled": "\u{ff61}", + "hanger-off": "\u{f13e}", + "hash": "\u{eabc}", + "haze": "\u{efaa}", + "haze-moon": "\u{faf8}", + "hdr": "\u{fa7b}", + "heading": "\u{ee9b}", + "heading-off": "\u{f13f}", + "headphones": "\u{eabd}", + "headphones-filled": "\u{fa3c}", + "headphones-off": "\u{ed1d}", + "headset": "\u{eb90}", + "headset-off": "\u{f3f6}", + "health-recognition": "\u{f1fb}", + "heart": "\u{eabe}", + "heart-bitcoin": "\u{ff3b}", + "heart-bolt": "\u{fb9e}", + "heart-broken": "\u{ecba}", + "heart-broken-filled": "\u{1016a}", + "heart-cancel": "\u{fb9f}", + "heart-check": "\u{fba0}", + "heart-code": "\u{fba1}", + "heart-cog": "\u{fba2}", + "heart-discount": "\u{fba3}", + "heart-dollar": "\u{fba4}", + "heart-down": "\u{fba5}", + "heart-exclamation": "\u{fba6}", + "heart-filled": "\u{f67c}", + "heart-handshake": "\u{f0f3}", + "heart-minus": "\u{f140}", + "heart-off": "\u{f141}", + "heart-pause": "\u{fba7}", + "heart-pin": "\u{fba8}", + "heart-plus": "\u{f142}", + "heart-question": "\u{fba9}", + "heart-rate-monitor": "\u{ef61}", + "heart-search": "\u{fbaa}", + "heart-share": "\u{fbab}", + "heart-spark": "\u{ffb6}", + "heart-star": "\u{fbac}", + "heart-up": "\u{fbad}", + "heart-x": "\u{fbae}", + "heartbeat": "\u{ef92}", + "hearts": "\u{f387}", + "hearts-off": "\u{f3f7}", + "helicopter": "\u{ed8e}", + "helicopter-filled": "\u{100f9}", + "helicopter-landing": "\u{ed8d}", + "helicopter-landing-filled": "\u{100c1}", + "helmet": "\u{efca}", + "helmet-off": "\u{f143}", + "help": "\u{eabf}", + "help-circle": "\u{f91d}", + "help-circle-filled": "\u{fa3d}", + "help-hexagon": "\u{f7a8}", + "help-hexagon-filled": "\u{fa3e}", + "help-octagon": "\u{f7a9}", + "help-octagon-filled": "\u{fa3f}", + "help-off": "\u{f3f8}", + "help-small": "\u{f91e}", + "help-square": "\u{f920}", + "help-square-filled": "\u{fa40}", + "help-square-rounded": "\u{f91f}", + "help-square-rounded-filled": "\u{fa41}", + "help-triangle": "\u{f921}", + "help-triangle-filled": "\u{fa42}", + "hemisphere": "\u{faa2}", + "hemisphere-off": "\u{faa0}", + "hemisphere-plus": "\u{faa1}", + "hexagon": "\u{ec02}", + "hexagon-0": "\u{f459}", + "hexagon-1": "\u{f45a}", + "hexagon-2": "\u{f45b}", + "hexagon-3": "\u{f45c}", + "hexagon-3d": "\u{f4c7}", + "hexagon-4": "\u{f45d}", + "hexagon-5": "\u{f45e}", + "hexagon-6": "\u{f45f}", + "hexagon-7": "\u{f460}", + "hexagon-8": "\u{f461}", + "hexagon-9": "\u{f462}", + "hexagon-filled": "\u{f67d}", + "hexagon-letter-a": "\u{f463}", + "hexagon-letter-a-filled": "\u{fe47}", + "hexagon-letter-b": "\u{f464}", + "hexagon-letter-b-filled": "\u{fe46}", + "hexagon-letter-c": "\u{f465}", + "hexagon-letter-c-filled": "\u{fe45}", + "hexagon-letter-d": "\u{f466}", + "hexagon-letter-d-filled": "\u{fe44}", + "hexagon-letter-e": "\u{f467}", + "hexagon-letter-e-filled": "\u{fe43}", + "hexagon-letter-f": "\u{f468}", + "hexagon-letter-f-filled": "\u{fe42}", + "hexagon-letter-g": "\u{f469}", + "hexagon-letter-g-filled": "\u{fe41}", + "hexagon-letter-h": "\u{f46a}", + "hexagon-letter-h-filled": "\u{fe40}", + "hexagon-letter-i": "\u{f46b}", + "hexagon-letter-i-filled": "\u{fe3f}", + "hexagon-letter-j": "\u{f46c}", + "hexagon-letter-j-filled": "\u{fe3e}", + "hexagon-letter-k": "\u{f46d}", + "hexagon-letter-k-filled": "\u{fe3d}", + "hexagon-letter-l": "\u{f46e}", + "hexagon-letter-l-filled": "\u{fe3c}", + "hexagon-letter-m": "\u{f46f}", + "hexagon-letter-m-filled": "\u{fe3b}", + "hexagon-letter-n": "\u{f470}", + "hexagon-letter-n-filled": "\u{fe3a}", + "hexagon-letter-o": "\u{f471}", + "hexagon-letter-o-filled": "\u{fe39}", + "hexagon-letter-p": "\u{f472}", + "hexagon-letter-p-filled": "\u{fe38}", + "hexagon-letter-q": "\u{f473}", + "hexagon-letter-q-filled": "\u{fe37}", + "hexagon-letter-r": "\u{f474}", + "hexagon-letter-r-filled": "\u{fe36}", + "hexagon-letter-s": "\u{f475}", + "hexagon-letter-s-filled": "\u{fe35}", + "hexagon-letter-t": "\u{f476}", + "hexagon-letter-t-filled": "\u{fe34}", + "hexagon-letter-u": "\u{f477}", + "hexagon-letter-u-filled": "\u{fe33}", + "hexagon-letter-v": "\u{f4b3}", + "hexagon-letter-v-filled": "\u{fe32}", + "hexagon-letter-w": "\u{f478}", + "hexagon-letter-w-filled": "\u{fe31}", + "hexagon-letter-x": "\u{f479}", + "hexagon-letter-x-filled": "\u{fe30}", + "hexagon-letter-y": "\u{f47a}", + //"hexagon-letter-y-filled": "\u{fe2f}", + "hexagon-letter-z": "\u{f47b}", + //"hexagon-letter-z-filled": "\u{fe2e}", + "hexagon-minus": "\u{fc8f}", + "hexagon-minus-2": "\u{fc8e}", + //"hexagon-minus-filled": "\u{fe2d}", + "hexagon-number-0": "\u{f459}", + "hexagon-number-0-filled": "\u{f74c}", + "hexagon-number-1": "\u{f45a}", + "hexagon-number-1-filled": "\u{f74d}", + "hexagon-number-2": "\u{f45b}", + "hexagon-number-2-filled": "\u{f74e}", + "hexagon-number-3": "\u{f45c}", + "hexagon-number-3-filled": "\u{f74f}", + "hexagon-number-4": "\u{f45d}", + "hexagon-number-4-filled": "\u{f750}", + "hexagon-number-5": "\u{f45e}", + "hexagon-number-5-filled": "\u{f751}", + "hexagon-number-6": "\u{f45f}", + "hexagon-number-6-filled": "\u{f752}", + "hexagon-number-7": "\u{f460}", + "hexagon-number-7-filled": "\u{f753}", + "hexagon-number-8": "\u{f461}", + "hexagon-number-8-filled": "\u{f754}", + "hexagon-number-9": "\u{f462}", + "hexagon-number-9-filled": "\u{f755}", + "hexagon-off": "\u{ee9c}", + "hexagon-plus": "\u{fc45}", + "hexagon-plus-2": "\u{fc90}", + //"hexagon-plus-filled": "\u{fe2c}", + "hexagonal-prism": "\u{faa5}", + "hexagonal-prism-off": "\u{faa3}", + "hexagonal-prism-plus": "\u{faa4}", + "hexagonal-pyramid": "\u{faa8}", + "hexagonal-pyramid-off": "\u{faa6}", + "hexagonal-pyramid-plus": "\u{faa7}", + "hexagons": "\u{f09d}", + "hexagons-off": "\u{f3f9}", + "hierarchy": "\u{ee9e}", + "hierarchy-2": "\u{ee9d}", + "hierarchy-3": "\u{f289}", + "hierarchy-off": "\u{f3fa}", + "highlight": "\u{ef3f}", + "highlight-off": "\u{f144}", + "history": "\u{ebea}", + "history-off": "\u{f3fb}", + "history-toggle": "\u{f1fc}", + "home": "\u{eac1}", + "home-2": "\u{eac0}", + "home-bitcoin": "\u{ff3a}", + "home-bolt": "\u{f336}", + "home-cancel": "\u{f350}", + "home-check": "\u{f337}", + "home-cog": "\u{f338}", + "home-dollar": "\u{f339}", + "home-dot": "\u{f33a}", + "home-down": "\u{f33b}", + "home-eco": "\u{f351}", + "home-edit": "\u{f352}", + "home-exclamation": "\u{f33c}", + //"home-filled": "\u{fe2b}", + "home-hand": "\u{f504}", + "home-heart": "\u{f353}", + "home-infinity": "\u{f505}", + "home-link": "\u{f354}", + "home-minus": "\u{f33d}", + "home-move": "\u{f33e}", + "home-off": "\u{f145}", + "home-plus": "\u{f33f}", + "home-question": "\u{f340}", + "home-ribbon": "\u{f355}", + "home-search": "\u{f341}", + "home-share": "\u{f342}", + "home-shield": "\u{f343}", + "home-signal": "\u{f356}", + "home-spark": "\u{ffb5}", + "home-star": "\u{f344}", + "home-stats": "\u{f345}", + "home-up": "\u{f346}", + "home-x": "\u{f347}", + "horse": "\u{fc46}", + "horse-toy": "\u{f28a}", + "horseshoe": "\u{fcb7}", + "hospital": "\u{fd59}", + "hospital-circle": "\u{fd58}", + "hospital-circle-filled": "\u{fed2}", + "hotel-service": "\u{ef80}", + "hourglass": "\u{ef93}", + "hourglass-empty": "\u{f146}", + "hourglass-filled": "\u{f756}", + "hourglass-high": "\u{f092}", + "hourglass-low": "\u{f093}", + "hourglass-off": "\u{f147}", + "hours-12": "\u{fc53}", + "hours-24": "\u{f5e7}", + "html": "\u{f7b1}", + "http-connect": "\u{fa28}", + "http-connect-off": "\u{100e7}", + "http-delete": "\u{fa29}", + "http-delete-off": "\u{100e6}", + "http-get": "\u{fa2a}", + "http-get-off": "\u{100e5}", + "http-head": "\u{fa2b}", + "http-head-off": "\u{100e4}", + "http-options": "\u{fa2c}", + "http-options-off": "\u{100e3}", + "http-patch": "\u{fa2d}", + "http-patch-off": "\u{100e2}", + "http-post": "\u{fa2e}", + "http-post-off": "\u{100e1}", + "http-put": "\u{fa2f}", + "http-put-off": "\u{100e0}", + "http-que": "\u{fa5b}", + "http-que-off": "\u{100df}", + "http-trace": "\u{fa30}", + "http-trace-off": "\u{100de}", + "hyprland": "\u{ec6a}", + "ice-cream": "\u{eac2}", + "ice-cream-2": "\u{ee9f}", + "ice-cream-off": "\u{f148}", + "ice-skating": "\u{efcb}", + "icons": "\u{f1d4}", + "icons-filled": "\u{10070}", + "icons-off": "\u{f3fc}", + "id": "\u{eac3}", + "id-badge": "\u{eff7}", + "id-badge-2": "\u{f076}", + "id-badge-off": "\u{f3fd}", + "id-off": "\u{f149}", + "ikosaedr": "\u{fec6}", + "image-in-picture": "\u{fd9f}", + "inbox": "\u{eac4}", + "inbox-off": "\u{f14a}", + "indent-decrease": "\u{eb91}", + "indent-increase": "\u{eb92}", + "infinity": "\u{eb69}", + "infinity-off": "\u{f3fe}", + "info-circle": "\u{eac5}", + "info-circle-filled": "\u{f6d8}", + "info-hexagon": "\u{f7aa}", + "info-hexagon-filled": "\u{fa43}", + "info-octagon": "\u{f7ab}", + "info-octagon-filled": "\u{fa44}", + "info-small": "\u{f922}", + "info-square": "\u{eac6}", + "info-square-filled": "\u{fa45}", + "info-square-rounded": "\u{f635}", + "info-square-rounded-filled": "\u{f6d9}", + "info-triangle": "\u{f923}", + "info-triangle-filled": "\u{fa46}", + "inner-shadow-bottom": "\u{f520}", + "inner-shadow-bottom-filled": "\u{f757}", + "inner-shadow-bottom-left": "\u{f51e}", + "inner-shadow-bottom-left-filled": "\u{f758}", + "inner-shadow-bottom-right": "\u{f51f}", + "inner-shadow-bottom-right-filled": "\u{f759}", + "inner-shadow-left": "\u{f521}", + "inner-shadow-left-filled": "\u{f75a}", + "inner-shadow-right": "\u{f522}", + "inner-shadow-right-filled": "\u{f75b}", + "inner-shadow-top": "\u{f525}", + "inner-shadow-top-filled": "\u{f75c}", + "inner-shadow-top-left": "\u{f523}", + "inner-shadow-top-left-filled": "\u{f75d}", + "inner-shadow-top-right": "\u{f524}", + "inner-shadow-top-right-filled": "\u{f75e}", + "input-ai": "\u{fc5a}", + "input-check": "\u{fc5b}", + "input-search": "\u{f2a2}", + "input-spark": "\u{ffb4}", + "input-x": "\u{fc5c}", + "invoice": "\u{feab}", + "ironing": "\u{fa7c}", + "ironing-1": "\u{f2f4}", + "ironing-1-filled": "\u{1006f}", + "ironing-2": "\u{f2f5}", + "ironing-2-filled": "\u{1006e}", + "ironing-3": "\u{f2f6}", + "ironing-3-filled": "\u{1006d}", + //"ironing-filled": "\u{fe2a}", + "ironing-off": "\u{f2f7}", + "ironing-steam": "\u{f2f9}", + "ironing-steam-filled": "\u{1006c}", + "ironing-steam-off": "\u{f2f8}", + "irregular-polyhedron": "\u{faab}", + "irregular-polyhedron-off": "\u{faa9}", + "irregular-polyhedron-plus": "\u{faaa}", + "italic": "\u{eb93}", + "jacket": "\u{f661}", + "jetpack": "\u{f581}", + //"jetpack-filled": "\u{fe29}", + "jewish-star": "\u{f3ff}", + "jewish-star-filled": "\u{f67e}", + "join-bevel": "\u{ff4c}", + "join-round": "\u{ff4b}", + "join-straight": "\u{ff4a}", + "joker": "\u{1005f}", + "jpg": "\u{f3ac}", + "json": "\u{f7b2}", + "jump-rope": "\u{ed8f}", + "karate": "\u{ed32}", + "kayak": "\u{f1d6}", + "kering": "\u{efb8}", + "kerning": "\u{efb8}", + "key": "\u{eac7}", + //"key-filled": "\u{fe28}", + "key-off": "\u{f14b}", + "keyboard": "\u{ebd6}", + "keyboard-filled": "\u{100a2}", + "keyboard-hide": "\u{ec7e}", + "keyboard-off": "\u{eea0}", + "keyboard-show": "\u{ec7f}", + "keyframe": "\u{f576}", + "keyframe-align-center": "\u{f582}", + "keyframe-align-center-filled": "\u{fc30}", + "keyframe-align-horizontal": "\u{f583}", + "keyframe-align-horizontal-filled": "\u{fc31}", + "keyframe-align-vertical": "\u{f584}", + "keyframe-align-vertical-filled": "\u{fc32}", + "keyframe-filled": "\u{fc33}", + "keyframes": "\u{f585}", + "keyframes-filled": "\u{fc34}", + "label": "\u{ff38}", + "label-filled": "\u{ff41}", + "label-important": "\u{ff49}", + "label-important-filled": "\u{ff60}", + "label-off": "\u{ff39}", + "ladder": "\u{efe2}", + "ladder-off": "\u{f14c}", + "ladle": "\u{fc14}", + "lambda": "\u{f541}", + "lamp": "\u{efab}", + "lamp-2": "\u{f09e}", + "lamp-off": "\u{f14d}", + "lane": "\u{faf9}", + "language": "\u{ebbe}", + "language-hiragana": "\u{ef77}", + "language-katakana": "\u{ef78}", + "language-off": "\u{f14e}", + "lasso": "\u{efac}", + "lasso-off": "\u{f14f}", + "lasso-polygon": "\u{f388}", + "lasso-polygon-filled": "\u{ff5f}", + "laurel-wreath": "\u{ff45}", + "laurel-wreath-1": "\u{ff48}", + "laurel-wreath-1-filled": "\u{10169}", + "laurel-wreath-2": "\u{ff47}", + "laurel-wreath-2-filled": "\u{10168}", + "laurel-wreath-3": "\u{ff46}", + "laurel-wreath-3-filled": "\u{10167}", + "laurel-wreath-filled": "\u{100c0}", + "layers-difference": "\u{eac8}", + "layers-intersect": "\u{eac9}", + "layers-intersect-2": "\u{eff8}", + "layers-linked": "\u{eea1}", + "layers-off": "\u{f150}", + "layers-selected": "\u{fea9}", + "layers-selected-bottom": "\u{feaa}", + "layers-subtract": "\u{eaca}", + "layers-union": "\u{eacb}", + "layout": "\u{eadb}", + "layout-2": "\u{eacc}", + //"layout-2-filled": "\u{fe27}", + //"layout-align-bottom": "\u{eacd}", + //"layout-align-bottom-filled": "\u{fe26}", + //"layout-align-center": "\u{eace}", + //"layout-align-center-filled": "\u{fe25}", + "layout-align-left": "\u{eacf}", + //"layout-align-left-filled": "\u{fe24}", + "layout-align-middle": "\u{ead0}", + //"layout-align-middle-filled": "\u{fe23}", + "layout-align-right": "\u{ead1}", + //"layout-align-right-filled": "\u{fe22}", + "layout-align-top": "\u{ead2}", + //"layout-align-top-filled": "\u{fe21}", + "layout-board": "\u{ef95}", + "layout-board-filled": "\u{10182}", + "layout-board-split": "\u{ef94}", + "layout-board-split-filled": "\u{10183}", + "layout-bottombar": "\u{ead3}", + "layout-bottombar-collapse": "\u{f28b}", + "layout-bottombar-collapse-filled": "\u{fc35}", + "layout-bottombar-expand": "\u{f28c}", + "layout-bottombar-expand-filled": "\u{fc36}", + "layout-bottombar-filled": "\u{fc37}", + "layout-bottombar-inactive": "\u{fd45}", + "layout-cards": "\u{ec13}", + //"layout-cards-filled": "\u{fe20}", + "layout-collage": "\u{f389}", + "layout-columns": "\u{ead4}", + "layout-dashboard": "\u{f02c}", + "layout-dashboard-filled": "\u{fe1f}", + "layout-distribute-horizontal": "\u{ead5}", + "layout-distribute-horizontal-filled": "\u{fe1e}", + "layout-distribute-vertical": "\u{ead6}", + "layout-distribute-vertical-filled": "\u{fe1d}", + "layout-filled": "\u{fe17}", + "layout-grid": "\u{edba}", + "layout-grid-add": "\u{edb9}", + "layout-grid-filled": "\u{fe1c}", + "layout-grid-remove": "\u{fa7d}", + "layout-kanban": "\u{ec3f}", + "layout-kanban-filled": "\u{fe1b}", + "layout-list": "\u{ec14}", + "layout-list-filled": "\u{fe1a}", + "layout-navbar": "\u{ead7}", + "layout-navbar-collapse": "\u{f28d}", + "layout-navbar-collapse-filled": "\u{fc38}", + "layout-navbar-expand": "\u{f28e}", + "layout-navbar-expand-filled": "\u{fc39}", + "layout-navbar-filled": "\u{fc3a}", + "layout-navbar-inactive": "\u{fd46}", + "layout-off": "\u{f151}", + "layout-rows": "\u{ead8}", + "layout-sidebar": "\u{eada}", + "layout-sidebar-filled": "\u{fe18}", + "layout-sidebar-inactive": "\u{fd47}", + "layout-sidebar-left-collapse": "\u{f004}", + "layout-sidebar-left-collapse-filled": "\u{fc3b}", + "layout-sidebar-left-expand": "\u{f005}", + "layout-sidebar-left-expand-filled": "\u{fc3c}", + "layout-sidebar-right": "\u{ead9}", + "layout-sidebar-right-collapse": "\u{f006}", + "layout-sidebar-right-collapse-filled": "\u{fc3d}", + "layout-sidebar-right-expand": "\u{f007}", + "layout-sidebar-right-expand-filled": "\u{fc3e}", + "layout-sidebar-right-filled": "\u{fe19}", + "layout-sidebar-right-inactive": "\u{fd48}", + "leaf": "\u{ed4f}", + "leaf-2": "\u{ff44}", + "leaf-off": "\u{f400}", + "lego": "\u{eadc}", + "lego-filled": "\u{fe16}", + "lego-off": "\u{f401}", + "lemon": "\u{ef10}", + "lemon-2": "\u{ef81}", + "lemon-2-filled": "\u{100bf}", + "letter-a": "\u{ec50}", + "letter-a-small": "\u{fcc7}", + "letter-b": "\u{ec51}", + "letter-b-small": "\u{fcc8}", + "letter-c": "\u{ec52}", + "letter-c-small": "\u{fcc9}", + "letter-case": "\u{eea5}", + "letter-case-lower": "\u{eea2}", + "letter-case-toggle": "\u{eea3}", + "letter-case-upper": "\u{eea4}", + "letter-d": "\u{ec53}", + "letter-d-small": "\u{fcca}", + "letter-e": "\u{ec54}", + "letter-e-small": "\u{fccb}", + "letter-f": "\u{ec55}", + "letter-f-small": "\u{fccc}", + "letter-g": "\u{ec56}", + "letter-g-small": "\u{fccd}", + "letter-h": "\u{ec57}", + "letter-h-small": "\u{fcce}", + "letter-i": "\u{ec58}", + "letter-i-small": "\u{fccf}", + "letter-j": "\u{ec59}", + "letter-j-small": "\u{fcd0}", + "letter-k": "\u{ec5a}", + "letter-k-small": "\u{fcd1}", + "letter-l": "\u{ec5b}", + "letter-l-small": "\u{fcd2}", + "letter-m": "\u{ec5c}", + "letter-m-small": "\u{fcd3}", + "letter-n": "\u{ec5d}", + "letter-n-small": "\u{fcd4}", + "letter-o": "\u{ec5e}", + "letter-o-small": "\u{fcd5}", + "letter-p": "\u{ec5f}", + "letter-p-small": "\u{fcd6}", + "letter-q": "\u{ec60}", + "letter-q-small": "\u{fcd7}", + "letter-r": "\u{ec61}", + "letter-r-small": "\u{fcd8}", + "letter-s": "\u{ec62}", + "letter-s-small": "\u{fcd9}", + "letter-spacing": "\u{eea6}", + "letter-t": "\u{ec63}", + "letter-t-small": "\u{fcda}", + "letter-u": "\u{ec64}", + "letter-u-small": "\u{fcdb}", + "letter-v": "\u{ec65}", + "letter-v-small": "\u{fcdc}", + "letter-w": "\u{ec66}", + "letter-w-small": "\u{fcdd}", + "letter-x": "\u{ec67}", + "letter-x-small": "\u{fcde}", + "letter-y": "\u{ec68}", + "letter-y-small": "\u{fcdf}", + "letter-z": "\u{ec69}", + "letter-z-small": "\u{fce0}", + "library": "\u{fd4c}", + "library-filled": "\u{10180}", + "library-minus": "\u{fd49}", + "library-photo": "\u{fd4a}", + "library-plus": "\u{fd4b}", + "library-plus-filled": "\u{10181}", + "license": "\u{ebc0}", + "license-off": "\u{f153}", + "lifebuoy": "\u{eadd}", + "lifebuoy-filled": "\u{100be}", + "lifebuoy-off": "\u{f154}", + "lighter": "\u{f794}", + "line": "\u{ec40}", + "line-dashed": "\u{eea7}", + "line-dotted": "\u{eea8}", + "line-height": "\u{eb94}", + "line-scan": "\u{fcb8}", + "link": "\u{eade}", + "link-minus": "\u{fd16}", + "link-off": "\u{f402}", + "link-plus": "\u{fd17}", + "list": "\u{eb6b}", + "list-check": "\u{eb6a}", + "list-details": "\u{ef40}", + "list-letters": "\u{fc47}", + "list-numbers": "\u{ef11}", + "list-search": "\u{eea9}", + "list-tree": "\u{fafa}", + "live-photo": "\u{eadf}", + "live-photo-filled": "\u{fed1}", + "live-photo-off": "\u{f403}", + "live-view": "\u{ec6b}", + "live-view-filled": "\u{100a1}", + "load-balancer": "\u{fa5c}", + "loader": "\u{eca3}", + "loader-2": "\u{f226}", + "loader-3": "\u{f513}", + "loader-quarter": "\u{eca2}", + "location": "\u{eae0}", + "location-bolt": "\u{fbaf}", + "location-broken": "\u{f2c4}", + "location-cancel": "\u{fbb0}", + "location-check": "\u{fbb1}", + "location-code": "\u{fbb2}", + "location-cog": "\u{fbb3}", + "location-discount": "\u{fbb4}", + "location-dollar": "\u{fbb5}", + "location-down": "\u{fbb6}", + "location-exclamation": "\u{fbb7}", + "location-filled": "\u{f67f}", + "location-heart": "\u{fbb8}", + "location-minus": "\u{fbb9}", + "location-off": "\u{f155}", + "location-pause": "\u{fbba}", + "location-pin": "\u{fbbb}", + "location-plus": "\u{fbbc}", + "location-question": "\u{fbbd}", + "location-search": "\u{fbbe}", + "location-share": "\u{fbbf}", + "location-star": "\u{fbc0}", + "location-up": "\u{fbc1}", + "location-x": "\u{fbc2}", + "lock": "\u{eae2}", + "lock-access": "\u{eeaa}", + "lock-access-off": "\u{f404}", + "lock-bitcoin": "\u{ff37}", + "lock-bolt": "\u{f924}", + "lock-cancel": "\u{f925}", + "lock-check": "\u{f926}", + "lock-code": "\u{f927}", + "lock-cog": "\u{f928}", + "lock-dollar": "\u{f929}", + "lock-down": "\u{f92a}", + "lock-exclamation": "\u{f92b}", + "lock-filled": "\u{fe15}", + "lock-heart": "\u{f92c}", + "lock-minus": "\u{f92d}", + "lock-off": "\u{ed1e}", + "lock-open": "\u{eae1}", + "lock-open-2": "\u{fea8}", + "lock-open-off": "\u{f156}", + "lock-password": "\u{ff9f}", + "lock-pause": "\u{f92e}", + "lock-pin": "\u{f92f}", + "lock-plus": "\u{f930}", + "lock-question": "\u{f931}", + "lock-search": "\u{f932}", + "lock-share": "\u{f933}", + "lock-square": "\u{ef51}", + "lock-square-rounded": "\u{f636}", + "lock-square-rounded-filled": "\u{f6da}", + "lock-star": "\u{f934}", + "lock-up": "\u{f935}", + "lock-x": "\u{f936}", + "logic-and": "\u{f240}", + "logic-buffer": "\u{f241}", + "logic-nand": "\u{f242}", + "logic-nor": "\u{f243}", + "logic-not": "\u{f244}", + "logic-or": "\u{f245}", + "logic-xnor": "\u{f246}", + "logic-xor": "\u{f247}", + "login": "\u{eba7}", + "login-2": "\u{fc76}", + "logout": "\u{eba8}", + "logout-2": "\u{fa7e}", + "logs": "\u{fea7}", + "lollipop": "\u{efcc}", + "lollipop-off": "\u{f157}", + "luggage": "\u{efad}", + "luggage-off": "\u{f158}", + "lungs": "\u{ef62}", + "lungs-filled": "\u{fe14}", + "lungs-off": "\u{f405}", + "macro": "\u{eeab}", + "macro-filled": "\u{fe13}", + "macro-off": "\u{f406}", + "magnet": "\u{eae3}", + "magnet-filled": "\u{fe12}", + "magnet-off": "\u{f159}", + "magnetic": "\u{fcb9}", + "mail": "\u{eae5}", + "mail-ai": "\u{fa31}", + "mail-bitcoin": "\u{ff36}", + "mail-bolt": "\u{f937}", + "mail-cancel": "\u{f938}", + "mail-check": "\u{f939}", + "mail-code": "\u{f93a}", + "mail-cog": "\u{f93b}", + "mail-dollar": "\u{f93c}", + "mail-down": "\u{f93d}", + "mail-exclamation": "\u{f93e}", + "mail-fast": "\u{f069}", + "mail-filled": "\u{fa47}", + "mail-forward": "\u{eeac}", + "mail-heart": "\u{f93f}", + "mail-minus": "\u{f940}", + "mail-off": "\u{f15a}", + "mail-opened": "\u{eae4}", + "mail-opened-filled": "\u{fa48}", + "mail-pause": "\u{f941}", + "mail-pin": "\u{f942}", + "mail-plus": "\u{f943}", + "mail-question": "\u{f944}", + "mail-search": "\u{f945}", + "mail-share": "\u{f946}", + "mail-spark": "\u{ffb3}", + "mail-star": "\u{f947}", + "mail-up": "\u{f948}", + "mail-x": "\u{f949}", + "mailbox": "\u{eead}", + "mailbox-off": "\u{f15b}", + "man": "\u{eae6}", + "man-filled": "\u{fe11}", + "manual-gearbox": "\u{ed7b}", + "manual-gearbox-filled": "\u{fe10}", + "map": "\u{eae9}", + "map-2": "\u{eae7}", + "map-bolt": "\u{fbc3}", + "map-cancel": "\u{fbc4}", + "map-check": "\u{fbc5}", + "map-code": "\u{fbc6}", + "map-cog": "\u{fbc7}", + "map-discount": "\u{fbc8}", + "map-dollar": "\u{fbc9}", + "map-down": "\u{fbca}", + "map-east": "\u{fc5d}", + "map-exclamation": "\u{fbcb}", + "map-heart": "\u{fbcc}", + "map-minus": "\u{fbcd}", + "map-north": "\u{fc5e}", + "map-off": "\u{f15c}", + "map-pause": "\u{fbce}", + "map-pin": "\u{eae8}", + "map-pin-2": "\u{fc48}", + "map-pin-bolt": "\u{f94a}", + "map-pin-cancel": "\u{f94b}", + "map-pin-check": "\u{f94c}", + "map-pin-code": "\u{f94d}", + "map-pin-cog": "\u{f94e}", + "map-pin-dollar": "\u{f94f}", + "map-pin-down": "\u{f950}", + "map-pin-exclamation": "\u{f951}", + "map-pin-filled": "\u{f680}", + "map-pin-heart": "\u{f952}", + "map-pin-minus": "\u{f953}", + "map-pin-off": "\u{ecf3}", + "map-pin-pause": "\u{f954}", + "map-pin-pin": "\u{f955}", + "map-pin-plus": "\u{f956}", + "map-pin-question": "\u{f957}", + "map-pin-search": "\u{f958}", + "map-pin-share": "\u{f795}", + "map-pin-star": "\u{f959}", + "map-pin-up": "\u{f95a}", + "map-pin-x": "\u{f95b}", + "map-pins": "\u{ed5e}", + "map-plus": "\u{fbcf}", + "map-question": "\u{fbd0}", + "map-route": "\u{fc79}", + "map-search": "\u{ef82}", + "map-share": "\u{fbd1}", + "map-south": "\u{fc5f}", + "map-star": "\u{fbd2}", + "map-up": "\u{fbd3}", + "map-west": "\u{fc60}", + "map-x": "\u{fbd4}", + "markdown": "\u{ec41}", + "markdown-off": "\u{f407}", + "marquee": "\u{ec77}", + "marquee-2": "\u{eeae}", + "marquee-off": "\u{f15d}", + "mars": "\u{ec80}", + "mask": "\u{eeb0}", + "mask-off": "\u{eeaf}", + "masks-theater": "\u{f263}", + "masks-theater-off": "\u{f408}", + "massage": "\u{eeb1}", + "matchstick": "\u{f577}", + "math": "\u{ebeb}", + "math-1-divide-2": "\u{f4e2}", + "math-1-divide-3": "\u{f4e3}", + "math-avg": "\u{f0f4}", + "math-cos": "\u{ff1f}", + "math-ctg": "\u{ff35}", + "math-equal-greater": "\u{f4e4}", + "math-equal-lower": "\u{f4e5}", + "math-function": "\u{eeb2}", + "math-function-off": "\u{f15e}", + "math-function-y": "\u{f4e6}", + "math-greater": "\u{f4e7}", + "math-integral": "\u{f4e9}", + "math-integral-x": "\u{f4e8}", + "math-integrals": "\u{f4ea}", + "math-lower": "\u{f4eb}", + "math-max": "\u{f0f5}", + "math-max-min": "\u{fda0}", + "math-min": "\u{f0f6}", + "math-not": "\u{f4ec}", + "math-off": "\u{f409}", + "math-pi": "\u{f4ee}", + "math-pi-divide-2": "\u{f4ed}", + "math-sec": "\u{ff34}", + "math-sin": "\u{ff1e}", + "math-symbols": "\u{eeb3}", + "math-tg": "\u{ff33}", + "math-x-divide-2": "\u{f4ef}", + "math-x-divide-y": "\u{f4f1}", + "math-x-divide-y-2": "\u{f4f0}", + "math-x-floor-divide-y": "\u{10073}", + "math-x-minus-x": "\u{f4f2}", + "math-x-minus-y": "\u{f4f3}", + "math-x-plus-x": "\u{f4f4}", + "math-x-plus-y": "\u{f4f5}", + "math-xy": "\u{f4f6}", + "math-y-minus-y": "\u{f4f7}", + "math-y-plus-y": "\u{f4f8}", + "matrix": "\u{100bc}", + "maximize": "\u{eaea}", + "maximize-off": "\u{f15f}", + "meat": "\u{ef12}", + "meat-off": "\u{f40a}", + "medal": "\u{ec78}", + "medal-2": "\u{efcd}", + "medical-cross": "\u{ec2f}", + "medical-cross-circle": "\u{fae8}", + "medical-cross-filled": "\u{f681}", + "medical-cross-off": "\u{f160}", + "medicine-syrup": "\u{ef63}", + "meeple": "\u{f514}", + "meeple-filled": "\u{100a0}", + "melon": "\u{fc7a}", + "melon-filled": "\u{1000e}", + "menorah": "\u{f58c}", + "menu": "\u{eaeb}", + "menu-2": "\u{ec42}", + "menu-3": "\u{ff43}", + "menu-4": "\u{ff42}", + "menu-deep": "\u{fafb}", + "menu-order": "\u{f5f5}", + "message": "\u{eaef}", + "message-2": "\u{eaec}", + "message-2-bolt": "\u{f95c}", + "message-2-cancel": "\u{f95d}", + "message-2-check": "\u{f95e}", + "message-2-code": "\u{f012}", + "message-2-cog": "\u{f95f}", + "message-2-dollar": "\u{f960}", + "message-2-down": "\u{f961}", + "message-2-exclamation": "\u{f962}", + "message-2-filled": "\u{1009f}", + "message-2-heart": "\u{f963}", + "message-2-minus": "\u{f964}", + "message-2-off": "\u{f40b}", + "message-2-pause": "\u{f965}", + "message-2-pin": "\u{f966}", + "message-2-plus": "\u{f967}", + "message-2-question": "\u{f968}", + "message-2-search": "\u{f969}", + "message-2-share": "\u{f077}", + "message-2-star": "\u{f96a}", + "message-2-up": "\u{f96b}", + "message-2-x": "\u{f96c}", + "message-bolt": "\u{f96d}", + "message-cancel": "\u{f96e}", + "message-chatbot": "\u{f38a}", + "message-chatbot-filled": "\u{fed0}", + "message-check": "\u{f96f}", + "message-circle": "\u{eaed}", + "message-circle-2": "\u{eaed}", + "message-circle-2-filled": "\u{fecf}", + "message-circle-bolt": "\u{f970}", + "message-circle-cancel": "\u{f971}", + "message-circle-check": "\u{f972}", + "message-circle-code": "\u{f973}", + "message-circle-cog": "\u{f974}", + "message-circle-dollar": "\u{f975}", + "message-circle-down": "\u{f976}", + "message-circle-exclamation": "\u{f977}", + "message-circle-filled": "\u{fecf}", + "message-circle-heart": "\u{f978}", + "message-circle-minus": "\u{f979}", + "message-circle-off": "\u{ed40}", + "message-circle-pause": "\u{f97a}", + "message-circle-pin": "\u{f97b}", + "message-circle-plus": "\u{f97c}", + "message-circle-question": "\u{f97d}", + "message-circle-search": "\u{f97e}", + "message-circle-share": "\u{f97f}", + "message-circle-star": "\u{f980}", + "message-circle-up": "\u{f981}", + "message-circle-user": "\u{fec5}", + "message-circle-x": "\u{f982}", + "message-code": "\u{f013}", + "message-cog": "\u{f983}", + "message-dollar": "\u{f984}", + "message-dots": "\u{eaee}", + "message-down": "\u{f985}", + "message-exclamation": "\u{f986}", + "message-filled": "\u{fecd}", + "message-forward": "\u{f28f}", + "message-heart": "\u{f987}", + "message-language": "\u{efae}", + "message-minus": "\u{f988}", + "message-off": "\u{ed41}", + "message-pause": "\u{f989}", + "message-pin": "\u{f98a}", + "message-plus": "\u{ec9a}", + "message-question": "\u{f98b}", + "message-reply": "\u{fd4d}", + "message-report": "\u{ec9b}", + "message-report-filled": "\u{fece}", + "message-search": "\u{f98c}", + "message-share": "\u{f078}", + "message-star": "\u{f98d}", + "message-up": "\u{f98e}", + "message-user": "\u{fec4}", + "message-x": "\u{f98f}", + "messages": "\u{eb6c}", + "messages-off": "\u{ed42}", + "meteor": "\u{f1fd}", + "meteor-filled": "\u{1000d}", + "meteor-off": "\u{f40c}", + "meter-cube": "\u{fd7c}", + "meter-square": "\u{fd7d}", + "metronome": "\u{fd25}", + "michelin-bib-gourmand": "\u{fae9}", + "michelin-star": "\u{faeb}", + "michelin-star-filled": "\u{1000c}", + "michelin-star-green": "\u{faea}", + "mickey": "\u{f2a3}", + "mickey-filled": "\u{f683}", + "microphone": "\u{eaf0}", + "microphone-2": "\u{ef2c}", + "microphone-2-off": "\u{f40d}", + //"microphone-filled": "\u{fe0f}", + "microphone-off": "\u{ed16}", + "microscope": "\u{ef64}", + "microscope-filled": "\u{10166}", + "microscope-off": "\u{f40e}", + "microwave": "\u{f248}", + //"microwave-filled": "\u{fe0e}", + "microwave-off": "\u{f264}", + "military-award": "\u{f079}", + "military-rank": "\u{efcf}", + "military-rank-filled": "\u{ff5e}", + "milk": "\u{ef13}", + "milk-filled": "\u{1000b}", + "milk-off": "\u{f40f}", + "milkshake": "\u{f4c8}", + "minimize": "\u{eaf1}", + "minus": "\u{eaf2}", + "minus-vertical": "\u{eeb4}", + "mist": "\u{ec30}", + "mist-off": "\u{f410}", + "mobiledata": "\u{f9f5}", + "mobiledata-off": "\u{f9f4}", + "moneybag": "\u{f506}", + "moneybag-edit": "\u{1013d}", + "moneybag-heart": "\u{1013c}", + "moneybag-minus": "\u{1013b}", + "moneybag-move": "\u{10139}", + "moneybag-move-back": "\u{1013a}", + "moneybag-plus": "\u{10138}", + "monkeybar": "\u{feb4}", + "mood-angry": "\u{f2de}", + "mood-angry-filled": "\u{ff0a}", + "mood-annoyed": "\u{f2e0}", + "mood-annoyed-2": "\u{f2df}", + "mood-bitcoin": "\u{ff32}", + "mood-boy": "\u{ed2d}", + "mood-check": "\u{f7b3}", + "mood-cog": "\u{f7b4}", + "mood-confuzed": "\u{eaf3}", + "mood-confuzed-filled": "\u{f7f2}", + "mood-crazy-happy": "\u{ed90}", + "mood-crazy-happy-filled": "\u{ff09}", + "mood-cry": "\u{ecbb}", + "mood-dollar": "\u{f7b5}", + "mood-edit": "\u{fa05}", + "mood-empty": "\u{eeb5}", + "mood-empty-filled": "\u{f7f3}", + "mood-happy": "\u{eaf4}", + "mood-happy-filled": "\u{f7f4}", + "mood-heart": "\u{f7b6}", + "mood-kid": "\u{ec03}", + "mood-kid-filled": "\u{f7f5}", + "mood-look-down": "\u{fd37}", + "mood-look-left": "\u{f2c5}", + "mood-look-right": "\u{f2c6}", + "mood-look-up": "\u{fd38}", + "mood-minus": "\u{f7b7}", + "mood-nerd": "\u{f2e1}", + "mood-nervous": "\u{ef96}", + "mood-neutral": "\u{eaf5}", + "mood-neutral-filled": "\u{f7f6}", + "mood-off": "\u{f161}", + "mood-pin": "\u{f7b8}", + "mood-plus": "\u{f7b9}", + "mood-puzzled": "\u{fd39}", + "mood-sad": "\u{eaf6}", + "mood-sad-2": "\u{f2e2}", + "mood-sad-dizzy": "\u{f2e3}", + "mood-sad-filled": "\u{f7f7}", + "mood-sad-squint": "\u{f2e4}", + "mood-search": "\u{f7ba}", + "mood-share": "\u{fa06}", + "mood-sick": "\u{f2e5}", + "mood-silence": "\u{f2e6}", + "mood-sing": "\u{f2c7}", + "mood-smile": "\u{eaf7}", + "mood-smile-beam": "\u{f2e7}", + "mood-smile-dizzy": "\u{f2e8}", + "mood-smile-filled": "\u{f7f8}", + "mood-spark": "\u{ffb2}", + "mood-suprised": "\u{ec04}", + "mood-surprised": "\u{ec04}", + "mood-tongue": "\u{eb95}", + "mood-tongue-wink": "\u{f2ea}", + "mood-tongue-wink-2": "\u{f2e9}", + "mood-unamused": "\u{f2eb}", + "mood-up": "\u{f7bb}", + "mood-wink": "\u{f2ed}", + "mood-wink-2": "\u{f2ec}", + "mood-wrrr": "\u{f2ee}", + "mood-wrrr-filled": "\u{ff08}", + "mood-x": "\u{f7bc}", + "mood-xd": "\u{f2ef}", + "moon": "\u{eaf8}", + "moon-2": "\u{ece6}", + "moon-filled": "\u{f684}", + "moon-off": "\u{f162}", + "moon-stars": "\u{ece7}", + "moped": "\u{ecbc}", + "motorbike": "\u{eeb6}", + "motorbike-filled": "\u{100f8}", + "mountain": "\u{ef97}", + "mountain-filled": "\u{1000a}", + "mountain-off": "\u{f411}", + "mouse": "\u{eaf9}", + "mouse-2": "\u{f1d7}", + "mouse-filled": "\u{fb2f}", + "mouse-off": "\u{f163}", + "moustache": "\u{f4c9}", + "movie": "\u{eafa}", + "movie-off": "\u{f164}", + "mug": "\u{eafb}", + "mug-filled": "\u{10009}", + "mug-off": "\u{f165}", + "multiplier-0-5x": "\u{ef41}", + "multiplier-1-5x": "\u{ef42}", + "multiplier-1x": "\u{ef43}", + "multiplier-2x": "\u{ef44}", + "mushroom": "\u{ef14}", + "mushroom-filled": "\u{f7f9}", + "mushroom-off": "\u{f412}", + "music": "\u{eafc}", + "music-bolt": "\u{fbd5}", + "music-cancel": "\u{fbd6}", + "music-check": "\u{fbd7}", + "music-code": "\u{fbd8}", + "music-cog": "\u{fbd9}", + "music-discount": "\u{fbda}", + "music-dollar": "\u{fbdb}", + "music-down": "\u{fbdc}", + "music-exclamation": "\u{fbdd}", + "music-heart": "\u{fbde}", + "music-minus": "\u{fbdf}", + "music-off": "\u{f166}", + "music-pause": "\u{fbe0}", + "music-pin": "\u{fbe1}", + "music-plus": "\u{fbe2}", + "music-question": "\u{fbe3}", + "music-search": "\u{fbe4}", + "music-share": "\u{fbe5}", + "music-star": "\u{fbe6}", + "music-up": "\u{fbe7}", + "music-x": "\u{fbe8}", + "navigation": "\u{f2c8}", + "navigation-bolt": "\u{fbe9}", + "navigation-cancel": "\u{fbea}", + "navigation-check": "\u{fbeb}", + "navigation-code": "\u{fbec}", + "navigation-cog": "\u{fbed}", + "navigation-discount": "\u{fbee}", + "navigation-dollar": "\u{fbef}", + "navigation-down": "\u{fbf0}", + "navigation-east": "\u{fcba}", + "navigation-exclamation": "\u{fbf1}", + "navigation-filled": "\u{f685}", + "navigation-heart": "\u{fbf2}", + "navigation-minus": "\u{fbf3}", + "navigation-north": "\u{fcbb}", + "navigation-off": "\u{f413}", + "navigation-pause": "\u{fbf4}", + "navigation-pin": "\u{fbf5}", + "navigation-plus": "\u{fbf6}", + "navigation-question": "\u{fbf7}", + "navigation-search": "\u{fbf8}", + "navigation-share": "\u{fbf9}", + "navigation-south": "\u{fcbc}", + "navigation-star": "\u{fbfa}", + "navigation-top": "\u{faec}", + "navigation-up": "\u{fbfb}", + "navigation-west": "\u{fcbd}", + "navigation-x": "\u{fbfc}", + "needle": "\u{f508}", + "needle-thread": "\u{f507}", + "network": "\u{f09f}", + "network-off": "\u{f414}", + "new-section": "\u{ebc1}", + "news": "\u{eafd}", + "news-off": "\u{f167}", + "nfc": "\u{eeb7}", + "nfc-off": "\u{f168}", + "niri": "\u{ec32}", + "noctalia": "\u{ec33}", + "no-copyright": "\u{efb9}", + "no-creative-commons": "\u{efba}", + "no-derivatives": "\u{efbb}", + "north-star": "\u{f014}", + "note": "\u{eb6d}", + "note-off": "\u{f169}", + "notebook": "\u{eb96}", + "notebook-off": "\u{f415}", + "notes": "\u{eb6e}", + "notes-off": "\u{f16a}", + "notification": "\u{eafe}", + "notification-off": "\u{f16b}", + "number": "\u{f1fe}", + "number-0": "\u{edf0}", + "number-0-small": "\u{fce1}", + "number-1": "\u{edf1}", + "number-1-small": "\u{fce2}", + "number-10": "\u{1005e}", + "number-10-small": "\u{fce3}", + "number-100-small": "\u{10005}", + "number-11": "\u{1005d}", + "number-11-small": "\u{fce4}", + "number-12-small": "\u{fce5}", + "number-123": "\u{f554}", + "number-13-small": "\u{fce6}", + "number-14-small": "\u{fce7}", + "number-15-small": "\u{fce8}", + "number-16-small": "\u{fce9}", + "number-17-small": "\u{fcea}", + "number-18-small": "\u{fceb}", + "number-19-small": "\u{fcec}", + "number-2": "\u{edf2}", + "number-2-small": "\u{fced}", + "number-20-small": "\u{fcee}", + "number-21-small": "\u{fcef}", + "number-22-small": "\u{fcf0}", + "number-23-small": "\u{fcf1}", + "number-24-small": "\u{fcf2}", + "number-25-small": "\u{fcf3}", + "number-26-small": "\u{fcf4}", + "number-27-small": "\u{fcf5}", + "number-28-small": "\u{fcf6}", + "number-29-small": "\u{fcf7}", + "number-3": "\u{edf3}", + "number-3-small": "\u{fcf8}", + "number-30-small": "\u{10004}", + "number-31-small": "\u{10003}", + "number-32-small": "\u{10002}", + "number-33-small": "\u{10001}", + "number-34-small": "\u{10000}", + "number-35-small": "\u{ffff}", + "number-36-small": "\u{fffe}", + "number-37-small": "\u{fffd}", + "number-38-small": "\u{fffc}", + "number-39-small": "\u{fffb}", + "number-4": "\u{edf4}", + "number-4-small": "\u{fcf9}", + "number-40-small": "\u{fffa}", + "number-41-small": "\u{fff9}", + //"number-42-small": "\u{fff8}", + //"number-43-small": "\u{fff7}", + //"number-44-small": "\u{fff6}", + //"number-45-small": "\u{fff5}", + //"number-46-small": "\u{fff4}", + //"number-47-small": "\u{fff3}", + //"number-48-small": "\u{fff2}", + //"number-49-small": "\u{fff1}", + "number-5": "\u{edf5}", + "number-5-small": "\u{fcfa}", + //"number-50-small": "\u{fff0}", + "number-51-small": "\u{ffef}", + "number-52-small": "\u{ffee}", + "number-53-small": "\u{ffed}", + "number-54-small": "\u{ffec}", + "number-55-small": "\u{ffeb}", + "number-56-small": "\u{ffea}", + "number-57-small": "\u{ffe9}", + "number-58-small": "\u{ffe8}", + "number-59-small": "\u{ffe7}", + "number-6": "\u{edf6}", + "number-6-small": "\u{fcfb}", + "number-60-small": "\u{ffe6}", + "number-61-small": "\u{ffe5}", + "number-62-small": "\u{ffe4}", + "number-63-small": "\u{ffe3}", + "number-64-small": "\u{ffe2}", + "number-65-small": "\u{ffe1}", + "number-66-small": "\u{ffe0}", + "number-67-small": "\u{ffdf}", + "number-68-small": "\u{ffde}", + "number-69-small": "\u{ffdd}", + "number-7": "\u{edf7}", + "number-7-small": "\u{fcfc}", + "number-70-small": "\u{ffdc}", + "number-71-small": "\u{ffdb}", + "number-72-small": "\u{ffda}", + "number-73-small": "\u{ffd9}", + "number-74-small": "\u{ffd8}", + "number-75-small": "\u{ffd7}", + "number-76-small": "\u{ffd6}", + "number-77-small": "\u{ffd5}", + "number-78-small": "\u{ffd4}", + "number-79-small": "\u{ffd3}", + "number-8": "\u{edf8}", + "number-8-small": "\u{fcfd}", + "number-80-small": "\u{ffd2}", + "number-81-small": "\u{ffd1}", + "number-82-small": "\u{ffd0}", + "number-83-small": "\u{ffcf}", + "number-84-small": "\u{ffce}", + "number-85-small": "\u{ffcd}", + "number-86-small": "\u{ffcc}", + "number-87-small": "\u{ffcb}", + "number-88-small": "\u{ffca}", + "number-89-small": "\u{ffc9}", + "number-9": "\u{edf9}", + "number-9-small": "\u{fcfe}", + "number-90-small": "\u{ffc8}", + "number-91-small": "\u{ffc7}", + "number-92-small": "\u{ffc6}", + "number-93-small": "\u{ffc5}", + "number-94-small": "\u{ffc4}", + "number-95-small": "\u{ffc3}", + "number-96-small": "\u{ffc2}", + "number-97-small": "\u{ffc1}", + "number-98-small": "\u{ffc0}", + "number-99-small": "\u{ffbf}", + "numbers": "\u{f015}", + "nurse": "\u{ef65}", + "nurse-filled": "\u{1009e}", + "nut": "\u{fc61}", + "object-scan": "\u{fef1}", + "octagon": "\u{ecbd}", + "octagon-filled": "\u{f686}", + "octagon-minus": "\u{fc92}", + "octagon-minus-2": "\u{fc91}", + "octagon-minus-filled": "\u{1017f}", + "octagon-off": "\u{eeb8}", + "octagon-plus": "\u{fc94}", + "octagon-plus-2": "\u{fc93}", + "octagon-plus-filled": "\u{1017e}", + "octahedron": "\u{faae}", + "octahedron-off": "\u{faac}", + "octahedron-plus": "\u{faad}", + "old": "\u{eeb9}", + "olympics": "\u{eeba}", + "olympics-off": "\u{f416}", + "om": "\u{f58d}", + "omega": "\u{eb97}", + "outbound": "\u{f249}", + "outlet": "\u{ebd7}", + "oval": "\u{f02e}", + "oval-filled": "\u{f687}", + "oval-vertical": "\u{f02d}", + "oval-vertical-filled": "\u{f688}", + "overline": "\u{eebb}", + "package": "\u{eaff}", + "package-export": "\u{f07a}", + "package-import": "\u{f07b}", + "package-off": "\u{f16c}", + "packages": "\u{f2c9}", + "pacman": "\u{eebc}", + "page-break": "\u{ec81}", + "paint": "\u{eb00}", + "paint-filled": "\u{f75f}", + "paint-off": "\u{f16d}", + "palette": "\u{eb01}", + "palette-filled": "\u{1009d}", + "palette-off": "\u{f16e}", + "panorama-horizontal": "\u{ed33}", + "panorama-horizontal-filled": "\u{fecc}", + "panorama-horizontal-off": "\u{f417}", + "panorama-vertical": "\u{ed34}", + "panorama-vertical-filled": "\u{fecb}", + "panorama-vertical-off": "\u{f418}", + "paper-bag": "\u{f02f}", + "paper-bag-off": "\u{f16f}", + "paperclip": "\u{eb02}", + "parachute": "\u{ed7c}", + "parachute-off": "\u{f170}", + "parentheses": "\u{ebd8}", + "parentheses-off": "\u{f171}", + "parking": "\u{eb03}", + "parking-circle": "\u{fd5a}", + "parking-circle-filled": "\u{feca}", + "parking-off": "\u{f172}", + "password": "\u{f4ca}", + "password-fingerprint": "\u{fc7b}", + "password-mobile-phone": "\u{fc7c}", + "password-user": "\u{fc7d}", + "paw": "\u{eff9}", + "paw-filled": "\u{f689}", + "paw-off": "\u{f419}", + "paywall": "\u{fd7e}", + "pdf": "\u{f7ac}", + "peace": "\u{ecbe}", + "pencil": "\u{eb04}", + "pencil-bolt": "\u{fbfd}", + "pencil-cancel": "\u{fbfe}", + "pencil-check": "\u{fbff}", + "pencil-code": "\u{fc00}", + "pencil-cog": "\u{fc01}", + "pencil-discount": "\u{fc02}", + "pencil-dollar": "\u{fc03}", + "pencil-down": "\u{fc04}", + "pencil-exclamation": "\u{fc05}", + "pencil-heart": "\u{fc06}", + "pencil-minus": "\u{f1eb}", + "pencil-off": "\u{f173}", + "pencil-pause": "\u{fc07}", + "pencil-pin": "\u{fc08}", + "pencil-plus": "\u{f1ec}", + "pencil-question": "\u{fc09}", + "pencil-search": "\u{fc0a}", + "pencil-share": "\u{fc0b}", + "pencil-star": "\u{fc0c}", + "pencil-up": "\u{fc0d}", + "pencil-x": "\u{fc0e}", + "pennant": "\u{ed7d}", + "pennant-2": "\u{f06a}", + "pennant-2-filled": "\u{f68a}", + "pennant-filled": "\u{f68b}", + "pennant-off": "\u{f174}", + "pentagon": "\u{efe3}", + "pentagon-filled": "\u{f68c}", + "pentagon-minus": "\u{feb3}", + "pentagon-number-0": "\u{fc7e}", + "pentagon-number-1": "\u{fc7f}", + "pentagon-number-2": "\u{fc80}", + "pentagon-number-3": "\u{fc81}", + "pentagon-number-4": "\u{fc82}", + "pentagon-number-5": "\u{fc83}", + "pentagon-number-6": "\u{fc84}", + "pentagon-number-7": "\u{fc85}", + "pentagon-number-8": "\u{fc86}", + "pentagon-number-9": "\u{fc87}", + "pentagon-off": "\u{f41a}", + "pentagon-plus": "\u{fc49}", + "pentagon-x": "\u{fc88}", + "pentagram": "\u{f586}", + "pepper": "\u{ef15}", + "pepper-off": "\u{f175}", + "percentage": "\u{ecf4}", + "percentage-0": "\u{fee5}", + "percentage-10": "\u{fee4}", + "percentage-100": "\u{fee3}", + "percentage-20": "\u{fee2}", + "percentage-25": "\u{fee1}", + "percentage-30": "\u{fee0}", + "percentage-33": "\u{fedf}", + "percentage-40": "\u{fede}", + "percentage-50": "\u{fedd}", + "percentage-60": "\u{fedc}", + "percentage-66": "\u{fedb}", + "percentage-70": "\u{feda}", + "percentage-75": "\u{fed9}", + "percentage-80": "\u{fed8}", + "percentage-90": "\u{fed7}", + "perfume": "\u{f509}", + "perspective": "\u{eebd}", + "perspective-off": "\u{f176}", + "phone": "\u{eb09}", + "phone-call": "\u{eb05}", + "phone-calling": "\u{ec43}", + "phone-check": "\u{ec05}", + "phone-done": "\u{ff9e}", + "phone-end": "\u{ff9d}", + "phone-filled": "\u{fa49}", + "phone-incoming": "\u{eb06}", + "phone-off": "\u{ecf5}", + "phone-outgoing": "\u{eb07}", + "phone-pause": "\u{eb08}", + "phone-plus": "\u{ec06}", + "phone-ringing": "\u{ff9c}", + "phone-spark": "\u{ffb1}", + "phone-x": "\u{ec07}", + "photo": "\u{eb0a}", + "photo-ai": "\u{fa32}", + "photo-bitcoin": "\u{ff31}", + "photo-bolt": "\u{f990}", + "photo-cancel": "\u{f35d}", + "photo-check": "\u{f35e}", + "photo-circle": "\u{fc4a}", + "photo-circle-minus": "\u{fc62}", + "photo-circle-plus": "\u{fc63}", + "photo-code": "\u{f991}", + "photo-cog": "\u{f992}", + "photo-dollar": "\u{f993}", + "photo-down": "\u{f35f}", + "photo-edit": "\u{f360}", + "photo-exclamation": "\u{f994}", + "photo-filled": "\u{fa4a}", + "photo-heart": "\u{f361}", + "photo-hexagon": "\u{fc4b}", + "photo-minus": "\u{f362}", + "photo-off": "\u{ecf6}", + "photo-pause": "\u{f995}", + "photo-pentagon": "\u{fc4c}", + "photo-pin": "\u{f996}", + "photo-plus": "\u{f363}", + "photo-question": "\u{f997}", + "photo-scan": "\u{fca8}", + "photo-search": "\u{f364}", + "photo-sensor": "\u{f798}", + "photo-sensor-2": "\u{f796}", + "photo-sensor-3": "\u{f797}", + "photo-share": "\u{f998}", + "photo-shield": "\u{f365}", + "photo-spark": "\u{ffb0}", + "photo-square-rounded": "\u{fc4d}", + "photo-star": "\u{f366}", + "photo-up": "\u{f38b}", + "photo-video": "\u{fc95}", + "photo-x": "\u{f367}", + "physotherapist": "\u{eebe}", + "piano": "\u{fad3}", + "pick": "\u{fafc}", + "picnic-table": "\u{fed6}", + "picture-in-picture": "\u{ed35}", + "picture-in-picture-filled": "\u{fec1}", + "picture-in-picture-off": "\u{ed43}", + "picture-in-picture-on": "\u{ed44}", + "picture-in-picture-top": "\u{efe4}", + "picture-in-picture-top-filled": "\u{fec2}", + "pig": "\u{ef52}", + "pig-filled": "\u{1010a}", + "pig-money": "\u{f38c}", + "pig-off": "\u{f177}", + "pilcrow": "\u{f5f6}", + "pilcrow-left": "\u{fd7f}", + "pilcrow-right": "\u{fd80}", + "pill": "\u{ec44}", + "pill-filled": "\u{ff07}", + "pill-off": "\u{f178}", + "pills": "\u{ef66}", + "pin": "\u{ec9c}", + "pin-end": "\u{fd5b}", + "pin-filled": "\u{f68d}", + "pin-invoke": "\u{fd5c}", + "ping-pong": "\u{f38d}", + "pinned": "\u{ed60}", + "pinned-filled": "\u{f68e}", + "pinned-off": "\u{ed5f}", + "pizza": "\u{edbb}", + "pizza-filled": "\u{10008}", + "pizza-off": "\u{f179}", + "placeholder": "\u{f626}", + "plane": "\u{eb6f}", + "plane-arrival": "\u{eb99}", + "plane-departure": "\u{eb9a}", + "plane-inflight": "\u{ef98}", + "plane-off": "\u{f17a}", + "plane-tilt": "\u{f1ed}", + "planet": "\u{ec08}", + "planet-off": "\u{f17b}", + "plant": "\u{ed50}", + "plant-2": "\u{ed7e}", + "plant-2-off": "\u{f17c}", + "plant-off": "\u{f17d}", + "play-basketball": "\u{fa66}", + "play-card": "\u{eebf}", + "play-card-1": "\u{1005c}", + "play-card-1-filled": "\u{10083}", + "play-card-10": "\u{1005b}", + "play-card-10-filled": "\u{10082}", + "play-card-2": "\u{1005a}", + "play-card-2-filled": "\u{10081}", + "play-card-3": "\u{10059}", + "play-card-3-filled": "\u{10080}", + "play-card-4": "\u{10058}", + "play-card-4-filled": "\u{1007f}", + "play-card-5": "\u{10057}", + "play-card-5-filled": "\u{1007e}", + "play-card-6": "\u{10056}", + "play-card-6-filled": "\u{1007d}", + "play-card-7": "\u{10055}", + "play-card-7-filled": "\u{1007c}", + "play-card-8": "\u{10054}", + "play-card-8-filled": "\u{1007b}", + "play-card-9": "\u{10053}", + "play-card-9-filled": "\u{1007a}", + "play-card-a": "\u{10052}", + "play-card-a-filled": "\u{10079}", + "play-card-j": "\u{10051}", + "play-card-j-filled": "\u{10078}", + "play-card-k": "\u{10050}", + "play-card-k-filled": "\u{10077}", + "play-card-off": "\u{f17e}", + "play-card-q": "\u{1004f}", + "play-card-q-filled": "\u{10076}", + "play-card-star": "\u{1004e}", + "play-card-star-filled": "\u{10075}", + "play-football": "\u{fa67}", + "play-handball": "\u{fa68}", + "play-volleyball": "\u{fa69}", + "player-eject": "\u{efbc}", + "player-eject-filled": "\u{f68f}", + "player-pause": "\u{ed45}", + "player-pause-filled": "\u{f690}", + "player-play": "\u{ed46}", + "player-play-filled": "\u{f691}", + "player-record": "\u{ed47}", + "player-record-filled": "\u{f692}", + "player-skip-back": "\u{ed48}", + "player-skip-back-filled": "\u{f693}", + "player-skip-forward": "\u{ed49}", + "player-skip-forward-filled": "\u{f694}", + "player-stop": "\u{ed4a}", + "player-stop-filled": "\u{f695}", + "player-track-next": "\u{ed4b}", + "player-track-next-filled": "\u{f696}", + "player-track-prev": "\u{ed4c}", + "player-track-prev-filled": "\u{f697}", + "playlist": "\u{eec0}", + "playlist-add": "\u{f008}", + "playlist-off": "\u{f17f}", + "playlist-x": "\u{f009}", + "playstation-circle": "\u{f2ad}", + "playstation-square": "\u{f2ae}", + "playstation-triangle": "\u{f2af}", + "playstation-x": "\u{f2b0}", + "plug": "\u{ebd9}", + "plug-filled": "\u{f6b3}", + "plug-connected": "\u{f00a}", + "plug-connected-x": "\u{f0a0}", + "plug-off": "\u{f180}", + "plug-x": "\u{f0a1}", + "plus": "\u{eb0b}", + "plus-equal": "\u{f7ad}", + "plus-minus": "\u{f7ae}", + "png": "\u{f3ad}", + "podium": "\u{f1d8}", + "podium-off": "\u{f41b}", + "point": "\u{eb0c}", + "point-filled": "\u{f698}", + "point-off": "\u{f181}", + "pointer": "\u{f265}", + "pointer-bolt": "\u{f999}", + "pointer-cancel": "\u{f99a}", + "pointer-check": "\u{f99b}", + "pointer-code": "\u{f99c}", + "pointer-cog": "\u{f99d}", + "pointer-dollar": "\u{f99e}", + "pointer-down": "\u{f99f}", + "pointer-exclamation": "\u{f9a0}", + "pointer-filled": "\u{fb30}", + "pointer-heart": "\u{f9a1}", + "pointer-minus": "\u{f9a2}", + "pointer-off": "\u{f9a3}", + "pointer-pause": "\u{f9a4}", + "pointer-pin": "\u{f9a5}", + "pointer-plus": "\u{f9a6}", + "pointer-question": "\u{f9a7}", + "pointer-search": "\u{f9a8}", + "pointer-share": "\u{f9a9}", + "pointer-star": "\u{f9aa}", + "pointer-up": "\u{f9ab}", + "pointer-x": "\u{f9ac}", + "pokeball": "\u{eec1}", + "pokeball-off": "\u{f41c}", + "poker-chip": "\u{f515}", + "polaroid": "\u{eec2}", + "polaroid-filled": "\u{fa4b}", + "polygon": "\u{efd0}", + "polygon-off": "\u{f182}", + "poo": "\u{f258}", + "poo-filled": "\u{fec9}", + "pool": "\u{ed91}", + "pool-off": "\u{f41d}", + "power": "\u{eb0d}", + "pray": "\u{ecbf}", + "premium-rights": "\u{efbd}", + "prescription": "\u{ef99}", + "presentation": "\u{eb70}", + "presentation-analytics": "\u{eec3}", + "presentation-analytics-filled": "\u{ff5d}", + "presentation-filled": "\u{ff5c}", + "presentation-off": "\u{f183}", + "printer": "\u{eb0e}", + "printer-off": "\u{f184}", + "prism": "\u{fab1}", + "prism-light": "\u{fea6}", + "prism-off": "\u{faaf}", + "prism-plus": "\u{fab0}", + "prison": "\u{ef79}", + "progress": "\u{fa0d}", + "progress-alert": "\u{fa07}", + "progress-bolt": "\u{fa08}", + "progress-check": "\u{fa09}", + "progress-down": "\u{fa0a}", + "progress-help": "\u{fa0b}", + "progress-x": "\u{fa0c}", + "prompt": "\u{eb0f}", + "prong": "\u{fda1}", + "propeller": "\u{eec4}", + "propeller-off": "\u{f185}", + "protocol": "\u{fd81}", + "pumpkin-scary": "\u{f587}", + "puzzle": "\u{eb10}", + "puzzle-2": "\u{ef83}", + "puzzle-filled": "\u{f699}", + "puzzle-off": "\u{f186}", + "pyramid": "\u{eec5}", + "pyramid-off": "\u{f187}", + "pyramid-plus": "\u{fab2}", + "qrcode": "\u{eb11}", + "qrcode-off": "\u{f41e}", + "question-mark": "\u{ec9d}", + "quote": "\u{efbe}", + "quote-filled": "\u{1009c}", + "quote-off": "\u{f188}", + //"quotes": "\u{fb1e}", + "radar": "\u{f017}", + "radar-2": "\u{f016}", + //"radar-filled": "\u{fe0d}", + "radar-off": "\u{f41f}", + "radio": "\u{ef2d}", + "radio-off": "\u{f420}", + "radioactive": "\u{ecc0}", + "radioactive-filled": "\u{f760}", + "radioactive-off": "\u{f189}", + "radius-bottom-left": "\u{eec6}", + "radius-bottom-right": "\u{eec7}", + "radius-top-left": "\u{eec8}", + "radius-top-right": "\u{eec9}", + "rainbow": "\u{edbc}", + "rainbow-off": "\u{f18a}", + "rating-12-plus": "\u{f266}", + "rating-14-plus": "\u{f267}", + "rating-16-plus": "\u{f268}", + "rating-18-plus": "\u{f269}", + "rating-21-plus": "\u{f26a}", + "razor": "\u{f4b5}", + "razor-electric": "\u{f4b4}", + "receipt": "\u{edfd}", + "receipt-2": "\u{edfa}", + "receipt-bitcoin": "\u{fd66}", + "receipt-dollar": "\u{fd67}", + "receipt-dollar-filled": "\u{1017d}", + "receipt-euro": "\u{fd68}", + "receipt-euro-filled": "\u{1017c}", + "receipt-filled": "\u{ff06}", + "receipt-off": "\u{edfb}", + "receipt-pound": "\u{fd69}", + "receipt-pound-filled": "\u{1017b}", + "receipt-refund": "\u{edfc}", + "receipt-rupee": "\u{fd82}", + "receipt-rupee-filled": "\u{1017a}", + "receipt-tax": "\u{edbd}", + "receipt-yen": "\u{fd6a}", + "receipt-yen-filled": "\u{10179}", + "receipt-yuan": "\u{fd6b}", + "receipt-yuan-filled": "\u{10178}", + "recharging": "\u{eeca}", + "record-mail": "\u{eb12}", + "record-mail-off": "\u{f18b}", + "rectangle": "\u{ed37}", + "rectangle-filled": "\u{f69a}", + "rectangle-rounded-bottom": "\u{faed}", + "rectangle-rounded-top": "\u{faee}", + "rectangle-vertical": "\u{ed36}", + "rectangle-vertical-filled": "\u{f69b}", + "rectangular-prism": "\u{fab5}", + "rectangular-prism-off": "\u{fab3}", + "rectangular-prism-plus": "\u{fab4}", + "recycle": "\u{eb9b}", + "recycle-off": "\u{f18c}", + "refresh": "\u{eb13}", + "refresh-alert": "\u{ed57}", + "refresh-dot": "\u{efbf}", + "refresh-off": "\u{f18d}", + "regex": "\u{f31f}", + "regex-off": "\u{f421}", + "registered": "\u{eb14}", + "relation-many-to-many": "\u{ed7f}", + //"relation-many-to-many-filled": "\u{fe0c}", + "relation-one-to-many": "\u{ed80}", + //"relation-one-to-many-filled": "\u{fe0b}", + "relation-one-to-one": "\u{ed81}", + //"relation-one-to-one-filled": "\u{fe0a}", + "reload": "\u{f3ae}", + "reorder": "\u{fc15}", + "repeat": "\u{eb72}", + "repeat-off": "\u{f18e}", + "repeat-once": "\u{eb71}", + "replace": "\u{ebc7}", + "replace-filled": "\u{f69c}", + "replace-off": "\u{f422}", + "replace-user": "\u{100f0}", + "report": "\u{eece}", + "report-analytics": "\u{eecb}", + "report-medical": "\u{eecc}", + "report-money": "\u{eecd}", + "report-off": "\u{f18f}", + "report-search": "\u{ef84}", + "reserved-line": "\u{f9f6}", + "resize": "\u{eecf}", + "restore": "\u{fafd}", + "rewind-backward-10": "\u{faba}", + "rewind-backward-15": "\u{fabb}", + "rewind-backward-20": "\u{fabc}", + "rewind-backward-30": "\u{fabd}", + "rewind-backward-40": "\u{fabe}", + "rewind-backward-5": "\u{fabf}", + "rewind-backward-50": "\u{fac0}", + "rewind-backward-60": "\u{fac1}", + "rewind-forward-10": "\u{fac2}", + "rewind-forward-15": "\u{fac3}", + "rewind-forward-20": "\u{fac4}", + "rewind-forward-30": "\u{fac5}", + "rewind-forward-40": "\u{fac6}", + "rewind-forward-5": "\u{fac7}", + "rewind-forward-50": "\u{fac8}", + "rewind-forward-60": "\u{fac9}", + "ribbon-health": "\u{f58e}", + "rings": "\u{fa6a}", + "ripple": "\u{ed82}", + "ripple-off": "\u{f190}", + "road": "\u{f018}", + "road-off": "\u{f191}", + "road-sign": "\u{ecdd}", + "robot": "\u{f00b}", + "robot-face": "\u{fcbe}", + "robot-off": "\u{f192}", + "rocket": "\u{ec45}", + "rocket-off": "\u{f193}", + "roller-skating": "\u{efd1}", + "rollercoaster": "\u{f0a2}", + "rollercoaster-filled": "\u{100f7}", + "rollercoaster-off": "\u{f423}", + "rosette": "\u{f599}", + "rosette-discount": "\u{ee7c}", + "rosette-discount-check": "\u{f1f8}", + "rosette-discount-check-filled": "\u{f746}", + "rosette-discount-check-off": "\u{ff10}", + "rosette-discount-filled": "\u{ff05}", + "rosette-discount-off": "\u{f3e6}", + "rosette-filled": "\u{f69d}", + "rosette-number-0": "\u{f58f}", + "rosette-number-1": "\u{f590}", + "rosette-number-2": "\u{f591}", + "rosette-number-3": "\u{f592}", + "rosette-number-4": "\u{f593}", + "rosette-number-5": "\u{f594}", + "rosette-number-6": "\u{f595}", + "rosette-number-7": "\u{f596}", + "rosette-number-8": "\u{f597}", + "rosette-number-9": "\u{f598}", + "rotate": "\u{eb16}", + "rotate-2": "\u{ebb4}", + "rotate-360": "\u{ef85}", + "rotate-3d": "\u{f020}", + "rotate-clockwise": "\u{eb15}", + "rotate-clockwise-2": "\u{ebb5}", + "rotate-dot": "\u{efe5}", + "rotate-rectangle": "\u{ec15}", + "route": "\u{eb17}", + "route-2": "\u{f4b6}", + "route-alt-left": "\u{fca9}", + "route-alt-right": "\u{fcaa}", + "route-off": "\u{f194}", + "route-scan": "\u{fcbf}", + "route-square": "\u{fcac}", + "route-square-2": "\u{fcab}", + "route-x": "\u{fcae}", + "route-x-2": "\u{fcad}", + "router": "\u{eb18}", + "router-off": "\u{f424}", + "row-insert-bottom": "\u{eed0}", + "row-insert-top": "\u{eed1}", + "row-remove": "\u{fafe}", + "rss": "\u{eb19}", + "rubber-stamp": "\u{f5ab}", + "rubber-stamp-off": "\u{f5aa}", + "ruler": "\u{eb1a}", + "ruler-2": "\u{eed2}", + "ruler-2-off": "\u{f195}", + "ruler-3": "\u{f290}", + "ruler-measure": "\u{f291}", + "ruler-measure-2": "\u{ff0f}", + "ruler-off": "\u{f196}", + "run": "\u{ec82}", + "rv-truck": "\u{fcc0}", + "s-turn-down": "\u{f516}", + "s-turn-left": "\u{f517}", + "s-turn-right": "\u{f518}", + "s-turn-up": "\u{f519}", + "sailboat": "\u{ec83}", + "sailboat-2": "\u{f5f7}", + "sailboat-off": "\u{f425}", + "salad": "\u{f50a}", + "salad-filled": "\u{10007}", + "salt": "\u{ef16}", + "sandbox": "\u{fd6c}", + "satellite": "\u{eed3}", + "satellite-off": "\u{f197}", + "sausage": "\u{ef17}", + "scale": "\u{ebc2}", + "scale-off": "\u{f198}", + "scale-outline": "\u{ef53}", + "scale-outline-off": "\u{f199}", + "scan": "\u{ebc8}", + "scan-eye": "\u{f1ff}", + "scan-position": "\u{fdac}", + "schema": "\u{f200}", + "schema-off": "\u{f426}", + "school": "\u{ecf7}", + "school-bell": "\u{f64a}", + "school-off": "\u{f19a}", + "scissors": "\u{eb1b}", + "scissors-off": "\u{f19b}", + "scooter": "\u{ec6c}", + "scooter-electric": "\u{ecc1}", + "scoreboard": "\u{fa6b}", + "screen-share": "\u{ed18}", + "screen-share-off": "\u{ed17}", + "screenshot": "\u{f201}", + "scribble": "\u{f0a3}", + "scribble-off": "\u{f427}", + "script": "\u{f2da}", + "script-minus": "\u{f2d7}", + "script-plus": "\u{f2d8}", + "script-x": "\u{f2d9}", + "scuba-diving": "\u{fd4e}", + "scuba-diving-tank": "\u{fefa}", + "scuba-diving-tank-filled": "\u{ff04}", + "scuba-mask": "\u{eed4}", + "scuba-mask-off": "\u{f428}", + "sdk": "\u{f3af}", + "search": "\u{eb1c}", + "search-off": "\u{f19c}", + "section": "\u{eed5}", + //"section-filled": "\u{fe09}", + "section-sign": "\u{f019}", + "seeding": "\u{ed51}", + "seeding-filled": "\u{10006}", + "seeding-off": "\u{f19d}", + "seedling": "\u{ed51}", + "seedling-filled": "\u{10006}", + "seedling-off": "\u{f19d}", + "select": "\u{ec9e}", + "select-all": "\u{f9f7}", + "selector": "\u{eb1d}", + "send": "\u{eb1e}", + "send-2": "\u{fd5d}", + "send-off": "\u{f429}", + "seo": "\u{f26b}", + "separator": "\u{ebda}", + "separator-horizontal": "\u{ec79}", + "separator-vertical": "\u{ec7a}", + "server": "\u{eb1f}", + "server-2": "\u{f07c}", + "server-bolt": "\u{f320}", + "server-cog": "\u{f321}", + "server-off": "\u{f19e}", + "server-spark": "\u{ffaf}", + "servicemark": "\u{ec09}", + "settings": "\u{eb20}", + "settings-2": "\u{f5ac}", + "settings-automation": "\u{eed6}", + "settings-bolt": "\u{f9ad}", + "settings-cancel": "\u{f9ae}", + "settings-check": "\u{f9af}", + "settings-code": "\u{f9b0}", + "settings-cog": "\u{f9b1}", + "settings-dollar": "\u{f9b2}", + "settings-down": "\u{f9b3}", + "settings-exclamation": "\u{f9b4}", + "settings-filled": "\u{f69e}", + "settings-heart": "\u{f9b5}", + "settings-minus": "\u{f9b6}", + "settings-off": "\u{f19f}", + "settings-pause": "\u{f9b7}", + "settings-pin": "\u{f9b8}", + "settings-plus": "\u{f9b9}", + "settings-question": "\u{f9ba}", + "settings-search": "\u{f9bb}", + "settings-share": "\u{f9bc}", + "settings-spark": "\u{ffae}", + "settings-star": "\u{f9bd}", + "settings-up": "\u{f9be}", + "settings-x": "\u{f9bf}", + "shadow": "\u{eed8}", + "shadow-off": "\u{eed7}", + "shape": "\u{eb9c}", + "shape-2": "\u{eed9}", + "shape-3": "\u{eeda}", + "shape-off": "\u{f1a0}", + "share": "\u{eb21}", + "share-2": "\u{f799}", + "share-3": "\u{f7bd}", + "share-off": "\u{f1a1}", + "shareplay": "\u{fea5}", + "shi-jumping": "\u{fa6c}", + "shield": "\u{eb24}", + "shield-bolt": "\u{f9c0}", + "shield-cancel": "\u{f9c1}", + "shield-check": "\u{eb22}", + "shield-check-filled": "\u{f761}", + "shield-checkered": "\u{ef9a}", + "shield-checkered-filled": "\u{f762}", + "shield-chevron": "\u{ef9b}", + "shield-code": "\u{f9c2}", + "shield-cog": "\u{f9c3}", + "shield-dollar": "\u{f9c4}", + "shield-down": "\u{f9c5}", + "shield-exclamation": "\u{f9c6}", + "shield-filled": "\u{f69f}", + "shield-half": "\u{f358}", + "shield-half-filled": "\u{f357}", + "shield-heart": "\u{f9c7}", + "shield-lock": "\u{ed58}", + "shield-lock-filled": "\u{f763}", + "shield-minus": "\u{f9c8}", + "shield-off": "\u{ecf8}", + "shield-pause": "\u{f9c9}", + "shield-pin": "\u{f9ca}", + "shield-plus": "\u{f9cb}", + "shield-question": "\u{f9cc}", + "shield-search": "\u{f9cd}", + "shield-share": "\u{f9ce}", + "shield-star": "\u{f9cf}", + "shield-up": "\u{f9d0}", + "shield-x": "\u{eb23}", + "ship": "\u{ec84}", + "ship-off": "\u{f42a}", + "shirt": "\u{ec0a}", + "shirt-filled": "\u{f6a0}", + "shirt-off": "\u{f1a2}", + "shirt-sport": "\u{f26c}", + "shoe": "\u{efd2}", + "shoe-off": "\u{f1a4}", + "shopping-bag": "\u{f5f8}", + "shopping-bag-check": "\u{fc16}", + "shopping-bag-discount": "\u{fc17}", + "shopping-bag-edit": "\u{fc18}", + "shopping-bag-exclamation": "\u{fc19}", + "shopping-bag-heart": "\u{fda2}", + "shopping-bag-minus": "\u{fc1a}", + "shopping-bag-plus": "\u{fc1b}", + "shopping-bag-search": "\u{fc1c}", + "shopping-bag-x": "\u{fc1d}", + "shopping-cart": "\u{eb25}", + "shopping-cart-bolt": "\u{fb57}", + "shopping-cart-cancel": "\u{fb58}", + "shopping-cart-check": "\u{fb59}", + "shopping-cart-code": "\u{fb5a}", + "shopping-cart-cog": "\u{fb5b}", + "shopping-cart-copy": "\u{fb5c}", + "shopping-cart-discount": "\u{fb5d}", + "shopping-cart-dollar": "\u{fb5e}", + "shopping-cart-down": "\u{fb5f}", + "shopping-cart-exclamation": "\u{fb60}", + "shopping-cart-filled": "\u{fc3f}", + "shopping-cart-heart": "\u{fb61}", + "shopping-cart-minus": "\u{fb62}", + "shopping-cart-off": "\u{eedc}", + "shopping-cart-pause": "\u{fb63}", + "shopping-cart-pin": "\u{fb64}", + "shopping-cart-plus": "\u{fb65}", + "shopping-cart-question": "\u{fb66}", + "shopping-cart-search": "\u{fb67}", + "shopping-cart-share": "\u{fb68}", + "shopping-cart-star": "\u{fb69}", + "shopping-cart-up": "\u{fb6a}", + "shopping-cart-x": "\u{fb6b}", + "shovel": "\u{f1d9}", + "shovel-pitchforks": "\u{fd3a}", + "shredder": "\u{eedf}", + "sign-left": "\u{f06b}", + "sign-left-filled": "\u{f6a1}", + "sign-right": "\u{f06c}", + "sign-right-filled": "\u{f6a2}", + "signal-2g": "\u{f79a}", + "signal-3g": "\u{f1ee}", + "signal-4g": "\u{f1ef}", + "signal-4g-plus": "\u{f259}", + "signal-5g": "\u{f1f0}", + "signal-6g": "\u{f9f8}", + "signal-e": "\u{f9f9}", + "signal-g": "\u{f9fa}", + "signal-h": "\u{f9fc}", + "signal-h-plus": "\u{f9fb}", + "signal-lte": "\u{f9fd}", + "signature": "\u{eee0}", + "signature-off": "\u{f1a5}", + "sitemap": "\u{eb9d}", + "sitemap-filled": "\u{1006b}", + "sitemap-off": "\u{f1a6}", + "skateboard": "\u{ecc2}", + "skateboard-off": "\u{f42b}", + "skateboarding": "\u{faca}", + "skew-x": "\u{fd3b}", + "skew-y": "\u{fd3c}", + "ski-jumping": "\u{fa6c}", + "skull": "\u{f292}", + "slash": "\u{f4f9}", + "slashes": "\u{f588}", + "sleigh": "\u{ef9c}", + "slice": "\u{ebdb}", + "slideshow": "\u{ebc9}", + "smart-home": "\u{ecde}", + "smart-home-off": "\u{f1a7}", + "smoking": "\u{ecc4}", + "smoking-no": "\u{ecc3}", + "snowboarding": "\u{fd4f}", + "snowflake": "\u{ec0b}", + "snowflake-off": "\u{f1a8}", + "snowman": "\u{f26d}", + "soccer-field": "\u{ed92}", + "social": "\u{ebec}", + "social-off": "\u{f1a9}", + "sock": "\u{eee1}", + "sofa": "\u{efaf}", + "sofa-off": "\u{f42c}", + "solar-electricity": "\u{fcc1}", + "solar-panel": "\u{f7bf}", + "solar-panel-2": "\u{f7be}", + "sort-0-9": "\u{f54d}", + "sort-9-0": "\u{f54e}", + "sort-a-z": "\u{f54f}", + "sort-ascending": "\u{eb26}", + "sort-ascending-2": "\u{eee2}", + "sort-ascending-2-filled": "\u{ff5b}", + "sort-ascending-letters": "\u{ef18}", + "sort-ascending-numbers": "\u{ef19}", + "sort-ascending-shapes": "\u{fd94}", + "sort-ascending-shapes-filled": "\u{ff5a}", + "sort-ascending-small-big": "\u{fd95}", + "sort-deacending-small-big": "\u{fd96}", + "sort-descending": "\u{eb27}", + "sort-descending-2": "\u{eee3}", + "sort-descending-2-filled": "\u{ff59}", + "sort-descending-letters": "\u{ef1a}", + "sort-descending-numbers": "\u{ef1b}", + "sort-descending-shapes": "\u{fd97}", + "sort-descending-shapes-filled": "\u{ff58}", + "sort-descending-small-big": "\u{fd96}", + "sort-z-a": "\u{f550}", + "sos": "\u{f24a}", + "soup": "\u{ef2e}", + //"soup-filled": "\u{fe08}", + "soup-off": "\u{f42d}", + "source-code": "\u{f4a2}", + "space": "\u{ec0c}", + "space-off": "\u{f1aa}", + "spaces": "\u{fea4}", + "spacing-horizontal": "\u{ef54}", + "spacing-vertical": "\u{ef55}", + "spade": "\u{effa}", + "spade-filled": "\u{f6a3}", + "sparkles": "\u{f6d7}", + "speakerphone": "\u{ed61}", + "speedboat": "\u{ed93}", + "speedboat-filled": "\u{100f6}", + "sphere": "\u{fab8}", + "sphere-off": "\u{fab6}", + "sphere-plus": "\u{fab7}", + "spider": "\u{f293}", + "spider-filled": "\u{10109}", + "spiral": "\u{f294}", + "spiral-off": "\u{f42e}", + "sport-billard": "\u{eee4}", + "spray": "\u{f50b}", + "spy": "\u{f227}", + "spy-off": "\u{f42f}", + "sql": "\u{f7c0}", + "square": "\u{eb2c}", + "square-0": "\u{eee5}", + "square-1": "\u{eee6}", + "square-2": "\u{eee7}", + "square-3": "\u{eee8}", + "square-4": "\u{eee9}", + "square-5": "\u{eeea}", + "square-6": "\u{eeeb}", + "square-7": "\u{eeec}", + "square-8": "\u{eeed}", + "square-9": "\u{eeee}", + "square-arrow-down": "\u{f4b7}", + "square-arrow-down-filled": "\u{fb31}", + "square-arrow-left": "\u{f4b8}", + "square-arrow-left-filled": "\u{fb32}", + "square-arrow-right": "\u{f4b9}", + "square-arrow-right-filled": "\u{fb33}", + "square-arrow-up": "\u{f4ba}", + "square-arrow-up-filled": "\u{fb34}", + "square-asterisk": "\u{f01a}", + "square-asterisk-filled": "\u{fb35}", + "square-check": "\u{eb28}", + "square-check-filled": "\u{f76d}", + "square-chevron-down": "\u{f627}", + "square-chevron-down-filled": "\u{fb36}", + "square-chevron-left": "\u{f628}", + "square-chevron-left-filled": "\u{fb37}", + "square-chevron-right": "\u{f629}", + "square-chevron-right-filled": "\u{fb38}", + "square-chevron-up": "\u{f62a}", + "square-chevron-up-filled": "\u{fb39}", + "square-chevrons-down": "\u{f64b}", + "square-chevrons-down-filled": "\u{fb3a}", + "square-chevrons-left": "\u{f64c}", + "square-chevrons-left-filled": "\u{fb3b}", + "square-chevrons-right": "\u{f64d}", + "square-chevrons-right-filled": "\u{fb3c}", + "square-chevrons-up": "\u{f64e}", + "square-chevrons-up-filled": "\u{fb3d}", + "square-dashed": "\u{100bb}", + "square-dot": "\u{ed59}", + "square-dot-filled": "\u{fb3e}", + "square-f0": "\u{f526}", + "square-f0-filled": "\u{f76e}", + "square-f1": "\u{f527}", + "square-f1-filled": "\u{f76f}", + "square-f2": "\u{f528}", + "square-f2-filled": "\u{f770}", + "square-f3": "\u{f529}", + "square-f3-filled": "\u{f771}", + "square-f4": "\u{f52a}", + "square-f4-filled": "\u{f772}", + "square-f5": "\u{f52b}", + "square-f5-filled": "\u{f773}", + "square-f6": "\u{f52c}", + "square-f6-filled": "\u{f774}", + "square-f7": "\u{f52d}", + "square-f7-filled": "\u{f775}", + "square-f8": "\u{f52e}", + "square-f8-filled": "\u{f776}", + "square-f9": "\u{f52f}", + "square-f9-filled": "\u{f777}", + "square-filled": "\u{fc40}", + "square-forbid": "\u{ed5b}", + "square-forbid-2": "\u{ed5a}", + "square-half": "\u{effb}", + "square-key": "\u{f638}", + "square-letter-a": "\u{f47c}", + //"square-letter-a-filled": "\u{fe07}", + "square-letter-b": "\u{f47d}", + //"square-letter-b-filled": "\u{fe06}", + "square-letter-c": "\u{f47e}", + //"square-letter-c-filled": "\u{fe05}", + "square-letter-d": "\u{f47f}", + //"square-letter-d-filled": "\u{fe04}", + "square-letter-e": "\u{f480}", + //"square-letter-e-filled": "\u{fe03}", + "square-letter-f": "\u{f481}", + //"square-letter-f-filled": "\u{fe02}", + "square-letter-g": "\u{f482}", + //"square-letter-g-filled": "\u{fe01}", + "square-letter-h": "\u{f483}", + //"square-letter-h-filled": "\u{fe00}", + "square-letter-i": "\u{f484}", + "square-letter-i-filled": "\u{fdff}", + "square-letter-j": "\u{f485}", + "square-letter-j-filled": "\u{fdfe}", + "square-letter-k": "\u{f486}", + "square-letter-k-filled": "\u{fdfd}", + "square-letter-l": "\u{f487}", + "square-letter-l-filled": "\u{fdfc}", + "square-letter-m": "\u{f488}", + "square-letter-m-filled": "\u{fdfb}", + "square-letter-n": "\u{f489}", + "square-letter-n-filled": "\u{fdfa}", + "square-letter-o": "\u{f48a}", + "square-letter-o-filled": "\u{fdf9}", + "square-letter-p": "\u{f48b}", + "square-letter-p-filled": "\u{fdf8}", + "square-letter-q": "\u{f48c}", + "square-letter-q-filled": "\u{fdf7}", + "square-letter-r": "\u{f48d}", + "square-letter-r-filled": "\u{fdf6}", + "square-letter-s": "\u{f48e}", + "square-letter-s-filled": "\u{fdf5}", + "square-letter-t": "\u{f48f}", + "square-letter-t-filled": "\u{fdf4}", + "square-letter-u": "\u{f490}", + "square-letter-u-filled": "\u{fdf3}", + "square-letter-v": "\u{f4bb}", + "square-letter-v-filled": "\u{fdf2}", + "square-letter-w": "\u{f491}", + "square-letter-w-filled": "\u{fdf1}", + "square-letter-x": "\u{f4bc}", + "square-letter-x-filled": "\u{fdf0}", + "square-letter-y": "\u{f492}", + "square-letter-y-filled": "\u{fdef}", + "square-letter-z": "\u{f493}", + "square-letter-z-filled": "\u{fdee}", + "square-minus": "\u{eb29}", + "square-minus-filled": "\u{fb3f}", + "square-number-0": "\u{eee5}", + "square-number-0-filled": "\u{f764}", + "square-number-1": "\u{eee6}", + "square-number-1-filled": "\u{f765}", + "square-number-2": "\u{eee7}", + "square-number-2-filled": "\u{f7fa}", + "square-number-3": "\u{eee8}", + "square-number-3-filled": "\u{f766}", + "square-number-4": "\u{eee9}", + "square-number-4-filled": "\u{f767}", + "square-number-5": "\u{eeea}", + "square-number-5-filled": "\u{f768}", + "square-number-6": "\u{eeeb}", + "square-number-6-filled": "\u{f769}", + "square-number-7": "\u{eeec}", + "square-number-7-filled": "\u{f76a}", + "square-number-8": "\u{eeed}", + "square-number-8-filled": "\u{f76b}", + "square-number-9": "\u{eeee}", + "square-number-9-filled": "\u{f76c}", + "square-off": "\u{eeef}", + "square-percentage": "\u{fd83}", + "square-plus": "\u{eb2a}", + "square-plus-2": "\u{fc96}", + "square-root": "\u{eef1}", + "square-root-2": "\u{eef0}", + "square-rotated": "\u{ecdf}", + "square-rotated-filled": "\u{f6a4}", + "square-rotated-forbid": "\u{f01c}", + "square-rotated-forbid-2": "\u{f01b}", + "square-rotated-off": "\u{eef2}", + "square-rounded": "\u{f59a}", + "square-rounded-arrow-down": "\u{f639}", + "square-rounded-arrow-down-filled": "\u{f6db}", + "square-rounded-arrow-left": "\u{f63a}", + "square-rounded-arrow-left-filled": "\u{f6dc}", + "square-rounded-arrow-right": "\u{f63b}", + "square-rounded-arrow-right-filled": "\u{f6dd}", + "square-rounded-arrow-up": "\u{f63c}", + "square-rounded-arrow-up-filled": "\u{f6de}", + "square-rounded-check": "\u{f63d}", + "square-rounded-check-filled": "\u{f6df}", + "square-rounded-chevron-down": "\u{f62b}", + "square-rounded-chevron-down-filled": "\u{f6e0}", + "square-rounded-chevron-left": "\u{f62c}", + "square-rounded-chevron-left-filled": "\u{f6e1}", + "square-rounded-chevron-right": "\u{f62d}", + "square-rounded-chevron-right-filled": "\u{f6e2}", + "square-rounded-chevron-up": "\u{f62e}", + "square-rounded-chevron-up-filled": "\u{f6e3}", + "square-rounded-chevrons-down": "\u{f64f}", + "square-rounded-chevrons-down-filled": "\u{f6e4}", + "square-rounded-chevrons-left": "\u{f650}", + "square-rounded-chevrons-left-filled": "\u{f6e5}", + "square-rounded-chevrons-right": "\u{f651}", + "square-rounded-chevrons-right-filled": "\u{f6e6}", + "square-rounded-chevrons-up": "\u{f652}", + "square-rounded-chevrons-up-filled": "\u{f6e7}", + "square-rounded-filled": "\u{f6a5}", + "square-rounded-letter-a": "\u{f5ae}", + "square-rounded-letter-a-filled": "\u{fded}", + "square-rounded-letter-b": "\u{f5af}", + "square-rounded-letter-b-filled": "\u{fdec}", + "square-rounded-letter-c": "\u{f5b0}", + "square-rounded-letter-c-filled": "\u{fdeb}", + "square-rounded-letter-d": "\u{f5b1}", + "square-rounded-letter-d-filled": "\u{fdea}", + "square-rounded-letter-e": "\u{f5b2}", + "square-rounded-letter-e-filled": "\u{fde9}", + "square-rounded-letter-f": "\u{f5b3}", + "square-rounded-letter-f-filled": "\u{fde8}", + "square-rounded-letter-g": "\u{f5b4}", + "square-rounded-letter-g-filled": "\u{fde7}", + "square-rounded-letter-h": "\u{f5b5}", + "square-rounded-letter-h-filled": "\u{fde6}", + "square-rounded-letter-i": "\u{f5b6}", + "square-rounded-letter-i-filled": "\u{fde5}", + "square-rounded-letter-j": "\u{f5b7}", + "square-rounded-letter-j-filled": "\u{fde4}", + "square-rounded-letter-k": "\u{f5b8}", + "square-rounded-letter-k-filled": "\u{fde3}", + "square-rounded-letter-l": "\u{f5b9}", + "square-rounded-letter-l-filled": "\u{fde2}", + "square-rounded-letter-m": "\u{f5ba}", + "square-rounded-letter-m-filled": "\u{fde1}", + "square-rounded-letter-n": "\u{f5bb}", + "square-rounded-letter-n-filled": "\u{fde0}", + "square-rounded-letter-o": "\u{f5bc}", + "square-rounded-letter-o-filled": "\u{fddf}", + "square-rounded-letter-p": "\u{f5bd}", + "square-rounded-letter-p-filled": "\u{fdde}", + "square-rounded-letter-q": "\u{f5be}", + "square-rounded-letter-q-filled": "\u{fddd}", + "square-rounded-letter-r": "\u{f5bf}", + "square-rounded-letter-r-filled": "\u{fddc}", + "square-rounded-letter-s": "\u{f5c0}", + "square-rounded-letter-s-filled": "\u{fddb}", + "square-rounded-letter-t": "\u{f5c1}", + "square-rounded-letter-t-filled": "\u{fdda}", + "square-rounded-letter-u": "\u{f5c2}", + "square-rounded-letter-u-filled": "\u{fdd9}", + "square-rounded-letter-v": "\u{f5c3}", + "square-rounded-letter-v-filled": "\u{fdd8}", + "square-rounded-letter-w": "\u{f5c4}", + "square-rounded-letter-w-filled": "\u{fdd7}", + "square-rounded-letter-x": "\u{f5c5}", + "square-rounded-letter-x-filled": "\u{fdd6}", + "square-rounded-letter-y": "\u{f5c6}", + "square-rounded-letter-y-filled": "\u{fdd5}", + "square-rounded-letter-z": "\u{f5c7}", + "square-rounded-letter-z-filled": "\u{fdd4}", + "square-rounded-minus": "\u{f63e}", + "square-rounded-minus-2": "\u{fc97}", + "square-rounded-minus-filled": "\u{fb40}", + "square-rounded-number-0": "\u{f5c8}", + "square-rounded-number-0-filled": "\u{f778}", + "square-rounded-number-1": "\u{f5c9}", + "square-rounded-number-1-filled": "\u{f779}", + "square-rounded-number-2": "\u{f5ca}", + "square-rounded-number-2-filled": "\u{f77a}", + "square-rounded-number-3": "\u{f5cb}", + "square-rounded-number-3-filled": "\u{f77b}", + "square-rounded-number-4": "\u{f5cc}", + "square-rounded-number-4-filled": "\u{f77c}", + "square-rounded-number-5": "\u{f5cd}", + "square-rounded-number-5-filled": "\u{f77d}", + "square-rounded-number-6": "\u{f5ce}", + "square-rounded-number-6-filled": "\u{f77e}", + "square-rounded-number-7": "\u{f5cf}", + "square-rounded-number-7-filled": "\u{f77f}", + "square-rounded-number-8": "\u{f5d0}", + "square-rounded-number-8-filled": "\u{f780}", + "square-rounded-number-9": "\u{f5d1}", + "square-rounded-number-9-filled": "\u{f781}", + "square-rounded-percentage": "\u{fd84}", + "square-rounded-plus": "\u{f63f}", + "square-rounded-plus-2": "\u{fc98}", + "square-rounded-plus-filled": "\u{f6e8}", + "square-rounded-x": "\u{f640}", + "square-rounded-x-filled": "\u{f6e9}", + "square-toggle": "\u{eef4}", + "square-toggle-horizontal": "\u{eef3}", + "square-x": "\u{eb2b}", + "square-x-filled": "\u{fb41}", + "squares": "\u{eef6}", + "squares-diagonal": "\u{eef5}", + "squares-filled": "\u{fe9f}", + "squares-selected": "\u{fea3}", + "stack": "\u{eb2d}", + "stack-2": "\u{eef7}", + "stack-2-filled": "\u{fdd3}", + "stack-3": "\u{ef9d}", + "stack-3-filled": "\u{fdd2}", + "stack-back": "\u{fd26}", + "stack-backward": "\u{fd27}", + "stack-filled": "\u{fdd1}", + "stack-forward": "\u{fd28}", + "stack-front": "\u{fd29}", + "stack-middle": "\u{fd2a}", + "stack-pop": "\u{f234}", + "stack-push": "\u{f235}", + "stairs": "\u{eca6}", + "stairs-down": "\u{eca4}", + "stairs-up": "\u{eca5}", + "star": "\u{eb2e}", + "star-filled": "\u{f6a6}", + "star-half": "\u{ed19}", + "star-half-filled": "\u{f6a7}", + "star-off": "\u{ed62}", + "stars": "\u{ed38}", + "stars-filled": "\u{f6a8}", + "stars-off": "\u{f430}", + "status-change": "\u{f3b0}", + "steam": "\u{f24b}", + "steering-wheel": "\u{ec7b}", + "steering-wheel-filled": "\u{ff03}", + "steering-wheel-off": "\u{f431}", + "step-into": "\u{ece0}", + "step-out": "\u{ece1}", + "stereo-glasses": "\u{f4cb}", + "stethoscope": "\u{edbe}", + "stethoscope-off": "\u{f432}", + "sticker": "\u{eb2f}", + "sticker-2": "\u{fd3d}", + "stopwatch": "\u{ff9b}", + "storm": "\u{f24c}", + "storm-off": "\u{f433}", + "stretching": "\u{f2db}", + "stretching-2": "\u{fa6d}", + "strikethrough": "\u{eb9e}", + "submarine": "\u{ed94}", + "subscript": "\u{eb9f}", + "subtask": "\u{ec9f}", + "sum": "\u{eb73}", + "sum-off": "\u{f1ab}", + "sun": "\u{eb30}", + "sun-electricity": "\u{fcc2}", + "sun-filled": "\u{f6a9}", + "sun-high": "\u{f236}", + "sun-high-filled": "\u{10108}", + "sun-low": "\u{f237}", + "sun-low-filled": "\u{10107}", + "sun-moon": "\u{f4a3}", + "sun-off": "\u{ed63}", + "sun-wind": "\u{f238}", + "sunglasses": "\u{f239}", + "sunglasses-filled": "\u{fec8}", + "sunrise": "\u{ef1c}", + "sunrise-filled": "\u{10106}", + "sunset": "\u{ec31}", + "sunset-2": "\u{f23a}", + "sunset-2-filled": "\u{10105}", + "sunset-filled": "\u{10104}", + "superscript": "\u{eba0}", + "svg": "\u{f25a}", + "swimming": "\u{ec92}", + "swipe": "\u{f551}", + "swipe-down": "\u{fd5e}", + "swipe-down-filled": "\u{ff57}", + "swipe-left": "\u{fd5f}", + "swipe-left-filled": "\u{ff56}", + "swipe-right": "\u{fd60}", + "swipe-right-filled": "\u{ff55}", + "swipe-up": "\u{fd61}", + "swipe-up-filled": "\u{ff54}", + "switch": "\u{eb33}", + "switch-2": "\u{edbf}", + "switch-3": "\u{edc0}", + "switch-horizontal": "\u{eb31}", + "switch-vertical": "\u{eb32}", + "sword": "\u{f030}", + "sword-off": "\u{f434}", + "swords": "\u{f132}", + "table": "\u{eba1}", + "table-alias": "\u{f25b}", + "table-column": "\u{faff}", + "table-dashed": "\u{100ba}", + "table-down": "\u{fa1c}", + "table-export": "\u{eef8}", + "table-filled": "\u{f782}", + "table-heart": "\u{fa1d}", + "table-import": "\u{eef9}", + "table-minus": "\u{fa1e}", + "table-off": "\u{eefa}", + "table-options": "\u{f25c}", + "table-plus": "\u{fa1f}", + "table-row": "\u{fb00}", + "table-share": "\u{fa20}", + "table-shortcut": "\u{f25d}", + "table-spark": "\u{ffad}", + "tag": "\u{10096}", + "tag-filled": "\u{ff02}", + "tag-minus": "\u{eb34}", + "tag-off": "\u{efc0}", + "tag-plus": "\u{10097}", + "tag-starred": "\u{fc99}", + "tags": "\u{ef86}", + "tags-filled": "\u{ff01}", + "tags-off": "\u{efc1}", + "tallymark-1": "\u{ec46}", + "tallymark-2": "\u{ec47}", + "tallymark-3": "\u{ec48}", + "tallymark-4": "\u{ec49}", + "tallymarks": "\u{ec4a}", + "tank": "\u{ed95}", + "target": "\u{eb35}", + "target-arrow": "\u{f51a}", + "target-off": "\u{f1ad}", + "tax": "\u{feee}", + "tax-euro": "\u{fef0}", + "tax-pound": "\u{feef}", + "teapot": "\u{f552}", + "telescope": "\u{f07d}", + "telescope-off": "\u{f1ae}", + "temperature": "\u{eb38}", + "temperature-celsius": "\u{eb36}", + "temperature-fahrenheit": "\u{eb37}", + "temperature-minus": "\u{ebed}", + "temperature-minus-filled": "\u{10103}", + "temperature-off": "\u{f1af}", + "temperature-plus": "\u{ebee}", + "temperature-plus-filled": "\u{10102}", + "temperature-snow": "\u{fda3}", + "temperature-sun": "\u{fda4}", + "template": "\u{eb39}", + "template-filled": "\u{10177}", + "template-off": "\u{f1b0}", + "tent": "\u{eefb}", + "tent-off": "\u{f435}", + "terminal": "\u{ebdc}", + "terminal-2": "\u{ebef}", + "test-pipe": "\u{eb3a}", + "test-pipe-2": "\u{f0a4}", + "test-pipe-2-filled": "\u{ff53}", + "test-pipe-off": "\u{f1b1}", + "tex": "\u{f4e0}", + "text-caption": "\u{f4a4}", + "text-color": "\u{f2dc}", + "text-decrease": "\u{f202}", + "text-direction-ltr": "\u{eefc}", + "text-direction-rtl": "\u{eefd}", + "text-grammar": "\u{fd6d}", + "text-increase": "\u{f203}", + "text-orientation": "\u{f2a4}", + "text-plus": "\u{f2a5}", + "text-recognition": "\u{f204}", + "text-resize": "\u{ef87}", + "text-scan-2": "\u{fcc3}", + "text-size": "\u{f2b1}", + "text-spellcheck": "\u{f2a6}", + "text-wrap": "\u{ebdd}", + "text-wrap-column": "\u{feb2}", + "text-wrap-disabled": "\u{eca7}", + "texture": "\u{f51b}", + "theater": "\u{f79b}", + "thermometer": "\u{ef67}", + "thumb-down": "\u{eb3b}", + "thumb-down-filled": "\u{f6aa}", + "thumb-down-off": "\u{f436}", + "thumb-up": "\u{eb3c}", + "thumb-up-filled": "\u{f6ab}", + "thumb-up-off": "\u{f437}", + "tic-tac": "\u{f51c}", + "ticket": "\u{eb3d}", + "ticket-off": "\u{f1b2}", + "tie": "\u{f07e}", + "tilde": "\u{f4a5}", + "tilt-shift": "\u{eefe}", + "tilt-shift-filled": "\u{fec7}", + "tilt-shift-off": "\u{f1b3}", + "time-duration-0": "\u{fad4}", + "time-duration-10": "\u{fad5}", + "time-duration-15": "\u{fad6}", + "time-duration-30": "\u{fad7}", + "time-duration-45": "\u{fad8}", + "time-duration-5": "\u{fad9}", + "time-duration-60": "\u{fada}", + "time-duration-90": "\u{fadb}", + "time-duration-off": "\u{fadc}", + "timeline": "\u{f031}", + "timeline-event": "\u{f553}", + "timeline-event-exclamation": "\u{f662}", + "timeline-event-filled": "\u{fd18}", + "timeline-event-minus": "\u{f663}", + "timeline-event-plus": "\u{f664}", + "timeline-event-text": "\u{f665}", + "timeline-event-x": "\u{f666}", + "timezone": "\u{feed}", + "tip-jar": "\u{feea}", + "tip-jar-euro": "\u{feec}", + "tip-jar-pound": "\u{feeb}", + "tir": "\u{ebf0}", + "toggle-left": "\u{eb3e}", + "toggle-left-filled": "\u{fec0}", + "toggle-right": "\u{eb3f}", + "toggle-right-filled": "\u{febf}", + "toilet-paper": "\u{efd3}", + "toilet-paper-off": "\u{f1b4}", + "toml": "\u{fa5d}", + "tool": "\u{eb40}", + "tools": "\u{ebca}", + "tools-kitchen": "\u{ed64}", + "tools-kitchen-2": "\u{eeff}", + "tools-kitchen-2-off": "\u{f1b5}", + "tools-kitchen-3": "\u{fd2b}", + "tools-kitchen-off": "\u{f1b6}", + "tools-off": "\u{f1b7}", + "tooltip": "\u{f2dd}", + "topology-bus": "\u{f5d9}", + "topology-complex": "\u{f5da}", + "topology-full": "\u{f5dc}", + "topology-full-hierarchy": "\u{f5db}", + "topology-ring": "\u{f5df}", + "topology-ring-2": "\u{f5dd}", + "topology-ring-3": "\u{f5de}", + "topology-star": "\u{f5e5}", + "topology-star-2": "\u{f5e0}", + "topology-star-3": "\u{f5e1}", + "topology-star-ring": "\u{f5e4}", + "topology-star-ring-2": "\u{f5e2}", + "topology-star-ring-3": "\u{f5e3}", + "torii": "\u{f59b}", + "tornado": "\u{ece2}", + "tournament": "\u{ecd0}", + "tower": "\u{f2cb}", + "tower-off": "\u{f2ca}", + "track": "\u{ef00}", + "tractor": "\u{ec0d}", + "trademark": "\u{ec0e}", + "traffic-cone": "\u{ec0f}", + "traffic-cone-off": "\u{f1b8}", + "traffic-lights": "\u{ed39}", + "traffic-lights-off": "\u{f1b9}", + "train": "\u{ed96}", + "train-filled": "\u{100f5}", + "transaction-bitcoin": "\u{fd6e}", + "transaction-dollar": "\u{fd6f}", + "transaction-euro": "\u{fd70}", + "transaction-pound": "\u{fd71}", + "transaction-rupee": "\u{fd85}", + "transaction-yen": "\u{fd72}", + "transaction-yuan": "\u{fd73}", + "transfer": "\u{fc1f}", + "transfer-in": "\u{ef2f}", + "transfer-out": "\u{ef30}", + "transfer-vertical": "\u{fc1e}", + "transform": "\u{f38e}", + "transform-filled": "\u{f6ac}", + "transform-point": "\u{fda9}", + "transform-point-bottom-left": "\u{fda5}", + "transform-point-bottom-right": "\u{fda6}", + "transform-point-top-left": "\u{fda7}", + "transform-point-top-right": "\u{fda8}", + "transition-bottom": "\u{f2b2}", + "transition-bottom-filled": "\u{fdd0}", + "transition-left": "\u{f2b3}", + "transition-left-filled": "\u{fdcf}", + "transition-right": "\u{f2b4}", + "transition-right-filled": "\u{fdce}", + "transition-top": "\u{f2b5}", + "transition-top-filled": "\u{fdcd}", + "trash": "\u{eb41}", + "trash-filled": "\u{f783}", + "trash-off": "\u{ed65}", + "trash-x": "\u{ef88}", + "trash-x-filled": "\u{f784}", + "treadmill": "\u{fa6e}", + "tree": "\u{ef01}", + "trees": "\u{ec10}", + "trekking": "\u{f5ad}", + "trending-down": "\u{eb42}", + "trending-down-2": "\u{edc1}", + "trending-down-3": "\u{edc2}", + "trending-up": "\u{eb43}", + "trending-up-2": "\u{edc3}", + "trending-up-3": "\u{edc4}", + "triangle": "\u{eb44}", + "triangle-filled": "\u{f6ad}", + "triangle-inverted": "\u{f01d}", + "triangle-inverted-filled": "\u{f6ae}", + "triangle-minus": "\u{fc9b}", + "triangle-minus-2": "\u{fc9a}", + "triangle-off": "\u{ef02}", + "triangle-plus": "\u{fc9d}", + "triangle-plus-2": "\u{fc9c}", + "triangle-square-circle": "\u{ece8}", + "triangle-square-circle-filled": "\u{fb42}", + "triangles": "\u{f0a5}", + "trident": "\u{ecc5}", + "trolley": "\u{f4cc}", + "trolley-filled": "\u{100f4}", + "trophy": "\u{eb45}", + "trophy-filled": "\u{f6af}", + "trophy-off": "\u{f438}", + "trowel": "\u{f368}", + "truck": "\u{ebc4}", + "truck-delivery": "\u{ec4b}", + "truck-filled": "\u{100f3}", + "truck-loading": "\u{f1da}", + "truck-off": "\u{ef03}", + "truck-return": "\u{ec4c}", + "txt": "\u{f3b1}", + "typeface": "\u{fdab}", + "typography": "\u{ebc5}", + "typography-off": "\u{f1ba}", + "u-turn-left": "\u{fea2}", + "u-turn-right": "\u{fea1}", + "ufo": "\u{f26f}", + "ufo-filled": "\u{10165}", + "ufo-off": "\u{f26e}", + "uhd": "\u{100aa}", + "umbrella": "\u{ebf1}", + "umbrella-2": "\u{ff0e}", + "umbrella-closed": "\u{ff0c}", + "umbrella-closed-2": "\u{ff0d}", + "umbrella-filled": "\u{f6b0}", + "umbrella-off": "\u{f1bb}", + "underline": "\u{eba2}", + "universe": "\u{fcc4}", + "unlink": "\u{eb46}", + "upload": "\u{eb47}", + "urgent": "\u{eb48}", + "usb": "\u{f00c}", + "user": "\u{eb4d}", + "user-bitcoin": "\u{ff30}", + "user-bolt": "\u{f9d1}", + "user-cancel": "\u{f9d2}", + "user-check": "\u{eb49}", + "user-circle": "\u{ef68}", + "user-code": "\u{f9d3}", + "user-cog": "\u{f9d4}", + "user-dollar": "\u{f9d5}", + "user-down": "\u{f9d6}", + "user-edit": "\u{f7cc}", + "user-exclamation": "\u{ec12}", + "user-filled": "\u{fd19}", + "user-heart": "\u{f7cd}", + "user-hexagon": "\u{fc4e}", + "user-minus": "\u{eb4a}", + "user-off": "\u{ecf9}", + "user-pause": "\u{f9d7}", + "user-pentagon": "\u{fc4f}", + "user-pin": "\u{f7ce}", + "user-plus": "\u{eb4b}", + "user-question": "\u{f7cf}", + "user-scan": "\u{fcaf}", + "user-screen": "\u{fea0}", + "user-search": "\u{ef89}", + "user-share": "\u{f9d8}", + "user-shield": "\u{f7d0}", + "user-square": "\u{fc51}", + "user-square-rounded": "\u{fc50}", + "user-star": "\u{f7d1}", + "user-up": "\u{f7d2}", + "user-x": "\u{eb4c}", + "users": "\u{ebf2}", + "users-group": "\u{fa21}", + "users-minus": "\u{fa0e}", + "users-plus": "\u{fa0f}", + "uv-index": "\u{f3b2}", + "ux-circle": "\u{f369}", + "vaccine": "\u{ef04}", + "vaccine-bottle": "\u{ef69}", + "vaccine-bottle-off": "\u{f439}", + "vaccine-off": "\u{f1bc}", + "vacuum-cleaner": "\u{f5e6}", + "variable": "\u{ef05}", + "variable-minus": "\u{f36a}", + "variable-off": "\u{f1bd}", + "variable-plus": "\u{f36b}", + "vector": "\u{eca9}", + "vector-bezier": "\u{ef1d}", + "vector-bezier-2": "\u{f1a3}", + "vector-bezier-arc": "\u{f4cd}", + "vector-bezier-circle": "\u{f4ce}", + "vector-off": "\u{f1be}", + "vector-spline": "\u{f565}", + "vector-triangle": "\u{eca8}", + "vector-triangle-off": "\u{f1bf}", + "venus": "\u{ec86}", + "versions": "\u{ed52}", + "versions-filled": "\u{f6b1}", + "versions-off": "\u{f1c0}", + "video": "\u{ed22}", + "video-filled": "\u{1009b}", + "video-minus": "\u{ed1f}", + "video-off": "\u{ed20}", + "video-plus": "\u{ed21}", + "view-360": "\u{ed84}", + "view-360-arrow": "\u{f62f}", + "view-360-number": "\u{f566}", + "view-360-off": "\u{f1c1}", + "viewfinder": "\u{eb4e}", + "viewfinder-off": "\u{f1c2}", + "viewport-narrow": "\u{ebf3}", + "viewport-short": "\u{fee9}", + "viewport-tall": "\u{fee8}", + "viewport-wide": "\u{ebf4}", + "vinyl": "\u{f00d}", + "vip": "\u{f3b3}", + "vip-off": "\u{f43a}", + "virus": "\u{eb74}", + "virus-off": "\u{ed66}", + "virus-search": "\u{ed67}", + "vocabulary": "\u{ef1e}", + "vocabulary-off": "\u{f43b}", + "volcano": "\u{f79c}", + "volume": "\u{eb51}", + "volume-2": "\u{eb4f}", + "volume-3": "\u{eb50}", + "volume-off": "\u{f1c3}", + "vs": "\u{fc52}", + "walk": "\u{ec87}", + "wall": "\u{ef7a}", + "wall-off": "\u{f43c}", + "wallet": "\u{eb75}", + "wallet-off": "\u{f1c4}", + "wallpaper": "\u{ef56}", + "wallpaper-off": "\u{f1c5}", + "wand": "\u{ebcb}", + "wand-off": "\u{f1c6}", + "wash": "\u{f311}", + "wash-dry": "\u{f304}", + "wash-dry-1": "\u{f2fa}", + "wash-dry-2": "\u{f2fb}", + "wash-dry-3": "\u{f2fc}", + "wash-dry-a": "\u{f2fd}", + "wash-dry-dip": "\u{f2fe}", + "wash-dry-f": "\u{f2ff}", + "wash-dry-flat": "\u{fa7f}", + "wash-dry-hang": "\u{f300}", + "wash-dry-off": "\u{f301}", + "wash-dry-p": "\u{f302}", + "wash-dry-shade": "\u{f303}", + "wash-dry-w": "\u{f322}", + "wash-dryclean": "\u{f305}", + "wash-dryclean-off": "\u{f323}", + "wash-eco": "\u{fa80}", + "wash-gentle": "\u{f306}", + "wash-hand": "\u{fa81}", + "wash-machine": "\u{f25e}", + "wash-off": "\u{f307}", + "wash-press": "\u{f308}", + "wash-temperature-1": "\u{f309}", + "wash-temperature-2": "\u{f30a}", + "wash-temperature-3": "\u{f30b}", + "wash-temperature-4": "\u{f30c}", + "wash-temperature-5": "\u{f30d}", + "wash-temperature-6": "\u{f30e}", + "wash-tumble-dry": "\u{f30f}", + "wash-tumble-off": "\u{f310}", + "waterpolo": "\u{fa6f}", + "wave-saw-tool": "\u{ecd3}", + "wave-sine": "\u{ecd4}", + "wave-square": "\u{ecd5}", + "waves-electricity": "\u{fcc5}", + "webhook": "\u{f01e}", + "webhook-off": "\u{f43d}", + "weight": "\u{f589}", + "wheat": "\u{100a8}", + "wheat-off": "\u{100a9}", + "wheel": "\u{fc64}", + "wheelchair": "\u{f1db}", + "wheelchair-off": "\u{f43e}", + "whirl": "\u{f51d}", + "wifi": "\u{eb52}", + "wifi-0": "\u{eba3}", + "wifi-1": "\u{eba4}", + "wifi-2": "\u{eba5}", + "wifi-3": "\u{ebfc}", + "wifi-off": "\u{ecfa}", + "wifi-exclamation": "\u{ebfd}", + "wifi-question": "\u{ebfe}", + "wind": "\u{ec34}", + "wind-electricity": "\u{fcc6}", + "wind-off": "\u{f1c7}", + "windmill": "\u{ed85}", + "windmill-filled": "\u{f6b2}", + "windmill-off": "\u{f1c8}", + "window": "\u{ef06}", + "window-maximize": "\u{f1f1}", + "window-minimize": "\u{f1f2}", + "window-off": "\u{f1c9}", + "windsock": "\u{f06d}", + "windsock-filled": "\u{1009a}", + "wiper": "\u{ecab}", + "wiper-wash": "\u{ecaa}", + "woman": "\u{eb53}", + "woman-filled": "\u{fdcc}", + "wood": "\u{f359}", + "world": "\u{eb54}", + "world-bolt": "\u{f9d9}", + "world-cancel": "\u{f9da}", + "world-check": "\u{f9db}", + "world-code": "\u{f9dc}", + "world-cog": "\u{f9dd}", + "world-dollar": "\u{f9de}", + "world-down": "\u{f9df}", + "world-download": "\u{ef8a}", + "world-exclamation": "\u{f9e0}", + "world-heart": "\u{f9e1}", + "world-latitude": "\u{ed2e}", + "world-longitude": "\u{ed2f}", + "world-minus": "\u{f9e2}", + "world-off": "\u{f1ca}", + "world-pause": "\u{f9e3}", + "world-pin": "\u{f9e4}", + "world-plus": "\u{f9e5}", + "world-question": "\u{f9e6}", + "world-search": "\u{f9e7}", + "world-share": "\u{f9e8}", + "world-star": "\u{f9e9}", + "world-up": "\u{f9ea}", + "world-upload": "\u{ef8b}", + "world-www": "\u{f38f}", + "world-x": "\u{f9eb}", + "wrecking-ball": "\u{ed97}", + "writing": "\u{ef08}", + "writing-off": "\u{f1cb}", + "writing-sign": "\u{ef07}", + "writing-sign-off": "\u{f1cc}", + "x": "\u{eb55}", + "x-power-y": "\u{10072}", + "xbox-a": "\u{f2b6}", + "xbox-a-filled": "\u{fdcb}", + "xbox-b": "\u{f2b7}", + "xbox-b-filled": "\u{fdca}", + "xbox-x": "\u{f2b8}", + "xbox-x-filled": "\u{fdc9}", + "xbox-y": "\u{f2b9}", + "xbox-y-filled": "\u{fdc8}", + "xd": "\u{fa33}", + "xxx": "\u{fc20}", + "yin-yang": "\u{ec35}", + "yin-yang-filled": "\u{f785}", + "yoga": "\u{f01f}", + "zeppelin": "\u{f270}", + "zeppelin-filled": "\u{fdc7}", + "zeppelin-off": "\u{f43f}", + "zip": "\u{f3b4}", + "zodiac-aquarius": "\u{ecac}", + "zodiac-aries": "\u{ecad}", + "zodiac-cancer": "\u{ecae}", + "zodiac-capricorn": "\u{ecaf}", + "zodiac-gemini": "\u{ecb0}", + "zodiac-leo": "\u{ecb1}", + "zodiac-libra": "\u{ecb2}", + "zodiac-pisces": "\u{ecb3}", + "zodiac-sagittarius": "\u{ecb4}", + "zodiac-scorpio": "\u{ecb5}", + "zodiac-taurus": "\u{ecb6}", + "zodiac-virgo": "\u{ecb7}", + "zoom": "\u{fdaa}", + "zoom-cancel": "\u{ec4d}", + "zoom-cancel-filled": "\u{fdc6}", + "zoom-check": "\u{ef09}", + "zoom-check-filled": "\u{f786}", + "zoom-code": "\u{f07f}", + "zoom-code-filled": "\u{fdc5}", + "zoom-exclamation": "\u{f080}", + "zoom-exclamation-filled": "\u{fdc4}", + "zoom-filled": "\u{f787}", + "zoom-in": "\u{eb56}", + "zoom-in-area": "\u{f1dc}", + "zoom-in-area-filled": "\u{f788}", + "zoom-in-filled": "\u{f789}", + "zoom-money": "\u{ef0a}", + "zoom-money-filled": "\u{fdc3}", + "zoom-out": "\u{eb57}", + "zoom-out-area": "\u{f1dd}", + "zoom-out-area-filled": "\u{fdc2}", + "zoom-out-filled": "\u{f78a}", + "zoom-pan": "\u{f1de}", + "zoom-pan-filled": "\u{fdc1}", + "zoom-question": "\u{edeb}", + "zoom-question-filled": "\u{fdc0}", + "zoom-replace": "\u{f2a7}", + "zoom-reset": "\u{f295}", + "zoom-scan": "\u{fcb0}", + "zoom-scan-filled": "\u{fdbf}", + "zzz": "\u{f228}", + "zzz-off": "\u{f440}" + } +} diff --git a/quickshell/compat/noctalia/Commons/Keybinds.qml b/quickshell/compat/noctalia/Commons/Keybinds.qml new file mode 100644 index 0000000..e807b01 --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Keybinds.qml @@ -0,0 +1,201 @@ +pragma Singleton + +import QtQuick + +QtObject { + function getKeybindString(event) { + let keyStr = ""; + if (event.modifiers & Qt.ControlModifier) + keyStr += "Ctrl+"; + if (event.modifiers & Qt.AltModifier) + keyStr += "Alt+"; + if (event.modifiers & Qt.ShiftModifier) + keyStr += "Shift+"; + + let keyName = ""; + let rawText = event.text; + + if (event.key >= Qt.Key_A && event.key <= Qt.Key_Z || event.key >= Qt.Key_0 && event.key <= Qt.Key_9) { + keyName = String.fromCharCode(event.key); + } else if (event.key >= Qt.Key_F1 && event.key <= Qt.Key_F12) { + keyName = "F" + (event.key - Qt.Key_F1 + 1); + } else if (rawText && rawText.length > 0 && rawText.charCodeAt(0) > 31 && rawText.charCodeAt(0) !== 127) { + keyName = rawText.toUpperCase(); + + if (event.modifiers & Qt.ShiftModifier) { + const shiftMap = { + "!": "1", + "\"": "2", + "§": "3", + "$": "4", + "%": "5", + "&": "6", + "/": "7", + "(": "8", + ")": "9", + "=": "0", + "@": "2", + "#": "3", + "^": "6", + "*": "8" + }; + if (shiftMap[keyName]) { + keyName = shiftMap[keyName]; + } + } + } else { + switch (event.key) { + case Qt.Key_Escape: + keyName = "Esc"; + break; + case Qt.Key_Space: + keyName = "Space"; + break; + case Qt.Key_Return: + keyName = "Return"; + break; + case Qt.Key_Enter: + keyName = "Enter"; + break; + case Qt.Key_Tab: + keyName = "Tab"; + break; + case Qt.Key_Backspace: + keyName = "Backspace"; + break; + case Qt.Key_Delete: + keyName = "Del"; + break; + case Qt.Key_Insert: + keyName = "Ins"; + break; + case Qt.Key_Home: + keyName = "Home"; + break; + case Qt.Key_End: + keyName = "End"; + break; + case Qt.Key_PageUp: + keyName = "PgUp"; + break; + case Qt.Key_PageDown: + keyName = "PgDn"; + break; + case Qt.Key_Left: + keyName = "Left"; + break; + case Qt.Key_Right: + keyName = "Right"; + break; + case Qt.Key_Up: + keyName = "Up"; + break; + case Qt.Key_Down: + keyName = "Down"; + break; + case Qt.Key_BracketLeft: + keyName = "["; + break; + case Qt.Key_BracketRight: + keyName = "]"; + break; + case Qt.Key_Backslash: + keyName = "\\"; + break; + case Qt.Key_Slash: + keyName = "/"; + break; + case Qt.Key_QuoteLeft: + case Qt.Key_AsciiTilde: + case Qt.Key_Dead_Grave: + keyName = "`"; + break; + } + } + + if (!keyName) + return ""; + return keyStr + keyName; + } + + function checkKey(event, settingName, settings) { + // Accept both simplified names ("remove") and full property names ("keyRemove") + // so callers are less error-prone. + var normalized = String(settingName || ""); + if (!normalized) + return false; + + var propName = normalized.startsWith("key") ? normalized : ("key" + normalized.charAt(0).toUpperCase() + normalized.slice(1)); + var boundKeys = settings.data.general.keybinds[propName]; + if (!boundKeys || boundKeys.length === 0) + return false; + var eventString = getKeybindString(event); + for (var i = 0; i < boundKeys.length; i++) { + if (boundKeys[i] === eventString) + return true; + } + return false; + } + + /** + * Check if a keybind string conflicts with any other existing keybinds. + * @param {string} keyStr - The keybind string to check (e.g., "Ctrl+A"). + * @param {string} currentPath - The settings path of the keybind being edited (to skip checking itself). + * @param {object} data - The settings data object (from Settings.data). + * @returns {string|null} - The name of the conflicting action, or null if no conflict. + */ + function getKeybindConflict(keyStr, currentPath, data) { + if (!keyStr || !data) + return null; + + const searchKey = String(keyStr).trim().toLowerCase(); + + // 1. Check navigation keybinds + const navKeybinds = data.general ? data.general.keybinds : null; + const navMap = { + "keyUp": "Navigation: Up", + "keyDown": "Navigation: Down", + "keyLeft": "Navigation: Left", + "keyRight": "Navigation: Right", + "keyEnter": "Navigation: Enter", + "keyEscape": "Navigation: Escape" + }; + + if (navKeybinds) { + for (const prop in navMap) { + const fullPath = "general.keybinds." + prop; + if (fullPath === currentPath) + continue; + + const boundKeys = navKeybinds[prop]; + if (boundKeys && boundKeys.length !== undefined) { + for (let i = 0; i < boundKeys.length; i++) { + if (String(boundKeys[i]).trim().toLowerCase() === searchKey) { + return navMap[prop]; + } + } + } + } + } + + // 2. Check session menu power options + const sessionMenu = data.sessionMenu; + if (sessionMenu && sessionMenu.powerOptions) { + const powerOptions = sessionMenu.powerOptions; + for (let i = 0; i < powerOptions.length; i++) { + const entry = powerOptions[i]; + const fullPath = "sessionMenu.powerOptions[" + i + "].keybind"; + if (fullPath === currentPath) + continue; + + if (entry.keybind && String(entry.keybind).trim().toLowerCase() === searchKey) { + // Capitalize action name + const actionName = entry.action ? entry.action.charAt(0).toUpperCase() + entry.action.slice(1) : "Unknown"; + return "Session Menu: " + actionName; + } + } + } + + return null; + } +} diff --git a/quickshell/compat/noctalia/Commons/Logger.qml b/quickshell/compat/noctalia/Commons/Logger.qml new file mode 100644 index 0000000..f3f3aec --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Logger.qml @@ -0,0 +1,69 @@ +pragma Singleton + +import Quickshell +import qs.compat.noctalia.Commons + +Singleton { + id: root + + function _formatMessage(...args) { + var t = Time.getFormattedTimestamp(); + if (args.length > 1) { + const maxLength = 14; + var module = args.shift().substring(0, maxLength).padStart(maxLength, " "); + return `\x1b[36m[${t}]\x1b[0m \x1b[35m${module}\x1b[0m ` + args.join(" "); + } else { + return `[\x1b[36m[${t}]\x1b[0m ` + args.join(" "); + } + } + + function _getStackTrace() { + try { + throw new Error("Stack trace"); + } catch (e) { + return e.stack; + } + } + + // Debug log (only when Settings.isDebug is true) + function d(...args) { + if (Settings?.isDebug) { + var msg = _formatMessage(...args); + console.debug(msg); + } + } + + // Info log (always visible) + function i(...args) { + var msg = _formatMessage(...args); + console.info(msg); + } + + // Warning log (always visible) + function w(...args) { + var msg = _formatMessage(...args); + console.warn(msg); + } + + // Error log (always visible) + function e(...args) { + var msg = _formatMessage(...args); + console.error(msg); + } + + function callStack() { + var stack = _getStackTrace(); + Logger.i("Debug", "--------------------------"); + Logger.i("Debug", "Current call stack"); + // Split the stack into lines and log each one + var stackLines = stack.split('\n'); + for (var i = 0; i < stackLines.length; i++) { + var line = stackLines[i].trim(); // Remove leading/trailing whitespace + if (line.length > 0) { + // Only log non-empty lines + Logger.i("Debug", `- ${line}`); + } + } + Logger.i("Debug", "--------------------------"); + } +} diff --git a/quickshell/compat/noctalia/Commons/Migrations/Migration27.qml b/quickshell/compat/noctalia/Commons/Migrations/Migration27.qml new file mode 100644 index 0000000..644218d --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Migrations/Migration27.qml @@ -0,0 +1,23 @@ +import QtQuick + +QtObject { + id: root + + // Migrate from version < 27 to version 27 + // Converts settingsPanelAttachToBar boolean to settingsPanelMode string + function migrate(adapter, logger, rawJson) { + logger.i("Settings", "Migrating settings to v27"); + + // Check rawJson for old property (adapter doesn't expose removed properties) + if (rawJson?.ui?.settingsPanelAttachToBar !== undefined) { + if (rawJson.ui.settingsPanelAttachToBar === true) { + adapter.ui.settingsPanelMode = "attached"; + } else { + adapter.ui.settingsPanelMode = "centered"; + } + logger.i("Settings", "Migrated settingsPanelAttachToBar to settingsPanelMode: " + adapter.ui.settingsPanelMode); + } + + return true; + } +} diff --git a/quickshell/compat/noctalia/Commons/Migrations/Migration28.qml b/quickshell/compat/noctalia/Commons/Migrations/Migration28.qml new file mode 100644 index 0000000..d3ef7b7 --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Migrations/Migration28.qml @@ -0,0 +1,37 @@ +import QtQuick + +QtObject { + id: root + + // Migrate TaskbarGrouped widgets to Workspace with showApplications: true + function migrate(adapter, logger, rawJson) { + logger.i("Settings", "Migrating settings to v28"); + + // Check bar widgets in all sections + const sections = ["left", "center", "right"]; + + for (const section of sections) { + if (!rawJson?.bar?.widgets?.[section]) + continue; + + const widgets = rawJson.bar.widgets[section]; + for (let i = 0; i < widgets.length; i++) { + if (widgets[i].id === "TaskbarGrouped") { + // Convert TaskbarGrouped to Workspace with showApplications + const oldWidget = widgets[i]; + adapter.bar.widgets[section][i] = { + id: "Workspace", + showApplications: true, + labelMode: oldWidget.labelMode || "index", + hideUnoccupied: oldWidget.hideUnoccupied || false, + showLabelsOnlyWhenOccupied: oldWidget.showLabelsOnlyWhenOccupied ?? true, + colorizeIcons: oldWidget.colorizeIcons || false + }; + logger.i("Settings", "Migrated TaskbarGrouped to Workspace in " + section + " section"); + } + } + } + + return true; + } +} diff --git a/quickshell/compat/noctalia/Commons/Migrations/Migration32.qml b/quickshell/compat/noctalia/Commons/Migrations/Migration32.qml new file mode 100644 index 0000000..34ca759 --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Migrations/Migration32.qml @@ -0,0 +1,18 @@ +import QtQuick + +QtObject { + id: root + + // Migrate systemMonitor.enableNvidiaGpu to systemMonitor.enableDgpuMonitoring + function migrate(adapter, logger, rawJson) { + logger.i("Settings", "Migrating settings to v32"); + + // Check rawJson for old property (adapter doesn't expose removed properties) + if (rawJson?.systemMonitor?.enableNvidiaGpu !== undefined) { + adapter.systemMonitor.enableDgpuMonitoring = rawJson.systemMonitor.enableNvidiaGpu; + logger.i("Settings", "Migrated systemMonitor.enableNvidiaGpu to enableDgpuMonitoring: " + adapter.systemMonitor.enableDgpuMonitoring); + } + + return true; + } +} diff --git a/quickshell/compat/noctalia/Commons/Migrations/Migration33.qml b/quickshell/compat/noctalia/Commons/Migrations/Migration33.qml new file mode 100644 index 0000000..f012fa1 --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Migrations/Migration33.qml @@ -0,0 +1,26 @@ +import QtQuick + +QtObject { + id: root + + // Migrate wallpaper.randomEnabled to wallpaper.wallpaperChangeMode + function migrate(adapter, logger, rawJson) { + logger.i("Settings", "Migrating settings to v33"); + + if (rawJson?.wallpaper?.randomEnabled !== undefined) { + // We'll keep randomEnabled for backward compatibility but set wallpaperChangeMode + if (rawJson.wallpaper.randomEnabled === true) { + adapter.wallpaper.wallpaperChangeMode = "random"; + logger.i("Settings", "Migrated wallpaper.randomEnabled=true to wallpaperChangeMode=random"); + } else { + adapter.wallpaper.wallpaperChangeMode = "random"; + logger.i("Settings", "Set wallpaperChangeMode=random (randomEnabled was false)"); + } + } else { + adapter.wallpaper.wallpaperChangeMode = "random"; + logger.i("Settings", "Set default wallpaperChangeMode=random"); + } + + return true; + } +} diff --git a/quickshell/compat/noctalia/Commons/Migrations/Migration35.qml b/quickshell/compat/noctalia/Commons/Migrations/Migration35.qml new file mode 100644 index 0000000..3721782 --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Migrations/Migration35.qml @@ -0,0 +1,20 @@ +import QtQuick + +QtObject { + id: root + + // Migrate bar.transparent to bar.backgroundOpacity + bar.useSeparateOpacity + function migrate(adapter, logger, rawJson) { + logger.i("Settings", "Migrating settings to v35"); + + if (rawJson?.bar?.transparent !== undefined) { + if (rawJson.bar.transparent === true) { + adapter.bar.backgroundOpacity = 0; + adapter.bar.useSeparateOpacity = true; + logger.i("Settings", "Migrated bar.transparent=true to backgroundOpacity=0, useSeparateOpacity=true"); + } + } + + return true; + } +} diff --git a/quickshell/compat/noctalia/Commons/Migrations/Migration36.qml b/quickshell/compat/noctalia/Commons/Migrations/Migration36.qml new file mode 100644 index 0000000..be46ca4 --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Migrations/Migration36.qml @@ -0,0 +1,29 @@ +import QtQuick +import Quickshell +import qs.compat.noctalia.Commons + +QtObject { + id: root + + // Clear legacy emoji usage cache to adopt new format + function migrate(adapter, logger, rawJson) { + logger.i("Settings", "Migrating settings to v36"); + + const usagePath = Settings.cacheDir + "emoji_usage.json"; + + if (!usagePath.endsWith("emoji_usage.json")) { + logger.w("Settings", "Skipping emoji usage cleanup due to unexpected path: " + usagePath); + return true; + } + + try { + // Ensure dir exists then remove the file + Quickshell.execDetached(["sh", "-c", `mkdir -p "${Settings.cacheDir}" && rm -f -- "${usagePath}"`]); + logger.i("Settings", "Cleared legacy emoji usage file at: " + usagePath); + } catch (e) { + logger.w("Settings", "Failed to clear emoji usage cache: " + e); + } + + return true; + } +} diff --git a/quickshell/compat/noctalia/Commons/Migrations/Migration37.qml b/quickshell/compat/noctalia/Commons/Migrations/Migration37.qml new file mode 100644 index 0000000..26d64ce --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Migrations/Migration37.qml @@ -0,0 +1,79 @@ +import QtQuick + +QtObject { + id: root + + // Rename WiFi widgets/shortcuts to Network + function migrate(adapter, logger, rawJson) { + logger.i("Settings", "Migrating settings to v37 (WiFi → Network)"); + + let changed = false; + + function migrateArray(contextName, rawArr, adapterArr, setItem) { + if (!adapterArr) + return; + const len = adapterArr.length; + for (let i = 0; i < len; i++) { + // Prefer raw item if present, otherwise use adapter item + const item = rawArr && rawArr[i] !== undefined ? rawArr[i] : adapterArr[i]; + + if (item === undefined || item === null) + continue; + + // Case 1: simple string entries + if (typeof item === "string") { + if (item === "WiFi") { + setItem(i, "Network"); + changed = true; + logger.i("Settings", `Migrated ${contextName}[${i}] from WiFi to Network (string entry)`); + } + continue; + } + + // Case 2: object entries with id + let id = item.id !== undefined ? item.id : (item.widgetId !== undefined ? item.widgetId : undefined); + if (id === "WiFi") { + var newObj = {}; + for (var key in item) + newObj[key] = item[key]; + if (newObj.id !== undefined) + newObj.id = "Network"; + if (newObj.widgetId !== undefined && newObj.id === undefined) + newObj.widgetId = "Network"; // fallback if older schema used widgetId + setItem(i, newObj); + changed = true; + logger.i("Settings", `Migrated ${contextName}[${i}] from WiFi to Network (object entry)`); + } + } + } + + // --- Bar widgets: left/center/right + const sections = ["left", "center", "right"]; + for (const section of sections) { + const rawArr = rawJson?.bar?.widgets?.[section]; + const adapterArr = adapter?.bar?.widgets?.[section]; + migrateArray(`bar.widgets.${section}`, rawArr, adapterArr, function (i, v) { + adapter.bar.widgets[section][i] = v; + }); + } + + // --- Control Center shortcuts: left/right + const rawLeft = rawJson?.controlCenter?.shortcuts?.left; + const adLeft = adapter?.controlCenter?.shortcuts?.left; + migrateArray("controlCenter.shortcuts.left", rawLeft, adLeft, function (i, v) { + adapter.controlCenter.shortcuts.left[i] = v; + }); + + const rawRight = rawJson?.controlCenter?.shortcuts?.right; + const adRight = adapter?.controlCenter?.shortcuts?.right; + migrateArray("controlCenter.shortcuts.right", rawRight, adRight, function (i, v) { + adapter.controlCenter.shortcuts.right[i] = v; + }); + + if (!changed) { + logger.i("Settings", "No WiFi widget IDs found to migrate; leaving settings unchanged"); + } + + return true; + } +} diff --git a/quickshell/compat/noctalia/Commons/Migrations/Migration38.qml b/quickshell/compat/noctalia/Commons/Migrations/Migration38.qml new file mode 100644 index 0000000..febbc90 --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Migrations/Migration38.qml @@ -0,0 +1,27 @@ +import QtQuick +import qs.compat.noctalia.Commons + +QtObject { + function migrate(adapter, logger, rawJson) { + logger.i("Migration38", "Migrating bar margins from percentages to integers"); + + // Use rawJson to read original values, adapter to write new values (following migration patterns) + const rawVertical = rawJson?.bar?.marginVertical; + const rawHorizontal = rawJson?.bar?.marginHorizontal; + + // Only migrate if values exist and are percentages (<= 1.0) + if (rawVertical !== undefined && typeof rawVertical === 'number' && rawVertical <= 1.0) { + const marginXL = 18; // Standard value of Style.marginXL + adapter.bar.marginVertical = Math.round(rawVertical * marginXL); + logger.d("Migration38", "Converted marginVertical from " + rawVertical + " to " + adapter.bar.marginVertical + "px"); + } + + if (rawHorizontal !== undefined && typeof rawHorizontal === 'number' && rawHorizontal <= 1.0) { + const marginXL = 18; // Standard value of Style.marginXL + adapter.bar.marginHorizontal = Math.round(rawHorizontal * marginXL); + logger.d("Migration38", "Converted marginHorizontal from " + rawHorizontal + " to " + adapter.bar.marginHorizontal + "px"); + } + + return true; + } +} diff --git a/quickshell/compat/noctalia/Commons/Migrations/Migration40.qml b/quickshell/compat/noctalia/Commons/Migrations/Migration40.qml new file mode 100644 index 0000000..7cb2399 --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Migrations/Migration40.qml @@ -0,0 +1,43 @@ +import QtQuick + +QtObject { + id: root + + // List of all template IDs that existed as booleans in the old format + readonly property var templateIds: ["gtk", "qt", "kcolorscheme", "alacritty", "kitty", "ghostty", "foot", "wezterm", "fuzzel", "discord", "pywalfox", "vicinae", "walker", "code", "spicetify", "telegram", "cava", "yazi", "emacs", "niri", "hyprland", "mango", "zed", "helix", "zenBrowser"] + + function migrate(adapter, logger, rawJson) { + logger.i("Migration39", "Migrating templates from boolean format to activeTemplates array"); + + // Check if old format exists (any boolean template property) + const oldTemplates = rawJson?.templates; + if (!oldTemplates) { + logger.d("Migration39", "No templates section found, skipping migration"); + return true; + } + + // Check if already migrated (has activeTemplates array) + if (Array.isArray(oldTemplates.activeTemplates)) { + logger.d("Migration39", "Already has activeTemplates array, skipping migration"); + return true; + } + + // Build the new activeTemplates array from old boolean values + const activeTemplates = []; + for (const templateId of templateIds) { + if (oldTemplates[templateId] === true) { + activeTemplates.push({ + "id": templateId, + "enabled": true + }); + logger.d("Migration40", "Migrated enabled template: " + templateId); + } + } + + // Write the new format + adapter.templates.activeTemplates = activeTemplates; + logger.i("Migration40", "Migrated " + activeTemplates.length + " templates to new array format"); + + return true; + } +} diff --git a/quickshell/compat/noctalia/Commons/Migrations/Migration42.qml b/quickshell/compat/noctalia/Commons/Migrations/Migration42.qml new file mode 100644 index 0000000..64358c8 --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Migrations/Migration42.qml @@ -0,0 +1,28 @@ +import QtQuick + +QtObject { + id: root + + function migrate(adapter, logger, rawJson) { + logger.i("Migration42", "Migrating randomEnabled to automationEnabled"); + + const wallpaper = rawJson?.wallpaper; + if (!wallpaper) { + logger.d("Migration42", "No wallpaper section found, skipping migration"); + return true; + } + + // Check if already migrated (has automationEnabled) + if (wallpaper.automationEnabled !== undefined) { + logger.d("Migration42", "Already has automationEnabled, skipping migration"); + return true; + } + + // Migrate randomEnabled to automationEnabled + const oldValue = wallpaper.randomEnabled ?? false; + adapter.wallpaper.automationEnabled = oldValue; + logger.i("Migration42", "Migrated randomEnabled=" + oldValue + " to automationEnabled=" + oldValue); + + return true; + } +} diff --git a/quickshell/compat/noctalia/Commons/Migrations/Migration43.qml b/quickshell/compat/noctalia/Commons/Migrations/Migration43.qml new file mode 100644 index 0000000..93daf31 --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Migrations/Migration43.qml @@ -0,0 +1,29 @@ +import QtQuick + +QtObject { + id: root + + function migrate(adapter, logger, rawJson) { + logger.i("Migration43", "Migrating recursiveSearch to viewMode"); + + const wallpaper = rawJson?.wallpaper; + if (!wallpaper) { + logger.d("Migration43", "No wallpaper section found, skipping migration"); + return true; + } + + // Check if already migrated (has viewMode) + if (wallpaper.viewMode !== undefined) { + logger.d("Migration43", "Already has viewMode, skipping migration"); + return true; + } + + // Migrate recursiveSearch to viewMode + const oldValue = wallpaper.recursiveSearch ?? false; + const newValue = oldValue ? "recursive" : "single"; + adapter.wallpaper.viewMode = newValue; + logger.i("Migration43", "Migrated recursiveSearch=" + oldValue + " to viewMode=" + newValue); + + return true; + } +} diff --git a/quickshell/compat/noctalia/Commons/Migrations/Migration44.qml b/quickshell/compat/noctalia/Commons/Migrations/Migration44.qml new file mode 100644 index 0000000..584da80 --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Migrations/Migration44.qml @@ -0,0 +1,35 @@ +import QtQuick +import Quickshell +import qs.compat.noctalia.Commons + +QtObject { + id: root + + function migrate(adapter, logger, rawJson) { + logger.i("Migration44", "Updating PAM pam/password.conf"); + + const configDir = Settings.configDir; + const pamConfigDir = configDir + "pam"; + const pamConfigFile = pamConfigDir + "/password.conf"; + const pamConfigDirEsc = pamConfigDir.replace(/'/g, "'\\''"); + const pamConfigFileEsc = pamConfigFile.replace(/'/g, "'\\''"); + + // Ensure directory exists + Quickshell.execDetached(["mkdir", "-p", pamConfigDir]); + + // Generate the PAM config file content (updated version) + var configContent = "auth sufficient pam_fprintd.so timeout=-1\n"; + configContent += "auth sufficient /run/current-system/sw/lib/security/pam_fprintd.so timeout=-1 # for NixOS\n"; + configContent += "auth required pam_unix.so\n"; + + // Write the config file using heredoc + var script = `cat > '${pamConfigFileEsc}' << 'EOF'\n`; + script += configContent; + script += "EOF\n"; + Quickshell.execDetached(["sh", "-c", script]); + + logger.d("Migration44", "PAM config file updated at:", pamConfigFile); + + return true; + } +} diff --git a/quickshell/compat/noctalia/Commons/Migrations/Migration45.qml b/quickshell/compat/noctalia/Commons/Migrations/Migration45.qml new file mode 100644 index 0000000..25c0f8d --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Migrations/Migration45.qml @@ -0,0 +1,18 @@ +import QtQuick + +QtObject { + /** + * Migration 45: Migrate 'floating' bar setting to 'barType' + */ + function migrate(adapter, logger, rawJson) { + logger.i("Migration45", "Migrating bar settings..."); + + if (rawJson?.bar?.floating) { + adapter.bar.barType = "floating"; + } else { + adapter.bar.barType = "simple"; + } + + return true; + } +} diff --git a/quickshell/compat/noctalia/Commons/Migrations/Migration46.qml b/quickshell/compat/noctalia/Commons/Migrations/Migration46.qml new file mode 100644 index 0000000..94abee3 --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Migrations/Migration46.qml @@ -0,0 +1,21 @@ +import QtQuick +import Quickshell +import qs.compat.noctalia.Commons + +QtObject { + id: root + + function migrate(adapter, logger, rawJson) { + logger.i("Migration46", "Removing legacy PAM configuration file"); + + const configDir = Settings.configDir; + const pamConfigDir = configDir + "pam"; + // Remove the entire pam directory if it exists + const script = `rm -rf '${pamConfigDir}'`; + Quickshell.execDetached(["sh", "-c", script]); + + logger.d("Migration46", "Cleaned up legacy PAM config"); + + return true; + } +} diff --git a/quickshell/compat/noctalia/Commons/Migrations/Migration47.qml b/quickshell/compat/noctalia/Commons/Migrations/Migration47.qml new file mode 100644 index 0000000..4880f9e --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Migrations/Migration47.qml @@ -0,0 +1,18 @@ +import QtQuick +import Quickshell +import qs.compat.noctalia.Commons + +QtObject { + id: root + + function migrate(adapter, logger, rawJson) { + logger.i("Migration47", "Removing network_stats.json cache"); + + const networkStatsFile = Settings.cacheDir + "network_stats.json"; + Quickshell.execDetached(["rm", "-f", networkStatsFile]); + + logger.d("Migration47", "Removed network_stats.json"); + + return true; + } +} diff --git a/quickshell/compat/noctalia/Commons/Migrations/Migration48.qml b/quickshell/compat/noctalia/Commons/Migrations/Migration48.qml new file mode 100644 index 0000000..a775e95 --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Migrations/Migration48.qml @@ -0,0 +1,22 @@ +import QtQuick + +QtObject { + id: root + + // Migrate battery thresholds from notifications to systemMonitor + function migrate(adapter, logger, rawJson) { + logger.i("Settings", "Migrating settings to v48"); + + if (rawJson?.notifications?.batteryWarningThreshold !== undefined) { + adapter.systemMonitor.batteryWarningThreshold = rawJson.notifications.batteryWarningThreshold; + logger.i("Settings", "Migrated notifications.batteryWarningThreshold to systemMonitor: " + adapter.systemMonitor.batteryWarningThreshold); + } + + if (rawJson?.notifications?.batteryCriticalThreshold !== undefined) { + adapter.systemMonitor.batteryCriticalThreshold = rawJson.notifications.batteryCriticalThreshold; + logger.i("Settings", "Migrated notifications.batteryCriticalThreshold to systemMonitor: " + adapter.systemMonitor.batteryCriticalThreshold); + } + + return true; + } +} diff --git a/quickshell/compat/noctalia/Commons/Migrations/Migration49.qml b/quickshell/compat/noctalia/Commons/Migrations/Migration49.qml new file mode 100644 index 0000000..6bb7999 --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Migrations/Migration49.qml @@ -0,0 +1,17 @@ +import QtQuick +import Quickshell +import qs.compat.noctalia.Commons + +QtObject { + id: root + + // Remove old launcher_app_usage.json (usage tracking moved to ShellState) + function migrate(adapter, logger, rawJson) { + logger.i("Settings", "Migrating settings to v49"); + + Quickshell.execDetached(["rm", "-f", Settings.cacheDir + "launcher_app_usage.json"]); + logger.i("Settings", "Removed old launcher_app_usage.json"); + + return true; + } +} diff --git a/quickshell/compat/noctalia/Commons/Migrations/Migration50.qml b/quickshell/compat/noctalia/Commons/Migrations/Migration50.qml new file mode 100644 index 0000000..398b266 --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Migrations/Migration50.qml @@ -0,0 +1,24 @@ +import QtQuick + +QtObject { + id: root + + // Migrate keybinds from single strings to arrays of strings + function migrate(adapter, logger, rawJson) { + logger.i("Settings", "Migrating settings to v50"); + + const keybinds = rawJson?.general?.keybinds; + if (!keybinds) + return true; + + const keys = ["keyUp", "keyDown", "keyLeft", "keyRight", "keyEnter", "keyEscape"]; + for (const key of keys) { + if (keybinds[key] !== undefined && typeof keybinds[key] === "string") { + adapter.general.keybinds[key] = [keybinds[key]]; + logger.i("Settings", "Migrated keybinds." + key + " from string to array: [" + keybinds[key] + "]"); + } + } + + return true; + } +} diff --git a/quickshell/compat/noctalia/Commons/Migrations/Migration53.qml b/quickshell/compat/noctalia/Commons/Migrations/Migration53.qml new file mode 100644 index 0000000..cf2382d --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Migrations/Migration53.qml @@ -0,0 +1,39 @@ +import QtQuick + +QtObject { + id: root + + // Add default keybinds (1-6) to session menu power options if none are defined + function migrate(adapter, logger, rawJson) { + logger.i("Settings", "Migrating settings to v53"); + + const powerOptions = rawJson?.sessionMenu?.powerOptions; + if (!powerOptions || !Array.isArray(powerOptions)) + return true; + + // Check if any power option has a keybind defined + const hasAnyKeybind = powerOptions.some(opt => opt.keybind && opt.keybind !== ""); + if (hasAnyKeybind) + return true; + + // No keybinds defined — apply defaults matching the action order + const defaultKeybinds = { + "lock": "1", + "suspend": "2", + "hibernate": "3", + "reboot": "4", + "logout": "5", + "shutdown": "6" + }; + + for (let i = 0; i < powerOptions.length; i++) { + const action = powerOptions[i].action; + if (defaultKeybinds[action]) { + adapter.sessionMenu.powerOptions[i].keybind = defaultKeybinds[action]; + logger.i("Settings", "Set keybind '" + defaultKeybinds[action] + "' for session menu action: " + action); + } + } + + return true; + } +} diff --git a/quickshell/compat/noctalia/Commons/Migrations/Migration54.qml b/quickshell/compat/noctalia/Commons/Migrations/Migration54.qml new file mode 100644 index 0000000..367ab12 --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Migrations/Migration54.qml @@ -0,0 +1,28 @@ +import QtQuick + +QtObject { + id: root + + // Add numpad Enter as a second default keybind for keyEnter + function migrate(adapter, logger, rawJson) { + logger.i("Settings", "Migrating settings to v54"); + + const keybinds = rawJson?.general?.keybinds; + if (!keybinds) + return true; + + const keyEnter = keybinds.keyEnter; + if (!keyEnter || !Array.isArray(keyEnter)) + return true; + + // Only add "Enter" if the first entry is "Return" and "Enter" isn't already present + if (keyEnter[0] === "Return" && !keyEnter.includes("Enter")) { + var updated = Array.from(keyEnter); + updated.splice(1, 0, "Enter"); + adapter.general.keybinds.keyEnter = updated; + logger.i("Settings", "Added 'Enter' (numpad) as second default keybind for keyEnter"); + } + + return true; + } +} diff --git a/quickshell/compat/noctalia/Commons/Migrations/Migration55.qml b/quickshell/compat/noctalia/Commons/Migrations/Migration55.qml new file mode 100644 index 0000000..0e08276 --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Migrations/Migration55.qml @@ -0,0 +1,22 @@ +import QtQuick + +QtObject { + id: root + + function migrate(adapter, logger, rawJson) { + logger.i("Settings", "Migrating settings to v55"); + + // Check if the old setting exists + if (rawJson.controlCenter && rawJson.controlCenter.openAtMouseOnBarRightClick !== undefined) { + if (!rawJson.bar) + rawJson.bar = {}; + + rawJson.bar.rightClickFollowMouse = rawJson.controlCenter.openAtMouseOnBarRightClick; + delete rawJson.controlCenter.openAtMouseOnBarRightClick; + + logger.i("Settings", "Successfully moved openAtMouseOnBarRightClick to bar.rightClickFollowMouse"); + } + + return true; + } +} diff --git a/quickshell/compat/noctalia/Commons/Migrations/Migration56.qml b/quickshell/compat/noctalia/Commons/Migrations/Migration56.qml new file mode 100644 index 0000000..c21eb68 --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Migrations/Migration56.qml @@ -0,0 +1,21 @@ +import QtQuick +import Quickshell +import qs.compat.noctalia.Commons + +QtObject { + id: root + + function migrate(adapter, logger, rawJson) { + logger.i("Settings", "Migrating settings to v56 (Color Scheme Migration)"); + + const scriptPath = Quickshell.shellDir + "/Scripts/python/src/theming/migrate-colorschemes.py"; + const configDir = Settings.configDir; + + logger.i("Settings", `Running color scheme migration script: ${scriptPath} with configDir: ${configDir}`); + + // Run the migration script detached + Quickshell.execDetached(["python3", scriptPath, configDir]); + + return true; + } +} diff --git a/quickshell/compat/noctalia/Commons/Migrations/Migration57.qml b/quickshell/compat/noctalia/Commons/Migrations/Migration57.qml new file mode 100644 index 0000000..a8e3444 --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Migrations/Migration57.qml @@ -0,0 +1,16 @@ +import QtQuick + +QtObject { + id: root + + function migrate(adapter, logger, rawJson) { + logger.i("Settings", "Migrating settings to v57 (cavaFrameRate -> spectrumFrameRate)"); + + if (rawJson && rawJson.audio && rawJson.audio.cavaFrameRate !== undefined) { + adapter.audio.spectrumFrameRate = rawJson.audio.cavaFrameRate; + logger.i("Settings", "Migrated cavaFrameRate:", rawJson.audio.cavaFrameRate, "-> spectrumFrameRate"); + } + + return true; + } +} diff --git a/quickshell/compat/noctalia/Commons/Migrations/Migration58.qml b/quickshell/compat/noctalia/Commons/Migrations/Migration58.qml new file mode 100644 index 0000000..32dd42f --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Migrations/Migration58.qml @@ -0,0 +1,14 @@ +import QtQuick + +QtObject { + function migrate(adapter, logger, rawJson) { + logger.i("Settings", "Migrating settings to v58 (dock.dockType: static -> attached)"); + + if (rawJson && rawJson.dock && rawJson.dock.dockType === "static") { + adapter.dock.dockType = "attached"; + logger.i("Settings", "Migrated dock.dockType: static -> attached"); + } + + return true; + } +} diff --git a/quickshell/compat/noctalia/Commons/Migrations/Migration59.qml b/quickshell/compat/noctalia/Commons/Migrations/Migration59.qml new file mode 100644 index 0000000..89d8bba --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Migrations/Migration59.qml @@ -0,0 +1,25 @@ +import QtQuick + +QtObject { + function migrate(adapter, logger, rawJson) { + logger.i("Settings", "Migrating settings to v59 (wallpaper.transitionType: string -> array)"); + + if (rawJson && rawJson.wallpaper && typeof rawJson.wallpaper.transitionType === "string") { + var oldValue = rawJson.wallpaper.transitionType; + var newValue; + + if (oldValue === "random") { + newValue = ["fade", "disc", "stripes", "wipe", "pixelate", "honeycomb"]; + } else if (oldValue === "none") { + newValue = []; + } else { + newValue = [oldValue]; + } + + adapter.wallpaper.transitionType = newValue; + logger.i("Settings", "Migrated wallpaper.transitionType:", oldValue, "->", JSON.stringify(newValue)); + } + + return true; + } +} diff --git a/quickshell/compat/noctalia/Commons/Migrations/MigrationRegistry.qml b/quickshell/compat/noctalia/Commons/Migrations/MigrationRegistry.qml new file mode 100644 index 0000000..80a9571 --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Migrations/MigrationRegistry.qml @@ -0,0 +1,63 @@ +pragma Singleton + +import QtQuick + +QtObject { + id: root + + // Map of version number to migration component + readonly property var migrations: ({ + 27: migration27Component, + 28: migration28Component, + 32: migration32Component, + 33: migration33Component, + 35: migration35Component, + 36: migration36Component, + 37: migration37Component, + 38: migration38Component, + 40: migration40Component, + 42: migration42Component, + 43: migration43Component, + 44: migration44Component, + 45: migration45Component, + 46: migration46Component, + 47: migration47Component, + 48: migration48Component, + 49: migration49Component, + 50: migration50Component, + 53: migration53Component, + 54: migration54Component, + 55: migration55Component, + 56: migration56Component, + 57: migration57Component, + 58: migration58Component, + 59: migration59Component + }) + + // Migration components + property Component migration27Component: Migration27 {} + property Component migration28Component: Migration28 {} + property Component migration32Component: Migration32 {} + property Component migration33Component: Migration33 {} + property Component migration35Component: Migration35 {} + property Component migration36Component: Migration36 {} + property Component migration37Component: Migration37 {} + property Component migration38Component: Migration38 {} + property Component migration40Component: Migration40 {} + property Component migration42Component: Migration42 {} + property Component migration43Component: Migration43 {} + property Component migration44Component: Migration44 {} + property Component migration45Component: Migration45 {} + property Component migration46Component: Migration46 {} + property Component migration47Component: Migration47 {} + property Component migration48Component: Migration48 {} + property Component migration49Component: Migration49 {} + property Component migration50Component: Migration50 {} + property Component migration53Component: Migration53 {} + property Component migration54Component: Migration54 {} + property Component migration55Component: Migration55 {} + property Component migration56Component: Migration56 {} + property Component migration57Component: Migration57 {} + property Component migration58Component: Migration58 {} + property Component migration59Component: Migration59 {} +} diff --git a/quickshell/compat/noctalia/Commons/Settings.qml b/quickshell/compat/noctalia/Commons/Settings.qml new file mode 100644 index 0000000..be13ec6 --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Settings.qml @@ -0,0 +1,1298 @@ +pragma Singleton + +import QtQuick +import Quickshell +import Quickshell.Io +import "../Helpers/QtObj2JS.js" as QtObj2JS +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Commons.Migrations +import qs.compat.noctalia.Modules.OSD +import qs.compat.noctalia.Services.Noctalia +import qs.compat.noctalia.Services.UI + +Singleton { + id: root + + property bool isLoaded: false + property bool reloadSettings: false + property bool directoriesCreated: false + property bool shouldOpenSetupWizard: false + property bool isFreshInstall: false + + /* + Shell directories. + - Default config directory: ~/.config/noctalia + - Default cache directory: ~/.cache/noctalia + */ + readonly property alias data: adapter // Used to access via Settings.data.xxx.yyy + readonly property int settingsVersion: 59 + property bool isDebug: Quickshell.env("NOCTALIA_DEBUG") === "1" + readonly property string shellName: "noctalia" + // glassMxrph: keep the compatibility settings apart from any real Noctalia + // install (never read or write ~/.config/noctalia). + readonly property string configDir: ensureTrailingSlash((Quickshell.env("XDG_CONFIG_HOME") || Quickshell.env("HOME") + "/.config") + "/glassMxrph/noctalia-compat/") + readonly property string cacheDir: ensureTrailingSlash((Quickshell.env("XDG_CACHE_HOME") || Quickshell.env("HOME") + "/.cache") + "/glassMxrph/noctalia-compat/") + + readonly property string settingsFile: configDir + "settings.json" + readonly property string defaultAvatar: Quickshell.env("HOME") + "/.face" + readonly property string defaultVideosDirectory: Quickshell.env("HOME") + "/Videos" + readonly property string defaultWallpapersDirectory: Quickshell.env("HOME") + "/Pictures/Wallpapers" + + signal settingsLoaded + signal settingsSaved + signal settingsReloaded + + // Debounce external reload requests (file watcher + directory watcher) + // so atomic replacements only trigger one reload. + Timer { + id: externalReloadTimer + running: false + interval: 200 + onTriggered: { + if (settingsFileView.path !== undefined) { + Logger.d("Settings", "Reloading settings after external change detection"); + reloadSettings = true; + settingsFileView.reload(); + } + } + } + + function scheduleExternalReload() { + if (!directoriesCreated || settingsFileView.path === undefined) { + return; + } + externalReloadTimer.restart(); + } + + // ----------------------------------------------------- + // ----------------------------------------------------- + // Ensure directories exist before FileView tries to read files + Component.onCompleted: { + // ensure settings dir exists + Quickshell.execDetached(["mkdir", "-p", configDir]); + Quickshell.execDetached(["mkdir", "-p", cacheDir]); + + // Mark directories as created and trigger file loading + directoriesCreated = true; + + // This should only be activated once when the settings structure has changed + // Then it should be commented out again, regular users don't need to generate + // default settings on every start + if (isDebug) { + generateDefaultSettings(); + generateWidgetDefaultSettings(); + } + + // Patch-in the local default, resolved to user's home + adapter.general.avatarImage = defaultAvatar; + adapter.wallpaper.directory = defaultWallpapersDirectory; + adapter.ui.fontDefault = Qt.application.font.family; + adapter.ui.fontFixed = "monospace"; + + // Set the adapter to the settingsFileView to trigger the real settings load + settingsFileView.adapter = adapter; + } + + // Don't write settings to disk immediately + // This avoid excessive IO when a variable changes rapidly (ex: sliders) + Timer { + id: saveTimer + running: false + interval: 500 + onTriggered: { + root.saveImmediate(); + } + } + + FileView { + id: settingsFileView + path: directoriesCreated ? settingsFile : undefined + printErrors: false + watchChanges: true + onAdapterUpdated: saveTimer.start() + + onFileChanged: scheduleExternalReload() + + // Trigger initial load when path changes from empty to actual path + onPathChanged: { + if (path !== undefined) { + reload(); + } + } + onLoaded: function () { + if (!isLoaded) { + Logger.i("Settings", "Settings loaded"); + + // Load raw JSON for migrations (adapter doesn't expose removed properties) + var rawJson = null; + try { + rawJson = JSON.parse(settingsFileView.text()); + } catch (e) { + Logger.w("Settings", "Could not parse raw JSON for migrations"); + } + + // Run versioned migrations immediately, don't move it in upgradeSettings + runVersionedMigrations(rawJson); + + // Finally, update our local settings version + adapter.settingsVersion = settingsVersion; + + // Emit the signal + root.isLoaded = true; + root.settingsLoaded(); + + upgradeSettings(); + } else { + Logger.d("Settings", "Settings reloaded from external file change"); + root.settingsReloaded(); + } + } + onLoadFailed: function (error) { + if (reloadSettings) { + reloadSettings = false; + return; + } + if (error.toString().includes("No such file") || error === 2) { + // File doesn't exist, create it with default values + root.isFreshInstall = true; + writeAdapter(); + + // We started without settings, we should open the setupWizard + root.shouldOpenSetupWizard = true; + } + } + } + + // Watch parent config directory as a fallback for declarative setups where + // settings.json may be replaced atomically (e.g., symlink/store-path swap). + FileView { + id: settingsDirWatcher + path: directoriesCreated ? configDir : undefined + printErrors: false + watchChanges: true + onFileChanged: scheduleExternalReload() + } + + // FileView to load default settings for comparison + FileView { + id: defaultSettingsFileView + path: Quickshell.shellDir + "/Assets/settings-default.json" + printErrors: false + watchChanges: false + } + + // Cached default settings object + property var _defaultSettings: null + + // Load default settings when file is loaded + Connections { + target: defaultSettingsFileView + function onLoaded() { + try { + root._defaultSettings = JSON.parse(defaultSettingsFileView.text()); + } catch (e) { + Logger.w("Settings", "Failed to parse default settings file: " + e); + root._defaultSettings = null; + } + } + } + + JsonAdapter { + id: adapter + + property int settingsVersion: 0 + + // bar + property JsonObject bar: JsonObject { + property string barType: "simple" // "simple", "floating", "framed" + property string position: "top" // "top", "bottom", "left", or "right" + property list monitors: [] // holds bar visibility per monitor + property string density: "default" // "compact", "default", "comfortable" + property bool showOutline: false + property bool showCapsule: true + property real capsuleOpacity: 1.0 + property string capsuleColorKey: "none" + property int widgetSpacing: 6 + property int contentPadding: 2 + property real fontScale: 1.0 + property bool enableExclusionZoneInset: true + + // Bar background opacity settings + property real backgroundOpacity: 0.93 + property bool useSeparateOpacity: false + + // Floating bar settings + property int marginVertical: 4 + property int marginHorizontal: 4 + + // Framed bar settings + property int frameThickness: 8 + property int frameRadius: 12 + + // Bar outer corners (inverted/concave corners at bar edges when not floating) + property bool outerCorners: true + + // Hide bar/panels when compositor overview is active + property bool hideOnOverview: false + + // Auto-hide settings + property string displayMode: "always_visible" + property int autoHideDelay: 500 // ms before hiding after mouse leaves + property int autoShowDelay: 150 // ms before showing when mouse enters + property bool showOnWorkspaceSwitch: true // show bar briefly on workspace switch + + // Widget configuration for modular bar system + property JsonObject widgets + widgets: JsonObject { + property list left: [ + { + "id": "Launcher" + }, + { + "id": "Clock" + }, + { + "id": "SystemMonitor" + }, + { + "id": "ActiveWindow" + }, + { + "id": "MediaMini" + } + ] + property list center: [ + { + "id": "Workspace" + } + ] + property list right: [ + { + "id": "Tray" + }, + { + "id": "NotificationHistory" + }, + { + "id": "Battery" + }, + { + "id": "Volume" + }, + { + "id": "Brightness" + }, + { + "id": "ControlCenter" + } + ] + } + property string mouseWheelAction: "none" + property bool reverseScroll: false + property bool mouseWheelWrap: true + property string middleClickAction: "none" + property bool middleClickFollowMouse: false + property string middleClickCommand: "" + property string rightClickAction: "controlCenter" + property bool rightClickFollowMouse: true + property string rightClickCommand: "" + // Per-screen overrides for position and widgets + // Format: [{ "name": "HDMI-1", "position": "left" }, { "name": "DP-1", "position": "bottom", "widgets": {...} }] + property list screenOverrides: [] + } + + // general + property JsonObject general: JsonObject { + property string avatarImage: "" + property real dimmerOpacity: 0.2 + property bool showScreenCorners: false + property bool forceBlackScreenCorners: false + property real scaleRatio: 1.0 + property real radiusRatio: 1.0 + property real iRadiusRatio: 1.0 + property real boxRadiusRatio: 1.0 + property real screenRadiusRatio: 1.0 + property real animationSpeed: 1.0 + property bool animationDisabled: false + property bool compactLockScreen: false + property bool lockScreenAnimations: false + property bool lockOnSuspend: true + property bool showSessionButtonsOnLockScreen: true + property bool showHibernateOnLockScreen: false + property bool enableLockScreenMediaControls: false + property bool enableShadows: true + property bool enableBlurBehind: true + property string shadowDirection: "bottom_right" + property int shadowOffsetX: 2 + property int shadowOffsetY: 3 + property string language: "" + property bool allowPanelsOnScreenWithoutBar: true + property bool showChangelogOnStartup: true + property bool telemetryEnabled: false + property bool enableLockScreenCountdown: true + property int lockScreenCountdownDuration: 10000 + property bool autoStartAuth: false + property bool allowPasswordWithFprintd: false + property string clockStyle: "custom" + property string clockFormat: "hh\\nmm" + property bool passwordChars: false + property list lockScreenMonitors: [] // holds lock screen visibility per monitor + property real lockScreenBlur: 0.0 + property real lockScreenTint: 0.0 + property JsonObject keybinds: JsonObject { + property list keyUp: ["Up"] + property list keyDown: ["Down"] + property list keyLeft: ["Left"] + property list keyRight: ["Right"] + property list keyEnter: ["Return", "Enter"] + property list keyEscape: ["Esc"] + property list keyRemove: ["Del"] + } + property bool reverseScroll: false + property bool smoothScrollEnabled: true + } + + // ui + property JsonObject ui: JsonObject { + property string fontDefault: "" + property string fontFixed: "" + property real fontDefaultScale: 1.0 + property real fontFixedScale: 1.0 + property bool tooltipsEnabled: true + property bool scrollbarAlwaysVisible: true + property bool boxBorderEnabled: false + property real panelBackgroundOpacity: 0.93 + property bool translucentWidgets: false + property bool panelsAttachedToBar: true + property string settingsPanelMode: "attached" // "centered", "attached", "window" + property bool settingsPanelSideBarCardStyle: false + } + + // location + property JsonObject location: JsonObject { + property string name: "" + property bool weatherEnabled: true + property bool weatherShowEffects: true + property bool weatherTaliaMascotAlways: false + property bool useFahrenheit: false + property bool use12hourFormat: false + property bool showWeekNumberInCalendar: false + property bool showCalendarEvents: true + property bool showCalendarWeather: true + property bool analogClockInCalendar: false + property int firstDayOfWeek: -1 // -1 = auto (use locale), 0 = Sunday, 1 = Monday, 6 = Saturday + property bool hideWeatherTimezone: false + property bool hideWeatherCityName: false + property bool autoLocate: false + } + + // calendar + property JsonObject calendar: JsonObject { + property list cards: [ + { + "id": "calendar-header-card", + "enabled": true + }, + { + "id": "calendar-month-card", + "enabled": true + }, + { + "id": "weather-card", + "enabled": true + } + ] + } + + // wallpaper + property JsonObject wallpaper: JsonObject { + property bool enabled: true + property bool overviewEnabled: false + property string directory: "" + property list monitorDirectories: [] + property bool enableMultiMonitorDirectories: false + property bool showHiddenFiles: false + property string viewMode: "single" // "single" | "recursive" | "browse" + property bool setWallpaperOnAllMonitors: true + property bool linkLightAndDarkWallpapers: true + property string fillMode: "crop" + property color fillColor: "#000000" + property bool useSolidColor: false + property color solidColor: "#1a1a2e" + property bool automationEnabled: false + property string wallpaperChangeMode: "random" // "random" or "alphabetical" + property int randomIntervalSec: 300 // 5 min + property int transitionDuration: 1500 // 1500 ms + property list transitionType: ["fade", "disc", "stripes", "wipe", "pixelate", "honeycomb"] + property bool skipStartupTransition: false + property real transitionEdgeSmoothness: 0.05 + property string panelPosition: "follow_bar" + property bool hideWallpaperFilenames: false + property bool useOriginalImages: false + property real overviewBlur: 0.4 + property real overviewTint: 0.6 + // Wallhaven settings + property bool useWallhaven: false + property string wallhavenQuery: "" + property string wallhavenSorting: "relevance" + property string wallhavenOrder: "desc" + property string wallhavenCategories: "111" // general,anime,people + property string wallhavenPurity: "100" // sfw only + property string wallhavenRatios: "" + property string wallhavenApiKey: "" + property string wallhavenResolutionMode: "atleast" // "atleast" or "exact" + property string wallhavenResolutionWidth: "" + + property string wallhavenResolutionHeight: "" + property string sortOrder: "name" // "name", "name_desc", "date", "date_desc", "random" + property list favorites: [] + // Format: [{ "path": "...", "appearance": "light"|"dark", "colorScheme": "...", "darkMode": bool, "useWallpaperColors": bool, "generationMethod": "...", "paletteColors": [...] }] + // Legacy entries omit "appearance" and use darkMode to infer light vs dark slot. + } + + // applauncher + property JsonObject appLauncher: JsonObject { + property bool enableClipboardHistory: false + property bool autoPasteClipboard: false + property bool enableClipPreview: true + property bool clipboardWrapText: true + property bool enableClipboardSmartIcons: true + property bool enableClipboardChips: true + property string clipboardWatchTextCommand: "wl-paste --type text --watch cliphist store" + property string clipboardWatchImageCommand: "wl-paste --type image --watch cliphist store" + property string position: "center" // Position: center, top_left, top_right, bottom_left, bottom_right, bottom_center, top_center + property list pinnedApps: [] + property bool sortByMostUsed: true + property string terminalCommand: "alacritty -e" + property bool customLaunchPrefixEnabled: false + property string customLaunchPrefix: "" + // View mode: "list" or "grid" + property string viewMode: "list" + property bool showCategories: true + // Icon mode: "tabler" or "native" + property string iconMode: "tabler" + property bool showIconBackground: false + property bool enableSettingsSearch: true + property bool enableWindowsSearch: true + property bool enableSessionSearch: true + property bool ignoreMouseInput: false + property string screenshotAnnotationTool: "" + property bool overviewLayer: false + property string density: "default" // "compact", "default", "comfortable" + } + + // control center + property JsonObject controlCenter: JsonObject { + // Position: close_to_bar_button, center, top_left, top_right, bottom_left, bottom_right, bottom_center, top_center + property string position: "close_to_bar_button" + property string diskPath: "/" + property JsonObject shortcuts + shortcuts: JsonObject { + property list left: [ + { + "id": "Network" + }, + { + "id": "Bluetooth" + }, + { + "id": "WallpaperSelector" + }, + { + "id": "NoctaliaPerformance" + } + ] + property list right: [ + { + "id": "Notifications" + }, + { + "id": "PowerProfile" + }, + { + "id": "KeepAwake" + }, + { + "id": "NightLight" + } + ] + } + property list cards: [ + { + "id": "profile-card", + "enabled": true + }, + { + "id": "shortcuts-card", + "enabled": true + }, + { + "id": "audio-card", + "enabled": true + }, + { + "id": "brightness-card", + "enabled": false + }, + { + "id": "weather-card", + "enabled": true + }, + { + "id": "media-sysmon-card", + "enabled": true + } + ] + } + + // system monitor + property JsonObject systemMonitor: JsonObject { + property int cpuWarningThreshold: 80 + property int cpuCriticalThreshold: 90 + property int tempWarningThreshold: 80 + property int tempCriticalThreshold: 90 + property int gpuWarningThreshold: 80 + property int gpuCriticalThreshold: 90 + property int memWarningThreshold: 80 + property int memCriticalThreshold: 90 + property int swapWarningThreshold: 80 + property int swapCriticalThreshold: 90 + property int diskWarningThreshold: 80 + property int diskCriticalThreshold: 90 + property int diskAvailWarningThreshold: 20 + property int diskAvailCriticalThreshold: 10 + property int batteryWarningThreshold: 20 + property int batteryCriticalThreshold: 5 + property bool enableDgpuMonitoring: false // Opt-in: reading dGPU sysfs/nvidia-smi wakes it from D3cold, draining battery + property bool useCustomColors: false + property string warningColor: "" + property string criticalColor: "" + property string externalMonitor: "resources || missioncenter || jdsystemmonitor || corestats || system-monitoring-center || gnome-system-monitor || plasma-systemmonitor || mate-system-monitor || ukui-system-monitor || deepin-system-monitor || pantheon-system-monitor" + } + + // performance + property JsonObject noctaliaPerformance: JsonObject { + property bool disableWallpaper: true + property bool disableDesktopWidgets: true + } + + // dock + property JsonObject dock: JsonObject { + property bool enabled: true + property string position: "bottom" // "top", "bottom", "left", "right" + property string displayMode: "auto_hide" // "always_visible", "auto_hide", "exclusive" + property string dockType: "floating" // "floating", "attached" + property real backgroundOpacity: 1.0 + property real floatingRatio: 1.0 + property real size: 1 + property bool onlySameOutput: true + property list monitors: [] // holds dock visibility per monitor + property list pinnedApps: [] // Desktop entry IDs pinned to the dock (e.g., "org.kde.konsole", "firefox.desktop") + property bool colorizeIcons: false + property bool showLauncherIcon: false + property string launcherPosition: "end" // "start", "end" + property bool launcherUseDistroLogo: false + property string launcherIcon: "" + property string launcherIconColor: "none" + property bool pinnedStatic: false + property bool inactiveIndicators: false + property bool groupApps: false + property string groupContextMenuMode: "extended" // "list", "extended" + property string groupClickAction: "cycle" // "cycle", "list" + property string groupIndicatorStyle: "dots" // "number", "dots" + property double deadOpacity: 0.6 + property real animationSpeed: 1.0 // Speed multiplier for hide/show animations (0.1 = slowest, 2.0 = fastest) + property bool sitOnFrame: false + property bool showDockIndicator: false + property int indicatorThickness: 3 + property string indicatorColor: "primary" + property real indicatorOpacity: 0.6 + } + + // network + property JsonObject network: JsonObject { + property bool bluetoothRssiPollingEnabled: false // Opt-in Bluetooth RSSI polling (uses bluetoothctl) + property int bluetoothRssiPollIntervalMs: 60000 // Polling interval in milliseconds for RSSI queries + property string networkPanelView: "wifi" + property string wifiDetailsViewMode: "grid" // "grid" or "list" + property string bluetoothDetailsViewMode: "grid" // "grid" or "list" + property bool bluetoothHideUnnamedDevices: false + property bool disableDiscoverability: false + property bool bluetoothAutoConnect: true + } + + // session menu + property JsonObject sessionMenu: JsonObject { + property bool enableCountdown: true + property int countdownDuration: 10000 + property string position: "center" + property bool showHeader: true + property bool showKeybinds: true + property bool largeButtonsStyle: true + property string largeButtonsLayout: "single-row" + property list powerOptions: [ + { + "action": "lock", + "enabled": true, + "keybind": "1" + }, + { + "action": "suspend", + "enabled": true, + "keybind": "2" + }, + { + "action": "hibernate", + "enabled": true, + "keybind": "3" + }, + { + "action": "reboot", + "enabled": true, + "keybind": "4" + }, + { + "action": "logout", + "enabled": true, + "keybind": "5" + }, + { + "action": "shutdown", + "enabled": true, + "keybind": "6" + }, + { + "action": "rebootToUefi", + "enabled": true, + "keybind": "7" + } + ] + } + + // notifications + property JsonObject notifications: JsonObject { + property bool enabled: true + property bool enableMarkdown: false + property string density: "default" // "default", "compact" + property list monitors: [] // holds notifications visibility per monitor + property string location: "top_right" + property bool overlayLayer: true + property real backgroundOpacity: 1.0 + property bool respectExpireTimeout: false + property int lowUrgencyDuration: 3 + property int normalUrgencyDuration: 8 + property int criticalUrgencyDuration: 15 + property bool clearDismissed: true + property JsonObject saveToHistory: JsonObject { + property bool low: true + property bool normal: true + property bool critical: true + } + property JsonObject sounds: JsonObject { + property bool enabled: false + property real volume: 0.5 + property bool separateSounds: false + property string criticalSoundFile: "" + property string normalSoundFile: "" + property string lowSoundFile: "" + property string excludedApps: "discord,firefox,chrome,chromium,edge" + } + property bool enableMediaToast: false + property bool enableKeyboardLayoutToast: true + property bool enableBatteryToast: true + } + + // on-screen display + property JsonObject osd: JsonObject { + property bool enabled: true + property string location: "top_right" + property int autoHideMs: 2000 + property bool overlayLayer: true + property real backgroundOpacity: 1.0 + property list enabledTypes: [OSD.Type.Volume, OSD.Type.InputVolume, OSD.Type.Brightness] + property list monitors: [] // holds osd visibility per monitor + } + + // audio + property JsonObject audio: JsonObject { + property int volumeStep: 5 + property bool volumeOverdrive: false + property int spectrumFrameRate: 30 + property string visualizerType: "linear" + property bool spectrumMirrored: true + property list mprisBlacklist: [] + property string preferredPlayer: "" + property bool volumeFeedback: false + property string volumeFeedbackSoundFile: "" + } + + // brightness + property JsonObject brightness: JsonObject { + property int brightnessStep: 5 + property bool enforceMinimum: true + property bool enableDdcSupport: false + property list backlightDeviceMappings: [] + // Format: [{ "output": "eDP-1", "device": "/sys/class/backlight/intel_backlight" }] + } + + property JsonObject colorSchemes: JsonObject { + property bool useWallpaperColors: false + property string predefinedScheme: "Noctalia (default)" + property bool darkMode: true + property string schedulingMode: "off" + property string manualSunrise: "06:30" + property string manualSunset: "18:30" + property string generationMethod: "tonal-spot" + property string monitorForColors: "" + property bool syncGsettings: true + } + + // templates toggles + property JsonObject templates: JsonObject { + property list activeTemplates: [] + // Format: [{ "id": "gtk", "enabled": true }, { "id": "qt", "enabled": true }, ...] + property bool enableUserTheming: false + } + + // night light + property JsonObject nightLight: JsonObject { + property bool enabled: false + property bool forced: false + property bool autoSchedule: true + property string nightTemp: "4000" + property string dayTemp: "6500" + property string manualSunrise: "06:30" + property string manualSunset: "18:30" + } + + // hooks + property JsonObject hooks: JsonObject { + property bool enabled: false + property string wallpaperChange: "" + property string darkModeChange: "" + property string screenLock: "" + property string screenUnlock: "" + property string performanceModeEnabled: "" + property string performanceModeDisabled: "" + property string startup: "" + property string session: "" + property string colorGeneration: "" + } + + // plugins + property JsonObject plugins: JsonObject { + property bool autoUpdate: false + property bool notifyUpdates: true + } + + // idle management + property JsonObject idle: JsonObject { + property bool enabled: false + property int screenOffTimeout: 600 // seconds, 0 = disabled + property int lockTimeout: 660 // seconds, 0 = disabled + property int suspendTimeout: 1800 // seconds, 0 = disabled + property int fadeDuration: 5 // seconds of fade-to-black before action fires + property string screenOffCommand: "" + property string lockCommand: "" + property string suspendCommand: "" + property string resumeScreenOffCommand: "" + property string resumeLockCommand: "" + property string resumeSuspendCommand: "" + property string customCommands: "[]" // JSON array of {timeout, command, resumeCommand} + } + + // desktop widgets + property JsonObject desktopWidgets: JsonObject { + property bool enabled: false + property bool overviewEnabled: true + property bool gridSnap: false + property bool gridSnapScale: false + property list monitorWidgets: [] + // Format: [{ "name": "DP-1", "widgets": [...] }, { "name": "HDMI-1", "widgets": [...] }] + } + } + + // ----------------------------------------------------- + // Preprocess paths by adding trailing "/" + function ensureTrailingSlash(path) { + return path.endsWith("/") ? path : path + "/"; + } + + // ----------------------------------------------------- + // Preprocess paths by expanding "~" to user's home directory + function preprocessPath(path) { + if (typeof path !== "string" || path === "") { + return path; + } + + // Expand "~" to user's home directory + if (path.startsWith("~/")) { + return Quickshell.env("HOME") + path.substring(1); + } else if (path === "~") { + return Quickshell.env("HOME"); + } + + return path; + } + + // ----------------------------------------------------- + // Get default value for a setting path (e.g., "general.scaleRatio" or "bar.position") + // Returns undefined if not found + function getDefaultValue(path) { + if (!root._defaultSettings) { + return undefined; + } + + var parts = path.split("."); + var current = root._defaultSettings; + + for (var i = 0; i < parts.length; i++) { + if (current === undefined || current === null) { + return undefined; + } + current = current[parts[i]]; + } + + return current; + } + + // ----------------------------------------------------- + // Compare current value with default value + // Returns true if values differ, false if they match or default is not found + function isValueChanged(path, currentValue) { + var defaultValue = getDefaultValue(path); + if (defaultValue === undefined) { + return false; // Can't compare if default not found + } + + // Deep comparison for objects and arrays + if (typeof currentValue === "object" && typeof defaultValue === "object") { + return JSON.stringify(currentValue) !== JSON.stringify(defaultValue); + } + + // Simple comparison for primitives + return currentValue !== defaultValue; + } + + // ----------------------------------------------------- + // Format default value for tooltip display + // Returns a human-readable string representation of the default value + function formatDefaultValueForTooltip(path) { + var defaultValue = getDefaultValue(path); + if (defaultValue === undefined) { + return ""; + } + + // Format based on type + if (typeof defaultValue === "boolean") { + return defaultValue ? "true" : "false"; + } else if (typeof defaultValue === "number") { + return defaultValue.toString(); + } else if (typeof defaultValue === "string") { + return defaultValue === "" ? "(empty)" : defaultValue; + } else if (Array.isArray(defaultValue)) { + return defaultValue.length === 0 ? "(empty)" : "[" + defaultValue.length + " items]"; + } else if (typeof defaultValue === "object") { + return "(object)"; + } + + return String(defaultValue); + } + + // ----------------------------------------------------- + // Helper to find a screen override entry by name in the array + // Format: [{ "name": "HDMI-A-1", "position": "left" }, ...] + // Note: QML's list is not a true JS array, so we check for .length instead of Array.isArray() + function _findScreenOverride(screenName) { + var overrides = data.bar.screenOverrides; + if (!screenName || !overrides || overrides.length === undefined) { + return null; + } + for (var i = 0; i < overrides.length; i++) { + if (overrides[i] && overrides[i].name === screenName) { + return overrides[i]; + } + } + return null; + } + + // Helper to find index of a screen override entry + function _findScreenOverrideIndex(screenName) { + var overrides = data.bar.screenOverrides; + if (!screenName || !overrides || overrides.length === undefined) { + return -1; + } + for (var i = 0; i < overrides.length; i++) { + if (overrides[i] && overrides[i].name === screenName) { + return i; + } + } + return -1; + } + + // ----------------------------------------------------- + // Check if a screen's overrides are enabled + // Returns true if enabled flag is true or undefined (backward compat) + // Returns false only if enabled is explicitly false + function isScreenOverrideEnabled(screenName) { + var override = _findScreenOverride(screenName); + if (!override) { + return false; + } + return override.enabled !== false; + } + + // ----------------------------------------------------- + // Get effective bar position for a screen (with inheritance) + // If the screen has a position override and overrides are enabled, use it; otherwise use global default + function getBarPositionForScreen(screenName) { + var override = _findScreenOverride(screenName); + if (override && override.enabled !== false && override.position !== undefined) { + return override.position; + } + return data.bar.position || "top"; + } + + // ----------------------------------------------------- + // Get effective bar widgets for a screen (with inheritance) + // If the screen has widget overrides and overrides are enabled, use them; otherwise use global defaults + function getBarWidgetsForScreen(screenName) { + var override = _findScreenOverride(screenName); + if (override && override.enabled !== false && override.widgets !== undefined) { + return override.widgets; + } + return data.bar.widgets; + } + + // ----------------------------------------------------- + // Get effective bar density for a screen (with inheritance) + // If the screen has a density override and overrides are enabled, use it; otherwise use global default + function getBarDensityForScreen(screenName) { + var override = _findScreenOverride(screenName); + if (override && override.enabled !== false && override.density !== undefined) { + return override.density; + } + return data.bar.density || "default"; + } + + // ----------------------------------------------------- + // Get effective bar display mode for a screen (with inheritance) + // If the screen has a displayMode override and overrides are enabled, use it; otherwise use global default + function getBarDisplayModeForScreen(screenName) { + var override = _findScreenOverride(screenName); + if (override && override.enabled !== false && override.displayMode !== undefined) { + return override.displayMode; + } + return data.bar.displayMode || "always_visible"; + } + + // ----------------------------------------------------- + // Check if a screen has any overrides, optionally for a specific property + function hasScreenOverride(screenName, property) { + var override = _findScreenOverride(screenName); + if (!override) { + return false; + } + if (property) { + return override[property] !== undefined; + } + // Check if screen has any override property (besides "name") + var keys = Object.keys(override); + return keys.length > 1 || (keys.length === 1 && keys[0] !== "name"); + } + + // ----------------------------------------------------- + // Get the screen override entry directly (for in-place modifications) + // Returns the actual entry object from the array, not a copy + function getScreenOverrideEntry(screenName) { + return _findScreenOverride(screenName); + } + + // ----------------------------------------------------- + // Set a per-screen override + function setScreenOverride(screenName, property, value) { + if (!screenName) + return; + + var overrides = JSON.parse(JSON.stringify(data.bar.screenOverrides || [])); + if (overrides.length === undefined) { + overrides = []; + } + + var index = -1; + for (var i = 0; i < overrides.length; i++) { + if (overrides[i] && overrides[i].name === screenName) { + index = i; + break; + } + } + + if (index === -1) { + // Create new entry + var newEntry = { + "name": screenName + }; + newEntry[property] = value; + overrides.push(newEntry); + } else { + // Update existing entry + overrides[index][property] = value; + } + data.bar.screenOverrides = overrides; + } + + // ----------------------------------------------------- + // Clear a per-screen override (revert to global default) + // If property is null, clears all overrides for that screen + function clearScreenOverride(screenName, property) { + if (!screenName) + return; + + var overrides = data.bar.screenOverrides; + if (!overrides || overrides.length === undefined) { + return; + } + + overrides = JSON.parse(JSON.stringify(overrides)); + + var index = -1; + for (var i = 0; i < overrides.length; i++) { + if (overrides[i] && overrides[i].name === screenName) { + index = i; + break; + } + } + + if (index === -1) { + return; + } + + if (property) { + delete overrides[index][property]; + // Remove screen entry if only "name" remains + var keys = Object.keys(overrides[index]); + if (keys.length <= 1 && (keys.length === 0 || keys[0] === "name")) { + overrides.splice(index, 1); + } + } else { + overrides.splice(index, 1); + } + data.bar.screenOverrides = overrides; + } + + // ----------------------------------------------------- + // Public function to trigger immediate settings saving + function saveImmediate() { + settingsFileView.writeAdapter(); + root.settingsSaved(); // Emit signal after saving + } + + // ----------------------------------------------------- + // Generate default settings: for reference only, not used by the shell + function generateDefaultSettings() { + try { + Logger.d("Settings", "Generating settings-default.json"); + + // Prepare a clean JSON + var plainAdapter = QtObj2JS.qtObjectToPlainObject(adapter); + var jsonData = JSON.stringify(plainAdapter, null, 2); + + var defaultPath = Quickshell.shellDir + "/Assets/settings-default.json"; + + Quickshell.execDetached(["sh", "-c", `cat > "${defaultPath}" << 'NOCTALIA_EOF'\n${jsonData}\nNOCTALIA_EOF`]); + } catch (error) { + Logger.e("Settings", "Failed to generate default settings file: " + error); + } + } + + // ----------------------------------------------------- + // Generate default widget settings: for reference only, not used by the shell + function generateWidgetDefaultSettings() { + try { + Logger.d("Settings", "Generating settings-widgets-default.json"); + + var output = { + "bar": QtObj2JS.qtObjectToPlainObject(BarWidgetRegistry.widgetMetadata), + "controlCenter": QtObj2JS.qtObjectToPlainObject(ControlCenterWidgetRegistry.widgetMetadata), + "desktop": QtObj2JS.qtObjectToPlainObject(DesktopWidgetRegistry.widgetMetadata) + }; + var jsonData = JSON.stringify(output, null, 2); + + var defaultPath = Quickshell.shellDir + "/Assets/settings-widgets-default.json"; + + Quickshell.execDetached(["sh", "-c", `cat > "${defaultPath}" << 'NOCTALIA_EOF'\n${jsonData}\nNOCTALIA_EOF`]); + } catch (error) { + Logger.e("Settings", "Failed to generate widget default settings file: " + error); + } + } + + // ----------------------------------------------------- + // Run versioned migrations using MigrationRegistry + // rawJson is the parsed JSON file content (before adapter filtering) + function runVersionedMigrations(rawJson) { + // Skip migrations on fresh installs (no prior settings file) + if (!rawJson || root.isFreshInstall) { + Logger.i("Settings", "Fresh install detected, skipping migrations"); + return; + } + + const currentVersion = adapter.settingsVersion; + const migrations = MigrationRegistry.migrations; + + Logger.i("Settings", "adapter.settingsVersion:", adapter.settingsVersion); + + // Get all migration versions and sort them + const versions = Object.keys(migrations).map(v => parseInt(v)).sort((a, b) => a - b); + + // Run migrations in order for versions newer than current + for (var i = 0; i < versions.length; i++) { + const version = versions[i]; + + if (currentVersion < version) { + // Create migration instance and run it + const migrationComponent = migrations[version]; + const migration = migrationComponent.createObject(root); + + if (migration && typeof migration.migrate === "function") { + const success = migration.migrate(adapter, Logger, rawJson); + if (!success) { + Logger.e("Settings", "Migration to v" + version + " failed"); + } + } else { + Logger.e("Settings", "Invalid migration for v" + version); + } + + // Clean up migration instance + if (migration) { + migration.destroy(); + } + } + } + } + + // ----------------------------------------------------- + // If the settings structure has changed, ensure + // backward compatibility by upgrading the settings + function upgradeSettings() { + // Wait for PluginService to finish loading plugins first + // This prevents deleting plugin widgets during reload before plugins are registered + if (!PluginService.initialized || !PluginService.pluginsFullyLoaded) { + Logger.d("Settings", "Plugins not fully loaded yet, deferring upgrade"); + Qt.callLater(upgradeSettings); + return; + } + + // Wait for BarWidgetRegistry to be ready + if (!BarWidgetRegistry.widgets || Object.keys(BarWidgetRegistry.widgets).length === 0) { + Logger.d("Settings", "BarWidgetRegistry not ready, deferring upgrade"); + Qt.callLater(upgradeSettings); + return; + } + + // ----------------- + const sections = ["left", "center", "right"]; + + // 1. remove any non existing bar widget type + var removedWidget = false; + for (var s = 0; s < sections.length; s++) { + const sectionName = sections[s]; + const widgets = adapter.bar.widgets[sectionName]; + // Iterate backward through the widgets array, so it does not break when removing a widget + for (var i = widgets.length - 1; i >= 0; i--) { + var widget = widgets[i]; + if (!BarWidgetRegistry.hasWidget(widget.id)) { + Logger.w(`Settings`, `!!! Deleted invalid bar widget ${widget.id} !!!`); + widgets.splice(i, 1); + removedWidget = true; + } + } + } + + // ----------------- + // 2. remove any non existing control center widget type + const ccSections = ["left", "right"]; + for (var s = 0; s < ccSections.length; s++) { + const sectionName = ccSections[s]; + const shortcuts = adapter.controlCenter.shortcuts[sectionName]; + for (var i = shortcuts.length - 1; i >= 0; i--) { + var shortcut = shortcuts[i]; + if (!ControlCenterWidgetRegistry.hasWidget(shortcut.id)) { + Logger.w(`Settings`, `!!! Deleted invalid control center widget ${shortcut.id} !!!`); + shortcuts.splice(i, 1); + removedWidget = true; + } + } + } + + // ----------------- + // 3. remove any non existing desktop widget type + const monitorWidgets = adapter.desktopWidgets.monitorWidgets; + for (var m = 0; m < monitorWidgets.length; m++) { + const monitor = monitorWidgets[m]; + if (!monitor.widgets) + continue; + for (var i = monitor.widgets.length - 1; i >= 0; i--) { + var desktopWidget = monitor.widgets[i]; + if (!DesktopWidgetRegistry.hasWidget(desktopWidget.id)) { + Logger.w(`Settings`, `!!! Deleted invalid desktop widget ${desktopWidget.id} !!!`); + monitor.widgets.splice(i, 1); + removedWidget = true; + } + } + } + + // ----------------- + // 4. upgrade user widget settings + for (var s = 0; s < sections.length; s++) { + const sectionName = sections[s]; + for (var i = 0; i < adapter.bar.widgets[sectionName].length; i++) { + var widget = adapter.bar.widgets[sectionName][i]; + + // Check if widget registry supports user settings, if it does not, then there is nothing to do + if (BarWidgetRegistry.widgetMetadata[widget.id] === undefined) { + continue; + } + + if (upgradeWidget(widget)) { + Logger.d("Settings", `Upgraded ${widget.id} widget:`, JSON.stringify(widget)); + } + } + } + } + + // ----------------------------------------------------- + // Function to clean up deprecated user/custom bar widgets settings + function upgradeWidget(widget) { + // Backup the widget definition before altering + const widgetBefore = JSON.stringify(widget); + + // Get all existing custom settings keys + const keys = Object.keys(BarWidgetRegistry.widgetMetadata[widget.id]); + + // Delete deprecated user settings from the wiget + for (const k of Object.keys(widget)) { + if (k === "id") { + continue; + } + if (!keys.includes(k)) { + delete widget[k]; + } + } + + // Inject missing default setting (metaData) from BarWidgetRegistry + for (var i = 0; i < keys.length; i++) { + const k = keys[i]; + if (k === "id") { + continue; + } + + if (widget[k] === undefined) { + widget[k] = BarWidgetRegistry.widgetMetadata[widget.id][k]; + } + } + + // Compare settings, to detect if something has been upgraded + const widgetAfter = JSON.stringify(widget); + return (widgetAfter !== widgetBefore); + } +} diff --git a/quickshell/compat/noctalia/Commons/ShellState.qml b/quickshell/compat/noctalia/Commons/ShellState.qml new file mode 100644 index 0000000..0b46139 --- /dev/null +++ b/quickshell/compat/noctalia/Commons/ShellState.qml @@ -0,0 +1,287 @@ +pragma Singleton + +import QtQuick +import Quickshell +import Quickshell.Io +import "../Helpers/QtObj2JS.js" as QtObj2JS +import qs.compat.noctalia.Services.Power +import qs.compat.noctalia.Services.System +import qs.compat.noctalia.Services.UI + +// Centralized shell state management for small cache files +Singleton { + id: root + + property string stateFile: "" + property bool isLoaded: false + + // State properties for different services + readonly property alias data: adapter + + // Signals for state changes + signal displayStateChanged + signal notificationsStateChanged + signal changelogStateChanged + signal colorSchemesListChanged + + Component.onCompleted: { + // Setup state file path (needs Settings to be available) + Qt.callLater(() => { + if (typeof Settings !== 'undefined' && Settings.cacheDir) { + stateFile = Settings.cacheDir + "shell-state.json"; + stateFileView.path = stateFile; + } + }); + } + + // FileView for shell state + FileView { + id: stateFileView + printErrors: false + watchChanges: false + + adapter: JsonAdapter { + id: adapter + + // CompositorService: display scales + property var display: ({}) + + // NotificationService: notification state + property var notificationsState: ({ + lastSeenTs: 0 + }) + + // UpdateService: changelog state + property var changelogState: ({ + lastSeenVersion: "" + }) + + // SchemeDownloader: color schemes list + property var colorSchemesList: ({ + schemes: [], + timestamp: 0 + }) + + // UI state: settings panel, etc. + property var ui: ({ + settingsSidebarExpanded: true + }) + + // Telemetry state + property var telemetry: ({ + instanceId: "" + }) + + // Launcher app usage counts + property var launcherUsage: ({}) + } + + onLoaded: { + root.isLoaded = true; + Logger.d("ShellState", "Loaded state file"); + } + + onLoadFailed: error => { + if (error === 2) { + // File doesn't exist, will be created on first write + root.isLoaded = true; + Logger.d("ShellState", "State file doesn't exist, will create on first write"); + } else { + Logger.e("ShellState", "Failed to load state file:", error); + root.isLoaded = true; + } + } + } + + // Launcher usage + function getLauncherUsageCount(key) { + const m = adapter.launcherUsage; + if (!m) + return 0; + const v = m[key]; + return typeof v === 'number' && isFinite(v) ? v : 0; + } + + function recordLauncherUsage(key) { + let counts = Object.assign({}, adapter.launcherUsage || {}); + counts[key] = getLauncherUsageCount(key) + 1; + adapter.launcherUsage = counts; + save(); + } + + // Migrate usage from one key to another, merging counts in a single save + function migrateLauncherUsage(fromKey, toKey) { + let counts = Object.assign({}, adapter.launcherUsage || {}); + const fromCount = typeof counts[fromKey] === 'number' && isFinite(counts[fromKey]) ? counts[fromKey] : 0; + const toCount = typeof counts[toKey] === 'number' && isFinite(counts[toKey]) ? counts[toKey] : 0; + counts[toKey] = toCount + fromCount; + delete counts[fromKey]; + adapter.launcherUsage = counts; + save(); + } + + // Debounced save timer + Timer { + id: saveTimer + interval: 500 + onTriggered: performSave() + } + + property bool saveQueued: false + + function save() { + saveQueued = true; + saveTimer.restart(); + } + + function performSave() { + if (!saveQueued || !stateFile) { + return; + } + + saveQueued = false; + + try { + // Ensure cache directory exists + Quickshell.execDetached(["mkdir", "-p", Settings.cacheDir]); + + Qt.callLater(() => { + try { + stateFileView.writeAdapter(); + Logger.d("ShellState", "Saved state file"); + } catch (writeError) { + Logger.e("ShellState", "Failed to write state file:", writeError); + } + }); + } catch (error) { + Logger.e("ShellState", "Failed to save state:", error); + } + } + + // Convenience functions for each service + + // Display state (CompositorService) + function setDisplay(displayData) { + adapter.display = displayData; + save(); + displayStateChanged(); + } + + function getDisplay() { + return adapter.display || {}; + } + + // Notifications state (NotificationService) + function setNotificationsState(stateData) { + adapter.notificationsState = stateData; + save(); + notificationsStateChanged(); + } + + function getNotificationsState() { + return adapter.notificationsState || { + lastSeenTs: 0 + }; + } + + // Changelog state (UpdateService) + function setChangelogState(stateData) { + adapter.changelogState = stateData; + save(); + changelogStateChanged(); + } + + function getChangelogState() { + return adapter.changelogState || { + lastSeenVersion: "" + }; + } + + // Color schemes list (SchemeDownloader) + function setColorSchemesList(listData) { + adapter.colorSchemesList = listData; + save(); + colorSchemesListChanged(); + } + + function getColorSchemesList() { + return adapter.colorSchemesList || { + schemes: [], + timestamp: 0 + }; + } + + // UI state + function setUiState(stateData) { + adapter.ui = stateData; + save(); + } + + function getUiState() { + return adapter.ui || { + settingsSidebarExpanded: true + }; + } + + function setSettingsSidebarExpanded(expanded) { + let uiState = getUiState(); + uiState.settingsSidebarExpanded = expanded; + setUiState(uiState); + } + + function getSettingsSidebarExpanded() { + return getUiState().settingsSidebarExpanded !== false; // default to true + } + + // Telemetry state + function setTelemetryState(stateData) { + adapter.telemetry = stateData; + save(); + } + + function getTelemetryState() { + return adapter.telemetry || { + instanceId: "" + }; + } + + function getTelemetryInstanceId() { + return getTelemetryState().instanceId || ""; + } + + function setTelemetryInstanceId(instanceId) { + let state = getTelemetryState(); + state.instanceId = instanceId; + setTelemetryState(state); + } + + // ----------------------------------------------------- + function buildStateSnapshot() { + try { + const settingsData = QtObj2JS.qtObjectToPlainObject(Settings.data); + const shellStateData = ShellState?.data ? QtObj2JS.qtObjectToPlainObject(ShellState.data) || {} : {}; + + return { + settings: settingsData, + state: { + doNotDisturb: NotificationService.doNotDisturb, + noctaliaPerformanceMode: PowerProfileService.noctaliaPerformanceMode, + barVisible: BarService.isVisible, + openedPanel: PanelService.openedPanel?.objectName || "", + lockScreenActive: PanelService.lockScreen?.active || false, + wallpapers: WallpaperService.getWallpapersEffectiveMap(), + desktopWidgetsEditMode: DesktopWidgetRegistry.editMode || false, + // ------------- + display: shellStateData.display || {}, + notificationsState: shellStateData.notificationsState || {}, + changelogState: shellStateData.changelogState || {}, + colorSchemesList: shellStateData.colorSchemesList || {}, + ui: shellStateData.ui || {} + } + }; + } catch (error) { + Logger.e("Settings", "Failed to build state snapshot:", error); + return null; + } + } +} diff --git a/quickshell/compat/noctalia/Commons/Style.qml b/quickshell/compat/noctalia/Commons/Style.qml new file mode 100644 index 0000000..afe1876 --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Style.qml @@ -0,0 +1,203 @@ +pragma Singleton + +import QtQuick +import Quickshell +import qs.compat.noctalia.Services.Power +import "../../../theme" as G +import "../../../core" as Core + +Singleton { + id: root + + // glassMxrph: radii, bar sizes, animation and panel opacity follow the + // glassMxrph theme so Noctalia plugins match the shell. + readonly property real glassRadiusRatio: G.Theme.radius / 20 + readonly property real glassBarHeight: Core.BarDrawers.height + readonly property real glassCapsuleHeight: Core.ModuleRegistry.pillHeight + + // Font size + readonly property real fontSizeXXS: 8 + readonly property real fontSizeXS: 9 + readonly property real fontSizeS: 10 + readonly property real fontSizeM: 11 + readonly property real fontSizeL: 13 + readonly property real fontSizeXL: 16 + readonly property real fontSizeXXL: 18 + readonly property real fontSizeXXXL: 24 + + // Font weight + readonly property int fontWeightRegular: 400 + readonly property int fontWeightMedium: 500 + readonly property int fontWeightSemiBold: 600 + readonly property int fontWeightBold: 700 + + // Container Radii: major layout sections (sidebars, cards, content panels) + readonly property int radiusXXXS: Math.round(3 * root.glassRadiusRatio) + readonly property int radiusXXS: Math.round(4 * root.glassRadiusRatio) + readonly property int radiusXS: Math.round(8 * root.glassRadiusRatio) + readonly property int radiusS: Math.round(12 * root.glassRadiusRatio) + readonly property int radiusM: Math.round(16 * root.glassRadiusRatio) + readonly property int radiusL: Math.round(20 * root.glassRadiusRatio) + + // Input radii: interactive elements (buttons, toggles, text fields) + readonly property int iRadiusXXXS: Math.round(3 * root.glassRadiusRatio) + readonly property int iRadiusXXS: Math.round(4 * root.glassRadiusRatio) + readonly property int iRadiusXS: Math.round(8 * root.glassRadiusRatio) + readonly property int iRadiusS: Math.round(12 * root.glassRadiusRatio) + readonly property int iRadiusM: Math.round(16 * root.glassRadiusRatio) + readonly property int iRadiusL: Math.round(20 * root.glassRadiusRatio) + + readonly property int screenRadius: Math.round(20 * Settings.data.general.screenRadiusRatio) + + // Border + readonly property int borderS: Math.max(1, Math.round(1 * uiScaleRatio)) + readonly property int borderM: Math.max(1, Math.round(2 * uiScaleRatio)) + readonly property int borderL: Math.max(1, Math.round(3 * uiScaleRatio)) + + // Margins (for margins and spacing) + readonly property int marginXXXS: Math.round(1 * uiScaleRatio) + readonly property int marginXXS: Math.round(2 * uiScaleRatio) + readonly property int marginXS: Math.round(4 * uiScaleRatio) + readonly property int marginS: Math.round(6 * uiScaleRatio) + readonly property int marginM: Math.round(9 * uiScaleRatio) + readonly property int marginL: Math.round(13 * uiScaleRatio) + readonly property int marginXL: Math.round(18 * uiScaleRatio) + + // Double margins, for proper container sizing only (e.g. height: id.implicitHeight + Style.margin2M) + readonly property int margin2XXXS: marginXXXS * 2 + readonly property int margin2XXS: marginXXS * 2 + readonly property int margin2XS: marginXS * 2 + readonly property int margin2S: marginS * 2 + readonly property int margin2M: marginM * 2 + readonly property int margin2L: marginL * 2 + readonly property int margin2XL: marginXL * 2 + + // Opacity + readonly property real opacityNone: 0.0 + readonly property real opacityLight: 0.25 + readonly property real opacityMedium: 0.5 + readonly property real opacityHeavy: 0.75 + readonly property real opacityAlmost: 0.95 + readonly property real opacityFull: 1.0 + + readonly property real effectivePanelOpacity: G.Theme.glassOpacity + readonly property real effectiveBarOpacity: G.Theme.glassOpacity + + // Shadows + readonly property real shadowOpacity: 0.85 + readonly property real shadowBlur: 1.0 + readonly property int shadowBlurMax: 22 + readonly property real shadowHorizontalOffset: Settings.data.general.shadowOffsetX + readonly property real shadowVerticalOffset: Settings.data.general.shadowOffsetY + + // Animation duration (ms) + readonly property int animationFaster: Math.round(G.Theme.duration * 0.35) + readonly property int animationFast: Math.round(G.Theme.duration * 0.7) + readonly property int animationNormal: Math.round(G.Theme.duration * 1.3) + readonly property int animationSlow: Math.round(G.Theme.duration * 2) + readonly property int animationSlowest: Math.round(G.Theme.duration * 3.3) + + // Delays + readonly property int tooltipDelay: 300 + readonly property int tooltipDelayLong: 1200 + readonly property int pillDelay: 500 + + // Widgets base size + readonly property real baseWidgetSize: 33 + readonly property real sliderWidth: 200 + + readonly property real uiScaleRatio: 1.0 + + // Bar Height + readonly property real barHeight: glassBarHeight + readonly property real capsuleHeight: glassCapsuleHeight + readonly property real _barBaseFontSize: 12 + readonly property real barFontSize: 12 + + readonly property color capsuleColor: "transparent" + + readonly property color capsuleBorderColor: "transparent" + readonly property int capsuleBorderWidth: 0 + + readonly property color boxBorderColor: Color.mOutline + + // Pixel-perfect utility for centering content without subpixel positioning + function pixelAlignCenter(containerSize, contentSize) { + return Math.round((containerSize - contentSize) / 2); + } + + // Ensures a number is always odd (rounds down to nearest odd) + function toOdd(n) { + return Math.floor(n / 2) * 2 + 1; + } + + // Ensures a number is always even (rounds down to nearest even) + function toEven(n) { + return Math.floor(n / 2) * 2; + } + + // Get bar height for a specific density and orientation + function getBarHeightForDensity(density, isVertical) { + let h; + switch (density) { + case "mini": + h = isVertical ? 23 : 21; + break; + case "compact": + h = isVertical ? 27 : 25; + break; + case "comfortable": + h = isVertical ? 39 : 37; + break; + case "spacious": + h = isVertical ? 49 : 47; + break; + default: + case "default": + h = isVertical ? 33 : 31; + } + return toOdd(h); + } + + // Get capsule height for a specific density and bar height + function getCapsuleHeightForDensity(density, barHeight) { + let h; + switch (density) { + case "mini": + h = Math.round(barHeight * 0.90); + break; + case "compact": + h = Math.round(barHeight * 0.85); + break; + case "comfortable": + h = Math.round(barHeight * 0.75); + break; + case "spacious": + h = Math.round(barHeight * 0.65); + break; + default: + h = Math.round(barHeight * 0.82); + break; + } + return toOdd(h); + } + + // Get bar font size for a specific bar height, capsule height, and orientation + function getBarFontSizeForDensity(barHeight, capsuleHeight, isVertical) { + const baseFontSize = Math.max(1, (barHeight / capsuleHeight) * Style.fontSizeXXS); + return isVertical ? baseFontSize * 0.9 * Settings.data.bar.fontScale : baseFontSize * Settings.data.bar.fontScale; + } + + // Convenience functions for per-screen bar sizing + function getBarHeightForScreen(screenName) { + return glassBarHeight; + } + + function getCapsuleHeightForScreen(screenName) { + return glassCapsuleHeight; + } + + function getBarFontSizeForScreen(screenName) { + return barFontSize; + } +} diff --git a/quickshell/compat/noctalia/Commons/ThemeIcons.qml b/quickshell/compat/noctalia/Commons/ThemeIcons.qml new file mode 100644 index 0000000..aa0e4d8 --- /dev/null +++ b/quickshell/compat/noctalia/Commons/ThemeIcons.qml @@ -0,0 +1,289 @@ +pragma Singleton + +import QtQuick +import Quickshell +import qs.compat.noctalia.Commons + +Singleton { + id: root + + property real scoreThreshold: 0.2 + + // Manual overrides for tricky apps + property var substitutions: ({ + "code-url-handler": "visual-studio-code", + "Code": "visual-studio-code", + "gnome-tweaks": "org.gnome.tweaks", + "pavucontrol-qt": "pavucontrol", + "wps": "wps-office2019-kprometheus", + "wpsoffice": "wps-office2019-kprometheus", + "footclient": "foot" + }) + + // Dynamic fixups + property var regexSubstitutions: [ + { + "regex": /^steam_app_(\d+)$/, + "replace": "steam_icon_$1" + }, + { + "regex": /Minecraft.*/, + "replace": "minecraft-launcher" + }, + { + "regex": /.*polkit.*/, + "replace": "system-lock-screen" + }, + { + "regex": /gcr.prompter/, + "replace": "system-lock-screen" + } + ] + + property list entryList: [] + property var preppedNames: [] + property var preppedIcons: [] + property var preppedIds: [] + + Component.onCompleted: refreshEntries() + + Connections { + target: DesktopEntries.applications + function onValuesChanged() { + refreshEntries(); + } + } + + function refreshEntries() { + if (typeof DesktopEntries === 'undefined') + return; + + const values = Array.from(DesktopEntries.applications.values); + if (values) { + entryList = values.sort((a, b) => a.name.localeCompare(b.name)); + updatePreppedData(); + } + } + + function updatePreppedData() { + if (typeof FuzzySort === 'undefined') + return; + + const list = Array.from(entryList); + preppedNames = list.map(a => ({ + name: FuzzySort.prepare(`${a.name} `), + entry: a + })); + preppedIcons = list.map(a => ({ + name: FuzzySort.prepare(`${a.icon} `), + entry: a + })); + preppedIds = list.map(a => ({ + name: FuzzySort.prepare(`${a.id} `), + entry: a + })); + } + + function iconForAppId(appId, fallbackName) { + const fallback = fallbackName || "application-x-executable"; + if (!appId) + return iconFromName(fallback, fallback); + + const entry = findAppEntry(appId); + if (entry) { + return iconFromName(entry.icon, fallback); + } + + return iconFromName(appId, fallback); + } + + // Robust lookup strategy + function findAppEntry(str) { + if (!str || str.length === 0) + return null; + + let result = null; + + if (result = checkHeuristic(str)) + return result; + if (result = checkSubstitutions(str)) + return result; + if (result = checkRegex(str)) + return result; + if (result = checkSimpleTransforms(str)) + return result; + if (result = checkFuzzySearch(str)) + return result; + if (result = checkCleanMatch(str)) + return result; + + return null; + } + + function iconFromName(iconName, fallbackName) { + const fallback = fallbackName || "application-x-executable"; + try { + if (iconName && typeof Quickshell !== 'undefined' && Quickshell.iconPath) { + const p = Quickshell.iconPath(iconName, fallback); + if (p && p !== "") + return p; + } + } catch (e) {} + + try { + return Quickshell.iconPath ? (Quickshell.iconPath(fallback, true) || "") : ""; + } catch (e2) { + return ""; + } + } + + function distroLogoPath() { + try { + return (typeof OSInfo !== 'undefined' && OSInfo.distroIconPath) ? OSInfo.distroIconPath : ""; + } catch (e) { + return ""; + } + } + + // --- Lookup Helpers --- + + function checkHeuristic(str) { + if (typeof DesktopEntries !== 'undefined' && DesktopEntries.heuristicLookup) { + const entry = DesktopEntries.heuristicLookup(str); + if (entry) + return entry; + } + return null; + } + + function checkSubstitutions(str) { + let effectiveStr = substitutions[str]; + if (!effectiveStr) + effectiveStr = substitutions[str.toLowerCase()]; + + if (effectiveStr && effectiveStr !== str) { + return findAppEntry(effectiveStr); + } + return null; + } + + function checkRegex(str) { + for (let i = 0; i < regexSubstitutions.length; i++) { + const sub = regexSubstitutions[i]; + const replaced = str.replace(sub.regex, sub.replace); + if (replaced !== str) { + return findAppEntry(replaced); + } + } + return null; + } + + function checkSimpleTransforms(str) { + if (typeof DesktopEntries === 'undefined' || !DesktopEntries.byId) + return null; + + const lower = str.toLowerCase(); + + const variants = [str, lower, getFromReverseDomain(str), getFromReverseDomain(str)?.toLowerCase(), normalizeWithHyphens(str), str.replace(/_/g, '-').toLowerCase(), str.replace(/-/g, '_').toLowerCase()]; + + for (let i = 0; i < variants.length; i++) { + const variant = variants[i]; + if (variant) { + const entry = DesktopEntries.byId(variant); + if (entry) + return entry; + } + } + return null; + } + + function checkFuzzySearch(str) { + if (typeof FuzzySort === 'undefined') + return null; + + // Check filenames (IDs) first + if (preppedIds.length > 0) { + let results = fuzzyQuery(str, preppedIds); + if (results.length === 0) { + const underscored = str.replace(/-/g, '_').toLowerCase(); + if (underscored !== str) + results = fuzzyQuery(underscored, preppedIds); + } + if (results.length > 0) + return results[0]; + } + + // Then icons + if (preppedIcons.length > 0) { + const results = fuzzyQuery(str, preppedIcons); + if (results.length > 0) + return results[0]; + } + + // Then names + if (preppedNames.length > 0) { + const results = fuzzyQuery(str, preppedNames); + if (results.length > 0) + return results[0]; + } + + return null; + } + + function checkCleanMatch(str) { + if (!str || str.length <= 3) + return null; + if (typeof DesktopEntries === 'undefined' || !DesktopEntries.byId) + return null; + + // Aggressive fallback: strip all separators + const cleanStr = str.toLowerCase().replace(/[\.\-_]/g, ''); + const list = Array.from(entryList); + + for (let i = 0; i < list.length; i++) { + const entry = list[i]; + const cleanId = (entry.id || "").toLowerCase().replace(/[\.\-_]/g, ''); + if (cleanId.includes(cleanStr) || cleanStr.includes(cleanId)) { + return entry; + } + } + return null; + } + + function fuzzyQuery(search, preppedData) { + if (!search || !preppedData || preppedData.length === 0) + return []; + return FuzzySort.go(search, preppedData, { + all: true, + key: "name" + }).map(r => r.obj.entry); + } + + function iconExists(iconName) { + if (!iconName || iconName.length === 0) + return false; + if (iconName.startsWith("/")) + return true; + + const path = Quickshell.iconPath(iconName, true); + return path && path.length > 0 && !path.includes("image-missing"); + } + + function getFromReverseDomain(str) { + if (!str) + return ""; + return str.split('.').slice(-1)[0]; + } + + function normalizeWithHyphens(str) { + if (!str) + return ""; + return str.toLowerCase().replace(/\s+/g, "-"); + } + + // Deprecated shim + function guessIcon(str) { + const entry = findAppEntry(str); + return entry ? entry.icon : "image-missing"; + } +} diff --git a/quickshell/compat/noctalia/Commons/Time.qml b/quickshell/compat/noctalia/Commons/Time.qml new file mode 100644 index 0000000..c403246 --- /dev/null +++ b/quickshell/compat/noctalia/Commons/Time.qml @@ -0,0 +1,232 @@ +pragma Singleton +import QtQuick + +import Quickshell +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Services.System + +Singleton { + id: root + + // Current date + property var now: new Date() + + // Unix timestamp of the last update + property real _lastUpdateTs: Date.now() + + // Signal emitted when a significant time jump is detected (e.g. system resume) + signal resumed + + // Returns a Unix Timestamp (in seconds) + readonly property int timestamp: { + return Math.floor(root.now / 1000); + } + + // Timer state (for countdown/stopwatch) + property bool timerRunning: false + property bool timerStopwatchMode: false + property int timerRemainingSeconds: 0 + property int timerTotalSeconds: 0 + property int timerElapsedSeconds: 0 + property bool timerSoundPlaying: false + property int timerStartTimestamp: 0 // Unix timestamp when timer was started + property int timerPausedAt: 0 // Value when paused (for resuming) + + Timer { + id: updateTimer + interval: 1000 + repeat: true + running: true + triggeredOnStart: false + onTriggered: { + var newTime = new Date(); + var currentTs = newTime.getTime(); + + // Detect time jump (e.g. system resume) - threshold: 5 seconds + if (currentTs - root._lastUpdateTs > 5000) { + Logger.i("Time", "Time jump detected (" + Math.round((currentTs - root._lastUpdateTs) / 1000) + "s) - likely system resume"); + root.resumed(); + } + root._lastUpdateTs = currentTs; + + root.now = newTime; + + // Update timer if running + if (root.timerRunning && root.timerStartTimestamp > 0) { + const elapsedSinceStart = root.timestamp - root.timerStartTimestamp; + + if (root.timerStopwatchMode) { + root.timerElapsedSeconds = root.timerPausedAt + elapsedSinceStart; + } else { + root.timerRemainingSeconds = root.timerTotalSeconds - elapsedSinceStart; + if (root.timerRemainingSeconds <= 0) { + root.timerOnFinished(); + } + } + } + + // Adjust next interval to sync with the start of the next second + var msIntoSecond = newTime.getMilliseconds(); + if (msIntoSecond > 100) { + // If we're more than 100ms into the second, adjust for next time + updateTimer.interval = 1000 - msIntoSecond + 10; // +10ms buffer + updateTimer.restart(); + } else { + updateTimer.interval = 1000; + } + } + } + + Component.onCompleted: { + // Start by syncing to the next second boundary + var now = new Date(); + var msUntilNextSecond = 1000 - now.getMilliseconds(); + updateTimer.interval = msUntilNextSecond + 10; // +10ms buffer + updateTimer.restart(); + } + + // Formats a Date object into a YYYYMMDD-HHMMSS string. + function getFormattedTimestamp(date) { + if (!date) { + date = new Date(); + } + const year = date.getFullYear(); + + // getMonth() is zero-based, so we add 1 + const month = String(date.getMonth() + 1).padStart(2, '0'); + const day = String(date.getDate()).padStart(2, '0'); + + const hours = String(date.getHours()).padStart(2, '0'); + const minutes = String(date.getMinutes()).padStart(2, '0'); + const seconds = String(date.getSeconds()).padStart(2, '0'); + + return `${year}${month}${day}-${hours}${minutes}${seconds}`; + } + + // Format an easy to read approximate duration ex: 4h 32m + // Used to display the time remaining on the Battery widget, computer uptime, etc.. + function formatVagueHumanReadableDuration(totalSeconds) { + if (typeof totalSeconds !== 'number' || totalSeconds < 0) { + return '0s'; + } + + // Floor the input to handle decimal seconds + totalSeconds = Math.floor(totalSeconds); + + const days = Math.floor(totalSeconds / 86400); + const hours = Math.floor((totalSeconds % 86400) / 3600); + const minutes = Math.floor((totalSeconds % 3600) / 60); + const seconds = totalSeconds % 60; + + const parts = []; + if (days) + parts.push(`${days}d`); + if (hours) + parts.push(`${hours}h`); + if (minutes) + parts.push(`${minutes}m`); + + // Only show seconds if no hours and no minutes + if (!hours && !minutes) { + parts.push(`${seconds}s`); + } + + return parts.join(' '); + } + + // Format a date into + function formatRelativeTime(date) { + if (!date) + return ""; + const diff = Date.now() - date.getTime(); + if (diff < 60000) + return I18n.tr("notifications.time.now"); + if (diff < 120000) + return I18n.tr("notifications.time.diff-m"); + if (diff < 3600000) + return I18n.tr("notifications.time.diff-mm", { + "diff": Math.floor(diff / 60000) + }); + if (diff < 7200000) + return I18n.tr("notifications.time.diff-h"); + if (diff < 86400000) + return I18n.tr("notifications.time.diff-hh", { + "diff": Math.floor(diff / 3600000) + }); + if (diff < 172800000) + return I18n.tr("notifications.time.diff-d"); + return I18n.tr("notifications.time.diff-dd", { + "diff": Math.floor(diff / 86400000) + }); + } + + // Timer functions + function timerStart() { + if (root.timerStopwatchMode) { + root.timerRunning = true; + root.timerStartTimestamp = root.timestamp; + root.timerPausedAt = root.timerElapsedSeconds; + } else { + if (root.timerRemainingSeconds <= 0) { + return; + } + root.timerRunning = true; + root.timerTotalSeconds = root.timerRemainingSeconds; + root.timerStartTimestamp = root.timestamp; + root.timerPausedAt = 0; + } + } + + function timerPause() { + if (root.timerRunning) { + // Calculate and set remainingSeconds BEFORE changing timerRunning + // This ensures the UI sees the correct value when it reacts to timerRunning changing + if (root.timerStopwatchMode) { + root.timerPausedAt = root.timerElapsedSeconds; + } else { + // Calculate remaining seconds at the exact moment of pause + // Use current time directly to avoid stale timestamp issues + const currentTimestamp = Math.floor(Date.now() / 1000); + const elapsedSinceStart = currentTimestamp - root.timerStartTimestamp; + const currentRemaining = root.timerTotalSeconds - elapsedSinceStart; + root.timerPausedAt = Math.max(0, currentRemaining); + + // CRITICAL: Update timerRemainingSeconds to the paused value BEFORE changing timerRunning + // This ensures UI sees correct value when it reacts to timerRunning change + root.timerRemainingSeconds = root.timerPausedAt; + } + } + root.timerRunning = false; + root.timerStartTimestamp = 0; + // Stop any repeating notification sound when pausing + SoundService.stopSound("alarm-beep.wav"); + root.timerSoundPlaying = false; + } + + function timerReset() { + root.timerRunning = false; + root.timerStartTimestamp = 0; + if (root.timerStopwatchMode) { + root.timerElapsedSeconds = 0; + root.timerPausedAt = 0; + } else { + root.timerRemainingSeconds = 0; + root.timerTotalSeconds = 0; + root.timerPausedAt = 0; + } + // Stop any repeating notification sound + SoundService.stopSound("alarm-beep.wav"); + root.timerSoundPlaying = false; + } + + function timerOnFinished() { + root.timerRunning = false; + root.timerRemainingSeconds = 0; + // Play notification sound with repeat at lower volume + root.timerSoundPlaying = true; + SoundService.playSound("alarm-beep.wav", { + repeat: true, + volume: 0.3 + }); + } +} diff --git a/quickshell/compat/noctalia/Helpers/AdvancedMath.js b/quickshell/compat/noctalia/Helpers/AdvancedMath.js new file mode 100644 index 0000000..d7bc367 --- /dev/null +++ b/quickshell/compat/noctalia/Helpers/AdvancedMath.js @@ -0,0 +1,161 @@ +// AdvancedMath.js - Lightweight math library for Noctalia Calculator +// Provides advanced mathematical functions beyond basic arithmetic + +// Helper function to convert degrees to radians +function toRadians(degrees) { + return degrees * (Math.PI / 180); +} + +// Helper function to convert radians to degrees +function toDegrees(radians) { + return radians * (180 / Math.PI); +} + +// Constants +var constants = { + PI: Math.PI, + E: Math.E, + LN2: Math.LN2, + LN10: Math.LN10, + LOG2E: Math.LOG2E, + LOG10E: Math.LOG10E, + SQRT1_2: Math.SQRT1_2, + SQRT2: Math.SQRT2 +}; + +// Safe evaluation function that handles advanced math +function evaluate(expression) { + try { + // Fixes decimal arithmetic + var cleanExpr = expression.replace(/\s+/g, '').toLowerCase(); + + // Allows numbers (including decimals), basic operators, and explicitly permitted math terms only + var safeRegex = /^(\d*\.?\d+|[+\-*/()^%,]|sin|cos|tan|asin|acos|atan|atan2|sinh|cosh|tanh|asinh|acosh|atanh|log|ln|exp|pow|sqrt|cbrt|abs|floor|ceil|round|trunc|min|max|random|pi|e|sind|cosd|tand)+$/; + + if (!safeRegex.test(cleanExpr)) { + throw new Error("Invalid characters or unauthorized functions in expression"); + } + + // Replace mathematical constants (Original Structure) + var processed = cleanExpr + .replace(/\bpi\b/gi, Math.PI) + .replace(/\be\b/gi, Math.E); + + // Replace function calls with Math object equivalents + processed = processed + // Trigonometric functions + .replace(/\bsin\s*\(/g, 'Math.sin(') + .replace(/\bcos\s*\(/g, 'Math.cos(') + .replace(/\btan\s*\(/g, 'Math.tan(') + .replace(/\basin\s*\(/g, 'Math.asin(') + .replace(/\bacos\s*\(/g, 'Math.acos(') + .replace(/\batan\s*\(/g, 'Math.atan(') + .replace(/\batan2\s*\(/g, 'Math.atan2(') + + // Hyperbolic functions + .replace(/\bsinh\s*\(/g, 'Math.sinh(') + .replace(/\bcosh\s*\(/g, 'Math.cosh(') + .replace(/\btanh\s*\(/g, 'Math.tanh(') + .replace(/\basinh\s*\(/g, 'Math.asinh(') + .replace(/\bacosh\s*\(/g, 'Math.acosh(') + .replace(/\batanh\s*\(/g, 'Math.atanh(') + + // Logarithmic and exponential functions + .replace(/\blog\s*\(/g, 'Math.log10(') + .replace(/\bln\s*\(/g, 'Math.log(') + .replace(/\bexp\s*\(/g, 'Math.exp(') + .replace(/\bpow\s*\(/g, 'Math.pow(') + + // Root functions + .replace(/\bsqrt\s*\(/g, 'Math.sqrt(') + .replace(/\bcbrt\s*\(/g, 'Math.cbrt(') + + // Rounding and absolute + .replace(/\babs\s*\(/g, 'Math.abs(') + .replace(/\bfloor\s*\(/g, 'Math.floor(') + .replace(/\bceil\s*\(/g, 'Math.ceil(') + .replace(/\bround\s*\(/g, 'Math.round(') + .replace(/\btrunc\s*\(/g, 'Math.trunc(') + + // Min/Max + .replace(/\bmin\s*\(/g, 'Math.min(') + .replace(/\bmax\s*\(/g, 'Math.max(') + + // Random + .replace(/\brandom\s*\(\s*\)/g, 'Math.random()'); + + // Handle degree versions of trig functions + processed = processed + .replace(/\bsind\s*\(/g, '(function(x) { return Math.sin(' + (Math.PI / 180) + ' * x); })(') + .replace(/\bcosd\s*\(/g, '(function(x) { return Math.cos(' + (Math.PI / 180) + ' * x); })(') + .replace(/\btand\s*\(/g, '(function(x) { return Math.tan(' + (Math.PI / 180) + ' * x); })('); + + // Handle ^ for exponentiation: convert 2^3 to Math.pow(2,3) + processed = processed.replace(/([\d.]+|\))\^([\d.]+|\([^)]*\))/g, 'Math.pow($1,$2)'); + + // Replacing eval() with a scoped function constructor + // This is safe because the strict whitelist guarantees only math reaches this point + var result = new Function('return ' + processed)(); + + if (!isFinite(result) || isNaN(result)) { + throw new Error("Invalid result"); + } + + return result; + } catch (error) { + throw new Error("Evaluation failed: " + error.message); + } +} + +// Format result for display +function formatResult(result) { + if (Number.isInteger(result)) { + return result.toString(); + } + + // Handle very large or very small numbers + if (Math.abs(result) >= 1e15 || (Math.abs(result) < 1e-6 && result !== 0)) { + return result.toExponential(6); + } + + // Normal decimal formatting + return parseFloat(result.toFixed(10)).toString(); +} + +// Get list of available functions for help +function getAvailableFunctions() { + return [ + // Basic arithmetic: +, -, *, /, %, ^, () + + // Trigonometric functions + "sin(x), cos(x), tan(x) - trigonometric functions (radians)", + "sind(x), cosd(x), tand(x) - trigonometric functions (degrees)", + "asin(x), acos(x), atan(x) - inverse trigonometric", + "atan2(y, x) - two-argument arctangent", + + // Hyperbolic functions + "sinh(x), cosh(x), tanh(x) - hyperbolic functions", + "asinh(x), acosh(x), atanh(x) - inverse hyperbolic", + + // Logarithmic and exponential + "log(x) - base 10 logarithm", + "ln(x) - natural logarithm", + "exp(x) - e^x", + "pow(x, y) - x^y", + + // Root functions + "sqrt(x) - square root", + "cbrt(x) - cube root", + + // Rounding and absolute + "abs(x) - absolute value", + "floor(x), ceil(x), round(x), trunc(x)", + + // Min/Max/Random + "min(a, b, ...), max(a, b, ...)", + "random() - random number 0-1", + + // Constants + "pi, e - mathematical constants" + ]; +} diff --git a/quickshell/compat/noctalia/Helpers/BluetoothUtils.js b/quickshell/compat/noctalia/Helpers/BluetoothUtils.js new file mode 100644 index 0000000..879b275 --- /dev/null +++ b/quickshell/compat/noctalia/Helpers/BluetoothUtils.js @@ -0,0 +1,127 @@ +.pragma library + +// Address helpers +var macFromDevice = (dev) => { + if (!dev) return ""; + if (dev.address && dev.address.length > 0) return dev.address; + if (dev.nativePath && dev.nativePath.indexOf("/dev_") !== -1) + return dev.nativePath.split("dev_")[1].split("_").join(":"); + return ""; +}; + +var deviceKey = (dev) => { + if (!dev) return ""; + if (dev.address && dev.address.length > 0) return dev.address.toUpperCase(); + if (dev.nativePath && dev.nativePath.length > 0) return dev.nativePath; + if (dev.devicePath && dev.devicePath.length > 0) return dev.devicePath; + return (dev.name || dev.deviceName || "") + "|" + (dev.icon || ""); +}; + +var dedupeDevices = (list) => { + if (!list || list.length === 0) return []; + var seen = ({}); + var out = []; + for (var i = 0; i < list.length; ++i) { + var d = list[i]; + if (!d) continue; + var k = deviceKey(d); + if (k && !seen[k]) { seen[k] = true; out.push(d); } + } + return out; +}; + +// RSSI parsing +var parseRssiOutput = (text) => { + try { + text = text || ""; + var mParen = text.match(/\(\s*(-?\d+)\s*(?:d?b?m?)?\s*\)/i); + if (mParen && mParen.length > 1) return Number(mParen[1]); + var mDec = text.match(/RSSI:\s*(-?\d+)/i); + if (mDec && mDec.length > 1) return Number(mDec[1]); + var mHex = text.match(/RSSI:\s*0x([0-9a-fA-F]+)/i); + if (mHex && mHex.length > 1) { + var v = parseInt(mHex[1], 16); + if (v >= 0x80000000) v = v - 0x100000000; // 32-bit two's complement + else if (v >= 0x8000) v = v - 0x10000; // 16-bit + else if (v >= 0x80) v = v - 0x100; // 8-bit + return v; + } + } catch (e) {} + return null; +}; + +var dbmToPercent = (dbm) => { + if (dbm === null || dbm === undefined || isNaN(dbm)) return null; + // Clamp simple linear map roughly from -100..0 dBm to 0..100% + var pct = Math.round((Number(dbm) + 100) * 2); + if (isNaN(pct)) return null; + return Math.max(0, Math.min(100, pct)); +}; + +// Signal helpers +var signalPercent = (device, cache, _version) => { + if (!device) return null; + try { + var addr = macFromDevice(device); + if (addr && cache && cache[addr] !== undefined) { + var cached = Number(cache[addr]) | 0; + return Math.max(0, Math.min(100, cached)); + } + } catch (e) {} + var s = device && device.signalStrength; + if (s === undefined || s <= 0) return null; + var p = Number(s) | 0; + return Math.max(0, Math.min(100, p)); +}; + +var signalIcon = (p) => { + if (p === null) return "antenna-bars-off"; + if (p >= 80) return "antenna-bars-5"; + if (p >= 60) return "antenna-bars-4"; + if (p >= 40) return "antenna-bars-3"; + if (p >= 20) return "antenna-bars-2"; + return "antenna-bars-1"; +}; + +// Icon mapping +var deviceIcon = (name, icon) => { + var s1 = String(name || "").toLowerCase(); + var s2 = String(icon || "").toLowerCase(); + + // Prefer icon-based hints for display devices first to avoid "audio" catching TVs + var displayHints = ["display", "tv", "monitor", "projector", "screen", "chromecast", "cast"]; + for (var dh = 0; dh < displayHints.length; dh++) { + if (s2.indexOf(displayHints[dh]) !== -1) return "bt-device-tv"; + } + + var tests = [ + [["controller", "gamepad"], "bt-device-gamepad"], + [["microphone"], "bt-device-microphone"], + [["pod", "bud", "minor"], "bt-device-earbuds"], + [["headset", "arctis", "major"], "bt-device-headset"], + [["headphone"], "bt-device-headphones"], + [["mouse"], "bt-device-mouse"], + [["keyboard"], "bt-device-keyboard"], + [["watch"], "bt-device-watch"], + [["display", "tv", "monitor", "projector", "screen", "chromecast", "cast"], "bt-device-tv"], + [["speaker", "audio", "sound"], "bt-device-speaker"], + [["phone", "iphone", "android", "samsung"], "bt-device-phone"] + ]; + for (var i = 0; i < tests.length; i++) { + var keys = tests[i][0]; + var out = tests[i][1]; + for (var j = 0; j < keys.length; j++) { + var k = keys[j]; + if (s1.indexOf(k) !== -1 || s2.indexOf(k) !== -1) return out; + } + } + return "bt-device-generic"; +}; + +// Battery percent helper +var batteryPercent = (device) => { + if (!device || !device.batteryAvailable || device.battery === undefined) return null; + var val = Math.round(Number(device.battery) * 100); + if (isNaN(val)) return null; + return Math.max(0, Math.min(100, val)); +}; diff --git a/quickshell/compat/noctalia/Helpers/ColorList.js b/quickshell/compat/noctalia/Helpers/ColorList.js new file mode 100644 index 0000000..3893214 --- /dev/null +++ b/quickshell/compat/noctalia/Helpers/ColorList.js @@ -0,0 +1,187 @@ +var colors = [ + // --- REDS --- + { name: "MistyRose", color: "mistyrose" }, + { name: "LightPink", color: "lightpink" }, + { name: "Pink", color: "pink" }, + { name: "PaleVioletRed", color: "palevioletred" }, + { name: "Pink 500", color: "#E91E63" }, // Material + { name: "HotPink", color: "hotpink" }, + { name: "DeepPink", color: "deeppink" }, + { name: "MediumVioletRed", color: "mediumvioletred" }, + { name: "LightSalmon", color: "lightsalmon" }, + { name: "Salmon", color: "salmon" }, + { name: "DarkSalmon", color: "darksalmon" }, + { name: "LightCoral", color: "lightcoral" }, + { name: "IndianRed", color: "indianred" }, + { name: "Alizarin", color: "#E74C3C" }, // Flat UI + { name: "Red 500", color: "#F44336" }, // Material + { name: "Crimson", color: "crimson" }, + { name: "Red", color: "red" }, + { name: "FireBrick", color: "firebrick" }, + { name: "DarkRed", color: "darkred" }, + { name: "Maroon", color: "maroon" }, + { name: "Brown", color: "brown" }, + + // --- ORANGES & BROWNS --- + { name: "Coral", color: "coral" }, + { name: "Tomato", color: "tomato" }, + { name: "OrangeRed", color: "orangered" }, + { name: "Deep Orange 500", color: "#FF5722" }, // Material + { name: "DarkOrange", color: "darkorange" }, + { name: "Carrot", color: "#E67E22" }, // Flat UI + { name: "Orange 500", color: "#FF9800" }, // Material + { name: "Orange", color: "orange" }, + { name: "SandyBrown", color: "sandybrown" }, + { name: "Peru", color: "peru" }, + { name: "Chocolate", color: "chocolate" }, + { name: "SaddleBrown", color: "saddlebrown" }, + { name: "Sienna", color: "sienna" }, + { name: "Brown 500", color: "#795548" }, // Material + + // --- YELLOWS, BEIGES & GOLDS --- + { name: "LightYellow", color: "lightyellow" }, + { name: "LemonChiffon", color: "lemonchiffon" }, + { name: "LightGoldenrodYellow", color: "lightgoldenrodyellow" }, + { name: "PapayaWhip", color: "papayawhip" }, + { name: "Moccasin", color: "moccasin" }, + { name: "PeachPuff", color: "peachpuff" }, + { name: "NavajoWhite", color: "navajowhite" }, + { name: "Wheat", color: "wheat" }, + { name: "BurlyWood", color: "burlywood" }, + { name: "Tan", color: "tan" }, + { name: "Bisque", color: "bisque" }, + { name: "BlanchedAlmond", color: "blanchedalmond" }, + { name: "Cornsilk", color: "cornsilk" }, + { name: "PaleGoldenrod", color: "palegoldenrod" }, + { name: "Khaki", color: "khaki" }, + { name: "DarkKhaki", color: "darkkhaki" }, + { name: "Goldenrod", color: "goldenrod" }, + { name: "DarkGoldenrod", color: "darkgoldenrod" }, + { name: "Sun Flower", color: "#F1C40F" }, // Flat UI + { name: "Yellow 500", color: "#FFEB3B" }, // Material + { name: "Yellow", color: "yellow" }, + { name: "Gold", color: "gold" }, + { name: "Amber 500", color: "#FFC107" }, // Material + + // --- GREENS --- + { name: "GreenYellow", color: "greenyellow" }, + { name: "Chartreuse", color: "chartreuse" }, + { name: "LawnGreen", color: "lawngreen" }, + { name: "Lime 500", color: "#CDDC39" }, // Material + { name: "Lime", color: "lime" }, + { name: "LimeGreen", color: "limegreen" }, + { name: "PaleGreen", color: "palegreen" }, + { name: "LightGreen", color: "lightgreen" }, + { name: "Light Green 500", color: "#8BC34A" }, // Material + { name: "MediumSpringGreen", color: "mediumspringgreen" }, + { name: "SpringGreen", color: "springgreen" }, + { name: "Emerald", color: "#2ECC71" }, // Flat UI + { name: "Green 500", color: "#4CAF50" }, // Material + { name: "MediumSeaGreen", color: "mediumseagreen" }, + { name: "SeaGreen", color: "seagreen" }, + { name: "ForestGreen", color: "forestgreen" }, + { name: "Green", color: "green" }, + { name: "DarkGreen", color: "darkgreen" }, + { name: "YellowGreen", color: "yellowgreen" }, + { name: "OliveDrab", color: "olivedrab" }, + { name: "Olive", color: "olive" }, + { name: "DarkOliveGreen", color: "darkolivegreen" }, + + // --- TEALS & CYANS --- + { name: "MediumAquamarine", color: "mediumaquamarine" }, + { name: "DarkSeaGreen", color: "darkseagreen" }, + { name: "LightSeaGreen", color: "lightseagreen" }, + { name: "DarkCyan", color: "darkcyan" }, + { name: "Teal", color: "teal" }, + { name: "Turquoise", color: "#1ABC9C" }, // Flat UI + { name: "LightCyan", color: "lightcyan" }, + { name: "PaleTurquoise", color: "paleturquoise" }, + { name: "Aquamarine", color: "aquamarine" }, + { name: "Turquoise", color: "turquoise" }, + { name: "MediumTurquoise", color: "mediumturquoise" }, + { name: "DarkTurquoise", color: "darkturquoise" }, + { name: "Aqua", color: "aqua" }, + { name: "Cyan", color: "cyan" }, + { name: "Cyan 500", color: "#00BCD4" }, // Material + { name: "CadetBlue", color: "cadetblue" }, + { name: "Teal 500", color: "#009688" }, // Material + { name: "DarkSlateGray", color: "darkslategray" }, + + // --- BLUES --- + { name: "PowderBlue", color: "powderblue" }, + { name: "LightBlue", color: "lightblue" }, + { name: "SkyBlue", color: "skyblue" }, + { name: "LightSkyBlue", color: "lightskyblue" }, + { name: "Light Blue 500", color: "#03A9F4" }, // Material + { name: "DeepSkyBlue", color: "deepskyblue" }, + { name: "DodgerBlue", color: "dodgerblue" }, + { name: "CornflowerBlue", color: "cornflowerblue" }, + { name: "Peter River", color: "#3498DB" }, // Flat UI + { name: "Blue 500", color: "#2196F3" }, // Material + { name: "SteelBlue", color: "steelblue" }, + { name: "LightSteelBlue", color: "lightsteelblue" }, + { name: "RoyalBlue", color: "royalblue" }, + { name: "Blue", color: "blue" }, + { name: "MediumBlue", color: "mediumblue" }, + { name: "Belize Hole", color: "#2980B9" }, // Flat UI + { name: "DarkBlue", color: "darkblue" }, + { name: "Navy", color: "navy" }, + { name: "MidnightBlue", color: "midnightblue" }, + { name: "Midnight Blue", color: "#2C3E50" }, // Flat UI (Same name, different color) + { name: "Indigo 500", color: "#3F51B5" }, // Material + { name: "DarkSlateBlue", color: "darkslateblue" }, + { name: "MediumSlateBlue", color: "mediumslateblue" }, + { name: "SlateBlue", color: "slateblue" }, + + // --- PURPLES & MAGENTAS --- + { name: "Lavender", color: "lavender" }, + { name: "Thistle", color: "thistle" }, + { name: "Plum", color: "plum" }, + { name: "Violet", color: "violet" }, + { name: "Orchid", color: "orchid" }, + { name: "Fuchsia", color: "fuchsia" }, + { name: "Magenta", color: "magenta" }, + { name: "MediumOrchid", color: "mediumorchid" }, + { name: "MediumPurple", color: "mediumpurple" }, + { name: "Amethyst", color: "#9B59B6" }, // Flat UI + { name: "Purple 500", color: "#9C27B0" }, // Material + { name: "BlueViolet", color: "blueviolet" }, + { name: "DarkViolet", color: "darkviolet" }, + { name: "DarkOrchid", color: "darkorchid" }, + { name: "DarkMagenta", color: "darkmagenta" }, + { name: "Purple", color: "purple" }, + { name: "Deep Purple 500", color: "#673AB7" }, // Material + { name: "Indigo", color: "indigo" }, + + // --- NEUTRALS --- + { name: "White", color: "white" }, + { name: "Snow", color: "snow" }, + { name: "HoneyDew", color: "honeydew" }, + { name: "MintCream", color: "mintcream" }, + { name: "Azure", color: "azure" }, + { name: "AliceBlue", color: "aliceblue" }, + { name: "GhostWhite", color: "ghostwhite" }, + { name: "WhiteSmoke", color: "whitesmoke" }, + { name: "Seashell", color: "seashell" }, + { name: "Beige", color: "beige" }, + { name: "OldLace", color: "oldlace" }, + { name: "FloralWhite", color: "floralwhite" }, + { name: "Ivory", color: "ivory" }, + { name: "AntiqueWhite", color: "antiquewhite" }, + { name: "Linen", color: "linen" }, + { name: "LavenderBlush", color: "lavenderblush" }, + { name: "Gainsboro", color: "gainsboro" }, + { name: "LightGray", color: "lightgray" }, + { name: "Silver", color: "silver" }, + { name: "DarkGray", color: "darkgray" }, + { name: "Gray", color: "gray" }, + { name: "Grey 500", color: "#9E9E9E" }, // Material + { name: "Concrete", color: "#95A5A6" }, // Flat UI + { name: "DimGray", color: "dimgray" }, + { name: "LightSlateGray", color: "lightslategray" }, + { name: "SlateGray", color: "slategray" }, + { name: "Asbestos", color: "#7F8C8D" }, // Flat UI + { name: "Blue Grey 500", color: "#607D8B" }, // Material + { name: "Wet Asphalt", color: "#34495E" }, // Flat UI + { name: "Black", color: "black" } + ] diff --git a/quickshell/compat/noctalia/Helpers/ColorsConvert.js b/quickshell/compat/noctalia/Helpers/ColorsConvert.js new file mode 100644 index 0000000..0e5eb7a --- /dev/null +++ b/quickshell/compat/noctalia/Helpers/ColorsConvert.js @@ -0,0 +1,270 @@ +// Convert hex color to HSL +function hexToHSL(hex) { + const rgb = hexToRgb(hex); + if (!rgb) return null; + return rgbToHsl(rgb.r, rgb.g, rgb.b); +} + +// Convert HSL to hex color +function hslToHex(h, s, l) { + const rgb = hslToRgb(h, s, l); + return rgbToHex(rgb.r, rgb.g, rgb.b); +} + +// Convert hex color to RGB +function hexToRgb(hex) { + const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); + return result ? { + r: parseInt(result[1], 16), + g: parseInt(result[2], 16), + b: parseInt(result[3], 16) + } : { r: 0, g: 0, b: 0 }; +} + +// Convert RGB to hex color +function rgbToHex(r, g, b) { + return "#" + [r, g, b].map(x => { + const hex = Math.round(Math.max(0, Math.min(255, x))).toString(16); + return hex.length === 1 ? "0" + hex : hex; + }).join(""); +} + +// Convert RGB to HSL +function rgbToHsl(r, g, b) { + r /= 255; + g /= 255; + b /= 255; + + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + let h, s, l = (max + min) / 2; + + if (max === min) { + h = s = 0; + } else { + const d = max - min; + s = l > 0.5 ? d / (2 - max - min) : d / (max + min); + + switch (max) { + case r: h = ((g - b) / d + (g < b ? 6 : 0)) / 6; break; + case g: h = ((b - r) / d + 2) / 6; break; + case b: h = ((r - g) / d + 4) / 6; break; + } + } + + return { h: h * 360, s: s * 100, l: l * 100 }; +} + +// Convert HSL to RGB +function hslToRgb(h, s, l) { + h /= 360; + s /= 100; + l /= 100; + + let r, g, b; + + if (s === 0) { + r = g = b = l; + } else { + const hue2rgb = (p, q, t) => { + if (t < 0) t += 1; + if (t > 1) t -= 1; + if (t < 1/6) return p + (q - p) * 6 * t; + if (t < 1/2) return q; + if (t < 2/3) return p + (q - p) * (2/3 - t) * 6; + return p; + }; + + const q = l < 0.5 ? l * (1 + s) : l + s - l * s; + const p = 2 * l - q; + + r = hue2rgb(p, q, h + 1/3); + g = hue2rgb(p, q, h); + b = hue2rgb(p, q, h - 1/3); + } + + return { r: Math.round(r * 255), g: Math.round(g * 255), b: Math.round(b * 255) }; +} + +// Convert RGB to HSV +function rgbToHsv(r, g, b) { + r /= 255; + g /= 255; + b /= 255; + var max = Math.max(r, g, b), min = Math.min(r, g, b); + var h, s, v = max; + var d = max - min; + s = max === 0 ? 0 : d / max; + if (max === min) { + h = 0; + } else { + switch (max) { + case r: + h = (g - b) / d + (g < b ? 6 : 0); + break; + case g: + h = (b - r) / d + 2; + break; + case b: + h = (r - g) / d + 4; + break; + } + h /= 6; + } + return { h: h * 360, s: s * 100, v: v * 100 }; +} + +// Convert HSV to RGB +function hsvToRgb(h, s, v) { + h /= 360; + s /= 100; + v /= 100; + + var r, g, b; + var i = Math.floor(h * 6); + var f = h * 6 - i; + var p = v * (1 - s); + var q = v * (1 - f * s); + var t = v * (1 - (1 - f) * s); + + switch (i % 6) { + case 0: + r = v; + g = t; + b = p; + break; + case 1: + r = q; + g = v; + b = p; + break; + case 2: + r = p; + g = v; + b = t; + break; + case 3: + r = p; + g = q; + b = v; + break; + case 4: + r = t; + g = p; + b = v; + break; + case 5: + r = v; + g = p; + b = q; + break; + } + + return { r: Math.round(r * 255), g: Math.round(g * 255), b: Math.round(b * 255) }; +} + +// Calculate relative luminance (WCAG standard) +function getLuminance(hex) { + const rgb = hexToRgb(hex); + const [r, g, b] = [rgb.r, rgb.g, rgb.b].map(val => { + val /= 255; + return val <= 0.03928 ? val / 12.92 : Math.pow((val + 0.055) / 1.055, 2.4); + }); + return 0.2126 * r + 0.7152 * g + 0.0722 * b; +} + +// Calculate contrast ratio between two colors +function getContrastRatio(hex1, hex2) { + const lum1 = getLuminance(hex1); + const lum2 = getLuminance(hex2); + const brightest = Math.max(lum1, lum2); + const darkest = Math.min(lum1, lum2); + return (brightest + 0.05) / (darkest + 0.05); +} + +// Check if a color is considered "light" +function isLightColor(hex) { + return getLuminance(hex) > 0.5; +} + +// Adjust color lightness +function adjustLightness(hex, amount) { + const hsl = hexToHSL(hex); + hsl.l = Math.max(0, Math.min(100, hsl.l + amount)); + return hslToHex(hsl.h, hsl.s, hsl.l); +} + +// Adjust color saturation +function adjustSaturation(hex, amount) { + const hsl = hexToHSL(hex); + hsl.s = Math.max(0, Math.min(100, hsl.s + amount)); + return hslToHex(hsl.h, hsl.s, hsl.l); +} + +// Adjust both lightness and saturation +function adjustLightnessAndSaturation(hex, lightnessAmount, saturationAmount) { + const hsl = hexToHSL(hex); + hsl.l = Math.max(0, Math.min(100, hsl.l + lightnessAmount)); + hsl.s = Math.max(0, Math.min(100, hsl.s + saturationAmount)); + return hslToHex(hsl.h, hsl.s, hsl.l); +} + +// Generate "on" color with proper contrast (for text/icons) +function generateOnColor(baseColor, isDarkMode) { + const isBaseLight = isLightColor(baseColor); + + // If base is light, we need dark text; if base is dark, we need light text + if (isBaseLight) { + // Try darker variants + let testColor = "#000000"; + if (getContrastRatio(baseColor, testColor) >= 4.5) { + return testColor; + } + // Fallback to dark gray + return "#1c1b1f"; + } else { + // Try lighter variants + let testColor = "#ffffff"; + if (getContrastRatio(baseColor, testColor) >= 4.5) { + return testColor; + } + // Fallback to light gray + return "#e6e1e5"; + } +} + +// Generate container color (lighter in light mode, darker in dark mode) +function generateContainerColor(baseColor, isDarkMode) { + const rgb = hexToRgb(baseColor); + const hsl = rgbToHsl(rgb.r, rgb.g, rgb.b); + + if (isDarkMode) { + // In dark mode, containers are darker and more saturated + hsl.l = Math.max(10, Math.min(30, hsl.l - 20)); + hsl.s = Math.min(100, hsl.s + 10); + } else { + // In light mode, containers are lighter and less saturated + hsl.l = Math.min(90, Math.max(75, hsl.l + 30)); + hsl.s = Math.max(0, hsl.s - 10); + } + + const newRgb = hslToRgb(hsl.h, hsl.s, hsl.l); + return rgbToHex(newRgb.r, newRgb.g, newRgb.b); +} + +// Generate surface variant colors +function generateSurfaceVariant(backgroundColor, step, isDarkMode) { + const rgb = hexToRgb(backgroundColor); + const hsl = rgbToHsl(rgb.r, rgb.g, rgb.b); + + if (isDarkMode) { + // In dark mode, variants get progressively lighter + hsl.l = Math.min(100, hsl.l + (step * 3)); + } else { + // In light mode, variants get progressively darker + hsl.l = Math.max(0, hsl.l - (step * 2)); + } + + const newRgb = hslToRgb(hsl.h, hsl.s, hsl.l); + return rgbToHex(newRgb.r, newRgb.g, newRgb.b); +} diff --git a/quickshell/compat/noctalia/Helpers/Debug.js b/quickshell/compat/noctalia/Helpers/Debug.js new file mode 100644 index 0000000..90dc27e --- /dev/null +++ b/quickshell/compat/noctalia/Helpers/Debug.js @@ -0,0 +1,25 @@ +// Helper function to stringify even if there are circular refs. +function stringify(obj, replacer, spaces, cycleReplacer) { + return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces) +} + +function serializer(replacer, cycleReplacer) { + var stack = [], keys = [] + + if (cycleReplacer == null) cycleReplacer = function(key, value) { + if (stack[0] === value) return "[Circular ~]" + return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]" + } + + return function(key, value) { + if (stack.length > 0) { + var thisPos = stack.indexOf(this) + ~thisPos ? stack.splice(thisPos + 1) : stack.push(this) + ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key) + if (~stack.indexOf(value)) value = cycleReplacer.call(this, key, value) + } + else stack.push(value) + + return replacer == null ? value : replacer.call(this, key, value) + } +} \ No newline at end of file diff --git a/quickshell/compat/noctalia/Helpers/QtObj2JS.js b/quickshell/compat/noctalia/Helpers/QtObj2JS.js new file mode 100644 index 0000000..75a248f --- /dev/null +++ b/quickshell/compat/noctalia/Helpers/QtObj2JS.js @@ -0,0 +1,114 @@ +// ----------------------------------------------------- +// Helper function to convert Qt objects to plain JavaScript objects +// Only used when generating settings-default.json +function qtObjectToPlainObject(obj) { + if (obj === null || obj === undefined) { + return obj; + } + + // Handle primitive types + if (typeof obj !== "object") { + return obj; + } + + // Handle native JavaScript arrays + if (Array.isArray(obj)) { + return obj.map((item) => qtObjectToPlainObject(item)); + } + + // Detect QML arrays FIRST (before color detection) + // QML arrays have a numeric length property and indexed properties + if (typeof obj.length === "number" && obj.length >= 0) { + // Check if it has indexed properties - be more flexible about detection + var hasIndexedProps = true; + var hasNumericKeys = false; + + // Check if we have at least some numeric properties + for (var i = 0; i < obj.length; i++) { + if (obj.hasOwnProperty(i) || obj[i] !== undefined) { + hasNumericKeys = true; + break; + } + } + + // If we have length > 0 and some numeric keys, treat as array + if (obj.length > 0 && hasNumericKeys) { + var arr = []; + for (var i = 0; i < obj.length; i++) { + // Use direct property access, handle undefined gracefully + var item = obj[i]; + if (item !== undefined) { + arr.push(qtObjectToPlainObject(item)); + } + } + return arr; // Return here to avoid processing as object + } + + // Handle empty arrays (length = 0) + if (obj.length === 0) { + return []; + } + } + + // Detect and convert QML color objects to hex strings + if ( + typeof obj.r === "number" && + typeof obj.g === "number" && + typeof obj.b === "number" && + typeof obj.a === "number" && + typeof obj.valid === "boolean" + ) { + // This looks like a QML color object + try { + // Try to get the string representation (should be hex like "#000000") + if (typeof obj.toString === "function") { + return obj.toString(); + } else { + // Fallback: convert RGBA to hex manually + var r = Math.round(obj.r * 255); + var g = Math.round(obj.g * 255); + var b = Math.round(obj.b * 255); + var hex = + "#" + + r.toString(16).padStart(2, "0") + + g.toString(16).padStart(2, "0") + + b.toString(16).padStart(2, "0"); + return hex; + } + } catch (e) { + // If conversion fails, fall through to regular object handling + } + } + + // Handle regular objects + var plainObj = {}; + + // Get all property names, but filter out Qt-specific ones + var propertyNames = Object.getOwnPropertyNames(obj); + + for (var i = 0; i < propertyNames.length; i++) { + var propName = propertyNames[i]; + + // Skip Qt-specific properties, functions, and array-like properties + if ( + propName === "objectName" || + propName === "objectNameChanged" || + propName === "length" || // Skip length property + /^\d+$/.test(propName) || // Skip numeric keys (0, 1, 2, etc.) + propName.endsWith("Changed") || + typeof obj[propName] === "function" + ) { + continue; + } + + try { + var value = obj[propName]; + plainObj[propName] = qtObjectToPlainObject(value); + } catch (e) { + // Skip properties that can't be accessed + continue; + } + } + + return plainObj; +} diff --git a/quickshell/compat/noctalia/Helpers/sha256.js b/quickshell/compat/noctalia/Helpers/sha256.js new file mode 100644 index 0000000..39f255d --- /dev/null +++ b/quickshell/compat/noctalia/Helpers/sha256.js @@ -0,0 +1,192 @@ +function sha256(message) { + // SHA-256 constants + const K = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 + ]; + + // Initial hash values + let h0 = 0x6a09e667; + let h1 = 0xbb67ae85; + let h2 = 0x3c6ef372; + let h3 = 0xa54ff53a; + let h4 = 0x510e527f; + let h5 = 0x9b05688c; + let h6 = 0x1f83d9ab; + let h7 = 0x5be0cd19; + + // Convert string to UTF-8 bytes manually + const msgBytes = stringToUtf8Bytes(message); + const msgLength = msgBytes.length; + const bitLength = msgLength * 8; + + // Calculate padding + // Message + 1 bit (0x80) + padding zeros + 8 bytes for length = multiple of 64 bytes + const totalBitsNeeded = bitLength + 1 + 64; // message bits + padding bit + 64-bit length + const totalBytesNeeded = Math.ceil(totalBitsNeeded / 8); + const paddedLength = Math.ceil(totalBytesNeeded / 64) * 64; // Round up to multiple of 64 + + const paddedMsg = new Array(paddedLength).fill(0); + + // Copy original message + for (let i = 0; i < msgLength; i++) { + paddedMsg[i] = msgBytes[i]; + } + + // Add padding bit (0x80 = 10000000 in binary) + paddedMsg[msgLength] = 0x80; + + // Add length as 64-bit big-endian integer at the end + // JavaScript numbers are not precise enough for 64-bit integers, so we handle high/low separately + const highBits = Math.floor(bitLength / 0x100000000); + const lowBits = bitLength % 0x100000000; + + // Write 64-bit length in big-endian format + paddedMsg[paddedLength - 8] = (highBits >>> 24) & 0xFF; + paddedMsg[paddedLength - 7] = (highBits >>> 16) & 0xFF; + paddedMsg[paddedLength - 6] = (highBits >>> 8) & 0xFF; + paddedMsg[paddedLength - 5] = highBits & 0xFF; + paddedMsg[paddedLength - 4] = (lowBits >>> 24) & 0xFF; + paddedMsg[paddedLength - 3] = (lowBits >>> 16) & 0xFF; + paddedMsg[paddedLength - 2] = (lowBits >>> 8) & 0xFF; + paddedMsg[paddedLength - 1] = lowBits & 0xFF; + + // Process message in 512-bit (64-byte) chunks + for (let chunk = 0; chunk < paddedLength; chunk += 64) { + const w = new Array(64); + + // Break chunk into sixteen 32-bit big-endian words + for (let i = 0; i < 16; i++) { + const offset = chunk + i * 4; + w[i] = (paddedMsg[offset] << 24) | + (paddedMsg[offset + 1] << 16) | + (paddedMsg[offset + 2] << 8) | + paddedMsg[offset + 3]; + // Ensure unsigned 32-bit + w[i] = w[i] >>> 0; + } + + // Extend the sixteen 32-bit words into sixty-four 32-bit words + for (let i = 16; i < 64; i++) { + const s0 = rightRotate(w[i - 15], 7) ^ rightRotate(w[i - 15], 18) ^ (w[i - 15] >>> 3); + const s1 = rightRotate(w[i - 2], 17) ^ rightRotate(w[i - 2], 19) ^ (w[i - 2] >>> 10); + w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0; + } + + // Initialize working variables for this chunk + let a = h0, b = h1, c = h2, d = h3, e = h4, f = h5, g = h6, h = h7; + + // Main loop + for (let i = 0; i < 64; i++) { + const S1 = rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25); + const ch = (e & f) ^ (~e & g); + const temp1 = (h + S1 + ch + K[i] + w[i]) >>> 0; + const S0 = rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22); + const maj = (a & b) ^ (a & c) ^ (b & c); + const temp2 = (S0 + maj) >>> 0; + + h = g; + g = f; + f = e; + e = (d + temp1) >>> 0; + d = c; + c = b; + b = a; + a = (temp1 + temp2) >>> 0; + } + + // Add this chunk's hash to result so far + h0 = (h0 + a) >>> 0; + h1 = (h1 + b) >>> 0; + h2 = (h2 + c) >>> 0; + h3 = (h3 + d) >>> 0; + h4 = (h4 + e) >>> 0; + h5 = (h5 + f) >>> 0; + h6 = (h6 + g) >>> 0; + h7 = (h7 + h) >>> 0; + } + + // Produce the final hash value as a hex string + return [h0, h1, h2, h3, h4, h5, h6, h7] + .map(h => h.toString(16).padStart(8, '0')) + .join(''); +} + +function stringToUtf8Bytes(str) { + const bytes = []; + for (let i = 0; i < str.length; i++) { + let code = str.charCodeAt(i); + + if (code < 0x80) { + // 1-byte character (ASCII) + bytes.push(code); + } else if (code < 0x800) { + // 2-byte character + bytes.push(0xC0 | (code >> 6)); + bytes.push(0x80 | (code & 0x3F)); + } else if (code < 0xD800 || code > 0xDFFF) { + // 3-byte character (not surrogate) + bytes.push(0xE0 | (code >> 12)); + bytes.push(0x80 | ((code >> 6) & 0x3F)); + bytes.push(0x80 | (code & 0x3F)); + } else { + // 4-byte character (surrogate pair) + i++; // Move to next character + const code2 = str.charCodeAt(i); + const codePoint = 0x10000 + (((code & 0x3FF) << 10) | (code2 & 0x3FF)); + bytes.push(0xF0 | (codePoint >> 18)); + bytes.push(0x80 | ((codePoint >> 12) & 0x3F)); + bytes.push(0x80 | ((codePoint >> 6) & 0x3F)); + bytes.push(0x80 | (codePoint & 0x3F)); + } + } + return bytes; +} + +function rightRotate(value, amount) { + return ((value >>> amount) | (value << (32 - amount))) >>> 0; +} + +// Test function to verify implementation +// function testSHA256() { +// const tests = [ +// { +// input: "", +// expected: +// "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", +// }, +// { +// input: "Hello World", +// expected: +// "a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e", +// }, +// { +// input: "abc", +// expected: +// "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", +// }, +// { +// input: "The quick brown fox jumps over the lazy dog", +// expected: +// "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592", +// }, +// ]; + +// console.log("Running SHA-256 tests:"); +// tests.forEach((test, i) => { +// const result = Crypto.sha256(test.input); +// const passed = result === test.expected; +// console.log(`Test ${i + 1}: ${passed ? "PASS" : "FAIL"}`); +// if (!passed) { +// console.log(` Input: "${test.input}"`); +// console.log(` Expected: ${test.expected}`); +// console.log(` Got: ${result}`); +// } +// }); +// } diff --git a/quickshell/compat/noctalia/Host/PanelHost.qml b/quickshell/compat/noctalia/Host/PanelHost.qml new file mode 100644 index 0000000..acf5906 --- /dev/null +++ b/quickshell/compat/noctalia/Host/PanelHost.qml @@ -0,0 +1,103 @@ +import QtQuick +import Quickshell +import Quickshell.Wayland +import "../../../components" as C +import "../../../core" as Core +import "../../../services" as GS + +// Hosts a Noctalia v4 plugin's Panel.qml as a glassMxrph bar drawer: it grows +// out of the bar under the button that opened it, sized from the panel's +// contentPreferredWidth/Height. Escape or an outside click closes it. +PanelWindow { + id: root + + required property var api + property url source: "" + readonly property bool open: !!api && !!api.panelOpenScreen + // Lets test drivers find this panel. + Component.onCompleted: GS.PluginService.panelWindows[api.pluginId] = root + // Keep the last screen while the drawer animates closed. + property var lastScreen: null + onOpenChanged: { + if (open) + lastScreen = api.panelOpenScreen; + else + GS.PluginService.releasePopout(api); + } + screen: open ? api.panelOpenScreen : lastScreen + + readonly property Item anchorItem: api && api.panelAnchor ? api.panelAnchor : null + readonly property var anchorWindow: anchorItem && anchorItem.QsWindow ? anchorItem.QsWindow.window : null + readonly property bool fromBar: !!anchorWindow && GS.TrayService.barWindows.includes(anchorWindow) + readonly property real screenW: screen ? screen.width : 1920 + readonly property real screenH: screen ? screen.height : 1080 + readonly property real anchorCenter: { + root.open; + if (!fromBar) + return screenW / 2; + const p = anchorItem.mapToItem(anchorWindow.contentItem, anchorItem.width / 2, 0); + return p.x; + } + readonly property Item panel: loader.item + readonly property var panelObject: loader.item + readonly property real preferredWidth: panelObject && panelObject.contentPreferredWidth > 0 ? panelObject.contentPreferredWidth : 400 + readonly property real preferredHeight: panelObject && panelObject.contentPreferredHeight > 0 ? panelObject.contentPreferredHeight : 320 + readonly property real drawerX: Core.BarDrawers.clampX(anchorCenter, drawer.width, screenW) + + anchors { + top: true + left: true + } + // qmllint disable unqualified unresolved-type + margins.left: root.drawerX + // qmllint enable unqualified unresolved-type + implicitWidth: Math.max(1, Math.round(drawer.width)) + implicitHeight: Math.max(1, Math.round(Core.BarDrawers.bottom + drawer.contentHeight)) + visible: open || drawer.shown + color: "transparent" + exclusionMode: ExclusionMode.Ignore + WlrLayershell.namespace: "glassMxrph-plugin-panel" + WlrLayershell.layer: WlrLayer.Overlay + WlrLayershell.keyboardFocus: open ? WlrKeyboardFocus.Exclusive : WlrKeyboardFocus.None + + MouseArea { + x: -20000 + y: -20000 + width: 40000 + height: 40000 + enabled: root.open + onPressed: root.api.closePanel(null) + } + + C.BarDrawer { + id: drawer + objectName: "noctaliaPanelSurface" + y: Core.BarDrawers.bottom + open: root.open + contentWidth: Math.min(root.preferredWidth, root.screenW - 2 * (Core.BarDrawers.margin + Core.BarDrawers.radius + ear)) + contentHeight: Math.min(root.preferredHeight, root.screenH - Core.BarDrawers.bottom - 20) + drawerId: "noctalia-panel-" + (root.api ? root.api.pluginId : "") + screenName: root.screen ? root.screen.name : "" + screenX: root.drawerX + focus: root.open + Keys.onEscapePressed: root.api.closePanel(null) + + MouseArea { + anchors.fill: parent + acceptedButtons: Qt.AllButtons + } + Loader { + id: loader + anchors.fill: parent + active: root.open || drawer.shown + onActiveChanged: if (active) + setSource(root.source, { + pluginApi: root.api + }) + onLoaded: { + if ("screen" in item) + item.screen = Qt.binding(() => root.screen); + } + } + } +} diff --git a/quickshell/compat/noctalia/Host/PluginApi.qml b/quickshell/compat/noctalia/Host/PluginApi.qml new file mode 100644 index 0000000..4afd2f5 --- /dev/null +++ b/quickshell/compat/noctalia/Host/PluginApi.qml @@ -0,0 +1,134 @@ +import QtQuick +import Quickshell +import Quickshell.Io + +// glassMxrph implementation of Noctalia v4's per-plugin `pluginApi`: same +// properties and functions (settings, translations, panel control), backed by +// glassMxrph. Settings persist to settings.json in the plugin's folder, like +// in Noctalia; panels open as glassMxrph bar drawers (see PluginService). +QtObject { + id: api + + required property string pluginId + required property string pluginDir + property var manifest: ({}) + property var pluginSettings: ({}) + + property var mainInstance: null + property var barWidget: null + property var desktopWidget: null + property var launcherProvider: null + property var controlCenterWidget: null + + // The screen the panel is open on (null when closed), and the button it hangs from. + property var panelOpenScreen: null + property var panelAnchor: null + property var ipcHandlers: ({}) + + property var pluginTranslations: ({}) + property var pluginFallbackTranslations: ({}) + property string currentLanguage: (Qt.locale().name || "en").split("_")[0] + property int translationVersion: 0 + + // Host callbacks (set by glassMxrph's PluginService). + property var _currentScreen: null + property var _requestPanel: null + + function nested(obj, path) { + let current = obj; + for (const key of String(path).split(".")) { + if (current === undefined || current === null) + return undefined; + current = current[key]; + } + return current; + } + + function saveSettings() { + settingsFile.setText(JSON.stringify(api.pluginSettings, null, 2)); + api.pluginSettings = Object.assign({}, api.pluginSettings); + } + function openPanel(screen, buttonItem) { + api.panelAnchor = buttonItem || api.barWidget || null; + api.panelOpenScreen = screen || (api._currentScreen ? api._currentScreen() : Quickshell.screens[0]); + if (api._requestPanel) + api._requestPanel(api); + return true; + } + function closePanel(screen) { + if (!api.panelOpenScreen) + return false; + api.panelOpenScreen = null; + return true; + } + // Lets glassMxrph's popout coordinator close this panel like any other. + function close() { + api.closePanel(null); + } + function togglePanel(screen, buttonItem) { + if (api.panelOpenScreen && (!screen || screen === api.panelOpenScreen)) + return api.closePanel(screen); + return api.openPanel(screen, buttonItem); + } + function openLauncher(screen) { + } + function closeLauncher(screen) { + } + function toggleLauncher(screen) { + } + function withCurrentScreen(callback) { + callback(api._currentScreen ? api._currentScreen() : Quickshell.screens[0]); + } + + function tr(key, interpolations) { + let translation = api.nested(api.pluginTranslations, key); + if (typeof translation !== "string") + translation = api.nested(api.pluginFallbackTranslations, key); + if (typeof translation !== "string") + return "!!" + key + "!!"; + for (const placeholder in (interpolations || {})) + translation = translation.replace(new RegExp("\\{" + placeholder + "\\}", "g"), interpolations[placeholder]); + return translation; + } + function trp(key, count, interpolations) { + return api.tr(count === 1 ? key : key + "-plural", Object.assign({ + "count": count + }, interpolations || {})); + } + function hasTranslation(key) { + return api.nested(api.pluginTranslations, key) !== undefined || api.nested(api.pluginFallbackTranslations, key) !== undefined; + } + + function parse(text) { + try { + return JSON.parse(text); + } catch (e) { + return {}; + } + } + property FileView settingsFile: FileView { + path: api.pluginDir + "/settings.json" + blockLoading: true + printErrors: false + onLoaded: api.pluginSettings = Object.assign({}, (api.manifest.metadata && api.manifest.metadata.defaultSettings) || {}, api.parse(text())) + onLoadFailed: api.pluginSettings = Object.assign({}, (api.manifest.metadata && api.manifest.metadata.defaultSettings) || {}) + } + property FileView languageFile: FileView { + path: api.pluginDir + "/i18n/" + api.currentLanguage + ".json" + blockLoading: true + printErrors: false + onLoaded: { + api.pluginTranslations = api.parse(text()); + api.translationVersion++; + } + } + property FileView fallbackFile: FileView { + path: api.pluginDir + "/i18n/en.json" + blockLoading: true + printErrors: false + onLoaded: { + api.pluginFallbackTranslations = api.parse(text()); + api.translationVersion++; + } + } +} diff --git a/quickshell/compat/noctalia/LICENSE b/quickshell/compat/noctalia/LICENSE new file mode 100644 index 0000000..2bdaed9 --- /dev/null +++ b/quickshell/compat/noctalia/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 noctalia-dev + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/quickshell/compat/noctalia/Modules.qml b/quickshell/compat/noctalia/Modules.qml new file mode 100644 index 0000000..8ad040e --- /dev/null +++ b/quickshell/compat/noctalia/Modules.qml @@ -0,0 +1,21 @@ +import QtQuick +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Commons.Migrations +import qs.compat.noctalia.Modules.OSD +import qs.compat.noctalia.Services.Compositor +import qs.compat.noctalia.Services.Hardware +import qs.compat.noctalia.Services.Location +import qs.compat.noctalia.Services.Media +import qs.compat.noctalia.Services.Networking +import qs.compat.noctalia.Services.Noctalia +import qs.compat.noctalia.Services.Power +import qs.compat.noctalia.Services.System +import qs.compat.noctalia.Services.UI +import qs.compat.noctalia.Widgets +import qs.compat.noctalia.Widgets.AudioSpectrum + +// Quickshell indexes qs.* modules from the shell's own import graph. Plugins +// live outside the shell folder, so this file pulls every Noctalia +// compatibility module into that graph for them. It renders nothing. +QtObject { +} diff --git a/quickshell/compat/noctalia/Modules/OSD/OSD.qml b/quickshell/compat/noctalia/Modules/OSD/OSD.qml new file mode 100644 index 0000000..f1e9d9b --- /dev/null +++ b/quickshell/compat/noctalia/Modules/OSD/OSD.qml @@ -0,0 +1,11 @@ +import QtQuick + +// glassMxrph stub: Noctalia's Settings reads OSD.Type; glassMxrph has its own OSD. +QtObject { + enum Type { + Volume, + InputVolume, + Brightness, + LockKey + } +} diff --git a/quickshell/compat/noctalia/NOTICE b/quickshell/compat/noctalia/NOTICE new file mode 100644 index 0000000..d85fba6 --- /dev/null +++ b/quickshell/compat/noctalia/NOTICE @@ -0,0 +1,14 @@ +Noctalia v4 shell kit (Commons, Widgets, Helpers and selected Services), +vendored so Noctalia v4 plugins run inside glassMxrph. +Source: https://github.com/noctalia-dev/noctalia-shell (branch legacy-v4). MIT, see LICENSE. +Tabler icon font: Assets/Fonts/tabler (MIT, see tabler-icons-license.txt). + +glassMxrph changes: +- Imports point at qs.compat.noctalia.* (Modules.qml registers them). +- Commons/Color.qml is replaced: Material roles come from the glassMxrph theme. +- Commons/Style.qml: radii, bar/capsule size, animation and opacity follow glassMxrph. +- Commons/Settings.qml stores its file in ~/.config/glassMxrph/noctalia-compat. +- Services/UI, Noctalia, Compositor, Networking, System/NotificationService and + Media/SpectrumService are small glassMxrph-backed stand-ins; Hardware/Battery, + Power/PowerProfile, Location, System/SystemStat and System/Sound are Noctalia's own. +- Host/ holds glassMxrph's pluginApi and the bar-drawer panel host. diff --git a/quickshell/compat/noctalia/Services/Compositor/CompositorService.qml b/quickshell/compat/noctalia/Services/Compositor/CompositorService.qml new file mode 100644 index 0000000..3cee374 --- /dev/null +++ b/quickshell/compat/noctalia/Services/Compositor/CompositorService.qml @@ -0,0 +1,31 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Hyprland + +// glassMxrph stand-in: glassMxrph runs on Hyprland. +Singleton { + readonly property bool isHyprland: true + readonly property bool isNiri: false + readonly property bool isSway: false + readonly property bool isMango: false + readonly property bool isLabwc: false + readonly property bool overviewActive: false + readonly property var workspaces: Hyprland.workspaces.values.map(w => ({ + "id": w.id, + "idx": w.id, + "name": w.name, + "output": w.monitor ? w.monitor.name : "", + "isFocused": w.focused, + "isActive": w.active, + "isUrgent": w.urgent, + "isOccupied": w.toplevels.values.length > 0 + })) + function getDisplayScale(screenName) { + const s = Quickshell.screens.find(x => x.name === screenName); + return s ? s.devicePixelRatio : 1; + } + function switchToWorkspace(workspace) { + Hyprland.dispatch("workspace " + (workspace && workspace.id !== undefined ? workspace.id : workspace)); + } +} diff --git a/quickshell/compat/noctalia/Services/Hardware/BatteryService.qml b/quickshell/compat/noctalia/Services/Hardware/BatteryService.qml new file mode 100644 index 0000000..d0fa480 --- /dev/null +++ b/quickshell/compat/noctalia/Services/Hardware/BatteryService.qml @@ -0,0 +1,368 @@ +pragma Singleton +import QtQml +import QtQuick + +import Quickshell +import Quickshell.Io +import Quickshell.Services.UPower +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Services.Networking +import qs.compat.noctalia.Services.UI + +Singleton { + id: root + + readonly property var primaryDevice: _laptopBattery || _bluetoothBattery || null // Primary battery device (prioritizes laptop over Bluetooth) + readonly property real batteryPercentage: getPercentage(primaryDevice) + readonly property bool batteryCharging: isCharging(primaryDevice) + readonly property bool batteryPluggedIn: isPluggedIn(primaryDevice) + readonly property bool batteryReady: isDeviceReady(primaryDevice) + readonly property bool batteryPresent: isDevicePresent(primaryDevice) + readonly property real warningThreshold: Settings.data.systemMonitor.batteryWarningThreshold + readonly property real criticalThreshold: Settings.data.systemMonitor.batteryCriticalThreshold + readonly property string batteryIcon: getIcon(batteryPercentage, batteryCharging, batteryPluggedIn, batteryReady) + + readonly property var laptopBatteries: UPower.devices.values.filter(d => d.isLaptopBattery).sort((x, y) => { + // Force DisplayDevice to the top + if (x.nativePath.includes("DisplayDevice")) + return -1; + if (y.nativePath.includes("DisplayDevice")) + return 1; + + // Standard string comparison works for BAT0 vs BAT1 + return x.nativePath.localeCompare(y.nativePath, undefined, { + numeric: true + }); + }) + + readonly property var bluetoothBatteries: { + var list = []; + var btArray = BluetoothService.devices?.values || []; + for (var i = 0; i < btArray.length; i++) { + var btd = btArray[i]; + if (btd && btd.connected && btd.batteryAvailable) { + list.push(btd); + } + } + return list; + } + + readonly property var _laptopBattery: UPower.displayDevice.isPresent ? UPower.displayDevice : (laptopBatteries.length > 0 ? laptopBatteries[0] : null) + readonly property var _bluetoothBattery: bluetoothBatteries.length > 0 ? bluetoothBatteries[0] : null + + property var deviceModel: { + var model = [ + { + "key": "__default__", + "name": I18n.tr("bar.battery.device-default") + } + ]; + const devices = UPower.devices?.values || []; + for (let d of devices) { + if (!d || d.type === UPowerDeviceType.LinePower) { + continue; + } + model.push({ + key: d.nativePath || "", + name: d.model || d.nativePath || I18n.tr("common.unknown") + }); + } + return model; + } + + property var _hasNotified: ({}) + + function findDevice(nativePath) { + if (!nativePath || nativePath === "__default__" || nativePath === "DisplayDevice") { + return _laptopBattery; + } + + if (!UPower.devices) { + return null; + } + + const devices = UPower.devices?.values || []; + for (let d of devices) { + if (d && d.nativePath === nativePath) { + if (d.type === UPowerDeviceType.LinePower) { + continue; + } + return d; + } + } + return null; + } + + function isDevicePresent(device) { + if (!device) { + return false; + } + + // Handle Bluetooth devices (identified by having batteryAvailable property) + if (device.batteryAvailable !== undefined) { + return device.connected === true; + } + + // Handle UPower devices + if (device.type !== undefined) { + if (device.type === UPowerDeviceType.Battery && device.isPresent !== undefined) { + return device.isPresent === true; + } + // Fallback for non-battery UPower devices or if isPresent is missing + return device.ready && device.percentage !== undefined; + } + return false; + } + + function isDeviceReady(device) { + if (!isDevicePresent(device)) { + return false; + } + if (device.batteryAvailable !== undefined) { + return device.battery !== undefined; + } + return device.ready && device.percentage !== undefined; + } + + function getPercentage(device) { + if (!device) { + return -1; + } + if (device.batteryAvailable !== undefined) { + return Math.round((device.battery || 0) * 100); + } + return Math.round((device.percentage || 0) * 100); + } + + function isCharging(device) { + if (!device || isBluetoothDevice(device)) { + // Tracking bluetooth devices can charge or not is a loop hole, none of my devices has it, even if it possible?! + return false; // Assuming not charging until someone/quickshell brings a way to do pretty unlikely. + } + if (device.state !== undefined) { + return device.state === UPowerDeviceState.Charging; + } + return false; + } + + function isPluggedIn(device) { + if (!device || isBluetoothDevice(device)) { + // Tracking bluetooth devices can charge or not is a loop hole, none of my devices has it, even if it possible?! + return false; // Assuming not charging until someone/quickshell brings a way to do pretty unlikely. + } + if (device.state !== undefined) { + return device.state === UPowerDeviceState.FullyCharged || device.state === UPowerDeviceState.PendingCharge; + } + return false; + } + + function isCriticalBattery(device) { + return (!isCharging(device) && !isPluggedIn(device)) && getPercentage(device) <= criticalThreshold; + } + + function isLowBattery(device) { + return (!isCharging(device) && !isPluggedIn(device)) && getPercentage(device) <= warningThreshold && getPercentage(device) > criticalThreshold; + } + + function isBluetoothDevice(device) { + if (!device) { + return false; + } + // Check for Quickshell Bluetooth device property + if (device.batteryAvailable !== undefined) { + return true; + } + // Check for UPower device path indicating it's a Bluetooth device + if (device.nativePath && (device.nativePath.includes("bluez") || device.nativePath.includes("bluetooth"))) { + return true; + } + return false; + } + + function getDeviceName(device) { + if (!isDeviceReady(device)) { + return ""; + } + + if (!isBluetoothDevice(device) && device.isLaptopBattery) { + // If there is more than one battery explicitly name them + // Logger.e("BatteryDebug", "Available Battery count: " + laptopBatteries.length); // can be useful for debugging + if (laptopBatteries.length > 1 && device.nativePath) { + if (device.nativePath === "DisplayDevice") { + return I18n.tr("battery.all-batteries"); + } + var match = device.nativePath.match(/(\d+)$/); + if (match) { + // In case of 2 batteries: bat0 => bat1 bat1 => bat2 + return I18n.tr("common.battery") + " " + (parseInt(match[1]) + 1); // Append numbers + } + } + // Return Battery if there is only one + return I18n.tr("common.battery"); + } + + if (isBluetoothDevice(device) && device.name) { + return device.name; + } + + if (device.model) { + return device.model; + } + + return ""; + } + + function getIcon(percent, charging, pluggedIn, isReady) { + if (!isReady) { + return "battery-exclamation"; + } + if (charging) { + return "battery-charging"; + } + if (pluggedIn) { + return "battery-charging-2"; + } + + const icons = [ + { + threshold: 86, + icon: "battery-4" + }, + { + threshold: 56, + icon: "battery-3" + }, + { + threshold: 31, + icon: "battery-2" + }, + { + threshold: 11, + icon: "battery-1" + }, + { + threshold: 0, + icon: "battery" + } + ]; + + const match = icons.find(tier => percent >= tier.threshold); + return match ? match.icon : "battery-off"; // New fallback icon clearly represent if nothing is true here. + } + + function getRateText(device) { + if (!device || device.changeRate === undefined) { + return ""; + } + const rate = Math.abs(device.changeRate); + if (device.timeToFull > 0) { + return I18n.tr("battery.charging-rate", { + "rate": rate.toFixed(2) + }); + } else if (device.timeToEmpty > 0) { + return I18n.tr("battery.discharging-rate", { + "rate": rate.toFixed(2) + }); + } + } + + function getTimeRemainingText(device) { + if (!isDeviceReady(device)) { + return I18n.tr("battery.no-battery-detected"); + } + if (isPluggedIn(device)) { + return I18n.tr("battery.plugged-in"); + } else if (device.timeToFull > 0) { + return I18n.tr("battery.time-until-full", { + "time": Time.formatVagueHumanReadableDuration(device.timeToFull) + }); + } else if (device.timeToEmpty > 0) { + return I18n.tr("battery.time-left", { + "time": Time.formatVagueHumanReadableDuration(device.timeToEmpty) + }); + } + return I18n.tr("common.idle"); + } + + function checkDevice(device) { + if (!device || !isDeviceReady(device)) { + return; + } + + const percentage = getPercentage(device); + const charging = isCharging(device); + const pluggedIn = isPluggedIn(device); + const level = isLowBattery(device) ? "low" : (isCriticalBattery(device) ? "critical" : ""); + var deviceKey = device.nativePath; + + if (!_hasNotified[deviceKey]) { + _hasNotified[deviceKey] = { + low: false, + critical: false + }; + } + + if (charging || pluggedIn) { + _hasNotified[deviceKey].low = false; + _hasNotified[deviceKey].critical = false; + } + + if (percentage > warningThreshold) { + _hasNotified[deviceKey].low = false; + _hasNotified[deviceKey].critical = false; + } else if (percentage > criticalThreshold) { + _hasNotified[deviceKey].critical = false; + } + + if (level) { + if (!_hasNotified[deviceKey][level]) { + notify(device, level); + _hasNotified[deviceKey][level] = true; + } + } + } + + function notify(device, level) { + if (!Settings.data.notifications.enableBatteryToast) { + return; + } + var name = getDeviceName(device); + var titleKey = level === "critical" ? "toast.battery.critical" : "toast.battery.low"; + var descKey = level === "critical" ? "toast.battery.critical-desc" : "toast.battery.low-desc"; + + var title = I18n.tr(titleKey); + var desc = I18n.tr(descKey, { + "percent": getPercentage(device) + }); + var icon = level === "critical" ? "battery-exclamation" : "battery-charging-2"; + + if (device == _bluetoothBattery && name) { + title = title + " " + name; + } + + // Only 'showNotice' supports custom icons + ToastService.showNotice(title, desc, icon, 6000); + } + + Instantiator { + model: deviceModel + delegate: Connections { + required property var modelData + property var device: findDevice(modelData.key) + target: device + + function onPercentageChanged() { + if (device.isLaptopBattery && modelData.key !== "__default__") { + return; + } + checkDevice(device); + } + function onStateChanged() { + if (device.isLaptopBattery && modelData.key !== "__default__") { + return; + } + checkDevice(device); + } + } + } +} diff --git a/quickshell/compat/noctalia/Services/Location/LocationService.qml b/quickshell/compat/noctalia/Services/Location/LocationService.qml new file mode 100644 index 0000000..2d3ce22 --- /dev/null +++ b/quickshell/compat/noctalia/Services/Location/LocationService.qml @@ -0,0 +1,397 @@ +pragma Singleton + +import QtQuick +import Quickshell +import Quickshell.Io +import qs.compat.noctalia.Commons + +// Location and weather service with decoupled geocoding and weather fetching. +Singleton { + id: root + + property string locationFile: Quickshell.env("NOCTALIA_WEATHER_FILE") || (Settings.cacheDir + "location.json") + property int weatherUpdateFrequency: 30 * 60 + property bool isFetchingWeather: false + + // Talia weather + readonly property int taliaMascotWeatherMonth: 3 + readonly property int taliaMascotWeatherDay: 1 + + readonly property bool taliaWeatherMascotDayActive: { + const d = Time.now; + return d.getMonth() === root.taliaMascotWeatherMonth && d.getDate() === root.taliaMascotWeatherDay; + } + + readonly property bool taliaWeatherMascotActive: taliaWeatherMascotDayActive || Settings.data.location.weatherTaliaMascotAlways + + readonly property alias data: adapter + + // True when the user has set a location name or enabled auto-locate + readonly property bool locationConfigured: Settings.data.location.name !== "" || Settings.data.location.autoLocate + + // Stable UI properties - only updated when location is successfully geocoded + property bool coordinatesReady: false + property string stableLatitude: "" + property string stableLongitude: "" + property string stableName: "" + + FileView { + id: locationFileView + path: locationFile + printErrors: false + onAdapterUpdated: saveTimer.start() + onLoaded: { + Logger.d("Location", "Loaded cached data"); + if (adapter.latitude !== "" && adapter.longitude !== "" && adapter.weatherLastFetch > 0) { + root.stableLatitude = adapter.latitude; + root.stableLongitude = adapter.longitude; + root.stableName = adapter.name; + root.coordinatesReady = true; + Logger.i("Location", "Coordinates ready"); + } + update(); + } + onLoadFailed: function (error) { + update(); + } + + JsonAdapter { + id: adapter + property string latitude: "" + property string longitude: "" + property string name: "" + property int weatherLastFetch: 0 + property var weather: null + } + } + + // Formatted coordinates for UI display + readonly property string displayCoordinates: { + if (!root.coordinatesReady || root.stableLatitude === "" || root.stableLongitude === "") { + return ""; + } + const lat = parseFloat(root.stableLatitude).toFixed(4); + const lon = parseFloat(root.stableLongitude).toFixed(4); + return `${lat}, ${lon}`; + } + + // Auto-geolocate timer - periodically updates location via IP geolocation + Timer { + id: autoLocateTimer + interval: 30 * 60 * 1000 + running: Settings.data.location.autoLocate + repeat: true + triggeredOnStart: true + onTriggered: root.geolocateAndApply() + } + + // Update timer runs when weather is enabled or location-based scheduling is active + Timer { + id: updateTimer + interval: 20 * 1000 + running: Settings.data.location.weatherEnabled || Settings.data.colorSchemes.schedulingMode == "location" + repeat: true + onTriggered: { + update(); + } + } + + Timer { + id: saveTimer + running: false + interval: 1000 + onTriggered: locationFileView.writeAdapter() + } + + function init() { + Logger.i("Location", "Service started"); + } + + function resetWeather() { + Logger.i("Location", "Resetting location and weather data"); + + root.coordinatesReady = false; + root.stableLatitude = ""; + root.stableLongitude = ""; + root.stableName = ""; + + adapter.latitude = ""; + adapter.longitude = ""; + adapter.name = ""; + adapter.weatherLastFetch = 0; + adapter.weather = null; + isFetchingWeather = false; + update(); + } + + // Main update function - geocodes location if needed, then fetches weather if enabled + function update() { + updateLocation(); + + if (Settings.data.location.weatherEnabled) { + updateWeatherData(); + } + } + + // Runs independently of weather toggle + function updateLocation() { + const locationChanged = adapter.name !== Settings.data.location.name; + const needsGeocoding = (adapter.latitude === "") || (adapter.longitude === "") || locationChanged; + + if (!needsGeocoding) { + return; + } + + if (isFetchingWeather) { + return; + } + + isFetchingWeather = true; + + if (locationChanged) { + root.coordinatesReady = false; + Logger.d("Location", "Location changed from", adapter.name, "to", Settings.data.location.name); + } + + geocodeLocation(Settings.data.location.name, function (latitude, longitude, name, country) { + adapter.name = Settings.data.location.name; + adapter.latitude = latitude.toString(); + adapter.longitude = longitude.toString(); + root.stableLatitude = adapter.latitude; + root.stableLongitude = adapter.longitude; + root.stableName = `${name}, ${country}`; + root.coordinatesReady = true; + + isFetchingWeather = false; + Logger.i("Location", `Geocoded ${Settings.data.location.name}: ${root.stableLatitude}, ${root.stableLongitude}`); + + if (locationChanged) { + adapter.weatherLastFetch = 0; + updateWeatherData(); + } + }, errorCallback); + } + + // Fetch weather data if enabled and coordinates are available + function updateWeatherData() { + if (!Settings.data.location.weatherEnabled) { + return; + } + + if (isFetchingWeather) { + return; + } + + if (adapter.latitude === "" || adapter.longitude === "") { + Logger.w("Location", "Cannot fetch weather without coordinates"); + return; + } + const needsWeatherUpdate = (adapter.weatherLastFetch === "") || (adapter.weather === null) || (Time.timestamp >= adapter.weatherLastFetch + weatherUpdateFrequency); + + if (needsWeatherUpdate) { + isFetchingWeather = true; + fetchWeatherData(adapter.latitude, adapter.longitude, errorCallback); + } + } + + // Query geocoding API to convert location name to coordinates + function geocodeLocation(locationName, callback, errorCallback) { + if (locationName === "") { + isFetchingWeather = false; + return; + } + + Logger.d("Location", "Geocoding location name"); + var geoUrl = "https://api.noctalia.dev/geocode?city=" + encodeURIComponent(locationName); + var xhr = new XMLHttpRequest(); + xhr.onreadystatechange = function () { + if (xhr.readyState === XMLHttpRequest.DONE) { + if (xhr.status === 200) { + try { + var geoData = JSON.parse(xhr.responseText); + if (geoData.lat != null) { + callback(geoData.lat, geoData.lng, geoData.name, geoData.country); + } else { + errorCallback("Location", "could not resolve location name"); + } + } catch (e) { + errorCallback("Location", "Failed to parse geocoding data: " + e); + } + } else { + errorCallback("Location", `Geocoding error: ${xhr.status} ${xhr.responseText}`); + } + } + }; + xhr.open("GET", geoUrl); + xhr.send(); + } + + // Fetch weather data from Open-Meteo API + function fetchWeatherData(latitude, longitude, errorCallback) { + Logger.d("Location", "Fetching weather from api.open-meteo.com"); + var url = "https://api.open-meteo.com/v1/forecast?latitude=" + latitude + "&longitude=" + longitude + "¤t_weather=true¤t=relativehumidity_2m,surface_pressure,is_day&daily=temperature_2m_max,temperature_2m_min,weathercode,sunset,sunrise&timezone=auto"; + var xhr = new XMLHttpRequest(); + xhr.onreadystatechange = function () { + if (xhr.readyState === XMLHttpRequest.DONE) { + if (xhr.status === 200) { + try { + var weatherData = JSON.parse(xhr.responseText); + //console.log(JSON.stringify(weatherData)) + + // Save core data + data.weather = weatherData; + data.weatherLastFetch = Time.timestamp; + + // Update stable display values only when complete and successful + root.stableLatitude = data.latitude = weatherData.latitude.toString(); + root.stableLongitude = data.longitude = weatherData.longitude.toString(); + root.coordinatesReady = true; + + isFetchingWeather = false; + Logger.d("Location", "Cached weather to disk - stable coordinates updated"); + } catch (e) { + errorCallback("Location", "Failed to parse weather data"); + } + } else { + errorCallback("Location", `Weather error: ${xhr.status} ${xhr.responseText}`); + } + } + }; + xhr.open("GET", url); + xhr.send(); + } + + // Geolocate via IP address using the Noctalia API + function geolocate(callback, errorCallback) { + Logger.d("Location", "Geolocating via IP"); + var url = "https://api.noctalia.dev/geolocate"; + var xhr = new XMLHttpRequest(); + xhr.onreadystatechange = function () { + if (xhr.readyState === XMLHttpRequest.DONE) { + if (xhr.status === 200) { + try { + var data = JSON.parse(xhr.responseText); + if (data.lat != null) { + callback(data.lat, data.lng, data.city, data.country); + } else { + errorCallback("Location", "Geolocate: no coordinates returned"); + } + } catch (e) { + errorCallback("Location", "Failed to parse geolocate data: " + e); + } + } else { + errorCallback("Location", `Geolocate error: ${xhr.status} ${xhr.responseText}`); + } + } + }; + xhr.open("GET", url); + xhr.send(); + } + + // Geolocate via IP and apply the result as the current location + function geolocateAndApply() { + if (isFetchingWeather) { + Logger.w("Location", "Geolocate skipped, fetch already in progress"); + return; + } + geolocate(function (lat, lng, city, country) { + Logger.i("Location", "Geolocated to", city + ",", country + ":", lat + "," + lng); + + const locationChanged = adapter.name !== city; + Settings.data.location.name = city; + adapter.name = city; + adapter.latitude = lat.toString(); + adapter.longitude = lng.toString(); + root.stableLatitude = adapter.latitude; + root.stableLongitude = adapter.longitude; + root.stableName = `${city}, ${country}`; + root.coordinatesReady = true; + + if (locationChanged) { + adapter.weatherLastFetch = 0; + adapter.weather = null; + } + + if (Settings.data.location.weatherEnabled) { + updateWeatherData(); + } + }, errorCallback); + } + + // -------------------------------- + function errorCallback(module, message) { + Logger.w(module, message); + isFetchingWeather = false; + } + + // -------------------------------- + function weatherSymbolFromCode(code) { + var isDay = data.weather ? data.weather.current_weather.is_day : true; + if (code === 0) + return isDay ? "weather-sun" : "weather-moon"; + if (code === 1 || code === 2) + return isDay ? "weather-cloud-sun" : "weather-moon-stars"; + if (code === 3) + return "weather-cloud"; + if (code >= 45 && code <= 48) + return "weather-cloud-haze"; + if (code >= 51 && code <= 67) + return "weather-cloud-rain"; + if (code >= 80 && code <= 82) + return "weather-cloud-rain"; + if (code >= 71 && code <= 77) + return "weather-cloud-snow"; + if (code >= 71 && code <= 77) + return "weather-cloud-snow"; + if (code >= 85 && code <= 86) + return "weather-cloud-snow"; + if (code >= 95 && code <= 99) + return "weather-cloud-lightning"; + return "weather-cloud"; + } + + // -------------------------------- + function taliaWeatherImageFromCode(code) { + var isDay = data.weather ? data.weather.current_weather.is_day : true; + if (code >= 40 && code <= 49) + return Quickshell.shellDir + "/Assets/Talia/TaliaDazed.png"; + if (code >= 95 && code <= 99) + return Quickshell.shellDir + "/Assets/Talia/TaliaFear.png"; + var wet = (code >= 51 && code <= 67) || (code >= 80 && code <= 82) || (code >= 71 && code <= 77) || (code >= 85 && code <= 86); + if (wet) + return Quickshell.shellDir + "/Assets/Talia/TaliaSob.png"; + if ((code === 0 || code === 1 || code === 2) && isDay === false) + return Quickshell.shellDir + "/Assets/Talia/TaliaVampire.png"; + if ((code === 0 && isDay === true) || code === 1 || code === 2) + return Quickshell.shellDir + "/Assets/Talia/TaliaParty.png"; + return Quickshell.shellDir + "/Assets/Talia/TaliaBlank.png"; + } + + // -------------------------------- + function weatherDescriptionFromCode(code) { + if (code === 0) + return "Clear sky"; + if (code === 1) + return "Mainly clear"; + if (code === 2) + return "Partly cloudy"; + if (code === 3) + return "Overcast"; + if (code === 45 || code === 48) + return "Fog"; + if (code >= 51 && code <= 67) + return "Drizzle"; + if (code >= 71 && code <= 77) + return "Snow"; + if (code >= 80 && code <= 82) + return "Rain showers"; + if (code >= 95 && code <= 99) + return "Thunderstorm"; + return "Unknown"; + } + + // -------------------------------- + function celsiusToFahrenheit(celsius) { + return 32 + celsius * 1.8; + } +} diff --git a/quickshell/compat/noctalia/Services/Media/SpectrumService.qml b/quickshell/compat/noctalia/Services/Media/SpectrumService.qml new file mode 100644 index 0000000..70a2aac --- /dev/null +++ b/quickshell/compat/noctalia/Services/Media/SpectrumService.qml @@ -0,0 +1,35 @@ +pragma Singleton +import QtQuick +import Quickshell +import "../../../../services" as GS + +// glassMxrph stand-in: the audio spectrum comes from glassMxrph's Cava +// (Noctalia's PwAudioSpectrum is not in Quickshell 0.3.1). +Singleton { + id: root + property var _registeredComponents: ({}) + readonly property int _registeredCount: Object.keys(_registeredComponents).length + readonly property var values: GS.CavaService.bars + readonly property bool isIdle: !GS.CavaService.wanted + property bool subscribed: false + on_RegisteredCountChanged: { + const want = _registeredCount > 0; + if (want !== subscribed) { + GS.CavaService.widgetConsumers += want ? 1 : -1; + subscribed = want; + } + } + function registerComponent(componentId) { + const next = Object.assign({}, _registeredComponents); + next[componentId] = true; + _registeredComponents = next; + } + function unregisterComponent(componentId) { + const next = Object.assign({}, _registeredComponents); + delete next[componentId]; + _registeredComponents = next; + } + function isRegistered(componentId) { + return !!_registeredComponents[componentId]; + } +} diff --git a/quickshell/compat/noctalia/Services/Networking/BluetoothService.qml b/quickshell/compat/noctalia/Services/Networking/BluetoothService.qml new file mode 100644 index 0000000..8867f92 --- /dev/null +++ b/quickshell/compat/noctalia/Services/Networking/BluetoothService.qml @@ -0,0 +1,11 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Bluetooth + +// glassMxrph stand-in: only what other compatibility services read. +Singleton { + readonly property var adapter: Bluetooth.defaultAdapter + readonly property var devices: Bluetooth.devices + readonly property bool enabled: !!adapter && adapter.enabled +} diff --git a/quickshell/compat/noctalia/Services/Noctalia/PluginRegistry.qml b/quickshell/compat/noctalia/Services/Noctalia/PluginRegistry.qml new file mode 100644 index 0000000..de69809 --- /dev/null +++ b/quickshell/compat/noctalia/Services/Noctalia/PluginRegistry.qml @@ -0,0 +1,46 @@ +pragma Singleton +import QtQuick +import Quickshell +import "../../../../services" as GS + +// glassMxrph stand-in: answers from glassMxrph's installed plugins. +Singleton { + readonly property string pluginsDir: (Quickshell.env("XDG_DATA_HOME") || Quickshell.env("HOME") + "/.local/share") + "/glassMxrph/plugins" + readonly property var pluginSources: [] + function getPluginManifest(pluginId) { + const p = GS.PluginService.plugin(pluginId); + return p ? p.manifest : null; + } + function getPluginDir(pluginId) { + const p = GS.PluginService.plugin(pluginId); + return p ? p.dir : ""; + } + function getAllInstalledPluginIds() { + return GS.PluginService.plugins.map(p => p.id); + } + function isPluginEnabled(pluginId) { + return GS.PluginService.isEnabled(pluginId); + } + function isMainSource(url) { + return true; + } + function getPluginSourceUrl(pluginId) { + const p = GS.PluginService.plugin(pluginId); + return p ? p.source : ""; + } + function parseCompositeKey(key) { + return { + "pluginId": String(key), + "sourceHash": "" + }; + } + function getSourceNameByHash(hash) { + return ""; + } + function addPluginSource(name, url) { + } + function removePluginSource(url) { + } + function setSourceEnabled(url, enabled) { + } +} diff --git a/quickshell/compat/noctalia/Services/Noctalia/PluginService.qml b/quickshell/compat/noctalia/Services/Noctalia/PluginService.qml new file mode 100644 index 0000000..839fa3a --- /dev/null +++ b/quickshell/compat/noctalia/Services/Noctalia/PluginService.qml @@ -0,0 +1,46 @@ +pragma Singleton +import QtQuick +import Quickshell +import "../../../../services" as GS + +// glassMxrph stand-in: Noctalia plugins talk to glassMxrph's plugin service. +Singleton { + readonly property bool initialized: GS.PluginService.loaded + readonly property bool pluginsFullyLoaded: GS.PluginService.loaded + readonly property var availablePlugins: [] + readonly property var pluginUpdates: ({}) + readonly property int pluginUpdatesPending: 0 + readonly property var installingPlugins: ({}) + readonly property int activeFetches: 0 + function getPluginAPI(pluginId) { + return GS.PluginService.noctaliaApi(pluginId); + } + function hasPluginError(pluginId) { + return false; + } + function getPluginError(pluginId) { + return ""; + } + function enablePlugin(pluginId) { + GS.PluginService.setEnabled(pluginId, true); + } + function disablePlugin(pluginId) { + GS.PluginService.setEnabled(pluginId, false); + } + function uninstallPlugin(pluginId) { + GS.PluginService.remove(pluginId); + } + function installPlugin(plugin) { + } + function updatePlugin(pluginId) { + } + function checkForUpdates() { + } + function refreshAvailablePlugins() { + } + function isPluginHotReloadEnabled(pluginId) { + return false; + } + function togglePluginHotReload(pluginId) { + } +} diff --git a/quickshell/compat/noctalia/Services/Power/PowerProfileService.qml b/quickshell/compat/noctalia/Services/Power/PowerProfileService.qml new file mode 100644 index 0000000..afd2003 --- /dev/null +++ b/quickshell/compat/noctalia/Services/Power/PowerProfileService.qml @@ -0,0 +1,132 @@ +pragma Singleton + +import QtQuick +import Quickshell +import Quickshell.Services.UPower +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Services.UI + +Singleton { + id: root + + readonly property var powerProfiles: PowerProfiles + readonly property bool available: powerProfiles && powerProfiles.hasPerformanceProfile + property int profile: powerProfiles ? powerProfiles.profile : PowerProfile.Balanced + + // Not a power profile but a volatile property to quickly disable shadows, animations, etc.. + property bool noctaliaPerformanceMode: false + + function getName(p) { + if (!available) + return "Unknown"; + + const prof = (p !== undefined) ? p : profile; + + switch (prof) { + case PowerProfile.Performance: + return "Performance"; + case PowerProfile.Balanced: + return "Balanced"; + case PowerProfile.PowerSaver: + return "Power saver"; + default: + return "Unknown"; + } + } + + function getIcon(p) { + if (!available) + return "balanced"; + + const prof = (p !== undefined) ? p : profile; + + switch (prof) { + case PowerProfile.Performance: + return "performance"; + case PowerProfile.Balanced: + return "balanced"; + case PowerProfile.PowerSaver: + return "powersaver"; + default: + return "balanced"; + } + } + + function init() { + Logger.d("PowerProfileService", "Service started"); + } + + function setProfile(p) { + if (!available) + return; + try { + powerProfiles.profile = p; + } catch (e) { + Logger.e("PowerProfileService", "Failed to set profile:", e); + } + } + + function cycleProfile() { + if (!available) + return; + const current = powerProfiles.profile; + if (current === PowerProfile.Performance) + setProfile(PowerProfile.PowerSaver); + else if (current === PowerProfile.Balanced) + setProfile(PowerProfile.Performance); + else if (current === PowerProfile.PowerSaver) + setProfile(PowerProfile.Balanced); + } + + function cycleProfileReverse() { + if (!available) + return; + const current = powerProfiles.profile; + if (current === PowerProfile.Performance) + setProfile(PowerProfile.Balanced); + else if (current === PowerProfile.Balanced) + setProfile(PowerProfile.PowerSaver); + else if (current === PowerProfile.PowerSaver) + setProfile(PowerProfile.Performance); + } + + function isDefault() { + if (!available) + return true; + return (profile === PowerProfile.Balanced); + } + + Connections { + target: powerProfiles + function onProfileChanged() { + root.profile = powerProfiles.profile; + // Only show toast if we have a valid profile name (not "Unknown") + const profileName = root.getName(); + if (profileName !== "Unknown") { + ToastService.showNotice(I18n.tr("toast.power-profile.profile-name", { + "profile": profileName + }), I18n.tr("toast.power-profile.changed"), profileName.toLowerCase().replace(" ", "")); + } + } + } + + // Noctalia Performance Mode + // - Turning shadow off + // - Turning animation off + // - Do Not Disturb + function toggleNoctaliaPerformance() { + noctaliaPerformanceMode = !noctaliaPerformanceMode; + } + + function setNoctaliaPerformance(value) { + noctaliaPerformanceMode = value; + } + + onNoctaliaPerformanceModeChanged: { + if (noctaliaPerformanceMode) { + ToastService.showNotice(I18n.tr("toast.noctalia-performance.label"), I18n.tr("toast.noctalia-performance.enabled"), "rocket"); + } else { + ToastService.showNotice(I18n.tr("toast.noctalia-performance.label"), I18n.tr("toast.noctalia-performance.disabled"), "rocket-off"); + } + } +} diff --git a/quickshell/compat/noctalia/Services/System/NotificationService.qml b/quickshell/compat/noctalia/Services/System/NotificationService.qml new file mode 100644 index 0000000..990f13e --- /dev/null +++ b/quickshell/compat/noctalia/Services/System/NotificationService.qml @@ -0,0 +1,8 @@ +pragma Singleton +import QtQuick +import Quickshell + +// glassMxrph stand-in: notifications are handled outside the shell. +Singleton { + property bool doNotDisturb: false +} diff --git a/quickshell/compat/noctalia/Services/System/SoundService.qml b/quickshell/compat/noctalia/Services/System/SoundService.qml new file mode 100644 index 0000000..ab41bda --- /dev/null +++ b/quickshell/compat/noctalia/Services/System/SoundService.qml @@ -0,0 +1,205 @@ +pragma Singleton + +import QtQuick +import Quickshell +import qs.compat.noctalia.Commons + +Singleton { + id: root + + // Map to track active sound players: resolvedPath -> MediaPlayer instance + property var activePlayers: ({}) + + // Check if QtMultimedia is available + property bool multimediaAvailable: false + + // Container for dynamically created players + Item { + id: playersContainer + } + + Component.onCompleted: { + // Test if QtMultimedia is available by trying to create a simple component + try { + var testComponent = Qt.createQmlObject(` + import QtQuick + import QtMultimedia + Item {} + `, root, "MultimediaTest"); + if (testComponent) { + multimediaAvailable = true; + testComponent.destroy(); + Logger.i("SoundService", "QtMultimedia found - sound playback enabled"); + } + } catch (e) { + multimediaAvailable = false; + Logger.w("SoundService", "QtMultimedia not available - no audio will be played from noctalia-shell"); + } + } + + function resolvePath(soundPath) { + if (!soundPath || soundPath === "") { + return ""; + } + + let resolvedPath = soundPath; + + // If it's just a filename (no path separators), assume it's in Assets/Sounds/ + if (!soundPath.includes("/") && !soundPath.startsWith("file://")) { + resolvedPath = Quickshell.shellDir + "/Assets/Sounds/" + soundPath; + } else if (!soundPath.startsWith("/") && !soundPath.startsWith("file://")) { + // Relative path - assume it's relative to shellDir + resolvedPath = Quickshell.shellDir + "/" + soundPath; + } else if (soundPath.startsWith("file://")) { + resolvedPath = soundPath.substring(7); // Remove "file://" prefix + } + // Absolute paths are used as-is + + return resolvedPath; + } + + function playSound(soundPath, options) { + if (!soundPath || soundPath === "") { + Logger.w("SoundService", "No sound path provided"); + return; + } + + if (!multimediaAvailable) { + Logger.d("SoundService", "QtMultimedia not available, cannot play sound:", soundPath); + return; + } + + const opts = options || {}; + const volume = opts.volume !== undefined ? opts.volume : 1.0; + const fallback = opts.fallback !== undefined ? opts.fallback : false; + const repeat = opts.repeat !== undefined ? opts.repeat : false; + + // Resolve path + const resolvedPath = resolvePath(soundPath); + + // Stop any existing player for this path if it's looping + if (repeat && activePlayers[resolvedPath]) { + stopSound(soundPath); + } + + // Create MediaPlayer instance dynamically with QtMultimedia import + const loopsValue = repeat ? "MediaPlayer.Infinite" : "1"; + const escapedPath = resolvedPath.replace(/\\/g, "\\\\").replace(/"/g, '\\"'); + const playerQml = ` + import QtQuick + import QtMultimedia + import Quickshell + import qs.compat.noctalia.Commons + import qs.compat.noctalia.Services.System + MediaPlayer { + id: mediaPlayer + property string resolvedPath: "${escapedPath}" + property bool shouldFallback: ${fallback && !repeat} + property real soundVolume: ${Math.max(0, Math.min(1, volume))} + source: "file://${escapedPath}" + loops: ${loopsValue} + audioOutput: AudioOutput { + volume: soundVolume + } + onErrorOccurred: { + Logger.w("SoundService", "Error playing sound:", source, error, errorString); + if (shouldFallback) { + const fallbackPath = Quickshell.shellDir + "/Assets/Sounds/notification.mp3"; + if (fallbackPath !== resolvedPath) { + SoundService.playSound(fallbackPath, { + volume: soundVolume, + fallback: false, + repeat: false + }); + } + } + if (SoundService.activePlayers[resolvedPath]) { + delete SoundService.activePlayers[resolvedPath]; + } + destroy(); + } + onPlaybackStateChanged: function (state) { + if (state === MediaPlayer.StoppedState && loops === 1) { + if (SoundService.activePlayers[resolvedPath]) { + delete SoundService.activePlayers[resolvedPath]; + } + destroy(); + } + } + Component.onCompleted: { + play(); + } + } + `; + + try { + const player = Qt.createQmlObject(playerQml, playersContainer, "MediaPlayer_" + resolvedPath.replace(/[^a-zA-Z0-9]/g, "_")); + + if (!player) { + Logger.w("SoundService", "Failed to create MediaPlayer for:", resolvedPath); + // Try fallback if requested + if (fallback && !repeat) { + const defaultSound = Quickshell.shellDir + "/Assets/Sounds/notification.mp3"; + if (defaultSound !== resolvedPath) { + playSound(defaultSound, { + volume: volume, + fallback: false, + repeat: false + }); + } + } + return; + } + + // Store player in activePlayers map + activePlayers[resolvedPath] = player; + + Logger.d("SoundService", "Playing sound:", resolvedPath, `(volume: ${Math.round(volume * 100)}%)`, repeat ? "(repeat)" : ""); + } catch (e) { + Logger.w("SoundService", "Failed to create MediaPlayer:", e); + // Try fallback if requested + if (fallback && !repeat) { + const defaultSound = Quickshell.shellDir + "/Assets/Sounds/notification.mp3"; + if (defaultSound !== resolvedPath) { + playSound(defaultSound, { + volume: volume, + fallback: false, + repeat: false + }); + } + } + } + } + + function stopSound(soundPath) { + if (!multimediaAvailable) { + // If multimedia isn't available, there are no active players to stop + return; + } + + if (soundPath) { + // Resolve path the same way as playSound + const resolvedPath = resolvePath(soundPath); + + // Stop and remove the player for this specific sound + if (activePlayers[resolvedPath]) { + const player = activePlayers[resolvedPath]; + player.stop(); + delete activePlayers[resolvedPath]; + player.destroy(); + Logger.d("SoundService", "Stopped sound:", resolvedPath); + } + } else { + // Stop all active players (typically used for repeating sounds) + const paths = Object.keys(activePlayers); + for (let i = 0; i < paths.length; i++) { + const path = paths[i]; + const player = activePlayers[path]; + player.stop(); + player.destroy(); + } + activePlayers = {}; + Logger.d("SoundService", "Stopped all sounds"); + } + } +} diff --git a/quickshell/compat/noctalia/Services/System/SystemStatService.qml b/quickshell/compat/noctalia/Services/System/SystemStatService.qml new file mode 100644 index 0000000..254dcfc --- /dev/null +++ b/quickshell/compat/noctalia/Services/System/SystemStatService.qml @@ -0,0 +1,1506 @@ +pragma Singleton +import Qt.labs.folderlistmodel + +import QtQuick +import Quickshell +import Quickshell.Io +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Services.UI + +Singleton { + id: root + + // Component registration - only poll when something needs system stat data + function registerComponent(componentId) { + root._registered[componentId] = true; + root._registered = Object.assign({}, root._registered); + Logger.d("SystemStat", "Component registered:", componentId, "- total:", root._registeredCount); + } + + function unregisterComponent(componentId) { + delete root._registered[componentId]; + root._registered = Object.assign({}, root._registered); + Logger.d("SystemStat", "Component unregistered:", componentId, "- total:", root._registeredCount); + } + + property var _registered: ({}) + readonly property int _registeredCount: Object.keys(_registered).length + readonly property bool _lockScreenActive: PanelService.lockScreen?.active ?? false + readonly property bool shouldRun: _registeredCount > 0 && !_lockScreenActive + + // Polling intervals (hardcoded to sensible values per stat type) + readonly property int cpuUsageIntervalMs: 1000 + readonly property int cpuFreqIntervalMs: 3000 + readonly property int memIntervalMs: 5000 + readonly property int networkIntervalMs: 3000 + readonly property int loadAvgIntervalMs: 10000 + readonly property int diskIntervalMs: 30000 + readonly property int gpuIntervalMs: 5000 + + // Public values + property real cpuUsage: 0 + property list coresUsage: [] + property real cpuTemp: 0 + property string cpuFreq: "0.0GHz" + property real cpuFreqRatio: 0 + property real cpuGlobalMaxFreq: 3.5 + property real gpuTemp: 0 + property bool gpuAvailable: false + property string gpuType: "" // "amd", "intel", "nvidia" + property real memGb: 0 + property real memPercent: 0 + property real memTotalGb: 0 + property real swapGb: 0 + property real swapPercent: 0 + property real swapTotalGb: 0 + property var diskPercents: ({}) + property var diskAvailPercents: ({}) // available disk space in percent + property var diskUsedGb: ({}) // Used space in GB per mount point + property var diskAvailableGb: ({}) // available space in GB per mount point + property var diskSizeGb: ({}) // Total size in GB per mount point + property real rxSpeed: 0 + property real txSpeed: 0 + property real zfsArcSizeKb: 0 // ZFS ARC cache size in KB + property real zfsArcCminKb: 0 // ZFS ARC minimum (non-reclaimable) size in KB + property real loadAvg1: 0 + property real loadAvg5: 0 + property real loadAvg15: 0 + property int nproc: 0 // Number of cpu cores + + // History arrays (2 minutes of data, length computed from polling interval) + // Pre-filled with zeros so the graph scrolls smoothly from the start + readonly property int historyDurationMs: (1 * 60 * 1000) // 1 minute + + // Computed history lengths based on polling intervals + readonly property int cpuHistoryLength: Math.ceil(historyDurationMs / cpuUsageIntervalMs) + readonly property int gpuHistoryLength: Math.ceil(historyDurationMs / gpuIntervalMs) + readonly property int memHistoryLength: Math.ceil(historyDurationMs / memIntervalMs) + readonly property int diskHistoryLength: Math.max(10, Math.ceil(historyDurationMs / diskIntervalMs)) + readonly property int networkHistoryLength: Math.ceil(historyDurationMs / networkIntervalMs) + + property var cpuHistory: new Array(cpuHistoryLength).fill(0) + property var cpuTempHistory: new Array(cpuHistoryLength).fill(40) // Reasonable default temp + property var gpuTempHistory: new Array(gpuHistoryLength).fill(40) // Reasonable default temp + property var memHistory: new Array(memHistoryLength).fill(0) + property var diskHistories: ({}) // Keyed by mount path, initialized on first update + property var rxSpeedHistory: new Array(networkHistoryLength).fill(0) + property var txSpeedHistory: new Array(networkHistoryLength).fill(0) + + // Historical min/max tracking (since shell started) for consistent graph scaling + // Temperature defaults create a valid 30-80°C range that expands as real data comes in + property real cpuTempHistoryMin: 30 + property real cpuTempHistoryMax: 80 + property real gpuTempHistoryMin: 30 + property real gpuTempHistoryMax: 80 + // Network uses autoscaling from current history window + // Disk is always 0-100% + + // History management - called from update functions, not change handlers + // (change handlers don't fire when value stays the same) + function pushCpuHistory() { + let h = cpuHistory.slice(); + h.push(cpuUsage); + if (h.length > cpuHistoryLength) + h.shift(); + cpuHistory = h; + } + + function pushCpuTempHistory() { + if (cpuTemp > 0) { + if (cpuTemp < cpuTempHistoryMin) + cpuTempHistoryMin = cpuTemp; + if (cpuTemp > cpuTempHistoryMax) + cpuTempHistoryMax = cpuTemp; + } + let h = cpuTempHistory.slice(); + h.push(cpuTemp); + if (h.length > cpuHistoryLength) + h.shift(); + cpuTempHistory = h; + } + + function pushGpuHistory() { + if (gpuTemp > 0) { + if (gpuTemp < gpuTempHistoryMin) + gpuTempHistoryMin = gpuTemp; + if (gpuTemp > gpuTempHistoryMax) + gpuTempHistoryMax = gpuTemp; + } + let h = gpuTempHistory.slice(); + h.push(gpuTemp); + if (h.length > gpuHistoryLength) + h.shift(); + gpuTempHistory = h; + } + + function pushMemHistory() { + let h = memHistory.slice(); + h.push(memPercent); + if (h.length > memHistoryLength) + h.shift(); + memHistory = h; + } + + function pushDiskHistory() { + let newHistories = {}; + for (let path in diskPercents) { + // Pre-fill with zeros if this is a new path + let h = diskHistories[path] ? diskHistories[path].slice() : new Array(diskHistoryLength).fill(0); + h.push(diskPercents[path]); + if (h.length > diskHistoryLength) + h.shift(); + newHistories[path] = h; + } + diskHistories = newHistories; + } + + function pushNetworkHistory() { + let rxH = rxSpeedHistory.slice(); + rxH.push(rxSpeed); + if (rxH.length > networkHistoryLength) + rxH.shift(); + rxSpeedHistory = rxH; + + let txH = txSpeedHistory.slice(); + txH.push(txSpeed); + if (txH.length > networkHistoryLength) + txH.shift(); + txSpeedHistory = txH; + } + + // Network max speed tracking (autoscales from current history window) + // Minimum floor of 1 MB/s so graph doesn't fluctuate at low speeds + readonly property real rxMaxSpeed: { + const max = Math.max(...rxSpeedHistory); + return Math.max(max, 1000000); // 1 MB/s floor + } + readonly property real txMaxSpeed: { + const max = Math.max(...txSpeedHistory); + return Math.max(max, 512000); // 512 KB/s floor + } + + // Ready-to-use ratios based on current maximums (0..1 range) + readonly property real rxRatio: rxMaxSpeed > 0 ? Math.min(1, rxSpeed / rxMaxSpeed) : 0 + readonly property real txRatio: txMaxSpeed > 0 ? Math.min(1, txSpeed / txMaxSpeed) : 0 + + // Color resolution (respects useCustomColors setting) + readonly property color warningColor: Settings.data.systemMonitor.useCustomColors ? (Settings.data.systemMonitor.warningColor || Color.mTertiary) : Color.mTertiary + readonly property color criticalColor: Settings.data.systemMonitor.useCustomColors ? (Settings.data.systemMonitor.criticalColor || Color.mError) : Color.mError + + // Threshold values from settings + readonly property int cpuWarningThreshold: Settings.data.systemMonitor.cpuWarningThreshold + readonly property int cpuCriticalThreshold: Settings.data.systemMonitor.cpuCriticalThreshold + readonly property int tempWarningThreshold: Settings.data.systemMonitor.tempWarningThreshold + readonly property int tempCriticalThreshold: Settings.data.systemMonitor.tempCriticalThreshold + readonly property int gpuWarningThreshold: Settings.data.systemMonitor.gpuWarningThreshold + readonly property int gpuCriticalThreshold: Settings.data.systemMonitor.gpuCriticalThreshold + readonly property int memWarningThreshold: Settings.data.systemMonitor.memWarningThreshold + readonly property int memCriticalThreshold: Settings.data.systemMonitor.memCriticalThreshold + readonly property int swapWarningThreshold: Settings.data.systemMonitor.swapWarningThreshold + readonly property int swapCriticalThreshold: Settings.data.systemMonitor.swapCriticalThreshold + readonly property int diskWarningThreshold: Settings.data.systemMonitor.diskWarningThreshold + readonly property int diskCriticalThreshold: Settings.data.systemMonitor.diskCriticalThreshold + readonly property int diskAvailWarningThreshold: Settings.data.systemMonitor.diskAvailWarningThreshold + readonly property int diskAvailCriticalThreshold: Settings.data.systemMonitor.diskAvailCriticalThreshold + + // Computed warning/critical states (uses >= inclusive comparison) + readonly property bool cpuWarning: cpuUsage >= cpuWarningThreshold + readonly property bool cpuCritical: cpuUsage >= cpuCriticalThreshold + readonly property bool tempWarning: cpuTemp >= tempWarningThreshold + readonly property bool tempCritical: cpuTemp >= tempCriticalThreshold + readonly property bool gpuWarning: gpuAvailable && gpuTemp >= gpuWarningThreshold + readonly property bool gpuCritical: gpuAvailable && gpuTemp >= gpuCriticalThreshold + readonly property bool memWarning: memPercent >= memWarningThreshold + readonly property bool memCritical: memPercent >= memCriticalThreshold + readonly property bool swapWarning: swapPercent >= swapWarningThreshold + readonly property bool swapCritical: swapPercent >= swapCriticalThreshold + + // Helper functions for disk (disk path is dynamic) + function isDiskWarning(diskPath, available = false) { + return available ? (diskAvailPercents[diskPath] || 0) <= diskAvailWarningThreshold : (diskPercents[diskPath] || 0) >= diskWarningThreshold; + } + + function isDiskCritical(diskPath, available = false) { + return available ? (diskAvailPercents[diskPath] || 0) <= diskAvailCriticalThreshold : (diskPercents[diskPath] || 0) >= diskCriticalThreshold; + } + + // Ready-to-use stat colors (for gauges, panels, icons) + readonly property color cpuColor: cpuCritical ? criticalColor : (cpuWarning ? warningColor : Color.mPrimary) + readonly property color tempColor: tempCritical ? criticalColor : (tempWarning ? warningColor : Color.mPrimary) + readonly property color gpuColor: gpuCritical ? criticalColor : (gpuWarning ? warningColor : Color.mPrimary) + readonly property color memColor: memCritical ? criticalColor : (memWarning ? warningColor : Color.mPrimary) + readonly property color swapColor: swapCritical ? criticalColor : (swapWarning ? warningColor : Color.mPrimary) + + function getCoreUsageColor(usage) { + if (usage >= cpuCriticalThreshold) + return criticalColor; + if (usage >= cpuWarningThreshold) + return warningColor; + return Color.mPrimary; + } + + function getDiskColor(diskPath, available = false) { + return isDiskCritical(diskPath, available) ? criticalColor : (isDiskWarning(diskPath, available) ? warningColor : Color.mPrimary); + } + + // Internal state for CPU calculation + property var prevCpuStats: null + property var prevCpuCoresStats: null + + // Internal state for network speed calculation + // Previous Bytes need to be stored as 'real' as they represent the total of bytes transfered + // since the computer started, so their value will easily overlfow a 32bit int. + property real prevRxBytes: 0 + property real prevTxBytes: 0 + property real prevTime: 0 + + // Cpu temperature is the most complex + readonly property var supportedTempCpuSensorNames: ["coretemp", "k10temp", "zenpower"] + property string cpuTempSensorName: "" + property string cpuTempHwmonPath: "" + // For Intel coretemp averaging of all cores/sensors + property var intelTempValues: [] + property int intelTempFilesChecked: 0 + property int intelTempMaxFiles: 20 // Will test up to temp20_input + + // Thermal zone fallback (for ARM SoCs with SCMI sensors, etc.) + property var cpuThermalZonePaths: [] // All matching CPU zones for averaging + property string gpuThermalZonePath: "" + + // GPU temperature detection + // On dual-GPU systems, we prioritize discrete GPUs over integrated GPUs + // Priority: NVIDIA (opt-in) > AMD dGPU > Intel Arc > AMD iGPU + // Note: NVIDIA requires opt-in because nvidia-smi wakes the dGPU on laptops, draining battery + readonly property var supportedTempGpuSensorNames: ["amdgpu", "xe"] + property string gpuTempHwmonPath: "" + property var foundGpuSensors: [] // [{hwmonPath, type, hasDedicatedVram}] + property int gpuVramCheckIndex: 0 + + // -------------------------------------------- + Component.onCompleted: { + Logger.i("SystemStat", "Service started (polling deferred until a consumer registers)."); + + // Kickoff the cpu name detection for temperature (one-time probes, not polling) + cpuTempNameReader.checkNext(); + + // Kickoff the gpu sensor detection for temperature (one-time probes, not polling) + gpuTempNameReader.checkNext(); + + // Get nproc on startup (one-time) + nprocProcess.running = true; + } + + onShouldRunChanged: { + if (shouldRun) { + // Reset differential state so first readings after resume are clean + root.prevCpuStats = null; + root.prevCpuCoresStats = null; + root.prevTime = 0; + + // Trigger initial reads + zfsArcStatsFile.reload(); + loadAvgFile.reload(); + + // Start persistent disk shell + if (!dfShell.running) { + dfShell.running = true; + } + } else { + // Stop persistent disk shell + if (dfShell.running) { + dfShell.running = false; + } + } + } + + // Re-run GPU detection when dGPU opt-in setting changes + Connections { + target: Settings.data.systemMonitor + function onEnableDgpuMonitoringChanged() { + Logger.i("SystemStat", "dGPU monitoring opt-in setting changed, re-detecting GPUs"); + restartGpuDetection(); + } + } + + // Reset differential state after suspend so the first reading is treated as fresh + Connections { + target: Time + function onResumed() { + Logger.i("SystemStat", "System resumed - resetting differential state"); + root.prevCpuStats = null; + root.prevCpuCoresStats = null; + root.prevTime = 0; + } + } + + function restartGpuDetection() { + // Reset GPU state + root.gpuAvailable = false; + root.gpuType = ""; + root.gpuTempHwmonPath = ""; + root.gpuTemp = 0; + root.foundGpuSensors = []; + root.gpuVramCheckIndex = 0; + + // Restart GPU detection + gpuTempNameReader.currentIndex = 0; + gpuTempNameReader.checkNext(); + } + + // -------------------------------------------- + // Timer for CPU usage and temperature + Timer { + id: cpuTimer + interval: root.cpuUsageIntervalMs + repeat: true + running: root.shouldRun + triggeredOnStart: true + onTriggered: { + cpuStatFile.reload(); + updateCpuTemperature(); + } + } + + // Timer for CPU frequency (slower — /proc/cpuinfo is large and freq changes infrequently) + Timer { + id: cpuFreqTimer + interval: root.cpuFreqIntervalMs + repeat: true + running: root.shouldRun + triggeredOnStart: true + onTriggered: cpuInfoFile.reload() + } + + // Timer for load average + Timer { + id: loadAvgTimer + interval: root.loadAvgIntervalMs + repeat: true + running: root.shouldRun + triggeredOnStart: true + onTriggered: loadAvgFile.reload() + } + + // Timer for memory stats + Timer { + id: memoryTimer + interval: root.memIntervalMs + repeat: true + running: root.shouldRun + triggeredOnStart: true + onTriggered: { + memInfoFile.reload(); + zfsArcStatsFile.reload(); + } + } + + // Timer for disk usage + Timer { + id: diskTimer + interval: root.diskIntervalMs + repeat: true + running: root.shouldRun + triggeredOnStart: true + onTriggered: { + if (dfShell.running) { + dfShell.write("df --output=target,pcent,used,size,avail --block-size=1 -x efivarfs 2>/dev/null; echo '@@DF_END@@'\n"); + } + } + } + + // Timer for network speeds + Timer { + id: networkTimer + interval: root.networkIntervalMs + repeat: true + running: root.shouldRun + triggeredOnStart: true + onTriggered: netDevFile.reload() + } + + // Timer for GPU temperature + Timer { + id: gpuTempTimer + interval: root.gpuIntervalMs + repeat: true + running: root.shouldRun && root.gpuAvailable + triggeredOnStart: true + onTriggered: updateGpuTemperature() + } + + // -------------------------------------------- + // FileView components for reading system files + FileView { + id: memInfoFile + path: "/proc/meminfo" + onLoaded: parseMemoryInfo(text()) + } + + FileView { + id: cpuStatFile + path: "/proc/stat" + onLoaded: calculateCpuUsage(text()) + } + + FileView { + id: netDevFile + path: "/proc/net/dev" + onLoaded: calculateNetworkSpeed(text()) + } + + FileView { + id: loadAvgFile + path: "/proc/loadavg" + onLoaded: parseLoadAverage(text()) + } + + // ZFS ARC stats file (only exists on ZFS systems) + FileView { + id: zfsArcStatsFile + path: "/proc/spl/kstat/zfs/arcstats" + printErrors: false + onLoaded: parseZfsArcStats(text()) + onLoadFailed: { + // File doesn't exist (non-ZFS system), set ARC values to 0 + root.zfsArcSizeKb = 0; + root.zfsArcCminKb = 0; + } + } + + // -------------------------------------------- + // Persistent shell for disk usage queries (avoids fork+exec of large Quickshell process every poll) + // Uses 'df' aka 'disk free' + // "-x efivarfs" skips efivarfs mountpoints, for which the `statfs` syscall may cause system-wide stuttering + // --block-size=1 gives us bytes for precise GB calculation + // Timer writes commands to stdin; SplitParser reads output delimited by @@DF_END@@ + Process { + id: dfShell + command: ["sh"] + stdinEnabled: true + running: false + + onRunningChanged: { + if (!running && root.shouldRun) { + // Restart if it died unexpectedly while we still need it + Logger.w("SystemStat", "Disk shell exited unexpectedly, restarting"); + Qt.callLater(() => { + dfShell.running = true; + }); + } + } + + stdout: SplitParser { + splitMarker: "@@DF_END@@" + onRead: data => { + const lines = data.trim().split('\n'); + const newPercents = {}; + const newAvailPercents = {}; + const newUsedGb = {}; + const newSizeGb = {}; + const newAvailableGb = {}; + const bytesPerGb = 1000 * 1000 * 1000; + // Start from line 1 (skip header) + for (var i = 1; i < lines.length; i++) { + const parts = lines[i].trim().split(/\s+/); + if (parts.length >= 5) { + const target = parts[0]; + const percent = parseInt(parts[1].replace(/[^0-9]/g, '')) || 0; + const usedBytes = parseFloat(parts[2]) || 0; + const sizeBytes = parseFloat(parts[3]) || 0; + const availBytes = parseFloat(parts[4]) || 0; + const availPercent = sizeBytes > 0 ? (availBytes / sizeBytes) * 100 : 0; + newPercents[target] = percent; + newAvailPercents[target] = Math.round(availPercent); + newUsedGb[target] = usedBytes / bytesPerGb; + newSizeGb[target] = sizeBytes / bytesPerGb; + newAvailableGb[target] = availBytes / bytesPerGb; + } + } + root.diskPercents = newPercents; + root.diskAvailPercents = newAvailPercents; + root.diskUsedGb = newUsedGb; + root.diskSizeGb = newSizeGb; + root.diskAvailableGb = newAvailableGb; + root.pushDiskHistory(); + } + } + } + + // Process to get number of processors + Process { + id: nprocProcess + command: ["nproc"] + running: false + stdout: StdioCollector { + onStreamFinished: { + root.nproc = parseInt(text.trim()); + } + } + } + + // FileView to get avg cpu frequency (replaces subprocess spawn of `cat /proc/cpuinfo`) + FileView { + id: cpuInfoFile + path: "/proc/cpuinfo" + onLoaded: { + let txt = text(); + let matches = txt.match(/cpu MHz\s+:\s+([0-9.]+)/g); + if (matches && matches.length > 0) { + let totalFreq = 0.0; + for (let i = 0; i < matches.length; i++) { + totalFreq += parseFloat(matches[i].split(":")[1]); + } + let avgFreq = (totalFreq / matches.length) / 1000.0; + root.cpuFreq = avgFreq.toFixed(1) + "GHz"; + cpuMaxFreqFile.reload(); + if (avgFreq > root.cpuGlobalMaxFreq) + root.cpuGlobalMaxFreq = avgFreq; + if (root.cpuGlobalMaxFreq > 0) { + root.cpuFreqRatio = Math.min(1.0, avgFreq / root.cpuGlobalMaxFreq); + } + } + } + } + + // FileView to get maximum CPU frequency limit (replaces subprocess spawn) + // Reads cpu0's scaling_max_freq as representative value + FileView { + id: cpuMaxFreqFile + path: "/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq" + printErrors: false + onLoaded: { + let maxKHz = parseInt(text().trim()); + if (!isNaN(maxKHz) && maxKHz > 0) { + let newMaxFreq = maxKHz / 1000000.0; + if (Math.abs(root.cpuGlobalMaxFreq - newMaxFreq) > 0.01) { + root.cpuGlobalMaxFreq = newMaxFreq; + } + } + } + } + + // -------------------------------------------- + // -------------------------------------------- + // CPU Temperature + // It's more complex. + // ---- + // #1 - Find a common cpu sensor name ie: "coretemp", "k10temp", "zenpower" + FileView { + id: cpuTempNameReader + property int currentIndex: 0 + printErrors: false + + function checkNext() { + if (currentIndex >= 16) { + // No hwmon sensor found, try thermal_zone fallback (ARM SoCs, SCMI, etc.) + thermalZoneScanner.startScan(); + return; + } + + //Logger.i("SystemStat", "---- Probing: hwmon", currentIndex) + cpuTempNameReader.path = `/sys/class/hwmon/hwmon${currentIndex}/name`; + cpuTempNameReader.reload(); + } + + onLoaded: { + const name = text().trim(); + if (root.supportedTempCpuSensorNames.includes(name)) { + root.cpuTempSensorName = name; + root.cpuTempHwmonPath = `/sys/class/hwmon/hwmon${currentIndex}`; + Logger.i("SystemStat", `Found ${root.cpuTempSensorName} CPU thermal sensor at ${root.cpuTempHwmonPath}`); + } else { + currentIndex++; + Qt.callLater(() => { + // Qt.callLater is mandatory + checkNext(); + }); + } + } + + onLoadFailed: function (error) { + currentIndex++; + Qt.callLater(() => { + // Qt.callLater is mandatory + checkNext(); + }); + } + } + + // ---- + // #2 - Read sensor value + FileView { + id: cpuTempReader + printErrors: false + + onLoaded: { + const data = text().trim(); + if (root.cpuTempSensorName === "coretemp") { + // For Intel, collect all temperature values + const temp = parseInt(data) / 1000.0; + //console.log(temp, cpuTempReader.path) + root.intelTempValues.push(temp); + Qt.callLater(() => { + // Qt.callLater is mandatory + checkNextIntelTemp(); + }); + } else { + // For AMD sensors (k10temp and zenpower), directly set the temperature + root.cpuTemp = Math.round(parseInt(data) / 1000.0); + root.pushCpuTempHistory(); + } + } + onLoadFailed: function (error) { + Qt.callLater(() => { + // Qt.callLater is mandatory + checkNextIntelTemp(); + }); + } + } + + // -------------------------------------------- + // Thermal zone fallback for CPU and GPU temperature + // Used on ARM SoCs (e.g., SCMI sensors) where hwmon doesn't expose + // coretemp/k10temp/zenpower. Scans /sys/class/thermal/thermal_zoneN/type + // for CPU and GPU zone names, then reads temp from all matching zones. + // + // CPU: reads all cpu-*-thermal zones and reports the hottest core. + // GPU: prefers gpu-avg-thermal (firmware average), falls back to max of gpu[0-9]-thermal. + + FileView { + id: thermalZoneScanner + property int currentIndex: 0 + property var cpuZones: [] + property var gpuZones: [] + property string gpuAvgZonePath: "" + printErrors: false + + function startScan() { + currentIndex = 0; + cpuZones = []; + gpuZones = []; + gpuAvgZonePath = ""; + checkNext(); + } + + function checkNext() { + if (currentIndex >= 20) { + finishScan(); + return; + } + thermalZoneScanner.path = `/sys/class/thermal/thermal_zone${currentIndex}/type`; + thermalZoneScanner.reload(); + } + + onLoaded: { + const name = text().trim(); + const zonePath = `/sys/class/thermal/thermal_zone${currentIndex}`; + if (name.startsWith("cpu") && name.endsWith("thermal")) { + cpuZones.push({ + "type": name, + "path": zonePath + "/temp" + }); + } else if (name === "gpu-avg-thermal") { + gpuAvgZonePath = zonePath + "/temp"; + } else if (/^gpu[0-9]+-?thermal$/.test(name)) { + gpuZones.push({ + "type": name, + "path": zonePath + "/temp" + }); + } + currentIndex++; + Qt.callLater(() => { + checkNext(); + }); + } + + onLoadFailed: function (error) { + currentIndex++; + Qt.callLater(() => { + checkNext(); + }); + } + + function finishScan() { + // CPU thermal zones + if (cpuZones.length > 0) { + root.cpuTempSensorName = "thermal_zone"; + root.cpuThermalZonePaths = cpuZones.map(z => z.path); + const types = cpuZones.map(z => z.type).join(", "); + Logger.i("SystemStat", `Found ${cpuZones.length} CPU thermal zone(s): ${types}`); + } else if (root.cpuTempHwmonPath === "") { + Logger.w("SystemStat", "No supported temperature sensor found"); + } + + // GPU thermal zones + if (gpuAvgZonePath !== "") { + root.gpuThermalZonePath = gpuAvgZonePath; + root.gpuAvailable = true; + root.gpuType = "thermal_zone"; + Logger.i("SystemStat", `Found GPU thermal zone: gpu-avg-thermal`); + } else if (gpuZones.length > 0) { + root.gpuThermalZonePaths = gpuZones.map(z => z.path); + root.gpuThermalZonePath = gpuZones[0].path; // fallback single path + root.gpuAvailable = true; + root.gpuType = "thermal_zone"; + const types = gpuZones.map(z => z.type).join(", "); + Logger.i("SystemStat", `Found ${gpuZones.length} GPU thermal zone(s): ${types} (using max)`); + } + } + } + + // Thermal zone reader for CPU: reads all zones, reports max (hottest core) + FileView { + id: cpuThermalZoneReader + property int currentZoneIndex: 0 + property var collectedTemps: [] + printErrors: false + + onLoaded: { + const temp = parseInt(text().trim()) / 1000.0; + if (!isNaN(temp) && temp > 0) + collectedTemps.push(temp); + currentZoneIndex++; + Qt.callLater(() => { + readNextCpuThermalZone(); + }); + } + + onLoadFailed: function (error) { + currentZoneIndex++; + Qt.callLater(() => { + readNextCpuThermalZone(); + }); + } + } + + function readNextCpuThermalZone() { + if (cpuThermalZoneReader.currentZoneIndex >= root.cpuThermalZonePaths.length) { + if (cpuThermalZoneReader.collectedTemps.length > 0) { + root.cpuTemp = Math.round(Math.max(...cpuThermalZoneReader.collectedTemps)); + } else { + root.cpuTemp = 0; + } + root.pushCpuTempHistory(); + return; + } + cpuThermalZoneReader.path = root.cpuThermalZonePaths[cpuThermalZoneReader.currentZoneIndex]; + cpuThermalZoneReader.reload(); + } + + // Thermal zone reader for GPU: reads single zone (gpu-avg-thermal) or max of gpu[N] zones + FileView { + id: gpuThermalZoneReader + property int currentZoneIndex: 0 + property var collectedTemps: [] + printErrors: false + + onLoaded: { + const temp = parseInt(text().trim()) / 1000.0; + if (!isNaN(temp) && temp > 0) + collectedTemps.push(temp); + + // If we have multiple GPU zones (no gpu-avg), iterate and take max + if (root.gpuThermalZonePaths && root.gpuThermalZonePaths.length > 0) { + currentZoneIndex++; + if (currentZoneIndex < root.gpuThermalZonePaths.length) { + Qt.callLater(() => { + readNextGpuThermalZone(); + }); + return; + } + // All zones read, take max + root.gpuTemp = Math.round(Math.max(...collectedTemps)); + } else { + // Single gpu-avg-thermal zone + root.gpuTemp = Math.round(temp); + } + root.pushGpuHistory(); + } + } + + function readNextGpuThermalZone() { + gpuThermalZoneReader.path = root.gpuThermalZonePaths[gpuThermalZoneReader.currentZoneIndex]; + gpuThermalZoneReader.reload(); + } + + // Property to store multiple GPU thermal zone paths (when no gpu-avg is available) + property var gpuThermalZonePaths: [] + + // -------------------------------------------- + // -------------------------------------------- + // GPU Temperature + // On dual-GPU systems (e.g., Intel iGPU + NVIDIA dGPU, or AMD APU + AMD dGPU), + // we scan all hwmon entries, then select the best GPU based on priority. + // ---- + // #1 - Scan all hwmon entries to find GPU sensors + FileView { + id: gpuTempNameReader + property int currentIndex: 0 + printErrors: false + + function checkNext() { + if (currentIndex >= 16) { + // Finished scanning all hwmon entries + // Only check nvidia-smi if user has explicitly enabled dGPU monitoring (opt-in) + // because nvidia-smi wakes up the dGPU on laptops, draining battery + if (Settings.data.systemMonitor.enableDgpuMonitoring) { + Logger.d("SystemStat", `Found ${root.foundGpuSensors.length} sysfs GPU sensor(s), checking nvidia-smi (dGPU opt-in enabled)`); + nvidiaSmiCheck.running = true; + } else { + Logger.d("SystemStat", `Found ${root.foundGpuSensors.length} sysfs GPU sensor(s), skipping nvidia-smi (dGPU opt-in disabled)`); + root.gpuVramCheckIndex = 0; + checkNextGpuVram(); + } + return; + } + + gpuTempNameReader.path = `/sys/class/hwmon/hwmon${currentIndex}/name`; + gpuTempNameReader.reload(); + } + + onLoaded: { + const name = text().trim(); + if (root.supportedTempGpuSensorNames.includes(name)) { + // Collect this GPU sensor, don't stop - continue scanning for more + const hwmonPath = `/sys/class/hwmon/hwmon${currentIndex}`; + const gpuType = name === "amdgpu" ? "amd" : "intel"; + root.foundGpuSensors.push({ + "hwmonPath": hwmonPath, + "type": gpuType, + "hasDedicatedVram": false // Will be checked later for AMD + }); + Logger.d("SystemStat", `Found ${name} GPU sensor at ${hwmonPath}`); + } + // Continue scanning regardless of whether we found a match + currentIndex++; + Qt.callLater(() => { + checkNext(); + }); + } + + onLoadFailed: function (error) { + currentIndex++; + Qt.callLater(() => { + checkNext(); + }); + } + } + + // ---- + // #2 - Read GPU sensor value (AMD/Intel via sysfs) + FileView { + id: gpuTempReader + printErrors: false + + onLoaded: { + const data = text().trim(); + root.gpuTemp = Math.round(parseInt(data) / 1000.0); + root.pushGpuHistory(); + } + } + + // ---- + // #3 - Check if nvidia-smi is available (for NVIDIA GPUs) + Process { + id: nvidiaSmiCheck + command: ["sh", "-c", "command -v nvidia-smi"] + running: false + stdout: StdioCollector { + onStreamFinished: { + if (text.trim().length > 0) { + // Add NVIDIA as a GPU option (always discrete, highest priority) + root.foundGpuSensors.push({ + "hwmonPath": "", + "type": "nvidia", + "hasDedicatedVram": true // NVIDIA is always discrete + }); + Logger.d("SystemStat", "Found NVIDIA GPU (nvidia-smi available)"); + } + // After NVIDIA check, check VRAM for AMD GPUs to distinguish dGPU from iGPU + root.gpuVramCheckIndex = 0; + checkNextGpuVram(); + } + } + } + + // ---- + // #4 - Check VRAM for AMD GPUs to distinguish dGPU from iGPU + // dGPUs have dedicated VRAM, iGPUs don't (use system RAM) + FileView { + id: gpuVramChecker + printErrors: false + + onLoaded: { + // File exists and has content = dGPU with dedicated VRAM + const vramSize = parseInt(text().trim()); + if (vramSize > 0) { + root.foundGpuSensors[root.gpuVramCheckIndex].hasDedicatedVram = true; + Logger.d("SystemStat", `GPU at ${root.foundGpuSensors[root.gpuVramCheckIndex].hwmonPath} has dedicated VRAM (dGPU)`); + } + root.gpuVramCheckIndex++; + Qt.callLater(() => { + checkNextGpuVram(); + }); + } + + onLoadFailed: function (error) { + // File doesn't exist = iGPU (no dedicated VRAM) + // hasDedicatedVram is already false by default + root.gpuVramCheckIndex++; + Qt.callLater(() => { + checkNextGpuVram(); + }); + } + } + + // ---- + // #4 - Read GPU temperature via nvidia-smi (NVIDIA only) + Process { + id: nvidiaTempProcess + command: ["nvidia-smi", "--query-gpu=temperature.gpu", "--format=csv,noheader,nounits"] + running: false + stdout: StdioCollector { + onStreamFinished: { + const temp = parseInt(text.trim()); + if (!isNaN(temp)) { + root.gpuTemp = temp; + root.pushGpuHistory(); + } + } + } + } + + // ------------------------------------------------------- + // ------------------------------------------------------- + // Parse ZFS ARC stats from /proc/spl/kstat/zfs/arcstats + function parseZfsArcStats(text) { + if (!text) + return; + const lines = text.split('\n'); + + // The file format is: name type data + // We need to find the lines with "size" and "c_min" and extract the values (third column) + let foundSize = false; + let foundCmin = false; + + for (const line of lines) { + const parts = line.trim().split(/\s+/); + if (parts.length >= 3) { + if (parts[0] === 'size') { + // The value is in bytes, convert to KB + const arcSizeBytes = parseInt(parts[2]) || 0; + root.zfsArcSizeKb = Math.floor(arcSizeBytes / 1024); + foundSize = true; + } else if (parts[0] === 'c_min') { + // The value is in bytes, convert to KB + const arcCminBytes = parseInt(parts[2]) || 0; + root.zfsArcCminKb = Math.floor(arcCminBytes / 1024); + foundCmin = true; + } + + // If we found both, we can return early + if (foundSize && foundCmin) { + return; + } + } + } + + // If fields not found, set to 0 + if (!foundSize) { + root.zfsArcSizeKb = 0; + } + if (!foundCmin) { + root.zfsArcCminKb = 0; + } + } + + // ------------------------------------------------------- + // Parse load average from /proc/loadavg + function parseLoadAverage(text) { + if (!text) + return; + const parts = text.trim().split(/\s+/); + if (parts.length >= 3) { + root.loadAvg1 = parseFloat(parts[0]); + root.loadAvg5 = parseFloat(parts[1]); + root.loadAvg15 = parseFloat(parts[2]); + } + } + + // ------------------------------------------------------- + // Parse memory info from /proc/meminfo + function parseMemoryInfo(text) { + if (!text) + return; + const lines = text.split('\n'); + let memTotal = 0; + let memAvailable = 0; + let swapTotal = 0; + let swapFree = 0; + + for (const line of lines) { + if (line.startsWith('MemTotal:')) { + memTotal = parseInt(line.split(/\s+/)[1]) || 0; + } else if (line.startsWith('MemAvailable:')) { + memAvailable = parseInt(line.split(/\s+/)[1]) || 0; + } else if (line.startsWith('SwapTotal:')) { + swapTotal = parseInt(line.split(/\s+/)[1]) || 0; + } else if (line.startsWith('SwapFree:')) { + swapFree = parseInt(line.split(/\s+/)[1]) || 0; + } + } + + if (memTotal > 0) { + // Calculate usage, adjusting for ZFS ARC cache if present + let usageKb = memTotal - memAvailable; + if (root.zfsArcSizeKb > 0) { + usageKb = Math.max(0, usageKb - root.zfsArcSizeKb + root.zfsArcCminKb); + } + root.memGb = (usageKb / 1048576).toFixed(1); // 1024*1024 = 1048576 + root.memPercent = Math.round((usageKb / memTotal) * 100); + root.memTotalGb = (memTotal / 1048576).toFixed(1); + root.pushMemHistory(); + } + + // Swap usage + root.swapTotalGb = (swapTotal / 1048576).toFixed(1); + if (swapTotal > 0) { + const swapUsedKb = swapTotal - swapFree; + root.swapGb = (swapUsedKb / 1048576).toFixed(1); + root.swapPercent = Math.round((swapUsedKb / swapTotal) * 100); + } else { + root.swapGb = 0; + root.swapPercent = 0; + } + } + + // ------------------------------------------------------- + // Calculate CPU usage from /proc/stat + + function calculateLineUsage(line) { + const parts = line.split(/\s+/); + const stats = { + "user": parseInt(parts[1]) || 0, + "nice": parseInt(parts[2]) || 0, + "system": parseInt(parts[3]) || 0, + "idle": parseInt(parts[4]) || 0, + "iowait": parseInt(parts[5]) || 0, + "irq": parseInt(parts[6]) || 0, + "softirq": parseInt(parts[7]) || 0, + "steal": parseInt(parts[8]) || 0, + "guest": parseInt(parts[9]) || 0, + "guestNice": parseInt(parts[10]) || 0 + }; + return stats; + } + + function computeUsage(prev, curr) { + if (!prev || !curr) + return -1; + const currTotalIdle = curr.idle + curr.iowait; + const currTotal = Object.values(curr).reduce((sum, val) => sum + val, 0); + const prevTotalIdle = prev.idle + prev.iowait; + const prevTotal = Object.values(prev).reduce((sum, val) => sum + val, 0); + + const diffTotal = currTotal - prevTotal; + const diffIdle = currTotalIdle - prevTotalIdle; + if (diffTotal > 0) { + return (((diffTotal - diffIdle) / diffTotal) * 100).toFixed(1); + } + return -1; + } + + function calculateCpuUsage(text) { + if (!text) + return; + const lines = text.split('\n'); + const cpuLine = lines[0]; + + // First line is total CPU + if (!cpuLine.startsWith('cpu ')) + return; + + const currCpuStats = calculateLineUsage(cpuLine); + const usage = computeUsage(root.prevCpuStats, currCpuStats); + + if (usage >= 0) { + root.cpuUsage = usage; + root.pushCpuHistory(); + } + root.prevCpuStats = currCpuStats; + + // Find the number of CPU cores + let nbCores = 0; + for (let i = 1; i < lines.length; i++) { + if (!lines[i].startsWith('cpu')) + break; + nbCores++; + } + + // Fallback if we did not find any cores + if (nbCores === 0) + return; + + // If we found more cores than before, we reset our stats + if (root.coresUsage.length < nbCores) + root.coresUsage = new Array(nbCores).fill(0); + + let coresStats = []; + let newCoresUsage = root.coresUsage.slice(); + for (let i = 0; i < nbCores; i++) { + const coreCpuLine = lines[i + 1]; + const currCoreStats = calculateLineUsage(coreCpuLine); + const coreUsage = computeUsage(root.prevCpuCoresStats?.[i], currCoreStats); + if (coreUsage >= 0) { + newCoresUsage[i] = coreUsage; + } + coresStats.push(currCoreStats); + } + root.coresUsage = newCoresUsage; + root.prevCpuCoresStats = coresStats; + } + + // ------------------------------------------------------- + // Check whether a network interface is virtual/tunnel/bridge. + // Only physical interfaces (eth*, en*, wl*, ww*) are kept so + // that traffic routed through VPNs, Docker bridges, etc. is + // not double-counted. + readonly property var _virtualPrefixes: ["lo", "docker", "veth", "br-", "virbr", "vnet", "tun", "tap", "wg", "tailscale", "nordlynx", "proton", "mullvad", "flannel", "cni", "cali", "vxlan", "genev", "gre", "sit", "ip6tnl", "dummy", "ifb", "nlmon", "bond"] + + function isVirtualInterface(name) { + for (let i = 0; i < _virtualPrefixes.length; ++i) { + if (name.startsWith(_virtualPrefixes[i])) + return true; + } + return false; + } + + // ------------------------------------------------------- + // Calculate RX and TX speed from /proc/net/dev + // Sums speeds of all physical interfaces + function calculateNetworkSpeed(text) { + if (!text) { + return; + } + + const currentTime = Date.now() / 1000; + const lines = text.split('\n'); + + let totalRx = 0; + let totalTx = 0; + + for (var i = 2; i < lines.length; i++) { + const line = lines[i].trim(); + if (!line) { + continue; + } + + const colonIndex = line.indexOf(':'); + if (colonIndex === -1) { + continue; + } + + const iface = line.substring(0, colonIndex).trim(); + if (isVirtualInterface(iface)) { + continue; + } + + const statsLine = line.substring(colonIndex + 1).trim(); + const stats = statsLine.split(/\s+/); + + const rxBytes = parseInt(stats[0], 10) || 0; + const txBytes = parseInt(stats[8], 10) || 0; + + totalRx += rxBytes; + totalTx += txBytes; + } + + // Compute only if we have a previous run to compare to. + if (root.prevTime > 0) { + const timeDiff = currentTime - root.prevTime; + + // Avoid division by zero if time hasn't passed. + if (timeDiff > 0) { + let rxDiff = totalRx - root.prevRxBytes; + let txDiff = totalTx - root.prevTxBytes; + + // Handle counter resets (e.g., WiFi reconnect), which would cause a negative value. + if (rxDiff < 0) { + rxDiff = 0; + } + if (txDiff < 0) { + txDiff = 0; + } + + root.rxSpeed = Math.round(rxDiff / timeDiff); // Speed in Bytes/s + root.txSpeed = Math.round(txDiff / timeDiff); + } + } + + root.prevRxBytes = totalRx; + root.prevTxBytes = totalTx; + root.prevTime = currentTime; + + // Update network history after speeds are computed + root.pushNetworkHistory(); + } + + // ------------------------------------------------------- + // Helper function to format network speeds + function formatSpeed(bytesPerSecond) { + const units = ["KB", "MB", "GB"]; + let value = bytesPerSecond / 1000; + let unitIndex = 0; + + while (value >= 1000 && unitIndex < units.length - 1) { + value /= 1000; + unitIndex++; + } + + const unit = units[unitIndex]; + const shortUnit = unit[0]; + const numStr = value < 10 ? value.toFixed(1) : Math.round(value).toString(); + + return (numStr + unit).length > 5 ? numStr + shortUnit : numStr + unit; + } + + // ------------------------------------------------------- + // Compact speed formatter for vertical bar display + function formatCompactSpeed(bytesPerSecond) { + if (!bytesPerSecond || bytesPerSecond <= 0) + return "0"; + const units = ["", "K", "M", "G"]; + let value = bytesPerSecond; + let unitIndex = 0; + while (value >= 1000 && unitIndex < units.length - 1) { + value = value / 1000.0; + unitIndex++; + } + // Promote at ~100 of current unit (e.g., 100k -> ~0.1M shown as 0.1M or 0M if rounded) + if (unitIndex < units.length - 1 && value >= 100) { + value = value / 1000.0; + unitIndex++; + } + const display = Math.round(value).toString(); + return display + units[unitIndex]; + } + + // ------------------------------------------------------- + // Smart formatter for memory values (GB) - max 4 chars + // Uses decimal for < 10GB, integer otherwise + function formatGigabytes(memGb) { + const value = parseFloat(memGb); + if (isNaN(value)) + return "0G"; + + if (value < 10) + return value.toFixed(1) + "G"; // "0.0G" to "9.9G" + return Math.round(value) + "G"; // "10G" to "999G" + } + + // ------------------------------------------------------- + // Formatting gigabytes with optional padding + function formatGigabytesDisplay(memGb, maxGb = null) { + const value = formatGigabytes(memGb === null ? 0 : memGb); + if (maxGb !== null) { + const padding = Math.max(4, formatGigabytes(maxGb).length); + return value.padStart(padding, " "); + } + return value; + } + + // ------------------------------------------------------- + // Formatting percentage with optional padding + function formatPercentageDisplay(value, padding = false) { + return `${Math.round(value === null ? 0 : value)}%`.padStart(padding ? 4 : 0, " "); + } + + // ------------------------------------------------------- + // Formatting disk usage + function formatDiskDisplay(diskPath, { + percent = false, + available = false, + padding = false +} = {}) { + if (percent) { + const raw = available ? root.diskAvailPercents[diskPath] : root.diskPercents[diskPath]; + return formatPercentageDisplay(raw, padding); + } else { + const rawGb = available ? root.diskAvailableGb[diskPath] : root.diskUsedGb[diskPath]; + const maxGb = padding ? root.diskSizeGb[diskPath] : null; + return formatGigabytesDisplay(rawGb, maxGb); + } + } + + // ------------------------------------------------------- + // Formatting ram usage + function formatRamDisplay({ + swap = false, + percent = false, + padding = false +} = {}) { + if (percent) { + const raw = swap ? swapPercent : memPercent; + return formatPercentageDisplay(raw, padding); + } else { + const rawGb = swap ? swapGb : memGb; + const maxGb = padding ? (swap ? swapTotalGb : memTotalGb) : null; + return formatGigabytesDisplay(rawGb, maxGb); + } + } + + // ------------------------------------------------------- + // Function to start fetching and computing the cpu temperature + function updateCpuTemperature() { + // For AMD sensors (k10temp and zenpower), only use Tctl sensor + // temp1_input corresponds to Tctl (Temperature Control) on these sensors + if (root.cpuTempSensorName === "k10temp" || root.cpuTempSensorName === "zenpower") { + cpuTempReader.path = `${root.cpuTempHwmonPath}/temp1_input`; + cpuTempReader.reload(); + } // For Intel coretemp, start averaging all available sensors/cores + else if (root.cpuTempSensorName === "coretemp") { + root.intelTempValues = []; + root.intelTempFilesChecked = 0; + checkNextIntelTemp(); + } // For thermal_zone fallback (ARM SoCs, SCMI, etc.), read all CPU zones and take max + else if (root.cpuTempSensorName === "thermal_zone") { + cpuThermalZoneReader.currentZoneIndex = 0; + cpuThermalZoneReader.collectedTemps = []; + readNextCpuThermalZone(); + } + } + + // ------------------------------------------------------- + // Function to check next Intel temperature sensor + function checkNextIntelTemp() { + if (root.intelTempFilesChecked >= root.intelTempMaxFiles) { + // Calculate average of all found temperatures + if (root.intelTempValues.length > 0) { + let sum = 0; + for (var i = 0; i < root.intelTempValues.length; i++) { + sum += root.intelTempValues[i]; + } + root.cpuTemp = Math.round(sum / root.intelTempValues.length); + root.pushCpuTempHistory(); + //Logger.i("SystemStat", `Averaged ${root.intelTempValues.length} CPU thermal sensors: ${root.cpuTemp}°C`) + } else { + Logger.w("SystemStat", "No temperature sensors found for coretemp"); + root.cpuTemp = 0; + root.pushCpuTempHistory(); + } + return; + } + + // Check next temperature file + root.intelTempFilesChecked++; + cpuTempReader.path = `${root.cpuTempHwmonPath}/temp${root.intelTempFilesChecked}_input`; + cpuTempReader.reload(); + } + + // ------------------------------------------------------- + // Function to check VRAM for each AMD GPU to determine if it's a dGPU + function checkNextGpuVram() { + // Skip non-AMD GPUs (NVIDIA and Intel Arc are always discrete) + while (root.gpuVramCheckIndex < root.foundGpuSensors.length) { + const gpu = root.foundGpuSensors[root.gpuVramCheckIndex]; + if (gpu.type === "amd") { + // Check for dedicated VRAM at hwmonPath/device/mem_info_vram_total + gpuVramChecker.path = `${gpu.hwmonPath}/device/mem_info_vram_total`; + gpuVramChecker.reload(); + return; + } + // Skip non-AMD GPUs + root.gpuVramCheckIndex++; + } + + // All VRAM checks complete, now select the best GPU + selectBestGpu(); + } + + // ------------------------------------------------------- + // Function to select the best GPU based on priority + // Priority (when dGPU monitoring enabled): NVIDIA > AMD dGPU > Intel Arc > AMD iGPU + // Priority (when dGPU monitoring disabled): AMD iGPU only (discrete GPUs skipped to preserve D3cold) + function selectBestGpu() { + const dgpuEnabled = Settings.data.systemMonitor.enableDgpuMonitoring; + + if (root.foundGpuSensors.length === 0) { + // No hwmon GPU sensors found, try thermal_zone fallback + if (dgpuEnabled && root.gpuThermalZonePath === "" && root.gpuThermalZonePaths.length === 0) { + // Thermal zone scanner hasn't found GPU zones yet; start a scan + thermalZoneScanner.startScan(); + } + return; + } + + let best = null; + + for (var i = 0; i < root.foundGpuSensors.length; i++) { + const gpu = root.foundGpuSensors[i]; + + // NVIDIA is always highest priority (always discrete) - skip if dGPU monitoring disabled + if (gpu.type === "nvidia") { + if (dgpuEnabled) { + best = gpu; + break; + } + continue; + } + + // AMD dGPU is second priority - skip if dGPU monitoring disabled (preserves D3cold power state) + if (gpu.type === "amd" && gpu.hasDedicatedVram) { + if (dgpuEnabled) { + best = gpu; + break; + } + continue; + } + + // Intel Arc is third priority (always discrete) - skip if dGPU monitoring disabled + if (gpu.type === "intel" && !best) { + if (dgpuEnabled) { + best = gpu; + } + continue; + } + + // AMD iGPU is lowest priority (fallback) - always allowed (no D3cold issue) + if (gpu.type === "amd" && !gpu.hasDedicatedVram && !best) { + best = gpu; + } + } + + if (best) { + root.gpuTempHwmonPath = best.hwmonPath; + root.gpuType = best.type; + root.gpuAvailable = true; + + const gpuDesc = best.type === "nvidia" ? "NVIDIA" : (best.type === "intel" ? "Intel Arc" : (best.hasDedicatedVram ? "AMD dGPU" : "AMD iGPU")); + Logger.i("SystemStat", `Selected ${gpuDesc} for temperature monitoring at ${best.hwmonPath || "nvidia-smi"}`); + } else if (!dgpuEnabled) { + Logger.d("SystemStat", "No iGPU found and dGPU monitoring is disabled"); + } + } + + // ------------------------------------------------------- + // Function to update GPU temperature + function updateGpuTemperature() { + if (root.gpuType === "nvidia") { + nvidiaTempProcess.running = true; + } else if (root.gpuType === "amd" || root.gpuType === "intel") { + gpuTempReader.path = `${root.gpuTempHwmonPath}/temp1_input`; + gpuTempReader.reload(); + } else if (root.gpuType === "thermal_zone") { + if (root.gpuThermalZonePaths && root.gpuThermalZonePaths.length > 0) { + // Multiple GPU zones (no gpu-avg), read all and take max + gpuThermalZoneReader.currentZoneIndex = 0; + gpuThermalZoneReader.collectedTemps = []; + readNextGpuThermalZone(); + } else { + // Single gpu-avg-thermal zone + gpuThermalZoneReader.path = root.gpuThermalZonePath; + gpuThermalZoneReader.reload(); + } + } + } +} diff --git a/quickshell/compat/noctalia/Services/UI/BarService.qml b/quickshell/compat/noctalia/Services/UI/BarService.qml new file mode 100644 index 0000000..b810644 --- /dev/null +++ b/quickshell/compat/noctalia/Services/UI/BarService.qml @@ -0,0 +1,22 @@ +pragma Singleton +import QtQuick +import Quickshell +import "../../../../core" as Core +import "../../../../services" as GS + +// glassMxrph stand-in: the bar is glassMxrph's own top bar. +Singleton { + readonly property bool isVisible: true + property int widgetsRevision: 0 + function getTooltipDirection(screenName) { + return "bottom"; + } + function getPillDirection(widgetInstance) { + return !widgetInstance || widgetInstance.section !== "left"; + } + // Plugin settings live in Settings → Plugins. + function openPluginSettings(screen, pluginManifest) { + GS.PluginService.focusedSettings = pluginManifest && pluginManifest.id ? pluginManifest.id : ""; + Core.ShellState.openSettings("plugins"); + } +} diff --git a/quickshell/compat/noctalia/Services/UI/BarWidgetRegistry.qml b/quickshell/compat/noctalia/Services/UI/BarWidgetRegistry.qml new file mode 100644 index 0000000..79aa13e --- /dev/null +++ b/quickshell/compat/noctalia/Services/UI/BarWidgetRegistry.qml @@ -0,0 +1,13 @@ +pragma Singleton +import QtQuick +import Quickshell + +// glassMxrph stand-in: Noctalia's built-in widget registry is not used. +Singleton { + property var widgets: ({}) + property var widgetMetadata: ({}) + property bool editMode: false + function hasWidget(id) { + return false; + } +} diff --git a/quickshell/compat/noctalia/Services/UI/ControlCenterWidgetRegistry.qml b/quickshell/compat/noctalia/Services/UI/ControlCenterWidgetRegistry.qml new file mode 100644 index 0000000..79aa13e --- /dev/null +++ b/quickshell/compat/noctalia/Services/UI/ControlCenterWidgetRegistry.qml @@ -0,0 +1,13 @@ +pragma Singleton +import QtQuick +import Quickshell + +// glassMxrph stand-in: Noctalia's built-in widget registry is not used. +Singleton { + property var widgets: ({}) + property var widgetMetadata: ({}) + property bool editMode: false + function hasWidget(id) { + return false; + } +} diff --git a/quickshell/compat/noctalia/Services/UI/DesktopWidgetRegistry.qml b/quickshell/compat/noctalia/Services/UI/DesktopWidgetRegistry.qml new file mode 100644 index 0000000..79aa13e --- /dev/null +++ b/quickshell/compat/noctalia/Services/UI/DesktopWidgetRegistry.qml @@ -0,0 +1,13 @@ +pragma Singleton +import QtQuick +import Quickshell + +// glassMxrph stand-in: Noctalia's built-in widget registry is not used. +Singleton { + property var widgets: ({}) + property var widgetMetadata: ({}) + property bool editMode: false + function hasWidget(id) { + return false; + } +} diff --git a/quickshell/compat/noctalia/Services/UI/LauncherProviderRegistry.qml b/quickshell/compat/noctalia/Services/UI/LauncherProviderRegistry.qml new file mode 100644 index 0000000..79aa13e --- /dev/null +++ b/quickshell/compat/noctalia/Services/UI/LauncherProviderRegistry.qml @@ -0,0 +1,13 @@ +pragma Singleton +import QtQuick +import Quickshell + +// glassMxrph stand-in: Noctalia's built-in widget registry is not used. +Singleton { + property var widgets: ({}) + property var widgetMetadata: ({}) + property bool editMode: false + function hasWidget(id) { + return false; + } +} diff --git a/quickshell/compat/noctalia/Services/UI/PanelService.qml b/quickshell/compat/noctalia/Services/UI/PanelService.qml new file mode 100644 index 0000000..e28ced9 --- /dev/null +++ b/quickshell/compat/noctalia/Services/UI/PanelService.qml @@ -0,0 +1,55 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Hyprland +import "../../../../core" as Core + +// glassMxrph stand-in: context menus open where the plugin asks and close on +// an outside click (Hyprland focus grab); launcher calls use glassMxrph's. +Singleton { + id: root + property var openedPanel: null + property var lockScreen: null + property bool isKeybindRecording: false + property var menu: null + + function showContextMenu(contextMenu, anchorItem, screen, targetItem) { + if (!contextMenu || !anchorItem) + return; + closeContextMenu(screen); + menu = contextMenu; + contextMenu.openAtItem(anchorItem, screen, targetItem); + Qt.callLater(() => grab.active = !!root.menu); + } + function closeContextMenu(screen) { + grab.active = false; + if (menu && typeof menu.close === "function") + menu.close(); + menu = null; + } + function getPopupMenuWindow(screen) { + return null; + } + function getPanel(name, screen) { + return null; + } + function isLauncherOpen() { + return Core.ShellState.launcherOpen; + } + function closeLauncher() { + Core.ShellState.launcherOpen = false; + } + function openLauncherWithSearch(text) { + Core.ShellState.openLauncher(); + } + function setLauncherSearchText(text) { + } + function getLauncherSearchText() { + return ""; + } + HyprlandFocusGrab { + id: grab + windows: root.menu ? [root.menu] : [] + onCleared: root.closeContextMenu(null) + } +} diff --git a/quickshell/compat/noctalia/Services/UI/ToastService.qml b/quickshell/compat/noctalia/Services/UI/ToastService.qml new file mode 100644 index 0000000..c2edeee --- /dev/null +++ b/quickshell/compat/noctalia/Services/UI/ToastService.qml @@ -0,0 +1,24 @@ +pragma Singleton +import QtQuick +import Quickshell + +// glassMxrph stand-in: Noctalia toasts become desktop notifications. +Singleton { + function notify(urgency, title, description, duration) { + Quickshell.execDetached(["notify-send", "-a", "glassMxrph", "-u", urgency, "-t", String(duration || 4000), String(title || ""), String(description || "")]); + } + function showNotice(title, description = "", icon = "", duration = 3000, actionLabel = "", actionCallback = null) { + notify("low", title, description, duration); + } + function showInfo(title, description = "", icon = "", duration = 3000) { + notify("low", title, description, duration); + } + function showWarning(title, description = "", duration = 4000, actionLabel = "", actionCallback = null) { + notify("normal", title, description, duration); + } + function showError(title, description = "", duration = 6000, actionLabel = "", actionCallback = null) { + notify("critical", title, description, duration); + } + function dismissToast() { + } +} diff --git a/quickshell/compat/noctalia/Services/UI/TooltipService.qml b/quickshell/compat/noctalia/Services/UI/TooltipService.qml new file mode 100644 index 0000000..5b3a0dc --- /dev/null +++ b/quickshell/compat/noctalia/Services/UI/TooltipService.qml @@ -0,0 +1,40 @@ +pragma Singleton +import QtQuick +import Quickshell +import "../../../../core" as Core +import "../../../../services" as GS + +// glassMxrph stand-in: tooltips of bar widgets use the shell's hover popout +// (it hangs from the bar); tooltips elsewhere are not shown. +Singleton { + id: root + property var current: null + function inBar(target) { + const w = target && target.QsWindow ? target.QsWindow.window : null; + return !!w && GS.TrayService.barWindows.includes(w); + } + function show(target, content, direction, delay, fontFamily) { + if (!target || !content || !inBar(target)) + return; + current = target; + Core.PopoutState.hover(target, "tooltip", String(content)); + } + function hide(target) { + if (target && current !== target) + return; + if (current) + Core.PopoutState.unhover(current); + current = null; + } + function hideImmediately() { + current = null; + Core.PopoutState.close(); + } + function updateContent(newContent) { + updateText(newContent); + } + function updateText(newText) { + if (current && Core.PopoutState.anchor === current) + Core.PopoutState.text = String(newText); + } +} diff --git a/quickshell/compat/noctalia/Services/UI/WallpaperService.qml b/quickshell/compat/noctalia/Services/UI/WallpaperService.qml new file mode 100644 index 0000000..3d14f75 --- /dev/null +++ b/quickshell/compat/noctalia/Services/UI/WallpaperService.qml @@ -0,0 +1,29 @@ +pragma Singleton +import QtQuick +import Quickshell +import "../../../../services" as GS + +// glassMxrph stand-in for wallpaper queries. +Singleton { + readonly property bool isInitialized: true + readonly property var currentWallpapers: GS.ConfigService.ready ? GS.ConfigService.data.wallpaper.byMonitor : ({}) + signal wallpaperProcessingComplete + function getWallpaper(screenName) { + return currentWallpapers[screenName] || ""; + } + function getWallpapersEffectiveMap() { + return currentWallpapers; + } + function changeWallpaper(path, screenName) { + GS.WallpaperService.apply(path); + } + function isSolidColorPath(path) { + return String(path).startsWith("solid://"); + } + function getSolidColor(path) { + return String(path).replace("solid://", ""); + } + function getFillModeUniform() { + return 1; + } +} diff --git a/quickshell/compat/noctalia/Widgets/AudioSpectrum/NLinearSpectrum.qml b/quickshell/compat/noctalia/Widgets/AudioSpectrum/NLinearSpectrum.qml new file mode 100644 index 0000000..dabdd46 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/AudioSpectrum/NLinearSpectrum.qml @@ -0,0 +1,49 @@ +import QtQuick +import qs.compat.noctalia.Commons + +Item { + id: root + property color fillColor: Color.mPrimary + property color strokeColor: Color.mOnSurface + property int strokeWidth: 0 + property var values: [] + property bool vertical: false + property string barPosition: "top" // "top", "bottom", "left", "right" + property bool mirrored: true + + // Minimum signal properties + property bool showMinimumSignal: false + property real minimumSignalValue: 0.01 // Default to 1% of height + + // Pre compute horizontal mirroring + readonly property int valuesCount: (values && values.length !== undefined) ? values.length : 0 + readonly property int totalBars: mirrored ? valuesCount * 2 : valuesCount + readonly property real barSlotSize: totalBars > 0 ? (vertical ? height : width) / totalBars : 0 + readonly property bool highQuality: (Settings.data.audio.visualizerType === "low") ? false : true + + Repeater { + model: root.totalBars + + Rectangle { + property int valueIndex: root.mirrored ? (index < root.valuesCount ? root.valuesCount - 1 - index : index - root.valuesCount) : index + + property real rawAmp: (root.values && root.values[valueIndex] !== undefined) ? root.values[valueIndex] : 0 + property real amp: (root.showMinimumSignal && rawAmp === 0) ? root.minimumSignalValue : rawAmp + + color: root.fillColor + border.color: root.strokeColor + border.width: root.strokeWidth + antialiasing: root.highQuality + smooth: root.highQuality + + // Only update when value actually changes - reduces GPU load + width: vertical ? root.width * amp : root.barSlotSize * 0.5 + height: vertical ? root.barSlotSize * 0.5 : root.height * amp + x: vertical ? (root.barPosition === "left" ? 0 : root.width - width) : index * root.barSlotSize + (root.barSlotSize * 0.25) + y: vertical ? index * root.barSlotSize + (root.barSlotSize * 0.25) : root.height - height + + // Disable updates when invisible to save GPU + visible: root.visible + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/AudioSpectrum/NMirroredSpectrum.qml b/quickshell/compat/noctalia/Widgets/AudioSpectrum/NMirroredSpectrum.qml new file mode 100644 index 0000000..cb3fcce --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/AudioSpectrum/NMirroredSpectrum.qml @@ -0,0 +1,51 @@ +import QtQuick +import qs.compat.noctalia.Commons + +Item { + id: root + property color fillColor: Color.mPrimary + property color strokeColor: Color.mOnSurface + property int strokeWidth: 0 + property var values: [] + property bool vertical: false + property bool mirrored: true + + // Minimum signal properties + property bool showMinimumSignal: false + property real minimumSignalValue: 0.01 // Default to 1% of height + + // Pre-compute mirroring + readonly property int valuesCount: (values && values.length !== undefined) ? values.length : 0 + readonly property int totalBars: mirrored ? valuesCount * 2 : valuesCount + readonly property real barSlotSize: totalBars > 0 ? (vertical ? height : width) / totalBars : 0 + readonly property bool highQuality: (Settings.data.audio.visualizerType === "low") ? false : true + readonly property real centerY: height / 2 + readonly property real centerX: width / 2 + + Repeater { + model: root.totalBars + + Rectangle { + property int valueIndex: root.mirrored ? (index < root.valuesCount ? root.valuesCount - 1 - index : index - root.valuesCount) : index + + property real rawAmp: (root.values && root.values[valueIndex] !== undefined) ? root.values[valueIndex] : 0 + property real amp: (root.showMinimumSignal && rawAmp === 0) ? root.minimumSignalValue : rawAmp + + property real barSize: (vertical ? root.width : root.height) * amp + + color: root.fillColor + border.color: root.strokeColor + border.width: root.strokeWidth + antialiasing: root.highQuality + smooth: root.highQuality + + width: vertical ? barSize : root.barSlotSize * 0.8 + height: vertical ? root.barSlotSize * 0.8 : barSize + x: vertical ? root.centerX - (barSize / 2) : index * root.barSlotSize + (root.barSlotSize * 0.25) + y: vertical ? index * root.barSlotSize + (root.barSlotSize * 0.25) : root.centerY - (barSize / 2) + + // Disable updates when invisible to save GPU + visible: root.visible + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/AudioSpectrum/NWaveSpectrum.qml b/quickshell/compat/noctalia/Widgets/AudioSpectrum/NWaveSpectrum.qml new file mode 100644 index 0000000..dacea24 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/AudioSpectrum/NWaveSpectrum.qml @@ -0,0 +1,72 @@ +import QtQuick +import Quickshell +import qs.compat.noctalia.Commons + +Item { + id: root + property color fillColor: Color.mPrimary + property color strokeColor: Color.mOnSurface + property int strokeWidth: 0 + property var values: [] + property bool vertical: false + property bool mirrored: true + + // Minimum signal properties + property bool showMinimumSignal: false + property real minimumSignalValue: 0.01 // Default to 1% of height + + readonly property int valuesCount: (values && values.length !== undefined) ? values.length : 0 + readonly property bool hasData: valuesCount >= 2 + + // Data texture: one pixel per value, R channel = amplitude + Item { + id: dataRow + width: Math.max(root.valuesCount, 4) + height: 1 + + Repeater { + model: dataRow.width + + Rectangle { + required property int index + x: index + width: 1 + height: 1 + color: { + if (index >= root.valuesCount) + return Qt.rgba(0, 0, 0, 1); + var v = root.values[index]; + if (v === undefined || v === null || !isFinite(v)) + v = 0; + if (root.showMinimumSignal && v === 0) + v = root.minimumSignalValue; + return Qt.rgba(Math.max(0, Math.min(1, v)), 0, 0, 1); + } + } + } + } + + ShaderEffectSource { + id: dataTex + sourceItem: dataRow + textureSize: Qt.size(dataRow.width, 1) + live: true + smooth: false + hideSource: true + } + + ShaderEffect { + anchors.fill: parent + visible: root.hasData && root.width > 0 && root.height > 0 + + property variant dataSource: dataTex + property color fillColor: root.fillColor + property real count: root.valuesCount + property real texWidth: dataRow.width + property real vertical: root.vertical ? 1.0 : 0.0 + property real mirrored: root.mirrored ? 1.0 : 0.0 + + fragmentShader: Qt.resolvedUrl(Quickshell.shellDir + "/Shaders/qsb/wave_spectrum.frag.qsb") + blending: true + } +} diff --git a/quickshell/compat/noctalia/Widgets/NBattery.qml b/quickshell/compat/noctalia/Widgets/NBattery.qml new file mode 100644 index 0000000..9dfeb21 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NBattery.qml @@ -0,0 +1,205 @@ +import QtQuick +import QtQuick.Layouts +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Widgets + +// Battery widget with Android 16 style rendering (horizontal or vertical) +Item { + id: root + + // Data (must be provided by parent) + required property real percentage + required property bool charging + required property bool pluggedIn + required property bool ready + required property bool low + required property bool critical + + // Sizing - baseSize controls overall scaleFactor for bar/panel usage + property real baseSize: Style.fontSizeM + + // Styling - no hardcoded colors, only theme colors + property color baseColor: Color.mOnSurface + property color lowColor: Color.mError + property color chargingColor: Color.mPrimary + property color textColor: Color.mSurface + + // Display options + property bool showPercentageText: true + property bool vertical: false + + // Alternating state icon display (toggles between percentage and icon when charging) + property bool showStateIcon: false + + onChargingChanged: { + if (!charging) + showStateIcon = false; + } + + // Internal sizing calculations based on baseSize + readonly property real scaleFactor: baseSize / Style.fontSizeM + readonly property real bodyWidth: { + const min = Style.toOdd(22 * scaleFactor); + if (!showPercentageText) { + return min; + } + + // increase length when showing 100% + if (percentage > 99) { + const max = Style.toOdd(30 * scaleFactor); + return max; + } + return min; + } + + readonly property real bodyHeight: Style.toOdd(14 * scaleFactor) + readonly property real terminalWidth: Math.round(2.5 * scaleFactor) + readonly property real terminalHeight: Math.round(7 * scaleFactor) + readonly property real cornerRadius: Math.round(3 * scaleFactor) + + // Total size is just body + terminal (no external icon) + readonly property real totalWidth: vertical ? bodyHeight : bodyWidth + terminalWidth + readonly property real totalHeight: vertical ? bodyWidth + terminalWidth : bodyHeight + + // Determine active color based on state + readonly property color activeColor: { + if (!ready) { + return Qt.alpha(baseColor, Style.opacityMedium); + } + if (charging) { + return chargingColor; + } + if (low || critical) { + return lowColor; + } + return baseColor; + } + + // Background color for empty portion (semi-transparent) + readonly property color emptyColor: Qt.alpha(baseColor, 0.66) + + // State icon logic + readonly property string stateIcon: { + if (!ready) + return "x"; + if (charging) + return "bolt-filled"; + if (pluggedIn) + return "plug-filled"; + return ""; + } + + // Animated percentage for smooth transitions + property real animatedPercentage: percentage + + Behavior on animatedPercentage { + enabled: !Settings.data.general.animationDisabled + NumberAnimation { + duration: Style.animationNormal + easing.type: Easing.OutCubic + } + } + + // Timer to alternate between percentage text and state icon when charging/plugged + Timer { + id: alternateTimer + interval: 4000 + repeat: true + running: root.charging && root.showPercentageText + onTriggered: root.showStateIcon = !root.showStateIcon + } + + implicitWidth: Math.round(totalWidth) + implicitHeight: Math.round(totalHeight) + Layout.maximumWidth: implicitWidth + Layout.maximumHeight: implicitHeight + + // Battery body container + Item { + id: batteryBody + width: root.vertical ? root.bodyHeight : root.bodyWidth + root.terminalWidth + height: root.vertical ? root.bodyWidth + root.terminalWidth : root.bodyHeight + anchors.left: root.vertical ? undefined : parent.left + anchors.bottom: root.vertical ? parent.bottom : undefined + anchors.horizontalCenter: root.vertical ? parent.horizontalCenter : undefined + anchors.verticalCenter: root.vertical ? undefined : parent.verticalCenter + + // Battery body background + Rectangle { + id: bodyBackground + y: root.vertical ? root.terminalWidth : 0 + width: root.vertical ? root.bodyHeight : root.bodyWidth + height: root.vertical ? root.bodyWidth : root.bodyHeight + radius: root.cornerRadius + color: root.emptyColor + } + + // Terminal cap + Rectangle { + x: root.vertical ? (root.bodyHeight - root.terminalHeight) / 2 : root.bodyWidth + y: root.vertical ? 0 : (root.bodyHeight - root.terminalHeight) / 2 + width: root.vertical ? root.terminalHeight : root.terminalWidth + height: root.vertical ? root.terminalWidth : root.terminalHeight + radius: root.cornerRadius / 2 + color: root.critical ? root.lowColor : root.emptyColor + } + + // Fill level + Rectangle { + id: fillRect + visible: root.ready && (root.animatedPercentage > 0 || root.critical) + x: 0 + y: root.vertical ? root.terminalWidth + root.bodyWidth * (1 - (root.critical ? 1 : root.animatedPercentage / 100)) : 0 + width: root.vertical ? root.bodyHeight : root.bodyWidth * (root.critical ? 1 : root.animatedPercentage / 100) + height: root.vertical ? root.bodyWidth * (root.critical ? 1 : root.animatedPercentage / 100) : root.bodyHeight + radius: root.cornerRadius + color: root.activeColor + } + } + + // Percentage text overlaid on battery center + NText { + id: percentageText + visible: opacity > 0 + opacity: root.showPercentageText && root.ready && (root.charging ? !root.showStateIcon : !root.pluggedIn) ? 1 : 0 + x: batteryBody.x + Style.pixelAlignCenter(bodyBackground.width, width) + y: batteryBody.y + bodyBackground.y + Style.pixelAlignCenter(bodyBackground.height, height) + font.family: Settings.data.ui.fontFixed + font.weight: Style.fontWeightBold + text: root.vertical ? String(Math.round(root.animatedPercentage)).split('').join('\n') : Math.round(root.animatedPercentage) + pointSize: root.baseSize * (root.vertical ? 0.82 : 0.82) + color: Qt.alpha(root.textColor, 0.75) + horizontalAlignment: Text.AlignHCenter + verticalAlignment: Text.AlignVCenter + lineHeight: root.vertical ? 0.7 : 1.0 + lineHeightMode: Text.ProportionalHeight + + Behavior on opacity { + enabled: !Settings.data.general.animationDisabled + NumberAnimation { + duration: Style.animationFast + easing.type: Easing.InOutQuad + } + } + } + + // State icon centered inside battery body (shown when alternating) + NIcon { + id: stateIconOverlay + visible: opacity > 0 + opacity: !root.ready || (root.charging ? (root.showStateIcon || !root.showPercentageText) : root.pluggedIn) ? 1 : 0 + x: batteryBody.x + Style.pixelAlignCenter(bodyBackground.width, width) + y: batteryBody.y + bodyBackground.y + Style.pixelAlignCenter(bodyBackground.height, height) + icon: root.stateIcon + pointSize: Style.toOdd(root.baseSize) + color: Qt.alpha(root.textColor, 0.75) + + Behavior on opacity { + enabled: !Settings.data.general.animationDisabled + NumberAnimation { + duration: Style.animationFast + easing.type: Easing.InOutQuad + } + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NBox.qml b/quickshell/compat/noctalia/Widgets/NBox.qml new file mode 100644 index 0000000..f8eec7c --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NBox.qml @@ -0,0 +1,30 @@ +import QtQuick +import qs.compat.noctalia.Commons + +// Rounded group container using the variant surface color. +// To be used in side panels and settings panes to group fields or buttons. +// Opacity is based on panelBackgroundOpacity but clamped to a minimum to avoid full transparency. + +Item { + id: root + + property color color: Color.mSurfaceVariant + property bool forceOpaque: false + property alias radius: bg.radius + property alias border: bg.border + + Rectangle { + id: bg + anchors.fill: parent + radius: Style.radiusM + border.color: Style.boxBorderColor + border.width: Style.borderS + color: { + if (forceOpaque) { + return root.color; + } + + return Color.smartAlpha(root.color); + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NBusyIndicator.qml b/quickshell/compat/noctalia/Widgets/NBusyIndicator.qml new file mode 100644 index 0000000..573ada5 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NBusyIndicator.qml @@ -0,0 +1,66 @@ +import QtQuick +import qs.compat.noctalia.Commons + +Item { + id: root + + property bool running: true + property color color: Color.mPrimary + property int size: Style.baseWidgetSize + property int strokeWidth: Style.borderL + property int duration: Style.animationSlow * 2 + + implicitWidth: size + implicitHeight: size + + onColorChanged: canvas.requestPaint() + + // GPU-optimized spinner - draw once, rotate with GPU transform + Item { + id: spinner + anchors.fill: parent + + // Static canvas - drawn ONCE, then cached + Canvas { + id: canvas + anchors.fill: parent + renderStrategy: Canvas.Cooperative // Better performance than Threaded for simple shapes + renderTarget: Canvas.FramebufferObject // GPU texture + + // Enable layer caching - critical for performance! + layer.enabled: true + layer.smooth: true + + Component.onCompleted: { + requestPaint(); + } + + onPaint: { + var ctx = getContext("2d"); + ctx.reset(); + + var centerX = width / 2; + var centerY = height / 2; + var radius = Math.min(width, height) / 2 - strokeWidth / 2; + + ctx.strokeStyle = root.color; + ctx.lineWidth = Math.max(1, root.strokeWidth); + ctx.lineCap = "round"; + + // Draw arc with gap (270 degrees = 3/4 of circle) + ctx.beginPath(); + ctx.arc(centerX, centerY, radius, -Math.PI / 2, -Math.PI / 2 + Math.PI * 1.5); + ctx.stroke(); + } + } + + // Smooth rotation animation - uses GPU transform, NO canvas repaints! + RotationAnimation on rotation { + running: root.running + from: 0 + to: 360 + duration: root.duration + loops: Animation.Infinite + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NButton.qml b/quickshell/compat/noctalia/Widgets/NButton.qml new file mode 100644 index 0000000..7a5938d --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NButton.qml @@ -0,0 +1,184 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Services.UI + +Item { + id: root + + // Public properties + property string text: "" + property string icon: "" + property var tooltipText + property color backgroundColor: Color.mPrimary + property color textColor: Color.mOnPrimary + property color hoverColor: Color.mHover + property color textHoverColor: Color.mOnHover + property real fontSize: Style.fontSizeM + property int fontWeight: Style.fontWeightSemiBold + property real iconSize: Style.fontSizeL + property bool outlined: false + property int horizontalAlignment: Qt.AlignHCenter + property real buttonRadius: Style.iRadiusS + + // Signals + signal clicked + signal rightClicked + signal middleClicked + signal entered + signal exited + + // Internal properties + property bool hovered: false + readonly property color contentColor: { + if (!root.enabled) { + return Color.mOnSurfaceVariant; + } + if (root.hovered) { + return root.textHoverColor; + } + if (root.outlined) { + return root.backgroundColor; + } + return root.textColor; + } + + // Dimensions - include margin so border renders cleanly at fractional scales + implicitWidth: bg.implicitWidth + 2 * Style.borderS + implicitHeight: bg.implicitHeight + 2 * Style.borderS + + opacity: enabled ? 1.0 : 0.6 + + Rectangle { + id: bg + anchors.fill: parent + anchors.margins: Style.borderS + + implicitWidth: contentRow.implicitWidth + (root.fontSize * 2) + implicitHeight: contentRow.implicitHeight + (root.fontSize) + + radius: root.buttonRadius + color: { + if (!root.enabled) + return root.outlined ? "transparent" : Qt.lighter(Color.mSurfaceVariant, 1.2); + if (root.hovered) + return root.hoverColor; + return root.outlined ? "transparent" : root.backgroundColor; + } + + border.width: root.outlined ? Style.borderS : 0 + border.color: { + if (!root.enabled) + return Color.mOutline; + if (root.hovered) + return root.hoverColor; + return root.outlined ? root.backgroundColor : "transparent"; + } + + Behavior on color { + enabled: !Color.isTransitioning + ColorAnimation { + duration: Style.animationFast + easing.type: Easing.OutCubic + } + } + + Behavior on border.color { + enabled: !Color.isTransitioning + ColorAnimation { + duration: Style.animationFast + easing.type: Easing.OutCubic + } + } + + // Content + RowLayout { + id: contentRow + anchors.verticalCenter: parent.verticalCenter + anchors.left: root.horizontalAlignment === Qt.AlignLeft ? parent.left : undefined + anchors.horizontalCenter: root.horizontalAlignment === Qt.AlignHCenter ? parent.horizontalCenter : undefined + anchors.leftMargin: root.horizontalAlignment === Qt.AlignLeft ? Style.marginL : 0 + spacing: Style.marginXS + + // Icon (optional) + NIcon { + Layout.alignment: Qt.AlignVCenter + visible: root.icon !== "" + icon: root.icon + pointSize: root.iconSize + color: root.contentColor + + Behavior on color { + enabled: !Color.isTransitioning + ColorAnimation { + duration: Style.animationFast + easing.type: Easing.OutCubic + } + } + } + + // Text + NText { + Layout.alignment: Qt.AlignVCenter + visible: root.text !== "" + text: root.text + pointSize: root.fontSize + font.weight: root.fontWeight + color: root.contentColor + + Behavior on color { + enabled: !Color.isTransitioning + ColorAnimation { + duration: Style.animationFast + easing.type: Easing.OutCubic + } + } + } + } + + // Mouse interaction + MouseArea { + id: mouseArea + anchors.fill: parent + enabled: root.enabled + hoverEnabled: true + acceptedButtons: Qt.LeftButton | Qt.RightButton | Qt.MiddleButton + cursorShape: root.enabled ? Qt.PointingHandCursor : Qt.ArrowCursor + + onEntered: { + root.hovered = root.enabled ? true : false; + root.entered(); + if (root.hovered && root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) { + TooltipService.show(root, root.tooltipText); + } + } + onExited: { + root.hovered = false; + root.exited(); + if (root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) { + TooltipService.hide(); + } + } + onPressed: mouse => { + if (root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) { + TooltipService.hide(); + } + if (mouse.button === Qt.LeftButton) { + root.clicked(); + } else if (mouse.button == Qt.RightButton) { + root.rightClicked(); + } else if (mouse.button == Qt.MiddleButton) { + root.middleClicked(); + } + } + + onCanceled: { + root.hovered = false; + if (root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) { + TooltipService.hide(); + } + } + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NCheckbox.qml b/quickshell/compat/noctalia/Widgets/NCheckbox.qml new file mode 100644 index 0000000..01f8d97 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NCheckbox.qml @@ -0,0 +1,87 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import qs.compat.noctalia.Commons + +RowLayout { + id: root + + // Public API + property string label: "" + property string description: "" + property bool checked: false + property bool hovering: false + property color activeColor: Color.mPrimary + property color activeOnColor: Color.mOnPrimary + property int baseSize: root.defaultSize + property real labelSize: Style.fontSizeL + + readonly property int defaultSize: Style.baseWidgetSize * 0.7 + + signal toggled(bool checked) + signal entered + signal exited + + Layout.fillWidth: true + + NLabel { + label: root.label + labelSize: root.labelSize + description: root.description + visible: root.label !== "" || root.description !== "" + } + + // Spacer to push the checkbox to the far right + Item { + Layout.fillWidth: true + } + + Rectangle { + id: box + + opacity: enabled ? 1.0 : 0.6 + Layout.margins: Style.borderS + implicitWidth: Style.toOdd(root.baseSize) + implicitHeight: Style.toOdd(root.baseSize) + radius: Style.iRadiusXS * (root.baseSize / root.defaultSize) + color: root.checked ? root.activeColor : Color.mSurface + border.color: Color.mOutline + border.width: Style.borderS + + Behavior on color { + ColorAnimation { + duration: Style.animationFast + } + } + + Behavior on border.color { + ColorAnimation { + duration: Style.animationFast + } + } + + NIcon { + visible: root.checked + x: Style.pixelAlignCenter(parent.width, width) + y: Style.pixelAlignCenter(parent.height, height) + icon: "check" + color: root.activeOnColor + pointSize: Style.toOdd(root.baseSize * 0.5) + } + + MouseArea { + anchors.fill: parent + cursorShape: Qt.PointingHandCursor + hoverEnabled: true + onEntered: { + hovering = true; + root.entered(); + } + onExited: { + hovering = false; + root.exited(); + } + onClicked: root.toggled(!root.checked) + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NCircleStat.qml b/quickshell/compat/noctalia/Widgets/NCircleStat.qml new file mode 100644 index 0000000..b2fb564 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NCircleStat.qml @@ -0,0 +1,164 @@ +import QtQuick +import QtQuick.Layouts +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Services.UI +import qs.compat.noctalia.Widgets + +// Compact circular statistic display using Layout management +Item { + id: root + + property real ratio: 0 // 0..1 range + property string icon: "" + property string suffix: "%" + property real contentScale: 1.0 + property color fillColor: Color.mPrimary + property var tooltipText + property string tooltipDirection: "top" + + // Arc geometry constants + readonly property real _gaugeSize: 60 * contentScale + readonly property real _lineWidth: 6 * contentScale + readonly property real _arcRadius: _gaugeSize / 2 - 5 * contentScale + // Arc goes from 150° to 390° (30°), gap at bottom + // Bottom of arc is at y = center + radius * sin(30°) = center + radius * 0.5 + // Plus half line width for stroke + readonly property real _arcBottomY: _gaugeSize / 2 + _arcRadius * 0.5 + _lineWidth / 2 + // Height needs to include the icon which sits inside the arc gap + // Icon is ~12px tall, positioned 4px below text center, need ~4px more padding + readonly property real _contentHeight: _arcBottomY + 4 * contentScale + + implicitWidth: Math.round(_gaugeSize) + implicitHeight: Math.round(_contentHeight) + Layout.maximumWidth: implicitWidth + Layout.maximumHeight: implicitHeight + + // Animated ratio for smooth transitions - reduces repaint frequency + property real animatedRatio: ratio + + Behavior on animatedRatio { + enabled: !Settings.data.general.animationDisabled + NumberAnimation { + duration: Style.animationNormal + easing.type: Easing.OutCubic + } + } + + // Repaint gauge when animated ratio changes (throttled by animation) + onAnimatedRatioChanged: { + if (!repaintTimer.running) { + repaintTimer.start(); + } + } + onFillColorChanged: gauge.requestPaint() + + // Throttle timer to limit repaint frequency during animation (~30 FPS) + Timer { + id: repaintTimer + interval: 33 + repeat: true + onTriggered: { + gauge.requestPaint(); + // Stop repeating once animation settles + if (Math.abs(root.animatedRatio - root.ratio) < 0.001) { + stop(); + } + } + } + + Canvas { + id: gauge + width: root._gaugeSize + height: root._gaugeSize + anchors.horizontalCenter: parent.horizontalCenter + y: 0 + + // Optimized Canvas settings for better GPU performance + renderStrategy: Canvas.Cooperative + renderTarget: Canvas.FramebufferObject + + // Enable layer caching - critical for performance! + layer.enabled: true + layer.smooth: true + + // Hide until first paint to avoid white FBO flash + visible: false + onPainted: visible = true + + Component.onCompleted: { + requestPaint(); + } + + onPaint: { + const ctx = getContext("2d"); + const w = width, h = height; + const cx = w / 2, cy = h / 2; + const r = root._arcRadius; + + // Rotated 90° to the right: gap at the bottom + // Start at 150° and end at 390° (30°) → bottom opening + const start = Math.PI * 5 / 6; // 150° + const endBg = Math.PI * 13 / 6; // 390° (equivalent to 30°) + + ctx.reset(); + ctx.lineWidth = root._lineWidth; + ctx.lineCap = Settings.data.general.iRadiusRatio > 0 ? "round" : "butt"; + + // Track uses outline for contrast against surfaceVariant backgrounds + ctx.strokeStyle = Color.mSurface; + ctx.beginPath(); + ctx.arc(cx, cy, r, start, endBg); + ctx.stroke(); + + // Value arc - only draw if ratio is meaningful (> 0.5%) + const r2 = Math.max(0, Math.min(1, root.animatedRatio)); + if (r2 > 0.005) { + const end = start + (endBg - start) * r2; + ctx.strokeStyle = root.fillColor; + ctx.beginPath(); + ctx.arc(cx, cy, r, start, end); + ctx.stroke(); + } + } + } + + // Percent centered in the circle + NText { + id: valueLabel + anchors.horizontalCenter: gauge.horizontalCenter + anchors.verticalCenter: gauge.verticalCenter + anchors.verticalCenterOffset: -4 * root.contentScale + text: `${Math.round(root.animatedRatio * 100)}${root.suffix}` + pointSize: Style.fontSizeM * root.contentScale * 0.9 + font.weight: Style.fontWeightBold + color: root.fillColor + horizontalAlignment: Text.AlignHCenter + } + + NIcon { + id: iconText + anchors.horizontalCenter: gauge.horizontalCenter + anchors.top: valueLabel.bottom + anchors.topMargin: 4 * root.contentScale + icon: root.icon + color: root.fillColor + pointSize: Style.fontSizeM * root.contentScale + horizontalAlignment: Text.AlignHCenter + verticalAlignment: Text.AlignVCenter + } + + MouseArea { + anchors.fill: parent + hoverEnabled: true + onEntered: { + if (root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) { + TooltipService.show(root, root.tooltipText, root.tooltipDirection); + } + } + onExited: { + if (root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) { + TooltipService.hide(); + } + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NClock.qml b/quickshell/compat/noctalia/Widgets/NClock.qml new file mode 100644 index 0000000..9a52b39 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NClock.qml @@ -0,0 +1,442 @@ +import QtQuick +import QtQuick.Layouts +import Quickshell +import "../Helpers/ColorsConvert.js" as ColorsConvert +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Widgets + +Item { + id: root + + property var now: Time.now + + // Style: "analog" or "digital" + property string clockStyle: "analog" + + // Show seconds progress ring (digital only) + property bool showProgress: true + + // Color properties + property color backgroundColor: Color.mPrimary + property color clockColor: Color.mOnPrimary + + property color secondHandColor: { + var defaultColor = Color.mError; + var bestContrast = 1.0; // 1.0 is "no contrast" + var bestColor = defaultColor; + var candidates = [Color.mSecondary, Color.mTertiary, Color.mError]; + + const minContrast = 1.149; + + for (var i = 0; i < candidates.length; i++) { + var candidate = candidates[i]; + var contrastClock = ColorsConvert.getContrastRatio(candidate.toString(), clockColor.toString()); + if (contrastClock < minContrast) { + continue; + } + var contrastBg = ColorsConvert.getContrastRatio(candidate.toString(), backgroundColor.toString()); + if (contrastBg < minContrast) { + continue; + } + + var currentWorstContrast = Math.min(contrastBg, contrastClock); + + if (currentWorstContrast > bestContrast) { + bestContrast = currentWorstContrast; + bestColor = candidate; + } + } + + return bestColor; + } + + property color progressColor: root.secondHandColor + + // Font size properties for digital clock + property real hoursFontSize: Style.fontSizeXS + property real minutesFontSize: Style.fontSizeXXS + property int hoursFontWeight: Style.fontWeightBold + property int minutesFontWeight: Style.fontWeightBold + + // Scale ratio for canvas line widths (used by desktop widget scaling) + property real scaleRatio: Style.uiScaleRatio + + height: Math.round((Style.fontSizeXXXL * 1.9) / 2 * Style.uiScaleRatio) * 2 + width: root.height + + Loader { + id: clockLoader + anchors.fill: parent + + sourceComponent: { + if (root.clockStyle === "analog") + return analogClockComponent; + if (root.clockStyle === "binary") + return binaryClockComponent; + return digitalClockComponent; + } + + onLoaded: { + item.now = Qt.binding(function () { + return root.now; + }); + item.backgroundColor = Qt.binding(function () { + return root.backgroundColor; + }); + item.clockColor = Qt.binding(function () { + return root.clockColor; + }); + if (item.hasOwnProperty("secondHandColor")) { + item.secondHandColor = Qt.binding(function () { + return root.secondHandColor; + }); + } + if (item.hasOwnProperty("progressColor")) { + item.progressColor = Qt.binding(function () { + return root.progressColor; + }); + } + if (item.hasOwnProperty("hoursFontSize")) { + item.hoursFontSize = Qt.binding(function () { + return root.hoursFontSize; + }); + } + if (item.hasOwnProperty("minutesFontSize")) { + item.minutesFontSize = Qt.binding(function () { + return root.minutesFontSize; + }); + } + if ("hoursFontWeight" in item) { + item.hoursFontWeight = Qt.binding(function () { + return root.hoursFontWeight; + }); + } + if ("minutesFontWeight" in item) { + item.minutesFontWeight = Qt.binding(function () { + return root.minutesFontWeight; + }); + } + if (item.hasOwnProperty("scaleRatio")) { + item.scaleRatio = Qt.binding(function () { + return root.scaleRatio; + }); + } + if ("showProgress" in item) { + item.showProgress = Qt.binding(function () { + return root.showProgress; + }); + } + } + } + + // Analog Clock Component + component NClockAnalog: Item { + property var now + property color backgroundColor: Color.mPrimary + property color clockColor: Color.mOnPrimary + property color secondHandColor: Color.mError + property real scaleRatio: Style.uiScaleRatio + anchors.fill: parent + + Canvas { + id: clockCanvas + anchors.fill: parent + + Connections { + target: Time + function onNowChanged() { + clockCanvas.requestPaint(); + } + } + + onPaint: { + var currentTime = Time.now; + var hours = currentTime.getHours(); + var minutes = currentTime.getMinutes(); + var seconds = currentTime.getSeconds(); + + const markAlpha = 0.7; + var ctx = getContext("2d"); + ctx.reset(); + ctx.translate(width / 2, height / 2); + var radius = Math.min(width, height) / 2; + + // Hour marks + ctx.strokeStyle = Qt.alpha(clockColor, markAlpha); + ctx.lineWidth = 2 * scaleRatio; + var scaleFactor = 0.7; + + for (var i = 0; i < 12; i++) { + var scaleFactor = 0.8; + if (i % 3 === 0) { + scaleFactor = 0.65; + } + ctx.save(); + ctx.rotate(i * Math.PI / 6); + ctx.beginPath(); + ctx.moveTo(0, -radius * scaleFactor); + ctx.lineTo(0, -radius); + ctx.stroke(); + ctx.restore(); + } + + // Hour hand + ctx.save(); + var hourAngle = (hours % 12 + minutes / 60) * Math.PI / 6; + ctx.rotate(hourAngle); + ctx.strokeStyle = clockColor; + ctx.lineWidth = 3 * scaleRatio; + ctx.lineCap = "round"; + ctx.beginPath(); + ctx.moveTo(0, 0); + ctx.lineTo(0, -radius * 0.6); + ctx.stroke(); + ctx.restore(); + + // Minute hand + ctx.save(); + var minuteAngle = (minutes + seconds / 60) * Math.PI / 30; + ctx.rotate(minuteAngle); + ctx.strokeStyle = clockColor; + ctx.lineWidth = 2 * scaleRatio; + ctx.lineCap = "round"; + ctx.beginPath(); + ctx.moveTo(0, 0); + ctx.lineTo(0, -radius * 0.9); + ctx.stroke(); + ctx.restore(); + + // Second hand + ctx.save(); + var secondAngle = seconds * Math.PI / 30; + ctx.rotate(secondAngle); + ctx.strokeStyle = secondHandColor; + ctx.lineWidth = 1.6 * scaleRatio; + ctx.lineCap = "round"; + ctx.beginPath(); + ctx.moveTo(0, 0); + ctx.lineTo(0, -radius); + ctx.stroke(); + ctx.restore(); + + // Center dot + ctx.beginPath(); + ctx.arc(0, 0, 3 * scaleRatio, 0, 2 * Math.PI); + ctx.fillStyle = clockColor; + ctx.fill(); + } + + Component.onCompleted: requestPaint() + } + } + + // Digital Clock Component + component NClockDigital: Item { + property var now + property color backgroundColor: Color.mPrimary + property color clockColor: Color.mOnPrimary + property color progressColor: Color.mError + property real hoursFontSize: Style.fontSizeXS + property real minutesFontSize: Style.fontSizeXXS + property int hoursFontWeight: Style.fontWeightBold + property int minutesFontWeight: Style.fontWeightBold + property real scaleRatio: Style.uiScaleRatio + property bool showProgress: true + + anchors.fill: parent + + // Digital clock's seconds circular progress + Canvas { + id: secondsProgress + anchors.fill: parent + visible: showProgress + property real progress: now.getSeconds() / 60 + onProgressChanged: requestPaint() + Connections { + target: Time + function onNowChanged() { + const total = now.getSeconds() * 1000 + now.getMilliseconds(); + secondsProgress.progress = total / 60000; + } + } + onPaint: { + var ctx = getContext("2d"); + var centerX = width / 2; + var centerY = height / 2; + var radius = Math.min(width, height) / 2 - 3 * scaleRatio; + ctx.reset(); + + // Background circle + ctx.beginPath(); + ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI); + ctx.lineWidth = 2.5 * scaleRatio; + ctx.strokeStyle = Qt.alpha(clockColor, 0.15); + ctx.stroke(); + + // Progress arc + ctx.beginPath(); + ctx.arc(centerX, centerY, radius, -Math.PI / 2, -Math.PI / 2 + progress * 2 * Math.PI); + ctx.lineWidth = 2.5 * scaleRatio; + ctx.strokeStyle = progressColor; + ctx.lineCap = "round"; + ctx.stroke(); + } + } + + // Digital clock + ColumnLayout { + anchors.centerIn: parent + spacing: -Style.marginXXS + + NText { + text: { + var t = Settings.data.location.use12hourFormat ? I18n.locale.toString(now, "hh AP") : I18n.locale.toString(now, "HH"); + return t.split(" ")[0]; + } + + pointSize: hoursFontSize + font.weight: hoursFontWeight + color: clockColor + family: Settings.data.ui.fontFixed + Layout.alignment: Qt.AlignHCenter + } + + NText { + text: Qt.formatTime(now, "mm") + pointSize: minutesFontSize + font.weight: minutesFontWeight + color: clockColor + family: Settings.data.ui.fontFixed + Layout.alignment: Qt.AlignHCenter + } + } + } + + // Binary Clock Component + component NClockBinary: Item { + property var now + property color backgroundColor + property color clockColor: Color.mOnPrimary + + anchors.fill: parent + + readonly property int h: now.getHours() + readonly property int m: now.getMinutes() + readonly property int s: now.getSeconds() + + // BCD (Binary Coded Decimal) Format: + // H1 H2 : M1 M2 : S1 S2 + // H1 (tens): 0-2 (2 bits) + // H2 (ones): 0-9 (4 bits) + // M1 (tens): 0-5 (3 bits) + // M2 (ones): 0-9 (4 bits) + // S1 (tens): 0-5 (3 bits) + // S2 (ones): 0-9 (4 bits) + + RowLayout { + anchors.centerIn: parent + spacing: parent.width * 0.05 + + // Hours + RowLayout { + spacing: parent.parent.width * 0.02 + BinaryColumn { + value: Math.floor(h / 10) + bits: 2 + dotSize: root.width * 0.08 + activeColor: clockColor + Layout.alignment: Qt.AlignBottom + } + BinaryColumn { + value: h % 10 + bits: 4 + dotSize: root.width * 0.08 + activeColor: clockColor + Layout.alignment: Qt.AlignBottom + } + } + + // Minutes + RowLayout { + spacing: parent.parent.width * 0.02 + BinaryColumn { + value: Math.floor(m / 10) + bits: 3 + dotSize: root.width * 0.08 + activeColor: clockColor + Layout.alignment: Qt.AlignBottom + } + BinaryColumn { + value: m % 10 + bits: 4 + dotSize: root.width * 0.08 + activeColor: clockColor + Layout.alignment: Qt.AlignBottom + } + } + + // Seconds + RowLayout { + spacing: parent.parent.width * 0.02 + BinaryColumn { + value: Math.floor(s / 10) + bits: 3 + dotSize: root.width * 0.08 + activeColor: clockColor + Layout.alignment: Qt.AlignBottom + } + BinaryColumn { + value: s % 10 + bits: 4 + dotSize: root.width * 0.08 + activeColor: clockColor + Layout.alignment: Qt.AlignBottom + } + } + } + } + + component BinaryColumn: Column { + property int value: 0 + property int bits: 4 + property real dotSize: 10 + property color activeColor: "white" + + spacing: dotSize * 0.4 + + Repeater { + model: bits + + Rectangle { + property int bitIndex: (bits - 1) - index + property bool isActive: (value >> bitIndex) & 1 + + width: dotSize + height: dotSize + radius: dotSize / 2 + color: isActive ? activeColor : Qt.alpha(activeColor, 0.2) + + Behavior on color { + ColorAnimation { + duration: 200 + } + } + } + } + } + + Component { + id: analogClockComponent + NClockAnalog {} + } + + Component { + id: digitalClockComponent + NClockDigital {} + } + + Component { + id: binaryClockComponent + NClockBinary {} + } +} diff --git a/quickshell/compat/noctalia/Widgets/NCollapsible.qml b/quickshell/compat/noctalia/Widgets/NCollapsible.qml new file mode 100644 index 0000000..fc21c2f --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NCollapsible.qml @@ -0,0 +1,191 @@ +import QtQuick +import QtQuick.Layouts +import qs.compat.noctalia.Commons + +ColumnLayout { + id: root + + property string label: "" + property string description: "" + property bool expanded: false + property real contentSpacing: Style.marginM + property bool _userInteracted: false + + signal toggled(bool expanded) + + Layout.fillWidth: true + spacing: 0 + + // Default property to accept children + default property alias content: contentLayout.children + + // Header with clickable area + Rectangle { + id: headerContainer + Layout.fillWidth: true + Layout.preferredHeight: headerContent.implicitHeight + Style.margin2M + color: root.expanded ? Color.mSecondary : Color.mPrimary + radius: Style.iRadiusM + border.color: root.expanded ? Color.mOnSecondary : Color.mOutline + border.width: Style.borderS + + // Smooth color transitions + Behavior on color { + enabled: root._userInteracted + ColorAnimation { + duration: Style.animationNormal + easing.type: Easing.OutCubic + } + } + + Behavior on border.color { + enabled: root._userInteracted + ColorAnimation { + duration: Style.animationNormal + easing.type: Easing.OutCubic + } + } + + MouseArea { + id: headerArea + anchors.fill: parent + cursorShape: Qt.PointingHandCursor + hoverEnabled: true + + onClicked: { + root._userInteracted = true; + root.expanded = !root.expanded; + root.toggled(root.expanded); + } + + // Hover effect overlay + Rectangle { + anchors.fill: parent + color: headerArea.containsMouse ? Color.mOnSurface : "transparent" + opacity: headerArea.containsMouse ? 0.08 : 0 + radius: headerContainer.radius // Reference the container's radius directly + + Behavior on opacity { + NumberAnimation { + duration: Style.animationFast + } + } + } + } + + RowLayout { + id: headerContent + anchors.fill: parent + anchors.margins: Style.marginM + spacing: Style.marginM + + // Expand/collapse icon with rotation animation + NIcon { + id: chevronIcon + icon: "chevron-right" + pointSize: Style.fontSizeL + color: root.expanded ? Color.mOnSecondary : Color.mOnPrimary + Layout.alignment: Qt.AlignVCenter + + rotation: root.expanded ? 90 : 0 + Behavior on rotation { + enabled: root._userInteracted + NumberAnimation { + duration: Style.animationNormal + easing.type: Easing.OutCubic + } + } + + Behavior on color { + enabled: root._userInteracted + ColorAnimation { + duration: Style.animationNormal + } + } + } + + // Header text content - properly contained + RowLayout { + Layout.fillWidth: true + Layout.alignment: Qt.AlignVCenter + spacing: Style.marginL + + NText { + text: root.label + pointSize: Style.fontSizeL + font.weight: Style.fontWeightSemiBold + color: root.expanded ? Color.mOnSecondary : Color.mOnPrimary + wrapMode: Text.WordWrap + + Behavior on color { + enabled: root._userInteracted + ColorAnimation { + duration: Style.animationNormal + } + } + } + + NText { + text: root.description + pointSize: Style.fontSizeS + font.weight: Style.fontWeightRegular + color: root.expanded ? Color.mOnSecondary : Color.mOnPrimary + Layout.fillWidth: true + wrapMode: Text.WordWrap + visible: root.description !== "" + opacity: 0.87 + + Behavior on color { + enabled: root._userInteracted + ColorAnimation { + duration: Style.animationNormal + } + } + } + } + } + } + + // Collapsible content with Material 3 styling + Rectangle { + id: contentContainer + Layout.fillWidth: true + Layout.topMargin: Style.marginS + + visible: root.expanded + color: Color.mSurface + radius: Style.iRadiusL + border.color: Color.mOutline + border.width: Style.borderS + + // Dynamic height based on content + Layout.preferredHeight: expanded ? contentLayout.implicitHeight + Style.margin2L : 0 + + // Smooth height animation + Behavior on Layout.preferredHeight { + enabled: root._userInteracted + NumberAnimation { + duration: Style.animationNormal + easing.type: Easing.OutCubic + } + } + + // Content layout + ColumnLayout { + id: contentLayout + anchors.fill: parent + anchors.margins: Style.marginL + spacing: root.contentSpacing + } + + // Fade in animation for content + opacity: root.expanded ? 1.0 : 0.0 + Behavior on opacity { + enabled: root._userInteracted + NumberAnimation { + duration: Style.animationNormal + easing.type: Easing.OutCubic + } + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NColorChoice.qml b/quickshell/compat/noctalia/Widgets/NColorChoice.qml new file mode 100644 index 0000000..1122386 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NColorChoice.qml @@ -0,0 +1,89 @@ +import QtQuick +import QtQuick.Layouts +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Services.UI + +RowLayout { + id: root + + property string label: I18n.tr("common.select-color") + property string description: I18n.tr("common.select-color-description") + property string tooltip: "" + property string currentKey: "" + property var defaultValue: undefined + property var noneColor: undefined // color declared as var so we can nullify + property var noneOnColor: undefined // color declared as var so we can nullify + + readonly property bool isValueChanged: (defaultValue !== undefined) && (currentKey !== defaultValue) + readonly property string indicatorTooltip: { + I18n.tr("panels.indicator.default-value", { + "value": defaultValue === "" ? "(empty)" : String(defaultValue) + }); + } + + readonly property int diameter: Style.baseWidgetSize * 0.9 * Style.uiScaleRatio + + signal selected(string key) + + NLabel { + label: root.label + description: root.description + showIndicator: root.isValueChanged + indicatorTooltip: root.indicatorTooltip + } + + RowLayout { + id: colourRow + + opacity: enabled ? 1.0 : 0.6 + Layout.minimumWidth: root.diameter * Color.colorKeyModel.length + + Repeater { + model: Color.colorKeyModel + + Rectangle { + id: colorCircle + + property bool isSelected: root.currentKey === modelData.key + property bool isHovered: circleMouseArea.containsMouse + + Layout.alignment: Qt.AlignHCenter + implicitWidth: root.diameter + implicitHeight: root.diameter + radius: root.diameter * 0.5 + color: (modelData.key === "none" && root.noneColor !== undefined) ? root.noneColor : Color.resolveColorKey(modelData.key) + border.color: (isSelected || isHovered) ? Color.mOnSurface : Color.mOutline + border.width: Style.borderM + + MouseArea { + id: circleMouseArea + + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onEntered: TooltipService.show(parent, modelData.name) + onExited: TooltipService.hide() + onClicked: { + root.currentKey = modelData.key; + root.selected(modelData.key); + } + } + + NIcon { + anchors.centerIn: parent + icon: "check" + pointSize: Math.max(Style.fontSizeXS, colorCircle.width * 0.4) + color: (modelData.key === "none" && root.noneOnColor !== undefined) ? root.noneOnColor : Color.resolveOnColorKey(modelData.key) + font.weight: Style.fontWeightBold + visible: colorCircle.isSelected + } + + Behavior on border.color { + ColorAnimation { + duration: Style.animationFast + } + } + } + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NColorPicker.qml b/quickshell/compat/noctalia/Widgets/NColorPicker.qml new file mode 100644 index 0000000..b9a692e --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NColorPicker.qml @@ -0,0 +1,76 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Widgets + +Rectangle { + id: root + + property var screen + property color selectedColor: "black" + + signal colorSelected(color color) + + Layout.margins: Style.borderS + implicitWidth: 150 + implicitHeight: Math.round(Style.baseWidgetSize * 1.1) + + radius: Style.iRadiusM + color: Color.mSurface + border.color: Color.mOutline + border.width: Style.borderS + + // Minimized Look + MouseArea { + anchors.fill: parent + cursorShape: Qt.PointingHandCursor + onClicked: { + var dialog = Qt.createComponent("NColorPickerDialog.qml").createObject(root, { + "selectedColor": selectedColor, + "parent": Overlay.overlay, + "screen": root.screen + }); + // Connect the dialog's signal to the picker's signal + dialog.colorSelected.connect(function (color) { + root.selectedColor = color; + root.colorSelected(color); + }); + + dialog.open(); + } + + RowLayout { + anchors.fill: parent + anchors { + leftMargin: Style.marginL + rightMargin: Style.marginL + } + spacing: Style.marginS + + // Color preview circle + Rectangle { + Layout.preferredWidth: root.height * 0.6 + Layout.preferredHeight: root.height * 0.6 + radius: Math.min(Style.iRadiusL, Layout.preferredWidth / 2) + color: root.selectedColor + border.color: Color.mOutline + border.width: Style.borderS + } + + NText { + text: root.selectedColor.toString().toUpperCase() + family: Settings.data.ui.fontFixed + Layout.fillWidth: true + Layout.alignment: Qt.AlignVCenter + } + + NIcon { + icon: "color-picker" + color: Color.mOnSurfaceVariant + Layout.fillWidth: true + Layout.alignment: Qt.AlignVCenter + } + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NColorPickerDialog.qml b/quickshell/compat/noctalia/Widgets/NColorPickerDialog.qml new file mode 100644 index 0000000..aeb8504 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NColorPickerDialog.qml @@ -0,0 +1,775 @@ +import QtQml +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import "../Helpers/ColorList.js" as ColorList +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Services.UI +import qs.compat.noctalia.Widgets + +Popup { + id: root + + property var screen + property color selectedColor: "black" + + enum EditMode { + R, + G, + B, + H, + S, + V + } + property int editMode: NColorPickerDialog.EditMode.R + + // Code to deal with Hue when color is achromatic + property real stableHue: 0 + onSelectedColorChanged: { + if (selectedColor.hsvHue >= 0) { + stableHue = selectedColor.hsvHue; + } + if (liveMode && visible) { + colorSelected(selectedColor); + } + } + readonly property real displayHue: selectedColor.hsvHue < 0 ? stableHue : selectedColor.hsvHue + + signal colorSelected(color color) + + // When true: hides Cancel/Apply, emits colorSelected on every color change + property bool liveMode: false + + width: 580 + padding: Style.marginXL + + modal: true + closePolicy: Popup.CloseOnEscape | Popup.CloseOnPressOutside + + onOpened: { + // Center on screen after popup is opened and parent position is known + if (screen && parent) { + var parentPos = parent.mapToItem(null, 0, 0); + x = Math.round((screen.width - width) / 2 - parentPos.x); + y = Math.round((screen.height - height) / 2 - parentPos.y); + } + } + + background: Rectangle { + color: Color.mSurface + radius: Style.iRadiusS + border.color: Color.mPrimary + border.width: Style.borderM + } + + contentItem: ColumnLayout { + id: mainContent + spacing: Style.marginL + + // Header + RowLayout { + Layout.fillWidth: true + + RowLayout { + spacing: Style.marginS + + NIcon { + icon: "color-picker" + pointSize: Style.fontSizeXXL + color: Color.mPrimary + } + + NText { + text: I18n.tr("widgets.color-picker.title") + pointSize: Style.fontSizeXL + font.weight: Style.fontWeightBold + color: Color.mPrimary + } + } + + Item { + Layout.fillWidth: true + } + + NIconButton { + icon: "close" + onClicked: root.close() + } + } + + // Color preview section + Rectangle { + Layout.fillWidth: true + Layout.preferredHeight: 80 + radius: Style.iRadiusS + color: root.selectedColor + border.color: Color.mOutline + border.width: Style.borderS + + ColumnLayout { + spacing: 0 + anchors.fill: parent + + Item { + Layout.fillHeight: true + } + + NText { + text: root.selectedColor.toString().toUpperCase() + family: Settings.data.ui.fontFixed + pointSize: Style.fontSizeL + font.weight: Style.fontWeightMedium + color: root.selectedColor.r + root.selectedColor.g + root.selectedColor.b > 1.5 ? "black" : "white" + Layout.alignment: Qt.AlignHCenter + } + + NText { + text: "RGB(" + Math.round(root.selectedColor.r * 255) + ", " + Math.round(root.selectedColor.g * 255) + ", " + Math.round(root.selectedColor.b * 255) + ")" + family: Settings.data.ui.fontFixed + pointSize: Style.fontSizeM + color: root.selectedColor.r + root.selectedColor.g + root.selectedColor.b > 1.5 ? "black" : "white" + Layout.alignment: Qt.AlignHCenter + } + + Item { + Layout.fillHeight: true + } + } + } + + // Main Box + NBox { + Layout.fillWidth: true + Layout.preferredHeight: controlsOutterColumn.implicitHeight + Style.margin2L + + ButtonGroup { + id: colorValues + } + + ColumnLayout { + id: controlsOutterColumn + anchors.fill: parent + anchors.margins: Style.marginL + spacing: Style.marginM + + RowLayout { + spacing: Style.marginL // Ensure nice gap between Left and Right groups + + // SpinBoxes Column + ColumnLayout { + Layout.fillWidth: true + Layout.fillHeight: true + Layout.alignment: Qt.AlignTop + Layout.preferredWidth: 3 + + // --- RED --- + RowLayout { + Layout.fillWidth: true + spacing: Style.marginM + + NRadioButton { + ButtonGroup.group: colorValues + text: "R" + font.weight: Style.fontWeightMedium + checked: true + onClicked: root.editMode = NColorPickerDialog.EditMode.R + Layout.fillWidth: false + } + + NSpinBox { + id: redSpinBox + from: 0 + to: 255 + + onValueChanged: { + if (!selectedSlider.pressed && !fieldMouse.pressed && !hexInput.activeFocus && value !== Math.round(root.selectedColor.r * 255)) { + root.selectedColor = Qt.rgba(value / 255, root.selectedColor.g, root.selectedColor.b, 1); + } + } + Binding { + target: redSpinBox + property: "value" + value: Math.round(root.selectedColor.r * 255) + } + } + } + + // --- GREEN --- + RowLayout { + Layout.fillWidth: true + spacing: Style.marginM + + NRadioButton { + ButtonGroup.group: colorValues + text: "G" + font.weight: Style.fontWeightMedium + onClicked: root.editMode = NColorPickerDialog.EditMode.G + Layout.fillWidth: false + } + + NSpinBox { + id: greenSpinBox + from: 0 + to: 255 + + onValueChanged: { + if (!selectedSlider.pressed && !fieldMouse.pressed && !hexInput.activeFocus && value !== Math.round(root.selectedColor.g * 255)) { + root.selectedColor = Qt.rgba(root.selectedColor.r, value / 255, root.selectedColor.b, 1); + } + } + Binding { + target: greenSpinBox + property: "value" + value: Math.round(root.selectedColor.g * 255) + } + } + } + + // --- BLUE --- + RowLayout { + Layout.fillWidth: true + spacing: Style.marginM + + NRadioButton { + ButtonGroup.group: colorValues + text: "B" + font.weight: Style.fontWeightMedium + onClicked: root.editMode = NColorPickerDialog.EditMode.B + Layout.fillWidth: false + } + + NSpinBox { + id: blueSpinBox + from: 0 + to: 255 + + onValueChanged: { + if (!selectedSlider.pressed && !fieldMouse.pressed && !hexInput.activeFocus && value !== Math.round(root.selectedColor.b * 255)) { + root.selectedColor = Qt.rgba(root.selectedColor.r, root.selectedColor.g, value / 255, 1); + } + } + Binding { + target: blueSpinBox + property: "value" + value: Math.round(root.selectedColor.b * 255) + } + } + } + + // Spacer + Item { + Layout.fillHeight: true + Layout.fillWidth: true + } + + // --- HUE --- + RowLayout { + Layout.fillWidth: true + spacing: Style.marginM + + NRadioButton { + ButtonGroup.group: colorValues + text: "H" + font.weight: Style.fontWeightMedium + checked: true + onClicked: root.editMode = NColorPickerDialog.EditMode.H + Layout.fillWidth: false + } + + NSpinBox { + id: hueSpinBox + from: 0 + to: 360 + + onValueChanged: { + if (!selectedSlider.pressed && !fieldMouse.pressed && !hexInput.activeFocus && value !== Math.round(root.displayHue * 360)) { + var newHue = value / 360; + root.selectedColor = Qt.hsva(newHue, root.selectedColor.hsvSaturation, root.selectedColor.hsvValue, 1); + root.stableHue = newHue; + } + } + + Binding { + target: hueSpinBox + property: "value" + value: Math.round(root.displayHue * 360) + } + } + } + + // --- SATURATION --- + RowLayout { + Layout.fillWidth: true + spacing: Style.marginM + + NRadioButton { + ButtonGroup.group: colorValues + text: "S" + font.weight: Style.fontWeightMedium + onClicked: root.editMode = NColorPickerDialog.EditMode.S + Layout.fillWidth: false + } + + NSpinBox { + id: satSpinBox + from: 0 + to: 100 + + onValueChanged: { + if (!selectedSlider.pressed && !fieldMouse.pressed && !hexInput.activeFocus && value !== Math.round(root.selectedColor.hsvSaturation * 100)) { + root.selectedColor = Qt.hsva(root.selectedColor.hsvHue, value / 100, root.selectedColor.hsvValue, 1); + } + } + Binding { + target: satSpinBox + property: "value" + value: Math.round(root.selectedColor.hsvSaturation * 100) + } + } + } + + // --- VALUE --- + RowLayout { + spacing: Style.marginM + + NRadioButton { + ButtonGroup.group: colorValues + text: "V" + font.weight: Style.fontWeightMedium + onClicked: root.editMode = NColorPickerDialog.EditMode.V + Layout.fillWidth: false + } + + NSpinBox { + id: valSpinBox + from: 0 + to: 100 + + onValueChanged: { + if (!selectedSlider.pressed && !fieldMouse.pressed && !hexInput.activeFocus && value !== Math.round(root.selectedColor.hsvValue * 100)) { + root.selectedColor = Qt.hsva(root.selectedColor.hsvHue, root.selectedColor.hsvSaturation, value / 100, 1); + } + } + Binding { + target: valSpinBox + property: "value" + value: Math.round(root.selectedColor.hsvValue * 100) + } + } + } + + // Spacer + Item { + Layout.fillHeight: true + Layout.fillWidth: true + } + + // Hex input + RowLayout { + id: hexInput + Layout.fillWidth: true + spacing: Style.marginM + + NLabel { + label: "Hex:" + Layout.alignment: Qt.AlignVCenter + } + + NTextInput { + text: root.selectedColor.toString().toUpperCase() + fontFamily: Settings.data.ui.fontFixed + Layout.fillWidth: true + Layout.minimumWidth: implicitWidth + onEditingFinished: { + if (/^#[0-9A-F]{6}$/i.test(text)) { + root.selectedColor = text; + } + } + } + } + } + + RowLayout { + Layout.fillWidth: true + Layout.fillHeight: true + Layout.preferredWidth: 5 + Layout.alignment: Qt.AlignTop + spacing: Style.marginS + + Layout.topMargin: Math.round(2 * Style.uiScaleRatio) //Shim to try and line up colorField with SpinBoxes + + // --- SLIDER --- + NColorSlider { + id: selectedSlider + Layout.fillHeight: true + rainbowMode: root.editMode === NColorPickerDialog.EditMode.H + topColor: { + if (rainbowMode) + return "transparent"; + switch (root.editMode) { + case NColorPickerDialog.EditMode.R: + return "#FF0000"; + case NColorPickerDialog.EditMode.G: + return "#00FF00"; + case NColorPickerDialog.EditMode.B: + return "#0000FF"; + default: + return "#FFFFFF"; + } + } + + Binding { + target: selectedSlider + property: "value" + when: !selectedSlider.pressed // Only update from model when NOT dragging + value: { + switch (root.editMode) { + case NColorPickerDialog.EditMode.R: + return root.selectedColor.r; + case NColorPickerDialog.EditMode.G: + return root.selectedColor.g; + case NColorPickerDialog.EditMode.B: + return root.selectedColor.b; + case NColorPickerDialog.EditMode.H: + return root.displayHue; + case NColorPickerDialog.EditMode.S: + return root.selectedColor.hsvSaturation; + case NColorPickerDialog.EditMode.V: + return root.selectedColor.hsvValue; + default: + return 0; + } + } + } + + onMoved: { + var v = value; + switch (root.editMode) { + case NColorPickerDialog.EditMode.R: + root.selectedColor = Qt.rgba(v, root.selectedColor.g, root.selectedColor.b, 1); + break; + case NColorPickerDialog.EditMode.G: + root.selectedColor = Qt.rgba(root.selectedColor.r, v, root.selectedColor.b, 1); + break; + case NColorPickerDialog.EditMode.B: + root.selectedColor = Qt.rgba(root.selectedColor.r, root.selectedColor.g, v, 1); + break; + case NColorPickerDialog.EditMode.H: + root.selectedColor = Qt.hsva(v, root.selectedColor.hsvSaturation, root.selectedColor.hsvValue, 1); + root.stableHue = v; + break; + case NColorPickerDialog.EditMode.S: + root.selectedColor = Qt.hsva(root.selectedColor.hsvHue, v, root.selectedColor.hsvValue, 1); + break; + case NColorPickerDialog.EditMode.V: + root.selectedColor = Qt.hsva(root.selectedColor.hsvHue, root.selectedColor.hsvSaturation, v, 1); + break; + } + } + } + + // Color Field + Rectangle { + id: colorField + Layout.fillWidth: true + + Layout.preferredHeight: width + Layout.alignment: Qt.AlignTop + + radius: 0 + border.color: Color.mOutline + border.width: Style.borderS + clip: true + + ShaderEffect { + anchors.fill: parent + anchors.margins: 1 // Avoid drawing over the border + + fragmentShader: "../Shaders/qsb/color_picker.frag.qsb" + + // Pass which radio is selected + readonly property real fixedVal: { + switch (root.editMode) { + case NColorPickerDialog.EditMode.R: + return root.selectedColor.r; + case NColorPickerDialog.EditMode.G: + return root.selectedColor.g; + case NColorPickerDialog.EditMode.B: + return root.selectedColor.b; + case NColorPickerDialog.EditMode.H: + return root.displayHue; + case NColorPickerDialog.EditMode.S: + return root.selectedColor.hsvSaturation; + case NColorPickerDialog.EditMode.V: + return root.selectedColor.hsvValue; + default: + return 0; + } + } + + // Send as one vector because GPUs are so damn picky + property vector4d params: Qt.vector4d(1.0, fixedVal, root.editMode, 0) + } + + MouseArea { + id: fieldMouse + anchors.fill: parent + cursorShape: Qt.CrossCursor + + // Update color when clicking or dragging + function updateColor(mouse) { + // Normalize X and Y (0.0 to 1.0) + var xVal = Math.max(0, Math.min(1, mouse.x / width)); + var yVal = Math.max(0, Math.min(1, 1.0 - (mouse.y / height))); // Flip Y (0 at bottom) + + // Get the current fixed value (from the slider) + var fixed = 0.0; + + switch (root.editMode) { + case NColorPickerDialog.EditMode.R: + fixed = root.selectedColor.r; + root.selectedColor = Qt.rgba(fixed, xVal, yVal, 1); + break; + case NColorPickerDialog.EditMode.G: + fixed = root.selectedColor.g; + root.selectedColor = Qt.rgba(xVal, fixed, yVal, 1); + break; + case NColorPickerDialog.EditMode.B: + fixed = root.selectedColor.b; + root.selectedColor = Qt.rgba(xVal, yVal, fixed, 1); + break; + case NColorPickerDialog.EditMode.H: + // Use stableHue to prevent flipping to -1 + fixed = root.displayHue; + root.selectedColor = Qt.hsva(fixed, xVal, yVal, 1); + root.stableHue = fixed; + break; + case NColorPickerDialog.EditMode.S: + fixed = root.selectedColor.hsvSaturation; + root.selectedColor = Qt.hsva(xVal, fixed, yVal, 1); + // If we dragged Hue (xVal), update stableHue + root.stableHue = yVal; + break; + case NColorPickerDialog.EditMode.V: + fixed = root.selectedColor.hsvValue; + root.selectedColor = Qt.hsva(xVal, yVal, fixed, 1); + // If we dragged Hue (xVal), update stableHue + root.stableHue = xVal; + break; + } + } + onPressed: mouse => updateColor(mouse) + onPositionChanged: mouse => updateColor(mouse) + } + + // Color Indicator + Rectangle { + width: 10 + height: 10 + radius: Math.min(Style.iRadiusXS, width / 2) + color: "transparent" + border.color: root.selectedColor.hsvValue < 0.5 ? "white" : "black" + border.width: 1 + + // Find position based on the current color + readonly property point selectedPos: { + switch (root.editMode) { + case NColorPickerDialog.EditMode.R: + return Qt.point(root.selectedColor.g, root.selectedColor.b); + case NColorPickerDialog.EditMode.G: + return Qt.point(root.selectedColor.r, root.selectedColor.b); + case NColorPickerDialog.EditMode.B: + return Qt.point(root.selectedColor.r, root.selectedColor.g); + case NColorPickerDialog.EditMode.H: + return Qt.point(root.selectedColor.hsvSaturation, root.selectedColor.hsvValue); + case NColorPickerDialog.EditMode.S: + return Qt.point(root.displayHue, root.selectedColor.hsvValue); + case NColorPickerDialog.EditMode.V: + return Qt.point(root.displayHue, root.selectedColor.hsvSaturation); + default: + return Qt.point(0, 0); + } + } + + // Convert values to pixel position + x: (selectedPos.x * parent.width) - width / 2 + y: ((1.0 - selectedPos.y) * parent.height) - height / 2 + } + + // Redraw the border in case Color Indicator is near the edge + Rectangle { + anchors.fill: parent + color: "transparent" + border.color: Color.mOutline + border.width: Style.borderS + antialiasing: false + } + } + } + } + + NLabel { + label: I18n.tr("widgets.color-picker.palette-label") + Layout.fillWidth: true + } + + NScrollView { + id: paletteScrollView + Layout.fillWidth: true + Layout.preferredHeight: Math.min(paletteGrid.implicitHeight, 200) + verticalPolicy: paletteGrid.implicitHeight > 200 ? ScrollBar.AsNeeded : ScrollBar.AlwaysOff + horizontalPolicy: ScrollBar.AlwaysOff + + GridLayout { + id: paletteGrid + width: paletteScrollView.availableWidth + columns: 17 + columnSpacing: 6 + rowSpacing: 6 + + NLabel { + Layout.columnSpan: 17 + Layout.fillWidth: true + description: I18n.tr("widgets.color-picker.palette-theme-colors") + } + + Repeater { + model: [ + { + name: "mPrimary", + color: Color.mPrimary + }, + { + name: "mSecondary", + color: Color.mSecondary + }, + { + name: "mTertiary", + color: Color.mTertiary + }, + { + name: "mError", + color: Color.mError + }, + { + name: "mSurface", + color: Color.mSurface + }, + { + name: "mSurfaceVariant", + color: Color.mSurfaceVariant + }, + { + name: "mOutline", + color: Color.mOutline + } + ] + + Rectangle { + width: 24 + height: 24 + radius: Style.iRadiusXXS + color: modelData.color + border.color: root.selectedColor.toString() === modelData.color.toString() ? Color.mPrimary : Color.mOutline + border.width: Math.max(1, root.selectedColor.toString() === modelData.color.toString() ? Style.borderM : Style.borderS) + + MouseArea { + anchors.fill: parent + cursorShape: Qt.PointingHandCursor + hoverEnabled: true + + onEntered: { + TooltipService.show(parent, modelData.name + "\n" + parent.color.toString().toUpperCase()); + } + onExited: { + TooltipService.hide(); + } + onClicked: { + root.selectedColor = modelData.color; + TooltipService.hide(); + } + } + } + } + + NDivider { + Layout.columnSpan: 17 + Layout.fillWidth: true + Layout.topMargin: Style.marginXS + Layout.bottomMargin: 0 + } + + NLabel { + Layout.columnSpan: 17 + Layout.fillWidth: true + description: I18n.tr("widgets.color-picker.palette-description") + } + + Repeater { + model: ColorList.colors + + Rectangle { + width: 24 + height: 24 + radius: Math.min(Style.iRadiusXS, width / 2) + color: modelData.color + border.color: root.selectedColor.toString() === modelData.color.toString() ? Color.mPrimary : Color.mOutline + border.width: root.selectedColor.toString() === modelData.color.toString() ? 2 : 1 + + MouseArea { + anchors.fill: parent + cursorShape: Qt.PointingHandCursor + hoverEnabled: true + + onEntered: { + TooltipService.show(parent, modelData.name + "\n" + parent.color.toString().toUpperCase(), "auto"); + } + onExited: { + TooltipService.hide(); + } + onClicked: { + root.selectedColor = modelData.color; + TooltipService.hide(); + } + } + } + } + } + } + } + } + + RowLayout { + visible: !root.liveMode + Layout.fillWidth: true + Layout.topMargin: 1 + Layout.bottomMargin: 1 + spacing: 10 + + Item { + Layout.fillWidth: true + } + + NButton { + id: cancelButton + text: I18n.tr("common.cancel") + outlined: cancelButton.hovered ? false : true + onClicked: { + root.close(); + } + } + + NButton { + text: I18n.tr("common.apply") + icon: "check" + onClicked: { + root.colorSelected(root.selectedColor); + // Delay close to prevent click propagation to elements behind the dialog + Qt.callLater(() => { + root.close(); + }); + } + } + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NColorSlider.qml b/quickshell/compat/noctalia/Widgets/NColorSlider.qml new file mode 100644 index 0000000..e2ec6b2 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NColorSlider.qml @@ -0,0 +1,238 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Shapes +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Services.UI + +Slider { + id: root + + property color fillColor: "transparent" + property var cutoutColor: Color.mSurface + property bool snapAlways: true + property real widthRatio: 0.7 + property var tooltipText + property string tooltipDirection: "auto" + property bool hovering: false + property color topColor: "white" + property color bottomColor: "black" + property bool rainbowMode: false + + readonly property real knobDiameter: Math.round((Style.baseWidgetSize * widthRatio * Style.uiScaleRatio) / 2) * 2 + readonly property real trackWidth: Math.round((knobDiameter * 0.4 * Style.uiScaleRatio) / 2) * 2 + readonly property real trackRadius: Math.min(Style.iRadiusL, trackWidth / 2) + readonly property real cutoutExtra: Math.round((Style.baseWidgetSize * 0.1 * Style.uiScaleRatio) / 2) * 2 + + orientation: Qt.Vertical + + padding: cutoutExtra / 2 + + snapMode: snapAlways ? Slider.SnapAlways : Slider.SnapOnRelease + implicitWidth: Math.max(trackWidth, knobDiameter) + + background: Item { + id: bgContainer + anchors.horizontalCenter: parent.horizontalCenter + anchors.verticalCenter: parent.verticalCenter + width: root.trackWidth + height: root.availableHeight + + LinearGradient { + id: standardLinearGradient + x1: 0 + y1: 0 + x2: 0 + y2: root.availableHeight + GradientStop { + position: 0.0 + color: root.topColor + } + GradientStop { + position: 1.0 + color: root.bottomColor + } + } + + LinearGradient { + id: rainbowLinearGradient + x1: 0 + y1: 0 + x2: 0 + y2: root.availableHeight + GradientStop { + position: 0.000 + color: "#FF0000" + } + GradientStop { + position: 0.167 + color: "#FF00FF" + } + GradientStop { + position: 0.333 + color: "#0000FF" + } + GradientStop { + position: 0.500 + color: "#00FFFF" + } + GradientStop { + position: 0.667 + color: "#00FF00" + } + GradientStop { + position: 0.833 + color: "#FFFF00" + } + GradientStop { + position: 1.000 + color: "#FF0000" + } + } + + Shape { + anchors.centerIn: parent + width: root.trackWidth + height: bgContainer.height + visible: root.trackWidth > 0 && bgContainer.height > 0 + preferredRendererType: Shape.CurveRenderer + asynchronous: true + + ShapePath { + id: trackPath + strokeColor: Qt.alpha(Color.mOutline, 0.5) + strokeWidth: Style.borderS + fillGradient: root.rainbowMode ? rainbowLinearGradient : standardLinearGradient + + readonly property real w: root.trackWidth + readonly property real h: root.availableHeight + readonly property real r: root.trackRadius + + startX: r + startY: 0 + + PathLine { + x: trackPath.w - trackPath.r + y: 0 + } + PathArc { + x: trackPath.w + y: trackPath.r + radiusX: trackPath.r + radiusY: trackPath.r + } + PathLine { + x: trackPath.w + y: trackPath.h - trackPath.r + } + PathArc { + x: trackPath.w - trackPath.r + y: trackPath.h + radiusX: trackPath.r + radiusY: trackPath.r + } + PathLine { + x: trackPath.r + y: trackPath.h + } + PathArc { + x: 0 + y: trackPath.h - trackPath.r + radiusX: trackPath.r + radiusY: trackPath.r + } + PathLine { + x: 0 + y: trackPath.r + } + PathArc { + x: trackPath.r + y: 0 + radiusX: trackPath.r + radiusY: trackPath.r + } + } + } + + // Circular cutout + Rectangle { + id: knobCutout + implicitWidth: root.knobDiameter + root.cutoutExtra + implicitHeight: root.knobDiameter + root.cutoutExtra + radius: Math.min(Style.iRadiusL, width / 2) + color: root.cutoutColor !== undefined ? root.cutoutColor : Color.mSurface + y: root.visualPosition * (root.availableHeight - root.knobDiameter) - root.cutoutExtra / 2 + anchors.horizontalCenter: parent.horizontalCenter + } + } + + handle: Item { + implicitWidth: root.knobDiameter + implicitHeight: root.knobDiameter + y: root.topPadding + root.visualPosition * (root.availableHeight - height) + anchors.horizontalCenter: parent.horizontalCenter + + Rectangle { + id: knob + implicitWidth: root.knobDiameter + implicitHeight: root.knobDiameter + radius: Math.min(Style.iRadiusL, width / 2) + color: { + if (root.rainbowMode) { + // Hue Logic: Map position (0.0 to 1.0) directly to Hue + return Qt.hsva(1 - root.visualPosition, 1, 1, 1); + } else { + // Linear Interpolation for Standard Gradients + // visualPosition 0.0 = Top, 1.0 = Bottom + var t = root.visualPosition; + var r = root.topColor.r * (1 - t) + root.bottomColor.r * t; + var g = root.topColor.g * (1 - t) + root.bottomColor.g * t; + var b = root.topColor.b * (1 - t) + root.bottomColor.b * t; + return Qt.rgba(r, g, b, 1); + } + } + + border.color: root.pressed ? Color.mHover : Color.mPrimary + border.width: Style.borderL + anchors.centerIn: parent + + Behavior on color { + ColorAnimation { + duration: Style.animationFast + } + } + } + + MouseArea { + enabled: true + anchors.fill: parent + cursorShape: Qt.PointingHandCursor + hoverEnabled: true + acceptedButtons: Qt.NoButton // Don't accept any mouse buttons - only hover + propagateComposedEvents: true + + onEntered: { + root.hovering = true; + if (root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) { + TooltipService.show(knob, root.tooltipText, root.tooltipDirection); + } + } + + onExited: { + root.hovering = false; + if (root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) { + TooltipService.hide(); + } + } + } + + // Hide tooltip when slider is pressed (anywhere on the slider) + Connections { + target: root + function onPressedChanged() { + if (root.pressed && root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) { + TooltipService.hide(); + } + } + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NComboBox.qml b/quickshell/compat/noctalia/Widgets/NComboBox.qml new file mode 100644 index 0000000..c5907a2 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NComboBox.qml @@ -0,0 +1,330 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Services.UI +import qs.compat.noctalia.Widgets + +RowLayout { + id: root + + property real minimumWidth: 200 + property real popupHeight: 180 + + property string label: "" + property string description: "" + property string tooltip: "" + property var model + property string currentKey: "" + property string placeholder: "" + property var defaultValue: undefined + property string settingsPath: "" + property real baseSize: 1.0 + + readonly property real preferredHeight: Math.round(Style.baseWidgetSize * 1.1 * root.baseSize) + readonly property var comboBox: combo + + signal selected(string key) + + spacing: Style.marginL + + // Less strict comparison with != (instead of !==) so it can properly compare int vs string (ex for FPS: 30 and "30") + readonly property bool isValueChanged: (defaultValue !== undefined) && (currentKey != defaultValue) + + readonly property string indicatorTooltip: { + if (defaultValue === undefined) + return ""; + var displayValue = ""; + if (defaultValue === "") { + // Try to find the display name for empty key in the model + var found = false; + if (root.model) { + if (Array.isArray(root.model)) { + for (var i = 0; i < root.model.length; i++) { + var item = root.model[i]; + if (item && item.key === "") { + displayValue = item.name || I18n.tr("panels.indicator.system-default"); + found = true; + break; + } + } + } else if (typeof root.model.get === 'function') { + for (var i = 0; i < root.itemCount(); i++) { + var item = root.getItem(i); + if (item && item.key === "") { + displayValue = item.name || I18n.tr("panels.indicator.system-default"); + found = true; + break; + } + } + } + } + // If not found in model, show "System Default" instead of "(empty)" + if (!found) { + displayValue = I18n.tr("panels.indicator.system-default"); + } + } else { + // Try to find the display name for the default key in the model + var found = false; + if (root.model) { + if (Array.isArray(root.model)) { + for (var i = 0; i < root.model.length; i++) { + var item = root.model[i]; + if (item && item.key === defaultValue) { + displayValue = item.name || String(defaultValue); + found = true; + break; + } + } + } else if (typeof root.model.get === 'function') { + for (var i = 0; i < root.itemCount(); i++) { + var item = root.getItem(i); + if (item && item.key === defaultValue) { + displayValue = item.name || String(defaultValue); + found = true; + break; + } + } + } + } + if (!found) { + displayValue = String(defaultValue); + } + } + return I18n.tr("panels.indicator.default-value", { + "value": displayValue + }); + } + + function itemCount() { + if (!root.model) + return 0; + if (typeof root.model.count === 'number') + return root.model.count; + if (Array.isArray(root.model)) + return root.model.length; + return 0; + } + + function getItem(index) { + if (!root.model) + return null; + if (typeof root.model.get === 'function') + return root.model.get(index); + if (Array.isArray(root.model)) + return root.model[index]; + return null; + } + + function findIndexByKey(key) { + for (var i = 0; i < itemCount(); i++) { + var item = getItem(i); + if (item && item.key === key) + return i; + } + return -1; + } + + NLabel { + label: root.label + description: root.description + showIndicator: root.isValueChanged + indicatorTooltip: root.indicatorTooltip + } + + ComboBox { + id: combo + + opacity: enabled ? 1.0 : 0.6 + Layout.margins: Style.borderS + Layout.minimumWidth: Math.round(root.minimumWidth * Style.uiScaleRatio) + Layout.preferredHeight: Math.round(root.preferredHeight * Style.uiScaleRatio) + implicitWidth: Layout.minimumWidth + model: root.model + textRole: "name" + currentIndex: root.findIndexByKey(root.currentKey) + + onActivated: { + var item = root.getItem(combo.currentIndex); + if (item && item.key !== undefined) + root.selected(item.key); + } + + Keys.onUpPressed: event => { + if (combo.popup.visible) { + if (listView.currentIndex > 0) { + listView.currentIndex--; + listView.positionViewAtIndex(listView.currentIndex, ListView.Contain); + } + event.accepted = true; + } else { + event.accepted = false; + } + } + + Keys.onDownPressed: event => { + if (combo.popup.visible) { + if (listView.currentIndex < root.itemCount() - 1) { + listView.currentIndex++; + listView.positionViewAtIndex(listView.currentIndex, ListView.Contain); + } + event.accepted = true; + } else { + event.accepted = false; + } + } + + Keys.onReturnPressed: event => { + if (combo.popup.visible) { + var item = root.getItem(listView.currentIndex); + if (item && item.key !== undefined) { + root.selected(item.key); + combo.currentIndex = listView.currentIndex; + combo.popup.close(); + } + event.accepted = true; + } else { + event.accepted = false; + } + } + + Keys.onEnterPressed: event => { + combo.Keys.returnPressed(event); + } + + background: Rectangle { + implicitWidth: Math.round(Style.baseWidgetSize * 3.75 * Style.uiScaleRatio) + implicitHeight: Math.round(root.preferredHeight * Style.uiScaleRatio) + color: Color.mSurface + border.color: combo.activeFocus ? Color.mSecondary : Color.mOutline + border.width: Style.borderS + radius: Style.iRadiusM + + Behavior on border.color { + ColorAnimation { + duration: Style.animationFast + } + } + + MouseArea { + anchors.fill: parent + hoverEnabled: true + acceptedButtons: Qt.NoButton + onEntered: { + if (root.tooltip != "") { + TooltipService.show(root, root.tooltip); + } + } + onExited: { + if (root.tooltip != "") { + TooltipService.hide(); + } + } + } + } + + contentItem: NText { + leftPadding: Style.marginL + rightPadding: combo.indicator.width + Style.marginL + pointSize: Style.fontSizeM + verticalAlignment: Text.AlignVCenter + elide: Text.ElideRight + color: combo.currentIndex >= 0 ? Color.mOnSurface : Color.mOnSurfaceVariant + text: { + if (combo.currentIndex >= 0 && combo.currentIndex < root.itemCount()) { + var item = root.getItem(combo.currentIndex); + return item ? item.name : root.placeholder; + } + return root.placeholder; + } + } + + indicator: NIcon { + x: combo.width - width - Style.marginM + y: combo.topPadding + (combo.availableHeight - height) / 2 + icon: "caret-down" + pointSize: Style.fontSizeL + } + + popup: Popup { + y: combo.height + Style.marginS + implicitWidth: combo.width + implicitHeight: Math.min(Math.round(root.popupHeight * Style.uiScaleRatio), listView.contentHeight + Style.margin2M) + padding: Style.marginM + + onOpened: { + listView.currentIndex = combo.currentIndex; + listView.positionViewAtIndex(combo.currentIndex, ListView.Beginning); + } + + contentItem: NListView { + id: listView + property var comboBox: combo + model: combo.popup.visible ? root.model : null + highlightMoveDuration: 0 + //showGradientMasks: false + + delegate: Rectangle { + id: delegateRect + required property int index + property bool isHighlighted: listView.currentIndex === index + + width: listView.availableWidth + height: delegateText.implicitHeight + Style.margin2S + radius: Style.iRadiusS + color: isHighlighted ? Color.mHover : "transparent" + + NText { + id: delegateText + anchors.fill: parent + anchors.leftMargin: Style.marginM + anchors.rightMargin: Style.marginM + verticalAlignment: Text.AlignVCenter + elide: Text.ElideRight + pointSize: Style.fontSizeM + color: delegateRect.isHighlighted ? Color.mOnHover : Color.mOnSurface + text: { + var item = root.getItem(delegateRect.index); + return item && item.name ? item.name : ""; + } + } + + MouseArea { + anchors.fill: parent + hoverEnabled: true + onContainsMouseChanged: { + if (containsMouse) { + listView.currentIndex = delegateRect.index; + } + } + onClicked: { + var item = root.getItem(delegateRect.index); + if (item && item.key !== undefined) { + root.selected(item.key); + listView.comboBox.currentIndex = delegateRect.index; + listView.comboBox.popup.close(); + } + } + } + } + } + + background: Rectangle { + color: Color.mSurfaceVariant + border.color: Color.mOutline + border.width: Style.borderS + radius: Style.iRadiusM + } + } + + Connections { + target: root + function onCurrentKeyChanged() { + combo.currentIndex = root.findIndexByKey(root.currentKey); + } + function onModelChanged() { + combo.currentIndex = root.findIndexByKey(root.currentKey); + } + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NContextMenu.qml b/quickshell/compat/noctalia/Widgets/NContextMenu.qml new file mode 100644 index 0000000..a345dfa --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NContextMenu.qml @@ -0,0 +1,182 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import qs.compat.noctalia.Commons + +/* +* NContextMenu - Popup-based context menu for use inside panels and dialogs +* +* Use this component when you need a context menu inside: +* - Settings panels +* - Dialogs +* - Repeater delegates +* - Any nested component context +* +* For bar widgets and top-level window contexts, use NPopupContextMenu instead, +* which provides better screen boundary handling and compositor integration. +* +* Usage: +* NContextMenu { +* id: contextMenu +* parent: Overlay.overlay +* model: [ +* { "label": "Action 1", "action": "action1", "icon": "icon-name" }, +* { "label": "Action 2", "action": "action2" } +* ] +* onTriggered: action => { Logger.i("MyModule", "Selected:", action) } +* } +* +* MouseArea { +* onClicked: contextMenu.openAtItem(parent, mouse.x, mouse.y) +* } +*/ +Popup { + id: root + + property var model: [] + property real itemHeight: 36 + property real itemPadding: Style.marginM + property int verticalPolicy: ScrollBar.AsNeeded + property int horizontalPolicy: ScrollBar.AsNeeded + // Optional: explicit item whose bounds the menu must stay within. + // When unset, openAtItem auto-detects the nearest clipping ancestor. + property Item constrainTo: null + property Item _detectedConstraint: null + + signal triggered(string action) + + // Filter out hidden items to avoid spacing artifacts from zero-height items + readonly property var filteredModel: { + if (!model || model.length === 0) + return []; + var filtered = []; + for (var i = 0; i < model.length; i++) { + if (model[i].visible !== false) { + filtered.push(model[i]); + } + } + return filtered; + } + + width: 180 + padding: Style.marginS + + background: Rectangle { + color: Color.mSurfaceVariant + border.color: Color.mOutline + border.width: Style.borderS + radius: Style.iRadiusM + } + + contentItem: NListView { + id: listView + implicitHeight: Math.max(contentHeight, root.itemHeight) + spacing: Style.marginXXS + interactive: contentHeight > root.height + verticalPolicy: root.verticalPolicy + horizontalPolicy: root.horizontalPolicy + reserveScrollbarSpace: false + model: root.filteredModel + + delegate: ItemDelegate { + id: menuItem + width: listView.availableWidth + height: root.itemHeight + opacity: modelData.enabled !== false ? 1.0 : 0.5 + enabled: modelData.enabled !== false + + // Store reference to the popup + property var popup: root + + background: Rectangle { + color: menuItem.hovered && menuItem.enabled ? Color.mHover : "transparent" + radius: Style.iRadiusS + + Behavior on color { + ColorAnimation { + duration: Style.animationFast + } + } + } + + contentItem: RowLayout { + spacing: Style.marginS + + // Optional icon + NIcon { + visible: modelData.icon !== undefined + icon: modelData.icon || "" + pointSize: Style.fontSizeM + color: menuItem.hovered && menuItem.enabled ? Color.mOnHover : Color.mOnSurface + Layout.leftMargin: root.itemPadding + + Behavior on color { + ColorAnimation { + duration: Style.animationFast + } + } + } + + NText { + text: modelData.label || modelData.text || "" + pointSize: Style.fontSizeM + color: menuItem.hovered && menuItem.enabled ? Color.mOnHover : Color.mOnSurface + verticalAlignment: Text.AlignVCenter + Layout.fillWidth: true + Layout.leftMargin: modelData.icon === undefined ? root.itemPadding : 0 + + Behavior on color { + ColorAnimation { + duration: Style.animationFast + } + } + } + } + + onClicked: { + if (enabled) { + popup.triggered(modelData.action || modelData.key || index.toString()); + popup.close(); + } + } + } + } + + // Helper function to open at mouse position + function openAt(x, y) { + if (root.parent) { + var menuWidth = root.width; + var itemCount = root.filteredModel.length; + var menuHeight = Math.max(itemCount * root.itemHeight + Math.max(0, itemCount - 1) * listView.spacing, root.itemHeight) + root.topPadding + root.bottomPadding; + var constraint = root.constrainTo || root._detectedConstraint; + if (constraint) { + var tl = constraint.mapToItem(root.parent, 0, 0); + x = Math.max(tl.x, Math.min(x, tl.x + constraint.width - menuWidth)); + y = Math.max(tl.y, Math.min(y, tl.y + constraint.height - menuHeight)); + } else { + x = Math.max(0, Math.min(x, root.parent.width - menuWidth)); + y = Math.max(0, Math.min(y, root.parent.height - menuHeight)); + } + } + root.x = x; + root.y = y; + root.open(); + } + + // Helper function to open at item + function openAtItem(item, mouseX, mouseY) { + if (!root.constrainTo) { + root._detectedConstraint = null; + var p = item; + while (p && p !== root.parent) { + if (p.clip && p.width > 0 && p.height > 0) { + root._detectedConstraint = p; + break; + } + p = p.parent; + } + } + var pos = item.mapToItem(root.parent, mouseX || 0, mouseY || 0); + openAt(pos.x, pos.y); + } +} diff --git a/quickshell/compat/noctalia/Widgets/NDateTimeTokens.qml b/quickshell/compat/noctalia/Widgets/NDateTimeTokens.qml new file mode 100644 index 0000000..79e1970 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NDateTimeTokens.qml @@ -0,0 +1,393 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import qs.compat.noctalia.Commons + +Rectangle { + id: root + + property date sampleDate: new Date() // Dec 25, 2023, 2:30:45.123 PM + + signal tokenClicked(string token) + + Layout.margins: Style.borderS + color: Color.mSurface + border.color: Color.mOutline + border.width: Style.borderS + radius: Style.iRadiusM + + ColumnLayout { + id: column + anchors.fill: parent + anchors.margins: Style.marginS + spacing: Style.marginS + + Flickable { + Layout.fillWidth: true + Layout.fillHeight: true + contentHeight: tokensColumn.implicitHeight + clip: true + + Column { + id: tokensColumn + width: parent.width + + Repeater { + model: [ + // Common format combinations + { + "category": "Common", + "token": "h:mm AP", + "description": I18n.tr("widgets.datetime-tokens.common-12hour-time-minutes"), + "example": "2:30 PM" + }, + { + "category": "Common", + "token": "HH:mm", + "description": I18n.tr("widgets.datetime-tokens.common-24hour-time-minutes"), + "example": "14:30" + }, + { + "category": "Common", + "token": "HH:mm:ss", + "description": I18n.tr("widgets.datetime-tokens.common-24hour-time-seconds"), + "example": "14:30:45" + }, + { + "category": "Common", + "token": "ddd MMM d", + "description": I18n.tr("widgets.datetime-tokens.common-weekday-month-day"), + "example": "Mon Dec 25" + }, + { + "category": "Common", + "token": "yyyy-MM-dd", + "description": I18n.tr("widgets.datetime-tokens.common-iso-date"), + "example": "2023-12-25" + }, + { + "category": "Common", + "token": "MM/dd/yyyy", + "description": I18n.tr("widgets.datetime-tokens.common-us-date"), + "example": "12/25/2023" + }, + { + "category": "Common", + "token": "dd.MM.yyyy", + "description": I18n.tr("widgets.datetime-tokens.common-european-date"), + "example": "25.12.2023" + }, + { + "category": "Common", + "token": "ddd, MMM dd", + "description": I18n.tr("widgets.datetime-tokens.common-weekday-date"), + "example": "Fri, Dec 12" + } // Hour tokens + , + { + "category": "Hour", + "token": "H", + "description": I18n.tr("widgets.datetime-tokens.hour-no-leading-zero"), + "example": "14" + }, + { + "category": "Hour", + "token": "HH", + "description": I18n.tr("widgets.datetime-tokens.hour-leading-zero"), + "example": "14" + } // Minute tokens + , + { + "category": "Minute", + "token": "m", + "description": I18n.tr("widgets.datetime-tokens.minute-no-leading-zero"), + "example": "30" + }, + { + "category": "Minute", + "token": "mm", + "description": I18n.tr("widgets.datetime-tokens.minute-leading-zero"), + "example": "30" + } // Second tokens + , + { + "category": "Second", + "token": "s", + "description": I18n.tr("widgets.datetime-tokens.second-no-leading-zero"), + "example": "45" + }, + { + "category": "Second", + "token": "ss", + "description": I18n.tr("widgets.datetime-tokens.second-leading-zero"), + "example": "45" + } // AM/PM tokens + , + { + "category": "AM/PM", + "token": "AP", + "description": I18n.tr("widgets.datetime-tokens.ampm-uppercase"), + "example": "PM" + }, + { + "category": "AM/PM", + "token": "ap", + "description": I18n.tr("widgets.datetime-tokens.ampm-lowercase"), + "example": "pm" + } // Timezone tokens + , + { + "category": "Timezone", + "token": "t", + "description": I18n.tr("widgets.datetime-tokens.timezone-abbreviation"), + "example": "UTC" + } // Year tokens + , + { + "category": "Year", + "token": "yy", + "description": I18n.tr("widgets.datetime-tokens.year-two-digit"), + "example": "23" + }, + { + "category": "Year", + "token": "yyyy", + "description": I18n.tr("widgets.datetime-tokens.year-four-digit"), + "example": "2023" + } // Month tokens + , + { + "category": "Month", + "token": "M", + "description": I18n.tr("widgets.datetime-tokens.month-number-no-zero"), + "example": "12" + }, + { + "category": "Month", + "token": "MM", + "description": I18n.tr("widgets.datetime-tokens.month-number-leading-zero"), + "example": "12" + }, + { + "category": "Month", + "token": "MMM", + "description": I18n.tr("widgets.datetime-tokens.month-abbreviated"), + "example": "Dec" + }, + { + "category": "Month", + "token": "MMMM", + "description": I18n.tr("widgets.datetime-tokens.month-full"), + "example": "December" + } // Day tokens + , + { + "category": "Day", + "token": "d", + "description": I18n.tr("widgets.datetime-tokens.day-no-leading-zero"), + "example": "25" + }, + { + "category": "Day", + "token": "dd", + "description": I18n.tr("widgets.datetime-tokens.day-leading-zero"), + "example": "25" + }, + { + "category": "Day", + "token": "ddd", + "description": I18n.tr("widgets.datetime-tokens.day-abbreviated"), + "example": "Mon" + }, + { + "category": "Day", + "token": "dddd", + "description": I18n.tr("widgets.datetime-tokens.day-full"), + "example": "Monday" + } + ] + + delegate: Rectangle { + id: tokenDelegate + width: tokensColumn.width + height: layout.implicitHeight + Style.marginS + radius: Style.iRadiusS + color: { + if (tokenMouseArea.containsMouse) { + return Qt.alpha(Color.mPrimary, 0.1); + } + return index % 2 === 0 ? Color.mSurfaceVariant : Qt.alpha(Color.mSurfaceVariant, 0.6); + } + + // Mouse area for the entire delegate + MouseArea { + id: tokenMouseArea + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + + onClicked: { + root.tokenClicked(modelData.token); + clickAnimation.start(); + } + } + + // Click animation + SequentialAnimation { + id: clickAnimation + PropertyAnimation { + target: tokenDelegate + property: "color" + to: Qt.alpha(Color.mPrimary, 0.3) + duration: 100 + } + PropertyAnimation { + target: tokenDelegate + property: "color" + to: tokenMouseArea.containsMouse ? Qt.alpha(Color.mPrimary, 0.1) : (index % 2 === 0 ? Color.mSurface : Color.mSurfaceVariant) + duration: 200 + } + } + + RowLayout { + id: layout + anchors.fill: parent + anchors.margins: Style.marginXS + spacing: Style.marginM + + // Category badge + Rectangle { + Layout.alignment: Qt.AlignVCenter + width: 70 + height: 22 + color: getCategoryColor(modelData.category)[0] + radius: Style.iRadiusS + opacity: tokenMouseArea.containsMouse ? 0.9 : 1.0 + + Behavior on opacity { + NumberAnimation { + duration: Style.animationFast + } + } + + NText { + anchors.centerIn: parent + text: modelData.category + color: getCategoryColor(modelData.category)[1] + pointSize: Style.fontSizeXS + } + } + + // Token - Made more prominent and clickable + Rectangle { + id: tokenButton + Layout.alignment: Qt.AlignVCenter // Added this line + width: 100 + height: 22 + color: tokenMouseArea.containsMouse ? Color.mPrimary : Color.mOnSurface + radius: Style.iRadiusS + + Behavior on color { + ColorAnimation { + duration: Style.animationFast + } + } + + NText { + anchors.centerIn: parent + text: modelData.token + color: tokenMouseArea.containsMouse ? Color.mOnPrimary : Color.mSurface + pointSize: Style.fontSizeS + font.weight: Style.fontWeightBold + + Behavior on color { + ColorAnimation { + duration: Style.animationFast + } + } + } + } + + // Description + NText { + Layout.fillWidth: true + Layout.alignment: Qt.AlignVCenter // Added this line + text: modelData.description + color: tokenMouseArea.containsMouse ? Color.mOnSurface : Color.mOnSurfaceVariant + pointSize: Style.fontSizeS + wrapMode: Text.WordWrap + + Behavior on color { + ColorAnimation { + duration: Style.animationFast + } + } + } + + // Live example + Rectangle { + Layout.alignment: Qt.AlignVCenter // Added this line + width: 90 + height: 22 + color: tokenMouseArea.containsMouse ? Color.mPrimary : Color.mOnSurfaceVariant + radius: Style.iRadiusS + border.color: tokenMouseArea.containsMouse ? Color.mPrimary : Color.mOutline + border.width: Style.borderS + + Behavior on color { + ColorAnimation { + duration: Style.animationFast + } + } + + Behavior on border.color { + ColorAnimation { + duration: Style.animationFast + } + } + + NText { + anchors.centerIn: parent + text: I18n.locale.toString(root.sampleDate, modelData.token) + color: tokenMouseArea.containsMouse ? Color.mOnPrimary : Color.mSurfaceVariant + pointSize: Style.fontSizeS + + Behavior on color { + ColorAnimation { + duration: Style.animationFast + } + } + } + } + } + } + } + } + } + } + + function getCategoryColor(category) { + switch (category) { + case "Year": + return [Color.mPrimary, Color.mOnPrimary]; + case "Month": + return [Color.mSecondary, Color.mOnSecondary]; + case "Day": + return [Color.mTertiary, Color.mOnTertiary]; + case "Hour": + return [Color.mPrimary, Color.mOnPrimary]; + case "Minute": + return [Color.mSecondary, Color.mOnSecondary]; + case "Second": + return [Color.mTertiary, Color.mOnTertiary]; + case "AM/PM": + return [Color.mError, Color.mOnError]; + case "Timezone": + return [Color.mOnSurface, Color.mSurface]; + case "Common": + return [Color.mError, Color.mOnError]; + default: + return [Color.mOnSurfaceVariant, Color.mSurfaceVariant]; + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NDivider.qml b/quickshell/compat/noctalia/Widgets/NDivider.qml new file mode 100644 index 0000000..572a90e --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NDivider.qml @@ -0,0 +1,30 @@ +import QtQuick +import Quickshell +import Quickshell.Widgets +import qs.compat.noctalia.Commons + +Rectangle { + property bool vertical: false + + width: vertical ? Style.borderS : parent.width + height: vertical ? parent.height : Style.borderS + gradient: Gradient { + orientation: vertical ? Gradient.Vertical : Gradient.Horizontal + GradientStop { + position: 0.0 + color: "transparent" + } + GradientStop { + position: 0.1 + color: Color.mOutline + } + GradientStop { + position: 0.9 + color: Color.mOutline + } + GradientStop { + position: 1.0 + color: "transparent" + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NDropShadow.qml b/quickshell/compat/noctalia/Widgets/NDropShadow.qml new file mode 100644 index 0000000..638d6c6 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NDropShadow.qml @@ -0,0 +1,31 @@ +import QtQuick +import QtQuick.Effects +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Services.Power + +// Unified shadow system +Item { + id: root + + required property var source + + property bool autoPaddingEnabled: false + property real shadowHorizontalOffset: Settings.data.general.shadowOffsetX + property real shadowVerticalOffset: Settings.data.general.shadowOffsetY + property real shadowOpacity: Style.shadowOpacity + property color shadowColor: "black" + property real shadowBlur: Style.shadowBlur + + layer.enabled: Settings.data.general.enableShadows && !PowerProfileService.noctaliaPerformanceMode + layer.effect: MultiEffect { + source: root.source + shadowEnabled: true + blurMax: Style.shadowBlurMax + shadowBlur: root.shadowBlur + shadowOpacity: root.shadowOpacity + shadowColor: root.shadowColor + shadowHorizontalOffset: root.shadowHorizontalOffset + shadowVerticalOffset: root.shadowVerticalOffset + autoPaddingEnabled: root.autoPaddingEnabled + } +} diff --git a/quickshell/compat/noctalia/Widgets/NFilePicker.qml b/quickshell/compat/noctalia/Widgets/NFilePicker.qml new file mode 100644 index 0000000..46f158b --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NFilePicker.qml @@ -0,0 +1,817 @@ +import Qt.labs.folderlistmodel +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import Quickshell +import Quickshell.Io +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Widgets + +Popup { + id: root + + // Properties + property string title: I18n.tr("widget.file-picker.title") + property string initialPath: Quickshell.env("HOME") || "/home" + property string selectionMode: "files" // "files" or "folders" + property var nameFilters: ["*"] + property bool showDirs: true + property bool showHiddenFiles: false + property bool allowMultiSelection: false + + property var selectedPaths: [] + property string currentPath: initialPath + property bool shouldResetSelection: false + + // Signals + signal accepted(var paths) + signal cancelled + + function openFilePicker() { + if (!root.currentPath) + root.currentPath = root.initialPath; + shouldResetSelection = true; + open(); + } + + function getFileIcon(fileName) { + const ext = fileName.split('.').pop().toLowerCase(); + const iconMap = { + "txt": 'filepicker-file-text', + "md": 'filepicker-file-text', + "log": 'filepicker-file-text', + "jpg": 'filepicker-photo', + "jpeg": 'filepicker-photo', + "png": 'filepicker-photo', + "gif": 'filepicker-photo', + "bmp": 'filepicker-photo', + "svg": 'filepicker-photo', + "mp4": 'filepicker-video', + "avi": 'filepicker-video', + "mkv": 'filepicker-video', + "mov": 'filepicker-video', + "mp3": 'filepicker-music', + "wav": 'filepicker-music', + "flac": 'filepicker-music', + "ogg": 'filepicker-music', + "zip": 'filepicker-archive', + "tar": 'filepicker-archive', + "gz": 'filepicker-archive', + "rar": 'filepicker-archive', + "7z": 'filepicker-archive', + "pdf": 'filepicker-text', + "doc": 'filepicker-text', + "docx": 'filepicker-text', + "xls": 'filepicker-table', + "xlsx": 'filepicker-table', + "ppt": 'filepicker-presentation', + "pptx": 'filepicker-presentation', + "html": 'filepicker-code', + "htm": 'filepicker-code', + "css": 'filepicker-code', + "js": 'filepicker-code', + "json": 'filepicker-code', + "xml": 'filepicker-code', + "exe": 'filepicker-settings', + "app": 'filepicker-settings', + "deb": 'filepicker-settings', + "rpm": 'filepicker-settings' + }; + return iconMap[ext] || 'filepicker-file'; + } + + function formatFileSize(bytes) { + if (bytes === 0) + return "0 B"; + const k = 1024, sizes = ["B", "KB", "MB", "GB", "TB"]; + const i = Math.floor(Math.log(bytes) / Math.log(k)); + return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i]; + } + + function confirmSelection() { + if (filePickerPanel.currentSelection.length === 0) + return; + root.selectedPaths = filePickerPanel.currentSelection; + root.accepted(filePickerPanel.currentSelection); + root.close(); + } + + function updateFilteredModel() { + filteredModel.clear(); + const searchText = filePickerPanel.filterText.toLowerCase(); + + for (var i = 0; i < folderModel.count; i++) { + const fileName = folderModel.get(i, "fileName"); + const filePath = folderModel.get(i, "filePath"); + const fileIsDir = folderModel.get(i, "fileIsDir"); + const fileSize = folderModel.get(i, "fileSize"); + + // Skip hidden items if showHiddenFiles is false + // This additional check ensures hidden files are properly filtered + if (!root.showHiddenFiles && fileName.startsWith(".")) { + continue; + } + + // In folder mode, hide files + if (root.selectionMode === "folders" && !fileIsDir) + continue; + if (searchText === "" || fileName.toLowerCase().includes(searchText)) { + filteredModel.append({ + "fileName": fileName, + "filePath": filePath, + "fileIsDir": fileIsDir, + "fileSize": fileSize + }); + } + } + } + + width: 900 + height: 700 + modal: true + closePolicy: Popup.CloseOnEscape + anchors.centerIn: Overlay.overlay + + background: Rectangle { + color: Color.mSurfaceVariant + radius: Style.iRadiusL + border.color: Color.mOutline + border.width: Style.borderS + } + + Rectangle { + id: filePickerPanel + anchors.fill: parent + anchors.margins: Style.marginL + color: "transparent" + + property string filterText: "" + property var currentSelection: [] + property bool viewMode: true // true = grid, false = list + property string searchText: "" + property bool showSearchBar: false + + focus: true + + Keys.onPressed: event => { + if (event.modifiers & Qt.ControlModifier && event.key === Qt.Key_F) { + filePickerPanel.showSearchBar = !filePickerPanel.showSearchBar; + if (filePickerPanel.showSearchBar) + Qt.callLater(() => searchInput.forceActiveFocus()); + event.accepted = true; + } else if (event.key === Qt.Key_Escape && filePickerPanel.showSearchBar) { + filePickerPanel.showSearchBar = false; + filePickerPanel.searchText = ""; + filePickerPanel.filterText = ""; + root.updateFilteredModel(); + event.accepted = true; + } + } + + // Function when an item is clicked, either a folder or a file since both have the same functionality, reduces repetitive code + function itemClicked(modifiers, path) { + var list = currentSelection.slice(); + const index = list.indexOf(path); + if (root.allowMultiSelection && (modifiers & Qt.ShiftModifier) && list.length > 0) { + if (index > -1) { + list.splice(index, 1); + currentSelection = list; + } else { + var i = 0; + var toggle = false; + const firstItemPath = list[0]; + while (i < filteredModel.count) { + const itemPath = filteredModel.get(i).filePath; + + // This should be called twice, when we get to the item selected and when we get to the starting item. + if (itemPath === firstItemPath || itemPath === path) { + toggle = !toggle; + } + + // Add all files between the starting item and the item selected. + if (toggle) { + if (!list.includes(itemPath)) { + list.push(itemPath); + } + } + + i++; + } + + // Add the path selected as well since it's skipped in the while loop + if (!list.includes(path)) { + list.push(path); + } + currentSelection = list; + } + } else if (root.allowMultiSelection && (modifiers & Qt.ControlModifier)) { + if (index > -1) { + list.splice(index, 1); + currentSelection = list; + } else { + list.push(path); + currentSelection = list; + } + } else { + currentSelection = [path]; + } + } + + ColumnLayout { + anchors.fill: parent + spacing: Style.marginM + + // Header + RowLayout { + Layout.fillWidth: true + spacing: Style.marginM + + NIcon { + icon: "filepicker-folder" + color: Color.mPrimary + pointSize: Style.fontSizeXXL + } + NText { + text: root.title + pointSize: Style.fontSizeXL + font.weight: Style.fontWeightBold + color: Color.mPrimary + Layout.fillWidth: true + } + + // "Select Current" button only visible in folder selection mode + NButton { + text: I18n.tr("widgets.file-picker.select-current") + icon: "filepicker-folder-current" + visible: root.selectionMode === "folders" + onClicked: { + filePickerPanel.currentSelection = [root.currentPath]; + root.confirmSelection(); + } + } + + NIconButton { + icon: "filepicker-refresh" + tooltipText: I18n.tr("common.refresh") + onClicked: { + // Force a proper refresh by resetting the folder + const currentFolder = folderModel.folder; + folderModel.folder = ""; + folderModel.folder = currentFolder; + Qt.callLater(root.updateFilteredModel); + } + } + NIconButton { + icon: "filepicker-close" + tooltipText: I18n.tr("common.close") + onClicked: { + root.cancelled(); + root.close(); + } + } + } + + NDivider { + Layout.fillWidth: true + } + + // Navigation toolbar + Rectangle { + Layout.fillWidth: true + Layout.preferredHeight: 45 + color: Color.mSurfaceVariant + radius: Style.iRadiusS + border.color: Color.mOutline + border.width: Style.borderS + + RowLayout { + anchors.left: parent.left + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + anchors.leftMargin: Style.marginS + anchors.rightMargin: Style.marginS + spacing: Style.marginS + + NIconButton { + icon: "filepicker-arrow-up" + tooltipText: I18n.tr("tooltips.up") + baseSize: Style.baseWidgetSize * 0.8 + enabled: folderModel.folder.toString() !== "file:///" + onClicked: { + const parentPath = folderModel.parentFolder.toString().replace("file://", ""); + folderModel.folder = "file://" + parentPath; + root.currentPath = parentPath; + } + } + + NIconButton { + icon: "filepicker-home" + tooltipText: I18n.tr("tooltips.home") + baseSize: Style.baseWidgetSize * 0.8 + onClicked: { + const homePath = Quickshell.env("HOME") || "/home"; + folderModel.folder = "file://" + homePath; + root.currentPath = homePath; + } + } + + NIconButton { + icon: filePickerPanel.showSearchBar ? "filepicker-x" : "filepicker-search" + tooltipText: filePickerPanel.showSearchBar ? I18n.tr("tooltips.search-close") : I18n.tr("common.search") + baseSize: Style.baseWidgetSize * 0.8 + onClicked: { + filePickerPanel.showSearchBar = !filePickerPanel.showSearchBar; + if (!filePickerPanel.showSearchBar) { + filePickerPanel.searchText = ""; + filePickerPanel.filterText = ""; + root.updateFilteredModel(); + } + } + } + + NTextInput { + id: locationInput + text: root.currentPath + placeholderText: I18n.tr("placeholders.enter-path") + Layout.fillWidth: true + + visible: !filePickerPanel.showSearchBar + enabled: !filePickerPanel.showSearchBar + + onEditingFinished: { + const newPath = text.trim(); + if (newPath !== "" && newPath !== root.currentPath) { + folderModel.folder = "file://" + newPath; + root.currentPath = newPath; + } else { + text = root.currentPath; + } + } + Connections { + target: root + function onCurrentPathChanged() { + if (!locationInput.activeFocus) + locationInput.text = root.currentPath; + } + } + } + + // Search bar + NTextInput { + id: searchInput + inputIconName: "search" + placeholderText: I18n.tr("placeholders.search") + Layout.fillWidth: true + + visible: filePickerPanel.showSearchBar + enabled: filePickerPanel.showSearchBar + + text: filePickerPanel.searchText + onTextChanged: { + filePickerPanel.searchText = text; + filePickerPanel.filterText = text; + root.updateFilteredModel(); + } + Keys.onEscapePressed: { + filePickerPanel.showSearchBar = false; + filePickerPanel.searchText = ""; + filePickerPanel.filterText = ""; + root.updateFilteredModel(); + } + } + + NIconButton { + icon: filePickerPanel.viewMode ? "filepicker-list" : "filepicker-layout-grid" + tooltipText: filePickerPanel.viewMode ? I18n.tr("tooltips.list-view") : I18n.tr("tooltips.grid-view") + baseSize: Style.baseWidgetSize * 0.8 + onClicked: filePickerPanel.viewMode = !filePickerPanel.viewMode + } + NIconButton { + icon: root.showHiddenFiles ? "filepicker-eye-off" : "filepicker-eye" + tooltipText: root.showHiddenFiles ? I18n.tr("tooltips.hidden-files-hide") : I18n.tr("tooltips.hidden-files-hide") + baseSize: Style.baseWidgetSize * 0.8 + onClicked: { + root.showHiddenFiles = !root.showHiddenFiles; + // Force model refresh by resetting the folder + const currentFolder = folderModel.folder; + folderModel.folder = ""; + folderModel.folder = currentFolder; + Qt.callLater(root.updateFilteredModel); + } + } + } + } + + // File list area + Rectangle { + Layout.fillWidth: true + Layout.fillHeight: true + color: Color.mSurface + radius: Style.iRadiusM + border.color: Color.mOutline + border.width: Style.borderS + + FolderListModel { + id: folderModel + folder: "file://" + root.currentPath + // Use wildcard filters including hidden files when showHiddenFiles is true + nameFilters: root.showHiddenFiles ? ["*", ".*"] : root.nameFilters + showDirs: root.showDirs + showHidden: true // Always true, we'll filter in updateFilteredModel + showDotAndDotDot: false + sortField: FolderListModel.Name + sortReversed: false + + onFolderChanged: { + root.currentPath = folder.toString().replace("file://", ""); + filePickerPanel.currentSelection = []; + Qt.callLater(root.updateFilteredModel); + } + + onStatusChanged: { + if (status === FolderListModel.Error) { + if (root.currentPath !== Quickshell.env("HOME")) { + folder = "file://" + Quickshell.env("HOME"); + root.currentPath = Quickshell.env("HOME"); + } + } else if (status === FolderListModel.Ready) { + root.updateFilteredModel(); + } + } + } + + // Update nameFilters when showHiddenFiles changes + Connections { + target: root + function onShowHiddenFilesChanged() { + folderModel.nameFilters = root.showHiddenFiles ? ["*", ".*"] : root.nameFilters; + } + } + + ListModel { + id: filteredModel + } + + // Grid view + NGridView { + id: gridView + anchors.fill: parent + anchors.margins: Style.marginM + model: filteredModel + visible: filePickerPanel.viewMode + reuseItems: true + gradientColor: Color.mSurface + + property int columns: Math.max(1, Math.floor(availableWidth / 120)) + property int itemSize: Math.floor((availableWidth - leftMargin - rightMargin - (columns * Style.marginS)) / columns) + + cellWidth: Math.floor((availableWidth - leftMargin - rightMargin) / columns) + cellHeight: Math.floor(itemSize * 0.8) + Style.marginXS + Style.fontSizeS + Style.marginM + + leftMargin: Style.marginS + rightMargin: Style.marginS + topMargin: Style.marginS + bottomMargin: Style.marginS + + delegate: Rectangle { + id: gridItem + width: gridView.itemSize + height: gridView.cellHeight + color: "transparent" + radius: Style.iRadiusM + + property bool isSelected: filePickerPanel.currentSelection.includes(model.filePath) + + Rectangle { + anchors.fill: parent + color: "transparent" + radius: parent.radius + border.color: isSelected ? Color.mSecondary : Color.mSurface + border.width: Style.borderL + Behavior on color { + ColorAnimation { + duration: Style.animationFast + } + } + } + + Rectangle { + anchors.fill: parent + color: (mouseArea.containsMouse && !isSelected) ? Color.mHover : "transparent" + radius: parent.radius + border.color: (mouseArea.containsMouse && !isSelected) ? Color.mHover : "transparent" + border.width: Style.borderS + Behavior on color { + ColorAnimation { + duration: Style.animationFast + } + } + Behavior on border.color { + ColorAnimation { + duration: Style.animationFast + } + } + } + + ColumnLayout { + anchors.fill: parent + anchors.margins: Style.marginS + spacing: Style.marginXS + + Rectangle { + id: iconContainer + Layout.fillWidth: true + Layout.preferredHeight: Math.round(gridView.itemSize * 0.67) + color: "transparent" + + property bool isImage: { + if (model.fileIsDir) + return false; + const ext = model.fileName.split('.').pop().toLowerCase(); + return ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg', 'ico'].includes(ext); + } + + Image { + id: thumbnail + anchors.fill: parent + anchors.margins: Style.marginXS + source: iconContainer.isImage ? "file://" + model.filePath : "" + fillMode: Image.PreserveAspectFit + visible: iconContainer.isImage && status === Image.Ready + smooth: false + cache: true + asynchronous: true + sourceSize.width: 120 + sourceSize.height: 120 + onStatusChanged: { + if (status === Image.Error) + visible = false; + } + + Rectangle { + anchors.fill: parent + color: Color.mSurfaceVariant + radius: Style.iRadiusS + visible: thumbnail.status === Image.Loading + NIcon { + icon: "filepicker-photo" + pointSize: Style.fontSizeL + color: Color.mOnSurfaceVariant + anchors.centerIn: parent + } + } + } + + NIcon { + icon: model.fileIsDir ? "filepicker-folder" : root.getFileIcon(model.fileName) + pointSize: Style.fontSizeXXL * 2 + color: { + if (isSelected) + return Color.mSecondary; + else if (mouseArea.containsMouse) + return Color.mOnHover; + else + return model.fileIsDir ? Color.mPrimary : Color.mOnSurfaceVariant; + } + anchors.centerIn: parent + visible: !iconContainer.isImage || thumbnail.status !== Image.Ready + } + + Rectangle { + anchors.top: parent.top + anchors.right: parent.right + anchors.margins: Style.marginS + width: 24 + height: 24 + radius: Math.min(Style.iRadiusL, width / 2) + color: Color.mSecondary + border.color: Color.mOutline + border.width: Style.borderS + visible: isSelected + NIcon { + icon: "filepicker-check" + pointSize: Style.fontSizeS + color: Color.mOnSecondary + anchors.centerIn: parent + } + } + } + + NText { + text: model.fileName + color: { + if (isSelected) + return Color.mSecondary; + else if (mouseArea.containsMouse) + return Color.mOnHover; + else + return Color.mOnSurfaceVariant; + } + pointSize: Style.fontSizeS + font.weight: isSelected ? Style.fontWeightBold : Style.fontWeightRegular + Layout.fillWidth: true + horizontalAlignment: Text.AlignHCenter + wrapMode: Text.WrapAnywhere + elide: Text.ElideRight + maximumLineCount: 2 + } + } + + MouseArea { + id: mouseArea + anchors.fill: parent + hoverEnabled: true + acceptedButtons: Qt.LeftButton | Qt.RightButton + + onClicked: mouse => { + if (mouse.button === Qt.LeftButton) { + if (model.fileIsDir) { + // In folder mode, single click selects the folder + if (root.selectionMode === "folders") { + filePickerPanel.itemClicked(mouse.modifiers, model.filePath); + } + // In file mode, single click on folder does nothing (must double-click to enter) + } else { + // Single click on file selects it (only in file mode) + if (root.selectionMode === "files") { + filePickerPanel.itemClicked(mouse.modifiers, model.filePath); + } + } + } + } + + onDoubleClicked: mouse => { + if (mouse.button === Qt.LeftButton) { + if (model.fileIsDir) { + // Double-click on folder always navigates into it + folderModel.folder = "file://" + model.filePath; + root.currentPath = model.filePath; + } else { + // Double-click on file selects and confirms (only in file mode) + if (root.selectionMode === "files") { + filePickerPanel.currentSelection = [model.filePath]; + root.confirmSelection(); + } + } + } + } + } + } + } + + // List view + NListView { + id: listView + anchors.fill: parent + anchors.margins: Style.marginS + model: filteredModel + visible: !filePickerPanel.viewMode + gradientColor: Color.mSurface + + delegate: Rectangle { + id: listItem + width: listView.width + height: 40 + color: { + if (filePickerPanel.currentSelection.includes(model.filePath)) + return Color.mSecondary; + if (mouseArea.containsMouse) + return Color.mHover; + return "transparent"; + } + radius: Style.iRadiusS + Behavior on color { + ColorAnimation { + duration: Style.animationFast + } + } + + RowLayout { + anchors.fill: parent + anchors.leftMargin: Style.marginM + anchors.rightMargin: Style.marginM + spacing: Style.marginM + + NIcon { + icon: model.fileIsDir ? "filepicker-folder" : root.getFileIcon(model.fileName) + pointSize: Style.fontSizeL + color: model.fileIsDir ? (filePickerPanel.currentSelection.includes(model.filePath) ? Color.mOnSecondary : Color.mPrimary) : Color.mOnSurfaceVariant + } + + NText { + text: model.fileName + color: filePickerPanel.currentSelection.includes(model.filePath) ? Color.mOnSecondary : Color.mOnSurface + pointSize: Style.fontSizeM + font.weight: filePickerPanel.currentSelection.includes(model.filePath) ? Style.fontWeightBold : Style.fontWeightRegular + Layout.fillWidth: true + elide: Text.ElideRight + } + + NText { + text: model.fileIsDir ? "" : root.formatFileSize(model.fileSize) + color: filePickerPanel.currentSelection.includes(model.filePath) ? Color.mOnSecondary : Color.mOnSurfaceVariant + pointSize: Style.fontSizeS + visible: !model.fileIsDir + Layout.preferredWidth: implicitWidth + } + } + + MouseArea { + id: mouseArea + anchors.fill: parent + hoverEnabled: true + acceptedButtons: Qt.LeftButton | Qt.RightButton + + onClicked: mouse => { + if (mouse.button === Qt.LeftButton) { + if (model.fileIsDir) { + // In folder mode, single click selects the folder + if (root.selectionMode === "folders") { + filePickerPanel.itemClicked(mouse.modifiers, model.filePath); + } + // In file mode, single click on folder does nothing (must double-click to enter) + } else { + // Single click on file selects it (only in file mode) + if (root.selectionMode === "files") { + filePickerPanel.itemClicked(mouse.modifiers, model.filePath); + } + } + } + } + + onDoubleClicked: mouse => { + if (mouse.button === Qt.LeftButton) { + if (model.fileIsDir) { + // Double-click on folder always navigates into it + folderModel.folder = "file://" + model.filePath; + root.currentPath = model.filePath; + } else { + // Double-click on file selects and confirms (only in file mode) + if (root.selectionMode === "files") { + filePickerPanel.currentSelection = [model.filePath]; + root.confirmSelection(); + } + } + } + } + } + } + } + } + + // Footer + RowLayout { + Layout.fillWidth: true + spacing: Style.marginM + + NText { + text: { + if (filePickerPanel.searchText.length > 0) { + return "Searching for: \"" + filePickerPanel.searchText + "\" (" + filteredModel.count + " matches)"; + } else if (filePickerPanel.currentSelection.length > 0) { + const selectedName = filePickerPanel.currentSelection[0].split('/').pop(); + return I18n.tr("widgets.file-picker.selected") + " " + selectedName; + } else { + return filteredModel.count + " " + (filteredModel.count === 1 ? I18n.tr("widgets.file-picker.item") : I18n.tr("widgets.file-picker.items")); + } + } + color: filePickerPanel.searchText.length > 0 ? Color.mPrimary : Color.mOnSurfaceVariant + pointSize: Style.fontSizeS + Layout.fillWidth: true + } + + NButton { + text: I18n.tr("common.cancel") + outlined: true + onClicked: { + root.cancelled(); + root.close(); + } + } + + NButton { + text: root.selectionMode === "folders" ? I18n.tr("widgets.file-picker.select-folder") : I18n.tr("widgets.file-picker.select-file") + icon: "filepicker-check" + enabled: filePickerPanel.currentSelection.length > 0 + onClicked: root.confirmSelection() + } + } + } + + Connections { + target: root + function onShouldResetSelectionChanged() { + if (root.shouldResetSelection) { + filePickerPanel.currentSelection = []; + root.shouldResetSelection = false; + } + } + } + + Component.onCompleted: { + if (!root.currentPath) + root.currentPath = root.initialPath; + folderModel.folder = "file://" + root.currentPath; + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NGraph.qml b/quickshell/compat/noctalia/Widgets/NGraph.qml new file mode 100644 index 0000000..cc24fce --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NGraph.qml @@ -0,0 +1,234 @@ +import QtQuick +import Quickshell +import qs.compat.noctalia.Commons + +Item { + id: root + clip: true + + // Primary line + property var values: [] + property color color: Color.mPrimary + + // Optional secondary line + property var values2: [] + property color color2: Color.mError + + // Range settings for primary line + property real minValue: 0 + property real maxValue: 100 + + // Range settings for secondary line (defaults to primary range) + property real minValue2: minValue + property real maxValue2: maxValue + + // Style settings + property real strokeWidth: 1 + property bool fill: true + property real fillOpacity: 0.15 + property real antialiasing: 0.5 + + // Smooth scrolling interval (how often data updates) + property int updateInterval: 1000 + + // Animate scale changes (for network graphs with dynamic max) + property bool animateScale: false + + // Vertical padding (percentage of range) to keep values from touching edges + readonly property real curvePadding: 0.12 + + readonly property bool hasData: values.length >= 4 + readonly property bool hasData2: values2.length >= 4 + + // Scale animation state + property real _targetMax1: maxValue + property real _targetMax2: maxValue2 + property real _animMax1: maxValue + property real _animMax2: maxValue2 + + onMaxValueChanged: { + _targetMax1 = maxValue; + if (animateScale && _ready1) { + _scaleTimer.start(); + } else { + _animMax1 = maxValue; + } + } + + onMaxValue2Changed: { + _targetMax2 = maxValue2; + if (animateScale && _ready2) { + _scaleTimer.start(); + } else { + _animMax2 = maxValue2; + } + } + + // Effective max values (animated or direct) + readonly property real _effectiveMax1: animateScale ? _animMax1 : maxValue + readonly property real _effectiveMax2: animateScale ? _animMax2 : maxValue2 + + // Scroll state (driven by NumberAnimation) + property real _t1: 1.0 + property bool _ready1: false + property real _pred1: 0 + + property real _t2: 1.0 + property bool _ready2: false + property real _pred2: 0 + + // Frame-accurate scroll animations tied to Qt's render loop + NumberAnimation { + id: _scrollAnim1 + target: root + property: "_t1" + from: 0 + to: 1 + duration: root.updateInterval + } + + NumberAnimation { + id: _scrollAnim2 + target: root + property: "_t2" + from: 0 + to: 1 + duration: root.updateInterval + } + + onValuesChanged: { + if (values.length < 4) + return; + + const last = values[values.length - 1]; + const prev = values[values.length - 2]; + _pred1 = Math.max(minValue, last + (last - prev) * 0.5); + + if (!_ready1) + _ready1 = true; + _scrollAnim1.restart(); + } + + onValues2Changed: { + if (values2.length < 4) + return; + + const last = values2[values2.length - 1]; + const prev = values2[values2.length - 2]; + _pred2 = Math.max(minValue2, last + (last - prev) * 0.5); + + if (!_ready2) + _ready2 = true; + _scrollAnim2.restart(); + } + + // Scale animation timer (only needed for animateScale mode) + Timer { + id: _scaleTimer + interval: 16 + repeat: true + + onTriggered: { + const scaleLerp = 0.15; + const threshold = 0.5; + let stillAnimating = false; + + if (Math.abs(root._animMax1 - root._targetMax1) > threshold) { + root._animMax1 += (root._targetMax1 - root._animMax1) * scaleLerp; + stillAnimating = true; + } else if (root._animMax1 !== root._targetMax1) { + root._animMax1 = root._targetMax1; + } + + if (Math.abs(root._animMax2 - root._targetMax2) > threshold) { + root._animMax2 += (root._targetMax2 - root._animMax2) * scaleLerp; + stillAnimating = true; + } else if (root._animMax2 !== root._targetMax2) { + root._animMax2 = root._targetMax2; + } + + if (!stillAnimating) + stop(); + } + } + + // Normalize a value to [0, 1] with padding applied + function _normalize(val, minVal, maxVal) { + let range = maxVal - minVal; + if (range <= 0) + return 0.5; + let padding = range * curvePadding; + let paddedMin = minVal - padding; + let paddedRange = (maxVal + padding) - paddedMin; + return Math.max(0, Math.min(1, (val - paddedMin) / paddedRange)); + } + + // Data texture built from Rectangles instead of Canvas. + // Each Rectangle is one data point, color-coded with normalized values. + // R channel = primary, G channel = secondary. + Item { + id: _dataRow + width: Math.max(root.values.length + 1, root.values2.length + 1, 4) + height: 1 + + Repeater { + model: _dataRow.width + + Rectangle { + required property int index + x: index + width: 1 + height: 1 + color: { + let r = 0, g = 0; + let n1 = root.values.length; + let n2 = root.values2.length; + let eMax1 = root._effectiveMax1; + let eMax2 = root._effectiveMax2; + + if (index < n1) + r = root._normalize(root.values[index], root.minValue, eMax1); + else if (n1 > 0) + r = root._normalize(root._pred1, root.minValue, eMax1); + + if (index < n2) + g = root._normalize(root.values2[index], root.minValue2, eMax2); + else if (n2 > 0) + g = root._normalize(root._pred2, root.minValue2, eMax2); + + return Qt.rgba(r, g, 0, 1); + } + } + } + } + + ShaderEffectSource { + id: _dataTex + sourceItem: _dataRow + textureSize: Qt.size(_dataRow.width, 1) + live: true + smooth: false + hideSource: true + } + + ShaderEffect { + anchors.fill: parent + visible: (root.hasData || root.hasData2) && width > 0 && height > 0 + + property variant dataSource: _dataTex + property color lineColor1: root.color + property color lineColor2: root.color2 + property real count1: root.values.length + property real count2: root.values2.length + property real scroll1: root._t1 + property real scroll2: root._t2 + property real lineWidth: root.strokeWidth + property real graphFillOpacity: root.fill ? root.fillOpacity : 0.0 + property real texWidth: _dataRow.width + property real resY: height + property real aaSize: root.antialiasing + + fragmentShader: Qt.resolvedUrl(Quickshell.shellDir + "/Shaders/qsb/graph.frag.qsb") + blending: true + } +} diff --git a/quickshell/compat/noctalia/Widgets/NGridView.qml b/quickshell/compat/noctalia/Widgets/NGridView.qml new file mode 100644 index 0000000..d1ecb33 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NGridView.qml @@ -0,0 +1,430 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Templates as T +import qs.compat.noctalia.Commons + +Item { + id: root + + // Signal for key press events when keyNavigationEnabled is true + signal keyPressed(var event) + + property color handleColor: Qt.alpha(Color.mHover, 0.8) + property color handleHoverColor: handleColor + property color handlePressedColor: handleColor + property color trackColor: "transparent" + property real handleWidth: 6 + property real handleRadius: Style.iRadiusM + property int verticalPolicy: ScrollBar.AsNeeded + property int horizontalPolicy: ScrollBar.AlwaysOff + readonly property bool verticalScrollBarActive: { + if (gridView.ScrollBar.vertical.policy === ScrollBar.AlwaysOff) + return false; + return gridView.contentHeight > gridView.height; + } + readonly property bool contentOverflows: gridView.contentHeight > gridView.height + + // Gradient properties + property bool showGradientMasks: true + property color gradientColor: Color.mSurfaceVariant + property int gradientHeight: 16 + property bool reserveScrollbarSpace: true + + // Keep scrollbars visible whenever overflow exists (without forcing visibility when not scrollable) + property bool showScrollbarWhenScrollable: Settings.data.ui.scrollbarAlwaysVisible + + // Available width for content (excludes scrollbar space when reserveScrollbarSpace is true) + // Note: Always reserves space when enabled to avoid binding loops with cellWidth calculations + readonly property real availableWidth: width - (reserveScrollbarSpace ? handleWidth + Style.marginXS : 0) + + // Expose activeFocus from internal gridView + readonly property bool hasActiveFocus: gridView.activeFocus + + // Forward GridView properties + property alias model: gridView.model + property alias delegate: gridView.delegate + property alias cellWidth: gridView.cellWidth + property alias cellHeight: gridView.cellHeight + property alias leftMargin: gridView.leftMargin + property alias rightMargin: gridView.rightMargin + property alias topMargin: gridView.topMargin + property alias bottomMargin: gridView.bottomMargin + property alias currentIndex: gridView.currentIndex + property alias count: gridView.count + property alias contentHeight: gridView.contentHeight + property alias contentWidth: gridView.contentWidth + property alias contentY: gridView.contentY + property alias contentX: gridView.contentX + property alias currentItem: gridView.currentItem + property alias highlightItem: gridView.highlightItem + property alias highlightFollowsCurrentItem: gridView.highlightFollowsCurrentItem + property alias preferredHighlightBegin: gridView.preferredHighlightBegin + property alias preferredHighlightEnd: gridView.preferredHighlightEnd + property alias highlightRangeMode: gridView.highlightRangeMode + property alias snapMode: gridView.snapMode + property alias keyNavigationEnabled: gridView.keyNavigationEnabled + property alias keyNavigationWraps: gridView.keyNavigationWraps + property alias cacheBuffer: gridView.cacheBuffer + property alias displayMarginBeginning: gridView.displayMarginBeginning + property alias displayMarginEnd: gridView.displayMarginEnd + property alias layoutDirection: gridView.layoutDirection + property alias effectiveLayoutDirection: gridView.effectiveLayoutDirection + property alias flow: gridView.flow + property alias boundsBehavior: gridView.boundsBehavior + property alias flickableDirection: gridView.flickableDirection + property alias interactive: gridView.interactive + property alias moving: gridView.moving + property alias flicking: gridView.flicking + property alias dragging: gridView.dragging + property alias horizontalVelocity: gridView.horizontalVelocity + property alias verticalVelocity: gridView.verticalVelocity + property alias reuseItems: gridView.reuseItems + + // Animate items when the model is reordered (e.g. ListModel.move()) + property bool animateMovement: false + + // Scroll speed multiplier for mouse wheel (1.0 = default, higher = faster) + property real wheelScrollMultiplier: 2.0 + property int smoothWheelAnimationDuration: Style.animationNormal + property real _wheelTargetY: 0 + + function clampScrollY(value) { + return Math.max(0, Math.min(value, gridView.contentHeight - gridView.height)); + } + + function applyWheelScroll(delta) { + if (!root.contentOverflows) + return; + + const step = delta * root.wheelScrollMultiplier; + + if (!Settings.data.general.smoothScrollEnabled || Settings.data.general.animationDisabled) { + gridView.contentY = root.clampScrollY(gridView.contentY - step); + root._wheelTargetY = gridView.contentY; + return; + } + + if (!wheelScrollAnimation.running) + root._wheelTargetY = gridView.contentY; + + root._wheelTargetY = root.clampScrollY(root._wheelTargetY - step); + wheelScrollAnimation.to = root._wheelTargetY; + wheelScrollAnimation.restart(); + } + + function animateToContentY(targetY) { + const clampedY = root.clampScrollY(targetY); + + if (!Settings.data.general.smoothScrollEnabled || Settings.data.general.animationDisabled || gridView.dragging || gridView.flicking) { + gridView.contentY = clampedY; + root._wheelTargetY = clampedY; + return; + } + + root._wheelTargetY = clampedY; + wheelScrollAnimation.to = clampedY; + wheelScrollAnimation.restart(); + } + + // Track selection index for gradient visibility (set externally) + property int trackedSelectionIndex: -1 + + // Check if selection is on first visible row + readonly property bool selectionOnFirstVisibleRow: { + if (trackedSelectionIndex < 0 || cellHeight <= 0 || cellWidth <= 0) + return false; + + // Calculate columns per row + var cols = Math.floor(gridView.width / cellWidth); + if (cols <= 0) + cols = 1; + + // Calculate the row of the selection + var selectionRow = Math.round(trackedSelectionIndex / cols); + + // Calculate the first visible row + var firstVisibleRow = Math.round(gridView.contentY / cellHeight); + + return selectionRow === firstVisibleRow; + } + + // Check if selection is on last visible row + readonly property bool selectionOnLastVisibleRow: { + if (trackedSelectionIndex < 0 || cellHeight <= 0 || cellWidth <= 0) + return false; + + // Calculate columns per row + var cols = Math.floor(gridView.width / cellWidth); + if (cols <= 0) + cols = 1; + + // Calculate the row of the selection + var selectionRow = Math.round(trackedSelectionIndex / cols); + + // Calculate the last visible row (might be partially visible) + var lastVisibleRow = Math.round((gridView.contentY + gridView.height - 1) / cellHeight); + + return selectionRow === lastVisibleRow; + } + + // Forward GridView methods + function positionViewAtIndex(index, mode) { + const shouldAnimate = mode === GridView.Contain; + if (!shouldAnimate) { + gridView.positionViewAtIndex(index, mode); + root._wheelTargetY = gridView.contentY; + return; + } + + const previousY = gridView.contentY; + gridView.positionViewAtIndex(index, mode); + const targetY = root.clampScrollY(gridView.contentY); + + if (Math.abs(targetY - previousY) < 0.5) { + root._wheelTargetY = targetY; + return; + } + + gridView.contentY = previousY; + root._wheelTargetY = previousY; + root.animateToContentY(targetY); + } + + function positionViewAtBeginning() { + gridView.positionViewAtBeginning(); + } + + function positionViewAtEnd() { + gridView.positionViewAtEnd(); + } + + function forceLayout() { + gridView.forceLayout(); + } + + function forceActiveFocus() { + gridView.forceActiveFocus(); + } + + function cancelFlick() { + gridView.cancelFlick(); + } + + function flick(xVelocity, yVelocity) { + gridView.flick(xVelocity, yVelocity); + } + + function incrementCurrentIndex() { + gridView.incrementCurrentIndex(); + } + + function decrementCurrentIndex() { + gridView.decrementCurrentIndex(); + } + + function indexAt(x, y) { + return gridView.indexAt(x, y); + } + + function itemAt(x, y) { + return gridView.itemAt(x, y); + } + + function itemAtIndex(index) { + return gridView.itemAtIndex(index); + } + + function moveCurrentIndexUp() { + gridView.moveCurrentIndexUp(); + } + + function moveCurrentIndexDown() { + gridView.moveCurrentIndexDown(); + } + + function moveCurrentIndexLeft() { + gridView.moveCurrentIndexLeft(); + } + + function moveCurrentIndexRight() { + gridView.moveCurrentIndexRight(); + } + + // Set reasonable implicit sizes for Layout usage + implicitWidth: 200 + implicitHeight: 200 + + Component.onCompleted: { + _wheelTargetY = gridView.contentY; + createGradients(); + } + + // Dynamically create gradient overlays + function createGradients() { + if (!showGradientMasks) + return; + + Qt.createQmlObject(` + import QtQuick + import qs.compat.noctalia.Commons + Rectangle { + x: 0 + y: 0 + width: root.availableWidth + height: root.gradientHeight + z: 1 + visible: root.showGradientMasks && root.contentOverflows + opacity: (gridView.contentY <= 1 || root.selectionOnFirstVisibleRow) ? 0 : 1 + Behavior on opacity { + NumberAnimation { duration: Style.animationFast; easing.type: Easing.InOutQuad } + } + gradient: Gradient { + GradientStop { position: 0.0; color: root.gradientColor } + GradientStop { position: 1.0; color: "transparent" } + } + } + `, root, "topGradient"); + + Qt.createQmlObject(` + import QtQuick + import qs.compat.noctalia.Commons + Rectangle { + x: 0 + anchors.bottom: parent.bottom + anchors.bottomMargin: -1 + width: root.availableWidth + height: root.gradientHeight + 1 + z: 1 + visible: root.showGradientMasks && root.contentOverflows + opacity: ((gridView.contentY + gridView.height >= gridView.contentHeight - 1) || root.selectionOnLastVisibleRow) ? 0 : 1 + Behavior on opacity { + NumberAnimation { duration: Style.animationFast; easing.type: Easing.InOutQuad } + } + gradient: Gradient { + GradientStop { position: 0.0; color: "transparent" } + GradientStop { position: 1.0; color: root.gradientColor } + } + } + `, root, "bottomGradient"); + } + + GridView { + id: gridView + anchors.fill: parent + anchors.rightMargin: root.reserveScrollbarSpace ? root.handleWidth + Style.marginXS : 0 + + move: root.animateMovement ? moveTransitionImpl : null + displaced: root.animateMovement ? displacedTransitionImpl : null + + Transition { + id: moveTransitionImpl + NumberAnimation { + properties: "x,y" + duration: Style.animationNormal + easing.type: Easing.InOutQuad + } + } + Transition { + id: displacedTransitionImpl + NumberAnimation { + properties: "x,y" + duration: Style.animationNormal + easing.type: Easing.InOutQuad + } + } + + // Enable clipping to keep content within bounds + clip: true + + // Enable flickable for smooth scrolling + boundsBehavior: Flickable.StopAtBounds + + NumberAnimation { + id: wheelScrollAnimation + target: gridView + property: "contentY" + duration: root.smoothWheelAnimationDuration + easing.type: Easing.OutCubic + } + + onDraggingChanged: { + if (dragging) { + wheelScrollAnimation.stop(); + root._wheelTargetY = contentY; + } + } + + onFlickingChanged: { + if (flicking) { + wheelScrollAnimation.stop(); + root._wheelTargetY = contentY; + } + } + + onContentHeightChanged: root._wheelTargetY = root.clampScrollY(root._wheelTargetY) + onHeightChanged: root._wheelTargetY = root.clampScrollY(root._wheelTargetY) + + // Focus handling depends on keyNavigationEnabled + focus: keyNavigationEnabled + activeFocusOnTab: keyNavigationEnabled + + // Emit keyPressed signal for custom key handling + Keys.onPressed: event => { + if (keyNavigationEnabled) { + root.keyPressed(event); + } + } + + WheelHandler { + enabled: root.wheelScrollMultiplier !== 1.0 + acceptedDevices: PointerDevice.Mouse | PointerDevice.TouchPad + onWheel: event => { + const delta = event.pixelDelta.y !== 0 ? event.pixelDelta.y : event.angleDelta.y / 2; + root.applyWheelScroll(delta); + event.accepted = true; + } + } + + ScrollBar.vertical: ScrollBar { + parent: root + x: root.mirrored ? 0 : root.width - width + y: 0 + height: root.height + policy: root.verticalPolicy + + contentItem: Rectangle { + implicitWidth: root.handleWidth + implicitHeight: 100 + radius: root.handleRadius + color: parent.pressed ? root.handlePressedColor : parent.hovered ? root.handleHoverColor : root.handleColor + opacity: parent.policy === ScrollBar.AlwaysOn ? 1.0 : root.verticalScrollBarActive ? ((root.showScrollbarWhenScrollable || parent.active) ? 1.0 : 0.0) : 0.0 + + Behavior on opacity { + NumberAnimation { + duration: Style.animationFast + } + } + + Behavior on color { + ColorAnimation { + duration: Style.animationFast + } + } + } + + background: Rectangle { + implicitWidth: root.handleWidth + implicitHeight: 100 + color: root.trackColor + opacity: parent.policy === ScrollBar.AlwaysOn ? 0.3 : root.verticalScrollBarActive ? ((root.showScrollbarWhenScrollable || parent.active) ? 0.3 : 0.0) : 0.0 + radius: root.handleRadius / 2 + + Behavior on opacity { + NumberAnimation { + duration: Style.animationFast + } + } + } + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NHeader.qml b/quickshell/compat/noctalia/Widgets/NHeader.qml new file mode 100644 index 0000000..79c6a64 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NHeader.qml @@ -0,0 +1,34 @@ +import QtQuick +import QtQuick.Layouts +import qs.compat.noctalia.Commons + +ColumnLayout { + id: root + + property string label: "" + property string description: "" + property bool enableDescriptionRichText: false + + opacity: enabled ? 1.0 : 0.6 + spacing: Style.marginXXS + Layout.fillWidth: true + Layout.bottomMargin: Style.marginM + + NText { + text: root.label + pointSize: Style.fontSizeXL + font.weight: Style.fontWeightSemiBold + color: Color.mPrimary + visible: root.label !== "" + } + + NText { + text: root.description + pointSize: Style.fontSizeM + color: Color.mOnSurfaceVariant + wrapMode: Text.WordWrap + Layout.fillWidth: true + visible: root.description !== "" + richTextEnabled: root.enableDescriptionRichText + } +} diff --git a/quickshell/compat/noctalia/Widgets/NIcon.qml b/quickshell/compat/noctalia/Widgets/NIcon.qml new file mode 100644 index 0000000..7b9e915 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NIcon.qml @@ -0,0 +1,30 @@ +import QtQuick +import QtQuick.Layouts +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Widgets + +Text { + id: root + + property string icon: Icons.defaultIcon + property real pointSize: Style.fontSizeL + property bool applyUiScale: true + + visible: (icon !== undefined) && (icon !== "") + text: { + if ((icon === undefined) || (icon === "")) { + return ""; + } + if (Icons.get(icon) === undefined) { + Logger.w("Icon", `"${icon}"`, "doesn't exist in the icons font"); + Logger.callStack(); + return Icons.get(Icons.defaultIcon); + } + return Icons.get(icon); + } + font.family: Icons.fontFamily + font.pointSize: Math.max(1, applyUiScale ? root.pointSize * Style.uiScaleRatio : root.pointSize) + color: Color.mOnSurface + verticalAlignment: Text.AlignVCenter + horizontalAlignment: Text.AlignHCenter +} diff --git a/quickshell/compat/noctalia/Widgets/NIconButton.qml b/quickshell/compat/noctalia/Widgets/NIconButton.qml new file mode 100644 index 0000000..15053a3 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NIconButton.qml @@ -0,0 +1,133 @@ +import QtQuick +import Quickshell +import Quickshell.Widgets +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Services.UI + +Item { + id: root + + property real baseSize: Style.baseWidgetSize + property bool applyUiScale: true + + property string icon + property var tooltipText + property string tooltipDirection: "auto" + property bool allowClickWhenDisabled: false + property bool handleWheel: false + property bool hovering: false + + property color colorBg: Color.smartAlpha(Color.mSurfaceVariant) + property color colorFg: Color.mPrimary + property color colorBgHover: Color.mHover + property color colorFgHover: Color.mOnHover + property color colorBorder: Color.mOutline + property color colorBorderHover: Color.mOutline + property real customRadius: -1 // -1 means use default (iRadiusL), otherwise use this value + + // Expose border properties for backwards compatibility (aliases to visualButton) + property alias border: visualButton.border + property alias radius: visualButton.radius + property alias color: visualButton.color + + signal entered + signal exited + signal clicked + signal rightClicked + signal middleClicked + signal wheel(int angleDelta) + + // Calculate button size based on settings + readonly property real buttonSize: applyUiScale ? Style.toOdd(baseSize * Style.uiScaleRatio) : Style.toOdd(baseSize) + + // Size: use implicit width/height which layout can override + // BarWidgetLoader sets explicit width/height to extend click area + implicitWidth: buttonSize + implicitHeight: buttonSize + + opacity: enabled ? 1.0 : 0.6 + + // Visual button - stays at buttonSize, centered in parent + Rectangle { + id: visualButton + width: root.buttonSize + height: root.buttonSize + anchors.centerIn: parent + + color: root.enabled && root.hovering ? colorBgHover : colorBg + radius: Math.min((customRadius >= 0 ? customRadius : Style.iRadiusL), width / 2) + border.color: root.enabled && root.hovering ? colorBorderHover : colorBorder + border.width: Style.borderS + + Behavior on color { + enabled: !Color.isTransitioning + ColorAnimation { + duration: Style.animationFast + easing.type: Easing.InOutQuad + } + } + + NIcon { + icon: root.icon + pointSize: Style.toOdd(visualButton.width * 0.48) + applyUiScale: root.applyUiScale + color: root.enabled && root.hovering ? colorFgHover : colorFg + // Pixel-perfect centering + x: Style.pixelAlignCenter(visualButton.width, width) + y: Style.pixelAlignCenter(visualButton.height, contentHeight) + + Behavior on color { + enabled: !Color.isTransitioning + ColorAnimation { + duration: Style.animationFast + easing.type: Easing.InOutQuad + } + } + } + } + + // MouseArea fills root (extends beyond visual button for bar click area) + MouseArea { + // Always enabled to allow hover/tooltip even when the button is disabled + enabled: true + anchors.fill: parent + cursorShape: root.enabled ? Qt.PointingHandCursor : Qt.ArrowCursor + acceptedButtons: Qt.LeftButton | Qt.RightButton | Qt.MiddleButton + hoverEnabled: true + onEntered: { + hovering = root.enabled ? true : false; + if (hovering && tooltipText && (!Array.isArray(tooltipText) || tooltipText.length > 0)) { + TooltipService.show(root, tooltipText, tooltipDirection); + } + root.entered(); + } + onExited: { + hovering = false; + if (tooltipText && (!Array.isArray(tooltipText) || tooltipText.length > 0)) { + TooltipService.hide(root); + } + root.exited(); + } + onClicked: mouse => { + if (tooltipText && (!Array.isArray(tooltipText) || tooltipText.length > 0)) { + TooltipService.hide(root); + } + if (!root.enabled && !allowClickWhenDisabled) { + return; + } + if (mouse.button === Qt.LeftButton) { + root.clicked(); + } else if (mouse.button === Qt.RightButton) { + root.rightClicked(); + } else if (mouse.button === Qt.MiddleButton) { + root.middleClicked(); + } + } + onWheel: wheel => { + if (root.handleWheel) { + root.wheel(wheel.angleDelta.y); + } + wheel.accepted = false; + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NIconButtonHot.qml b/quickshell/compat/noctalia/Widgets/NIconButtonHot.qml new file mode 100644 index 0000000..2a15849 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NIconButtonHot.qml @@ -0,0 +1,161 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Effects +import QtQuick.Layouts +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Services.UI + +Rectangle { + id: root + + // Public properties + property real baseSize: Style.baseWidgetSize + property bool applyUiScale: true + property string icon + property var tooltipText + property string tooltipDirection: "auto" + property bool allowClickWhenDisabled: false + property bool hot: false + + // Internal properties + property bool hovering: false + property bool pressed: false + + // Color properties + property color colorBg: Color.smartAlpha(Color.mSurfaceVariant) + property color colorFg: Color.mPrimary + property color colorBgHover: Color.mHover + property color colorFgHover: Color.mOnHover + property color colorBorder: Color.mOutline + property color colorBorderHover: Color.mOutline + + // Hot state colors + property color colorBgHot: Color.mPrimary + property color colorFgHot: Color.mOnPrimary + + // Signals + signal entered + signal exited + signal clicked + signal rightClicked + signal middleClicked + + // Dimensions + implicitWidth: applyUiScale ? Math.round(baseSize * Style.uiScaleRatio) : Math.round(baseSize) + implicitHeight: applyUiScale ? Math.round(baseSize * Style.uiScaleRatio) : Math.round(baseSize) + + // Appearance + opacity: enabled ? 1.0 : 0.6 + color: { + if (root.enabled && root.hovering || pressed) { + return colorBgHover; + } + + if (hot) { + return colorBgHot; + } + return colorBg; + } + radius: Math.min(Style.iRadiusL, width / 2) + border.color: root.enabled && root.hovering ? colorBorderHover : colorBorder + border.width: Style.borderS + + Behavior on color { + enabled: !Color.isTransitioning + ColorAnimation { + duration: Style.animationFast + easing.type: Easing.InOutQuad + } + } + + // Icon + NIcon { + icon: root.icon + pointSize: Math.max(1, Math.round(root.width * 0.48)) + applyUiScale: root.applyUiScale + color: { + if (root.enabled && root.hovering || pressed) { + return colorFgHover; + } + if (hot) { + return colorFgHot; + } + return colorFg; + } + // Center horizontally + x: (root.width - width) / 2 + // Center vertically accounting for font metrics + y: (root.height - height) / 2 + (height - contentHeight) / 2 + + Behavior on color { + enabled: !Color.isTransitioning + ColorAnimation { + duration: Style.animationFast + easing.type: Easing.InOutQuad + } + } + } + + MouseArea { + // Always enabled to allow hover/tooltip even when the button is disabled + enabled: true + anchors.fill: parent + cursorShape: root.enabled ? Qt.PointingHandCursor : Qt.ArrowCursor + acceptedButtons: Qt.LeftButton | Qt.RightButton | Qt.MiddleButton + hoverEnabled: true + + onEntered: { + hovering = root.enabled ? true : false; + if (hovering && tooltipText && (!Array.isArray(tooltipText) || tooltipText.length > 0)) { + TooltipService.show(parent, tooltipText, tooltipDirection); + } + root.entered(); + } + + onExited: { + hovering = false; + if (tooltipText && (!Array.isArray(tooltipText) || tooltipText.length > 0)) { + TooltipService.hide(); + } + root.exited(); + } + + onPressed: function (mouse) { + if (root.enabled) { + root.pressed = true; + } + if (tooltipText && (!Array.isArray(tooltipText) || tooltipText.length > 0)) { + TooltipService.hide(); + } + } + + onReleased: function (mouse) { + root.scale = 1.0; + root.pressed = false; + + if (!root.enabled && !allowClickWhenDisabled) { + return; + } + + // Only trigger actions if released while hovering + if (root.hovering) { + if (mouse.button === Qt.LeftButton) { + root.clicked(); + } else if (mouse.button === Qt.RightButton) { + root.rightClicked(); + } else if (mouse.button === Qt.MiddleButton) { + root.middleClicked(); + } + } + } + + onCanceled: { + root.hovering = false; + root.pressed = false; + root.scale = 1.0; + if (tooltipText && (!Array.isArray(tooltipText) || tooltipText.length > 0)) { + TooltipService.hide(); + } + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NIconPicker.qml b/quickshell/compat/noctalia/Widgets/NIconPicker.qml new file mode 100644 index 0000000..c7f8422 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NIconPicker.qml @@ -0,0 +1,170 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import QtQuick.Window +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Widgets + +Popup { + id: root + modal: true + + property string selectedIcon: "" + property string initialIcon: "" + + signal iconSelected(string iconName) + + width: Math.round(900 * Style.uiScaleRatio) + height: Math.round(700 * Style.uiScaleRatio) + anchors.centerIn: Overlay.overlay + padding: Style.marginXL + + property string query: "" + property var allIcons: Object.keys(Icons.icons) + property var filteredIcons: { + if (query === "") + return allIcons; + var q = query.toLowerCase(); + return allIcons.filter(name => name.toLowerCase().includes(q)); + } + readonly property int columns: 6 + readonly property int cellW: Math.floor(grid.width / columns) + readonly property int cellH: Math.round(cellW * 0.7 + 36) + + onOpened: { + selectedIcon = initialIcon; + query = initialIcon; + searchInput.forceActiveFocus(); + } + + background: Rectangle { + color: Color.mSurface + radius: Style.iRadiusL + border.color: Color.mPrimary + border.width: Style.borderM + } + + ColumnLayout { + anchors.fill: parent + spacing: Style.marginM + + // Title row + RowLayout { + Layout.fillWidth: true + NText { + text: I18n.tr("widgets.icon-picker.title") + pointSize: Style.fontSizeL + font.weight: Style.fontWeightBold + color: Color.mPrimary + Layout.fillWidth: true + } + NIconButton { + icon: "close" + tooltipText: I18n.tr("common.close") + onClicked: root.close() + } + } + + NDivider { + Layout.fillWidth: true + } + + RowLayout { + Layout.fillWidth: true + spacing: Style.marginS + NTextInput { + id: searchInput + Layout.fillWidth: true + label: I18n.tr("common.search") + placeholderText: I18n.tr("placeholders.search-icons") + text: root.query + onTextChanged: root.query = text.trim().toLowerCase() + } + } + + // Icon grid + NGridView { + id: grid + Layout.fillWidth: true + Layout.fillHeight: true + Layout.margins: Style.marginM + cellWidth: root.cellW + cellHeight: root.cellH + model: root.filteredIcons + reserveScrollbarSpace: false + gradientColor: Color.mSurface + + delegate: Rectangle { + width: grid.cellWidth + height: grid.cellHeight + radius: Style.iRadiusS + + color: (root.selectedIcon === modelData) ? Qt.alpha(Color.mPrimary, 0.15) : "transparent" + border.color: (root.selectedIcon === modelData) ? Color.mPrimary : "transparent" + border.width: (root.selectedIcon === modelData) ? Style.borderS : 0 + + MouseArea { + anchors.fill: parent + onClicked: root.selectedIcon = modelData + onDoubleClicked: { + root.selectedIcon = modelData; + root.iconSelected(root.selectedIcon); + root.close(); + } + } + + ColumnLayout { + anchors.fill: parent + anchors.margins: Style.marginS + spacing: Style.marginS + Item { + Layout.fillHeight: true + Layout.preferredHeight: 4 + } + NIcon { + Layout.alignment: Qt.AlignHCenter + icon: modelData + pointSize: 42 + } + NText { + Layout.alignment: Qt.AlignHCenter + Layout.fillWidth: true + Layout.topMargin: Style.marginXS + elide: Text.ElideRight + wrapMode: Text.NoWrap + maximumLineCount: 1 + horizontalAlignment: Text.AlignHCenter + color: Color.mOnSurfaceVariant + pointSize: Style.fontSizeXS + text: modelData + } + Item { + Layout.fillHeight: true + } + } + } + } + + RowLayout { + Layout.fillWidth: true + spacing: Style.marginM + Item { + Layout.fillWidth: true + } + NButton { + text: I18n.tr("common.cancel") + outlined: true + onClicked: root.close() + } + NButton { + text: I18n.tr("common.apply") + icon: "check" + enabled: root.selectedIcon !== "" + onClicked: { + root.iconSelected(root.selectedIcon); + root.close(); + } + } + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NImageRounded.qml b/quickshell/compat/noctalia/Widgets/NImageRounded.qml new file mode 100644 index 0000000..0e27205 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NImageRounded.qml @@ -0,0 +1,103 @@ +import QtQuick +import QtQuick.Effects +import Quickshell +import Quickshell.Widgets +import qs.compat.noctalia.Commons + +Item { + id: root + + property real radius: 0 + property string imagePath: "" + property string fallbackIcon: "" + property real fallbackIconSize: Style.fontSizeXXL + property real borderWidth: 0 + property color borderColor: "transparent" + property int imageFillMode: Image.PreserveAspectCrop + + readonly property bool _isAnimated: imagePath.toLowerCase().endsWith(".gif") + readonly property Item imageSource: imageSourceLoader.item + readonly property bool showFallback: fallbackIcon !== "" && (imagePath === "" || (imageSource && imageSource.status === Image.Error)) + readonly property int status: imageSource ? imageSource.status : Image.Null + + Rectangle { + anchors.fill: parent + radius: root.radius + color: "transparent" + border.width: root.borderWidth + border.color: root.borderColor + + Loader { + id: imageSourceLoader + anchors.fill: parent + anchors.margins: root.borderWidth + active: root.imagePath !== "" + sourceComponent: root._isAnimated ? animatedComponent : staticComponent + } + + Component { + id: staticComponent + Image { + visible: false + source: root.imagePath + mipmap: true + smooth: true + asynchronous: true + antialiasing: true + fillMode: root.imageFillMode + } + } + + Component { + id: animatedComponent + AnimatedImage { + visible: false + source: root.imagePath + mipmap: true + smooth: true + asynchronous: true + antialiasing: true + fillMode: root.imageFillMode + playing: true + } + } + + // Fallback texture provider to avoid null source warnings + ShaderEffectSource { + id: _safeFallback + sourceItem: Rectangle { + width: 1 + height: 1 + color: "transparent" + } + visible: false + live: false + } + + ShaderEffect { + anchors.fill: parent + anchors.margins: root.borderWidth + visible: !root.showFallback && root.imageSource !== null && root.status === Image.Ready + property var source: root.imageSource ?? _safeFallback + property real itemWidth: width + property real itemHeight: height + property real sourceWidth: root.imageSource?.sourceSize.width ?? 0 + property real sourceHeight: root.imageSource?.sourceSize.height ?? 0 + property real cornerRadius: Math.max(0, root.radius - root.borderWidth) + property real imageOpacity: 1.0 + property int fillMode: root.imageFillMode + + fragmentShader: Qt.resolvedUrl(Quickshell.shellDir + "/Shaders/qsb/rounded_image.frag.qsb") + supportsAtlasTextures: false + blending: true + } + + NIcon { + anchors.fill: parent + anchors.margins: root.borderWidth + visible: root.showFallback + icon: root.fallbackIcon + pointSize: root.fallbackIconSize + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NInputAction.qml b/quickshell/compat/noctalia/Widgets/NInputAction.qml new file mode 100644 index 0000000..8aef3a7 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NInputAction.qml @@ -0,0 +1,52 @@ +import QtQuick +import QtQuick.Layouts +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Widgets + +// Input and button row +RowLayout { + id: root + + // Public properties + property string label: "" + property string description: "" + property string placeholderText: "" + property string text: "" + property string actionButtonText: I18n.tr("common.test") + property string actionButtonIcon: "media-play" + property bool actionButtonEnabled: text !== "" + + // Signals + signal editingFinished + signal actionClicked + + // Internal properties + spacing: Style.marginM + + NTextInput { + id: textInput + label: root.label + description: root.description + placeholderText: root.placeholderText + text: root.text + onTextChanged: root.text = text + onEditingFinished: root.editingFinished() + Layout.fillWidth: true + } + + NButton { + Layout.fillWidth: false + Layout.alignment: Qt.AlignBottom + + text: root.actionButtonText + icon: root.actionButtonIcon + backgroundColor: Color.mSecondary + textColor: Color.mOnSecondary + hoverColor: Color.mHover + enabled: root.actionButtonEnabled + + onClicked: { + root.actionClicked(); + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NKeybindRecorder.qml b/quickshell/compat/noctalia/Widgets/NKeybindRecorder.qml new file mode 100644 index 0000000..12a43e1 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NKeybindRecorder.qml @@ -0,0 +1,249 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Services.UI +import qs.compat.noctalia.Widgets + +Item { + id: root + + property string label: "" + property string description: "" + property var currentKeybinds: [] + property string defaultKeybind: "" + property bool allowEmpty: false + property color labelColor: Color.mOnSurface + property color descriptionColor: Color.mOnSurfaceVariant + property string settingsPath: "" + + property int maxKeybinds: 2 + property bool requireModifierForNormalKeys: true + signal keybindsChanged(var newKeybinds) + + implicitHeight: contentLayout.implicitHeight + + // -1 = not recording, >= 0 = re-recording at index, -2 = adding new + property int recordingIndex: -1 + property bool hasConflict: false + + onRecordingIndexChanged: { + PanelService.isKeybindRecording = recordingIndex !== -1; + if (recordingIndex !== -1) { + hasConflict = false; + } + } + + readonly property real _pillHeight: Style.baseWidgetSize * 1.1 * Style.uiScaleRatio + + function _applyKeybind(keyStr) { + if (!keyStr) + return; + + // 1. Internal duplicate check (same action) + for (let i = 0; i < root.currentKeybinds.length; i++) { + if (i !== root.recordingIndex && String(root.currentKeybinds[i]).toLowerCase() === keyStr.toLowerCase()) { + hasConflict = true; + ToastService.showWarning(I18n.tr("panels.general.keybinds-conflict-title"), I18n.tr("panels.general.keybinds-conflict-description", { + "action": root.label || "This action" + })); + conflictTimer.restart(); + return; + } + } + + // 2. External conflict check (other actions) + const conflict = Keybinds.getKeybindConflict(keyStr, root.settingsPath, Settings.data); + if (conflict) { + hasConflict = true; + ToastService.showWarning(I18n.tr("panels.general.keybinds-conflict-title"), I18n.tr("panels.general.keybinds-conflict-description", { + "action": conflict + })); + conflictTimer.restart(); + return; + } + + var newKeybinds = Array.from(root.currentKeybinds); + if (recordingIndex >= 0) { + newKeybinds[recordingIndex] = keyStr; + } + // Ensure array is dense and limited to maxKeybinds + newKeybinds = newKeybinds.filter(k => k !== undefined && k !== "").slice(0, root.maxKeybinds); + recordingIndex = -1; + root.keybindsChanged(newKeybinds); + } + + Timer { + id: conflictTimer + interval: 2000 + onTriggered: { + hasConflict = false; + recordingIndex = -1; + } + } + + RowLayout { + id: contentLayout + width: parent.width + spacing: Style.marginL + + // Label and Description (optional) + NLabel { + id: labelContainer + label: root.label + description: root.description + labelColor: root.labelColor + descriptionColor: root.descriptionColor + visible: label !== "" || description !== "" + Layout.fillWidth: true + Layout.alignment: Qt.AlignVCenter + } + + RowLayout { + id: slotsRow + spacing: Style.marginS + Layout.alignment: Qt.AlignVCenter | (labelContainer.visible ? Qt.AlignRight : Qt.AlignLeft) + + Repeater { + model: root.maxKeybinds + delegate: MouseArea { + id: slotArea + width: Math.round(180 * Style.uiScaleRatio) + height: root._pillHeight + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + + readonly property bool isOccupied: index < root.currentKeybinds.length + readonly property bool isRecordingThis: root.recordingIndex === index + readonly property string keybindText: isRecordingThis ? I18n.tr("placeholders.keybind-recording") : (isOccupied ? root.currentKeybinds[index] : I18n.tr("placeholders.add-new-keybind")) + + onClicked: { + if (isRecordingThis) { + root.recordingIndex = -1; + } else { + root.recordingIndex = index; + keybindInput.forceActiveFocus(); + } + } + + Rectangle { + id: slotBg + anchors.fill: parent + radius: Style.iRadiusS + color: root.hasConflict && slotArea.isRecordingThis ? Color.mError : (slotArea.isRecordingThis ? Color.mSecondary : (slotArea.containsMouse ? Qt.alpha(Color.mSecondary, 0.15) : Color.mSurface)) + border.color: root.hasConflict && slotArea.isRecordingThis ? Color.mError : (slotArea.isRecordingThis ? Color.mPrimary : (slotArea.containsMouse ? Color.mSecondary : Color.mOutline)) + border.width: Style.borderS + + Behavior on color { + ColorAnimation { + duration: Style.animationFast + } + } + Behavior on border.color { + ColorAnimation { + duration: Style.animationFast + } + } + + RowLayout { + anchors.fill: parent + anchors.leftMargin: Style.marginM + anchors.rightMargin: Style.marginS + spacing: Style.marginXS + + NIcon { + icon: root.hasConflict && slotArea.isRecordingThis ? "alert-circle" : (slotArea.isRecordingThis ? "circle-dot" : "keyboard") + color: slotArea.isRecordingThis ? Color.mOnSecondary : (slotArea.isOccupied ? Color.mOnSurfaceVariant : Qt.alpha(Color.mOnSurfaceVariant, 0.4)) + opacity: 0.8 + visible: !slotArea.isRecordingThis || root.hasConflict + } + + NText { + Layout.fillWidth: true + text: slotArea.keybindText + color: slotArea.isRecordingThis ? Color.mOnSecondary : (slotArea.isOccupied ? Color.mOnSurface : Color.mOnSurfaceVariant) + font.family: slotArea.isOccupied && !slotArea.isRecordingThis ? Settings.data.ui.fontFixed : Settings.data.ui.fontDefault + font.pointSize: slotArea.isOccupied ? Style.fontSizeM : Style.fontSizeS + font.weight: slotArea.isOccupied ? Style.fontWeightBold : Style.fontWeightRegular + elide: Text.ElideRight + opacity: slotArea.isOccupied || slotArea.isRecordingThis ? 1.0 : 0.6 + } + + Item { + Layout.preferredWidth: Math.round(root._pillHeight * 0.7) + Layout.fillHeight: true + visible: slotArea.isOccupied && root.recordingIndex === -1 + + NIconButton { + anchors.centerIn: parent + visible: root.recordingIndex === -1 && (root.currentKeybinds.length > 1 || root.allowEmpty) + icon: "x" + colorBg: "transparent" + colorBgHover: Qt.alpha(Color.mError, 0.1) + colorFg: Color.mOnSurfaceVariant + colorFgHover: Color.mError + border.width: 0 + baseSize: Style.baseWidgetSize * 0.7 + onClicked: { + var newKeybinds = Array.from(root.currentKeybinds); + newKeybinds.splice(index, 1); + root.keybindsChanged(newKeybinds); + } + } + } + } + } + } + } + } + + // Hidden Item to capture keys + Item { + id: keybindInput + width: 0 + height: 0 + focus: true + + Keys.onPressed: event => { + if (root.recordingIndex === -1 || root.hasConflict) + return; + + // Handle Escape specifically to ensure it doesn't close the panel + if (event.key === Qt.Key_Escape) { + event.accepted = true; + root._applyKeybind("Esc"); + return; + } + + // Ignore modifier keys by themselves + if (event.key === Qt.Key_Control || event.key === Qt.Key_Shift || event.key === Qt.Key_Alt || event.key === Qt.Key_Meta) { + event.accepted = true; // Consume modifiers too while listening + return; + } + + const keybindStr = Keybinds.getKeybindString(event); + if (keybindStr) { + // Enforce modifier requirement (Ctrl or Alt) for "normal" keys unless explicitly disabled + // Allow Arrows, Nav, Function, and System keys without modifiers + const isSpecialKey = (event.key >= Qt.Key_F1 && event.key <= Qt.Key_F35) || (event.key >= Qt.Key_Left && event.key <= Qt.Key_Down) || (event.key === Qt.Key_Home || event.key === Qt.Key_End || event.key === Qt.Key_PageUp || event.key === Qt.Key_PageDown) || (event.key === Qt.Key_Insert || event.key === Qt.Key_Delete || event.key + === Qt.Key_Backspace) || (event.key === Qt.Key_Tab || event.key + === Qt.Key_Return || event.key === Qt.Key_Enter + || event.key === Qt.Key_Escape || event.key + === Qt.Key_Space); + + const hasModifier = (event.modifiers & Qt.ControlModifier) || (event.modifiers & Qt.AltModifier); + + if (root.requireModifierForNormalKeys && !hasModifier && !isSpecialKey) { + hasConflict = true; + ToastService.showWarning(I18n.tr("panels.general.keybinds-modifier-title"), I18n.tr("panels.general.keybinds-modifier-description")); + conflictTimer.restart(); + return; + } + + root._applyKeybind(keybindStr); + } + event.accepted = true; + } + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NLabel.qml b/quickshell/compat/noctalia/Widgets/NLabel.qml new file mode 100644 index 0000000..87c81a1 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NLabel.qml @@ -0,0 +1,69 @@ +import QtQuick +import QtQuick.Layouts +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Widgets + +ColumnLayout { + id: root + + property string label: "" + property string description: "" + property string icon: "" + property color labelColor: Color.mOnSurface + property color descriptionColor: Color.mOnSurfaceVariant + property color iconColor: Color.mOnSurface + property bool showIndicator: false + property string indicatorTooltip: "" + property real labelSize: Style.fontSizeL + + opacity: enabled ? 1.0 : 0.6 + spacing: Style.marginXXS + visible: root.label != "" || root.description != "" + + Layout.fillWidth: true + + RowLayout { + spacing: Style.marginXS + Layout.fillWidth: true + visible: root.label !== "" + + NIcon { + visible: root.icon !== "" + icon: root.icon + pointSize: Style.fontSizeXXL + color: root.iconColor + Layout.rightMargin: Style.marginS + } + + NText { + id: labelText + Layout.fillWidth: true + text: root.label + pointSize: root.labelSize + font.weight: Style.fontWeightSemiBold + color: labelColor + wrapMode: Text.WordWrap + + // Settings indicator dot positioned right after the text content + Loader { + active: root.showIndicator + x: labelText.contentWidth + Style.marginXS + anchors.verticalCenter: parent.verticalCenter + sourceComponent: NSettingsIndicator { + show: true + tooltipText: root.indicatorTooltip || "" + } + } + } + } + + NText { + visible: root.description !== "" + Layout.fillWidth: true + text: root.description + pointSize: Style.fontSizeS + color: root.descriptionColor + wrapMode: Text.WordWrap + textFormat: Text.StyledText + } +} diff --git a/quickshell/compat/noctalia/Widgets/NLinearGauge.qml b/quickshell/compat/noctalia/Widgets/NLinearGauge.qml new file mode 100644 index 0000000..31ebbed --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NLinearGauge.qml @@ -0,0 +1,28 @@ +import QtQuick +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Services.UI + +Rectangle { + id: root + + // Mandatory properties for gauges + required property int orientation // Qt.Vertical || Qt.Horizontal + required property real ratio // 0..1 + + radius: orientation === Qt.Vertical ? width / 2 : height / 2 + color: Color.mOutline + property color fillColor: Color.mPrimary + + // Fill that grows from bottom if vertical and left if horizontal. + // Snap to zero if the computed pixel length is sub-pixel (< 1px). + Rectangle { + readonly property real clampedRatio: Math.min(1, Math.max(0, root.ratio)) + readonly property real rawFill: (orientation === Qt.Vertical ? root.height : root.width) * clampedRatio + width: orientation === Qt.Vertical ? root.width : (rawFill < 1 ? 0 : rawFill) + height: orientation === Qt.Vertical ? (rawFill < 1 ? 0 : rawFill) : root.height + radius: root.radius + color: root.fillColor + anchors.bottom: orientation === Qt.Vertical ? parent.bottom : undefined + anchors.left: parent.left + } +} diff --git a/quickshell/compat/noctalia/Widgets/NListView.qml b/quickshell/compat/noctalia/Widgets/NListView.qml new file mode 100644 index 0000000..5e7befd --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NListView.qml @@ -0,0 +1,340 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Templates as T +import qs.compat.noctalia.Commons + +Item { + id: root + + property color handleColor: Qt.alpha(Color.mHover, 0.8) + property color handleHoverColor: handleColor + property color handlePressedColor: handleColor + property color trackColor: "transparent" + property real handleWidth: Math.round(6 * Style.uiScaleRatio) + property real handleRadius: Style.iRadiusM + property int verticalPolicy: ScrollBar.AsNeeded + property int horizontalPolicy: ScrollBar.AlwaysOff + readonly property bool verticalScrollBarActive: { + if (listView.ScrollBar.vertical.policy === ScrollBar.AlwaysOff) + return false; + return listView.contentHeight > listView.height; + } + readonly property bool contentOverflows: listView.contentHeight > listView.height + + property bool showGradientMasks: true + property color gradientColor: Color.mSurfaceVariant + property int gradientHeight: 16 + property bool reserveScrollbarSpace: true + + // Keep scrollbars visible whenever overflow exists (without forcing visibility when not scrollable) + property bool showScrollbarWhenScrollable: Settings.data.ui.scrollbarAlwaysVisible + + // Available width for content (excludes scrollbar space when reserveScrollbarSpace is true) + readonly property real availableWidth: width - (reserveScrollbarSpace ? handleWidth + Style.marginXS : 0) + + // Forward ListView properties + property alias model: listView.model + property alias delegate: listView.delegate + property alias spacing: listView.spacing + property alias orientation: listView.orientation + property alias currentIndex: listView.currentIndex + property alias count: listView.count + property alias contentHeight: listView.contentHeight + property alias contentWidth: listView.contentWidth + property alias contentY: listView.contentY + property alias contentX: listView.contentX + property alias currentItem: listView.currentItem + property alias highlightItem: listView.highlightItem + property alias headerItem: listView.headerItem + property alias footerItem: listView.footerItem + property alias section: listView.section + property alias highlightFollowsCurrentItem: listView.highlightFollowsCurrentItem + property alias highlightMoveDuration: listView.highlightMoveDuration + property alias highlightMoveVelocity: listView.highlightMoveVelocity + property alias preferredHighlightBegin: listView.preferredHighlightBegin + property alias preferredHighlightEnd: listView.preferredHighlightEnd + property alias highlightRangeMode: listView.highlightRangeMode + property alias snapMode: listView.snapMode + property alias keyNavigationWraps: listView.keyNavigationWraps + property alias cacheBuffer: listView.cacheBuffer + property alias displayMarginBeginning: listView.displayMarginBeginning + property alias displayMarginEnd: listView.displayMarginEnd + property alias layoutDirection: listView.layoutDirection + property alias effectiveLayoutDirection: listView.effectiveLayoutDirection + property alias verticalLayoutDirection: listView.verticalLayoutDirection + property alias boundsBehavior: listView.boundsBehavior + property alias flickableDirection: listView.flickableDirection + property alias interactive: listView.interactive + property alias moving: listView.moving + property alias flicking: listView.flicking + property alias dragging: listView.dragging + property alias horizontalVelocity: listView.horizontalVelocity + property alias verticalVelocity: listView.verticalVelocity + + // Scroll speed multiplier for mouse wheel (1.0 = default, higher = faster) + property real wheelScrollMultiplier: 2.0 + property int smoothWheelAnimationDuration: Style.animationNormal + property real _wheelTargetY: 0 + + function clampScrollY(value) { + return Math.max(0, Math.min(value, listView.contentHeight - listView.height)); + } + + function applyWheelScroll(delta) { + if (!root.contentOverflows) + return; + + const step = delta * root.wheelScrollMultiplier; + + if (!Settings.data.general.smoothScrollEnabled || Settings.data.general.animationDisabled) { + listView.contentY = root.clampScrollY(listView.contentY - step); + root._wheelTargetY = listView.contentY; + return; + } + + if (!wheelScrollAnimation.running) + root._wheelTargetY = listView.contentY; + + root._wheelTargetY = root.clampScrollY(root._wheelTargetY - step); + wheelScrollAnimation.to = root._wheelTargetY; + wheelScrollAnimation.restart(); + } + + function animateToContentY(targetY) { + const clampedY = root.clampScrollY(targetY); + + if (!Settings.data.general.smoothScrollEnabled || Settings.data.general.animationDisabled || listView.dragging || listView.flicking) { + listView.contentY = clampedY; + root._wheelTargetY = clampedY; + return; + } + + root._wheelTargetY = clampedY; + wheelScrollAnimation.to = clampedY; + wheelScrollAnimation.restart(); + } + + // Forward ListView methods + function positionViewAtIndex(index, mode) { + const shouldAnimate = mode === ListView.Contain; + if (!shouldAnimate) { + listView.positionViewAtIndex(index, mode); + root._wheelTargetY = listView.contentY; + return; + } + + const previousY = listView.contentY; + listView.positionViewAtIndex(index, mode); + const targetY = root.clampScrollY(listView.contentY); + + if (Math.abs(targetY - previousY) < 0.5) { + root._wheelTargetY = targetY; + return; + } + + listView.contentY = previousY; + root._wheelTargetY = previousY; + root.animateToContentY(targetY); + } + + function positionViewAtBeginning() { + listView.positionViewAtBeginning(); + } + + function positionViewAtEnd() { + listView.positionViewAtEnd(); + } + + function forceLayout() { + listView.forceLayout(); + } + + function cancelFlick() { + listView.cancelFlick(); + } + + function flick(xVelocity, yVelocity) { + listView.flick(xVelocity, yVelocity); + } + + function incrementCurrentIndex() { + listView.incrementCurrentIndex(); + } + + function decrementCurrentIndex() { + listView.decrementCurrentIndex(); + } + + function indexAt(x, y) { + return listView.indexAt(x, y); + } + + function itemAt(x, y) { + return listView.itemAt(x, y); + } + + function itemAtIndex(index) { + return listView.itemAtIndex(index); + } + + // Set reasonable implicit sizes for Layout usage + implicitWidth: 200 + implicitHeight: 200 + + Component.onCompleted: { + _wheelTargetY = listView.contentY; + createGradients(); + } + + // Dynamically create gradient overlays + function createGradients() { + if (!showGradientMasks) + return; + + Qt.createQmlObject(` + import QtQuick + import qs.compat.noctalia.Commons + Rectangle { + x: 0 + y: 0 + width: root.availableWidth + height: root.gradientHeight + z: 1 + visible: root.showGradientMasks && root.contentOverflows + opacity: { + if (listView.contentY <= 1) return 0; + if (listView.currentItem && listView.currentItem.y - listView.contentY < root.gradientHeight) return 0; + return 1; + } + Behavior on opacity { + NumberAnimation { duration: Style.animationFast; easing.type: Easing.InOutQuad } + } + gradient: Gradient { + GradientStop { position: 0.0; color: root.gradientColor } + GradientStop { position: 1.0; color: "transparent" } + } + } + `, root, "topGradient"); + + Qt.createQmlObject(` + import QtQuick + import qs.compat.noctalia.Commons + Rectangle { + x: 0 + anchors.bottom: parent.bottom + anchors.bottomMargin: -1 + width: root.availableWidth + height: root.gradientHeight + 1 + z: 1 + visible: root.showGradientMasks && root.contentOverflows + opacity: { + if (listView.contentY + listView.height >= listView.contentHeight - 1) return 0; + if (listView.currentItem && listView.currentItem.y + listView.currentItem.height > listView.contentY + listView.height - root.gradientHeight) return 0; + return 1; + } + Behavior on opacity { + NumberAnimation { duration: Style.animationFast; easing.type: Easing.InOutQuad } + } + gradient: Gradient { + GradientStop { position: 0.0; color: "transparent" } + GradientStop { position: 1.0; color: root.gradientColor } + } + } + `, root, "bottomGradient"); + } + + ListView { + id: listView + anchors.fill: parent + anchors.rightMargin: root.reserveScrollbarSpace ? root.handleWidth + Style.marginXS : 0 + + clip: true + boundsBehavior: Flickable.StopAtBounds + + NumberAnimation { + id: wheelScrollAnimation + target: listView + property: "contentY" + duration: root.smoothWheelAnimationDuration + easing.type: Easing.OutCubic + } + + onDraggingChanged: { + if (dragging) { + wheelScrollAnimation.stop(); + root._wheelTargetY = contentY; + } + } + + onFlickingChanged: { + if (flicking) { + wheelScrollAnimation.stop(); + root._wheelTargetY = contentY; + } + } + + onContentHeightChanged: root._wheelTargetY = root.clampScrollY(root._wheelTargetY) + onHeightChanged: root._wheelTargetY = root.clampScrollY(root._wheelTargetY) + + WheelHandler { + enabled: !root.contentOverflows + acceptedDevices: PointerDevice.Mouse | PointerDevice.TouchPad + onWheel: event => { + event.accepted = true; + } + } + + WheelHandler { + enabled: root.wheelScrollMultiplier !== 1.0 && root.contentOverflows + acceptedDevices: PointerDevice.Mouse | PointerDevice.TouchPad + onWheel: event => { + const delta = event.pixelDelta.y !== 0 ? event.pixelDelta.y : event.angleDelta.y / 2; + root.applyWheelScroll(delta); + event.accepted = true; + } + } + + ScrollBar.vertical: ScrollBar { + parent: root + x: root.mirrored ? 0 : root.width - width + y: 0 + height: root.height + policy: root.verticalPolicy + visible: policy === ScrollBar.AlwaysOn || root.verticalScrollBarActive + + contentItem: Rectangle { + implicitWidth: root.handleWidth + implicitHeight: 100 + radius: root.handleRadius + color: parent.pressed ? root.handlePressedColor : parent.hovered ? root.handleHoverColor : root.handleColor + opacity: parent.policy === ScrollBar.AlwaysOn ? 1.0 : root.verticalScrollBarActive ? ((root.showScrollbarWhenScrollable || parent.active) ? 1.0 : 0.0) : 0.0 + + Behavior on opacity { + NumberAnimation { + duration: Style.animationFast + } + } + + Behavior on color { + ColorAnimation { + duration: Style.animationFast + } + } + } + + background: Rectangle { + implicitWidth: root.handleWidth + implicitHeight: 100 + color: root.trackColor + opacity: parent.policy === ScrollBar.AlwaysOn ? 0.3 : root.verticalScrollBarActive ? ((root.showScrollbarWhenScrollable || parent.active) ? 0.3 : 0.0) : 0.0 + radius: root.handleRadius / 2 + + Behavior on opacity { + NumberAnimation { + duration: Style.animationFast + } + } + } + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NPluginSettingsPopup.qml b/quickshell/compat/noctalia/Widgets/NPluginSettingsPopup.qml new file mode 100644 index 0000000..d7fbbe4 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NPluginSettingsPopup.qml @@ -0,0 +1,152 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Services.Noctalia +import qs.compat.noctalia.Services.UI +import qs.compat.noctalia.Widgets + +Popup { + id: root + modal: true + dim: false + anchors.centerIn: parent + property var screen: null + readonly property real maxHeight: (screen ? screen.height : (parent ? parent.height : 800)) * 0.8 + + property real _minWidth: 600 * Style.uiScaleRatio + width: _minWidth + height: Math.min(settingsContent.implicitHeight + padding * 2, maxHeight) + padding: Style.marginXL + + property var currentPlugin: null + property var currentPluginApi: null + property bool showToastOnSave: false + + background: Rectangle { + color: Color.mSurface + radius: Style.radiusL + border.color: Color.mPrimary + border.width: Style.borderM + } + + contentItem: FocusScope { + focus: true + + ColumnLayout { + id: settingsContent + anchors.fill: parent + spacing: Style.marginM + + // Header + RowLayout { + Layout.fillWidth: true + + NText { + text: I18n.tr("panels.plugins.plugin-settings-title", { + "plugin": root.currentPlugin?.name || "" + }) + pointSize: Style.fontSizeL + font.weight: Style.fontWeightBold + color: Color.mPrimary + Layout.fillWidth: true + } + + NIconButton { + icon: "close" + tooltipText: I18n.tr("common.close") + onClicked: root.close() + } + } + + // Separator + Rectangle { + Layout.fillWidth: true + Layout.preferredHeight: 1 + color: Color.mOutline + } + + // Settings loader - pluginApi is passed via setSource() in openPluginSettings() + NScrollView { + id: settingsScrollView + Layout.fillWidth: true + Layout.fillHeight: true + Layout.minimumHeight: 100 + horizontalPolicy: ScrollBar.AlwaysOff + gradientColor: Color.mSurface + + Loader { + id: settingsLoader + width: settingsScrollView.availableWidth + } + } + + // Action buttons + RowLayout { + Layout.fillWidth: true + Layout.topMargin: Style.marginM + spacing: Style.marginM + + Item { + Layout.fillWidth: true + } + + NButton { + text: I18n.tr("common.close") + outlined: true + onClicked: root.close() + } + + NButton { + text: I18n.tr("common.apply") + icon: "check" + onClicked: { + if (settingsLoader.item && settingsLoader.item.saveSettings) { + settingsLoader.item.saveSettings(); + if (root.showToastOnSave) { + ToastService.showNotice(I18n.tr("panels.plugins.title"), I18n.tr("panels.plugins.settings-saved")); + } + } + } + } + } + } + } + + onClosed: { + // Clear both source and sourceComponent to ensure full cleanup + settingsLoader.sourceComponent = null; + settingsLoader.source = ""; + currentPlugin = null; + currentPluginApi = null; + } + + function openPluginSettings(pluginManifest, settingsEntryPoint) { + currentPlugin = pluginManifest; + + // Use composite key if available (for custom plugins), otherwise use manifest ID (for official plugins) + var pluginId = pluginManifest.compositeKey || pluginManifest.id; + + currentPluginApi = PluginService.getPluginAPI(pluginId); + if (!currentPluginApi) { + Logger.e("NPluginSettingsPopup", "Cannot open settings: plugin not loaded:", pluginId); + if (showToastOnSave) { + ToastService.showError(I18n.tr("panels.plugins.title"), I18n.tr("panels.plugins.settings-error-not-loaded")); + } + return; + } + + // Get plugin directory + var pluginDir = PluginRegistry.getPluginDir(pluginId); + var settingsEntry = settingsEntryPoint ? pluginManifest.entryPoints[settingsEntryPoint] : pluginManifest.entryPoints.settings; + var settingsPath = pluginDir + "/" + settingsEntry; + + settingsLoader.setSource("file://" + settingsPath, { + "pluginApi": currentPluginApi + }); + + var preferred = (settingsLoader.item && settingsLoader.item.preferredWidth !== undefined) ? settingsLoader.item.preferredWidth + padding * 2 : 0; + width = Math.max(preferred, _minWidth); + open(); + } +} diff --git a/quickshell/compat/noctalia/Widgets/NPopupContextMenu.qml b/quickshell/compat/noctalia/Widgets/NPopupContextMenu.qml new file mode 100644 index 0000000..63702c6 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NPopupContextMenu.qml @@ -0,0 +1,372 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import Quickshell +import qs.compat.noctalia.Commons + +// Simple context menu PopupWindow (similar to TrayMenu) +// Designed to be rendered inside a PopupMenuWindow for click-outside-to-close +// Automatically positions itself to respect screen boundaries +PopupWindow { + id: root + + property alias model: repeater.model + property real itemHeight: 28 // Match TrayMenu + property real itemPadding: Style.marginM + property int verticalPolicy: ScrollBar.AsNeeded + property int horizontalPolicy: ScrollBar.AsNeeded + + property var anchorItem: null + property ShellScreen screen: null + property real minWidth: 120 + property real calculatedWidth: 180 + + // Explicit offset for centering on target item (computed from targetItem in openAtItem) + property real targetOffsetX: 0 + property real targetOffsetY: 0 + property real targetWidth: 0 + property real targetHeight: 0 + + readonly property string barPosition: Settings.getBarPositionForScreen(screen?.name) + readonly property real barHeight: Style.getBarHeightForScreen(screen?.name) + + signal triggered(string action, var item) + + implicitWidth: calculatedWidth + implicitHeight: Math.min(600, flickable.contentHeight + Style.margin2S) + visible: false + color: "transparent" + + NText { + id: textMeasure + visible: false + pointSize: Style.fontSizeS + wrapMode: Text.NoWrap + elide: Text.ElideNone + width: undefined + } + + NIcon { + id: iconMeasure + visible: false + icon: "bell" + pointSize: Style.fontSizeS + applyUiScale: false + } + + onModelChanged: { + Qt.callLater(calculateWidth); + } + + function calculateWidth() { + let maxWidth = 0; + if (model && model.length) { + for (let i = 0; i < model.length; i++) { + const item = model[i]; + if (item && item.visible !== false) { + const label = item.label || item.text || ""; + textMeasure.text = label; + textMeasure.forceLayout(); + + let itemWidth = textMeasure.contentWidth + 8; + + if (item.icon !== undefined) { + itemWidth += iconMeasure.width + Style.marginS; + } + + itemWidth += Style.margin2M; + + if (itemWidth > maxWidth) { + maxWidth = itemWidth; + } + } + } + } + calculatedWidth = Math.max(maxWidth + Style.margin2S, minWidth); + } + + anchor.item: anchorItem + + anchor.rect.x: { + if (anchorItem && screen) { + const anchorGlobalPos = anchorItem.mapToItem(null, 0, 0); + + // Use stored targetOffsetX and targetWidth for positioning + const effectiveWidth = targetWidth > 0 ? targetWidth : anchorItem.width; + const targetGlobalX = anchorGlobalPos.x + targetOffsetX; + + // For right bar: position menu to the left of target + if (root.barPosition === "right") { + let baseX = targetOffsetX - implicitWidth - Style.marginM; + return baseX; + } + + // For left bar: position menu to the right of target + if (root.barPosition === "left") { + let baseX = targetOffsetX + effectiveWidth + Style.marginM; + return baseX; + } + + // For top/bottom bar: center horizontally on target + const targetCenterScreenX = targetGlobalX + (effectiveWidth / 2); + const menuScreenX = targetCenterScreenX - (implicitWidth / 2); + let baseX = menuScreenX - anchorGlobalPos.x; + + const menuRight = menuScreenX + implicitWidth; + + // Adjust if menu would clip on the right + if (menuRight > screen.width - Style.marginM) { + const overflow = menuRight - (screen.width - Style.marginM); + return baseX - overflow; + } + // Adjust if menu would clip on the left + if (menuScreenX < Style.marginM) { + return baseX + (Style.marginM - menuScreenX); + } + return baseX; + } + return 0; + } + anchor.rect.y: { + if (anchorItem && screen) { + // Check if using absolute positioning (small anchor point item) + const isAbsolutePosition = anchorItem.width <= 1 && anchorItem.height <= 1; + + if (isAbsolutePosition) { + // For absolute positioning, show menu directly at anchor Y + // Only adjust if menu would clip at bottom + const anchorGlobalPos = anchorItem.mapToItem(null, 0, 0); + const menuBottom = anchorGlobalPos.y + implicitHeight; + + if (menuBottom > screen.height - Style.marginM) { + // Position above the click point instead + return -implicitHeight; + } + return 0; + } + + const anchorGlobalPos = anchorItem.mapToItem(null, 0, 0); + + // Use target offset/height for vertical bars, anchor dimensions otherwise + const effectiveHeight = targetHeight > 0 ? targetHeight : anchorItem.height; + const effectiveOffsetY = targetOffsetY; + + // Calculate base Y position based on bar orientation + let baseY; + if (root.barPosition === "bottom") { + // For bottom bar: position menu above the bar + baseY = -(implicitHeight + Style.marginS); + } else if (root.barPosition === "top") { + // For top bar: position menu below bar at consistent height + // Compensate for anchor's Y position to ensure menu top is always at (barHeight + margin) + baseY = barHeight + Style.marginS - anchorGlobalPos.y; + } else { + // For left/right bar: vertically center on target item + const targetCenterY = effectiveOffsetY + (effectiveHeight / 2); + baseY = targetCenterY - (implicitHeight / 2); + } + + const menuScreenY = anchorGlobalPos.y + baseY; + const menuBottom = menuScreenY + implicitHeight; + + // Define clipping boundaries based on bar position + const topLimit = Style.marginM; + const bottomLimit = root.barPosition === "bottom" ? screen.height - barHeight - Style.marginS : screen.height - Style.marginM; + + // Adjust if menu would clip at top (skip for bottom bar - don't push menu down over bar) + if (menuScreenY < topLimit && root.barPosition !== "bottom") { + const adjustment = topLimit - menuScreenY; + return baseY + adjustment; + } + + // Adjust if menu would clip at bottom (or overlap bar for bottom bar) + if (menuBottom > bottomLimit) { + const overflow = menuBottom - bottomLimit; + return baseY - overflow; + } + + return baseY; + } + + // Fallback if no screen + if (root.barPosition === "bottom") { + return -implicitHeight - Style.marginS; + } + return barHeight; + } + + Component.onCompleted: { + Qt.callLater(calculateWidth); + } + + Item { + anchors.fill: parent + focus: true + Keys.onEscapePressed: root.close() + } + + Rectangle { + id: menuBackground + anchors.fill: parent + color: Color.mSurface + border.color: Color.mOutline + border.width: Style.borderS + radius: Style.radiusM + opacity: root.visible ? 1.0 : 0.0 + + Behavior on opacity { + NumberAnimation { + duration: Style.animationNormal + easing.type: Easing.OutQuad + } + } + } + + Flickable { + id: flickable + anchors.fill: parent + anchors.margins: Style.marginS + contentHeight: columnLayout.implicitHeight + interactive: true + opacity: root.visible ? 1.0 : 0.0 + + Behavior on opacity { + NumberAnimation { + duration: Style.animationNormal + easing.type: Easing.OutQuad + } + } + + ColumnLayout { + id: columnLayout + width: flickable.width + spacing: 0 + + Repeater { + id: repeater + + delegate: Rectangle { + id: menuItem + required property var modelData + required property int index + + Layout.preferredWidth: parent.width + Layout.preferredHeight: modelData.visible !== false ? root.itemHeight : 0 + visible: modelData.visible !== false + color: "transparent" + + Rectangle { + id: innerRect + anchors.fill: parent + color: mouseArea.containsMouse ? Color.mHover : "transparent" + radius: Style.radiusS + opacity: modelData.enabled !== false ? 1.0 : 0.5 + + Behavior on color { + ColorAnimation { + duration: Style.animationFast + } + } + + RowLayout { + anchors.fill: parent + anchors.leftMargin: Style.marginM + anchors.rightMargin: Style.marginM + spacing: Style.marginS + + NIcon { + visible: modelData.icon !== undefined + icon: modelData.icon || "" + pointSize: Style.fontSizeS + applyUiScale: false + color: mouseArea.containsMouse ? Color.mOnHover : Color.mOnSurface + verticalAlignment: Text.AlignVCenter + + Behavior on color { + ColorAnimation { + duration: Style.animationFast + } + } + } + + NText { + text: modelData.label || modelData.text || "" + pointSize: Style.fontSizeS + color: mouseArea.containsMouse ? Color.mOnHover : Color.mOnSurface + verticalAlignment: Text.AlignVCenter + Layout.fillWidth: true + + Behavior on color { + ColorAnimation { + duration: Style.animationFast + } + } + } + } + + MouseArea { + id: mouseArea + anchors.fill: parent + hoverEnabled: true + enabled: (modelData.enabled !== false) && root.visible + cursorShape: Qt.PointingHandCursor + + onClicked: { + if (menuItem.modelData.enabled !== false) { + root.triggered(menuItem.modelData.action || menuItem.modelData.key || menuItem.index.toString(), menuItem.modelData); + // Don't call root.close() here - let the parent PopupMenuWindow handle closing + } + } + } + } + } + } + } + } + + // Helper function to open context menu anchored to an item + // Position is calculated automatically based on bar position and screen boundaries + // Optional centerOnItem: if provided, menu will be horizontally centered on this item instead of anchorItem + function openAtItem(item, itemScreen, centerOnItem) { + if (!item) { + Logger.w("NPopupContextMenu", "anchorItem is undefined, won't show menu."); + return; + } + + // Set anchor and screen first + anchorItem = item; + screen = itemScreen || null; + + // Compute target offset and dimensions from centerOnItem + if (centerOnItem && centerOnItem !== item) { + const relPos = centerOnItem.mapToItem(item, 0, 0); + targetOffsetX = relPos.x; + targetOffsetY = relPos.y; + targetWidth = centerOnItem.width; + targetHeight = centerOnItem.height; + } else { + targetOffsetX = 0; + targetOffsetY = 0; + targetWidth = 0; + targetHeight = 0; + } + + // Calculate menu width after anchor is set + calculateWidth(); + + visible = true; + + // Force anchor recalculation after showing + Qt.callLater(() => { + anchor.updateAnchor(); + }); + } + + function close() { + visible = false; + } + + function closeMenu() { + close(); + } +} diff --git a/quickshell/compat/noctalia/Widgets/NRadioButton.qml b/quickshell/compat/noctalia/Widgets/NRadioButton.qml new file mode 100644 index 0000000..e95c1a1 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NRadioButton.qml @@ -0,0 +1,53 @@ +import QtQuick +import QtQuick.Controls +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Widgets + +RadioButton { + id: root + + property real pointSize: Style.fontSizeM + + implicitWidth: outerCircle.implicitWidth + Style.marginS + contentItem.implicitWidth + + indicator: Rectangle { + id: outerCircle + + implicitWidth: Style.baseWidgetSize * 0.625 * pointSize / Style.fontSizeM + implicitHeight: Style.baseWidgetSize * 0.625 * pointSize / Style.fontSizeM + radius: Math.min(Style.iRadiusL, width / 2) + color: "transparent" + border.color: root.checked ? Color.mPrimary : Color.mOnSurface + border.width: Style.borderM + anchors.verticalCenter: parent.verticalCenter + + Rectangle { + anchors.fill: parent + anchors.margins: parent.width * 0.3 + + radius: Math.min(Style.iRadiusL, width / 2) + color: Qt.alpha(Color.mPrimary, root.checked ? 1 : 0) + + Behavior on color { + ColorAnimation { + duration: Style.animationFast + } + } + } + + Behavior on border.color { + ColorAnimation { + duration: Style.animationFast + } + } + } + + contentItem: NText { + text: root.text + pointSize: root.pointSize + anchors.verticalCenter: parent.verticalCenter + anchors.left: outerCircle.right + anchors.right: parent.right + anchors.leftMargin: Style.marginS + } +} diff --git a/quickshell/compat/noctalia/Widgets/NReorderCheckboxes.qml b/quickshell/compat/noctalia/Widgets/NReorderCheckboxes.qml new file mode 100644 index 0000000..d016737 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NReorderCheckboxes.qml @@ -0,0 +1,310 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import qs.compat.noctalia.Commons + +Item { + id: root + + // Public API + property var model: [] + property var disabledIds: [] + property color activeColor: Color.mPrimary + property color activeOnColor: Color.mOnPrimary + property color dragHandleColor: Color.mOutline + property int baseSize: Style.baseWidgetSize * 0.7 + property int spacing: Style.marginM + + signal itemToggled(int index, bool enabled) + signal itemsReordered(int fromIndex, int toIndex) + signal dragPotentialStarted + signal dragPotentialEnded + + readonly property real itemHeight: root.baseSize + readonly property real contentHeight: root.model.length > 0 ? root.model.length * itemHeight + (root.model.length - 1) * root.spacing : 0 + implicitHeight: contentHeight + + function toggleItem(index) { + if (index < 0 || index >= root.model.length) + return; + var item = root.model[index]; + if (item.required) + return; + + // Create a new array to trigger binding update + var newModel = root.model.slice(); + newModel[index] = Object.assign({}, item, { + "enabled": !item.enabled + }); + root.model = newModel; + + root.itemToggled(index, newModel[index].enabled); + } + + function moveItem(fromIndex, toIndex) { + if (fromIndex === toIndex) + return; + if (fromIndex < 0 || fromIndex >= root.model.length) + return; + if (toIndex < 0 || toIndex >= root.model.length) + return; + + // Create a new array with item moved + var newModel = root.model.slice(); + var item = newModel.splice(fromIndex, 1)[0]; + newModel.splice(toIndex, 0, item); + root.model = newModel; + + root.itemsReordered(fromIndex, toIndex); + } + + Item { + id: itemsContainer + anchors.fill: parent + clip: true + + Repeater { + id: repeater + model: root.model + + delegate: Item { + id: delegateItem + + width: itemsContainer.width + height: checkboxRow.height + + required property int index + required property var modelData + + property string text: modelData.text || "" + property bool itemEnabled: modelData.enabled || false + property bool required: modelData.required || false + readonly property bool isDisabled: (root.disabledIds || []).indexOf(modelData.id) !== -1 + readonly property bool canDrag: !delegateItem.isDisabled + property bool dragging: false + property int dragStartY: 0 + property int dragStartIndex: -1 + property int dragTargetIndex: -1 + property int itemSpacing: root.spacing + + RowLayout { + id: checkboxRow + + width: parent.width + spacing: Style.marginS + opacity: isDisabled ? 0.5 : 1.0 + + // Drag handle + Rectangle { + id: dragHandle + + Layout.preferredWidth: root.baseSize + Layout.preferredHeight: root.baseSize + radius: Style.iRadiusXS + color: dragHandleMouseArea.containsMouse ? Color.mSurfaceVariant : "transparent" + + Behavior on color { + ColorAnimation { + duration: Style.animationFast + } + } + + ColumnLayout { + anchors.centerIn: parent + spacing: Style.marginS + + Repeater { + model: 3 + Rectangle { + Layout.preferredWidth: root.baseSize * 0.4 + Layout.preferredHeight: 2 + radius: 1 + color: root.dragHandleColor + } + } + } + + MouseArea { + id: dragHandleMouseArea + + anchors.fill: parent + cursorShape: delegateItem.canDrag ? Qt.SizeVerCursor : Qt.ArrowCursor + hoverEnabled: true + preventStealing: false + enabled: delegateItem.canDrag + z: 1000 + + onPressed: mouse => { + if (!delegateItem.canDrag) { + return; + } + delegateItem.dragStartIndex = delegateItem.index; + delegateItem.dragTargetIndex = delegateItem.index; + delegateItem.dragStartY = delegateItem.y; + delegateItem.dragging = true; + delegateItem.z = 999; + + // Signal that interaction started (prevents panel close) + preventStealing = true; + root.dragPotentialStarted(); + } + + onPositionChanged: mouse => { + if (delegateItem.dragging) { + var dy = mouse.y - dragHandle.height / 2; + var newY = delegateItem.y + dy; + + // Constrain within bounds + newY = Math.max(0, Math.min(newY, root.contentHeight - delegateItem.height)); + delegateItem.y = newY; + + // Calculate target index (but don't apply yet) + var targetIndex = Math.floor((newY + delegateItem.height / 2) / (delegateItem.height + delegateItem.itemSpacing)); + targetIndex = Math.max(0, Math.min(targetIndex, repeater.count - 1)); + + delegateItem.dragTargetIndex = targetIndex; + } + } + + onReleased: { + // Always signal end of interaction + preventStealing = false; + root.dragPotentialEnded(); + + // Apply the model change now that drag is complete + if (delegateItem.dragStartIndex !== -1 && delegateItem.dragTargetIndex !== -1 && delegateItem.dragStartIndex !== delegateItem.dragTargetIndex) { + root.moveItem(delegateItem.dragStartIndex, delegateItem.dragTargetIndex); + } + + delegateItem.dragging = false; + delegateItem.dragStartIndex = -1; + delegateItem.dragTargetIndex = -1; + delegateItem.z = 0; + } + + onCanceled: { + // Handle cancel (e.g., ESC key pressed during drag) + preventStealing = false; + root.dragPotentialEnded(); + + delegateItem.dragging = false; + delegateItem.dragStartIndex = -1; + delegateItem.dragTargetIndex = -1; + delegateItem.z = 0; + } + } + } + + // Checkbox + Rectangle { + id: box + + Layout.preferredWidth: root.baseSize + Layout.preferredHeight: root.baseSize + radius: Style.iRadiusXS + color: delegateItem.itemEnabled ? root.activeColor : Color.mSurface + border.color: delegateItem.required ? root.activeColor : Color.mOutline + border.width: Style.borderS + opacity: delegateItem.required ? 0.7 : 1.0 + + Behavior on color { + ColorAnimation { + duration: Style.animationFast + } + } + + Behavior on border.color { + ColorAnimation { + duration: Style.animationFast + } + } + + NIcon { + visible: delegateItem.itemEnabled + anchors.centerIn: parent + anchors.horizontalCenterOffset: -1 + icon: "check" + color: root.activeOnColor + pointSize: Math.max(Style.fontSizeXS, root.baseSize * 0.5) + } + + MouseArea { + anchors.fill: parent + cursorShape: (!delegateItem.required && !delegateItem.isDisabled) ? Qt.PointingHandCursor : Qt.ArrowCursor + enabled: !delegateItem.required && !delegateItem.isDisabled + + onClicked: { + if (!delegateItem.required && !delegateItem.isDisabled) { + root.toggleItem(delegateItem.index); + } + } + } + } + + // Label + NText { + Layout.fillWidth: true + text: delegateItem.text + color: Color.mOnSurface + verticalAlignment: Text.AlignVCenter + elide: Text.ElideRight + } + + // Required indicator + NText { + visible: delegateItem.required + text: I18n.tr("common.required") + color: Color.mOnSurfaceVariant + verticalAlignment: Text.AlignVCenter + } + } + + // Position binding for non-dragging state + y: { + if (delegateItem.dragging) { + return delegateItem.y; + } + + // Check if any item is being dragged + var draggedIndex = -1; + var targetIndex = -1; + for (var i = 0; i < repeater.count; i++) { + var item = repeater.itemAt(i); + if (item && item.dragging) { + draggedIndex = item.dragStartIndex; + targetIndex = item.dragTargetIndex; + break; + } + } + + // If an item is being dragged, adjust positions + if (draggedIndex !== -1 && targetIndex !== -1 && draggedIndex !== targetIndex) { + var currentIndex = delegateItem.index; + + if (draggedIndex < targetIndex) { + // Dragging down: shift items up between draggedIndex and targetIndex + if (currentIndex > draggedIndex && currentIndex <= targetIndex) { + return (currentIndex - 1) * (delegateItem.height + delegateItem.itemSpacing); + } + } else { + // Dragging up: shift items down between targetIndex and draggedIndex + if (currentIndex >= targetIndex && currentIndex < draggedIndex) { + return (currentIndex + 1) * (delegateItem.height + delegateItem.itemSpacing); + } + } + } + + return delegateItem.index * (delegateItem.height + delegateItem.itemSpacing); + } + + Behavior on y { + enabled: !delegateItem.dragging + NumberAnimation { + duration: Style.animationNormal + easing.type: Easing.OutQuad + } + } + } + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NScrollText.qml b/quickshell/compat/noctalia/Widgets/NScrollText.qml new file mode 100644 index 0000000..9a9d71f --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NScrollText.qml @@ -0,0 +1,229 @@ +import QtQuick +import QtQuick.Effects +import QtQuick.Layouts +import qs.compat.noctalia.Commons + +/* +NScrollText { +NText { +pointSize: Style.fontSizeS +// here any NText properties can be used +} +maxWidth: 200 +text: "Some long long long text" +scrollMode: NScrollText.ScrollMode.Always +} +*/ + +Item { + id: root + + required property string text + default property Component delegate: NText { + pointSize: Style.fontSizeS + } + + property real maxWidth: Infinity + + enum ScrollMode { + Never = 0, + Always = 1, + Hover = 2 + } + + property int scrollMode: NScrollText.ScrollMode.Never + property bool alwaysMaxWidth: false + property bool forcedHover: false + property int cursorShape: Qt.ArrowCursor + + property real waitBeforeScrolling: 1000 + property real scrollCycleDuration: Math.max(4000, root.text.length * 120) + property real resettingDuration: 300 + + // Stepped marquee: avoids NumberAnimation.Infinite (~every vsync). ~17ms ≈ 60 updates/s. + property int scrollTickIntervalMs: 16 + + // Fade controls (fadeExtent: 0.0–0.5, fraction of width that fades) + property real fadeExtent: 0.1 + property real fadeCornerRadius: 0 + property bool fadeRoundLeftCorners: true + + readonly property real contentWidth: { + if (!titleText.item) + return 0; + const implicit = titleText.item.implicitWidth; + return implicit > 0 ? implicit : titleText.item.width; + } + readonly property real measuredWidth: scrollContainer.width + + implicitWidth: alwaysMaxWidth ? maxWidth : Math.min(maxWidth, contentWidth) + implicitHeight: titleText.height + + layer.enabled: contentWidth > maxWidth + layer.effect: MultiEffect { + maskEnabled: true + maskThresholdMin: 0.5 + maskSpreadAtMin: 1.0 + maskSource: fadeMask + } + + enum ScrollState { + None = 0, + Scrolling = 1, + Resetting = 2 + } + + property int state: NScrollText.ScrollState.None + + onTextChanged: { + if (titleText.item) + titleText.item.text = text; + if (loopingText.item) + loopingText.item.text = text; + + // reset state + resetState(); + } + onMaxWidthChanged: resetState() + onContentWidthChanged: root.updateState() + onForcedHoverChanged: updateState() + + function resetState() { + root.state = NScrollText.ScrollState.None; + scrollContainer.x = 0; + scrollTimer.restart(); + root.updateState(); + } + + Timer { + id: scrollTimer + interval: root.waitBeforeScrolling + onTriggered: { + root.state = NScrollText.ScrollState.Scrolling; + root.updateState(); + } + } + + Timer { + id: marqueeTimer + interval: root.scrollTickIntervalMs + repeat: true + running: root.state === NScrollText.ScrollState.Scrolling + onTriggered: { + const cw = titleText.width + scrollContainer.spacing; + if (cw <= 0 || root.scrollCycleDuration <= 0) + return; + const step = cw * (marqueeTimer.interval / root.scrollCycleDuration); + scrollContainer.x -= step; + if (scrollContainer.x <= -cw) + scrollContainer.x += cw; + } + } + + MouseArea { + id: hoverArea + anchors.fill: parent + hoverEnabled: true + acceptedButtons: Qt.NoButton + onEntered: root.updateState() + onExited: root.updateState() + cursorShape: root.cursorShape + } + + function ensureReset() { + if (state === NScrollText.ScrollState.Scrolling) + state = NScrollText.ScrollState.Resetting; + } + + function updateState() { + if (contentWidth <= root.maxWidth || scrollMode === NScrollText.ScrollMode.Never) { + state = NScrollText.ScrollState.None; + return; + } + if (scrollMode === NScrollText.ScrollMode.Always) { + if (hoverArea.containsMouse) { + ensureReset(); + } else { + scrollTimer.restart(); + } + } else if (scrollMode === NScrollText.ScrollMode.Hover) { + if (hoverArea.containsMouse || forcedHover) + state = NScrollText.ScrollState.Scrolling; + else + ensureReset(); + } + } + + RowLayout { + id: scrollContainer + height: parent.height + x: 0 + spacing: 50 + + Loader { + id: titleText + sourceComponent: root.delegate + Layout.fillHeight: true + onLoaded: { + this.item.text = root.text; + // Bind height to container to enable vertical centering of overly high text + this.item.height = Qt.binding(() => titleText.height); + } + } + + Loader { + id: loopingText + sourceComponent: root.delegate + Layout.fillHeight: true + visible: root.state !== NScrollText.ScrollState.None + onLoaded: { + this.item.text = root.text; + this.item.height = Qt.binding(() => loopingText.height); + } + } + + NumberAnimation on x { + running: root.state === NScrollText.ScrollState.Resetting + to: 0 + duration: root.resettingDuration + easing.type: Easing.OutQuad + onFinished: { + root.state = NScrollText.ScrollState.None; + root.updateState(); + } + } + } + + // Transparency Fade Rectangle + Rectangle { + id: fadeMask + width: root.width + height: root.height + topLeftRadius: fadeRoundLeftCorners ? fadeCornerRadius : 0 + bottomLeftRadius: fadeRoundLeftCorners ? fadeCornerRadius : 0 + topRightRadius: fadeCornerRadius + bottomRightRadius: fadeCornerRadius + gradient: Gradient { + GradientStop { + position: 0.0 + color: "transparent" + } + GradientStop { + position: fadeExtent + color: "white" + } + GradientStop { + position: 1 - fadeExtent + color: "white" + } + GradientStop { + position: 1.0 + color: "transparent" + } + orientation: Gradient.Horizontal + } + layer.enabled: true + layer.smooth: true + opacity: 0 + } +} diff --git a/quickshell/compat/noctalia/Widgets/NScrollView.qml b/quickshell/compat/noctalia/Widgets/NScrollView.qml new file mode 100644 index 0000000..d712903 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NScrollView.qml @@ -0,0 +1,280 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Templates as T +import qs.compat.noctalia.Commons + +ScrollView { + id: root + + property color handleColor: Qt.alpha(Color.mHover, 0.8) + property color handleHoverColor: handleColor + property color handlePressedColor: handleColor + property color trackColor: "transparent" + property real handleWidth: Math.round(6 * Style.uiScaleRatio) + property real handleRadius: Style.iRadiusM + property int verticalPolicy: ScrollBar.AsNeeded + property int horizontalPolicy: ScrollBar.AsNeeded + property bool preventHorizontalScroll: horizontalPolicy === ScrollBar.AlwaysOff + property int boundsBehavior: Flickable.StopAtBounds + readonly property bool verticalScrollable: (contentItem.contentHeight > contentItem.height) || (verticalPolicy == ScrollBar.AlwaysOn) + readonly property bool horizontalScrollable: (contentItem.contentWidth > contentItem.width) || (horizontalPolicy == ScrollBar.AlwaysOn) + property bool showGradientMasks: true + property color gradientColor: Color.mSurfaceVariant + property int gradientHeight: 16 + property bool reserveScrollbarSpace: true + property real userRightPadding: 0 + // Keep scrollbars visible whenever overflow exists (without forcing visibility when not scrollable) + property bool showScrollbarWhenScrollable: Settings.data.ui.scrollbarAlwaysVisible + + // Scroll speed multiplier for mouse wheel (1.0 = default, higher = faster) + property real wheelScrollMultiplier: 2.0 + property int smoothWheelAnimationDuration: Style.animationNormal + property real _wheelTargetY: 0 + + function clampScrollY(value) { + if (!root._internalFlickable) + return 0; + const flickable = root._internalFlickable; + return Math.max(0, Math.min(value, flickable.contentHeight - flickable.height)); + } + + function applyWheelScroll(delta) { + if (!root._internalFlickable) + return; + + const flickable = root._internalFlickable; + const step = delta * root.wheelScrollMultiplier; + + if (!Settings.data.general.smoothScrollEnabled || Settings.data.general.animationDisabled) { + flickable.contentY = root.clampScrollY(flickable.contentY - step); + root._wheelTargetY = flickable.contentY; + return; + } + + if (!wheelScrollAnimation.running) + root._wheelTargetY = flickable.contentY; + + root._wheelTargetY = root.clampScrollY(root._wheelTargetY - step); + wheelScrollAnimation.to = root._wheelTargetY; + wheelScrollAnimation.restart(); + } + + rightPadding: userRightPadding + (reserveScrollbarSpace && verticalScrollable ? handleWidth + Style.marginXS : 0) + + implicitWidth: Math.max(implicitBackgroundWidth + leftInset + rightInset, contentWidth + leftPadding + rightPadding) + implicitHeight: Math.max(implicitBackgroundHeight + topInset + bottomInset, contentHeight + topPadding + bottomPadding) + + // Configure the internal flickable when it becomes available + Component.onCompleted: { + configureFlickable(); + createGradients(); + } + + // Dynamically create gradient overlays to avoid interfering with ScrollView content management + function createGradients() { + if (!showGradientMasks) + return; + + Qt.createQmlObject(` + import QtQuick + import qs.compat.noctalia.Commons + Rectangle { + x: root.leftPadding + y: root.topPadding + width: root.availableWidth + height: root.gradientHeight + z: 1 + visible: root.showGradientMasks && root.verticalScrollable + opacity: root.contentItem.contentY <= 1 ? 0 : 1 + Behavior on opacity { + NumberAnimation { duration: Style.animationFast; easing.type: Easing.InOutQuad } + } + gradient: Gradient { + GradientStop { position: 0.0; color: root.gradientColor } + GradientStop { position: 1.0; color: "transparent" } + } + } + `, root, "topGradient"); + + Qt.createQmlObject(` + import QtQuick + import qs.compat.noctalia.Commons + Rectangle { + x: root.leftPadding + y: root.height - root.bottomPadding - height + 1 + width: root.availableWidth + height: root.gradientHeight + 1 + z: 1 + visible: root.showGradientMasks && root.verticalScrollable + opacity: (root.contentItem.contentY + root.contentItem.height >= root.contentItem.contentHeight - 1) ? 0 : 1 + Behavior on opacity { + NumberAnimation { duration: Style.animationFast; easing.type: Easing.InOutQuad } + } + gradient: Gradient { + GradientStop { position: 0.0; color: "transparent" } + GradientStop { position: 1.0; color: root.gradientColor } + } + } + `, root, "bottomGradient"); + } + + // Reference to the internal Flickable for wheel handling + property Flickable _internalFlickable: null + + NumberAnimation { + id: wheelScrollAnimation + target: root._internalFlickable + property: "contentY" + duration: root.smoothWheelAnimationDuration + easing.type: Easing.OutCubic + } + + Connections { + target: root._internalFlickable + + function onDraggingChanged() { + if (!root._internalFlickable || !root._internalFlickable.dragging) + return; + wheelScrollAnimation.stop(); + root._wheelTargetY = root._internalFlickable.contentY; + } + + function onFlickingChanged() { + if (!root._internalFlickable || !root._internalFlickable.flicking) + return; + wheelScrollAnimation.stop(); + root._wheelTargetY = root._internalFlickable.contentY; + } + + function onContentHeightChanged() { + root._wheelTargetY = root.clampScrollY(root._wheelTargetY); + } + + function onHeightChanged() { + root._wheelTargetY = root.clampScrollY(root._wheelTargetY); + } + } + + // Function to configure the underlying Flickable + function configureFlickable() { + // Find the internal Flickable (it's usually the first child) + for (var i = 0; i < children.length; i++) { + var child = children[i]; + if (child.toString().indexOf("Flickable") !== -1) { + // Configure the flickable to prevent horizontal scrolling + child.boundsBehavior = root.boundsBehavior; + root._internalFlickable = child; + + if (root.preventHorizontalScroll) { + child.flickableDirection = Flickable.VerticalFlick; + child.contentWidth = Qt.binding(() => child.width); + } + + root._wheelTargetY = child.contentY; + break; + } + } + } + + WheelHandler { + enabled: root.wheelScrollMultiplier !== 1.0 && root._internalFlickable !== null + acceptedDevices: PointerDevice.Mouse | PointerDevice.TouchPad + onWheel: event => { + const delta = event.pixelDelta.y !== 0 ? event.pixelDelta.y : event.angleDelta.y / 2; + root.applyWheelScroll(delta); + event.accepted = true; + } + } + + // Watch for changes in horizontalPolicy + onHorizontalPolicyChanged: { + preventHorizontalScroll = (horizontalPolicy === ScrollBar.AlwaysOff); + configureFlickable(); + } + + ScrollBar.vertical: ScrollBar { + parent: root + x: root.mirrored ? 0 : root.width - width + y: root.topPadding + height: root.availableHeight + policy: root.verticalPolicy + interactive: root.verticalScrollable + + contentItem: Rectangle { + implicitWidth: root.handleWidth + implicitHeight: 100 + radius: root.handleRadius + color: parent.pressed ? root.handlePressedColor : parent.hovered ? root.handleHoverColor : root.handleColor + opacity: parent.policy === ScrollBar.AlwaysOn ? 1.0 : root.verticalScrollable ? ((root.showScrollbarWhenScrollable || parent.active) ? 1.0 : 0.0) : 0.0 + + Behavior on opacity { + NumberAnimation { + duration: Style.animationFast + } + } + + Behavior on color { + ColorAnimation { + duration: Style.animationFast + } + } + } + + background: Rectangle { + implicitWidth: root.handleWidth + implicitHeight: 100 + color: root.trackColor + opacity: parent.policy === ScrollBar.AlwaysOn ? 0.3 : root.verticalScrollable ? ((root.showScrollbarWhenScrollable || parent.active) ? 0.3 : 0.0) : 0.0 + radius: root.handleRadius / 2 + + Behavior on opacity { + NumberAnimation { + duration: Style.animationFast + } + } + } + } + + ScrollBar.horizontal: ScrollBar { + parent: root + x: root.leftPadding + y: root.height - height + width: root.availableWidth + policy: root.horizontalPolicy + interactive: root.horizontalScrollable + + contentItem: Rectangle { + implicitWidth: 100 + implicitHeight: root.handleWidth + radius: root.handleRadius + color: parent.pressed ? root.handlePressedColor : parent.hovered ? root.handleHoverColor : root.handleColor + opacity: parent.policy === ScrollBar.AlwaysOn ? 1.0 : root.horizontalScrollable ? ((root.showScrollbarWhenScrollable || parent.active) ? 1.0 : 0.0) : 0.0 + + Behavior on opacity { + NumberAnimation { + duration: Style.animationFast + } + } + + Behavior on color { + ColorAnimation { + duration: Style.animationFast + } + } + } + + background: Rectangle { + implicitWidth: 100 + implicitHeight: root.handleWidth + color: root.trackColor + opacity: parent.policy === ScrollBar.AlwaysOn ? 0.3 : root.horizontalScrollable ? ((root.showScrollbarWhenScrollable || parent.active) ? 0.3 : 0.0) : 0.0 + radius: root.handleRadius / 2 + + Behavior on opacity { + NumberAnimation { + duration: Style.animationFast + } + } + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NSearchableComboBox.qml b/quickshell/compat/noctalia/Widgets/NSearchableComboBox.qml new file mode 100644 index 0000000..34b9f32 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NSearchableComboBox.qml @@ -0,0 +1,436 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Widgets + +RowLayout { + id: root + + property real minimumWidth: 280 + property real popupHeight: 180 + + property bool selectOnNavigation: true + property string label: "" + property string description: "" + property ListModel model: {} + property string currentKey: "" + property string placeholder: "" + property string searchPlaceholder: I18n.tr("placeholders.search") + property Component delegate: null + property var defaultValue: undefined + property string settingsPath: "" + + readonly property real preferredHeight: Math.round(Style.baseWidgetSize * 1.1) + + signal selected(string key) + + spacing: Style.marginL + Layout.fillWidth: true + + readonly property bool isValueChanged: (defaultValue !== undefined) && (currentKey !== defaultValue) + readonly property string indicatorTooltip: { + if (defaultValue === undefined) + return ""; + var displayValue = ""; + if (defaultValue === "") { + // Try to find the display name for empty key in the model + if (model && model.count > 0) { + for (var i = 0; i < model.count; i++) { + var item = model.get(i); + if (item && item.key === "") { + displayValue = item.name || I18n.tr("panels.indicator.system-default"); + break; + } + } + // If not found in model, show "System Default" instead of "(empty)" + if (displayValue === "") { + displayValue = I18n.tr("panels.indicator.system-default"); + } + } else { + displayValue = I18n.tr("panels.indicator.system-default"); + } + } else { + // Try to find the display name for the default key in the model + if (model && model.count > 0) { + for (var i = 0; i < model.count; i++) { + var item = model.get(i); + if (item && item.key === defaultValue) { + displayValue = item.name || String(defaultValue); + break; + } + } + if (displayValue === "") { + displayValue = String(defaultValue); + } + } else { + displayValue = String(defaultValue); + } + } + return I18n.tr("panels.indicator.default-value", { + "value": displayValue + }); + } + + // Filtered model for search results + property ListModel filteredModel: ListModel {} + property string searchText: "" + + function findIndexByKey(key) { + if (!root.model) + return -1; + for (var i = 0; i < root.model.count; i++) { + if (root.model.get(i).key === key) { + return i; + } + } + return -1; + } + + // The active model used for the popup list (source model or filtered results) + readonly property var activeModel: isFiltered ? filteredModel : root.model + + function findIndexInActiveModel(key) { + if (!activeModel || activeModel.count === undefined) + return -1; + for (var i = 0; i < activeModel.count; i++) { + if (activeModel.get(i).key === key) { + return i; + } + } + return -1; + } + + // Whether we're using filtered results or the source model directly + property bool isFiltered: false + + function filterModel() { + // Check if model exists and has items + if (!root.model || root.model.count === undefined || root.model.count === 0) { + filteredModel.clear(); + isFiltered = false; + return; + } + + var query = searchText.trim(); + if (query === "") { + // No search text - use source model directly, don't copy + filteredModel.clear(); + isFiltered = false; + return; + } + + // We have search text - need to filter + isFiltered = true; + filteredModel.clear(); + + // Convert ListModel to array for fuzzy search + var items = []; + for (var i = 0; i < root.model.count; i++) { + items.push(root.model.get(i)); + } + + // Use fuzzy search if available, fallback to simple search + if (typeof FuzzySort !== 'undefined') { + var fuzzyResults = FuzzySort.go(query, items, { + "key": "name", + "limit": 50 + }); + + // Add results in order of relevance + for (var j = 0; j < fuzzyResults.length; j++) { + filteredModel.append(fuzzyResults[j].obj); + } + } else { + // Fallback to simple search + var searchLower = query.toLowerCase(); + for (var i = 0; i < items.length; i++) { + var item = items[i]; + if (item.name.toLowerCase().includes(searchLower)) { + filteredModel.append(item); + } + } + } + } + + onSearchTextChanged: { + filterModel(); + listView.currentIndex = 0; + } + + NLabel { + label: root.label + description: root.description + showIndicator: root.isValueChanged + indicatorTooltip: root.indicatorTooltip + } + + Item { + Layout.fillWidth: true + } + + ComboBox { + id: combo + + opacity: enabled ? 1.0 : 0.6 + Layout.margins: Style.borderS + Layout.minimumWidth: Math.round(root.minimumWidth * Style.uiScaleRatio) + Layout.preferredHeight: Math.round(root.preferredHeight * Style.uiScaleRatio) + implicitWidth: Layout.minimumWidth + model: root.activeModel + textRole: "name" + currentIndex: findIndexInActiveModel(currentKey) + onActivated: { + if (combo.currentIndex >= 0 && root.activeModel && combo.currentIndex < root.activeModel.count) { + root.selected(root.activeModel.get(combo.currentIndex).key); + } + } + + background: Rectangle { + implicitWidth: Math.round(Style.baseWidgetSize * 3.75 * Style.uiScaleRatio) + implicitHeight: Math.round(root.preferredHeight * Style.uiScaleRatio) + color: Color.mSurface + border.color: combo.activeFocus ? Color.mSecondary : Color.mOutline + border.width: Style.borderS + radius: Style.iRadiusM + + Behavior on border.color { + ColorAnimation { + duration: Style.animationFast + } + } + } + + contentItem: NText { + leftPadding: Style.marginL + rightPadding: combo.indicator.width + Style.marginL + pointSize: Style.fontSizeM + verticalAlignment: Text.AlignVCenter + elide: Text.ElideRight + + // Look up current selection directly in source model by key + readonly property int sourceIndex: root.findIndexByKey(root.currentKey) + readonly property bool hasSelection: root.model && sourceIndex >= 0 && sourceIndex < root.model.count + + color: hasSelection ? Color.mOnSurface : Color.mOnSurfaceVariant + text: hasSelection ? root.model.get(sourceIndex).name : root.placeholder + } + + indicator: NIcon { + x: combo.width - width - Style.marginM + y: combo.topPadding + (combo.availableHeight - height) / 2 + icon: "caret-down" + pointSize: Style.fontSizeL + } + + popup: Popup { + y: combo.height + Style.marginS + width: combo.width + height: Math.round((root.popupHeight + 60) * Style.uiScaleRatio) + padding: Style.marginM + + contentItem: ColumnLayout { + spacing: Style.marginS + + // Search input + NTextInput { + id: searchInput + inputIconName: "search" + Layout.fillWidth: true + placeholderText: root.searchPlaceholder + text: root.searchText + onTextChanged: root.searchText = text + fontSize: Style.fontSizeS + + Keys.onPressed: event => { + if (Keybinds.checkKey(event, 'enter', Settings)) { + selectHighlighted(); + combo.popup.close(); + event.accepted = true; + return; + } + + if (Keybinds.checkKey(event, 'escape', Settings)) { + combo.popup.close(); + event.accepted = true; + return; + } + + if (Keybinds.checkKey(event, 'up', Settings)) { + if (listView.currentIndex > 0) { + listView.currentIndex--; + if (root.selectOnNavigation) + selectHighlighted(); + } + event.accepted = true; + return; + } + + if (Keybinds.checkKey(event, 'down', Settings)) { + if (listView.currentIndex < listView.count - 1) { + listView.currentIndex++; + if (root.selectOnNavigation) + selectHighlighted(); + } + event.accepted = true; + return; + } + } + + function selectHighlighted() { + if (listView.currentIndex >= 0 && listView.model && listView.currentIndex < listView.model.count) { + var selectedKey = listView.model.get(listView.currentIndex).key; + root.selected(selectedKey); + } + } + } + + NListView { + id: listView + Layout.fillWidth: true + Layout.fillHeight: true + // Use activeModel (source model when not filtering, filtered results when searching) + model: combo.popup.visible ? root.activeModel : null + horizontalPolicy: ScrollBar.AlwaysOff + verticalPolicy: ScrollBar.AsNeeded + + onCurrentIndexChanged: { + if (currentIndex >= 0) + positionViewAtIndex(currentIndex, ListView.Contain); + } + + delegate: root.delegate ? root.delegate : defaultDelegate + + Component { + id: defaultDelegate + ItemDelegate { + id: delegateRoot + width: listView.availableWidth + leftPadding: Style.marginM + rightPadding: Style.marginM + topPadding: Style.marginS + bottomPadding: Style.marginS + hoverEnabled: true + highlighted: ListView.view.currentIndex === index + + onHoveredChanged: { + if (hovered) { + ListView.view.currentIndex = index; + } + } + + onClicked: { + var selectedKey = listView.model.get(index).key; + root.selected(selectedKey); + combo.popup.close(); + } + + contentItem: RowLayout { + width: delegateRoot.width - delegateRoot.leftPadding - delegateRoot.rightPadding + spacing: Style.marginM + + NText { + text: name + pointSize: Style.fontSizeM + color: highlighted ? Color.mOnHover : Color.mOnSurface + verticalAlignment: Text.AlignVCenter + elide: Text.ElideRight + Layout.fillWidth: true + } + + RowLayout { + spacing: Style.marginXXS + Layout.alignment: Qt.AlignRight + + // Generic badge renderer + Repeater { + model: { + if (typeof badges === 'undefined' || badges === null) + return 0; + // Handle both arrays and ListModels + if (typeof badges.length !== 'undefined') + return badges.length; + if (typeof badges.count !== 'undefined') + return badges.count; + return 0; + } + + delegate: NIcon { + required property int index + readonly property var badgeData: { + if (typeof badges === 'undefined' || badges === null) + return null; + // Handle both arrays and ListModels + if (typeof badges.length !== 'undefined') + return badges[index]; + if (typeof badges.get !== 'undefined') + return badges.get(index); + return null; + } + + icon: badgeData && badgeData.icon ? badgeData.icon : "" + pointSize: { + if (!badgeData || !badgeData.size) + return Style.fontSizeXS; + if (badgeData.size === "xsmall") + return Style.fontSizeXXS; + else if (badgeData.size === "medium") + return Style.fontSizeM; + else + return Style.fontSizeXS; + } + color: highlighted ? Color.mOnHover : (badgeData && badgeData.color ? badgeData.color : Color.mOnSurface) + Layout.preferredWidth: Math.round(Style.baseWidgetSize * 0.6) + Layout.preferredHeight: Math.round(Style.baseWidgetSize * 0.6) + visible: badgeData && badgeData.icon !== undefined && badgeData.icon !== "" + } + } + } + } + background: Rectangle { + anchors.fill: parent + color: highlighted ? Color.mHover : "transparent" + radius: Style.iRadiusS + } + } + } + } + } + + background: Rectangle { + color: Color.mSurfaceVariant + border.color: Color.mOutline + border.width: Style.borderS + radius: Style.iRadiusM + } + } + + // Update the currentIndex if the currentKey is changed externally + Connections { + target: root + function onCurrentKeyChanged() { + combo.currentIndex = root.findIndexInActiveModel(root.currentKey); + } + } + + // Focus search input when popup opens and ensure model is filtered + Connections { + target: combo.popup + function onVisibleChanged() { + if (combo.popup.visible) { + // Ensure the model is filtered when popup opens + filterModel(); + listView.currentIndex = Math.max(0, root.findIndexInActiveModel(root.currentKey)); + // Small delay to ensure the popup is fully rendered + Qt.callLater(() => { + if (searchInput && searchInput.inputItem) { + searchInput.inputItem.forceActiveFocus(); + } + }); + } else { + root.searchText = ""; + } + } + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NSectionEditor.qml b/quickshell/compat/noctalia/Widgets/NSectionEditor.qml new file mode 100644 index 0000000..b9bcf9f --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NSectionEditor.qml @@ -0,0 +1,958 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Effects +import QtQuick.Layouts +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Services.Noctalia +import qs.compat.noctalia.Widgets + +NBox { + id: root + + property string sectionName: "" + property string sectionSubtitle: "" + property string sectionId: "" + property var widgetModel: [] + property var availableWidgets: [] + property var availableSections: ["left", "center", "right"] + property var sectionLabels: ({}) // Map of sectionId -> display label + property var sectionIcons: ({}) // Map of sectionId -> icon name + property bool barIsVertical: false // When true, map left/right to top/bottom in labels + property int maxWidgets: -1 // -1 means unlimited + property bool draggable: true // Enable/disable drag reordering + property bool crossSectionDraggable: false + property alias dropTargetArea: gridContainer + + // Get display label for a section + function getSectionLabel(sectionId) { + if (sectionLabels && sectionLabels[sectionId]) { + return sectionLabels[sectionId]; + } + return sectionId; // Fallback to section ID + } + + // Get icon for a section + function getSectionIcon(sectionId) { + if (sectionIcons && sectionIcons[sectionId]) { + return sectionIcons[sectionId]; + } + return "arrow-right"; // Default fallback icon + } + + property var pluginSettingsEntryPoints: ["settings"] + property var widgetRegistry: null + property string settingsDialogComponent: "invalid-settings-dialog" + property var screen: null // Screen reference for per-screen widget settings + property var _activeDialog: null + property bool crossDropHoverActive: false + + function clearCrossSectionHover() { + crossDropHoverActive = false; + + var parentItem = root.parent; + if (!parentItem || !parentItem.children) { + return; + } + + for (var i = 0; i < parentItem.children.length; i++) { + var candidate = parentItem.children[i]; + if (!candidate || candidate.crossDropHoverActive === undefined) + continue; + candidate.crossDropHoverActive = false; + } + } + + function updateCrossSectionHover(globalX, globalY) { + var parentItem = root.parent; + if (!parentItem || !parentItem.children) { + crossDropHoverActive = false; + return; + } + + crossDropHoverActive = false; + + for (var i = 0; i < parentItem.children.length; i++) { + var candidate = parentItem.children[i]; + if (!candidate || candidate.sectionId === undefined || candidate.crossDropHoverActive === undefined) { + continue; + } + + var shouldHighlight = false; + if (candidate !== root && candidate.visible && candidate.enabled) { + var localPoint = candidate.mapFromGlobal(globalX, globalY); + var area = candidate.dropTargetArea ? candidate.dropTargetArea : candidate; + shouldHighlight = localPoint.x >= area.x && localPoint.y >= area.y && localPoint.x <= area.x + area.width && localPoint.y <= area.y + area.height; + } + + candidate.crossDropHoverActive = shouldHighlight; + } + } + + function isPointInsideSelf(globalX, globalY) { + if (globalX < 0 || globalY < 0) + return false; + var localPoint = root.mapFromGlobal(globalX, globalY); + return localPoint.x >= 0 && localPoint.y >= 0 && localPoint.x <= root.width && localPoint.y <= root.height; + } + + readonly property bool showCrossSectionDropHint: crossDropHoverActive + + Component.onDestruction: { + if (_activeDialog && _activeDialog.close) { + var dialog = _activeDialog; + _activeDialog = null; + dialog.close(); + dialog.destroy(); + } + } + + readonly property int gridColumns: 3 + readonly property real miniButtonSize: Style.baseWidgetSize * 0.65 + readonly property bool isAtMaxCapacity: maxWidgets >= 0 && widgetModel.length >= maxWidgets + readonly property real widgetItemHeight: Style.baseWidgetSize * 1.3 * Style.uiScaleRatio + + signal addWidget(string widgetId, string section) + signal removeWidget(string section, int index) + signal reorderWidget(string section, int fromIndex, int toIndex) + signal updateWidgetSettings(string section, int index, var settings) + signal moveWidget(string fromSection, int index, string toSection) + signal dragPotentialStarted + signal dragPotentialEnded + signal openPluginSettingsRequested(var pluginManifest, string settingsEntryPoint) + + color: Color.mSurface + Layout.fillWidth: true + z: flowDragArea.dragStarted ? 5000 : 0 + + // Calculate width to fit gridColumns widgets with spacing + function calculateWidgetWidth(gridWidth) { + var columnSpacing = (root.gridColumns - 1) * Style.marginM; + var widgetWidth = (gridWidth - columnSpacing) / root.gridColumns; + return Math.floor(widgetWidth); + } + + function findSectionAtGlobalPosition(globalX, globalY) { + var parentItem = root.parent; + if (!parentItem || !parentItem.children) { + return ""; + } + + for (var i = 0; i < parentItem.children.length; i++) { + var candidate = parentItem.children[i]; + if (!candidate || candidate === root) { + continue; + } + + // Only consider sibling section editors + if (candidate.sectionId === undefined || !candidate.visible || !candidate.enabled) { + continue; + } + + var localPoint = candidate.mapFromGlobal(globalX, globalY); + var area = candidate.dropTargetArea ? candidate.dropTargetArea : candidate; + if (localPoint.x >= area.x && localPoint.y >= area.y && localPoint.x <= area.x + area.width && localPoint.y <= area.y + area.height) { + return candidate.sectionId; + } + } + + return ""; + } + + Layout.minimumHeight: { + // header + minimal content area + var absoluteMin = Style.margin2L + (Style.fontSizeL * 2) + Style.marginM + (65 * Style.uiScaleRatio); + + var widgetCount = widgetModel.length; + if (widgetCount === 0) { + return absoluteMin; + } + + // Calculate rows based on grid layout + // Use actual parent width if available, otherwise estimate + var availableWidth = (parent && parent.width > 0) ? (parent.width - Style.margin2L) : 400; + var rows = Math.ceil(widgetCount / root.gridColumns); + + // Calculate widget width for height calculation + var containerWidth = availableWidth; + var widgetWidth = calculateWidgetWidth(containerWidth); + + // Header height + spacing + (rows * widget height) + (spacing between rows) + margins + var headerHeight = Style.fontSizeL * 2; + // Account for grid margins + var gridTopMargin = Style.marginS; + var gridBottomMargin = Style.marginL; + var widgetAreaHeight = gridTopMargin + (rows * widgetItemHeight) + ((rows - 1) * Style.marginL) + gridBottomMargin; + + return Math.max(absoluteMin, Style.margin2L + headerHeight + Style.marginM + widgetAreaHeight); + } + + // Generate widget color from name checksum + function getWidgetColor(widget) { + if (widget.id.startsWith('plugin:')) { + return [Color.mSecondary, Color.mOnSecondary]; + } + return [Color.mPrimary, Color.mOnPrimary]; + } + + // Check if widget has settings (either core widget with metadata or plugin with settings entry point) + function widgetHasSettings(widgetId) { + // Check if it's a plugin with settings + if (root.widgetRegistry && root.widgetRegistry.isPluginWidget(widgetId)) { + var pluginId = widgetId.replace("plugin:", ""); + var manifest = PluginRegistry.getPluginManifest(pluginId); + if (!manifest?.entryPoints) + return false; + for (var i = 0; i < root.pluginSettingsEntryPoints.length; i++) { + if (manifest.entryPoints[root.pluginSettingsEntryPoints[i]] !== undefined) + return true; + } + return false; + } + + // Check if it's a core widget with user settings + if (root.widgetRegistry && root.widgetRegistry.widgetHasUserSettings(widgetId)) { + return true; + } + + return false; + } + + // Open settings for a widget + function openWidgetSettings(index, widgetData) { + // Check if this is a plugin widget with a generic "settings" entry point + var isPlugin = root.widgetRegistry && root.widgetRegistry.isPluginWidget(widgetData.id); + + if (isPlugin) { + var pluginId = widgetData.id.replace("plugin:", ""); + var manifest = PluginRegistry.getPluginManifest(pluginId); + + var settingsKey = null; + if (manifest?.entryPoints) { + for (var i = 0; i < root.pluginSettingsEntryPoints.length; i++) { + if (manifest.entryPoints[root.pluginSettingsEntryPoints[i]] !== undefined) { + settingsKey = root.pluginSettingsEntryPoints[i]; + break; + } + } + } + if (!manifest || !settingsKey) { + Logger.e("NSectionEditor", "Plugin settings not found for:", pluginId); + return; + } + + // "desktopWidgetSettings" is handled by the settingsDialogComponent + // (DesktopWidgetSettingsDialog) which passes widgetSettings/save properly. + // Only generic "settings" goes through the plugin settings popup. + if (settingsKey !== "desktopWidgetSettings") { + root.openPluginSettingsRequested(manifest, settingsKey); + return; + } + } + + // Handle core widgets and plugin desktop widget settings + { + var component = Qt.createComponent(Qt.resolvedUrl(root.settingsDialogComponent)); + + function instantiateAndOpen() { + if (root._activeDialog) { + try { + root._activeDialog.close(); + root._activeDialog.destroy(); + } catch (e) {} + root._activeDialog = null; + } + + var dialog = component.createObject(Overlay.overlay, { + "widgetIndex": index, + "widgetData": widgetData, + "widgetId": widgetData.id, + "sectionId": root.sectionId, + "screen": root.screen, + "barIsVertical": root.barIsVertical + }); + + if (dialog) { + root._activeDialog = dialog; + dialog.updateWidgetSettings.connect(root.updateWidgetSettings); + dialog.closed.connect(() => { + if (root._activeDialog === dialog) { + root._activeDialog = null; + dialog.destroy(); + } + }); + dialog.open(); + } else { + Logger.e("NSectionEditor", "Failed to create settings dialog instance"); + } + } + + if (component.status === Component.Ready) { + instantiateAndOpen(); + } else if (component.status === Component.Error) { + Logger.e("NSectionEditor", component.errorString()); + } else { + component.statusChanged.connect(function () { + if (component.status === Component.Ready) { + instantiateAndOpen(); + } else if (component.status === Component.Error) { + Logger.e("NSectionEditor", component.errorString()); + } + }); + } + } + } + + ColumnLayout { + anchors.fill: parent + anchors.margins: Style.marginL + spacing: Style.marginM + + RowLayout { + Layout.fillWidth: true + Layout.rightMargin: Style.marginS + + ColumnLayout { + spacing: Style.marginXXS + Layout.alignment: Qt.AlignVCenter + Layout.fillWidth: false + Layout.leftMargin: Style.marginS + Layout.maximumWidth: { + // Reserve space for other elements: count indicator, combo box (~200), button (~50), and margins + // Use a reasonable maximum that leaves room for controls on the right + // On smaller screens, use a smaller percentage to ensure controls fit + var rowLayout = parent; + if (rowLayout && rowLayout.width > 0) { + // Use smaller percentage on smaller screens, but ensure minimum space for text + var minWidth = 150 * Style.uiScaleRatio; + var maxWidth = rowLayout.width < 600 ? rowLayout.width * 0.35 : rowLayout.width * 0.4; + return Math.max(minWidth, maxWidth); + } + return 250 * Style.uiScaleRatio; + } + + NText { + text: sectionName + pointSize: Style.fontSizeL + font.weight: Style.fontWeightBold + color: Color.mOnSurface + elide: Text.ElideRight + Layout.fillWidth: true + } + + NText { + visible: sectionSubtitle !== "" + text: sectionSubtitle + pointSize: Style.fontSizeS + color: Color.mOnSurfaceVariant + elide: Text.ElideRight + Layout.fillWidth: true + } + } + + // Widget count indicator (when max is set) + NText { + visible: root.maxWidgets >= 0 + text: root.maxWidgets === 0 ? "(LOCKED)" : "(" + widgetModel.length + "/" + root.maxWidgets + ")" + pointSize: Style.fontSizeS + color: root.isAtMaxCapacity ? Color.mError : Color.mOnSurfaceVariant + Layout.alignment: Qt.AlignVCenter + Layout.leftMargin: Style.marginXS + } + + Item { + Layout.fillWidth: true + } + + NSearchableComboBox { + id: comboBox + model: availableWidgets ?? null + label: "" + description: "" + placeholder: I18n.tr("bar.section-editor.placeholder") + searchPlaceholder: I18n.tr("bar.section-editor.search-placeholder") + onSelected: key => comboBox.currentKey = key + popupHeight: 300 * Style.uiScaleRatio + minimumWidth: 200 * Style.uiScaleRatio + enabled: !root.isAtMaxCapacity + + Layout.alignment: Qt.AlignVCenter + + // Re-filter when the model count changes (when widgets are loaded) + Connections { + target: availableWidgets ?? null + ignoreUnknownSignals: true + function onCountChanged() { + // Trigger a re-filter by clearing and re-setting the search text + var currentSearch = comboBox.searchText; + comboBox.searchText = ""; + comboBox.searchText = currentSearch; + } + } + } + + NIconButton { + icon: "add" + colorBg: Color.mPrimary + colorFg: Color.mOnPrimary + colorBgHover: Color.mSecondary + colorFgHover: Color.mOnSecondary + enabled: comboBox.currentKey !== "" && !root.isAtMaxCapacity + tooltipText: root.isAtMaxCapacity ? I18n.tr("tooltips.max-widgets-reached") : I18n.tr("tooltips.add-widget") + Layout.alignment: Qt.AlignVCenter + Layout.leftMargin: Style.marginS + onClicked: { + if (comboBox.currentKey !== "" && !root.isAtMaxCapacity) { + addWidget(comboBox.currentKey, sectionId); + comboBox.currentKey = ""; + } + } + } + } + + // Drag and Drop Widget Area + Item { + id: gridContainer + Layout.fillWidth: true + Layout.preferredHeight: { + if (widgetModel.length === 0) { + return 65 * Style.uiScaleRatio; + } + // Use actual width, fallback to a reasonable default if not yet available + var containerWidth = width > 0 ? width : (parent ? parent.width : 400); + var rows = Math.ceil(widgetModel.length / root.gridColumns); + // Calculate height: (rows * item height) + (row spacing between items) + grid margins + var gridTopMargin = Style.marginS; + var gridBottomMargin = Style.marginS; + var calculatedHeight = gridTopMargin + (rows * root.widgetItemHeight) + ((rows - 1) * Style.marginS) + gridBottomMargin; + return calculatedHeight; + } + Layout.minimumHeight: widgetModel.length === 0 ? (65 * Style.uiScaleRatio) : (Style.margin2S + root.widgetItemHeight) + clip: !flowDragArea.dragStarted + + Rectangle { + anchors.fill: parent + radius: Style.iRadiusL + color: Qt.alpha(Color.mSecondary, 0.12) + border.color: Color.mSecondary + border.width: Style.borderM + visible: root.showCrossSectionDropHint + z: 1500 + } + + Grid { + id: widgetGrid + anchors.left: parent.left + anchors.right: parent.right + anchors.top: parent.top + anchors.bottom: parent.bottom + anchors.leftMargin: Style.marginS + anchors.rightMargin: Style.marginS + anchors.topMargin: Style.marginS + anchors.bottomMargin: Style.marginS + columns: root.gridColumns + rowSpacing: Style.marginS + columnSpacing: Style.marginM + + Repeater { + id: widgetRepeater + model: widgetModel + + delegate: Rectangle { + id: widgetItem + required property int index + required property var modelData + + width: root.calculateWidgetWidth(parent.width) + height: root.widgetItemHeight + radius: Style.iRadiusL + color: root.getWidgetColor(modelData)[0] + border.color: Color.mOutline + border.width: Style.borderS + + // Store the widget index for drag operations + property int widgetIndex: index + readonly property int buttonsWidth: Math.round(20) + readonly property int buttonsCount: root.widgetHasSettings(modelData.id) ? 1 : 0 + + // Visual feedback during drag + opacity: flowDragArea.draggedIndex === index ? 0.5 : 1.0 + scale: flowDragArea.draggedIndex === index ? 0.95 : 1.0 + z: flowDragArea.draggedIndex === index ? 1000 : 0 + + Behavior on opacity { + NumberAnimation { + duration: Style.animationFast + } + } + Behavior on scale { + NumberAnimation { + duration: Style.animationFast + } + } + + // Context menu for moving widget to other sections + NContextMenu { + id: contextMenu + parent: Overlay.overlay + width: 240 * Style.uiScaleRatio + model: { + var items = []; + // Add move options for each available section (except current) + for (var i = 0; i < root.availableSections.length; i++) { + var section = root.availableSections[i]; + if (section !== root.sectionId) { + var label = root.getSectionLabel(section); + var displayLabel = ''; + // Map section IDs to correct position keys based on bar orientation + var positionKey = section; + if (root.barIsVertical) { + if (section === "left") + positionKey = "top"; + else if (section === "right") + positionKey = "bottom"; + } + if (I18n.hasTranslation("positions." + positionKey)) { + displayLabel = I18n.tr("positions." + positionKey); + } else { + displayLabel = label.charAt(0).toUpperCase() + label.slice(1); + } + + items.push({ + "label": I18n.tr("tooltips.move-to-section", { + "section": displayLabel + }), + "action": section, + "icon": root.getSectionIcon(section), + "visible": true + }); + } + } + // Add remove option + items.push({ + "label": I18n.tr("tooltips.remove-widget"), + "action": "remove", + "icon": "trash", + "visible": true + }); + return items; + } + + onTriggered: action => { + if (action === "remove") { + root.removeWidget(root.sectionId, widgetItem.index); + } else { + root.moveWidget(root.sectionId, widgetItem.index, action); + } + } + } + + // MouseArea for the context menu - only active when not dragging + MouseArea { + id: contextMouseArea + anchors.fill: parent + acceptedButtons: Qt.RightButton + cursorShape: Qt.PointingHandCursor + z: -1 // Below the buttons but above background + enabled: !flowDragArea.dragStarted && !flowDragArea.potentialDrag + + onPressed: mouse => { + mouse.accepted = true; + // Check if click is not on the settings button area (if visible) + const localX = mouse.x; + const buttonsStartX = parent.width - (parent.buttonsCount * parent.buttonsWidth); + if (localX < buttonsStartX || parent.buttonsCount === 0) { + contextMenu.openAtItem(widgetItem, mouse.x, mouse.y); + } + } + } + + RowLayout { + id: widgetContent + anchors.fill: parent + anchors.margins: Style.marginXS + anchors.rightMargin: Style.marginS + spacing: Style.marginXXS + + NText { + text: { + // For plugin widgets, get the actual plugin name from manifest + if (root.widgetRegistry && root.widgetRegistry.isPluginWidget(modelData.id)) { + const pluginId = modelData.id.replace("plugin:", ""); + const manifest = PluginRegistry.getPluginManifest(pluginId); + if (manifest && manifest.name) { + return manifest.name; + } + // Fallback: just strip the prefix + return pluginId; + } + return modelData.id; + } + pointSize: Style.fontSizeXS + color: root.getWidgetColor(modelData)[1] + horizontalAlignment: Text.AlignLeft + verticalAlignment: Text.AlignVCenter + elide: Text.ElideRight + leftPadding: Style.marginS + rightPadding: Style.marginS + Layout.fillWidth: true + Layout.fillHeight: true + } + + // Plugin indicator icon + NIcon { + visible: root.widgetRegistry && root.widgetRegistry.isPluginWidget(modelData.id) + icon: "plugin" + pointSize: Style.fontSizeXXS + color: root.getWidgetColor(modelData)[1] + Layout.preferredWidth: visible ? Style.baseWidgetSize * 0.5 : 0 + Layout.preferredHeight: Style.baseWidgetSize * 0.5 + } + + // CPU intensive indicator icon + NIcon { + visible: root.widgetRegistry && root.widgetRegistry.isCpuIntensive(modelData.id) + icon: "cpu-intensive" + pointSize: Style.fontSizeXXS + color: root.getWidgetColor(modelData)[1] + Layout.preferredWidth: visible ? Style.baseWidgetSize * 0.5 : 0 + Layout.preferredHeight: Style.baseWidgetSize * 0.5 + } + + RowLayout { + spacing: 0 + Layout.preferredWidth: buttonsCount * buttonsWidth * Style.uiScaleRatio + Layout.preferredHeight: parent.height + + Loader { + active: root.widgetHasSettings(modelData.id) && root.enabled + sourceComponent: NIconButton { + icon: "settings" + tooltipText: I18n.tr("actions.widget-settings") + baseSize: miniButtonSize + colorBorder: Qt.alpha(Color.mOutline, Style.opacityLight) + colorBg: Color.mOnSurface + colorFg: Color.mOnPrimary + colorBgHover: Qt.alpha(Color.mOnPrimary, Style.opacityLight) + colorFgHover: Color.mOnPrimary + onClicked: { + root.openWidgetSettings(index, modelData); + } + } + } + } + } + } + } + } + + // Ghost/Clone widget for dragging + Rectangle { + id: dragGhost + width: 0 + height: Style.baseWidgetSize * 1.15 + radius: Style.iRadiusL + color: "transparent" + border.color: Color.mOutline + border.width: Style.borderS + opacity: 0.7 + visible: flowDragArea.dragStarted + z: 2000 + clip: false // Ensure ghost isn't clipped + + NText { + id: ghostText + anchors.centerIn: parent + pointSize: Style.fontSizeS + color: Color.mOnPrimary + } + } + + // Drop indicator - visual feedback for where the widget will be inserted + Rectangle { + id: dropIndicator + width: 3 + height: Style.baseWidgetSize * 1.15 + radius: Style.iRadiusXXS + color: Color.mSecondary + opacity: 0 + visible: opacity > 0 + z: 1999 + + SequentialAnimation on opacity { + id: pulseAnimation + running: false + loops: Animation.Infinite + NumberAnimation { + to: 1 + duration: 400 + easing.type: Easing.InOutQuad + } + NumberAnimation { + to: 0.6 + duration: 400 + easing.type: Easing.InOutQuad + } + } + + Behavior on x { + NumberAnimation { + duration: 100 + easing.type: Easing.OutCubic + } + } + Behavior on y { + NumberAnimation { + duration: 100 + easing.type: Easing.OutCubic + } + } + } + + // MouseArea for drag and drop + MouseArea { + id: flowDragArea + anchors.fill: parent + z: 100 // Above widgets to ensure it captures events first + enabled: root.draggable || root.crossSectionDraggable + + acceptedButtons: Qt.LeftButton + preventStealing: true // Always prevent stealing to ensure we get all events + propagateComposedEvents: true // Allow events to propagate when not handled + hoverEnabled: potentialDrag || dragStarted // Only track hover during drag operations + cursorShape: dragStarted ? Qt.ClosedHandCursor : Qt.ArrowCursor + + property point startPos: Qt.point(0, 0) + property bool dragStarted: false + property bool potentialDrag: false // Track if we're in a potential drag interaction + property int draggedIndex: -1 + property real dragThreshold: 8 // Reduced threshold for more responsive drag + property Item draggedWidget: null + property int dropTargetIndex: -1 + property var draggedModelData: null + property bool isOverButtonArea: false + + // Drop position calculation + // Map widget coordinates from grid-local to gridContainer coordinates + function mapWidgetCoords(widget) { + return { + x: widget.x + widgetGrid.x, + y: widget.y + widgetGrid.y, + width: widget.width, + height: widget.height + }; + } + + function updateDropIndicator(mouseX, mouseY) { + if (!dragStarted || draggedIndex === -1) { + dropIndicator.opacity = 0; + pulseAnimation.running = false; + return; + } + + let bestIndex = -1; + let bestPosition = null; + let minDistance = Infinity; + + // Check position relative to each widget + for (var i = 0; i < widgetModel.length; i++) { + if (i === draggedIndex) + continue; + const widget = widgetRepeater.itemAt(i); + if (!widget || widget.widgetIndex === undefined) + continue; + + const mapped = mapWidgetCoords(widget); + + // Check distance to left edge (insert before) + const leftDist = Math.sqrt(Math.pow(mouseX - mapped.x, 2) + Math.pow(mouseY - (mapped.y + mapped.height / 2), 2)); + + // Check distance to right edge (insert after) + const rightDist = Math.sqrt(Math.pow(mouseX - (mapped.x + mapped.width), 2) + Math.pow(mouseY - (mapped.y + mapped.height / 2), 2)); + + if (leftDist < minDistance) { + minDistance = leftDist; + bestIndex = i; + bestPosition = Qt.point(mapped.x - dropIndicator.width / 2 - Style.marginXS, mapped.y); + } + + if (rightDist < minDistance) { + minDistance = rightDist; + bestIndex = i + 1; + bestPosition = Qt.point(mapped.x + mapped.width + Style.marginXS - dropIndicator.width / 2, mapped.y); + } + } + + // Check if we should insert at position 0 (very beginning) + if (widgetModel.length > 0 && draggedIndex !== 0) { + const firstWidget = widgetRepeater.itemAt(0); + if (firstWidget) { + const mapped = mapWidgetCoords(firstWidget); + const dist = Math.sqrt(Math.pow(mouseX - mapped.x, 2) + Math.pow(mouseY - mapped.y, 2)); + if (dist < minDistance && mouseX < mapped.x + mapped.width / 2) { + minDistance = dist; + bestIndex = 0; + // Position indicator to the left of the first widget + bestPosition = Qt.point(mapped.x - dropIndicator.width / 2 - Style.marginXS, mapped.y); + } + } + } + + // Only show indicator if we're close enough and it's a different position + if (minDistance < 80 && bestIndex !== -1) { + // Adjust index if we're moving forward + let adjustedIndex = bestIndex; + if (bestIndex > draggedIndex) { + adjustedIndex = bestIndex - 1; + } + + // Don't show if it's the same position + if (adjustedIndex === draggedIndex) { + dropIndicator.opacity = 0; + pulseAnimation.running = false; + dropTargetIndex = -1; + return; + } + + dropTargetIndex = adjustedIndex; + if (bestPosition) { + dropIndicator.x = bestPosition.x; + dropIndicator.y = bestPosition.y; + dropIndicator.opacity = 1; + if (!pulseAnimation.running) { + pulseAnimation.running = true; + } + } + } else { + dropIndicator.opacity = 0; + pulseAnimation.running = false; + dropTargetIndex = -1; + } + } + + function resetDragState() { + root.clearCrossSectionHover(); + dragStarted = false; + potentialDrag = false; + draggedIndex = -1; + draggedWidget = null; + dropTargetIndex = -1; + draggedModelData = null; + isOverButtonArea = false; + dropIndicator.opacity = 0; + pulseAnimation.running = false; + dragGhost.width = 0; + } + + onPressed: mouse => { + // Reset state + startPos = Qt.point(mouse.x, mouse.y); + dragStarted = false; + potentialDrag = false; + draggedIndex = -1; + draggedWidget = null; + dropTargetIndex = -1; + draggedModelData = null; + isOverButtonArea = false; + + // Find which widget was clicked + for (var i = 0; i < widgetModel.length; i++) { + const widget = widgetRepeater.itemAt(i); + if (widget && widget.widgetIndex !== undefined) { + if (mouse.x >= widget.x && mouse.x <= widget.x + widget.width && mouse.y >= widget.y && mouse.y <= widget.y + widget.height) { + const localX = mouse.x - widget.x; + const buttonsStartX = widget.width - (widget.buttonsCount * widget.buttonsWidth * Style.uiScaleRatio); + + if (localX >= buttonsStartX && widget.buttonsCount > 0) { + // Click is on button area - don't start drag, propagate event + isOverButtonArea = true; + mouse.accepted = false; + return; + } else { + // This is a draggable area + draggedIndex = widget.widgetIndex; + draggedWidget = widget; + draggedModelData = widget.modelData; + potentialDrag = true; + mouse.accepted = true; + + // Signal that interaction started (prevents panel close) + root.dragPotentialStarted(); + return; + } + } + } + } + + // Click was not on any widget + mouse.accepted = false; + } + + onPositionChanged: mouse => { + if (potentialDrag && draggedIndex !== -1) { + const deltaX = mouse.x - startPos.x; + const deltaY = mouse.y - startPos.y; + const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY); + + // Start drag if threshold exceeded + if (!dragStarted && distance > dragThreshold) { + dragStarted = true; + + // Setup ghost widget + if (draggedWidget) { + dragGhost.width = draggedWidget.width; + dragGhost.color = root.getWidgetColor(draggedModelData)[0]; + ghostText.text = draggedModelData.id; + } + + var startGlobal = flowDragArea.mapToGlobal(mouse.x, mouse.y); + root.updateCrossSectionHover(startGlobal.x, startGlobal.y); + } + + if (dragStarted) { + // Move ghost widget + dragGhost.x = mouse.x - dragGhost.width / 2; + dragGhost.y = mouse.y - dragGhost.height / 2; + + var moveGlobal = flowDragArea.mapToGlobal(mouse.x, mouse.y); + root.updateCrossSectionHover(moveGlobal.x, moveGlobal.y); + + // Update drop indicator + updateDropIndicator(mouse.x, mouse.y); + } + } + } + + onReleased: mouse => { + if (root.draggable && dragStarted && dropTargetIndex !== -1 && dropTargetIndex !== draggedIndex) { + // Perform the reorder + reorderWidget(sectionId, draggedIndex, dropTargetIndex); + } else if (dragStarted && draggedIndex !== -1) { + var globalPos = flowDragArea.mapToGlobal(mouse.x, mouse.y); + var targetSectionId = root.findSectionAtGlobalPosition(globalPos.x, globalPos.y); + if (targetSectionId !== "" && targetSectionId !== root.sectionId) { + root.moveWidget(root.sectionId, draggedIndex, targetSectionId); + } + } + + // Always signal end of interaction if we started one + if (potentialDrag) { + root.dragPotentialEnded(); + } + + // Reset everything + resetDragState(); + mouse.accepted = true; + } + + onCanceled: { + // Handle cancel (e.g., ESC key pressed during drag) + if (potentialDrag) { + root.dragPotentialEnded(); + } + + resetDragState(); + } + } + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NSettingsIndicator.qml b/quickshell/compat/noctalia/Widgets/NSettingsIndicator.qml new file mode 100644 index 0000000..ec7ffb1 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NSettingsIndicator.qml @@ -0,0 +1,47 @@ +import QtQuick +import QtQuick.Layouts +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Services.UI + +Rectangle { + id: root + + property bool show: false + property var tooltipText + + implicitWidth: root.show ? 6 * Style.uiScaleRatio : 0 + implicitHeight: root.show ? 6 * Style.uiScaleRatio : 0 + width: root.show ? 6 * Style.uiScaleRatio : 0 + height: root.show ? 6 * Style.uiScaleRatio : 0 + radius: width / 2 + color: Color.mOnSurfaceVariant + opacity: 0.6 + + visible: root.show + + Behavior on opacity { + NumberAnimation { + duration: Style.animationFast + } + } + + MouseArea { + enabled: root.show && root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0) + anchors.fill: parent + hoverEnabled: true + acceptedButtons: Qt.NoButton + cursorShape: Qt.PointingHandCursor + + onEntered: { + if (root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) { + TooltipService.show(root, root.tooltipText); + } + } + + onExited: { + if (root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) { + TooltipService.hide(); + } + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NSlideSwapView.qml b/quickshell/compat/noctalia/Widgets/NSlideSwapView.qml new file mode 100644 index 0000000..86bedec --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NSlideSwapView.qml @@ -0,0 +1,135 @@ +import QtQuick +import qs.compat.noctalia.Commons + +Item { + id: root + + property Component sourceComponent + property bool animationsEnabled: true + property int duration: Style.animationNormal + property real transitionGap: Style.marginXL + property real incomingStartOpacity: 0.0 + property real outgoingTargetOpacity: 0.25 + + readonly property var item: contentLoader.item + readonly property bool running: _running + + property bool _running: false + property var _pendingApplyChange: null + property real _contentOffset: 0 + property real _contentOpacity: 1 + property real _snapshotOffset: 0 + property real _snapshotOpacity: 0 + property real _snapshotTargetOffset: 0 + + clip: true + + function resetVisuals() { + _running = false; + _pendingApplyChange = null; + _contentOffset = 0; + _contentOpacity = 1; + _snapshotOffset = 0; + _snapshotOpacity = 0; + snapshot.visible = false; + transition.stop(); + } + + function swap(direction, applyChange) { + if (!animationsEnabled || width <= 0 || height <= 0 || direction === 0) { + if (applyChange) + applyChange(); + return; + } + + if (_running) + resetVisuals(); + + const slideDistance = Math.max(1, width + transitionGap); + const movingForward = direction > 0; + + snapshot.visible = true; + _snapshotOffset = 0; + _snapshotOpacity = 1; + _snapshotTargetOffset = movingForward ? -slideDistance : slideDistance; + + _contentOffset = movingForward ? slideDistance : -slideDistance; + _contentOpacity = incomingStartOpacity; + + _pendingApplyChange = applyChange || null; + _running = true; + snapshot.scheduleUpdate(); + + Qt.callLater(() => { + if (!_running) { + return; + } + + const applyFn = _pendingApplyChange; + _pendingApplyChange = null; + const shouldAnimate = applyFn ? applyFn() !== false : true; + if (!shouldAnimate) { + resetVisuals(); + return; + } + transition.restart(); + }); + } + + ShaderEffectSource { + id: snapshot + visible: false + width: parent.width + height: parent.height + y: 0 + sourceItem: contentLoader + hideSource: false + live: false + smooth: true + z: 2 + x: root._snapshotOffset + opacity: root._snapshotOpacity + } + + Loader { + id: contentLoader + width: parent.width + height: parent.height + x: root._contentOffset + opacity: root._contentOpacity + sourceComponent: root.sourceComponent + } + + ParallelAnimation { + id: transition + NumberAnimation { + target: root + property: "_contentOffset" + to: 0 + duration: root.duration + easing.type: Easing.OutCubic + } + NumberAnimation { + target: root + property: "_contentOpacity" + to: 1 + duration: root.duration + easing.type: Easing.OutCubic + } + NumberAnimation { + target: root + property: "_snapshotOffset" + to: root._snapshotTargetOffset + duration: root.duration + easing.type: Easing.OutCubic + } + NumberAnimation { + target: root + property: "_snapshotOpacity" + to: root.outgoingTargetOpacity + duration: root.duration + easing.type: Easing.OutCubic + } + onFinished: root.resetVisuals() + } +} diff --git a/quickshell/compat/noctalia/Widgets/NSlider.qml b/quickshell/compat/noctalia/Widgets/NSlider.qml new file mode 100644 index 0000000..f092f48 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NSlider.qml @@ -0,0 +1,253 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Shapes +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Services.UI + +Slider { + id: root + + readonly property bool sliderActive: activeFocus || pressed + property color fillColor: Color.mPrimary + property var cutoutColor: Color.mSurface + property bool snapAlways: true + property real heightRatio: 0.7 + property var tooltipText + property string tooltipDirection: "auto" + property bool hovering: false + + readonly property color effectiveFillColor: enabled ? fillColor : Color.mOutline + + readonly property real knobDiameter: Math.round((Style.baseWidgetSize * heightRatio * Style.uiScaleRatio) / 2) * 2 + readonly property real trackHeight: Math.round((knobDiameter * 0.4 * Style.uiScaleRatio) / 2) * 2 + readonly property real trackRadius: Math.min(Style.iRadiusL, trackHeight / 2) + readonly property real cutoutExtra: Math.round((Style.baseWidgetSize * 0.1 * Style.uiScaleRatio) / 2) * 2 + + padding: cutoutExtra / 2 + + snapMode: snapAlways ? Slider.SnapAlways : Slider.SnapOnRelease + implicitHeight: Math.max(trackHeight, knobDiameter) + + background: Item { + id: bgContainer + x: root.leftPadding + y: root.topPadding + Style.pixelAlignCenter(root.availableHeight, root.trackHeight) + implicitWidth: Style.sliderWidth + implicitHeight: root.trackHeight + width: root.availableWidth + height: root.trackHeight + + readonly property real fillWidth: root.visualPosition * width + + // Background track + Shape { + anchors.fill: parent + visible: bgContainer.width > 0 && bgContainer.height > 0 + preferredRendererType: Shape.CurveRenderer + asynchronous: true + + ShapePath { + id: bgPath + strokeColor: Qt.alpha(Color.mOutline, 0.5) + strokeWidth: Style.borderS + fillColor: Qt.alpha(Color.mSurface, 0.5) + + readonly property real w: bgContainer.width + readonly property real h: bgContainer.height + readonly property real r: root.trackRadius + + startX: r + startY: 0 + + PathLine { + x: bgPath.w - bgPath.r + y: 0 + } + PathArc { + x: bgPath.w + y: bgPath.r + radiusX: bgPath.r + radiusY: bgPath.r + } + PathLine { + x: bgPath.w + y: bgPath.h - bgPath.r + } + PathArc { + x: bgPath.w - bgPath.r + y: bgPath.h + radiusX: bgPath.r + radiusY: bgPath.r + } + PathLine { + x: bgPath.r + y: bgPath.h + } + PathArc { + x: 0 + y: bgPath.h - bgPath.r + radiusX: bgPath.r + radiusY: bgPath.r + } + PathLine { + x: 0 + y: bgPath.r + } + PathArc { + x: bgPath.r + y: 0 + radiusX: bgPath.r + radiusY: bgPath.r + } + } + } + + LinearGradient { + id: fillGradient + x1: 0 + y1: 0 + x2: root.availableWidth + y2: 0 + GradientStop { + position: 0.0 + color: Qt.darker(effectiveFillColor, 1.2) + } + GradientStop { + position: 1.0 + color: effectiveFillColor + } + } + + // Active/filled track + Shape { + width: bgContainer.fillWidth + height: bgContainer.height + visible: bgContainer.fillWidth > 0 && bgContainer.height > 0 + preferredRendererType: Shape.CurveRenderer + asynchronous: true + clip: true + + ShapePath { + id: fillPath + strokeColor: "transparent" + fillGradient: fillGradient + + readonly property real fullWidth: root.availableWidth + readonly property real h: root.trackHeight + readonly property real r: root.trackRadius + + startX: r + startY: 0 + + PathLine { + x: fillPath.fullWidth - fillPath.r + y: 0 + } + PathArc { + x: fillPath.fullWidth + y: fillPath.r + radiusX: fillPath.r + radiusY: fillPath.r + } + PathLine { + x: fillPath.fullWidth + y: fillPath.h - fillPath.r + } + PathArc { + x: fillPath.fullWidth - fillPath.r + y: fillPath.h + radiusX: fillPath.r + radiusY: fillPath.r + } + PathLine { + x: fillPath.r + y: fillPath.h + } + PathArc { + x: 0 + y: fillPath.h - fillPath.r + radiusX: fillPath.r + radiusY: fillPath.r + } + PathLine { + x: 0 + y: fillPath.r + } + PathArc { + x: fillPath.r + y: 0 + radiusX: fillPath.r + radiusY: fillPath.r + } + } + } + + // Circular cutout + Rectangle { + id: knobCutout + implicitWidth: root.knobDiameter + root.cutoutExtra + implicitHeight: root.knobDiameter + root.cutoutExtra + radius: Math.min(Style.iRadiusL, width / 2) + color: root.cutoutColor !== undefined ? root.cutoutColor : Color.mSurface + x: root.visualPosition * (root.availableWidth - root.knobDiameter) - root.cutoutExtra / 2 + anchors.verticalCenter: parent.verticalCenter + } + } + + handle: Item { + implicitWidth: knobDiameter + implicitHeight: knobDiameter + x: root.leftPadding + root.visualPosition * (root.availableWidth - width) + anchors.verticalCenter: parent.verticalCenter + + Rectangle { + id: knob + implicitWidth: knobDiameter + implicitHeight: knobDiameter + radius: Math.min(Style.iRadiusL, width / 2) + color: root.pressed ? Color.mHover : Color.mSurface + border.color: effectiveFillColor + border.width: Style.borderL + anchors.centerIn: parent + + Behavior on color { + ColorAnimation { + duration: Style.animationFast + } + } + } + + MouseArea { + enabled: true + anchors.fill: parent + cursorShape: Qt.PointingHandCursor + hoverEnabled: true + acceptedButtons: Qt.NoButton // Don't accept any mouse buttons - only hover + propagateComposedEvents: true + + onEntered: { + root.hovering = true; + if (root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) { + TooltipService.show(knob, root.tooltipText, root.tooltipDirection); + } + } + + onExited: { + root.hovering = false; + if (root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) { + TooltipService.hide(); + } + } + } + + // Hide tooltip when slider is pressed (anywhere on the slider) + Connections { + target: root + function onPressedChanged() { + if (root.pressed && root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) { + TooltipService.hide(); + } + } + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NSpinBox.qml b/quickshell/compat/noctalia/Widgets/NSpinBox.qml new file mode 100644 index 0000000..6ccfb7a --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NSpinBox.qml @@ -0,0 +1,314 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Widgets + +RowLayout { + id: root + + // Public properties + property int value: 0 + property int from: 0 + property int to: 100 + property int stepSize: 1 + property string suffix: "" + property string prefix: "" + property string label: "" + property string description: "" + property bool hovering: false + property int baseSize: Style.baseWidgetSize + property var defaultValue: undefined + property string settingsPath: "" + + // Convenience properties for common naming + property alias minimum: root.from + property alias maximum: root.to + + // Properties for repeating + property int initialRepeatDelay: 400 // The "pause" after the first click (in ms) + property int repeatInterval: 80 // How often to step up after fist pause (ms) + property int rampFactor: 4 // How many ticks to wait before increasing the step multiplier + property int maxStepMultiplier: 10 // The max step (e.g., 10 * stepSize) + property int _holdTicks: 0 // Internal counter for hold duration + property int _repeatDirection: 0 // -1 for decrease, 1 for increase + + signal entered + signal exited + + Layout.fillWidth: true + + readonly property bool isValueChanged: (defaultValue !== undefined) && (value !== defaultValue) + readonly property string indicatorTooltip: defaultValue !== undefined ? I18n.tr("panels.indicator.default-value", { + "value": String(defaultValue) + }) : "" + + Timer { + id: repeatTimer + repeat: true + interval: root.initialRepeatDelay + + onTriggered: { + if (repeatTimer.interval === root.initialRepeatDelay) { + repeatTimer.interval = root.repeatInterval; + root._holdTicks = 0; + } + root._holdTicks++; + var stepMultiplier = Math.min(root.maxStepMultiplier, 1 + Math.floor(root._holdTicks / root.rampFactor)); + changeValue(root._repeatDirection, root.stepSize * stepMultiplier); + } + } + + function changeValue(direction, step) { + var currentStep = step || root.stepSize; + + if (direction === 1 && root.value < root.to) { + root.value = Math.min(root.to, root.value + currentStep); + } else if (direction === -1 && root.value > root.from) { + root.value = Math.max(root.from, root.value - currentStep); + } else { + return; + } + + if (root.value === root.to || root.value === root.from) { + stopRepeat(); + } + } + + function stopRepeat() { + root._repeatDirection = 0; + repeatTimer.stop(); + repeatTimer.interval = root.initialRepeatDelay; + } + + NLabel { + label: root.label + description: root.description + showIndicator: root.isValueChanged + indicatorTooltip: root.indicatorTooltip + } + + // Main spinbox container + Rectangle { + id: spinBoxContainer + Layout.margins: Style.borderS + implicitWidth: 120 + implicitHeight: Math.round((root.baseSize - 4) / 2) * 2 + radius: Style.iRadiusS + color: Color.mSurfaceVariant + border.color: (root.hovering || decreaseArea.containsMouse || increaseArea.containsMouse) ? Color.mHover : Color.mOutline + border.width: Style.borderS + + Behavior on border.color { + ColorAnimation { + duration: Style.animationFast + } + } + + // Mouse area for hover and scroll + MouseArea { + anchors.fill: parent + acceptedButtons: Qt.NoButton + hoverEnabled: true + onEntered: { + if (!root.enabled) + return; + root.hovering = true; + root.entered(); + } + onExited: { + root.hovering = false; + root.exited(); + } + onWheel: wheel => { + if (wheel.angleDelta.y > 0 && root.value < root.to) { + let newValue = Math.min(root.to, root.value + root.stepSize); + root.value = newValue; + } else if (wheel.angleDelta.y < 0 && root.value > root.from) { + let newValue = Math.max(root.from, root.value - root.stepSize); + root.value = newValue; + } + } + } + + // Decrease button (left) + Item { + id: decreaseButton + height: parent.height + width: height + anchors.top: parent.top + anchors.bottom: parent.bottom + anchors.left: parent.left + opacity: (root.enabled && root.value > root.from) || decreaseArea.containsMouse ? 1.0 : 0.3 + + Rectangle { + anchors.centerIn: parent + width: parent.height + height: width + radius: spinBoxContainer.radius + color: Color.mHover + opacity: decreaseArea.containsMouse ? 1.0 : 0.0 + Behavior on opacity { + NumberAnimation { + duration: Style.animationFast + } + } + } + + NIcon { + anchors.centerIn: parent + icon: "chevron-left" + pointSize: Style.fontSizeS + color: decreaseArea.containsMouse ? Color.mOnHover : Color.mPrimary + } + + MouseArea { + id: decreaseArea + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + enabled: root.enabled && root.value > root.from + onPressed: { + root._repeatDirection = -1; + changeValue(root._repeatDirection, root.stepSize); + repeatTimer.start(); + } + onReleased: stopRepeat() + onExited: stopRepeat() + } + } + + // Increase button (right) + Item { + id: increaseButton + height: parent.height + width: height + anchors.top: parent.top + anchors.bottom: parent.bottom + anchors.right: parent.right + opacity: (root.enabled && root.value < root.to) || increaseArea.containsMouse ? 1.0 : 0.3 + + Rectangle { + anchors.centerIn: parent + width: parent.height + height: width + radius: spinBoxContainer.radius + color: Color.mHover + opacity: increaseArea.containsMouse ? 1.0 : 0.0 + Behavior on opacity { + NumberAnimation { + duration: Style.animationFast + } + } + } + + NIcon { + anchors.centerIn: parent + icon: "chevron-right" + pointSize: Style.fontSizeS + color: increaseArea.containsMouse ? Color.mOnHover : Color.mPrimary + } + + MouseArea { + id: increaseArea + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + enabled: root.enabled && root.value < root.to + onPressed: { + root._repeatDirection = 1; + changeValue(root._repeatDirection, root.stepSize); + repeatTimer.start(); + } + onReleased: stopRepeat() + onExited: stopRepeat() + } + } + + // Center value display with separate prefix, value, and suffix + Item { + id: valueContainer + anchors.left: decreaseButton.right + anchors.right: increaseButton.left + anchors.verticalCenter: parent.verticalCenter + anchors.margins: 4 + height: parent.height + + RowLayout { + anchors.centerIn: parent + spacing: 0 + + // Prefix text (non-editable) + NText { + text: root.prefix + family: Settings.data.ui.fontFixed + pointSize: Style.fontSizeM + font.weight: Style.fontWeightMedium + color: Qt.alpha(Color.mOnSurface, root.enabled ? 1.0 : 0.6) + verticalAlignment: Text.AlignVCenter + Layout.alignment: Qt.AlignVCenter + visible: root.prefix !== "" + } + + // Editable number input + TextInput { + id: valueInput + text: valueInput.focus ? valueInput.text : root.value.toString() + font.family: Settings.data.ui.fontFixed + font.pointSize: Style.fontSizeM + font.weight: Style.fontWeightMedium + color: Qt.alpha(Color.mOnSurface, root.enabled ? 1.0 : 0.6) + verticalAlignment: Text.AlignVCenter + Layout.alignment: Qt.AlignVCenter + selectByMouse: true + enabled: root.enabled + + // Only allow numeric input within range + validator: IntValidator { + bottom: root.from + top: root.to + } + + onAccepted: { + applyValue(); + focus = false; + } + + Keys.onEscapePressed: { + text = root.value.toString(); + focus = false; + } + + onFocusChanged: { + if (focus) { + selectAll(); + } else { + applyValue(); + } + } + + function applyValue() { + let newValue = parseInt(text); + if (!isNaN(newValue)) { + // Don't manually set text here - let the binding handle it + newValue = Math.max(root.from, Math.min(root.to, newValue)); + root.value = newValue; + } + } + } + + // Suffix text (non-editable) + NText { + text: root.suffix + family: Settings.data.ui.fontFixed + pointSize: Style.fontSizeM + font.weight: Style.fontWeightMedium + color: Qt.alpha(Color.mOnSurface, root.enabled ? 1.0 : 0.6) + verticalAlignment: Text.AlignVCenter + Layout.alignment: Qt.AlignVCenter + visible: root.suffix !== "" + } + } + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NTabBar.qml b/quickshell/compat/noctalia/Widgets/NTabBar.qml new file mode 100644 index 0000000..b4d987d --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NTabBar.qml @@ -0,0 +1,90 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Widgets + +Rectangle { + id: root + objectName: "NTabBar" + + // Public properties + property int currentIndex: 0 + property real spacing: Style.marginXS + property real margins: 0 + property real tabHeight: Style.baseWidgetSize + property bool distributeEvenly: false + default property alias content: tabRow.children + + onDistributeEvenlyChanged: _applyDistribution() + Component.onCompleted: _applyDistribution() + + function _updateFirstLast() { + // Defensive check for QML initialization timing + if (!tabRow || !tabRow.children) { + return; + } + var kids = tabRow.children; + var len = kids.length; + var firstVisible = -1; + var lastVisible = -1; + for (var i = 0; i < len; i++) { + var child = kids[i]; + // Only consider items that have isFirst/isLast (actual tab buttons, not Repeaters) + if (child.visible && "isFirst" in child) { + if (firstVisible === -1) + firstVisible = i; + lastVisible = i; + } + } + for (var i = 0; i < len; i++) { + var child = kids[i]; + if ("isFirst" in child) + child.isFirst = (i === firstVisible); + if ("isLast" in child) + child.isLast = (i === lastVisible); + } + } + + function _applyDistribution() { + if (!tabRow || !tabRow.children) { + return; + } + if (!distributeEvenly) { + for (var i = 0; i < tabRow.children.length; i++) { + var child = tabRow.children[i]; + child.Layout.fillWidth = true; + } + return; + } + + for (var i = 0; i < tabRow.children.length; i++) { + var child = tabRow.children[i]; + child.Layout.fillWidth = true; + child.Layout.preferredWidth = 1; + } + } + + // Styling + Layout.margins: Style.borderS + implicitWidth: tabRow.implicitWidth + (margins * 2) + implicitHeight: tabHeight + (margins * 2) + color: Color.smartAlpha(Color.mSurfaceVariant) + radius: Style.iRadiusM + + RowLayout { + id: tabRow + anchors.fill: parent + anchors.margins: margins + spacing: root.spacing + + onChildrenChanged: { + for (var i = 0; i < children.length; i++) { + var child = children[i]; + child.visibleChanged.connect(root._updateFirstLast); + } + root._updateFirstLast(); + root._applyDistribution(); + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NTabButton.qml b/quickshell/compat/noctalia/Widgets/NTabButton.qml new file mode 100644 index 0000000..9f10229 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NTabButton.qml @@ -0,0 +1,127 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Services.UI +import qs.compat.noctalia.Widgets + +Rectangle { + id: root + + // Public properties + property string text: "" + property string icon: "" + property var tooltipText + property bool checked: false + property int tabIndex: 0 + property real pointSize: Style.fontSizeM + property bool isFirst: false + property bool isLast: false + + // Internal state + property bool isHovered: false + + signal clicked + + // Sizing + Layout.fillHeight: true + implicitWidth: contentLayout.implicitWidth + Style.margin2M + + topLeftRadius: isFirst ? Style.iRadiusM : Style.iRadiusXXXS + bottomLeftRadius: isFirst ? Style.iRadiusM : Style.iRadiusXXXS + topRightRadius: isLast ? Style.iRadiusM : Style.iRadiusXXXS + bottomRightRadius: isLast ? Style.iRadiusM : Style.iRadiusXXXS + + color: root.isHovered ? Color.mHover : (root.checked ? Color.mPrimary : Color.smartAlpha(Color.mSurface)) + border.color: root.checked ? Color.mPrimary : Color.mOutline + border.width: Style.borderS + + Behavior on color { + enabled: !Color.isTransitioning + ColorAnimation { + duration: Style.animationFast + easing.type: Easing.OutCubic + } + } + + // Content + RowLayout { + id: contentLayout + anchors.centerIn: parent + width: Math.min(implicitWidth, parent.width - Style.margin2S) + spacing: (root.icon !== "" && root.text !== "") ? Style.marginXS : 0 + + NIcon { + visible: root.icon !== "" + Layout.alignment: Qt.AlignVCenter + icon: root.icon + pointSize: root.pointSize * 1.2 + color: root.isHovered ? Color.mOnHover : (root.checked ? Color.mOnPrimary : Color.mOnSurface) + + Behavior on color { + enabled: !Color.isTransitioning + ColorAnimation { + duration: Style.animationFast + easing.type: Easing.OutCubic + } + } + } + + NText { + id: tabText + visible: root.text !== "" + Layout.alignment: Qt.AlignVCenter + text: root.text + pointSize: root.pointSize + font.weight: Style.fontWeightSemiBold + color: root.isHovered ? Color.mOnHover : (root.checked ? Color.mOnPrimary : Color.mOnSurface) + horizontalAlignment: Text.AlignHCenter + verticalAlignment: Text.AlignVCenter + + Behavior on color { + enabled: !Color.isTransitioning + ColorAnimation { + duration: Style.animationFast + easing.type: Easing.OutCubic + } + } + } + } + + // Tooltip + Timer { + id: tooltipTimer + interval: 500 + onTriggered: { + if (root.isHovered && root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) { + TooltipService.show(root, root.tooltipText); + } + } + } + + MouseArea { + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onEntered: { + root.isHovered = true; + if (root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) { + tooltipTimer.start(); + } + } + onExited: { + root.isHovered = false; + tooltipTimer.stop(); + if (root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) { + TooltipService.hide(); + } + } + onClicked: { + root.clicked(); + // Update parent NTabBar's currentIndex + if (root.parent && root.parent.parent && root.parent.parent.currentIndex !== undefined) { + root.parent.parent.currentIndex = root.tabIndex; + } + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NTabView.qml b/quickshell/compat/noctalia/Widgets/NTabView.qml new file mode 100644 index 0000000..c35d834 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NTabView.qml @@ -0,0 +1,181 @@ +import QtQuick +import QtQuick.Layouts +import qs.compat.noctalia.Commons + +Item { + id: root + objectName: "NTabView" + + property int currentIndex: 0 + + // Private + property int previousIndex: 0 + property bool initialized: false + property bool animating: false + property real animatingHeight: 0 + property real transitionGap: Style.marginXL + property real transitionTime: Style.animationNormal + property list contentItems: [] + + default property alias content: container.data + + clip: true + Layout.fillWidth: true + + // During animation, use max height to prevent clipping. Otherwise use current item height. + implicitHeight: animating ? animatingHeight : (contentItems[currentIndex] ? contentItems[currentIndex].implicitHeight : 0) + + Item { + id: container + anchors.fill: parent + } + + // Set the visible tab to idx without triggering a slide animation. + // Call this BEFORE the bound currentIndex changes so that + // onCurrentIndexChanged sees previousIndex === currentIndex and skips. + function setIndexWithoutAnimation(idx) { + fromXAnim.stop(); + fromOpacityAnim.stop(); + toXAnim.stop(); + toOpacityAnim.stop(); + animating = false; + previousIndex = idx; + for (let i = 0; i < contentItems.length; i++) { + if (i === idx) { + contentItems[i].x = 0; + contentItems[i].visible = true; + contentItems[i].opacity = 1.0; + } else { + contentItems[i].x = root.width; + contentItems[i].visible = false; + contentItems[i].opacity = 1.0; + } + } + } + + Component.onCompleted: { + _initializeItems(); + } + + function _initializeItems() { + contentItems = []; + for (let i = 0; i < container.children.length; i++) { + const child = container.children[i]; + contentItems.push(child); + child.width = Qt.binding(() => root.width); + + if (i === currentIndex) { + child.x = 0; + child.visible = true; + } else { + child.x = root.width; + child.visible = false; + } + } + initialized = true; + } + + onCurrentIndexChanged: { + if (!initialized || contentItems.length === 0) + return; + if (previousIndex === currentIndex) + return; + + _animateTransition(previousIndex, currentIndex); + previousIndex = currentIndex; + } + + function _animateTransition(fromIdx, toIdx) { + // Stop any running animations + fromXAnim.stop(); + fromOpacityAnim.stop(); + toXAnim.stop(); + toOpacityAnim.stop(); + + // Reset all items to clean state (except target) + for (let i = 0; i < contentItems.length; i++) { + if (i !== toIdx) { + contentItems[i].visible = false; + contentItems[i].opacity = 1.0; + } + } + + const fromItem = contentItems[fromIdx]; + const toItem = contentItems[toIdx]; + const slideLeft = toIdx > fromIdx; + + // Set height to max of both items during animation + const fromHeight = fromItem ? fromItem.implicitHeight : 0; + const toHeight = toItem ? toItem.implicitHeight : 0; + animatingHeight = Math.max(fromHeight, toHeight); + animating = true; + + // Position outgoing item and make visible for animation + if (fromItem) { + fromItem.visible = true; + fromItem.x = 0; + fromItem.opacity = 1.0; + } + + // Position incoming item off-screen (with gap) and set initial opacity + if (toItem) { + toItem.visible = true; + toItem.x = slideLeft ? root.width + transitionGap : -root.width - transitionGap; + toItem.opacity = 0.0; + } + + // Animate both items together (with gap) + if (fromItem) { + fromXAnim.target = fromItem; + fromXAnim.to = slideLeft ? -root.width - transitionGap : root.width + transitionGap; + fromOpacityAnim.target = fromItem; + fromXAnim.start(); + fromOpacityAnim.start(); + } + + if (toItem) { + toXAnim.target = toItem; + toOpacityAnim.target = toItem; + toXAnim.start(); + toOpacityAnim.start(); + } + } + + NumberAnimation { + id: fromXAnim + property: "x" + duration: root.transitionTime + easing.type: Easing.OutCubic + onFinished: { + if (target && target !== contentItems[currentIndex]) { + target.visible = false; + target.opacity = 1.0; + } + animating = false; + } + } + + NumberAnimation { + id: fromOpacityAnim + property: "opacity" + to: 0.25 + duration: root.transitionTime + easing.type: Easing.OutCubic + } + + NumberAnimation { + id: toXAnim + property: "x" + to: 0 + duration: root.transitionTime + easing.type: Easing.OutCubic + } + + NumberAnimation { + id: toOpacityAnim + property: "opacity" + to: 1.0 + duration: root.transitionTime + easing.type: Easing.OutCubic + } +} diff --git a/quickshell/compat/noctalia/Widgets/NTagFilter.qml b/quickshell/compat/noctalia/Widgets/NTagFilter.qml new file mode 100644 index 0000000..3510498 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NTagFilter.qml @@ -0,0 +1,48 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Widgets + +NCollapsible { + id: root + + // Public API + property var tags: [] // Array of tag strings + property string selectedTag: "" + property alias label: root.label + property alias description: root.description + property alias expanded: root.expanded + + // Formatting function for tag display (optional override) + property var formatTag: function (tag) { + if (tag === "") + return I18n.tr("launcher.categories.all"); + // Default: capitalize first letter + return tag.charAt(0).toUpperCase() + tag.slice(1); + } + + Layout.fillWidth: true + contentSpacing: Style.marginXS + + Flow { + Layout.fillWidth: true + spacing: Style.marginXS + flow: Flow.LeftToRight + + Repeater { + model: [""].concat(root.tags) + + delegate: NButton { + text: root.formatTag(modelData) + backgroundColor: root.selectedTag === modelData ? Color.mPrimary : Color.mSurfaceVariant + textColor: root.selectedTag === modelData ? Color.mOnPrimary : Color.mOnSurfaceVariant + onClicked: root.selectedTag = modelData + fontSize: Style.fontSizeS + iconSize: Style.fontSizeS + fontWeight: Style.fontWeightSemiBold + buttonRadius: Style.iRadiusM + } + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NText.qml b/quickshell/compat/noctalia/Widgets/NText.qml new file mode 100644 index 0000000..b822899 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NText.qml @@ -0,0 +1,41 @@ +import QtQuick +import QtQuick.Layouts +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Widgets + +Text { + id: root + + property bool richTextEnabled: false + property bool markdownTextEnabled: false + property string family: Settings.data.ui.fontDefault + property real pointSize: Style.fontSizeM + property bool applyUiScale: true + property real fontScale: { + const fontScale = (root.family === Settings.data.ui.fontDefault ? Settings.data.ui.fontDefaultScale : Settings.data.ui.fontFixedScale); + if (applyUiScale) { + return fontScale * Style.uiScaleRatio; + } + return fontScale; + } + property var features: ({}) + + opacity: enabled ? 1.0 : 0.6 + font.family: root.family + font.weight: Style.fontWeightMedium + font.pointSize: Math.max(1, root.pointSize * fontScale) + font.features: root.features + color: Color.mOnSurface + elide: Text.ElideRight + wrapMode: Text.NoWrap + verticalAlignment: Text.AlignVCenter + + textFormat: { + if (root.richTextEnabled) { + return Text.RichText; + } else if (root.markdownTextEnabled) { + return Text.MarkdownText; + } + return Text.PlainText; + } +} diff --git a/quickshell/compat/noctalia/Widgets/NTextInput.qml b/quickshell/compat/noctalia/Widgets/NTextInput.qml new file mode 100644 index 0000000..709e36c --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NTextInput.qml @@ -0,0 +1,238 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Widgets + +ColumnLayout { + id: root + + property string label: "" + property string description: "" + property string inputIconName: "" + property bool readOnly: false + property color labelColor: Color.mOnSurface + property color descriptionColor: Color.mOnSurfaceVariant + property string fontFamily: Settings.data.ui.fontDefault + property real fontSize: Style.fontSizeS + property int fontWeight: Style.fontWeightRegular + property var defaultValue: undefined + property string settingsPath: "" + property real radius: Style.iRadiusM + property real minimumInputWidth: 80 * Style.uiScaleRatio + property bool showClearButton: true + + property alias text: input.text + property alias placeholderText: input.placeholderText + property alias inputMethodHints: input.inputMethodHints + property alias horizontalAlignment: input.horizontalAlignment + property alias inputItem: input + + signal editingFinished + signal accepted + + opacity: enabled ? 1.0 : 0.3 + spacing: Style.marginS + + readonly property bool isValueChanged: (defaultValue !== undefined) && (text !== defaultValue) + readonly property string indicatorTooltip: defaultValue !== undefined ? I18n.tr("panels.indicator.default-value", { + "value": defaultValue === "" ? "(empty)" : String(defaultValue) + }) : "" + + NLabel { + label: root.label + description: root.description + labelColor: root.labelColor + descriptionColor: root.descriptionColor + visible: root.label !== "" || root.description !== "" + Layout.fillWidth: true + showIndicator: root.isValueChanged + indicatorTooltip: root.indicatorTooltip + } + + // An active control that blocks input, to avoid events leakage and dragging stuff in the background. + Control { + id: frameControl + + Layout.fillWidth: true + Layout.minimumWidth: root.minimumInputWidth + Layout.margins: Style.borderS + implicitHeight: Style.baseWidgetSize * 1.1 * Style.uiScaleRatio + + // This is important - makes the control accept focus + focusPolicy: Qt.StrongFocus + hoverEnabled: true + + background: Rectangle { + id: frame + + radius: root.radius + color: Color.mSurface + border.color: input.activeFocus ? Color.mSecondary : Color.mOutline + border.width: Style.borderS + + Behavior on border.color { + ColorAnimation { + duration: Style.animationFast + } + } + } + + contentItem: Item { + // Invisible background that captures ALL mouse events + MouseArea { + id: backgroundCapture + anchors.fill: parent + z: 0 + acceptedButtons: Qt.AllButtons + hoverEnabled: true + preventStealing: true + propagateComposedEvents: false + + onPressed: mouse => { + mouse.accepted = true; + // Focus the input and position cursor + input.forceActiveFocus(); + var inputPos = mapToItem(inputContainer, mouse.x, mouse.y); + if (inputPos.x >= 0 && inputPos.x <= inputContainer.width) { + var textPos = inputPos.x - Style.marginM; + if (textPos >= 0 && textPos <= input.width) { + input.cursorPosition = input.positionAt(textPos, input.height / 2); + } + } + } + + onReleased: mouse => { + mouse.accepted = true; + } + onDoubleClicked: mouse => { + mouse.accepted = true; + input.selectAll(); + } + onPositionChanged: mouse => { + mouse.accepted = true; + } + onWheel: wheel => { + wheel.accepted = false; + } + } + + // Container for the actual text field + Item { + id: inputContainer + anchors.fill: parent + anchors.leftMargin: Style.marginM + anchors.rightMargin: 0 + clip: true + z: 1 + + RowLayout { + anchors.fill: parent + spacing: 0 + + NIcon { + id: inputIcon + icon: root.inputIconName + + visible: root.inputIconName !== "" + enabled: false + + Layout.alignment: Qt.AlignVCenter + Layout.rightMargin: visible ? Style.marginS : 0 + } + + TextField { + id: input + + Layout.fillWidth: true + Layout.fillHeight: true + + verticalAlignment: TextInput.AlignVCenter + + echoMode: TextInput.Normal + readOnly: root.readOnly + placeholderTextColor: Qt.alpha(Color.mOnSurfaceVariant, 0.6) + color: enabled ? Color.mOnSurface : Qt.alpha(Color.mOnSurface, 0.4) + + selectByMouse: true + + topPadding: 0 + bottomPadding: 0 + leftPadding: 0 + rightPadding: 0 + + background: null + + font.family: root.fontFamily + font.pointSize: root.fontSize * Style.uiScaleRatio + font.weight: root.fontWeight + + onEditingFinished: root.editingFinished() + onAccepted: root.accepted() + + // Override mouse handling to prevent propagation + MouseArea { + id: textFieldMouse + anchors.fill: parent + acceptedButtons: Qt.AllButtons + preventStealing: true + propagateComposedEvents: false + cursorShape: Qt.IBeamCursor + + property int selectionStart: 0 + + onPressed: mouse => { + mouse.accepted = true; + input.forceActiveFocus(); + var pos = input.positionAt(mouse.x, mouse.y); + input.cursorPosition = pos; + selectionStart = pos; + } + + onPositionChanged: mouse => { + if (mouse.buttons & Qt.LeftButton) { + mouse.accepted = true; + var pos = input.positionAt(mouse.x, mouse.y); + input.select(selectionStart, pos); + } + } + + onDoubleClicked: mouse => { + mouse.accepted = true; + input.selectAll(); + } + + onReleased: mouse => { + mouse.accepted = true; + } + onWheel: wheel => { + wheel.accepted = false; + } + } + } + NIconButton { + id: clearButton + icon: "x" + tooltipText: (input.text.length > 0 && !root.readOnly && root.enabled) ? I18n.tr("common.clear") : "" + + Layout.alignment: Qt.AlignVCenter + border.width: 0 + + colorBg: "transparent" + colorBgHover: "transparent" + colorFg: Color.mOnSurface + colorFgHover: Color.mError + + visible: root.showClearButton && input.text.length > 0 && !root.readOnly + enabled: input.text.length > 0 && !root.readOnly && root.enabled + + onClicked: { + input.clear(); + input.forceActiveFocus(); + } + } + } + } + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NTextInputButton.qml b/quickshell/compat/noctalia/Widgets/NTextInputButton.qml new file mode 100644 index 0000000..bf7b9c4 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NTextInputButton.qml @@ -0,0 +1,57 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Widgets + +ColumnLayout { + id: root + Layout.fillWidth: true + + property alias text: input.text + property alias placeholderText: input.placeholderText + property string label: "" + property string description: "" + property string inputIconName: "" + property alias buttonIcon: button.icon + property alias buttonTooltip: button.tooltipText + property alias buttonEnabled: button.enabled + property real maximumWidth: 0 + + signal buttonClicked + signal inputTextChanged(string text) + signal inputEditingFinished + + spacing: Style.marginS + + // Label and description + NLabel { + label: root.label + description: root.description + visible: root.label !== "" || root.description !== "" + Layout.fillWidth: true + } + + // Input field with button + RowLayout { + Layout.fillWidth: true + spacing: Style.marginM + + NTextInput { + id: input + inputIconName: root.inputIconName + Layout.fillWidth: true + Layout.alignment: Qt.AlignVCenter + enabled: root.enabled + onTextChanged: root.inputTextChanged(text) + onEditingFinished: root.inputEditingFinished() + } + + // Button + NIconButton { + id: button + baseSize: Style.baseWidgetSize + onClicked: root.buttonClicked() + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NToggle.qml b/quickshell/compat/noctalia/Widgets/NToggle.qml new file mode 100644 index 0000000..31ebf15 --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NToggle.qml @@ -0,0 +1,110 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Widgets + +RowLayout { + id: root + + property string label: "" + property string description: "" + property string icon: "" + property bool checked: false + property bool hovering: false + property int baseSize: Math.round(Style.baseWidgetSize * 0.8 * Style.uiScaleRatio) + property var defaultValue: undefined + property string settingsPath: "" + + signal toggled(bool checked) + signal entered + signal exited + + Layout.fillWidth: true + spacing: Style.marginM + + readonly property bool isValueChanged: (defaultValue !== undefined) && (checked !== defaultValue) + readonly property string indicatorTooltip: defaultValue !== undefined ? I18n.tr("panels.indicator.default-value", { + "value": typeof defaultValue === "boolean" ? (defaultValue ? "true" : "false") : String(defaultValue) + }) : "" + + NLabel { + Layout.fillWidth: true + label: root.label + description: root.description + icon: root.icon + iconColor: root.checked ? Color.mPrimary : Color.mOnSurface + visible: root.label !== "" || root.description !== "" + showIndicator: root.isValueChanged + indicatorTooltip: root.indicatorTooltip + } + + Rectangle { + id: switcher + + opacity: enabled ? 1.0 : 0.6 + Layout.alignment: Qt.AlignVCenter + Layout.margins: Style.borderS + implicitWidth: Math.round(root.baseSize * .85) * 2 + implicitHeight: Math.round(root.baseSize * .5) * 2 + radius: Math.min(Style.iRadiusL, height / 2) + color: root.checked ? Color.mPrimary : Color.mSurface + border.color: Color.mOutline + border.width: Style.borderS + + Behavior on color { + ColorAnimation { + duration: Style.animationFast + } + } + + Behavior on border.color { + ColorAnimation { + duration: Style.animationFast + } + } + + Rectangle { + implicitWidth: Math.round(root.baseSize * 0.4) * 2 + implicitHeight: Math.round(root.baseSize * 0.4) * 2 + radius: Math.min(Style.iRadiusL, height / 2) + color: root.checked ? Color.mOnPrimary : Color.mPrimary + border.color: root.checked ? Color.mSurface : Color.mSurface + border.width: Style.borderM + anchors.verticalCenter: parent.verticalCenter + anchors.verticalCenterOffset: 0 + x: root.checked ? switcher.width - width - 3 : 3 + + Behavior on x { + NumberAnimation { + duration: Style.animationFast + easing.type: Easing.OutCubic + } + } + } + + MouseArea { + enabled: root.enabled + anchors.fill: parent + cursorShape: Qt.PointingHandCursor + hoverEnabled: true + onEntered: { + if (!enabled) + return; + hovering = true; + root.entered(); + } + onExited: { + if (!enabled) + return; + hovering = false; + root.exited(); + } + onClicked: { + if (!enabled) + return; + root.toggled(!root.checked); + } + } + } +} diff --git a/quickshell/compat/noctalia/Widgets/NValueSlider.qml b/quickshell/compat/noctalia/Widgets/NValueSlider.qml new file mode 100644 index 0000000..d73d46d --- /dev/null +++ b/quickshell/compat/noctalia/Widgets/NValueSlider.qml @@ -0,0 +1,116 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import qs.compat.noctalia.Commons +import qs.compat.noctalia.Widgets + +RowLayout { + id: root + + property real from: 0 + property real to: 1 + property real value: 0 + property real stepSize: 0.01 + property var cutoutColor: Color.mSurface + property bool snapAlways: true + property real heightRatio: 0.7 + property string text: "" + property real textSize: Style.fontSizeM + property real customHeight: -1 + property real customHeightRatio: -1 + property string label: "" + property string description: "" + property var defaultValue: undefined + property bool showReset: false + + spacing: Style.marginL + Layout.fillWidth: true + + // Signals + signal moved(real value) + signal pressedChanged(bool pressed, real value) + + readonly property bool sliderActive: slider.activeFocus || slider.pressed + readonly property bool isValueChanged: defaultValue !== undefined && (value !== defaultValue) + readonly property string indicatorTooltip: { + if (defaultValue === undefined) + return ""; + var defaultVal = defaultValue; + if (typeof defaultVal === "number") { + // If it's a decimal between 0 and 1, format as percentage + if (defaultVal > 0 && defaultVal <= 1 && from >= 0 && from < 1) { + return I18n.tr("panels.indicator.default-value", { + "value": Math.floor(defaultVal * 100) + "%" + }); + } + return I18n.tr("panels.indicator.default-value", { + "value": String(defaultVal) + }); + } + return I18n.tr("panels.indicator.default-value", { + "value": String(defaultVal) + }); + } + + ColumnLayout { + spacing: Style.marginS + Layout.fillWidth: true + + NLabel { + label: root.label + description: root.description + visible: root.label !== "" || root.description !== "" + showIndicator: root.isValueChanged + indicatorTooltip: root.indicatorTooltip + opacity: root.enabled ? 1.0 : 0.6 + Layout.fillWidth: true + } + + RowLayout { + spacing: Style.marginL + Layout.fillWidth: true + + NSlider { + id: slider + Layout.fillWidth: true + from: root.from + to: root.to + value: root.value + stepSize: root.stepSize + cutoutColor: root.cutoutColor + snapAlways: root.snapAlways + heightRatio: root.customHeightRatio > 0 ? root.customHeightRatio : root.heightRatio + onMoved: root.moved(value) + onPressedChanged: root.pressedChanged(pressed, value) + } + + NText { + visible: root.text !== "" + text: root.text + pointSize: root.textSize + family: Settings.data.ui.fontFixed + opacity: root.enabled ? 1.0 : 0.6 + Layout.alignment: Qt.AlignVCenter + Layout.preferredWidth: 45 * Style.uiScaleRatio + horizontalAlignment: Text.AlignRight + } + } + } + + Item { + id: buttonItem + visible: root.showReset && root.defaultValue !== undefined + Layout.preferredWidth: 30 * Style.uiScaleRatio + Layout.preferredHeight: 30 * Style.uiScaleRatio + + NIconButton { + icon: "restore" + enabled: root.enabled + baseSize: Style.baseWidgetSize * 0.8 + tooltipText: I18n.tr("common.reset") + onClicked: root.moved(root.defaultValue) + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + } + } +} diff --git a/quickshell/compat/omarchy/Commons/Border.qml b/quickshell/compat/omarchy/Commons/Border.qml new file mode 100644 index 0000000..948aa78 --- /dev/null +++ b/quickshell/compat/omarchy/Commons/Border.qml @@ -0,0 +1,242 @@ +pragma Singleton +import QtQuick +import "BorderGeometry.js" as Geometry + +// Central border-spec factory for shell surfaces and controls. A spec carries +// color, optional gradient, and top/right/bottom/left widths so renderers can +// choose the cheap Rectangle path or the Shape-ring path without duplicating +// theme parsing logic. +QtObject { + id: root + + function none() { + return flat("transparent", 0) + } + + function flat(color, width) { + return { + color: color || "transparent", + widths: Geometry.parseWidthSpec(width, 0), + gradient: { colors: [], angle: 0, enabled: false }, + } + } + + function value(section, key) { + var v = Color.shellValues[section + "." + key] + return (v === undefined || v === null) ? "" : v + } + + function valueOr(section, keys) { + for (var i = 0; i < keys.length; i++) { + var v = value(section, keys[i]) + if (String(v).length > 0) return v + } + return "" + } + + function resolveValueRef(raw) { + var s = String(raw || "").replace(/^\s+|\s+$/g, "") + var seen = {} + while (s.match(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/) && !seen[s]) { + seen[s] = true + var next = Color.shellValues[s] + if (next === undefined || next === null || String(next).length === 0) break + s = String(next).replace(/^\s+|\s+$/g, "") + } + return s + } + + function alpha(section, key, fallback) { + var raw = value(section, key) + if (String(raw).length === 0) return fallback + var n = Number(raw) + return isFinite(n) ? Geometry.clampAlpha(n) : fallback + } + + function cssColor(color, opacity) { + var a = opacity === undefined || opacity === null ? 1 : Geometry.clampAlpha(opacity) + if (color && typeof color === "object" && color.r !== undefined) { + if (typeof Qt !== "undefined" && Qt.rgba) { + return Qt.rgba(color.r, color.g, color.b, (color.a === undefined ? 1 : color.a) * a) + } + return "#" + + Geometry.padHex(color.r * 255) + + Geometry.padHex(color.g * 255) + + Geometry.padHex(color.b * 255) + + Geometry.padHex((color.a === undefined ? 1 : color.a) * a * 255) + } + + var s = String(color || "").replace(/^\s+|\s+$/g, "") + var role = s.toLowerCase() + if (role === "foreground" || role === "text") return cssColor(Color.foreground, a) + if (role === "accent") return cssColor(Color.accent, a) + if (role === "urgent") return cssColor(Color.urgent, a) + if (role === "background") return cssColor(Color.background, a) + if (role === "transparent") return "transparent" + return Geometry.canonicalColor(s, a) + } + + function resolvedGradient(raw, fallbackColor, opacity) { + var s = String(raw || "").replace(/^\s+|\s+$/g, "") + if (s.length === 0) return { colors: [], angle: 0, enabled: false } + + var parts = s.split(/\s+/) + var colors = [] + var angle = 0 + for (var i = 0; i < parts.length; i++) { + if (parts[i].match(/^-?\d+(?:\.\d+)?deg$/)) angle = Number(parts[i].replace(/deg$/, "")) + else colors.push(cssColor(parts[i], opacity)) + } + if (colors.length === 0) colors.push(cssColor(fallbackColor, opacity)) + return { colors: colors, angle: angle, enabled: colors.length > 1 } + } + + function sameColor(a, b) { + if (typeof Qt === "undefined" || !Qt.color) return String(a) === String(b) + var ca = typeof a === "string" ? Qt.color(a) : a + var cb = typeof b === "string" ? Qt.color(b) : b + if (!ca || !cb || ca.r === undefined || cb.r === undefined) return String(a) === String(b) + return Math.round(ca.r * 255) === Math.round(cb.r * 255) + && Math.round(ca.g * 255) === Math.round(cb.g * 255) + && Math.round(ca.b * 255) === Math.round(cb.b * 255) + && Math.round((ca.a === undefined ? 1 : ca.a) * 255) === Math.round((cb.a === undefined ? 1 : cb.a) * 255) + } + + function localOrSurfaceSpec(section, token, localColor, defaultColor, fallbackWidth, alphaKey) { + if (!sameColor(localColor, defaultColor)) return flat(localColor, fallbackWidth) + return surfaceSpec(section, token, localColor, fallbackWidth, alphaKey) + } + + function surfaceWidths(section, token, fallbackWidth) { + var base = valueOr(section, token === "border" ? ["border-width"] : [token + "-width", "border-width"]) + var widths = Geometry.parseWidthSpec(base, fallbackWidth) + return Geometry.withSideOverrides( + widths, + valueOr(section, token === "border" ? ["border-width-top"] : [token + "-width-top", "border-width-top"]), + valueOr(section, token === "border" ? ["border-width-right"] : [token + "-width-right", "border-width-right"]), + valueOr(section, token === "border" ? ["border-width-bottom"] : [token + "-width-bottom", "border-width-bottom"]), + valueOr(section, token === "border" ? ["border-width-left"] : [token + "-width-left", "border-width-left"]) + ) + } + + function borderValue(raw, fallbackColor, opacity, legacyGradientRaw) { + var fallback = cssColor(fallbackColor, opacity) + var primaryRaw = String(raw || "").replace(/^\s+|\s+$/g, "") + var primary = resolvedGradient(primaryRaw.length > 0 ? primaryRaw : fallbackColor, fallbackColor, opacity) + var color = primary.colors.length > 0 ? primary.colors[0] : fallback + var gradient = primary.enabled ? primary : { colors: [], angle: 0, enabled: false } + + // Backward compatibility for existing configs written during the separate + // border-gradient experiment. New configs put solid colors and gradients in + // the same border token. + if (!gradient.enabled && String(legacyGradientRaw || "").replace(/^\s+|\s+$/g, "").length > 0) { + var legacy = resolvedGradient(legacyGradientRaw, color, opacity) + if (legacy.enabled) gradient = legacy + } + + return { color: color, gradient: gradient } + } + + function surfaceSpec(section, token, fallbackColor, fallbackWidth, alphaKey) { + var opacity = alpha(section, alphaKey || token + "-alpha", 1.0) + var legacyGradientRaw = valueOr(section, token === "border" ? ["border-gradient"] : [token + "-gradient", "border-gradient"]) + var resolved = borderValue(resolveValueRef(value(section, token)), fallbackColor, opacity, legacyGradientRaw) + + return { + color: resolved.color, + widths: surfaceWidths(section, token, fallbackWidth), + gradient: resolved.gradient, + } + } + + function hyprlandActiveSpec(fallbackColor, fallbackWidth) { + var raw = value("hyprland", "active-border") + var opacity = alpha("hyprland", "active-border-alpha", 1.0) + + // Existing generated themes predate [hyprland] and already keep the active + // border under [notifications]. Use it as the compatibility source until + // the next theme refresh writes the shared token. + if (String(raw).length === 0) { + raw = value("notifications", "border") + opacity = alpha("notifications", "border-alpha", opacity) + } + + var resolved = borderValue(resolveValueRef(raw), fallbackColor, opacity, "") + return { + color: resolved.color, + widths: Geometry.parseWidthSpec(value("hyprland", "active-border-width"), fallbackWidth), + gradient: resolved.gradient, + } + } + + function controlPrefix(state) { + if (state === "hover" || state === "hot") return "hover-cursor" + return state || "normal" + } + + function controlColor(prefix, foreground, accent, urgent) { + if (prefix === "focus") return Style.focusStateColor(foreground, accent, urgent) + if (prefix === "hover-cursor") return Style.hoverStateColor(foreground, accent, urgent) + if (prefix === "selected") return Style.selectedStateColor(foreground, accent, urgent) + return Style.normalStateColor(foreground, accent, urgent) + } + + function controlAlpha(prefix) { + if (prefix === "focus") return Style.focusBorderAlpha + if (prefix === "hover-cursor") return Style.hoverBorderAlpha + if (prefix === "selected") return Style.selectedBorderAlpha + return Style.normalBorderAlpha + } + + function controlFallbackWidth(prefix) { + if (prefix === "focus") return Style.focusBorderWidth + if (prefix === "hover-cursor") return Style.hoverBorderWidth + if (prefix === "selected") return Style.selectedBorderWidth + return Style.normalBorderWidth + } + + function controlWidths(state) { + var prefix = controlPrefix(state) + var fallbackWidth = controlFallbackWidth(prefix) + var base = Style.styleOverrides[prefix + "-border-width"] + var widths = Geometry.parseWidthSpec(base, fallbackWidth) + return Geometry.withSideOverrides( + widths, + Style.styleOverrides[prefix + "-border-width-top"], + Style.styleOverrides[prefix + "-border-width-right"], + Style.styleOverrides[prefix + "-border-width-bottom"], + Style.styleOverrides[prefix + "-border-width-left"] + ) + } + + function controlHasWidth(state) { + return Geometry.maxWidth(controlWidths(state)) > 0 + } + + function controlSpec(state, foreground, accent, urgent) { + var prefix = controlPrefix(state) + var resolved = borderValue( + Style.styleOverrides[prefix + "-border"], + controlColor(prefix, foreground, accent, urgent), + controlAlpha(prefix), + Style.styleOverrides[prefix + "-border-gradient"] + ) + + return { color: resolved.color, widths: controlWidths(prefix), gradient: resolved.gradient } + } + + function withWidth(spec, width) { + if (!spec) return flat("transparent", 0) + return { color: spec.color, gradient: spec.gradient, widths: Geometry.parseWidthSpec(width, 0) } + } + + function isNone(spec) { return !spec || Geometry.maxWidth(spec.widths) <= 0 } + function needsOverlay(spec) { return Geometry.needsOverlay(spec) } + function canUseNative(spec) { return Geometry.canUseNative(spec) } + function top(spec) { return spec && spec.widths ? spec.widths.top : 0 } + function right(spec) { return spec && spec.widths ? spec.widths.right : 0 } + function bottom(spec) { return spec && spec.widths ? spec.widths.bottom : 0 } + function left(spec) { return spec && spec.widths ? spec.widths.left : 0 } + function uniformWidth(spec) { return spec && spec.widths ? spec.widths.top : 0 } + function color(spec) { return spec ? spec.color : "transparent" } +} diff --git a/quickshell/compat/omarchy/Commons/BorderGeometry.js b/quickshell/compat/omarchy/Commons/BorderGeometry.js new file mode 100644 index 0000000..0a90903 --- /dev/null +++ b/quickshell/compat/omarchy/Commons/BorderGeometry.js @@ -0,0 +1,373 @@ +.pragma library + +function clamp(value, min, max) { + var n = Number(value) + if (!isFinite(n)) return min + return Math.max(min, Math.min(max, n)) +} + +function clampAlpha(value) { + return clamp(value, 0, 1) +} + +function padHex(value) { + var n = clamp(Math.round(Number(value)), 0, 255) + var h = n.toString(16) + return h.length < 2 ? "0" + h : h +} + +function qmlHexColor(rgb, alphaByte) { + var rgbPart = String(rgb || "").replace(/^#/, "") + var a = clamp(Math.round(Number(alphaByte)), 0, 255) + + if (typeof Qt !== "undefined" && Qt.rgba && rgbPart.length >= 6) { + return Qt.rgba( + parseInt(rgbPart.substring(0, 2), 16) / 255, + parseInt(rgbPart.substring(2, 4), 16) / 255, + parseInt(rgbPart.substring(4, 6), 16) / 255, + a / 255 + ) + } + + var aHex = padHex(a) + return aHex.toLowerCase() === "ff" ? "#" + rgbPart : "#" + rgbPart + aHex +} + +function canonicalColor(value, alpha) { + var a = alpha === undefined || alpha === null ? 1 : clampAlpha(alpha) + var s = String(value || "").replace(/^\s+|\s+$/g, "") + var m + + m = s.match(/^#([0-9A-Fa-f]{3})$/) + if (m) { + var sh = m[1] + return qmlHexColor( + sh.charAt(0) + sh.charAt(0) + + sh.charAt(1) + sh.charAt(1) + + sh.charAt(2) + sh.charAt(2), + a * 255 + ) + } + + m = s.match(/^#([0-9A-Fa-f]{6})([0-9A-Fa-f]{2})?$/) + if (m) { + var colorAlpha = m[2] ? parseInt(m[2], 16) / 255 : 1 + return qmlHexColor(m[1], colorAlpha * a * 255) + } + + m = s.match(/^[Rr][Gg][Bb]\(([0-9A-Fa-f]{6})\)$/) + if (m) return qmlHexColor(m[1], a * 255) + + m = s.match(/^[Rr][Gg][Bb][Aa]\(([0-9A-Fa-f]{6})([0-9A-Fa-f]{2})\)$/) + if (m) return qmlHexColor(m[1], (parseInt(m[2], 16) / 255) * a * 255) + + m = s.match(/^[Rr][Gg][Bb]\(([0-9]+),([0-9]+),([0-9]+)\)$/) + if (m) return qmlHexColor(padHex(m[1]) + padHex(m[2]) + padHex(m[3]), a * 255) + + m = s.match(/^[Rr][Gg][Bb][Aa]\(([0-9]+),([0-9]+),([0-9]+),([0-9.]+)\)$/) + if (m) return qmlHexColor(padHex(m[1]) + padHex(m[2]) + padHex(m[3]), clampAlpha(m[4]) * a * 255) + + m = s.match(/^0x([0-9A-Fa-f]{2})([0-9A-Fa-f]{6})$/) + if (m) return qmlHexColor(m[2], (parseInt(m[1], 16) / 255) * a * 255) + + return s +} + +function parseWidthSpec(value, fallback) { + var fb = Number(fallback) + if (!isFinite(fb) || fb < 0) fb = 0 + + if (value === undefined || value === null || value === "") { + return { top: fb, right: fb, bottom: fb, left: fb } + } + + var parts = String(value).match(/-?\d+(?:\.\d+)?/g) || [] + var nums = [] + for (var i = 0; i < parts.length && i < 4; i++) { + var n = Number(parts[i]) + nums.push(isFinite(n) && n > 0 ? n : 0) + } + + if (nums.length === 0) nums = [fb] + if (nums.length === 1) return { top: nums[0], right: nums[0], bottom: nums[0], left: nums[0] } + if (nums.length === 2) return { top: nums[0], right: nums[1], bottom: nums[0], left: nums[1] } + if (nums.length === 3) return { top: nums[0], right: nums[1], bottom: nums[2], left: nums[1] } + return { top: nums[0], right: nums[1], bottom: nums[2], left: nums[3] } +} + +function withSideOverrides(widths, top, right, bottom, left) { + var out = { + top: Number(widths && widths.top) || 0, + right: Number(widths && widths.right) || 0, + bottom: Number(widths && widths.bottom) || 0, + left: Number(widths && widths.left) || 0, + } + if (top !== undefined && top !== null && top !== "") out.top = Math.max(0, Number(top) || 0) + if (right !== undefined && right !== null && right !== "") out.right = Math.max(0, Number(right) || 0) + if (bottom !== undefined && bottom !== null && bottom !== "") out.bottom = Math.max(0, Number(bottom) || 0) + if (left !== undefined && left !== null && left !== "") out.left = Math.max(0, Number(left) || 0) + return out +} + +function parseGradientSpec(value, fallbackColor, alpha) { + var s = String(value || "").replace(/^\s+|\s+$/g, "") + var colors = [] + var angle = 0 + var parts = s.length > 0 ? s.split(/\s+/) : [] + + for (var i = 0; i < parts.length; i++) { + var part = parts[i] + var angleMatch = part.match(/^(-?\d+(?:\.\d+)?)deg$/) + if (angleMatch) angle = Number(angleMatch[1]) + else colors.push(canonicalColor(part, alpha)) + } + + if (colors.length === 0 && fallbackColor !== undefined && fallbackColor !== null) + colors.push(canonicalColor(fallbackColor, alpha)) + + return { + colors: colors, + angle: isFinite(angle) ? angle : 0, + enabled: colors.length > 1, + } +} + +function isUniform(widths) { + if (!widths) return true + return widths.top === widths.right && widths.top === widths.bottom && widths.top === widths.left +} + +function maxWidth(widths) { + if (!widths) return 0 + return Math.max(widths.top || 0, widths.right || 0, widths.bottom || 0, widths.left || 0) +} + +function needsOverlay(spec) { + if (!spec) return false + if (maxWidth(spec.widths) <= 0) return false + return !!(spec.gradient && spec.gradient.enabled) || !isUniform(spec.widths) +} + +function canUseNative(spec) { + return !!spec && maxWidth(spec.widths) > 0 && !needsOverlay(spec) +} + +function normalizeRadii(w, h, r) { + var tl = { rx: Math.max(0, Number(r.tlrx) || 0), ry: Math.max(0, Number(r.tlry) || 0) } + var tr = { rx: Math.max(0, Number(r.trrx) || 0), ry: Math.max(0, Number(r.trry) || 0) } + var br = { rx: Math.max(0, Number(r.brrx) || 0), ry: Math.max(0, Number(r.brry) || 0) } + var bl = { rx: Math.max(0, Number(r.blrx) || 0), ry: Math.max(0, Number(r.blry) || 0) } + var scale = 1 + + if (tl.rx + tr.rx > w && tl.rx + tr.rx > 0) scale = Math.min(scale, w / (tl.rx + tr.rx)) + if (bl.rx + br.rx > w && bl.rx + br.rx > 0) scale = Math.min(scale, w / (bl.rx + br.rx)) + if (tl.ry + bl.ry > h && tl.ry + bl.ry > 0) scale = Math.min(scale, h / (tl.ry + bl.ry)) + if (tr.ry + br.ry > h && tr.ry + br.ry > 0) scale = Math.min(scale, h / (tr.ry + br.ry)) + + if (scale < 1) { + tl.rx *= scale; tr.rx *= scale; br.rx *= scale; bl.rx *= scale + tl.ry *= scale; tr.ry *= scale; br.ry *= scale; bl.ry *= scale + } + + return { tl: tl, tr: tr, br: br, bl: bl } +} + +function appendArc(path, rx, ry, sweep, point) { + if (rx > 0 && ry > 0) path.push("A", rx, ry, 0, 0, sweep, point.x, point.y) + else path.push("L", point.x, point.y) +} + +function roundedRectPath(x, y, w, h, radii) { + if (w <= 0 || h <= 0) return "" + var r = normalizeRadii(w, h, radii) + var right = x + w + var bottom = y + h + var p = [] + + p.push("M", x + r.tl.rx, y) + p.push("H", right - r.tr.rx) + appendArc(p, r.tr.rx, r.tr.ry, 1, { x: right, y: y + r.tr.ry }) + p.push("V", bottom - r.br.ry) + appendArc(p, r.br.rx, r.br.ry, 1, { x: right - r.br.rx, y: bottom }) + p.push("H", x + r.bl.rx) + appendArc(p, r.bl.rx, r.bl.ry, 1, { x: x, y: bottom - r.bl.ry }) + p.push("V", y + r.tl.ry) + appendArc(p, r.tl.rx, r.tl.ry, 1, { x: x + r.tl.rx, y: y }) + p.push("Z") + + return p.join(" ") +} + +function borderBoundary(x, y, w, h, radii) { + var r = radii && radii.tl ? radii : normalizeRadii(w, h, radii) + var right = x + w + var bottom = y + h + return { + start: [ + { x: x + r.tl.rx, y: y }, + { x: right, y: y + r.tr.ry }, + { x: right - r.br.rx, y: bottom }, + { x: x, y: bottom - r.bl.ry }, + ], + end: [ + { x: right - r.tr.rx, y: y }, + { x: right, y: bottom - r.br.ry }, + { x: x + r.bl.rx, y: bottom }, + { x: x, y: y + r.tl.ry }, + ], + corner: [r.tr, r.br, r.bl, r.tl], + } +} + +function appendForwardCorner(path, boundary, side) { + var corner = boundary.corner[side] + appendArc(path, corner.rx, corner.ry, 1, boundary.start[(side + 1) % 4]) +} + +function appendReverseCorner(path, boundary, side) { + var corner = boundary.corner[side] + appendArc(path, corner.rx, corner.ry, 0, boundary.end[side]) +} + +function reverseBoundaryPath(boundary) { + var p = ["M", boundary.start[0].x, boundary.start[0].y] + for (var side = 3; side >= 0; side--) { + appendReverseCorner(p, boundary, side) + p.push("L", boundary.start[side].x, boundary.start[side].y) + } + p.push("Z") + return p.join(" ") +} + +function runPath(outer, inner, start, length) { + var previous = (start + 3) % 4 + var next = (start + length) % 4 + var p = ["M", outer.end[previous].x, outer.end[previous].y] + + appendForwardCorner(p, outer, previous) + for (var offset = 0; offset < length; offset++) { + var side = (start + offset) % 4 + p.push("L", outer.end[side].x, outer.end[side].y) + appendForwardCorner(p, outer, side) + } + + p.push("L", inner.start[next].x, inner.start[next].y) + for (var reverseOffset = length - 1; reverseOffset >= 0; reverseOffset--) { + var reverseSide = (start + reverseOffset) % 4 + appendReverseCorner(p, inner, reverseSide) + p.push("L", inner.start[reverseSide].x, inner.start[reverseSide].y) + } + appendReverseCorner(p, inner, previous) + p.push("Z") + return p.join(" ") +} + +function radiiFit(w, h, r) { + return r.tlrx + r.trrx <= w + && r.blrx + r.brrx <= w + && r.tlry + r.blry <= h + && r.trry + r.brry <= h +} + +// Internal geometry output used by ringPath and focused topology tests. +// Connected enabled-side runs share one closed contour; opposite-only sides +// need two. The all-sides case is one compound winding path with a reversed +// inner loop. Disabled sides never require touching or epsilon-offset inner +// geometry, so a zero/zero rounded corner emits no border pixels. +function borderPaths(w, h, radius, widths) { + w = Math.max(0, Number(w) || 0) + h = Math.max(0, Number(h) || 0) + radius = Math.max(0, Number(radius) || 0) + widths = widths || { top: 0, right: 0, bottom: 0, left: 0 } + if (w <= 0 || h <= 0) return [] + + var top = Math.max(0, Number(widths.top) || 0) + var right = Math.max(0, Number(widths.right) || 0) + var bottom = Math.max(0, Number(widths.bottom) || 0) + var left = Math.max(0, Number(widths.left) || 0) + var enabled = [top > 0, right > 0, bottom > 0, left > 0] + if (!enabled[0] && !enabled[1] && !enabled[2] && !enabled[3]) return [] + + var outerRadii = normalizeRadii(w, h, { + tlrx: radius, tlry: radius, + trrx: radius, trry: radius, + brrx: radius, brry: radius, + blrx: radius, blry: radius, + }) + var outerPath = roundedRectPath(0, 0, w, h, { + tlrx: outerRadii.tl.rx, tlry: outerRadii.tl.ry, + trrx: outerRadii.tr.rx, trry: outerRadii.tr.ry, + brrx: outerRadii.br.rx, brry: outerRadii.br.ry, + blrx: outerRadii.bl.rx, blry: outerRadii.bl.ry, + }) + + var iw = w - left - right + var ih = h - top - bottom + if (iw <= 0 || ih <= 0) return [outerPath] + + var desiredInnerRadii = { + tlrx: Math.max(0, outerRadii.tl.rx - left), + tlry: Math.max(0, outerRadii.tl.ry - top), + trrx: Math.max(0, outerRadii.tr.rx - right), + trry: Math.max(0, outerRadii.tr.ry - top), + brrx: Math.max(0, outerRadii.br.rx - right), + brry: Math.max(0, outerRadii.br.ry - bottom), + blrx: Math.max(0, outerRadii.bl.rx - left), + blry: Math.max(0, outerRadii.bl.ry - bottom), + } + + // Normalizing an inner radius that cannot fit can move its tangent beyond + // the outer rounded boundary. Winding fill may then paint outside the outer + // contour. Conservatively treat that rounded interior as consumed instead. + if (!radiiFit(iw, ih, desiredInnerRadii)) return [outerPath] + + var innerRadii = normalizeRadii(iw, ih, desiredInnerRadii) + var outer = borderBoundary(0, 0, w, h, outerRadii) + var inner = borderBoundary(left, top, iw, ih, innerRadii) + + if (enabled[0] && enabled[1] && enabled[2] && enabled[3]) + return [outerPath + " " + reverseBoundaryPath(inner)] + + var paths = [] + for (var start = 0; start < 4; start++) { + if (!enabled[start] || enabled[(start + 3) % 4]) continue + var length = 1 + while (length < 4 && enabled[(start + length) % 4]) length++ + paths.push(runPath(outer, inner, start, length)) + } + return paths +} + +function ringPath(w, h, radius, widths) { + return borderPaths(w, h, radius, widths).join(" ") +} + +function gradientEndpoints(w, h, angle) { + w = Math.max(1, Number(w) || 1) + h = Math.max(1, Number(h) || 1) + var rad = (Number(angle) || 0) * Math.PI / 180 + var dx = Math.cos(rad) + var dy = Math.sin(rad) + var len = (Math.abs(w * dx) + Math.abs(h * dy)) / 2 + var cx = w / 2 + var cy = h / 2 + return { + x1: cx - dx * len, + y1: cy - dy * len, + x2: cx + dx * len, + y2: cy + dy * len, + } +} + +function stopColor(colors, index) { + if (!colors || colors.length === 0) return "transparent" + if (index < colors.length) return colors[index] + return colors[colors.length - 1] +} + +function stopPosition(colors, index) { + var count = colors ? colors.length : 0 + if (count <= 1) return index === 0 ? 0 : 1 + if (index >= count) return 1 + return index / (count - 1) +} diff --git a/quickshell/compat/omarchy/Commons/Color.qml b/quickshell/compat/omarchy/Commons/Color.qml new file mode 100644 index 0000000..f732851 --- /dev/null +++ b/quickshell/compat/omarchy/Commons/Color.qml @@ -0,0 +1,109 @@ +pragma Singleton +import QtQuick +import "../../../theme" as G + +// glassMxrph replacement for Omarchy's Color singleton. Same API (palette, +// per-surface groups, helper functions), but every value comes from the +// glassMxrph theme so plugins render with our glass tint, accent and text. +// Omarchy's theme files (colors.toml / shell.toml) are not read. +QtObject { + id: root + + property color foreground: G.Theme.text + property color background: G.Theme.surface + property color accent: G.Theme.accentVivid + property color urgent: G.Theme.urgent + property color muted: G.Theme.textSecondary + + // Kept for API compatibility; always empty here. + property var shellValues: ({}) + property var themeShellValues: ({}) + property var userShellValues: ({}) + + // Surfaces: glass tint at the shell's glass opacity, hairline borders. + readonly property color glass: Qt.alpha(G.Theme.surface, G.Theme.glassOpacity) + readonly property color panel: Qt.alpha(G.Theme.surface, G.Theme.panelOpacity) + + function pick(key, fallback) { + return fallback; + } + function pickAlpha(key, fallback) { + return Util.clampAlpha(fallback); + } + function firstColorToken(value) { + return value; + } + function flatColor(value, fallback) { + return fallback; + } + function composed(colorKey, alphaKey, colorFallback, alphaFallback) { + return Util.alpha(colorFallback, alphaFallback); + } + function loadColors(raw) { + } + function parseShell(raw) { + return {}; + } + function mergeShell() { + } + function loadShell(raw) { + } + function loadUserShell(raw) { + } + + readonly property QtObject bar: QtObject { + property color background: root.glass + property color text: root.foreground + property color active: root.accent + } + readonly property QtObject popups: QtObject { + property color background: root.glass + property color text: root.foreground + property color border: G.Theme.border + } + readonly property QtObject tooltip: QtObject { + property color background: root.panel + property color text: root.foreground + property color border: G.Theme.border + } + readonly property QtObject notifications: QtObject { + property color background: root.panel + property color text: root.foreground + property color border: G.Theme.border + property color countdown: root.accent + } + readonly property QtObject menu: QtObject { + property color background: root.panel + property color text: root.foreground + property color border: G.Theme.border + property color scrim: Qt.alpha(G.Theme.surface, 0.5) + property color selectedBackground: G.Theme.hover + property color selectedText: root.accent + property color selectedBorder: "transparent" + } + readonly property QtObject polkit: QtObject { + property color background: root.panel + property color text: root.foreground + property color textError: root.urgent + property color border: G.Theme.border + property color borderError: root.urgent + property color accent: root.accent + property color scrim: Qt.alpha(G.Theme.surface, 0.5) + } + readonly property QtObject lock: QtObject { + property color background: root.panel + property color text: root.foreground + property color placeholder: Qt.alpha(root.foreground, 0.66) + property color textError: root.urgent + property color border: G.Theme.border + property color borderActive: root.accent + property color borderError: root.urgent + property color selection: Qt.alpha(root.accent, 0.45) + } + readonly property QtObject imagePicker: QtObject { + property color scrim: Qt.alpha(G.Theme.surface, 0.5) + property color text: root.foreground + property color selectedBorder: root.accent + property color unselectedBorder: Qt.alpha(root.foreground, 0.28) + } +} diff --git a/quickshell/compat/omarchy/Commons/IpcRegistry.qml b/quickshell/compat/omarchy/Commons/IpcRegistry.qml new file mode 100644 index 0000000..e479df2 --- /dev/null +++ b/quickshell/compat/omarchy/Commons/IpcRegistry.qml @@ -0,0 +1,77 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Io + +// Every ShellIpc handler, so the shell can answer an omarchy-shell call over +// its own socket instead of through a qs ipc client started per call. It +// answers only what qs ipc would: the first live, enabled handler for a +// target, and only the functions that handler declares. Those are allowed by +// name, never inferred from what a function call happens to reach: QObject +// methods such as destroy() are callable but not enumerable. +Singleton { + id: root + + property var handlers: [] + + // A bare handler's own functions (signals and hooks such as targetChanged), + // which qs ipc never exposes and neither may the socket. + readonly property var builtins: functionNames(bareHandler) + + IpcHandler { + id: bareHandler + enabled: false + } + + function functionNames(object) { + var names = [] + for (var key in object) { + if (typeof object[key] === "function") names.push(key) + } + return names + } + + function register(handler) { + if (handlers.indexOf(handler) === -1) handlers.push(handler) + } + + function unregister(handler) { + var index = handlers.indexOf(handler) + if (index !== -1) handlers.splice(index, 1) + } + + function handlerFor(target) { + for (var i = 0; i < handlers.length; i++) { + var handler = handlers[i] + if (handler && handler.enabled && handler.target === target) return handler + } + return null + } + + // { ran: true, output } once the function ran; { ran: false } when it did + // not (unknown target or function, wrong argument count), so the caller + // can ask qs ipc for its exact answer without running anything twice. + // The functions a handler declares: what it enumerates beyond a bare + // handler, less property change signals. + function declaredFunctions(handler) { + return functionNames(handler).filter(function(name) { + return builtins.indexOf(name) === -1 && !/Changed$/.test(name) + }) + } + + function call(target, method, args) { + var handler = handlerFor(target) + if (!handler) return { ran: false } + if (declaredFunctions(handler).indexOf(method) === -1) return { ran: false } + if (handler[method].length !== args.length) return { ran: false } + + var result + try { + result = handler[method].apply(handler, args) + } catch (error) { + console.warn("ipc " + target + " " + method + " failed: " + error) + return { ran: true, output: "" } + } + return { ran: true, output: result === undefined || result === null ? "" : String(result) } + } +} diff --git a/quickshell/compat/omarchy/Commons/ShellIpc.qml b/quickshell/compat/omarchy/Commons/ShellIpc.qml new file mode 100644 index 0000000..15f5d27 --- /dev/null +++ b/quickshell/compat/omarchy/Commons/ShellIpc.qml @@ -0,0 +1,12 @@ +import QtQuick +import Quickshell.Io + +// An IpcHandler the shell can also answer over its own socket (see +// IpcRegistry), so omarchy-shell reaches it without a qs ipc client. qs ipc +// still reaches it as before. +IpcHandler { + id: handler + + Component.onCompleted: IpcRegistry.register(handler) + Component.onDestruction: IpcRegistry.unregister(handler) +} diff --git a/quickshell/compat/omarchy/Commons/Style.qml b/quickshell/compat/omarchy/Commons/Style.qml new file mode 100644 index 0000000..56761c3 --- /dev/null +++ b/quickshell/compat/omarchy/Commons/Style.qml @@ -0,0 +1,466 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Io +import "../../../theme" as G + +// Shared structural style tokens for the shell. Color is the palette +// singleton; Style holds everything else themes can influence — corner +// rounding, gap to screen edges, state affordances, spacing, typography +// scale, and bar dimensions. +// +// `cornerRadius` mirrors Hyprland's `decoration:rounding`. `gapsOut` is +// half of Hyprland's `general:gaps_out` — Hyprland's value works well as +// a window-to-window gap but feels too cavernous when used as the +// distance from a panel/notification to the screen edge, so the shell +// halves it. Themes and user Hyprland config own those values; the +// shell picks them up by re-running `hyprctl getoption` on startup and +// after theme IPC applies a theme. +// +// Typography, spacing, and bar size come from theme/shell.toml. +// `[font] base-size` is the rem root; every `Style.font.` derives +// from it via the scale multipliers below unless the theme pins that +// specific token. `[spacing] scale` multiplies shared margins, gaps, +// padding, controls, and panel dimensions while preserving each component's +// proportions; by default it also tracks `base-size`. `[bar] +// size-horizontal` / `size-vertical` set the cross-axis dimension for +// top/bottom and left/right bars at the default 12px font size; by default +// those dimensions scale with `base-size` so larger fonts don't clip. +QtObject { + id: root + + // glassMxrph: rounding and spacing follow the glassMxrph theme; panels + // attach to the bar as drawers, so there is no gap to the screen edge. + property int cornerRadius: Math.round(G.Theme.radius * 0.5) + property int gapsOut: 0 + + // ---------------------------------------------------------- state tokens + // + // Shared interactive-state tokens for every reusable surface in the kit. + // The vocabulary: + // normal — idle control chrome + // hover-cursor — mouse hover OR panel keyboard cursor (`hasCursor`) + // selected — persistent chosen/current state + // focus — actual Qt activeFocus, defaulting to hover-cursor + // + // Each state has a color token plus fill/border alphas. Color tokens + // may be palette roles (`foreground`, `accent`, `urgent`, `background`) + // or hex colors. Set a state's border width to 0 to drop that border. + // glassMxrph state look: hairline borders, soft hover/selected fills and an + // accent selection, matching glassMxrph's own controls. + property var styleOverrides: ({ + "normal-border-alpha": 0.18, + "hover-cursor-border-alpha": 0.18, + "focus-border-alpha": 0.6, + "focus-color": "accent", + "normal-fill-alpha": 0.05, + "hover-cursor-fill-alpha": 0.09, + "selected-color": "accent", + "selected-fill-alpha": 0.28, + "selected-border-width": 0, + "pressed-fill-alpha": 0.16, + "selection-color": "accent" + }) + + function styleRawNum(key) { + var v = styleOverrides[key] + var n = Number(v) + return isFinite(n) ? n : null + } + + function styleNum(key, fallback) { + var n = styleRawNum(key) + return n === null ? fallback : n + } + + function styleAlpha(key, fallback) { + return Util.clampAlpha(styleNum(key, fallback)) + } + + function styleString(key, fallback) { + var v = styleOverrides[key] + if (typeof v !== "string") return fallback + v = v.replace(/^\s+|\s+$/g, "") + return v.length > 0 ? v : fallback + } + + readonly property string normalColorToken: styleString("normal-color", "foreground") + readonly property string hoverColorToken: styleString("hover-cursor-color", "foreground") + readonly property string selectedColorToken: styleString("selected-color", "foreground") + readonly property string pressedColorToken: styleString("pressed-color", hoverColorToken) + readonly property string focusColorToken: styleString("focus-color", hoverColorToken) + readonly property string selectionColorToken: styleString("selection-color", "foreground") + + readonly property int normalBorderWidth: Math.max(0, Math.round(styleNum("normal-border-width", 1))) + readonly property int hoverBorderWidth: Math.max(0, Math.round(styleNum("hover-cursor-border-width", normalBorderWidth))) + readonly property int selectedBorderWidth: Math.max(0, Math.round(styleNum("selected-border-width", 0))) + readonly property int focusBorderWidth: Math.max(0, Math.round(styleNum("focus-border-width", hoverBorderWidth))) + + readonly property real normalFillAlpha: styleAlpha("normal-fill-alpha", 0.04) + readonly property real hoverFillAlpha: styleAlpha("hover-cursor-fill-alpha", 0.08) + readonly property real selectedFillAlpha: styleAlpha("selected-fill-alpha", 0.18) + readonly property real pressedFillAlpha: styleAlpha("pressed-fill-alpha", 0.22) + readonly property real focusFillAlpha: styleAlpha("focus-fill-alpha", hoverFillAlpha) + readonly property real selectionFillAlpha: styleAlpha("selection-fill-alpha", 0.35) + + readonly property real normalBorderAlpha: styleAlpha("normal-border-alpha", 0.4) + readonly property real hoverBorderAlpha: styleAlpha("hover-cursor-border-alpha", 0.25) + readonly property real selectedBorderAlpha: styleAlpha("selected-border-alpha", 1.0) + readonly property real focusBorderAlpha: styleAlpha("focus-border-alpha", hoverBorderAlpha) + + function colorFromHex(value, fallback) { + var s = String(value || "").replace(/^\s+|\s+$/g, "") + var shortHex = s.match(/^#([0-9A-Fa-f]{3})$/) + if (shortHex) { + var sh = shortHex[1] + return Qt.rgba( + parseInt(sh.charAt(0) + sh.charAt(0), 16) / 255, + parseInt(sh.charAt(1) + sh.charAt(1), 16) / 255, + parseInt(sh.charAt(2) + sh.charAt(2), 16) / 255, + 1) + } + var hex = s.match(/^#([0-9A-Fa-f]{6})([0-9A-Fa-f]{2})?$/) + if (!hex) return fallback + var h = hex[1] + return Qt.rgba( + parseInt(h.substr(0, 2), 16) / 255, + parseInt(h.substr(2, 2), 16) / 255, + parseInt(h.substr(4, 2), 16) / 255, + hex[2] ? parseInt(hex[2], 16) / 255 : 1) + } + + function resolveStateColor(token, foreground, accent, urgent, fallback) { + var fb = fallback || foreground || Color.foreground + var s = String(token || "").replace(/^\s+|\s+$/g, "") + var role = s.toLowerCase() + if (role === "foreground" || role === "text") return foreground || Color.foreground + if (role === "accent") return accent || Color.accent + if (role === "urgent") return urgent || Color.urgent + if (role === "background") return Color.background + if (role === "transparent") return Qt.rgba(0, 0, 0, 0) + return colorFromHex(s, fb) + } + + function normalStateColor(foreground, accent, urgent) { + return resolveStateColor(normalColorToken, foreground, accent, urgent, foreground || Color.foreground) + } + + function hoverStateColor(foreground, accent, urgent) { + return resolveStateColor(hoverColorToken, foreground, accent, urgent, foreground || Color.foreground) + } + + function selectedStateColor(foreground, accent, urgent) { + return resolveStateColor(selectedColorToken, foreground, accent, urgent, foreground || Color.foreground) + } + + function pressedStateColor(foreground, accent, urgent) { + return resolveStateColor(pressedColorToken, foreground, accent, urgent, hoverStateColor(foreground, accent, urgent)) + } + + function focusStateColor(foreground, accent, urgent) { + var role = String(focusColorToken || "").replace(/^\s+|\s+$/g, "").toLowerCase() + if (role === "hover" || role === "hover-cursor" || role === "inherit") + return hoverStateColor(foreground, accent, urgent) + return resolveStateColor(focusColorToken, foreground, accent, urgent, hoverStateColor(foreground, accent, urgent)) + } + + function selectionStateColor(foreground, accent, urgent) { + return resolveStateColor(selectionColorToken, foreground, accent, urgent, foreground || Color.foreground) + } + + function normalFillFor(foreground, accent, urgent) { return Util.alpha(normalStateColor(foreground, accent, urgent), normalFillAlpha) } + function hoverFillFor(foreground, accent, urgent) { return Util.alpha(hoverStateColor(foreground, accent, urgent), hoverFillAlpha) } + function selectedFillFor(foreground, accent, urgent) { return Util.alpha(selectedStateColor(foreground, accent, urgent), selectedFillAlpha) } + function pressedFillFor(foreground, accent, urgent) { return Util.alpha(pressedStateColor(foreground, accent, urgent), pressedFillAlpha) } + function focusFillFor(foreground, accent, urgent) { return Util.alpha(focusStateColor(foreground, accent, urgent), focusFillAlpha) } + function selectionFillFor(foreground, accent, urgent) { return Util.alpha(selectionStateColor(foreground, accent, urgent), selectionFillAlpha) } + + function normalBorderFor(foreground, accent, urgent) { return Util.alpha(normalStateColor(foreground, accent, urgent), normalBorderAlpha) } + function hoverBorderFor(foreground, accent, urgent) { return Util.alpha(hoverStateColor(foreground, accent, urgent), hoverBorderAlpha) } + function selectedBorderFor(foreground, accent, urgent) { return Util.alpha(selectedStateColor(foreground, accent, urgent), selectedBorderAlpha) } + function focusBorderFor(foreground, accent, urgent) { return Util.alpha(focusStateColor(foreground, accent, urgent), focusBorderAlpha) } + + // Composite helpers for the focus > hover > normal priority chain used by + // every form control surface (TextField, NumberField, Dropdown, Toggle, + // etc.). Saves callers from re-writing the three-line ternary ladder for + // fill / border / border-width on every Rectangle background. + function controlFill(focused, hot, foreground, accent) { + if (focused) return focusFillFor(foreground, accent) + if (hot) return hoverFillFor(foreground, accent) + return normalFillFor(foreground, accent) + } + + function controlBorder(focused, hot, foreground, accent) { + if (focused) return focusBorderFor(foreground, accent) + if (hot) return hoverBorderFor(foreground, accent) + return normalBorderFor(foreground, accent) + } + + function controlBorderWidth(focused, hot) { + if (focused) return focusBorderWidth + if (hot) return hoverBorderWidth + return normalBorderWidth + } + + // Convenience colors resolved against the foundational palette. + readonly property color normalFill: normalFillFor(Color.foreground, Color.accent, Color.urgent) + readonly property color hoverFill: hoverFillFor(Color.foreground, Color.accent, Color.urgent) + readonly property color selectedFill: selectedFillFor(Color.foreground, Color.accent, Color.urgent) + readonly property color pressedFill: pressedFillFor(Color.foreground, Color.accent, Color.urgent) + readonly property color focusFillColor: focusFillFor(Color.foreground, Color.accent, Color.urgent) + readonly property color normalBorderColor: normalBorderFor(Color.foreground, Color.accent, Color.urgent) + readonly property color hoverBorderColor: hoverBorderFor(Color.foreground, Color.accent, Color.urgent) + readonly property color selectedBorderColor: selectedBorderFor(Color.foreground, Color.accent, Color.urgent) + readonly property color focusBorderColor: focusBorderFor(Color.foreground, Color.accent, Color.urgent) + readonly property color selectedAccentFill: Util.alpha(Color.accent, selectedFillAlpha) + readonly property color selectionFill: selectionFillFor(Color.foreground, Color.accent, Color.urgent) + + // ---------------------------------------------------------- spacing + // + // The spacing scale is the shell equivalent of rem for margins, gaps, + // and padding. Components keep their existing proportions by asking for + // the old pixel value through `Style.space(px)` (or `spaceReal(px)` for + // fractional geometry); themes can make the shell denser or roomier + // with `[spacing] scale`, or pin individual tokens. + property real spacingScale: 1.0 + property bool spacingScaleWithFont: true + property var spacingOverrides: ({}) + readonly property real effectiveSpacingScale: spacingScale * (spacingScaleWithFont ? fontScale : 1) + + function spaceReal(px) { + var n = Number(px) + if (!isFinite(n) || n <= 0) return 0 + return n * effectiveSpacingScale + } + + function space(px) { + var n = spaceReal(px) + if (n <= 0) return 0 + return Math.max(1, Math.round(n)) + } + + function spacingToken(key, fallback) { + var v = spacingOverrides[key] + var n = Number(v) + return (isFinite(n) && n >= 0) ? Math.round(n) : space(fallback) + } + + readonly property QtObject spacing: QtObject { + readonly property real scale: root.effectiveSpacingScale + + readonly property int hairline: root.space(1) + readonly property int xxs: root.spacingToken("xxs", 2) + readonly property int xs: root.spacingToken("xs", 3) + readonly property int sm: root.spacingToken("sm", 4) + readonly property int md: root.spacingToken("md", 6) + readonly property int lg: root.spacingToken("lg", 8) + readonly property int xl: root.spacingToken("xl", 10) + readonly property int xxl: root.spacingToken("xxl", 12) + readonly property int xxxl: root.spacingToken("xxxl", 14) + readonly property int huge: root.spacingToken("huge", 18) + + readonly property int controlGap: root.spacingToken("control-gap", 8) + readonly property int controlPaddingX: root.spacingToken("control-padding-x", 10) + readonly property int controlPaddingY: root.spacingToken("control-padding-y", 6) + readonly property int inputPaddingY: root.spacingToken("input-padding-y", 7) + readonly property int controlHeight: root.spacingToken("control-height", 28) + readonly property int popupRowHeight: root.spacingToken("popup-row-height", 28) + readonly property int dropdownWidth: root.spacingToken("dropdown-width", 240) + readonly property int searchableDropdownWidth: root.spacingToken("searchable-dropdown-width", 260) + readonly property int numberFieldWidth: root.spacingToken("number-field-width", 120) + readonly property int searchablePopupMinHeight: root.spacingToken("searchable-popup-min-height", 220) + readonly property int rowGap: root.spacingToken("row-gap", 8) + readonly property int rowPaddingX: root.spacingToken("row-padding-x", 12) + readonly property int labelGap: root.spacingToken("label-gap", 4) + readonly property int panelGap: root.spacingToken("panel-gap", 14) + readonly property int panelPadding: root.spacingToken("panel-padding", 18) + readonly property int popupPadding: root.spacingToken("popup-padding", 14) + } + + // ---------------------------------------------------------- typography + // + // `fontFamily` defaults to "monospace" so the bar and every qs.Ui + // component follows the fontconfig alias `omarchy-font-set` writes. + // Themes can override per-token via [font] in shell.toml, but the + // family stays system-wide. + property string fontFamily: Qt.application.font.family + + // The concrete family `monospace` resolves to right now, e.g. + // "JetBrainsMono Nerd Font". Bind `font.family` to `fontFamily` (so the + // alias path keeps working when the user runs `omarchy font set`), but + // read `resolvedFontFamily` when you want to *display* what's drawing. + property string resolvedFontFamily: Qt.application.font.family + + // The only sanity floor is 1px. Themes and users can make this as large + // as they like; if the shell gets ridiculous, that's their call. + property int fontBaseSize: 12 + + property var fontOverrides: ({}) + property var barOverrides: ({}) + property bool barScaleWithFont: true + readonly property real fontScale: Math.max(1 / 12, fontBaseSize / 12) + + function fontPx(mult) { + return Math.max(1, Math.round(fontBaseSize * mult)) + } + + function fontToken(key, fallback) { + var v = fontOverrides[key] + var n = Number(v) + return (isFinite(n) && n > 0) ? Math.round(n) : fallback + } + + function barToken(key, fallback) { + var v = barOverrides[key] + var n = Number(v) + var base = (isFinite(n) && n > 0) ? n : fallback + if (barScaleWithFont) base *= fontScale + return Math.max(1, Math.round(base)) + } + + function boolToken(value, fallback) { + if (value === undefined || value === null) return fallback + var s = String(value).replace(/^\s+|\s+$/g, "").toLowerCase() + if (s === "true" || s === "1" || s === "yes" || s === "on") return true + if (s === "false" || s === "0" || s === "no" || s === "off") return false + return fallback + } + + // The menu, polkit, emojis, and clipboard surfaces honor an + // OMARCHY_MENU_FONT override for users who want a different family on the + // summoned popups than on the bar. Resolved once at startup; an empty env + // value falls back to the shared fontconfig alias. + readonly property string menuFontFamily: { + var override = Quickshell.env("OMARCHY_MENU_FONT") + return (override && override.length > 0) ? override : fontFamily + } + + readonly property QtObject font: QtObject { + readonly property string family: root.fontFamily + readonly property string resolvedFamily: root.resolvedFontFamily + readonly property string menuFamily: root.menuFontFamily + readonly property int baseSize: root.fontBaseSize + + readonly property int caption: root.fontToken("caption", root.fontPx(0.833)) // 10 + readonly property int bodySmall: root.fontToken("body-small", root.fontPx(0.917)) // 11 + readonly property int body: root.fontToken("body", root.fontPx(1.0)) // 12 + readonly property int subtitle: root.fontToken("subtitle", root.fontPx(1.083)) // 13 + readonly property int title: root.fontToken("title", root.fontPx(1.167)) // 14 + readonly property int heading: root.fontToken("heading", root.fontPx(1.333)) // 16 + readonly property int display: root.fontToken("display", root.fontPx(2.0)) // 24 + readonly property int displayLarge: root.fontToken("display-large", root.fontPx(2.333)) // 28 + + readonly property int iconSmall: root.fontToken("icon-small", bodySmall) + readonly property int icon: root.fontToken("icon", title) + readonly property int iconLarge: root.fontToken("icon-large", root.fontPx(1.5)) // 18 + } + + readonly property QtObject bar: QtObject { + readonly property int sizeHorizontal: root.barToken("size-horizontal", 26) + readonly property int sizeVertical: root.barToken("size-vertical", 28) + readonly property int iconSlot: root.barToken("icon-slot", 27) + readonly property int iconCanvas: root.barToken("icon-canvas", 16) + readonly property int iconFont: root.barToken("icon-font", 13) + readonly property int statusSlot: root.barToken("status-slot", 21) + } + + // Off with Hyprland's own animations, as `omarchy toggle animations` turns + // them off for machines that render on the CPU. Every shell animation runs + // for Style.duration(ms), which is then 0, so nothing is drawn in between. + property bool reduceMotion: G.Theme.duration === 0 + + function duration(ms) { + return reduceMotion ? 0 : ms + } + + // Hyprland/fontconfig lookups are not used under glassMxrph. + function refresh() { + } + + function scheduleRefresh() { + } + + function applyRoundingJson(raw) { + try { + var json = JSON.parse(raw || "{}") + var n = Number(json.int) + if (isFinite(n) && n >= 0) cornerRadius = n + } catch (e) { + // hyprctl missing / Hyprland not running — leave the previous value. + } + } + + function applyGapsOutJson(raw) { + try { + var json = JSON.parse(raw || "{}") + var css = String(json.css || "") + var parts = css.match(/-?\d+(?:\.\d+)?/g) || [] + var n = parts.length > 0 ? Number(parts[0]) : Number(json.int) + if (isFinite(n) && n >= 0) gapsOut = Math.max(0, Math.round(n / 2)) + } catch (e) { + // hyprctl missing / Hyprland not running — leave the previous value. + } + } + + // Pull typography, bar dimensions, state tokens, and spacing out of the + // shell.toml dict that Color already parsed. Called by Color.loadShell so + // a single parse pass feeds both singletons. + function applyShellValues(values) { + var fontOut = {} + var barOut = {} + var styleOut = {} + var spacingOut = {} + var nextBase = 12 + var nextSpacingScale = 1.0 + var nextSpacingScaleWithFont = true + var nextBarScaleWithFont = true + var v = values || {} + for (var fullKey in v) { + var dot = fullKey.indexOf(".") + if (dot < 0) continue + var section = fullKey.substr(0, dot) + var key = fullKey.substr(dot + 1) + var raw = v[fullKey] + if (section === "font") { + var ival = parseInt(raw, 10) + if (!isFinite(ival)) continue + if (key === "base-size") nextBase = ival + else fontOut[key] = ival + } else if (section === "bar") { + if (key === "scale-with-font") { + nextBarScaleWithFont = boolToken(raw, nextBarScaleWithFont) + } else if (key === "size-horizontal" || key === "size-vertical") { + var b = parseInt(raw, 10) + if (isFinite(b)) barOut[key] = b + } + } else if (section === "spacing") { + if (key === "scale-with-font") { + nextSpacingScaleWithFont = boolToken(raw, nextSpacingScaleWithFont) + } else { + var fval = parseFloat(raw) + if (!isFinite(fval)) continue + if (key === "scale") nextSpacingScale = fval + else spacingOut[key] = fval + } + } else if (section === "controls" || section === "style") { + // Strings are passed through; styleRawNum/styleString coerce on read. + // [style] is the legacy name for [controls]. + styleOut[key] = raw + } + } + // Keep only a 1px sanity floor. Per-token overrides aren't clamped + // either — a theme that wants display-large = 64 should be allowed to + // ship it. + if (!isFinite(nextBase) || nextBase < 1) nextBase = 1 + if (!isFinite(nextSpacingScale) || nextSpacingScale < 0) nextSpacingScale = 1.0 + spacingScale = nextSpacingScale + spacingScaleWithFont = nextSpacingScaleWithFont + fontBaseSize = nextBase + fontOverrides = fontOut + barOverrides = barOut + barScaleWithFont = nextBarScaleWithFont + spacingOverrides = spacingOut + styleOverrides = styleOut + } + +} diff --git a/quickshell/compat/omarchy/Commons/Util.qml b/quickshell/compat/omarchy/Commons/Util.qml new file mode 100644 index 0000000..cacc98d --- /dev/null +++ b/quickshell/compat/omarchy/Commons/Util.qml @@ -0,0 +1,159 @@ +pragma Singleton +import Quickshell +import QtQuick + +// Shared utility helpers used across plugins. Pure functions only — no +// state. Anything stateful belongs on Color, Style, or a service. +QtObject { + id: root + + function clamp(value, min, max) { + var n = Number(value) + if (!isFinite(n)) return min + return Math.max(min, Math.min(max, n)) + } + + function clampAlpha(value) { + return clamp(value, 0, 1) + } + + function wheelSteps(accumulator, delta) { + // Some mouse/compositor combinations scale a single notch well beyond + // Qt's conventional 120 units. Keep one event to one step while still + // accumulating the smaller deltas emitted by touchpads. + delta = Math.max(-120, Math.min(120, delta)) + if (accumulator * delta < 0) accumulator = 0 + var total = accumulator + delta + var steps = total < 0 ? Math.ceil(total / 120) : Math.floor(total / 120) + return { steps: steps, remainder: total - steps * 120 } + } + + // Compose a base color with an opacity. Accepts a color object or a hex + // string; null/undefined yields transparent black at the requested alpha. + function alpha(c, opacity) { + var a = clampAlpha(opacity) + if (!c) return Qt.rgba(0, 0, 0, a) + if (typeof c === "string") c = Qt.color(c) + return Qt.rgba(c.r, c.g, c.b, a) + } + + // file:// URL with each path segment percent-encoded so spaces and + // special chars in user paths don't break Image.source. + function fileUrl(path) { + if (!path) return "" + return "file://" + String(path).split("/").map(encodeURIComponent).join("/") + } + + function isVideoPath(path) { + return /\.(mp4|m4v|mov|webm|mkv|avi)$/i.test(String(path || "")) + } + + // Single-quote a string for bash. The replace handles embedded single + // quotes by closing, escaping, and re-opening the literal. + function shellQuote(value) { + return "'" + String(value || "").replace(/'/g, "'\\''") + "'" + } + + function execDetached(command) { + Quickshell.execDetached(["bash", "-lc", command]) + } + + // Run an argv vector without a shell interpreting it: the constant `exec "$@"` + // means the args only ever land in positional parameters, which bash expands + // without re-tokenizing — so untrusted data ($(id), a filename) stays literal. + // The login shell (-l) keeps the PATH/session env GUI targets (omasnap, mpv, + // xdg-open) need. Prefer this over execDetached for anything built from input. + function execArgv(argv) { + Quickshell.execDetached(["bash", "-lc", 'exec "$@"', "bash"].concat(argv)) + } + + function isPlainObject(value) { + return value !== null && typeof value === "object" && !Array.isArray(value) + } + + function canonicalWidgetId(id) { + return String(id || "") + } + + // Best-effort base64 decode. Returns "" on parse failure rather than + // surfacing garbage downstream. + function decodeBase64(value) { + var s = String(value || "") + if (!s) return "" + try { return Qt.atob(s) } catch (e) { return "" } + } + + function cloneJson(value) { + return JSON.parse(JSON.stringify(value === undefined ? null : value)) + } + + // Parse the last line of a custom-module / indicator process output as + // waybar-style JSON ({text, class, tooltip, ...}). Falls back to {text: raw} + // when the output isn't JSON, and {} for empty output. + function parseModuleJson(raw) { + var text = String(raw || "").trim() + if (!text) return {} + var lines = text.split("\n") + try { + return JSON.parse(lines[lines.length - 1]) + } catch (e) { + return { text: text } + } + } + + // Standard Qt text-editing keys shared by every searchable panel's filter: + // Backspace delete previous character + // Ctrl+Backspace delete previous word (Qt DeleteStartOfWord) + // Ctrl+U clear the whole field + // True only when the event would actually change the text, so an empty + // filter never swallows the key — panels keep their own empty-filter + // fallbacks (e.g. menu back-navigation) in later branches. + function editsFilter(event, text) { + if (!text) return false + // Alt/Meta-modified sequences belong to other shortcuts — never edit here. + if (event.modifiers & (Qt.AltModifier | Qt.MetaModifier)) return false + if (event.key === Qt.Key_U) // Ctrl+U only (not Ctrl+Shift+U → Unicode input) + return event.modifiers === Qt.ControlModifier + return event.key === Qt.Key_Backspace // plain, Shift, or Ctrl Backspace + } + + // New filter text after applying an edit key. Assumes editsFilter(event, text). + function editedFilter(event, text) { + if (event.key === Qt.Key_U) return "" // Ctrl+U: clear + if (event.modifiers & Qt.ControlModifier) // Ctrl+Backspace: word + return text.replace(/\s+$/, "").replace(/\S+$/, "") + return text.slice(0, -1) // Backspace: char + } + + // Layout normalization shared by bar config consumers + // so the two never drift. Entries are deep-cloned to decouple from the + // input config; consumers can mutate without leaking back to shell.json. + function normalizeLayoutEntry(entry) { + if (typeof entry === "string") return { id: canonicalWidgetId(entry) } + if (isPlainObject(entry) && entry.id) { + var copy = cloneJson(entry) + copy.id = canonicalWidgetId(copy.id) + return copy + } + return null + } + + function normalizeLayoutSection(list) { + if (!Array.isArray(list)) return [] + var out = [] + for (var i = 0; i < list.length; i++) { + var e = normalizeLayoutEntry(list[i]) + if (e) out.push(e) + } + return out + } + + function normalizeLayout(layout) { + var src = isPlainObject(layout) ? layout : {} + return { + left: normalizeLayoutSection(src.left), + center: normalizeLayoutSection(src.center), + right: normalizeLayoutSection(src.right) + } + } +} diff --git a/quickshell/compat/omarchy/Commons/qmldir b/quickshell/compat/omarchy/Commons/qmldir new file mode 100644 index 0000000..dab0e3b --- /dev/null +++ b/quickshell/compat/omarchy/Commons/qmldir @@ -0,0 +1,6 @@ +singleton Border 1.0 Border.qml +singleton Color 1.0 Color.qml +singleton IpcRegistry 1.0 IpcRegistry.qml +singleton Style 1.0 Style.qml +singleton Util 1.0 Util.qml +ShellIpc 1.0 ShellIpc.qml diff --git a/quickshell/compat/omarchy/Host/PluginShellApi.qml b/quickshell/compat/omarchy/Host/PluginShellApi.qml new file mode 100644 index 0000000..0202aa0 --- /dev/null +++ b/quickshell/compat/omarchy/Host/PluginShellApi.qml @@ -0,0 +1,70 @@ +import QtQuick + +// Capability-scoped shell surface for installed third-party plugins. +// +// The callbacks are closed over one plugin id by shell.qml. A plugin can call +// them directly, but it cannot widen their scope: ordinary plugins are limited +// to their own id, and full-bar callbacks independently enforce their explicit +// non-authentication UI scope. This object avoids directly injecting the host +// shell, but it is not a QML sandbox: visual plugins share the host object tree. +QtObject { + id: api + + required property string pluginId + + property var appLibrary: null + property var bar: null + property var barConfig: ({}) + property var idleConfig: ({}) + + property var _serviceLookup: null + property var _firstPartyServiceLookup: null + property var _barEntryShellLookup: null + property var _summon: null + property var _hide: null + property var _toggle: null + property var _isOpen: null + property var _updateSettings: null + property var _mutateBarConfig: null + + function serviceFor(id) { + return _serviceLookup ? _serviceLookup(String(id || "")) : null + } + + // Only full-bar facades receive narrow proxies for the specific + // non-authentication services used by the built-in bar widgets. + function firstPartyServiceFor(id) { + return _firstPartyServiceLookup + ? _firstPartyServiceLookup(String(id || "")) : null + } + + function pluginShellForBarEntry(ownerId, moduleName) { + return _barEntryShellLookup + ? _barEntryShellLookup(String(ownerId || ""), String(moduleName || "")) : null + } + + function summon(id, payloadJson) { + return _summon ? _summon(String(id || ""), String(payloadJson || "")) : false + } + + function hide(id) { + return _hide ? _hide(String(id || "")) : false + } + + function toggle(id, payloadJson) { + return _toggle ? _toggle(String(id || ""), String(payloadJson || "")) : false + } + + function isPluginOpen(id) { + return _isOpen ? _isOpen(String(id || "")) : false + } + + function updateEntryInline(id, settings) { + return _updateSettings ? _updateSettings(String(id || ""), settings) : false + } + + function mutateShellConfig(mutator) { + return _mutateBarConfig && typeof mutator === "function" + ? _mutateBarConfig(mutator) : false + } +} diff --git a/quickshell/compat/omarchy/Host/qmldir b/quickshell/compat/omarchy/Host/qmldir new file mode 100644 index 0000000..152d2d3 --- /dev/null +++ b/quickshell/compat/omarchy/Host/qmldir @@ -0,0 +1 @@ +PluginShellApi 1.0 PluginShellApi.qml diff --git a/quickshell/compat/omarchy/NOTICE b/quickshell/compat/omarchy/NOTICE new file mode 100644 index 0000000..bb6547d --- /dev/null +++ b/quickshell/compat/omarchy/NOTICE @@ -0,0 +1,26 @@ +Omarchy shell UI kit (qs.Ui, qs.Commons), vendored for running Omarchy shell +plugins inside glassMxrph. Source: https://github.com/omacom/omarchy (branch quattro, shell/). +glassMxrph replaces Color and the Style tokens and restyles WidgetButton, ToggleSwitch, PanelSlider, +PopupCard and KeyboardPanel so plugins match the glassMxrph look; imports point at qs.compat.omarchy.*. +bin/ holds portable Omarchy helper commands, with #!/usr/bin/env shebangs for NixOS. + +Copyright (c) David Heinemeier Hansson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/quickshell/compat/omarchy/Ui/BackgroundMedia.qml b/quickshell/compat/omarchy/Ui/BackgroundMedia.qml new file mode 100644 index 0000000..2bb8105 --- /dev/null +++ b/quickshell/compat/omarchy/Ui/BackgroundMedia.qml @@ -0,0 +1,45 @@ +import QtQuick +import qs.compat.omarchy.Commons +// The shell draws stills only. OWE owns video backgrounds on the desktop, and +// it feeds the lock screen through its own socket. +Item { + id: root + + property string path: "" + property int version: 0 + // Unversioned images cache by path. A caller whose version changes with every + // new file, as the lock's does, may cache too: the version is in the URL. + property bool cached: version === 0 + // A caller that knows the size its screen needs, in physical pixels, sets + // constrainDecode and decodeSize. The image then waits for that size rather + // than decoding at the file's native size first. + property bool constrainDecode: false + property size decodeSize: Qt.size(0, 0) + readonly property var current: imageLoader.item + readonly property bool ready: current ? current.ready : false + readonly property bool video: Util.isVideoPath(path) + // Cache-bust images selected in a running lock session, so a theme switch + // that replaces the file behind an unchanged path shows the new pixels. + readonly property url imageUrl: path && !video ? Util.fileUrl(path) + (version ? "?v=" + version : "") : "" + + Loader { + id: imageLoader + anchors.fill: parent + active: root.path !== "" && !root.video + sourceComponent: imageComponent + } + + Component { + id: imageComponent + + Image { + readonly property bool ready: status === Image.Ready + source: !root.constrainDecode || root.decodeSize.width > 0 ? root.imageUrl : "" + fillMode: Image.PreserveAspectCrop + asynchronous: true + cache: root.cached + sourceSize.width: root.constrainDecode ? root.decodeSize.width : (root.version > 0 ? width : 0) + sourceSize.height: root.constrainDecode ? root.decodeSize.height : (root.version > 0 ? height : 0) + } + } +} diff --git a/quickshell/compat/omarchy/Ui/BarIconButton.qml b/quickshell/compat/omarchy/Ui/BarIconButton.qml new file mode 100644 index 0000000..5cff098 --- /dev/null +++ b/quickshell/compat/omarchy/Ui/BarIconButton.qml @@ -0,0 +1,66 @@ +import QtQuick +import Quickshell +import qs.compat.omarchy.Commons +WidgetButton { + id: root + + property Component iconComponent: null + property real slotSize: Style.bar.iconSlot + property real opticalSize: Style.bar.iconCanvas + property bool debugOpticalBounds: Quickshell.env("OMARCHY_DEBUG_BAR_ICONS") === "1" + // Measured against the slot, which the open-panel underline centers on. + readonly property real opticalCenterErrorX: glyph.visible ? opticalCanvas.x + glyph.paintedCenterX - root.width / 2 : 0 + readonly property real glyphPaintedWidth: glyph.visible ? glyph.tightWidth : 0 + readonly property real glyphBaselineY: glyph.visible ? glyph.baselineY : 0 + readonly property int glyphFontSize: glyph.visible ? glyph.renderedFontSize : 0 + + labelVisible: false + hasVisualContent: text !== "" || iconComponent !== null + fontSize: Style.bar.iconFont + fixedWidth: vertical ? -1 : slotSize + fixedHeight: vertical ? slotSize : -1 + + Item { + id: opticalCanvas + // Placed exactly, not anchored: centerIn snaps an even canvas in an odd slot + // to a whole pixel, pulling every glyph off the open-panel underline. + x: (root.width - width) / 2 + y: (root.height - height) / 2 + width: root.opticalSize + height: root.opticalSize + + OpticalGlyph { + id: glyph + anchors.fill: parent + visible: root.iconComponent === null + text: root.text + fontFamily: root.fontFamily + fontSize: root.fontSize + color: root.active && root.useActiveColor ? root.activeColor : root.foreground + rotation: root.textRotation + debugBounds: root.debugOpticalBounds + } + + Loader { + anchors.fill: parent + visible: root.iconComponent !== null + sourceComponent: root.iconComponent + } + + Rectangle { + visible: root.debugOpticalBounds && root.iconComponent !== null + anchors.fill: parent + color: "transparent" + border.width: 1 + border.color: "#4488ff" + } + } + + Rectangle { + visible: root.debugOpticalBounds + anchors.fill: parent + color: "transparent" + border.width: 1 + border.color: "#ff4455" + } +} diff --git a/quickshell/compat/omarchy/Ui/BarIndicator.qml b/quickshell/compat/omarchy/Ui/BarIndicator.qml new file mode 100644 index 0000000..591f1b5 --- /dev/null +++ b/quickshell/compat/omarchy/Ui/BarIndicator.qml @@ -0,0 +1,50 @@ +import QtQuick +import qs.compat.omarchy.Commons +BarIconButton { + id: root + + property string moduleName: "" + property var settings: ({}) + property string activeText: "" + property string inactiveText: activeText + property string activeTooltipText: "" + property string inactiveTooltipText: activeTooltipText + property string indicatorBlock: "single" + property var indicatorHost: null + property var activeOverride: null + readonly property bool effectiveActive: activeOverride === null || activeOverride === undefined ? active : activeOverride === true + readonly property bool belongsInBlock: indicatorBlock === "active" ? effectiveActive : (indicatorBlock === "inactive" ? !effectiveActive : true) + readonly property bool inactiveRevealed: !effectiveActive && !!indicatorHost && indicatorHost.revealInactiveIndicators + + function extractData(raw) { + return Util.parseModuleJson(raw) + } + + function syncIndicatorOpacity() { + root.opacity = !belongsInBlock ? 0 : (effectiveActive ? 1 : (inactiveRevealed ? 0.45 : 0)) + } + + Component.onCompleted: syncIndicatorOpacity() + onActiveChanged: syncIndicatorOpacity() + onEffectiveActiveChanged: syncIndicatorOpacity() + onBarChanged: syncIndicatorOpacity() + onBelongsInBlockChanged: syncIndicatorOpacity() + onInactiveRevealedChanged: syncIndicatorOpacity() + onIndicatorBlockChanged: syncIndicatorOpacity() + + visible: belongsInBlock && (text !== "" || keepSpace) + text: effectiveActive ? activeText : inactiveText + tooltipText: effectiveActive ? activeTooltipText : inactiveTooltipText + keepSpace: true + dimmed: !effectiveActive + concealed: !effectiveActive && !inactiveRevealed + interactive: belongsInBlock && (effectiveActive || indicatorBlock === "inactive" || inactiveRevealed) + useActiveColor: false + maintainIndicatorReveal: indicatorBlock === "inactive" + revealHost: indicatorHost + fontSize: Style.font.caption + horizontalMargin: 5 + verticalPadding: 5 + fixedWidth: vertical ? -1 : Style.bar.statusSlot + fixedHeight: vertical ? Style.bar.statusSlot : -1 +} diff --git a/quickshell/compat/omarchy/Ui/BarWidget.qml b/quickshell/compat/omarchy/Ui/BarWidget.qml new file mode 100644 index 0000000..b6ae4bb --- /dev/null +++ b/quickshell/compat/omarchy/Ui/BarWidget.qml @@ -0,0 +1,44 @@ +import QtQuick +import qs.compat.omarchy.Commons +// Base item every bar widget extends. Codifies the three properties the +// bar host injects into each widget slot: +// bar - the host Bar instance (foreground/background/run/etc). +// moduleName - widget's canonical id, used by the host registry to look +// up settings and to disambiguate inline IPC routes. +// settings - per-widget overrides read from shell.json's layout entry. +// +// Widgets are free to add their own properties, signals, and child items. +Item { + id: root + + property QtObject bar: null + property string moduleName: "" + property var settings: ({}) + + // Bar geometry, lifted off the host. Widgets read these constantly to pick + // between horizontal/vertical layouts; defining them on the base keeps the + // `bar ? bar.x : fallback` ternary out of every widget body. + readonly property bool vertical: bar ? bar.vertical : false + readonly property int barSize: bar ? bar.barSize : Style.bar.sizeHorizontal + + // Run `method` on every live instance of this widget. An IPC target only + // ever routes to one handler, but a bar surface exists per monitor, so the + // instance that owns the target relays the call to its peers — otherwise a + // refresh would land on a single screen and leave the others stale. + function broadcast(method) { + var items = bar && typeof bar.moduleWidgets === "function" + ? bar.moduleWidgets(moduleName) : [root] + for (var i = 0; i < items.length; i++) { + if (items[i] && typeof items[i][method] === "function") items[i][method]() + } + } + + // Read a single value from this widget's inline shell.json entry, with a + // fallback for missing/null values. Every widget that takes user-tunable + // settings needs this; defining it once on the base keeps the wiring + // consistent. + function setting(name, fallback) { + var value = settings ? settings[name] : undefined + return value === undefined || value === null ? fallback : value + } +} diff --git a/quickshell/compat/omarchy/Ui/BorderOverlay.qml b/quickshell/compat/omarchy/Ui/BorderOverlay.qml new file mode 100644 index 0000000..94d5072 --- /dev/null +++ b/quickshell/compat/omarchy/Ui/BorderOverlay.qml @@ -0,0 +1,54 @@ +import QtQuick +import QtQuick.Shapes +import qs.compat.omarchy.Commons +import "../Commons/BorderGeometry.js" as Geometry + +// Visual-only border renderer. It draws closed side-run contours, or a +// compound winding path for all four sides, so asymmetric/gradient borders +// do not require touching odd-even paths. Flat uniform borders use Rectangle.border. +Item { + id: root + + property var borderSpec: Border.none() + property real radius: 0 + + readonly property var _widths: borderSpec && borderSpec.widths ? borderSpec.widths : Geometry.parseWidthSpec(0, 0) + readonly property bool hasBorder: Geometry.maxWidth(_widths) > 0 + readonly property var _gradient: borderSpec && borderSpec.gradient ? borderSpec.gradient : ({ colors: [], angle: 0, enabled: false }) + readonly property var _colors: _gradient.enabled ? _gradient.colors : [Border.color(borderSpec), Border.color(borderSpec)] + readonly property var _endpoints: Geometry.gradientEndpoints(width, height, _gradient.angle || 0) + readonly property string _path: Geometry.ringPath(width, height, radius, _widths) + + visible: hasBorder && width > 0 && height > 0 + anchors.fill: parent + z: 100000 + + Shape { + anchors.fill: parent + preferredRendererType: Shape.CurveRenderer + + ShapePath { + fillRule: ShapePath.WindingFill + strokeWidth: 0 + fillGradient: LinearGradient { + x1: root._endpoints.x1 + y1: root._endpoints.y1 + x2: root._endpoints.x2 + y2: root._endpoints.y2 + + GradientStop { position: Geometry.stopPosition(root._colors, 0); color: Geometry.stopColor(root._colors, 0) } + GradientStop { position: Geometry.stopPosition(root._colors, 1); color: Geometry.stopColor(root._colors, 1) } + GradientStop { position: Geometry.stopPosition(root._colors, 2); color: Geometry.stopColor(root._colors, 2) } + GradientStop { position: Geometry.stopPosition(root._colors, 3); color: Geometry.stopColor(root._colors, 3) } + GradientStop { position: Geometry.stopPosition(root._colors, 4); color: Geometry.stopColor(root._colors, 4) } + GradientStop { position: Geometry.stopPosition(root._colors, 5); color: Geometry.stopColor(root._colors, 5) } + GradientStop { position: Geometry.stopPosition(root._colors, 6); color: Geometry.stopColor(root._colors, 6) } + GradientStop { position: Geometry.stopPosition(root._colors, 7); color: Geometry.stopColor(root._colors, 7) } + GradientStop { position: Geometry.stopPosition(root._colors, 8); color: Geometry.stopColor(root._colors, 8) } + GradientStop { position: Geometry.stopPosition(root._colors, 9); color: Geometry.stopColor(root._colors, 9) } + } + + PathSvg { path: root._path } + } + } +} diff --git a/quickshell/compat/omarchy/Ui/BorderSurface.qml b/quickshell/compat/omarchy/Ui/BorderSurface.qml new file mode 100644 index 0000000..22c2e7e --- /dev/null +++ b/quickshell/compat/omarchy/Ui/BorderSurface.qml @@ -0,0 +1,39 @@ +import QtQuick +import qs.compat.omarchy.Commons +// Rectangle-compatible surface with Omarchy border specs. Uses native +// Rectangle.border for cheap flat/uniform borders and BorderOverlay for +// gradients or per-side widths. +Rectangle { + id: root + + property var borderSpec: Border.none() + property real padding: 0 + property real topPadding: padding + property real rightPadding: padding + property real bottomPadding: padding + property real leftPadding: padding + + readonly property real borderTop: Border.top(borderSpec) + readonly property real borderRight: Border.right(borderSpec) + readonly property real borderBottom: Border.bottom(borderSpec) + readonly property real borderLeft: Border.left(borderSpec) + readonly property real contentTopInset: borderTop + topPadding + readonly property real contentRightInset: borderRight + rightPadding + readonly property real contentBottomInset: borderBottom + bottomPadding + readonly property real contentLeftInset: borderLeft + leftPadding + readonly property bool usesOverlayBorder: Border.needsOverlay(borderSpec) + + border.color: Border.canUseNative(borderSpec) ? Border.color(borderSpec) : "transparent" + border.width: Border.canUseNative(borderSpec) ? Border.uniformWidth(borderSpec) : 0 + + Loader { + anchors.fill: parent + active: root.usesOverlayBorder + + sourceComponent: BorderOverlay { + anchors.fill: parent + radius: root.radius + borderSpec: root.borderSpec + } + } +} diff --git a/quickshell/compat/omarchy/Ui/Button.qml b/quickshell/compat/omarchy/Ui/Button.qml new file mode 100644 index 0000000..dd6443a --- /dev/null +++ b/quickshell/compat/omarchy/Ui/Button.qml @@ -0,0 +1,208 @@ +import QtQuick +import QtQuick.Controls +import qs.compat.omarchy.Commons +// The button. One component for every clickable thing in the kit. +// States compose independently and are applied in priority order: +// +// pressed (mouse down) pressed fill +// activeFocus (Tab focus) focus fill + focus border token +// hasCursor || hover hover-cursor fill (+ border if `bordered`) +// selected selected fill + optional selected border +// active selected fill +// idle transparent or normal border if `bordered` +// +// All fills/borders come from `qs.Commons.Style` tokens, so themes +// control the look via [controls] in shell.toml. +// +// Emits `hovered(bool)` so panels with their own keyboard cursor model +// can update state on mouse enter/leave. +BorderSurface { + id: root + + property string text: "" + property string iconText: "" + property string tooltipText: "" + + // State flags (see comment above for paint priority). + property bool selected: false + property bool active: false + property bool hasCursor: false + property bool focusable: false + property bool bordered: false + + // Colors. Defaults track the theme; per-instance overrides are honored. + property color foreground: Color.foreground + property color background: "transparent" + property color accent: Color.accent + + // Sizing. + property string fontFamily: Style.font.family + property real fontSize: Style.font.body + property real iconSize: Style.font.icon + property real iconRotation: 0 + property bool iconSpinning: false + property real horizontalPadding: Style.spacing.controlPaddingX + property real verticalPadding: Style.spacing.controlPaddingY + property bool leftAlign: false + + leftPadding: horizontalPadding + rightPadding: horizontalPadding + topPadding: verticalPadding + bottomPadding: verticalPadding + + // Tooltip palette. Auto-rendered if tooltipText is set. Defaults pull + // from [tooltip] in shell.toml; override per-instance only when a button + // intentionally wants a tooltip that diverges from the theme. + property color tooltipBackground: Color.tooltip.background + property color tooltipForeground: Color.tooltip.text + property color tooltipBorder: Color.tooltip.border + + signal clicked() + signal rightClicked() + signal hovered(bool isHovered) + + activeFocusOnTab: focusable + Keys.onReturnPressed: if (focusable) root.clicked() + Keys.onEnterPressed: if (focusable) root.clicked() + Keys.onSpacePressed: if (focusable) root.clicked() + + // Reserve the largest border any visual state can paint. Otherwise a + // borderless idle button grows by a pixel per side on hover/focus and + // relayouts neighboring controls. + implicitWidth: row.implicitWidth + horizontalPadding * 2 + _reservedBorderLeft + _reservedBorderRight + implicitHeight: row.implicitHeight + verticalPadding * 2 + _reservedBorderTop + _reservedBorderBottom + radius: Style.cornerRadius + + readonly property bool hot: mouseArea.containsMouse || hasCursor + readonly property bool _showFocusRing: focusable && activeFocus + readonly property color _selectedColor: Style.selectedStateColor(root.foreground, root.accent) + readonly property var _tooltipBorderSpec: Border.localOrSurfaceSpec("tooltip", "border", root.tooltipBorder, Color.tooltip.border, Math.max(1, Style.normalBorderWidth)) + readonly property var _focusBorderSpec: Border.controlSpec("focus", root.foreground, root.accent) + readonly property var _hoverBorderSpec: Border.controlSpec("hover-cursor", root.foreground, root.accent) + readonly property var _selectedBorderSpec: Border.controlSpec("selected", root.foreground, root.accent) + readonly property var _normalBorderSpec: Border.controlSpec("normal", root.foreground, root.accent) + readonly property real _reservedBorderTop: Math.max( + focusable ? Border.top(_focusBorderSpec) : 0, + Border.top(_hoverBorderSpec), + Border.top(_selectedBorderSpec), + bordered ? Border.top(_normalBorderSpec) : 0) + readonly property real _reservedBorderRight: Math.max( + focusable ? Border.right(_focusBorderSpec) : 0, + Border.right(_hoverBorderSpec), + Border.right(_selectedBorderSpec), + bordered ? Border.right(_normalBorderSpec) : 0) + readonly property real _reservedBorderBottom: Math.max( + focusable ? Border.bottom(_focusBorderSpec) : 0, + Border.bottom(_hoverBorderSpec), + Border.bottom(_selectedBorderSpec), + bordered ? Border.bottom(_normalBorderSpec) : 0) + readonly property real _reservedBorderLeft: Math.max( + focusable ? Border.left(_focusBorderSpec) : 0, + Border.left(_hoverBorderSpec), + Border.left(_selectedBorderSpec), + bordered ? Border.left(_normalBorderSpec) : 0) + readonly property real _reservedContentLeftInset: _reservedBorderLeft + leftPadding + readonly property var _borderSpec: _showFocusRing ? _focusBorderSpec + : hot ? _hoverBorderSpec + : selected ? (Border.controlHasWidth("selected") ? _selectedBorderSpec : (bordered ? _normalBorderSpec : Border.none())) + : bordered ? _normalBorderSpec + : Border.none() + + color: mouseArea.pressed ? Style.pressedFillFor(root.foreground, root.accent) + : _showFocusRing ? Style.focusFillFor(root.foreground, root.accent) + : hot ? Style.hoverFillFor(root.foreground, root.accent) + : selected ? Style.selectedFillFor(root.foreground, root.accent) + : active ? Style.selectedFillFor(root.foreground, root.accent) + : background + + // Border follows the same state precedence as fill. Buttons stay + // borderless at rest unless `bordered` is set, but hover-cursor/focus + // always use the shared cursor border so the keyboard target is visible + // and consistent with the rest of the kit. Selected borders are off by + // default for plain buttons; explicitly bordered buttons keep their + // normal border when selected unless selected-border-width opts in to a + // dedicated selected border. + borderSpec: _borderSpec + + Behavior on color { ColorAnimation { duration: Style.duration(120) } } + + ToolTip { + visible: root.tooltipText !== "" && mouseArea.containsMouse + text: root.tooltipText + delay: 400 + padding: 0 + background: BorderSurface { + color: root.tooltipBackground + borderSpec: root._tooltipBorderSpec + radius: 0 + } + contentItem: Text { + textFormat: Text.PlainText + text: root.tooltipText + color: root.tooltipForeground + font.family: root.fontFamily + font.pixelSize: Style.font.bodySmall + leftPadding: Border.left(root._tooltipBorderSpec) + Style.spacing.controlPaddingX + rightPadding: Border.right(root._tooltipBorderSpec) + Style.spacing.controlPaddingX + topPadding: Border.top(root._tooltipBorderSpec) + Style.spacing.controlPaddingY + bottomPadding: Border.bottom(root._tooltipBorderSpec) + Style.spacing.controlPaddingY + } + } + + Row { + id: row + anchors.verticalCenter: parent.verticalCenter + anchors.left: root.leftAlign ? parent.left : undefined + anchors.leftMargin: root.leftAlign ? root._reservedContentLeftInset : 0 + anchors.horizontalCenter: root.leftAlign ? undefined : parent.horizontalCenter + spacing: Style.spacing.controlGap + + Text { + textFormat: Text.PlainText + visible: root.iconText !== "" + text: root.iconText + color: root.selected ? root._selectedColor : root.foreground + font.family: root.fontFamily + font.pixelSize: root.iconSize + rotation: root.iconSpinning ? 0 : root.iconRotation + transformOrigin: Item.Center + anchors.verticalCenter: parent.verticalCenter + + RotationAnimation on rotation { + from: 0 + to: 360 + duration: 900 + loops: Animation.Infinite + running: root.iconSpinning && !Style.reduceMotion + } + } + + Text { + textFormat: Text.PlainText + visible: root.text !== "" + text: root.text + color: root.selected ? root._selectedColor : root.foreground + font.family: root.fontFamily + font.pixelSize: root.fontSize + font.bold: root.selected + anchors.verticalCenter: parent.verticalCenter + } + } + + MouseArea { + id: mouseArea + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + acceptedButtons: Qt.LeftButton | Qt.RightButton + onClicked: function(mouse) { + if (root.focusable) root.forceActiveFocus() + if (mouse.button === Qt.RightButton) root.rightClicked() + else root.clicked() + } + } + + HoverHandler { + onHoveredChanged: root.hovered(hovered) + } +} diff --git a/quickshell/compat/omarchy/Ui/ButtonGroup.qml b/quickshell/compat/omarchy/Ui/ButtonGroup.qml new file mode 100644 index 0000000..3276234 --- /dev/null +++ b/quickshell/compat/omarchy/Ui/ButtonGroup.qml @@ -0,0 +1,131 @@ +import QtQuick +import qs.compat.omarchy.Commons +// Mutually-exclusive row of Buttons — the form-style "pick one of N" +// pattern (bar position top/right/bottom/left, theme preset chips, etc.). +// Emits `changed(value)` when the user activates a different option. +// +// `options` is either a plain string[] (label == value) or an array of +// { value, label, icon?, tooltip? } objects. Mixing is fine. +// +// Keyboard navigation. The group itself is a single Tab stop, not one +// stop per chip — so in a form that walks `activeFocusOnTab` items with +// Tab / j / k, the cursor enters the group as a unit. Once focused, +// h / l / Left / Right walks between chips and Enter / Space activates +// the current one. The selected chip is the default landing point so +// users see their existing choice on arrival. +// +// Panel-cursor consumers (the bar widget panels) drive `cursorIndex` +// directly and listen on `hovered` to sync the mouse — Tab focus and +// `cursorIndex` are independent; either one paints the chip's hot +// state, and the bar widget panels never give Tab focus to a +// ButtonGroup so they only see the cursorIndex path. +Row { + id: root + + property var options: [] + property string value: "" + property color foreground: Color.foreground + property color background: Color.background + property color accent: Color.accent + property string fontFamily: Style.font.family + property real fontSize: Style.font.body + property bool focusable: true + + // -1 disables the external cursor highlight (the panel-cursor case). + // Driven by a containing panel; the group's own Tab-focus h/l + // tracking is internal and lives in _focusedIndex. + property int cursorIndex: -1 + + // Internal: which chip h / l / Left / Right is currently sitting on + // when the group itself has Tab focus. Reset to the selected option + // each time focus arrives so the user sees their existing choice. + property int _focusedIndex: -1 + + signal changed(string value) + signal hovered(int index, bool isHovered) + + spacing: Style.spacing.md + + activeFocusOnTab: focusable + + function optionValue(o) { + return (o && typeof o === "object") ? String(o.value) : String(o) + } + function optionLabel(o) { + return (o && typeof o === "object" && o.label !== undefined) ? String(o.label) : String(o) + } + function optionIcon(o) { + return (o && typeof o === "object" && o.icon) ? String(o.icon) : "" + } + function optionTooltip(o) { + return (o && typeof o === "object" && o.tooltip) ? String(o.tooltip) : "" + } + + function selectedOptionIndex() { + for (var i = 0; i < options.length; i++) + if (optionValue(options[i]) === value) return i + return -1 + } + + function activateFocused() { + if (_focusedIndex < 0 || _focusedIndex >= options.length) return + var v = optionValue(options[_focusedIndex]) + root.changed(v) + } + + onActiveFocusChanged: { + if (activeFocus) { + var idx = selectedOptionIndex() + _focusedIndex = idx < 0 ? 0 : idx + } else { + _focusedIndex = -1 + } + } + + Keys.priority: Keys.BeforeItem + Keys.onPressed: function(event) { + if (event.key === Qt.Key_Left || event.key === Qt.Key_H + || event.text === "h") { + _focusedIndex = Math.max(0, (_focusedIndex < 0 ? 0 : _focusedIndex) - 1) + event.accepted = true + } else if (event.key === Qt.Key_Right || event.key === Qt.Key_L + || event.text === "l") { + var max = options.length - 1 + var next = (_focusedIndex < 0 ? 0 : _focusedIndex) + 1 + _focusedIndex = Math.min(max, next) + event.accepted = true + } else if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter + || event.key === Qt.Key_Space) { + activateFocused() + event.accepted = true + } + } + + Repeater { + model: root.options + + delegate: Button { + required property var modelData + required property int index + text: root.optionLabel(modelData) + iconText: root.optionIcon(modelData) + tooltipText: root.optionTooltip(modelData) + selected: root.optionValue(modelData) === root.value + // Chip lights up when either the external panel cursor lands here + // or the group has Tab focus and h/l has walked to this index. + hasCursor: root.cursorIndex === index + || (root.activeFocus && root._focusedIndex === index) + // Every chip carries the standard bordered-button chrome so the + // group reads as a row of distinct options. selected / hover-cursor / + // focus are all painted by Button from Style's shared state tokens. + bordered: true + foreground: root.foreground + background: root.background + accent: root.accent + fontFamily: root.fontFamily + fontSize: root.fontSize + onClicked: root.changed(root.optionValue(modelData)) + onHovered: function(h) { root.hovered(index, h) } + } + } +} diff --git a/quickshell/compat/omarchy/Ui/ConfirmDialog.qml b/quickshell/compat/omarchy/Ui/ConfirmDialog.qml new file mode 100644 index 0000000..a7fb43c --- /dev/null +++ b/quickshell/compat/omarchy/Ui/ConfirmDialog.qml @@ -0,0 +1,132 @@ +import QtQuick +import qs.compat.omarchy.Commons +Item { + id: root + + property bool opened: false + property string message: "" + property string cancelText: "Cancel" + property string confirmText: "Confirm" + property int selectedIndex: 1 + property color background: Color.background + property color foreground: Color.foreground + property color scrim: Util.alpha(Color.background, 0.7) + property color selectedBackground: Util.alpha(Color.foreground, 0.08) + property color selectedText: Color.accent + property string fontFamily: Style.font.family + property int cornerRadius: Style.cornerRadius + + signal canceled() + signal confirmed() + + function handleKey(event) { + if (!root.opened) return false + + if (event.key === Qt.Key_Escape) { + root.canceled() + return true + } else if (event.key === Qt.Key_Left || event.key === Qt.Key_Right || event.key === Qt.Key_Tab || event.key === Qt.Key_Backtab) { + root.selectedIndex = root.selectedIndex === 0 ? 1 : 0 + return true + } else if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter) { + if (root.selectedIndex === 0) root.canceled() + else root.confirmed() + return true + } + + return false + } + + visible: opened + + Rectangle { + anchors.fill: parent + color: root.scrim + + MouseArea { anchors.fill: parent; onClicked: root.canceled() } + + BorderSurface { + id: card + width: Math.min(parent.width - Style.space(32), Style.space(370)) + // Grows with the wrapped message so narrow hosts (like the menu card) + // don't squeeze the text into the buttons. + height: card.contentTopInset + card.contentBottomInset + messageText.implicitHeight + Style.space(20) + Style.space(34) + anchors.centerIn: parent + color: root.background + borderSpec: Border.flat(root.selectedText, Style.normalBorderWidth) + padding: Style.space(18) + radius: root.cornerRadius + + MouseArea { anchors.fill: parent; onClicked: {} } + + Item { + anchors.fill: parent + anchors.topMargin: card.contentTopInset + anchors.rightMargin: card.contentRightInset + anchors.bottomMargin: card.contentBottomInset + anchors.leftMargin: card.contentLeftInset + + Text { + id: messageText + textFormat: Text.PlainText + anchors.left: parent.left + anchors.right: parent.right + anchors.top: parent.top + text: root.message + color: root.foreground + font.family: root.fontFamily + font.pixelSize: Style.font.title + wrapMode: Text.WordWrap + } + + Row { + anchors.right: parent.right + anchors.bottom: parent.bottom + spacing: Style.space(10) + + Repeater { + model: [root.cancelText, root.confirmText] + + BorderSurface { + required property int index + required property string modelData + + readonly property bool selected: root.selectedIndex === index + readonly property bool destructive: index === 1 + + width: Style.space(88) + height: Style.space(34) + color: selected + ? (destructive ? Util.alpha(Color.urgent, 0.22) : root.selectedBackground) + : "transparent" + borderSpec: Border.flat(destructive + ? (selected ? Color.urgent : Util.alpha(Color.urgent, 0.56)) + : (selected ? root.selectedText : Util.alpha(root.foreground, 0.38)), Style.normalBorderWidth) + radius: 0 + + Text { + textFormat: Text.PlainText + anchors.centerIn: parent + text: modelData + color: destructive ? (selected ? Color.urgent : root.foreground) : (selected ? root.selectedText : root.foreground) + font.family: root.fontFamily + font.pixelSize: Style.font.caption + } + + MouseArea { + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onEntered: root.selectedIndex = index + onClicked: { + if (index === 0) root.canceled() + else root.confirmed() + } + } + } + } + } + } + } + } +} diff --git a/quickshell/compat/omarchy/Ui/CursorSurface.qml b/quickshell/compat/omarchy/Ui/CursorSurface.qml new file mode 100644 index 0000000..bcaa5f2 --- /dev/null +++ b/quickshell/compat/omarchy/Ui/CursorSurface.qml @@ -0,0 +1,40 @@ +import QtQuick +import qs.compat.omarchy.Commons +// Shared visual chrome for keyboard-and-mouse-navigable items inside a panel. +// Contract: items must NOT read `containsMouse` for color/border. Mouse +// hover updates the panel's cursor state at the root; visuals derive from +// `hasCursor` / `current`. That's what guarantees a single highlight on +// screen at any time across both keyboard and mouse interaction. +// +// Cursor paint is always the shared hover-cursor fill plus optional +// hover-cursor border. `outline` remains as a compatibility flag for +// callers that used to request border-only rows, but slider rows still +// receive the same hover-cursor background as every other row. +BorderSurface { + id: root + + property bool hasCursor: false + property bool current: false + property bool outline: false + property bool bordered: false + + property color foreground: Color.foreground + property color accent: Color.accent + property color fill: Style.hoverFillFor(foreground, accent) + property color currentFill: Style.selectedFillFor(foreground, accent) + + radius: Style.cornerRadius + + color: hasCursor ? fill : (current ? currentFill : "transparent") + borderSpec: root.hasCursor + ? Border.controlSpec("hover-cursor", root.foreground, root.accent) + : (root.current + ? Border.controlSpec("selected", root.foreground, root.accent) + : (root.bordered + ? Border.controlSpec("normal", root.foreground, root.accent) + : Border.none())) + + Behavior on color { + ColorAnimation { duration: Style.duration(60) } + } +} diff --git a/quickshell/compat/omarchy/Ui/Dropdown.qml b/quickshell/compat/omarchy/Ui/Dropdown.qml new file mode 100644 index 0000000..64d0173 --- /dev/null +++ b/quickshell/compat/omarchy/Ui/Dropdown.qml @@ -0,0 +1,243 @@ +import QtQuick +import QtQuick.Controls +import qs.compat.omarchy.Commons +// Themed single-select dropdown. Trigger row paints with the kit's focus +// chrome; the popup anchors below and uses Color.popups.background + +// Color.popups.border so it reads as a panel surface rather than the +// platform-native ComboBox look. +// +// `options` accepts either a plain string[] or an array of +// { value, label } objects (label is what we render; value is what we +// emit). Mixing is fine — each row is interpreted independently. +// +// Keyboard: Tab to focus the trigger, Enter/Space opens, Esc closes, +// j/k or Up/Down walks options inside the open popup, Enter selects. +// A sibling SearchableDropdown reuses the same visuals but adds an +// embedded filter input — keep the two separate so each stays simple. +Item { + id: root + + property string label: "" + property string value: "" + property var options: [] + + property color foreground: Color.popups.text + property color background: Color.popups.background + property color popupBorder: Color.popups.border + property color accent: Color.accent + readonly property var popupBorderSpec: Border.localOrSurfaceSpec("popups", "border", popupBorder, Color.popups.border, Style.normalBorderWidth) + property string fontFamily: Style.font.family + property int rowHeight: Style.spacing.controlHeight + property int popupRowHeight: Style.spacing.popupRowHeight + property bool showLabel: true + + // Panel-cursor flag. When true, the trigger renders the shared + // hover-cursor state. Active Qt focus defaults to the same visuals. + // Emits `hovered(bool)` on pointer enter/leave so the panel can keep + // its cursor state in sync with the mouse. + property bool hasCursor: false + + // popupOpen + open()/close()/toggle() let a parent panel know when the + // dropdown owns keys (its embedded ListView is active) and suspend its + // own keyCatcher so j/k inside the popup don't double-drive the panel + // cursor. + readonly property bool popupOpen: popup.opened + function open() { popup.open() } + function close() { popup.close() } + function toggle() { popup.opened ? popup.close() : popup.open() } + + signal changed(string value) + signal hovered(bool isHovered) + + function optionValue(o) { + return (o && typeof o === "object") ? String(o.value) : String(o) + } + function optionLabel(o) { + return (o && typeof o === "object") ? String(o.label) : String(o) + } + function currentLabel() { + for (var i = 0; i < options.length; i++) { + if (optionValue(options[i]) === value) return optionLabel(options[i]) + } + return value + } + + implicitWidth: Style.spacing.dropdownWidth + implicitHeight: showLabel && label !== "" ? rowHeight + Style.spacing.huge : rowHeight + + Column { + anchors.fill: parent + spacing: Style.spacing.labelGap + + Text { + textFormat: Text.PlainText + visible: root.showLabel && root.label !== "" + text: root.label + color: Qt.darker(root.foreground, 1.4) + font.family: root.fontFamily + font.pixelSize: Style.font.caption + font.bold: true + } + + BorderSurface { + id: trigger + width: parent.width + height: root.rowHeight + radius: Style.cornerRadius + + readonly property bool _focused: trigger.activeFocus + readonly property bool _hot: triggerHover.hovered || root.hasCursor + readonly property var _borderSpec: Border.controlSpec(trigger._focused ? "focus" : (trigger._hot ? "hover-cursor" : "normal"), root.foreground, root.accent) + + color: Style.controlFill(trigger._focused, trigger._hot, root.foreground, root.accent) + borderSpec: _borderSpec + + activeFocusOnTab: true + + HoverHandler { + id: triggerHover + onHoveredChanged: root.hovered(hovered) + } + + Keys.onPressed: function(event) { + if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter + || event.key === Qt.Key_Space || event.key === Qt.Key_Down) { + popup.opened ? popup.close() : popup.open() + event.accepted = true + } else if (event.key === Qt.Key_Escape && popup.opened) { + popup.close(); event.accepted = true + } + } + + Text { + textFormat: Text.PlainText + anchors.left: parent.left + anchors.right: chevron.left + anchors.verticalCenter: parent.verticalCenter + anchors.leftMargin: trigger.borderLeft + Style.spacing.controlPaddingX + anchors.rightMargin: trigger.borderRight + Style.spacing.md + text: root.currentLabel() + color: root.foreground + font.family: root.fontFamily + font.pixelSize: Style.font.body + elide: Text.ElideRight + } + + Text { + id: chevron + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + anchors.rightMargin: trigger.borderRight + Style.spacing.controlGap + text: "󰅀" + color: Qt.darker(root.foreground, 1.2) + font.family: root.fontFamily + font.pixelSize: Style.font.body + } + + MouseArea { + anchors.fill: parent + cursorShape: Qt.PointingHandCursor + onClicked: { + trigger.forceActiveFocus() + popup.opened ? popup.close() : popup.open() + } + } + + Popup { + id: popup + x: 0 + y: trigger.height + Style.spacing.xxs + width: trigger.width + implicitHeight: Math.min(root.options.length * root.popupRowHeight + Math.max(0, root.options.length - 1) * Style.spacing.labelGap + Style.spacing.xxs, + root.popupRowHeight * 8 + 7 * Style.spacing.labelGap + Style.spacing.xxs) + padding: Style.spacing.hairline + leftPadding: Border.left(root.popupBorderSpec) + Style.spacing.hairline + rightPadding: Border.right(root.popupBorderSpec) + Style.spacing.hairline + topPadding: Border.top(root.popupBorderSpec) + Style.spacing.hairline + bottomPadding: Border.bottom(root.popupBorderSpec) + Style.spacing.hairline + focus: true + + background: BorderSurface { + color: root.background + borderSpec: root.popupBorderSpec + radius: Style.cornerRadius + } + + onOpened: { + optionList.currentIndex = Math.max(0, optionList.indexOfValue(root.value)) + optionList.forceActiveFocus() + } + + contentItem: ListView { + id: optionList + spacing: Style.spacing.labelGap + + Keys.priority: Keys.BeforeItem + Keys.onPressed: function(event) { + if (event.key === Qt.Key_Escape) { popup.close(); event.accepted = true } + else if (event.key === Qt.Key_Down || event.text === "j") { + optionList.currentIndex = Math.min(root.options.length - 1, optionList.currentIndex + 1) + event.accepted = true + } else if (event.key === Qt.Key_Up || event.text === "k") { + optionList.currentIndex = Math.max(0, optionList.currentIndex - 1) + event.accepted = true + } else if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter) { + optionList.selectCurrent(); event.accepted = true + } + } + implicitHeight: contentHeight + clip: true + boundsBehavior: Flickable.StopAtBounds + model: root.options + currentIndex: -1 + + function indexOfValue(v) { + for (var i = 0; i < root.options.length; i++) + if (root.optionValue(root.options[i]) === v) return i + return -1 + } + + function selectCurrent() { + if (currentIndex < 0 || currentIndex >= root.options.length) return + var v = root.optionValue(root.options[currentIndex]) + root.value = v + root.changed(v) + popup.close() + } + + delegate: Rectangle { + required property var modelData + required property int index + width: optionList.width + height: root.popupRowHeight + color: index === optionList.currentIndex + ? Style.hoverFillFor(root.foreground, root.accent) + : "transparent" + + Text { + textFormat: Text.PlainText + anchors.left: parent.left + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + anchors.leftMargin: Style.spacing.controlPaddingX + anchors.rightMargin: Style.spacing.controlPaddingX + text: root.optionLabel(modelData) + color: index === optionList.currentIndex ? Style.hoverStateColor(root.foreground, root.accent) : root.foreground + font.family: root.fontFamily + font.pixelSize: Style.font.body + elide: Text.ElideRight + } + + MouseArea { + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onPositionChanged: optionList.currentIndex = parent.index + onClicked: optionList.selectCurrent() + } + } + } + } + } + } +} diff --git a/quickshell/compat/omarchy/Ui/GlassPopupBase.qml b/quickshell/compat/omarchy/Ui/GlassPopupBase.qml new file mode 100644 index 0000000..09686db --- /dev/null +++ b/quickshell/compat/omarchy/Ui/GlassPopupBase.qml @@ -0,0 +1,172 @@ +import QtQuick +import Quickshell +import Quickshell.Hyprland +import Quickshell.Wayland +import qs.compat.omarchy.Commons +import "../../../components" as C +import "../../../core" as Core +import "../../../theme" as G + +// glassMxrph base for Omarchy's PopupCard and KeyboardPanel: the popup is a +// glassMxrph bar drawer that grows out of the bar under its anchor, with the +// same glass, ears and animation as the shell's own panels. The public API +// (sizes, fitted*/capped* helpers, open/close, owner, focusTarget, popout +// coordination) matches Omarchy so plugins work unchanged. +// +// mode: "keyboard" — exclusive keyboard focus, outside clicks close (like the +// Control Center); "click" — focus grab, outside clicks +// close; "hover" — passive, the owner opens/closes it. +PanelWindow { + id: root + + required property Item anchorItem + required property QtObject bar + property var owner: null + property string mode: "keyboard" + property int margin: 8 + property int padding: Style.spacing.popupPadding + property int contentWidth: Style.space(280) + property int contentHeight: Style.space(200) + property var borderSpec: Border.none() + property color borderColor: G.Theme.border + property bool centerOnBar: false + property bool open: false + property int gap: 0 + property bool popoutSwitching: false + property bool popoutSwitchClosing: false + property bool focusPrimed: true + property Item focusTarget: null + + default property alias contentItem: contentHolder.children + + readonly property var coordinatorKey: owner || root + readonly property var anchorWindow: anchorItem ? anchorItem.QsWindow.window : null + readonly property string barPos: "top" + readonly property bool containsMouse: drawer.hovered + + function close() { + if (owner && "close" in owner) owner.close() + else root.open = false + } + function beginFocusPrime() { + } + + screen: anchorWindow ? anchorWindow.screen : null + readonly property real screenW: screen ? screen.width : 0 + readonly property real screenH: screen ? screen.height : 0 + readonly property real sideSpace: 2 * (Core.BarDrawers.margin + Core.BarDrawers.radius + Core.BarDrawers.ear) + readonly property real availableCardWidth: screenW > 0 ? Math.max(120, screenW - sideSpace) : 0 + readonly property real availableCardHeight: screenH > 0 ? Math.max(120, screenH - Core.BarDrawers.bottom - 20) : 0 + readonly property real verticalContentInset: padding * 2 + + function fittedContentWidth(width, cap) { + var desired = Math.max(1, Number(width) || 1) + var maxWidth = root.availableCardWidth > 0 ? root.availableCardWidth : desired + if (cap !== undefined && Number(cap) > 0) maxWidth = Math.min(maxWidth, Number(cap)) + return Math.round(Math.min(desired, maxWidth)) + } + function fittedContentHeight(implicitHeight, cap) { + var desired = Math.max(root.verticalContentInset, (Number(implicitHeight) || 0) + root.verticalContentInset) + var maxHeight = root.availableCardHeight > 0 ? root.availableCardHeight : desired + if (cap !== undefined && Number(cap) > 0) maxHeight = Math.min(maxHeight, Number(cap)) + return Math.round(Math.min(desired, maxHeight)) + } + function cappedContentHeight(height) { + var desired = Math.max(root.padding * 2, Number(height) || root.padding * 2) + var maxHeight = root.availableCardHeight > 0 ? root.availableCardHeight : desired + return Math.round(Math.min(desired, maxHeight)) + } + + readonly property real barW: anchorWindow ? anchorWindow.width : screenW + readonly property real barH: Core.BarDrawers.bottom + // Re-read on open: mapToItem is not reactive to layout changes. + readonly property point anchorScreenPos: { + root.open + if (!anchorItem || !anchorWindow) return Qt.point(0, 0) + return anchorItem.mapToItem(anchorWindow.contentItem, 0, 0) + } + readonly property real anchorW: anchorItem ? anchorItem.width : 0 + readonly property real anchorH: anchorItem ? anchorItem.height : 0 + readonly property real outerWidth: drawer.width + readonly property real drawerX: centerOnBar + ? Math.round((screenW - outerWidth) / 2) + : Core.BarDrawers.clampX(anchorScreenPos.x + anchorW / 2, outerWidth, screenW) + readonly property point cardOrigin: Qt.point(drawerX + drawer.ear, Core.BarDrawers.bottom) + + // Hang from the bar: the layer starts at the screen top so the join with + // the bar is inside its box (no HyprGlass edge there). + anchors { + top: true + left: true + } + // qmllint disable unqualified unresolved-type + margins.left: root.drawerX + // qmllint enable unqualified unresolved-type + implicitWidth: Math.max(1, Math.round(drawer.width)) + implicitHeight: Math.max(1, Math.round(Core.BarDrawers.bottom + drawer.contentHeight)) + visible: open || drawer.shown || popoutSwitching + color: "transparent" + exclusionMode: ExclusionMode.Ignore + WlrLayershell.namespace: "glassMxrph-plugin-popup" + WlrLayershell.layer: WlrLayer.Overlay + WlrLayershell.keyboardFocus: !open ? WlrKeyboardFocus.None : mode === "keyboard" ? WlrKeyboardFocus.Exclusive : mode === "click" ? WlrKeyboardFocus.OnDemand : WlrKeyboardFocus.None + // Passive popups only take input on the drawer itself. + Region { + id: bodyMask + item: drawer.body + } + mask: mode === "keyboard" ? null : bodyMask + + onOpenChanged: { + if (open && focusTarget) Qt.callLater(function() { + if (root.open && root.focusTarget) root.focusTarget.forceActiveFocus() + }) + if (!bar) return + if (open) { + popoutSwitchClosing = false + if (bar.requestPopout) bar.requestPopout(coordinatorKey) + } else { + popoutSwitchClosing = !!(owner && owner.popoutSwitchClosing) + if (bar.activePopout === coordinatorKey && bar.releasePopout) bar.releasePopout(coordinatorKey) + } + } + + // Keyboard mode: Hyprland routes every click to the exclusive layer, so + // outside clicks arrive here with out-of-bounds coordinates (see ControlCenter). + MouseArea { + x: -20000 + y: -20000 + width: 40000 + height: 40000 + enabled: root.open && root.mode === "keyboard" + acceptedButtons: Qt.AllButtons + onPressed: root.close() + } + HyprlandFocusGrab { + active: root.open && root.mode === "click" + windows: root.anchorWindow ? [root, root.anchorWindow] : [root] + onCleared: root.close() + } + + C.BarDrawer { + id: drawer + y: Core.BarDrawers.bottom + open: root.open + contentWidth: root.contentWidth + contentHeight: root.contentHeight + drawerId: "plugin-popup-" + (root.owner && root.owner.moduleName ? root.owner.moduleName : "") + screenName: root.screen ? root.screen.name : "" + screenX: root.drawerX + + // Swallow clicks on the card so they never reach the outside catcher. + MouseArea { + anchors.fill: parent + acceptedButtons: Qt.AllButtons + } + Item { + id: contentHolder + anchors.fill: parent + anchors.margins: root.padding + } + } +} diff --git a/quickshell/compat/omarchy/Ui/KeyboardPanel.qml b/quickshell/compat/omarchy/Ui/KeyboardPanel.qml new file mode 100644 index 0000000..333c90f --- /dev/null +++ b/quickshell/compat/omarchy/Ui/KeyboardPanel.qml @@ -0,0 +1,6 @@ +import QtQuick +// glassMxrph: Omarchy's keyboard-driven bar panel, drawn as a glassMxrph bar +// drawer. See GlassPopupBase for the shared implementation and API. +GlassPopupBase { + mode: "keyboard" +} diff --git a/quickshell/compat/omarchy/Ui/MultiSelect.qml b/quickshell/compat/omarchy/Ui/MultiSelect.qml new file mode 100644 index 0000000..f3f3556 --- /dev/null +++ b/quickshell/compat/omarchy/Ui/MultiSelect.qml @@ -0,0 +1,622 @@ +import QtQuick +import QtQuick.Controls as QQC +import QtQuick.Window +import Quickshell.Io +import qs.compat.omarchy.Commons +// Searchable multi-select dropdown. Trigger shape matches Dropdown / +// SearchableDropdown; the popup shows a search field, an optional refresh +// button, and a checkbox list. Click rows to toggle. Use when callers +// need to pick zero or more items from a (possibly long, possibly +// dynamic) list. +// +// Options are either: +// - static `options`: string[] or [{ value, label, description? }] +// - dynamic `optionsCommand`: argv array. The command's stdout is +// parsed as JSON when it trims to start with `[`, otherwise as +// one option per non-empty newline. Re-runs whenever the popup opens +// and via the refresh button. +// +// `values` is the persisted selection — always an array of strings. +// Emits `changed(values)` whenever the selection mutates. +Item { + id: root + + property string label: "" + property var values: [] + property var options: [] + property var optionsCommand: [] + property string optionsCommandCwd: "" + property string placeholderText: "Search..." + property string emptyText: "No options" + property string noSelectionText: "None selected" + property string triggerLabel: "" + property bool showLabel: true + + property color foreground: Color.popups.text + property color background: Color.popups.background + property color popupBorder: Color.popups.border + property color accent: Color.accent + readonly property var popupBorderSpec: Border.localOrSurfaceSpec("popups", "border", popupBorder, Color.popups.border, Style.normalBorderWidth) + property string fontFamily: Style.font.family + property int rowHeight: Style.spacing.controlHeight + property int popupRowHeight: Style.spacing.popupRowHeight + property int popupMinHeight: Style.spacing.searchablePopupMinHeight + + property bool hasCursor: false + + readonly property bool popupOpen: popup.opened + function open() { popup.open() } + function close() { popup.close() } + function toggle() { popup.opened ? popup.close() : popup.open() } + + signal changed(var values) + signal hovered(bool isHovered) + + // Loaded options after merging static + dynamic. Always normalized + // into the [{ value, label, description }] shape for delegate use. + property var resolvedOptions: [] + property bool loadingOptions: false + property string optionsError: "" + + function normalizeOption(o) { + if (o && typeof o === "object") { + return { + value: String(o.value), + label: String(o.label !== undefined ? o.label : o.value), + description: o.description ? String(o.description) : "" + } + } + var s = String(o) + return { value: s, label: s, description: "" } + } + + // QML schema arrays sometimes arrive as JSValue lists that fail + // `Array.isArray`. arrayFrom accepts anything array-like (`.length` + // numeric) and returns a real JS array so the rest of the component can + // rely on standard array operations. + function arrayFrom(v) { + if (!v || typeof v.length !== "number" || typeof v === "string") return [] + var out = [] + for (var i = 0; i < v.length; i++) out.push(v[i]) + return out + } + + function normalizeAll(arr) { + var out = [] + var src = arrayFrom(arr) + var seen = ({}) + for (var i = 0; i < src.length; i++) { + var n = normalizeOption(src[i]) + if (!n.value) continue + if (seen[n.value]) continue + seen[n.value] = true + out.push(n) + } + return out + } + + function valueSet() { + var set = ({}) + var arr = arrayFrom(values) + for (var i = 0; i < arr.length; i++) set[String(arr[i])] = true + return set + } + + function isSelected(value) { + var set = valueSet() + return !!set[String(value)] + } + + function toggleValue(value) { + var v = String(value) + var arr = arrayFrom(values) + var idx = arr.indexOf(v) + if (idx === -1) arr.push(v) + else arr.splice(idx, 1) + root.values = arr + root.changed(arr) + } + + function selectionLabel() { + var arr = arrayFrom(values) + if (arr.length === 0) return "" + var labels = [] + var byValue = ({}) + for (var i = 0; i < resolvedOptions.length; i++) + byValue[resolvedOptions[i].value] = resolvedOptions[i].label + for (var j = 0; j < arr.length; j++) + labels.push(byValue[String(arr[j])] || String(arr[j])) + if (labels.length <= 3) return labels.join(", ") + return arr.length + " selected" + } + + property var filtered: resolvedOptions + function recomputeFiltered() { + var q = searchField.text.toLowerCase() + if (!q) { filtered = resolvedOptions; return } + var out = [] + for (var i = 0; i < resolvedOptions.length; i++) { + var o = resolvedOptions[i] + if (o.label.toLowerCase().indexOf(q) !== -1 + || o.description.toLowerCase().indexOf(q) !== -1 + || o.value.toLowerCase().indexOf(q) !== -1) out.push(o) + } + filtered = out + } + + function rebuildFromStatic() { + resolvedOptions = normalizeAll(options) + recomputeFiltered() + } + + // Parse stdout from a dynamic optionsCommand into `{ options, error }`. + // Output starting with `[` is parsed strictly as JSON — a malformed array + // surfaces as an error rather than silently falling back to newline + // parsing, which would render the broken text as a literal option label. + // Output not starting with `[` is treated as one value per non-empty line. + function parseCommandOutput(text) { + var raw = String(text || "").trim() + if (raw === "") return { options: [], error: "" } + if (raw.charAt(0) === "[") { + try { + var parsed = JSON.parse(raw) + return { options: parsed, error: "" } + } catch (e) { + return { options: [], error: "Options command emitted invalid JSON" } + } + } + var out = [] + var lines = raw.split(/\r?\n/) + for (var i = 0; i < lines.length; i++) { + var line = lines[i].trim() + if (line !== "") out.push(line) + } + return { options: out, error: "" } + } + + // Monotonic request id so stale stdout/exit signals from a previous + // refresh can't clobber the resolvedOptions of a newer refresh, and + // a runaway command can be detected after a timeout. + property int refreshSeq: 0 + readonly property int refreshTimeoutMs: 6000 + + function refresh() { + var cmd = arrayFrom(optionsCommand) + if (cmd.length === 0) { + rebuildFromStatic() + return + } + refreshSeq++ + loadingOptions = true + optionsError = "" + optionsProcess.command = cmd + optionsProcess.workingDirectory = optionsCommandCwd + optionsProcess.running = false + optionsProcess.running = true + refreshTimeoutTimer.restart() + } + + Timer { + id: refreshTimeoutTimer + interval: root.refreshTimeoutMs + repeat: false + onTriggered: { + if (!root.loadingOptions) return + optionsProcess.running = false + root.loadingOptions = false + root.optionsError = "Options command timed out" + } + } + + onOptionsChanged: if (arrayFrom(optionsCommand).length === 0) rebuildFromStatic() + onOptionsCommandChanged: refresh() + Component.onCompleted: refresh() + + Process { + id: optionsProcess + running: false + command: [] + + property int seq: 0 + + stdout: StdioCollector { + waitForEnd: true + onStreamFinished: { + if (optionsProcess.seq !== root.refreshSeq) return + var result = root.parseCommandOutput(text) + if (result.error) { + root.optionsError = result.error + root.resolvedOptions = root.normalizeAll(root.options) + } else { + var combined = root.arrayFrom(root.options) + for (var j = 0; j < result.options.length; j++) combined.push(result.options[j]) + root.resolvedOptions = root.normalizeAll(combined) + } + root.recomputeFiltered() + root.loadingOptions = false + refreshTimeoutTimer.stop() + } + } + + onRunningChanged: if (running) seq = root.refreshSeq + + onExited: function(exitCode, exitStatus) { + if (seq !== root.refreshSeq) return + refreshTimeoutTimer.stop() + if (exitCode !== 0) { + root.loadingOptions = false + root.optionsError = "Options command exited " + exitCode + } + } + } + + implicitWidth: Style.spacing.searchableDropdownWidth + implicitHeight: showLabel && label !== "" ? rowHeight + Style.spacing.huge : rowHeight + + Column { + anchors.fill: parent + spacing: Style.spacing.labelGap + + Text { + textFormat: Text.PlainText + visible: root.showLabel && root.label !== "" + text: root.label + color: Qt.darker(root.foreground, 1.4) + font.family: root.fontFamily + font.pixelSize: Style.font.caption + font.bold: true + } + + BorderSurface { + id: trigger + width: parent.width + height: root.rowHeight + radius: Style.cornerRadius + + readonly property bool _focused: trigger.activeFocus + readonly property bool _hot: triggerHover.hovered || root.hasCursor + readonly property var _borderSpec: Border.controlSpec(trigger._focused ? "focus" : (trigger._hot ? "hover-cursor" : "normal"), root.foreground, root.accent) + + color: Style.controlFill(trigger._focused, trigger._hot, root.foreground, root.accent) + borderSpec: _borderSpec + + activeFocusOnTab: true + + HoverHandler { + id: triggerHover + onHoveredChanged: root.hovered(hovered) + } + + Keys.onPressed: function(event) { + if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter + || event.key === Qt.Key_Space || event.key === Qt.Key_Down) { + popup.opened ? popup.close() : popup.open() + event.accepted = true + } else if (event.key === Qt.Key_Escape && popup.opened) { + popup.close(); event.accepted = true + } + } + + Text { + textFormat: Text.PlainText + anchors.left: parent.left + anchors.right: chevron.left + anchors.verticalCenter: parent.verticalCenter + anchors.leftMargin: trigger.borderLeft + Style.spacing.controlPaddingX + anchors.rightMargin: trigger.borderRight + Style.spacing.md + text: root.selectionLabel() || root.triggerLabel || root.noSelectionText + color: root.selectionLabel() ? root.foreground : Qt.darker(root.foreground, 1.5) + font.family: root.fontFamily + font.pixelSize: Style.font.body + elide: Text.ElideRight + } + + Text { + id: chevron + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + anchors.rightMargin: trigger.borderRight + Style.spacing.controlGap + text: "󰅀" + color: Qt.darker(root.foreground, 1.2) + font.family: root.fontFamily + font.pixelSize: Style.font.body + } + + MouseArea { + anchors.fill: parent + cursorShape: Qt.PointingHandCursor + onClicked: { + trigger.forceActiveFocus() + popup.opened ? popup.close() : popup.open() + } + } + + QQC.Popup { + id: popup + // Reparent to the window's content item so the popup is free of any + // clipping ancestor. Position + // and available height are recomputed on open and any time the + // trigger's geometry changes, since a binding on mapToItem alone + // won't reliably re-evaluate when ancestors scroll or resize. + parent: trigger.Window.window ? trigger.Window.window.contentItem : trigger + property real _anchorX: 0 + property real _anchorY: 0 + property real _availableBelow: 0 + readonly property real _windowHeight: parent ? parent.height : 0 + readonly property real _idealContent: resultList.contentHeight + Style.space(50) + readonly property real _maxRowsHeight: root.popupRowHeight * 6 + 5 * Style.spacing.labelGap + Style.space(50) + + function reposition() { + if (!parent) return + var p = trigger.mapToItem(parent, 0, trigger.height + Style.spacing.xxs) + _anchorX = p.x + _anchorY = p.y + _availableBelow = Math.max(0, _windowHeight - _anchorY - Style.space(12)) + } + + x: _anchorX + y: _anchorY + width: trigger.width + // Clamp to whatever fits below the trigger; don't force popupMinHeight + // when there isn't room, otherwise the popup overflows the window. + implicitHeight: Math.min(_availableBelow, _idealContent, _maxRowsHeight) + padding: Style.spacing.hairline + leftPadding: Border.left(root.popupBorderSpec) + Style.spacing.hairline + rightPadding: Border.right(root.popupBorderSpec) + Style.spacing.hairline + topPadding: Border.top(root.popupBorderSpec) + Style.spacing.hairline + bottomPadding: Border.bottom(root.popupBorderSpec) + Style.spacing.hairline + focus: true + + Connections { + target: trigger + function onXChanged() { popup.reposition() } + function onYChanged() { popup.reposition() } + function onWidthChanged() { popup.reposition() } + function onHeightChanged() { popup.reposition() } + } + + background: BorderSurface { + color: root.background + borderSpec: root.popupBorderSpec + radius: Style.cornerRadius + } + + onOpened: { + reposition() + searchField.text = "" + root.refresh() + root.recomputeFiltered() + Qt.callLater(function() { searchField.forceActiveFocus() }) + } + onClosed: searchField.text = "" + + contentItem: Column { + spacing: 0 + + Item { + id: searchHeader + width: parent.width + height: root.popupRowHeight + Style.spacing.controlPaddingX + + Row { + anchors.fill: parent + anchors.margins: Style.spacing.md + spacing: Style.spacing.rowGap + + TextField { + id: searchField + width: parent.width - refreshButton.width - parent.spacing + height: parent.height + placeholderText: root.placeholderText + foreground: root.foreground + accent: root.accent + font.family: root.fontFamily + font.pixelSize: Style.font.body + + onTextChanged: { + root.recomputeFiltered() + if (resultList.count > 0) resultList.currentIndex = 0 + } + + Keys.onPressed: function(event) { + if (event.key === Qt.Key_Escape) { + popup.close(); event.accepted = true + } else if (event.key === Qt.Key_Down) { + if (resultList.count > 0) { + resultList.currentIndex = 0 + resultList.forceActiveFocus() + } + event.accepted = true + } else if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter) { + if (resultList.count > 0) { + resultList.currentIndex = 0 + resultList.toggleCurrent() + } + event.accepted = true + } + } + } + + BorderSurface { + id: refreshButton + visible: root.arrayFrom(root.optionsCommand).length > 0 + enabled: !root.loadingOptions + width: parent.height + height: parent.height + radius: Style.cornerRadius + color: refreshHover.hovered + ? Style.hoverFillFor(root.foreground, root.accent) + : Style.normalFillFor(root.foreground, root.accent) + borderSpec: refreshHover.hovered + ? Border.controlSpec("hover-cursor", root.foreground, root.accent) + : Border.controlSpec("normal", root.foreground, root.accent) + + Text { + textFormat: Text.PlainText + anchors.centerIn: parent + text: root.loadingOptions ? "󰦖" : "󰑐" + color: root.foreground + font.family: root.fontFamily + font.pixelSize: Style.font.body + + RotationAnimator on rotation { + running: root.loadingOptions && !Style.reduceMotion + from: 0; to: 360 + duration: 800 + loops: Animation.Infinite + } + } + + HoverHandler { id: refreshHover } + MouseArea { + anchors.fill: parent + cursorShape: Qt.PointingHandCursor + onClicked: root.refresh() + } + } + } + } + + Rectangle { + width: parent.width + height: 1 + color: Util.alpha(root.foreground, 0.10) + } + + Item { + width: parent.width + height: popup.height - searchHeader.height - Style.spacing.xxs - 1 + + Text { + textFormat: Text.PlainText + anchors.centerIn: parent + visible: resultList.count === 0 + text: root.loadingOptions ? "Loading…" : (root.optionsError !== "" ? root.optionsError : root.emptyText) + color: Qt.darker(root.foreground, 1.6) + font.family: root.fontFamily + font.pixelSize: Style.font.body + } + + ListView { + id: resultList + anchors.fill: parent + spacing: Style.spacing.labelGap + clip: true + boundsBehavior: Flickable.StopAtBounds + model: root.filtered + currentIndex: -1 + keyNavigationEnabled: false + + function toggleCurrent() { + if (currentIndex < 0 || currentIndex >= root.filtered.length) return + root.toggleValue(root.filtered[currentIndex].value) + } + + Keys.priority: Keys.BeforeItem + Keys.onPressed: function(event) { + if (event.key === Qt.Key_Escape) { + popup.close(); event.accepted = true + } else if (event.key === Qt.Key_Down || event.text === "j") { + if (resultList.currentIndex >= resultList.count - 1) { + event.accepted = true; return + } + resultList.currentIndex = resultList.currentIndex + 1 + event.accepted = true + } else if (event.key === Qt.Key_Up || event.text === "k") { + if (resultList.currentIndex <= 0) { + searchField.forceActiveFocus() + event.accepted = true; return + } + resultList.currentIndex = resultList.currentIndex - 1 + event.accepted = true + } else if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter + || event.key === Qt.Key_Space) { + resultList.toggleCurrent(); event.accepted = true + } + } + + delegate: Rectangle { + required property var modelData + required property int index + + readonly property bool selected: root.isSelected(modelData.value) + + width: resultList.width + height: Math.max(root.popupRowHeight, rowContent.implicitHeight + Style.spacing.rowPaddingX) + color: index === resultList.currentIndex + ? Style.hoverFillFor(root.foreground, root.accent) + : "transparent" + + Row { + id: rowContent + anchors.left: parent.left + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + anchors.leftMargin: Style.spacing.controlPaddingX + anchors.rightMargin: Style.spacing.controlPaddingX + spacing: Style.spacing.rowGap + + BorderSurface { + id: checkbox + width: Style.space(16) + height: Style.space(16) + radius: Math.max(2, Style.cornerRadius / 2) + anchors.verticalCenter: parent.verticalCenter + color: selected ? Style.selectedFillFor(root.foreground, root.accent) : "transparent" + borderSpec: selected + ? Border.controlSpec("selected", root.foreground, root.accent) + : Border.controlSpec("normal", root.foreground, root.accent) + + Text { + anchors.centerIn: parent + visible: selected + text: "✓" + color: Style.selectedStateColor(root.foreground, root.accent) + font.family: root.fontFamily + font.pixelSize: Math.round(checkbox.height * 0.85) + font.bold: true + } + } + + Column { + width: parent.width - checkbox.width - parent.spacing + anchors.verticalCenter: parent.verticalCenter + spacing: Style.spacing.xxs + + Text { + textFormat: Text.PlainText + text: modelData.label + color: index === resultList.currentIndex ? Style.hoverStateColor(root.foreground, root.accent) : root.foreground + font.family: root.fontFamily + font.pixelSize: Style.font.body + elide: Text.ElideRight + width: parent.width + } + Text { + textFormat: Text.PlainText + visible: text !== "" + text: modelData.description + color: Qt.darker(root.foreground, 1.5) + font.family: root.fontFamily + font.pixelSize: Style.font.caption + elide: Text.ElideRight + width: parent.width + } + } + } + + MouseArea { + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onPositionChanged: resultList.currentIndex = parent.index + onClicked: root.toggleValue(modelData.value) + } + } + } + } + } + } + } + } +} diff --git a/quickshell/compat/omarchy/Ui/NumberField.qml b/quickshell/compat/omarchy/Ui/NumberField.qml new file mode 100644 index 0000000..880952c --- /dev/null +++ b/quickshell/compat/omarchy/Ui/NumberField.qml @@ -0,0 +1,84 @@ +import QtQuick +import QtQuick.Controls as QQC +import qs.compat.omarchy.Commons +Column { + id: root + + property string label: "" + property int value: 0 + property int from: 0 + property int to: 100 + property int stepSize: 1 + property color foreground: Color.foreground + property color accent: Color.accent + property string fontFamily: Style.font.family + property real fontSize: Style.font.body + property real fieldWidth: Style.spacing.numberFieldWidth + property bool hasCursor: false + property bool _hovered: false + property alias field: spin + + signal modified(int value) + signal hovered(bool on) + + spacing: Style.spacing.md + + Text { + textFormat: Text.PlainText + visible: root.label !== "" + text: root.label + color: Qt.darker(root.foreground, 1.4) + font.family: root.fontFamily + font.pixelSize: Style.font.bodySmall + } + + QQC.SpinBox { + id: spin + width: root.fieldWidth + implicitHeight: Math.max(Style.spacing.controlHeight, root.fontSize + Style.spacing.controlPaddingY * 2) + from: root.from + to: root.to + stepSize: root.stepSize + value: root.value + editable: true + font.family: root.fontFamily + font.pixelSize: root.fontSize + + readonly property bool _focused: spin.activeFocus + readonly property bool _hot: root._hovered || root.hasCursor + readonly property var _borderSpec: Border.controlSpec(_focused ? "focus" : (_hot ? "hover-cursor" : "normal"), root.foreground, root.accent) + + leftPadding: Border.left(_borderSpec) + Style.spacing.controlPaddingX + rightPadding: Border.right(_borderSpec) + Style.spacing.controlPaddingX + topPadding: Border.top(_borderSpec) + bottomPadding: Border.bottom(_borderSpec) + + onValueModified: root.modified(value) + + background: BorderSurface { + color: Style.controlFill(spin._focused, spin._hot, root.foreground, root.accent) + borderSpec: spin._borderSpec + radius: Style.cornerRadius + + HoverHandler { + onHoveredChanged: { + root._hovered = hovered + root.hovered(hovered) + } + } + } + + contentItem: TextInput { + text: spin.displayText + font: spin.font + color: root.foreground + selectionColor: Style.selectionFillFor(root.foreground, root.accent) + selectedTextColor: root.foreground + horizontalAlignment: Qt.AlignHCenter + verticalAlignment: Qt.AlignVCenter + readOnly: !spin.editable + validator: spin.validator + inputMethodHints: Qt.ImhFormattedNumbersOnly + } + } +} diff --git a/quickshell/compat/omarchy/Ui/OpticalGlyph.qml b/quickshell/compat/omarchy/Ui/OpticalGlyph.qml new file mode 100644 index 0000000..1c38a2a --- /dev/null +++ b/quickshell/compat/omarchy/Ui/OpticalGlyph.qml @@ -0,0 +1,57 @@ +import QtQuick +import qs.compat.omarchy.Commons +Item { + id: root + + property string text: "" + property string fontFamily: Style.font.family + property real fontSize: Style.font.body + property color color: Color.foreground + property bool debugBounds: false + + readonly property int renderedFontSize: Math.max(1, Math.round(fontSize)) + readonly property real tightWidth: Math.max(1, glyphMetrics.tightBoundingRect.width) + readonly property real horizontalCorrection: glyph.implicitWidth / 2 - (glyphMetrics.tightBoundingRect.x + tightWidth / 2) + readonly property real paintedCenterX: glyph.x + glyphMetrics.tightBoundingRect.x + tightWidth / 2 + readonly property real baselineY: glyph.y + glyph.baselineOffset + + TextMetrics { + id: glyphMetrics + font.family: root.fontFamily + font.pixelSize: root.renderedFontSize + text: root.text + } + + Text { + id: glyph + textFormat: Text.PlainText + // Keep the shared line box and baseline intact. Correcting only the + // horizontal painted bounds avoids per-glyph vertical drift. + // The correction is fractional, so x is set exactly: centerIn would snap it + // to a whole pixel and undo it. y still snaps, keeping the baseline crisp. + x: (root.width - width) / 2 + root.horizontalCorrection + y: Math.round((root.height - height) / 2) + text: root.text + color: root.color + font.family: root.fontFamily + font.pixelSize: root.renderedFontSize + renderType: Text.NativeRendering + } + + Rectangle { + visible: root.debugBounds + anchors.fill: parent + color: "transparent" + border.width: 1 + border.color: "#4488ff" + } + + Rectangle { + visible: root.debugBounds + x: 0 + y: Math.round(root.baselineY) + width: parent.width + height: 1 + color: "#44ff88" + } +} diff --git a/quickshell/compat/omarchy/Ui/OverlayWindow.qml b/quickshell/compat/omarchy/Ui/OverlayWindow.qml new file mode 100644 index 0000000..43a9c32 --- /dev/null +++ b/quickshell/compat/omarchy/Ui/OverlayWindow.qml @@ -0,0 +1,56 @@ +import QtQuick +import Quickshell +import Quickshell.Hyprland +import Quickshell.Wayland + +// A fullscreen overlay whose surface outlives each open. A fresh surface draws +// its first frames before the compositor sends its fractional scale, so an +// overlay mapped per open flashed blurry until the scale arrived. Closed, the +// surface parks as a 1x1, input-less, content-less layer below windows: small +// enough to cost nothing, off the overlay layer so it never blocks direct +// scanout for fullscreen apps. Opening only resizes and raises it. +PanelWindow { + id: window + + // Whether the overlay is showing. Drive this instead of visible. + property bool shown: false + property int shownLayer: WlrLayer.Overlay + property int shownKeyboardFocus: WlrKeyboardFocus.Exclusive + + // The surface no longer lands on the focused output by being mapped there, + // so it follows the focused monitor each time it is shown. Unset until the + // first show lets the compositor choose. + property var targetScreen: null + property Region emptyRegion: Region {} + + function focusedScreen() { + var monitor = Hyprland.focusedMonitor + var name = monitor ? String(monitor.name || "") : "" + for (var i = 0; i < Quickshell.screens.length; i++) { + if (Quickshell.screens[i].name === name) return Quickshell.screens[i] + } + return null + } + + onShownChanged: if (shown) targetScreen = focusedScreen() || targetScreen + + visible: true + screen: targetScreen + anchors { top: true; left: true; bottom: shown; right: shown } + implicitWidth: 1 + implicitHeight: 1 + mask: shown ? null : emptyRegion + color: "transparent" + exclusionMode: ExclusionMode.Ignore + WlrLayershell.layer: shown ? shownLayer : WlrLayer.Bottom + WlrLayershell.keyboardFocus: shown ? shownKeyboardFocus : WlrKeyboardFocus.None + + // Draw nothing until the surface has actually grown. A frame drawn while it + // is still 1x1 holds only the scrim's color, which the compositor would + // stretch across the whole screen until the fullscreen frame arrives. + Binding { + target: window.contentItem + property: "visible" + value: window.shown && window.width > 1 && window.height > 1 + } +} diff --git a/quickshell/compat/omarchy/Ui/Panel.qml b/quickshell/compat/omarchy/Ui/Panel.qml new file mode 100644 index 0000000..82b4485 --- /dev/null +++ b/quickshell/compat/omarchy/Ui/Panel.qml @@ -0,0 +1,58 @@ +import QtQuick +import Quickshell.Io +import qs.compat.omarchy.Commons +// Base item for plugin popup widgets. Many first-party plugins expose a bar +// button plus a popup from one QML entry point; this base owns the shared +// IPC-backed open/close lifecycle while implementations own button behavior, +// keyboard navigation, and content. +Item { + id: root + + property QtObject bar: null + property string moduleName: "" + property var settings: ({}) + property string ipcTarget: "" + property bool manageIpc: true + property alias controller: panelController + property bool popoutSwitching: false + property bool popoutSwitchClosing: false + + readonly property bool opened: panelController.open + readonly property color barForeground: bar ? bar.barForeground : Color.foreground + + function open() { panelController.show() } + function close() { panelController.hide() } + function closeForPopoutSwitch() { + popoutSwitchClosing = true + close() + Qt.callLater(function() { popoutSwitchClosing = false }) + } + function toggle() { opened ? close() : open() } + function switchPanel(direction) { + if (bar && typeof bar.switchPanelFrom === "function") return bar.switchPanelFrom(root, direction) + return false + } + + // Read a single value from this panel's inline shell.json entry, with a + // fallback for missing/null values. Matches BarWidget.setting(). + function setting(name, fallback) { + var value = settings ? settings[name] : undefined + return value === undefined || value === null ? fallback : value + } + + PanelController { + id: panelController + } + + ShellIpc { + enabled: root.manageIpc && root.ipcTarget !== "" + target: root.ipcTarget + + function open(): void { root.open() } + function close(): void { root.close() } + function show(): void { root.open() } + function hide(): void { root.close() } + function toggle(): void { root.toggle() } + } + +} diff --git a/quickshell/compat/omarchy/Ui/PanelActionButton.qml b/quickshell/compat/omarchy/Ui/PanelActionButton.qml new file mode 100644 index 0000000..7c0da36 --- /dev/null +++ b/quickshell/compat/omarchy/Ui/PanelActionButton.qml @@ -0,0 +1,99 @@ +import QtQuick +import qs.compat.omarchy.Commons +// Small (22×22 by default) icon button used at the right edge of panel rows +// for inline actions — forget network, confirm passphrase, unpair device, +// etc. Two visual modes are supported via `hoverColor`: +// - default: hoverColor === foreground → subtle foreground-tint hover +// - urgent: hoverColor === bar.urgent → red-tint hover for destructive +// actions like forget/unpair +// +// `enabled` gates clicks and dims the icon. The component owns its own +// hover state visuals; mouse hover does NOT update any panel cursor state +// here because action buttons are not cursor targets — the row they live +// in is. +// +// Set `focusable: true` to make the button keyboard-tabbable with the +// shared hover-cursor/focus tokens. Use this +// in form contexts where Tab walks a list +// of controls; leave it false for the right-edge actions on panel rows +// where the row's CursorSurface owns the keyboard cursor. +// +// Set `hasCursor: true` to have the button render the same hover state as +// mouse hover — so a panel's keyboard cursor lands on it identically. +// Use this when a PanelActionButton is itself the cursor target (rather +// than living inside a CursorSurface row). Emits `hovered(bool)` on +// pointer enter/leave so the panel can update its cursor state to match. +BorderSurface { + id: root + + property string iconText: "" + property string tooltipText: "" + property color foreground: Color.foreground + property color hoverColor: foreground + property string fontFamily: Style.font.family + property real fontSize: Style.font.icon + property real size: Math.max(Style.space(22), fontSize + Style.spacing.sm * 2) + + property bool focusable: false + property bool hasCursor: false + property bool bordered: false + + signal clicked() + signal hovered(bool isHovered) + + activeFocusOnTab: focusable + Keys.onReturnPressed: if (focusable) root.clicked() + Keys.onEnterPressed: if (focusable) root.clicked() + Keys.onSpacePressed: if (focusable) root.clicked() + + implicitWidth: size + implicitHeight: size + radius: Style.cornerRadius + + readonly property bool _showFocusRing: focusable && activeFocus + readonly property bool _hot: (mouse.containsMouse || root.hasCursor) && root.enabled + readonly property var _borderSpec: _showFocusRing + ? Border.controlSpec("focus", hoverColor, hoverColor) + : (_hot && bordered + ? Border.controlSpec("hover-cursor", hoverColor, hoverColor) + : (bordered ? Border.controlSpec("normal", foreground, Color.accent) : Border.none())) + + color: _showFocusRing + ? Style.focusFillFor(hoverColor, hoverColor) + : (_hot + ? Style.hoverFillFor(hoverColor, hoverColor) + : "transparent") + borderSpec: _borderSpec + + Behavior on color { ColorAnimation { duration: Style.duration(60) } } + + Text { + textFormat: Text.PlainText + anchors.centerIn: parent + text: root.iconText + color: root.enabled + ? (root._hot ? root.hoverColor : root.foreground) + : Qt.darker(root.foreground, 2.0) + font.family: root.fontFamily + font.pixelSize: root.fontSize + } + + MouseArea { + id: mouse + anchors.fill: parent + hoverEnabled: true + cursorShape: root.enabled ? Qt.PointingHandCursor : Qt.ArrowCursor + enabled: root.enabled + onContainsMouseChanged: root.hovered(containsMouse) + onClicked: { + if (root.focusable) root.forceActiveFocus() + root.clicked() + } + } + + PanelToolTip { + visible: root.tooltipText !== "" && mouse.containsMouse + text: root.tooltipText + fontFamily: root.fontFamily + } +} diff --git a/quickshell/compat/omarchy/Ui/PanelController.qml b/quickshell/compat/omarchy/Ui/PanelController.qml new file mode 100644 index 0000000..c386640 --- /dev/null +++ b/quickshell/compat/omarchy/Ui/PanelController.qml @@ -0,0 +1,16 @@ +import QtQuick +// Stores the open state for a shell panel. Panel owns the public lifecycle +// methods and IPC wiring; this object only keeps state separate from the +// panel implementation's own properties. +// +// Usage: +// PanelController { id: panelController } +QtObject { + id: root + + property bool open: false + + function toggle() { open = !open } + function show() { if (!open) open = true } + function hide() { open = false } +} diff --git a/quickshell/compat/omarchy/Ui/PanelHero.qml b/quickshell/compat/omarchy/Ui/PanelHero.qml new file mode 100644 index 0000000..a60809a --- /dev/null +++ b/quickshell/compat/omarchy/Ui/PanelHero.qml @@ -0,0 +1,110 @@ +import QtQuick +import qs.compat.omarchy.Commons +Item { + id: root + + property Component iconComponent: null + property string title: "" + property string meta: "" + property string detail: "" + property color foreground: Color.foreground + property string fontFamily: Style.font.family + property real iconSize: Style.font.display + property real iconOpacity: 1.0 + property alias metaOpacity: metaText.opacity + + // Optional control pinned to the trailing edge of the hero — a ToggleSwitch, + // a small button. The hero centers it against the labels and reserves the + // space itself, so callers never do the geometry. + property Component trailingControl: null + + readonly property color dim: Qt.darker(foreground, 1.4) + readonly property real trailingInset: trailingLoader.item && trailingLoader.item.visible ? trailingLoader.width + Style.space(12) : 0 + + width: parent ? parent.width : implicitWidth + implicitHeight: Math.max(iconLoader.implicitHeight, heroLabels.implicitHeight, trailingLoader.implicitHeight) + + Loader { + id: iconLoader + sourceComponent: root.iconComponent + anchors.left: parent.left + anchors.verticalCenter: parent.verticalCenter + opacity: root.iconOpacity + } + + Column { + id: heroLabels + anchors.left: iconLoader.right + anchors.leftMargin: Style.space(14) + anchors.right: parent.right + anchors.rightMargin: root.trailingInset + anchors.verticalCenter: parent.verticalCenter + spacing: Style.space(2) + + Row { + id: titleRow + visible: root.title !== "" || detailPill.visible + width: parent.width + + Text { + textFormat: Text.PlainText + visible: root.title !== "" + text: root.title + width: Math.min(implicitWidth, Math.max(0, parent.width - (detailPill.visible ? detailPill.implicitWidth + Style.space(8) : 0))) + color: root.foreground + font.family: root.fontFamily + font.pixelSize: Style.font.title + font.bold: true + elide: Text.ElideRight + } + + Item { + width: Math.max(0, parent.width - parent.children[0].width - detailPill.implicitWidth) + height: 1 + } + + BorderSurface { + id: detailPill + visible: root.detail !== "" + implicitWidth: detailText.implicitWidth + Style.space(10) + implicitHeight: detailText.implicitHeight + Style.space(4) + anchors.verticalCenter: parent.verticalCenter + color: "transparent" + borderSpec: Border.controlSpec("normal", root.foreground, Color.accent) + radius: Style.cornerRadius + + Text { + id: detailText + textFormat: Text.PlainText + anchors.centerIn: parent + text: root.detail + color: root.dim + font.family: root.fontFamily + font.pixelSize: Style.font.body + font.bold: true + } + } + } + + Text { + id: metaText + textFormat: Text.PlainText + width: parent.width + text: root.meta.toUpperCase() + visible: text !== "" + color: root.dim + font.family: root.fontFamily + font.pixelSize: Style.font.caption + font.bold: true + font.letterSpacing: 1.2 + elide: Text.ElideRight + } + } + + Loader { + id: trailingLoader + sourceComponent: root.trailingControl + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + } +} diff --git a/quickshell/compat/omarchy/Ui/PanelKeyCatcher.qml b/quickshell/compat/omarchy/Ui/PanelKeyCatcher.qml new file mode 100644 index 0000000..03cf59f --- /dev/null +++ b/quickshell/compat/omarchy/Ui/PanelKeyCatcher.qml @@ -0,0 +1,97 @@ +import QtQuick + +// Drop-in key dispatcher for keyboard-driven panels. Wraps panel content +// and emits semantic signals so each panel keeps its own state machine +// (focusSection, selectedIndex, action rules) while the boilerplate +// key handling lives here. +// +// Usage: +// Common.KeyboardPanel { +// ... +// PanelKeyCatcher { +// anchors.fill: parent +// onMoveRequested: function(dx, dy) { root.moveCursor(dx, dy) } +// onActivateRequested: root.activateCursor() +// onCloseRequested: root.close() +// onDeleteRequested: root.deleteSelected() +// onTextKey: function(t, modifiers) { if (t === "r") root.refresh() } +// +// Column { ... panel content ... } +// } +// } +// +// Keys.priority: Keys.BeforeItem means this handler gets keys first, +// even when a descendant has activeFocus. That's what lets Up/Down +// arrows drive the cursor instead of being consumed by an inner +// Flickable's built-in scroll handling. When a panel has an inline +// editor (wifi passphrase, gallery TextField demo) the panel must +// set `blocked: editor.activeFocus` so this handler short-circuits +// and the editor receives keys normally. +// +// blocked: when true, ALL keys are forwarded to descendants without +// triggering signals. +Item { + id: root + + property bool blocked: false + // Panels that let items be reordered set this, and Ctrl+Up/Down (or + // Ctrl+k/j) then asks to move the current item instead of the cursor. + property bool reorderable: false + + signal moveRequested(int dx, int dy) + signal reorderRequested(int dy) + signal activateRequested() + signal returnRequested() + signal closeRequested() + signal deleteRequested() + signal tabRequested(int direction) + // The held modifiers ride along, so a panel can tell Alt+T from T. + signal textKey(string text, int modifiers) + + focus: true + Keys.priority: Keys.BeforeItem + Keys.onPressed: function(event) { + if (blocked) return + + if (event.key === Qt.Key_Escape) { + closeRequested(); event.accepted = true; return + } + if (event.key === Qt.Key_Tab || event.key === Qt.Key_Backtab) { + tabRequested((event.modifiers & Qt.ShiftModifier) || event.key === Qt.Key_Backtab ? -1 : 1) + event.accepted = true + return + } + if (reorderable && (event.modifiers & Qt.ControlModifier)) { + var up = event.key === Qt.Key_Up || event.key === Qt.Key_K + var down = event.key === Qt.Key_Down || event.key === Qt.Key_J + if (up || down) { + reorderRequested(down ? 1 : -1); event.accepted = true; return + } + } + if (event.key === Qt.Key_Down || event.text === "j") { + moveRequested(0, 1); event.accepted = true; return + } + if (event.key === Qt.Key_Up || event.text === "k") { + moveRequested(0, -1); event.accepted = true; return + } + if (event.key === Qt.Key_Right || event.text === "l") { + moveRequested(1, 0); event.accepted = true; return + } + if (event.key === Qt.Key_Left || event.text === "h") { + moveRequested(-1, 0); event.accepted = true; return + } + if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter) { + returnRequested() + activateRequested(); event.accepted = true; return + } + if (event.key === Qt.Key_Space) { + activateRequested(); event.accepted = true; return + } + if (event.key === Qt.Key_Delete || event.text === "x" || event.text === "X") { + deleteRequested(); event.accepted = true; return + } + if (event.text && event.text.length === 1) { + textKey(event.text, event.modifiers) + } + } +} diff --git a/quickshell/compat/omarchy/Ui/PanelSectionHeader.qml b/quickshell/compat/omarchy/Ui/PanelSectionHeader.qml new file mode 100644 index 0000000..2399d60 --- /dev/null +++ b/quickshell/compat/omarchy/Ui/PanelSectionHeader.qml @@ -0,0 +1,29 @@ +import QtQuick +import qs.compat.omarchy.Commons +// Small-caps-style label that introduces a panel section ("DNS provider", +// "Wi-Fi networks", "Output device", "Paired devices"). Sits between a +// PanelSeparator and the content rows. +Text { + id: root + + property color foreground: Color.foreground + property string fontFamily: Style.font.family + property real fontSize: Style.font.caption + + // Callers bind `text` from outside this file, so the default has to be set + // here. AutoText would let a section title that happens to carry a device or + // network name promote itself to rich text. + textFormat: Text.PlainText + color: Qt.darker(foreground, 1.4) + font.family: fontFamily + font.pixelSize: fontSize + font.bold: true + + // Glyphs can paint above the box Text reserves for them: JetBrainsMono Nerd + // Font's outlines run 10% of the em past its own ascent, and a patched or + // user-chosen family can be worse. That sliver is invisible in normal flow, + // but a header sitting at the top of a clipping list — bluetooth's device + // list, network's station list — loses it to the clip and renders beheaded. + // Reserve the overshoot here so every panel is covered at once. + topPadding: Math.ceil(fontSize * 0.15) +} diff --git a/quickshell/compat/omarchy/Ui/PanelSeparator.qml b/quickshell/compat/omarchy/Ui/PanelSeparator.qml new file mode 100644 index 0000000..9f5d0eb --- /dev/null +++ b/quickshell/compat/omarchy/Ui/PanelSeparator.qml @@ -0,0 +1,17 @@ +import QtQuick +import qs.compat.omarchy.Commons +// 1px horizontal divider for panel sections. The alpha-on-foreground tint +// keeps the rule legible against the panel background without competing +// with text or borders. +Rectangle { + id: root + + property color foreground: Color.foreground + property real strength: 0.12 + + width: parent ? parent.width : implicitWidth + implicitWidth: 100 + implicitHeight: 1 + height: 1 + color: Qt.rgba(foreground.r, foreground.g, foreground.b, strength) +} diff --git a/quickshell/compat/omarchy/Ui/PanelSlider.qml b/quickshell/compat/omarchy/Ui/PanelSlider.qml new file mode 100644 index 0000000..7fae205 --- /dev/null +++ b/quickshell/compat/omarchy/Ui/PanelSlider.qml @@ -0,0 +1,149 @@ +import QtQuick +import qs.compat.omarchy.Commons +import "../../../theme" as G +Item { + id: root + + property QtObject bar: null + property real value: 0 + property real minimum: 0 + property real maximum: 1 + property real step: 0.05 + property bool integer: false + property color trackColor: G.Theme.surfaceVariant + property color fillColor: G.Theme.accent + property color knobColor: G.Theme.text + property bool dragging: false + property real trackHeight: Math.max(4, Math.round(Style.spacing.controlHeight * 0.11)) + property real knobSize: Math.max(14, Math.round(Style.spacing.controlHeight * 0.38)) + property real liveValue: value + + // macOS-style notches. When > 1, that many evenly-spaced tick marks are cut + // into the track (drawn in the panel background color, so only the part + // crossing the track shows). Purely visual — snapping is the caller's job via + // `integer`/`step` or an index-based value. Default 0 leaves the track plain. + property int tickCount: 0 + property color tickColor: bar ? bar.background : Color.background + + onValueChanged: if (!dragging) liveValue = value + + signal moved(real value) + signal released(real value) + + // Right-click is a secondary action on the whole track — audio uses it to + // mute the channel the slider belongs to. Dragging stays left-button only. + signal rightClicked() + + implicitWidth: Style.space(200) + implicitHeight: Math.max(Style.space(22), knobSize + Style.spacing.md) + + readonly property real range: Math.max(0.0001, maximum - minimum) + readonly property real progress: Math.max(0, Math.min(1, (liveValue - minimum) / range)) + readonly property bool _hot: mouseArea.containsMouse || root.dragging + + Rectangle { + id: track + anchors.verticalCenter: parent.verticalCenter + anchors.left: parent.left + anchors.right: parent.right + height: root.trackHeight + radius: height / 2 + color: root.trackColor + } + + Rectangle { + id: fill + anchors.verticalCenter: track.verticalCenter + anchors.left: track.left + height: track.height + radius: track.radius + color: root.fillColor + width: track.width * root.progress + + Behavior on width { + enabled: !root.dragging + NumberAnimation { duration: Style.duration(140); easing.type: Easing.OutCubic } + } + } + + Repeater { + model: root.tickCount > 1 ? root.tickCount : 0 + Rectangle { + required property int index + width: Math.max(1, Style.space(2)) + height: root.trackHeight + Style.space(4) + radius: 1 + color: root.tickColor + anchors.verticalCenter: track.verticalCenter + x: Math.max(0, Math.min(track.width - width, + track.width * (index / (root.tickCount - 1)) - width / 2)) + } + } + + BorderSurface { + id: knob + width: root.knobSize + height: root.knobSize + radius: root.knobSize / 2 + color: root.knobColor + borderSpec: Border.flat(root.bar ? root.bar.background : "#101315", Math.max(1, Style.space(2))) + anchors.verticalCenter: track.verticalCenter + x: Math.max(0, Math.min(track.width - width, track.width * root.progress - width / 2)) + scale: root._hot ? 1.15 : 1.0 + + Behavior on x { + enabled: !root.dragging + NumberAnimation { duration: Style.duration(140); easing.type: Easing.OutCubic } + } + + Behavior on scale { + NumberAnimation { duration: Style.duration(110); easing.type: Easing.OutCubic } + } + } + + MouseArea { + id: mouseArea + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + acceptedButtons: Qt.LeftButton | Qt.RightButton + + function valueFromX(x) { + var clamped = Math.max(0, Math.min(track.width, x)) + var raw = root.minimum + (clamped / track.width) * root.range + if (root.integer) raw = Math.round(raw) + return Math.max(root.minimum, Math.min(root.maximum, raw)) + } + + onPressed: function(mouse) { + if (mouse.button !== Qt.LeftButton) return + root.dragging = true + var next = valueFromX(mouse.x) + root.liveValue = next + root.moved(next) + } + onClicked: function(mouse) { + if (mouse.button === Qt.RightButton) root.rightClicked() + } + onPositionChanged: function(mouse) { + if (!root.dragging) return + var next = valueFromX(mouse.x) + root.liveValue = next + root.moved(next) + } + onReleased: function(mouse) { + if (mouse.button !== Qt.LeftButton) return + root.dragging = false + root.released(root.liveValue) + root.liveValue = root.value + } + onWheel: function(wheel) { + var delta = wheel.angleDelta.y > 0 ? root.step : -root.step + var next = Math.max(root.minimum, Math.min(root.maximum, root.liveValue + delta)) + if (root.integer) next = Math.round(next) + root.liveValue = next + root.moved(next) + root.released(next) + } + } +} diff --git a/quickshell/compat/omarchy/Ui/PanelToolTip.qml b/quickshell/compat/omarchy/Ui/PanelToolTip.qml new file mode 100644 index 0000000..c1a400f --- /dev/null +++ b/quickshell/compat/omarchy/Ui/PanelToolTip.qml @@ -0,0 +1,48 @@ +import QtQuick +import QtQuick.Controls +import qs.compat.omarchy.Commons +// Styled wrapper around Qt Quick Controls ToolTip. Drop-in: declare inside +// the hovered item and bind `visible` to the hover state, e.g. +// PanelToolTip { +// visible: mouse.containsMouse +// text: "Forget network" +// } +// +// Defaults pull from [tooltip] in shell.toml via Color.tooltip.*. Override +// the panel* properties per-instance only when you need a tooltip that +// intentionally diverges from the theme. +// +// Property names are prefixed `panel*` to avoid clashing with ToolTip's +// built-in `background`/`font` properties. +ToolTip { + id: root + + property color panelForeground: Color.tooltip.text + property color panelBackground: Color.tooltip.background + property color panelBorder: Color.tooltip.border + property string fontFamily: Style.font.family + property real fontSize: Style.font.bodySmall + + readonly property var panelBorderSpec: Border.localOrSurfaceSpec("tooltip", "border", panelBorder, Color.tooltip.border, Style.normalBorderWidth) + + delay: 400 + padding: 0 + + background: BorderSurface { + color: root.panelBackground + borderSpec: root.panelBorderSpec + radius: Style.cornerRadius + } + + contentItem: Text { + textFormat: Text.PlainText + text: root.text + color: root.panelForeground + font.family: root.fontFamily + font.pixelSize: root.fontSize + leftPadding: Border.left(root.panelBorderSpec) + Style.spacing.controlPaddingX + rightPadding: Border.right(root.panelBorderSpec) + Style.spacing.controlPaddingX + topPadding: Border.top(root.panelBorderSpec) + Style.spacing.controlPaddingY + bottomPadding: Border.bottom(root.panelBorderSpec) + Style.spacing.controlPaddingY + } +} diff --git a/quickshell/compat/omarchy/Ui/PluginBarApi.qml b/quickshell/compat/omarchy/Ui/PluginBarApi.qml new file mode 100644 index 0000000..03c748b --- /dev/null +++ b/quickshell/compat/omarchy/Ui/PluginBarApi.qml @@ -0,0 +1,87 @@ +import QtQuick + +// Bar surface exposed to an installed third-party widget. Scalar presentation +// state is mirrored by Bar.qml and operations are delegated through scoped +// callbacks. The facade avoids direct host-Bar injection; it cannot isolate a +// visual child from the parent hierarchy of the QML scene that renders it. +QtObject { + id: api + + required property string pluginId + required property string moduleName + property var shell: null + + property color foreground: "transparent" + property color barForeground: "transparent" + property color background: "transparent" + property color urgent: "transparent" + property string fontFamily: "" + property string position: "top" + property bool vertical: false + property int barSize: 0 + property bool transparent: false + property bool foregroundAnimationEnabled: true + property bool centerSectionRevealHeld: false + property bool _centerHoverRevealSuppressed: false + readonly property bool centerHoverRevealSuppressed: _centerHoverRevealSuppressed + property var activePopout: null + property var clickTargets: [] + property var layoutConfig: ({}) + readonly property var foreignPopoutMarker: ({ foreign: true }) + + property var _showTooltip: null + property var _hideTooltip: null + property var _registerClickTarget: null + property var _unregisterClickTarget: null + property var _requestPopout: null + property var _releasePopout: null + property var _switchPanelFrom: null + property var _targetBelongsToWindow: null + property var _moduleWidgets: null + property var _run: null + property var _setCenterHoverRevealSuppressed: null + + function setCenterHoverRevealSuppressed(value) { + if (_setCenterHoverRevealSuppressed) _setCenterHoverRevealSuppressed(!!value) + } + + function showTooltip(target, text) { + if (_showTooltip) _showTooltip(target, String(text || "")) + } + + function hideTooltip(target) { + if (_hideTooltip) _hideTooltip(target) + } + + function registerClickTarget(target) { + if (_registerClickTarget) _registerClickTarget(target) + } + + function unregisterClickTarget(target) { + if (_unregisterClickTarget) _unregisterClickTarget(target) + } + + function requestPopout(owner) { + if (_requestPopout) _requestPopout(owner) + } + + function releasePopout(owner) { + if (_releasePopout) _releasePopout(owner) + } + + function switchPanelFrom(owner, direction) { + return _switchPanelFrom ? _switchPanelFrom(owner, direction) : false + } + + function targetBelongsToWindow(target, window) { + return _targetBelongsToWindow ? _targetBelongsToWindow(target, window) : false + } + + function moduleWidgets(id) { + return _moduleWidgets ? _moduleWidgets(String(id || "")) : [] + } + + function run(command) { + if (_run) _run(String(command || "")) + } +} diff --git a/quickshell/compat/omarchy/Ui/PointerMoveGate.qml b/quickshell/compat/omarchy/Ui/PointerMoveGate.qml new file mode 100644 index 0000000..e97b9d8 --- /dev/null +++ b/quickshell/compat/omarchy/Ui/PointerMoveGate.qml @@ -0,0 +1,54 @@ +import QtQuick + +// Filters synthetic hover churn from moving delegates under a stationary +// pointer. Call reset() after keyboard/list mutations, then moved() from a +// row MouseArea's onPositionChanged before changing cursor selection. A +// transition known to originate from the pointer can call allowInitialSample() +// so the item under the stationary pointer remains selected. +QtObject { + id: root + + property Item referenceItem: null + property real threshold: 1 + property bool primed: false + property bool initialSampleAllowed: false + property real lastX: 0 + property real lastY: 0 + + function reset() { + root.primed = false + root.initialSampleAllowed = false + root.lastX = 0 + root.lastY = 0 + } + + function allowInitialSample() { + root.reset() + root.initialSampleAllowed = true + } + + function moved(item, mouse) { + if (!item || !mouse) { + root.reset() + return false + } + + var target = root.referenceItem || item + var point = item.mapToItem(target, mouse.x, mouse.y) + var firstSample = !root.primed + var didMove = !firstSample + ? Math.abs(point.x - root.lastX) > root.threshold || Math.abs(point.y - root.lastY) > root.threshold + : root.initialSampleAllowed + + // Keep the previous accepted position while filtering jitter so slow, + // sub-threshold steps accumulate into deliberate pointer movement. + if (firstSample || didMove) { + root.lastX = point.x + root.lastY = point.y + } + root.primed = true + root.initialSampleAllowed = false + + return didMove + } +} diff --git a/quickshell/compat/omarchy/Ui/PopupCard.qml b/quickshell/compat/omarchy/Ui/PopupCard.qml new file mode 100644 index 0000000..51f598c --- /dev/null +++ b/quickshell/compat/omarchy/Ui/PopupCard.qml @@ -0,0 +1,8 @@ +import QtQuick +// glassMxrph: Omarchy's click/hover popup card, drawn as a glassMxrph bar +// drawer. "click" closes on outside clicks; "hover" leaves opening and closing +// to its owner. See GlassPopupBase for the shared implementation and API. +GlassPopupBase { + property string triggerMode: "click" + mode: triggerMode === "hover" ? "hover" : "click" +} diff --git a/quickshell/compat/omarchy/Ui/ScreenMoveRemap.qml b/quickshell/compat/omarchy/Ui/ScreenMoveRemap.qml new file mode 100644 index 0000000..44d2308 --- /dev/null +++ b/quickshell/compat/omarchy/Ui/ScreenMoveRemap.qml @@ -0,0 +1,43 @@ +import QtQuick + +// Hyprland leaves an already-mapped layer surface at its old global position +// when its monitor moves within the layout: undocking disables the internal +// panel, the external monitor shifts to x=0, and long-lived surfaces such as +// the bar and background keep rendering at the old offset — or entirely +// off-screen — until they are unmapped and remapped. Watch the screen's +// origin and pulse `remapping` when it moves; the owning window folds that +// into its `visible` binding so the compositor re-places the surface at the +// monitor's new origin. +Item { + id: root + + required property var window + readonly property var screen: window ? window.screen : null + + // Fold into the window's binding: visible: && !guard.remapping + property bool remapping: false + + visible: false + + // A layout reshuffle can move the monitor more than once before it lands. + // Let the positions settle before the single remap pulse. + Timer { + id: settleTimer + interval: 200 + onTriggered: root.remapping = true + } + + // Hold the surface unmapped for a beat so the compositor processes the + // unmap before the remap instead of coalescing them into a no-op. + Timer { + interval: 50 + running: root.remapping + onTriggered: root.remapping = false + } + + Connections { + target: root.screen + function onXChanged() { settleTimer.restart() } + function onYChanged() { settleTimer.restart() } + } +} diff --git a/quickshell/compat/omarchy/Ui/SearchableDropdown.qml b/quickshell/compat/omarchy/Ui/SearchableDropdown.qml new file mode 100644 index 0000000..794f516 --- /dev/null +++ b/quickshell/compat/omarchy/Ui/SearchableDropdown.qml @@ -0,0 +1,352 @@ +import QtQuick +import QtQuick.Controls as QQC +import qs.compat.omarchy.Commons +// Searchable single-select dropdown. Same trigger shape as Dropdown, but +// the popup leads with an embedded TextField that filters the option +// list in real time. Use for pickers with enough options that scanning +// is friction. +// +// Filtering is case-insensitive substring against each option's label. +// Options can be string[] or [{ value, label, description? }] — the same +// shape Dropdown accepts. The filter clears whenever the popup closes. +// +// Keyboard: Tab to focus the trigger, Enter/Space opens (search focused +// immediately). Down arrow from the search jumps to the first match; +// Up from the first match returns to the search. Enter selects, Esc +// closes (and clears the filter). +Item { + id: root + + property string label: "" + property string value: "" + property var options: [] + property string placeholderText: "Search..." + property string emptyText: "No matches" + property string triggerLabel: "" + + property color foreground: Color.popups.text + property color background: Color.popups.background + property color popupBorder: Color.popups.border + property color accent: Color.accent + readonly property var popupBorderSpec: Border.localOrSurfaceSpec("popups", "border", popupBorder, Color.popups.border, Style.normalBorderWidth) + property string fontFamily: Style.font.family + property int rowHeight: Style.spacing.controlHeight + property int popupRowHeight: Style.spacing.popupRowHeight + property int popupMinHeight: Style.spacing.searchablePopupMinHeight + property bool showLabel: true + + // Panel-cursor flag. When true, the trigger renders the shared + // hover-cursor state. Active Qt focus defaults to the same visuals. + // Emits `hovered(bool)` on pointer enter/leave so the panel can keep + // its cursor state in sync with the mouse. + property bool hasCursor: false + + // popupOpen + open()/close()/toggle() let a parent panel know when the + // dropdown owns keys (search field + result list are active) and + // suspend its own keyCatcher so typing into the filter doesn't drive + // the panel cursor. + readonly property bool popupOpen: popup.opened + function open() { popup.open() } + function close() { popup.close() } + function toggle() { popup.opened ? popup.close() : popup.open() } + + signal changed(string value) + signal hovered(bool isHovered) + + function optionValue(o) { + return (o && typeof o === "object") ? String(o.value) : String(o) + } + function optionLabel(o) { + return (o && typeof o === "object") ? String(o.label) : String(o) + } + function optionDescription(o) { + return (o && typeof o === "object" && o.description) ? String(o.description) : "" + } + function currentLabel() { + for (var i = 0; i < options.length; i++) { + if (optionValue(options[i]) === value) return optionLabel(options[i]) + } + return value + } + + property var filtered: options + function recomputeFiltered() { + var q = searchField.text.toLowerCase() + if (!q) { filtered = options; return } + var out = [] + for (var i = 0; i < options.length; i++) { + var lbl = optionLabel(options[i]).toLowerCase() + var desc = optionDescription(options[i]).toLowerCase() + if (lbl.indexOf(q) !== -1 || desc.indexOf(q) !== -1) out.push(options[i]) + } + filtered = out + } + + onOptionsChanged: recomputeFiltered() + + implicitWidth: Style.spacing.searchableDropdownWidth + implicitHeight: showLabel && label !== "" ? rowHeight + Style.spacing.huge : rowHeight + + Column { + anchors.fill: parent + spacing: Style.spacing.labelGap + + Text { + textFormat: Text.PlainText + visible: root.showLabel && root.label !== "" + text: root.label + color: Qt.darker(root.foreground, 1.4) + font.family: root.fontFamily + font.pixelSize: Style.font.caption + font.bold: true + } + + BorderSurface { + id: trigger + width: parent.width + height: root.rowHeight + radius: Style.cornerRadius + + readonly property bool _focused: trigger.activeFocus + readonly property bool _hot: triggerHover.hovered || root.hasCursor + readonly property var _borderSpec: Border.controlSpec(trigger._focused ? "focus" : (trigger._hot ? "hover-cursor" : "normal"), root.foreground, root.accent) + + color: Style.controlFill(trigger._focused, trigger._hot, root.foreground, root.accent) + borderSpec: _borderSpec + + activeFocusOnTab: true + + HoverHandler { + id: triggerHover + onHoveredChanged: root.hovered(hovered) + } + + Keys.onPressed: function(event) { + if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter + || event.key === Qt.Key_Space || event.key === Qt.Key_Down) { + popup.opened ? popup.close() : popup.open() + event.accepted = true + } else if (event.key === Qt.Key_Escape && popup.opened) { + popup.close(); event.accepted = true + } + } + + Text { + textFormat: Text.PlainText + anchors.left: parent.left + anchors.right: chevron.left + anchors.verticalCenter: parent.verticalCenter + anchors.leftMargin: trigger.borderLeft + Style.spacing.controlPaddingX + anchors.rightMargin: trigger.borderRight + Style.spacing.md + text: root.currentLabel() || root.triggerLabel || root.placeholderText + color: (root.currentLabel() || root.triggerLabel) ? root.foreground : Qt.darker(root.foreground, 1.5) + font.family: root.fontFamily + font.pixelSize: Style.font.body + elide: Text.ElideRight + } + + Text { + id: chevron + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + anchors.rightMargin: trigger.borderRight + Style.spacing.controlGap + text: "󰅀" + color: Qt.darker(root.foreground, 1.2) + font.family: root.fontFamily + font.pixelSize: Style.font.body + } + + MouseArea { + anchors.fill: parent + cursorShape: Qt.PointingHandCursor + onClicked: { + trigger.forceActiveFocus() + popup.opened ? popup.close() : popup.open() + } + } + + QQC.Popup { + id: popup + x: 0 + y: trigger.height + Style.spacing.xxs + width: trigger.width + implicitHeight: Math.max(root.popupMinHeight, + Math.min(resultList.contentHeight + Style.space(50), + root.popupRowHeight * 6 + 5 * Style.spacing.labelGap + Style.space(50))) + padding: Style.spacing.hairline + leftPadding: Border.left(root.popupBorderSpec) + Style.spacing.hairline + rightPadding: Border.right(root.popupBorderSpec) + Style.spacing.hairline + topPadding: Border.top(root.popupBorderSpec) + Style.spacing.hairline + bottomPadding: Border.bottom(root.popupBorderSpec) + Style.spacing.hairline + focus: true + + background: BorderSurface { + color: root.background + borderSpec: root.popupBorderSpec + radius: Style.cornerRadius + } + + onOpened: { + searchField.text = "" + root.recomputeFiltered() + Qt.callLater(function() { searchField.forceActiveFocus() }) + } + onClosed: searchField.text = "" + + contentItem: Column { + spacing: 0 + + Item { + id: searchHeader + width: parent.width + height: root.popupRowHeight + Style.spacing.controlPaddingX + + TextField { + id: searchField + anchors.fill: parent + anchors.margins: Style.spacing.md + placeholderText: root.placeholderText + foreground: root.foreground + accent: root.accent + font.family: root.fontFamily + font.pixelSize: Style.font.body + + onTextChanged: { + root.recomputeFiltered() + if (resultList.count > 0) resultList.currentIndex = 0 + } + + Keys.onPressed: function(event) { + if (event.key === Qt.Key_Escape) { + popup.close(); event.accepted = true + } else if (event.key === Qt.Key_Down) { + if (resultList.count > 0) { + resultList.currentIndex = 0 + resultList.forceActiveFocus() + } + event.accepted = true + } else if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter) { + if (resultList.count > 0) { + resultList.currentIndex = 0 + resultList.selectCurrent() + } + event.accepted = true + } + } + } + } + + Rectangle { + width: parent.width + height: 1 + color: Util.alpha(root.foreground, 0.10) + } + + Item { + width: parent.width + height: popup.height - searchHeader.height - Style.spacing.xxs - 1 + + Text { + textFormat: Text.PlainText + anchors.centerIn: parent + visible: resultList.count === 0 + text: root.emptyText + color: Qt.darker(root.foreground, 1.6) + font.family: root.fontFamily + font.pixelSize: Style.font.body + } + + ListView { + id: resultList + anchors.fill: parent + spacing: Style.spacing.labelGap + clip: true + boundsBehavior: Flickable.StopAtBounds + model: root.filtered + currentIndex: -1 + keyNavigationEnabled: false + + function selectCurrent() { + if (currentIndex < 0 || currentIndex >= root.filtered.length) return + var v = root.optionValue(root.filtered[currentIndex]) + root.value = v + root.changed(v) + popup.close() + } + + Keys.priority: Keys.BeforeItem + Keys.onPressed: function(event) { + if (event.key === Qt.Key_Escape) { + popup.close(); event.accepted = true + } else if (event.key === Qt.Key_Down || event.text === "j") { + if (resultList.currentIndex >= resultList.count - 1) { + event.accepted = true; return + } + resultList.currentIndex = resultList.currentIndex + 1 + event.accepted = true + } else if (event.key === Qt.Key_Up || event.text === "k") { + if (resultList.currentIndex <= 0) { + searchField.forceActiveFocus() + event.accepted = true; return + } + resultList.currentIndex = resultList.currentIndex - 1 + event.accepted = true + } else if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter) { + resultList.selectCurrent(); event.accepted = true + } + } + + delegate: Rectangle { + required property var modelData + required property int index + width: resultList.width + height: Math.max(root.popupRowHeight, rowContent.implicitHeight + Style.spacing.rowPaddingX) + color: index === resultList.currentIndex + ? Style.hoverFillFor(root.foreground, root.accent) + : "transparent" + + Column { + id: rowContent + anchors.left: parent.left + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + anchors.leftMargin: Style.spacing.controlPaddingX + anchors.rightMargin: Style.spacing.controlPaddingX + spacing: Style.spacing.xxs + + Text { + textFormat: Text.PlainText + text: root.optionLabel(modelData) + color: index === resultList.currentIndex ? Style.hoverStateColor(root.foreground, root.accent) : root.foreground + font.family: root.fontFamily + font.pixelSize: Style.font.body + elide: Text.ElideRight + width: parent.width + } + Text { + textFormat: Text.PlainText + visible: text !== "" + text: root.optionDescription(modelData) + color: Qt.darker(root.foreground, 1.5) + font.family: root.fontFamily + font.pixelSize: Style.font.caption + elide: Text.ElideRight + width: parent.width + } + } + + MouseArea { + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onPositionChanged: resultList.currentIndex = parent.index + onClicked: resultList.selectCurrent() + } + } + } + } + } + } + } + } +} diff --git a/quickshell/compat/omarchy/Ui/SpeedTestOverlay.qml b/quickshell/compat/omarchy/Ui/SpeedTestOverlay.qml new file mode 100644 index 0000000..270dafd --- /dev/null +++ b/quickshell/compat/omarchy/Ui/SpeedTestOverlay.qml @@ -0,0 +1,411 @@ +import QtQuick +import QtQuick.Layouts +import QtQuick.Shapes +import Quickshell +import Quickshell.Wayland +import qs.compat.omarchy.Commons +import qs.compat.omarchy.Ui +// Centered speed test overlay shared by the network and disk speed tests. No +// card: like the Tucson's floating cluster, the two dials sit directly on a +// darkened scrim -- open 270° arcs, faint tick rings, hubless gradient +// needles, and a digital readout in the middle. Esc, the scrim, or the corner +// dismiss close it; the needles sweep to full scale and back on open, then +// track the live readings. Callers name the dials, the unit, and the scale. +PanelWindow { + id: root + + required property string fontFamily + required property bool running + required property string leftLabel + required property string rightLabel + property string unit: "Mbps" + property string title: "" + property string layerNamespace: "omarchy-speed-test" + property string runAgainTooltip: "Measure again" + property real leftValue: 0 + property real rightValue: 0 + property bool leftLive: false + property bool rightLive: false + property string error: "" + property bool open: false + // Full-scale latch points for the dials, smallest first. The first stop is + // the base scale a fresh run starts from. + property var scaleStops: [100, 250, 500, 1000, 2500, 5000, 10000] + property real fullScale: scaleStops[0] + + signal closeRequested() + signal runAgainRequested() + + readonly property bool failed: error !== "" + + function resetScale() { + fullScale = scaleStops[0] + } + + function expandScale(value) { + // Either reading ranges the entire cluster upward. Keeping this latch on + // the overlay ensures both dials always describe the same scale. + for (var i = 0; i < scaleStops.length; i++) { + if (value <= scaleStops[i] * 0.92) { + if (scaleStops[i] > fullScale) fullScale = scaleStops[i] + return + } + } + fullScale = scaleStops[scaleStops.length - 1] + } + + onRunningChanged: if (running) resetScale() + onScaleStopsChanged: resetScale() + onLeftValueChanged: expandScale(leftValue) + onRightValueChanged: expandScale(rightValue) + + Behavior on fullScale { + NumberAnimation { duration: Style.duration(400); easing.type: Easing.OutCubic } + } + + // The scrim below is a fixed near-black regardless of theme, so text and + // ticks on it need a fixed light palette, not the themed bar.foreground. + readonly property color onScrim: "white" + readonly property color onScrimDim: Qt.rgba(1, 1, 1, 0.55) + readonly property color onScrimUrgent: "#ff6b6b" + + visible: open + // The window is instantiated hidden, so re-acquire focus after mapping and + // fire the ignition sweep once the surface is actually on screen. + onOpenChanged: { + if (open) Qt.callLater(function() { + if (!root.open) return + keyCatcher.forceActiveFocus() + leftDial.ignite() + rightDial.ignite() + }) + } + anchors { top: true; bottom: true; left: true; right: true } + color: "transparent" + exclusionMode: ExclusionMode.Ignore + WlrLayershell.namespace: root.layerNamespace + WlrLayershell.layer: WlrLayer.Overlay + WlrLayershell.keyboardFocus: WlrKeyboardFocus.Exclusive + + // Deep scrim: with no card behind them, the floating dials need the + // backdrop to carry the contrast on any wallpaper, like the near-black + // panel behind a real cluster. + Rectangle { + anchors.fill: parent + color: Qt.rgba(0, 0, 0, 0.78) + + MouseArea { + anchors.fill: parent + onClicked: root.closeRequested() + } + } + + Item { + id: keyCatcher + anchors.fill: parent + focus: true + + Keys.onEscapePressed: root.closeRequested() + Keys.onReturnPressed: if (!root.running) root.runAgainRequested() + Keys.onEnterPressed: if (!root.running) root.runAgainRequested() + + Item { + id: cluster + anchors.centerIn: parent + width: content.implicitWidth + height: content.implicitHeight + // Narrow or heavily scaled outputs: shrink the whole cluster rather + // than clipping it at the screen edge. + scale: Math.min(1, + (keyCatcher.width - Style.space(32)) / Math.max(1, width), + (keyCatcher.height - Style.space(32)) / Math.max(1, height)) + + // Swallow clicks so only the scrim outside the cluster dismisses. + MouseArea { anchors.fill: parent; onClicked: {} } + + ColumnLayout { + id: content + anchors.fill: parent + spacing: Style.space(16) + + Text { + textFormat: Text.PlainText + visible: root.title !== "" + text: root.title.toUpperCase() + color: root.onScrimDim + font.family: root.fontFamily + font.pixelSize: Style.font.caption + font.bold: true + font.letterSpacing: 2 + Layout.fillWidth: true + horizontalAlignment: Text.AlignHCenter + } + + Row { + spacing: Style.space(48) + Layout.alignment: Qt.AlignHCenter + + SpeedDial { + id: leftDial + label: root.leftLabel + value: root.leftValue + live: root.leftLive + } + + SpeedDial { + id: rightDial + label: root.rightLabel + value: root.rightValue + live: root.rightLive + } + } + + // Centered on the dial pair. Fades rather than unmounts while a run + // is in flight, so the cluster never shifts. + Button { + text: "Run Again" + tooltipText: root.runAgainTooltip + bordered: true + enabled: !root.running + opacity: root.running ? 0 : 1 + foreground: root.onScrim + fontFamily: root.fontFamily + fontSize: Style.font.bodySmall + horizontalPadding: Style.space(14) + verticalPadding: Style.space(4) + Layout.alignment: Qt.AlignHCenter + onClicked: root.runAgainRequested() + + Behavior on opacity { + NumberAnimation { duration: Style.duration(240); easing.type: Easing.OutCubic } + } + } + + Text { + textFormat: Text.PlainText + visible: root.failed + text: root.error + color: root.onScrimUrgent + font.family: root.fontFamily + font.pixelSize: Style.font.bodySmall + wrapMode: Text.Wrap + Layout.fillWidth: true + Layout.maximumWidth: Style.space(440) + horizontalAlignment: Text.AlignHCenter + } + } + } + } + + // One floating cluster dial: an open 270° scale with the gap at the + // bottom, a faint tick ring, a glowing accent value arc, a hubless needle + // that fades toward the pivot, and a digital readout in the middle. All + // writes to the needle funnel through `shown` so the ignition sweep and + // live readings share one animation. + component SpeedDial: Item { + id: dial + + required property string label + required property real value + required property bool live + + readonly property real diameter: Style.space(210) + // 0° = 3 o'clock, increasing clockwise (PathAngleArc's convention). + readonly property real dialStart: 135 + readonly property real dialSweep: 270 + readonly property int tickCount: 46 + readonly property real arcWidth: Style.space(4) + readonly property real arcRadius: diameter / 2 - arcWidth + readonly property color trackColor: Qt.rgba(1, 1, 1, 0.14) + readonly property color minorTickColor: Qt.rgba(1, 1, 1, 0.12) + readonly property color majorTickColor: Qt.rgba(1, 1, 1, 0.3) + // The dial that isn't measuring yet sits dimmed until it gets a figure. + readonly property bool engaged: live || value > 0 + + property real shown: 0 + // The digital readout stays on the real figure while the ignition sweep + // drives the needle -- a cluster sweeps its gauges, not its numerals. + readonly property real reading: ignition.running ? value : shown + readonly property real fullScale: root.fullScale + readonly property real fraction: fullScale > 0 ? Math.max(0, Math.min(1, shown / fullScale)) : 0 + readonly property bool arcVisible: fraction > 0.004 + + width: diameter + height: diameter + opacity: engaged ? 1 : 0.5 + + Behavior on opacity { + NumberAnimation { duration: Style.duration(240); easing.type: Easing.OutCubic } + } + + // Live readings land once a second; glide between them rather than snap. + Behavior on shown { + enabled: !ignition.running + NumberAnimation { duration: Style.duration(600); easing.type: Easing.OutCubic } + } + + onValueChanged: { + if (!ignition.running) shown = value + } + + function ignite() { + ignition.restart() + } + + // Car-cluster power-on: needle sweeps to full scale and falls back before + // the live figures take over. + SequentialAnimation { + id: ignition + NumberAnimation { target: dial; property: "shown"; to: dial.fullScale; duration: Style.duration(550); easing.type: Easing.InOutCubic } + NumberAnimation { target: dial; property: "shown"; to: 0; duration: Style.duration(650); easing.type: Easing.OutCubic } + onFinished: dial.shown = dial.value + } + + Shape { + anchors.fill: parent + preferredRendererType: Shape.CurveRenderer + + // Track: the full scale, always visible, dim. + ShapePath { + strokeWidth: dial.arcWidth + strokeColor: dial.trackColor + fillColor: "transparent" + capStyle: ShapePath.RoundCap + + PathAngleArc { + centerX: dial.width / 2 + centerY: dial.height / 2 + radiusX: dial.arcRadius + radiusY: dial.arcRadius + startAngle: dial.dialStart + sweepAngle: dial.dialSweep + } + } + + // Soft under-glow beneath the value arc, standing in for the backlit + // ring of a real cluster. Both arcs go transparent at rest, or their + // round caps would leave a stray dot at the foot of the scale. + ShapePath { + strokeWidth: dial.arcWidth * 3 + strokeColor: dial.arcVisible ? Qt.rgba(Color.accent.r, Color.accent.g, Color.accent.b, 0.18) : "transparent" + fillColor: "transparent" + capStyle: ShapePath.RoundCap + + PathAngleArc { + centerX: dial.width / 2 + centerY: dial.height / 2 + radiusX: dial.arcRadius + radiusY: dial.arcRadius + startAngle: dial.dialStart + sweepAngle: dial.dialSweep * dial.fraction + } + } + + // Value: fills behind the needle. + ShapePath { + strokeWidth: dial.arcWidth + strokeColor: dial.arcVisible ? Color.accent : "transparent" + fillColor: "transparent" + capStyle: ShapePath.RoundCap + + PathAngleArc { + centerX: dial.width / 2 + centerY: dial.height / 2 + radiusX: dial.arcRadius + radiusY: dial.arcRadius + startAngle: dial.dialStart + sweepAngle: dial.dialSweep * dial.fraction + } + } + } + + // Faint tick ring just inside the arc; every fifth tick is a major. + Repeater { + model: dial.tickCount + + Item { + required property int index + readonly property bool major: index % 5 === 0 + + anchors.fill: parent + rotation: dial.dialStart + (index / (dial.tickCount - 1)) * dial.dialSweep - 270 + + Rectangle { + anchors.horizontalCenter: parent.horizontalCenter + y: dial.arcWidth * 2 + (parent.major ? 0 : Style.space(2)) + width: parent.major ? Math.max(2, Style.space(2)) : 1 + height: parent.major ? Style.space(10) : Style.space(6) + radius: width / 2 + color: parent.major ? dial.majorTickColor : dial.minorTickColor + } + } + } + + // Hubless needle: a slender sliver that fades out toward the pivot, so + // it reads as floating like the rest of the cluster. + Item { + anchors.fill: parent + rotation: dial.dialStart + dial.fraction * dial.dialSweep - 270 + + Rectangle { + anchors.horizontalCenter: parent.horizontalCenter + y: dial.arcWidth * 2 + Style.space(10) + width: Math.max(2, Style.space(3)) + height: dial.diameter * 0.32 + radius: width / 2 + + gradient: Gradient { + GradientStop { position: 0.0; color: Color.accent } + GradientStop { position: 0.55; color: Color.accent } + GradientStop { position: 1.0; color: "transparent" } + } + } + } + + Column { + anchors.horizontalCenter: parent.horizontalCenter + anchors.top: parent.verticalCenter + anchors.topMargin: Style.space(14) + spacing: 0 + + Text { + textFormat: Text.PlainText + anchors.horizontalCenter: parent.horizontalCenter + // Both branches go through the locale: a reading is a measurement, so + // its separators follow the system's number conventions rather than the + // interface language. toFixed would have hardcoded a dot below 10 while + // everything above it was already grouped for the locale. + text: dial.reading < 10 + ? dial.reading.toLocaleString(Qt.locale(), 'f', 1) + : Math.round(dial.reading).toLocaleString(Qt.locale(), 'f', 0) + color: root.onScrim + font.family: root.fontFamily + font.pixelSize: Style.font.display + font.bold: true + } + + Text { + textFormat: Text.PlainText + anchors.horizontalCenter: parent.horizontalCenter + text: root.unit + color: root.onScrimDim + font.family: root.fontFamily + font.pixelSize: Style.font.caption + } + } + + // The 90° gap at the bottom of the scale is where a cluster prints its + // unit; here it names the direction. + Text { + textFormat: Text.PlainText + anchors.horizontalCenter: parent.horizontalCenter + anchors.bottom: parent.bottom + text: dial.label + color: root.onScrimDim + font.family: root.fontFamily + font.pixelSize: Style.font.caption + font.bold: true + font.letterSpacing: 1.5 + } + } +} diff --git a/quickshell/compat/omarchy/Ui/TextField.qml b/quickshell/compat/omarchy/Ui/TextField.qml new file mode 100644 index 0000000..3be6b11 --- /dev/null +++ b/quickshell/compat/omarchy/Ui/TextField.qml @@ -0,0 +1,56 @@ +import QtQuick +import QtQuick.Controls +import qs.compat.omarchy.Commons +// Single-line text input with the kit's focus + selection styling. Inherits +// from Qt Quick Controls TextField so the underlying type's API (text, +// placeholderText, accepted, editingFinished, validator, ...) is available +// to callers without re-exposing each property. +// +// Defaults bind to qs.Commons.Color so a caller with no theme overrides +// just works; foreground / accent / selectionTint can be overridden per +// instance. activeFocus and mouse hover / panel cursor use the same +// hover-cursor defaults, so text inputs match Button, Toggle, and Dropdown. +// +// Sizing is driven by font.pixelSize + verticalPadding. The default 30px +// implicitHeight fits dialog forms; inline callers (wifi's row-embedded +// passphrase prompt) drop verticalPadding to match a 22-26px row. +TextField { + id: root + + property color foreground: Color.foreground + property color accent: Color.accent + property color selectionTint: Style.selectionFillFor(foreground, accent) + property bool password: false + property real horizontalPadding: Style.spacing.controlPaddingX + property real verticalPadding: Style.spacing.inputPaddingY + + // Panel-cursor flag. When true (and the field isn't already focused), + // the background paints the shared hover/cursor state. + // For mouse-enter/leave the consumer reads QQC TextField's inherited + // `hovered` property (via onHoveredChanged) — we don't add a sibling + // signal because the inherited property would shadow it. + property bool hasCursor: false + + readonly property bool _focused: activeFocus + readonly property bool _hot: hovered || hasCursor + readonly property var _borderSpec: Border.controlSpec(_focused ? "focus" : (_hot ? "hover-cursor" : "normal"), root.foreground, root.accent) + + echoMode: password ? TextInput.Password : TextInput.Normal + font.family: Style.font.family + font.pixelSize: Style.font.body + color: foreground + selectionColor: selectionTint + selectedTextColor: foreground + placeholderTextColor: Qt.darker(foreground, 1.6) + + leftPadding: horizontalPadding + Border.left(_borderSpec) + rightPadding: horizontalPadding + Border.right(_borderSpec) + topPadding: verticalPadding + Border.top(_borderSpec) + bottomPadding: verticalPadding + Border.bottom(_borderSpec) + + background: BorderSurface { + color: Style.controlFill(root._focused, root._hot, root.foreground, root.accent) + borderSpec: root._borderSpec + radius: Style.cornerRadius + } +} diff --git a/quickshell/compat/omarchy/Ui/Toggle.qml b/quickshell/compat/omarchy/Ui/Toggle.qml new file mode 100644 index 0000000..781244f --- /dev/null +++ b/quickshell/compat/omarchy/Ui/Toggle.qml @@ -0,0 +1,116 @@ +import QtQuick +import qs.compat.omarchy.Commons +// Labeled toggle row: title + optional description on the left, a +// `ToggleSwitch` on the right. Clicking anywhere on the row emits `clicked()`; +// consumers flip `checked` in response (the component is stateless about the +// actual value so it composes cleanly with model-driven UI). +// +// Cursor and focus styling match the rest of the kit: hasCursor / mouse +// hover and activeFocus share the hover-cursor defaults. +// +// `rounded` is forwarded to the switch, which auto-detects from +// Style.cornerRadius: pill shape when Hyprland corners are rounded, square on +// sharp. Callers can override per-instance. +BorderSurface { + id: root + + property string label: "" + property string description: "" + property bool checked: false + + // Panel-cursor flag. Same role as Button.hasCursor: + // panels with their own keyboard cursor bind this to drive the highlight + // separately from activeFocus. Visuals use the same hover-cursor tokens. + property bool hasCursor: false + + // Switch shape follows the theme by default: pill on round, square on sharp. + // Override per-instance if a caller wants the opposite. + property bool rounded: Style.cornerRadius > 0 + + property color foreground: Color.foreground + property color accent: Color.accent + property string fontFamily: Style.font.family + property real titleSize: Style.font.subtitle + property real descriptionSize: Style.font.caption + + signal clicked() + signal hovered(bool isHovered) + + activeFocusOnTab: true + Keys.onReturnPressed: root.clicked() + Keys.onEnterPressed: root.clicked() + Keys.onSpacePressed: root.clicked() + + implicitHeight: Math.max(54, content.implicitHeight + Style.spacing.huge) + implicitWidth: Style.space(240) + radius: Style.cornerRadius + + readonly property bool _hot: hasCursor || mouse.containsMouse + readonly property var _borderSpec: Border.controlSpec(activeFocus ? "focus" : (_hot ? "hover-cursor" : "normal"), foreground, accent) + + color: Style.controlFill(activeFocus, _hot, foreground, accent) + borderSpec: _borderSpec + + Behavior on color { ColorAnimation { duration: Style.duration(100) } } + + Row { + id: content + anchors.left: parent.left + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + anchors.leftMargin: root.borderLeft + Style.spacing.rowPaddingX + anchors.rightMargin: root.borderRight + Style.spacing.rowPaddingX + spacing: Style.spacing.rowPaddingX + + Column { + width: parent.width - track.width - parent.spacing + spacing: Style.spacing.xs + anchors.verticalCenter: parent.verticalCenter + + Text { + textFormat: Text.PlainText + text: root.label + color: root.foreground + font.family: root.fontFamily + font.pixelSize: root.titleSize + font.bold: true + elide: Text.ElideRight + width: parent.width + } + + Text { + textFormat: Text.PlainText + visible: root.description !== "" + text: root.description + color: Qt.darker(root.foreground, 1.5) + font.family: root.fontFamily + font.pixelSize: root.descriptionSize + wrapMode: Text.WordWrap + width: parent.width + } + } + + // The row owns the click, so the switch is presentation only here. + ToggleSwitch { + id: track + checked: root.checked + rounded: root.rounded + foreground: root.foreground + accent: root.accent + interactive: false + anchors.verticalCenter: parent.verticalCenter + } + } + + MouseArea { + id: mouse + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: root.clicked() + } + + HoverHandler { + onHoveredChanged: root.hovered(hovered) + } +} diff --git a/quickshell/compat/omarchy/Ui/ToggleSwitch.qml b/quickshell/compat/omarchy/Ui/ToggleSwitch.qml new file mode 100644 index 0000000..5d4ece2 --- /dev/null +++ b/quickshell/compat/omarchy/Ui/ToggleSwitch.qml @@ -0,0 +1,110 @@ +import QtQuick +import qs.compat.omarchy.Commons +import "../../../theme" as G +// Bare on/off switch: a track with a sliding knob and no label. This is the +// switch `Toggle` parks at the end of its labeled row, factored out so panel +// headers and other compact controls render the identical thing. +// +// The caller owns the value: bind `checked` to real state and flip it in +// response to `toggled()`. Services that already track a desired state +// optimistically (see the Tailscale service's `_desired`) get an instant knob +// throw for free, because `checked` is already the optimistic value. +// +// `busy` marks an operation in flight and swallows further clicks, but leaves +// hover, cursor, and tooltips alone so the control does not flicker every time +// a background refresh runs. +// +// The cursor is a ring drawn outside the track rather than a state on the +// track itself: themes give normal chrome a stronger border than hover-cursor +// (0.4 vs 0.25 by default), which is right for controls that are borderless at +// rest but would make a bordered track go *fainter* under the cursor. On the +// panel background the ring reads immediately. `cursorRing` follows +// `interactive` — a switch whose surrounding row owns the click owns the +// cursor too. +// +// `rounded` auto-detects from Style.cornerRadius so the switch follows the +// theme: pill shape when Hyprland corners are rounded, square on sharp. +Item { + id: root + + property bool checked: false + property bool busy: false + + // Off when the surrounding row owns the click, as in `Toggle`. + property bool interactive: true + + // Panel-cursor flag. Same role as Button.hasCursor: panels with their own + // keyboard cursor bind this to drive the highlight separately from hover. + property bool hasCursor: false + + property bool cursorRing: interactive + property int cursorPad: Style.space(6) + property bool rounded: Style.cornerRadius > 0 + property color foreground: Color.foreground + property color accent: Color.accent + + signal toggled() + signal hovered(bool isHovered) + + readonly property alias containsMouse: mouse.containsMouse + readonly property bool hot: hasCursor || mouse.containsMouse + + // `trackHeight` is settable so a compact placement — a switch riding a panel + // section header, say — can ask for a genuinely smaller control instead of + // scaling a big one down, which lands the track and knob on fractional pixels + // and blurs their edges. The derived sizes only carry floors low enough to + // stay out of an override's way; at the default track height each one is + // already above its floor, so nothing about the normal switch changes. + property int trackHeight: Math.max(22, Math.round(Style.spacing.controlHeight * 0.55)) + property int trackWidth: Math.round(trackHeight * 1.9) + property int knobSize: Math.max(6, Math.round(trackHeight * 0.72)) + property int knobInset: Math.max(1, Math.round((trackHeight - knobSize) / 2)) + + readonly property int _pad: cursorRing ? cursorPad : 0 + + implicitWidth: trackWidth + _pad * 2 + implicitHeight: trackHeight + _pad * 2 + + BorderSurface { + anchors.fill: parent + visible: root.cursorRing && root.hot + color: "transparent" + radius: Style.cornerRadius + borderSpec: Border.controlSpec("hover-cursor", root.foreground, root.accent) + } + + BorderSurface { + id: track + width: root.trackWidth + height: root.trackHeight + anchors.centerIn: parent + // glassMxrph switch: solid accent when on, tinted glass when off. + radius: height / 2 + color: root.checked ? G.Theme.accent : G.Theme.surfaceVariant + borderSpec: root.checked ? Border.none() : Border.controlSpec("normal", root.foreground, root.accent) + + Behavior on color { ColorAnimation { duration: Style.duration(120) } } + + Rectangle { + width: root.knobSize + height: root.knobSize + radius: height / 2 + x: root.checked ? track.width - width - root.knobInset : root.knobInset + anchors.verticalCenter: parent.verticalCenter + color: root.checked ? G.Theme.accentText : G.Theme.text + + Behavior on x { NumberAnimation { duration: Style.duration(120); easing.type: Easing.OutCubic } } + Behavior on color { ColorAnimation { duration: Style.duration(120) } } + } + } + + MouseArea { + id: mouse + anchors.fill: parent + enabled: root.interactive + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onContainsMouseChanged: root.hovered(containsMouse) + onClicked: if (!root.busy) root.toggled() + } +} diff --git a/quickshell/compat/omarchy/Ui/WidgetButton.qml b/quickshell/compat/omarchy/Ui/WidgetButton.qml new file mode 100644 index 0000000..d036aba --- /dev/null +++ b/quickshell/compat/omarchy/Ui/WidgetButton.qml @@ -0,0 +1,143 @@ +import QtQuick +import qs.compat.omarchy.Commons +import "../../../theme" as G +Item { + id: root + + property var bar: null + property string text: "" + property string fontFamily: bar ? bar.fontFamily : Style.font.family + property real fontSize: Style.font.body + property color foreground: bar ? bar.barForeground : Color.foreground + property color activeColor: bar ? bar.urgent : Color.urgent + property bool active: false + property real horizontalMargin: 8.5 + property real verticalPadding: 6 + property real fixedWidth: -1 + property real fixedHeight: -1 + property real textRotation: 0 + property bool keepSpace: false + property bool dimmed: false + property bool concealed: false + property bool interactive: true + property bool pressable: true + property bool useActiveColor: true + property bool maintainIndicatorReveal: false + property bool labelVisible: true + // Off for icon-font labels, whose figure metrics say nothing about the glyph. + property bool centerFigures: true + property bool hasVisualContent: text !== "" + property var revealHost: bar + property string tooltipText: "" + property var registeredBar: null + + signal pressed(int button) + signal wheelMoved(int delta) + + function triggerPress(button) { + if (root.bar) root.bar.hideTooltip(root) + root.pressed(button) + } + + function hideOwnTooltip() { + if (root.bar) root.bar.hideTooltip(root) + } + + function syncClickRegistration() { + if (registeredBar && registeredBar.unregisterClickTarget) registeredBar.unregisterClickTarget(root) + registeredBar = root.bar + if (registeredBar && registeredBar.registerClickTarget) registeredBar.registerClickTarget(root) + } + + onBarChanged: syncClickRegistration() + onVisibleChanged: if (!visible) hideOwnTooltip() + onInteractiveChanged: if (!interactive) hideOwnTooltip() + onConcealedChanged: if (concealed) hideOwnTooltip() + Component.onCompleted: syncClickRegistration() + Component.onDestruction: if (registeredBar && registeredBar.unregisterClickTarget) registeredBar.unregisterClickTarget(root) + + readonly property bool vertical: bar ? bar.vertical : false + readonly property int barSize: bar ? bar.barSize : Style.bar.sizeHorizontal + readonly property real scaledHorizontalMargin: Style.spaceReal(horizontalMargin) + readonly property real scaledVerticalPadding: Style.spaceReal(verticalPadding) + readonly property bool tooltipHovered: visible && interactive && !concealed && mouseArea.containsMouse + // Width of the painted label, for bar chrome that wants to line up with the + // text rather than with the slot it sits in. Zero on icon-only buttons. + readonly property real labelWidth: label.visible ? label.implicitWidth : 0 + + visible: hasVisualContent || keepSpace + opacity: !hasVisualContent || concealed ? 0 : (dimmed ? 0.45 : 1) + implicitWidth: fixedWidth > 0 ? fixedWidth : (vertical ? barSize : Math.max(12, label.implicitWidth + scaledHorizontalMargin * 2)) + implicitHeight: fixedHeight > 0 ? fixedHeight : (vertical ? Math.max(12, label.implicitHeight + scaledVerticalPadding * 2) : barSize) + + Behavior on opacity { + NumberAnimation { duration: Style.duration(140); easing.type: Easing.OutCubic } + } + + // glassMxrph: the same rounded hover highlight as the tray and window pills. + Rectangle { + anchors.fill: parent + anchors.margins: 2 + radius: height / 2 + visible: root.interactive && root.pressable + color: mouseArea.pressed ? Qt.alpha(G.Theme.text, 0.16) : mouseArea.containsMouse ? G.Theme.hover : "transparent" + Behavior on color { + ColorAnimation { duration: Style.duration(G.Theme.duration) } + } + } + + Text { + id: label + textFormat: Text.PlainText + visible: root.labelVisible + anchors.centerIn: parent + // Centering the line box puts the figures above the bar's middle, since + // the box keeps room for descenders. Center the figure height instead, so + // labels line up with the icons beside them. + anchors.verticalCenterOffset: !root.centerFigures || root.vertical || root.text.indexOf("\n") !== -1 + ? 0 + : (labelMetrics.descent - labelMetrics.ascent + labelMetrics.tightBoundingRect("0").height) / 2 + text: root.text + color: root.active && root.useActiveColor ? root.activeColor : root.foreground + font.family: root.fontFamily + font.pixelSize: root.fontSize + rotation: root.textRotation + horizontalAlignment: Text.AlignHCenter + verticalAlignment: Text.AlignVCenter + + Behavior on color { + enabled: !root.bar || root.bar.foregroundAnimationEnabled + ColorAnimation { duration: Style.duration(160) } + } + } + + FontMetrics { + id: labelMetrics + font: label.font + } + + MouseArea { + id: mouseArea + anchors.fill: parent + acceptedButtons: Qt.LeftButton | Qt.RightButton | Qt.MiddleButton + enabled: root.interactive + hoverEnabled: true + cursorShape: root.pressable ? Qt.PointingHandCursor : Qt.ArrowCursor + onEntered: { + if (root.bar) { + root.bar.showTooltip(root, root.tooltipText) + } + if (root.maintainIndicatorReveal && root.revealHost && root.revealHost.setIndicatorItemHovered) + root.revealHost.setIndicatorItemHovered(true) + } + onExited: { + if (root.bar) { + root.bar.hideTooltip(root) + } + if (root.maintainIndicatorReveal && root.revealHost && root.revealHost.setIndicatorItemHovered) + root.revealHost.setIndicatorItemHovered(false) + } + onClicked: function(mouse) { if (root.pressable) root.triggerPress(mouse.button) } + onWheel: function(wheel) { root.wheelMoved(wheel.angleDelta.y) } + } +} diff --git a/quickshell/compat/omarchy/Ui/qmldir b/quickshell/compat/omarchy/Ui/qmldir new file mode 100644 index 0000000..c6871ec --- /dev/null +++ b/quickshell/compat/omarchy/Ui/qmldir @@ -0,0 +1,36 @@ +BarIndicator 1.0 BarIndicator.qml +BarIconButton 1.0 BarIconButton.qml +BarWidget 1.0 BarWidget.qml +BackgroundMedia 1.0 BackgroundMedia.qml +BorderOverlay 1.0 BorderOverlay.qml +BorderSurface 1.0 BorderSurface.qml +Button 1.0 Button.qml +ButtonGroup 1.0 ButtonGroup.qml +ConfirmDialog 1.0 ConfirmDialog.qml +CursorSurface 1.0 CursorSurface.qml +Dropdown 1.0 Dropdown.qml +KeyboardPanel 1.0 KeyboardPanel.qml +MultiSelect 1.0 MultiSelect.qml +NumberField 1.0 NumberField.qml +OpticalGlyph 1.0 OpticalGlyph.qml +OverlayWindow 1.0 OverlayWindow.qml +Panel 1.0 Panel.qml +PanelActionButton 1.0 PanelActionButton.qml +PanelController 1.0 PanelController.qml +PanelKeyCatcher 1.0 PanelKeyCatcher.qml +PanelHero 1.0 PanelHero.qml +PanelSectionHeader 1.0 PanelSectionHeader.qml +PanelSeparator 1.0 PanelSeparator.qml +PanelSlider 1.0 PanelSlider.qml +PanelToolTip 1.0 PanelToolTip.qml +PluginBarApi 1.0 PluginBarApi.qml +PointerMoveGate 1.0 PointerMoveGate.qml +ScreenMoveRemap 1.0 ScreenMoveRemap.qml +PopupCard 1.0 PopupCard.qml +SearchableDropdown 1.0 SearchableDropdown.qml +SpeedTestOverlay 1.0 SpeedTestOverlay.qml +TextField 1.0 TextField.qml +Toggle 1.0 Toggle.qml +ToggleSwitch 1.0 ToggleSwitch.qml +WidgetButton 1.0 WidgetButton.qml +GlassPopupBase 1.0 GlassPopupBase.qml diff --git a/quickshell/compat/omarchy/bin/omarchy-powerprofiles-list b/quickshell/compat/omarchy/bin/omarchy-powerprofiles-list new file mode 100755 index 0000000..042580d --- /dev/null +++ b/quickshell/compat/omarchy/bin/omarchy-powerprofiles-list @@ -0,0 +1,17 @@ +#!/usr/bin/env bash + +# omarchy:summary=Returns a list of all the available power profiles on the system. +# omarchy:args=[--active-state] + +if [[ ${1:-} != "" && ${1:-} != "--active-state" ]]; then + echo "Usage: omarchy-powerprofiles-list [--active-state]" >&2 + exit 1 +fi + +powerprofilesctl list 2>/dev/null | + awk -v with_state="${1:+1}" '/^\s*[* ]\s*[a-zA-Z0-9-]+:$/ { + active = ($1 == "*") ? 1 : 0 + gsub(/^[*[:space:]]+|:$/, "") + print $0 (with_state ? "\t" active : "") + }' | + tac diff --git a/quickshell/components/BarDrawer.qml b/quickshell/components/BarDrawer.qml new file mode 100644 index 0000000..285052e --- /dev/null +++ b/quickshell/components/BarDrawer.qml @@ -0,0 +1,111 @@ +import QtQuick +import "../core" +import "../theme" + +// A popup that grows out of the bar (Caelestia-style drawer). Place it at +// y = BarDrawers.bottom in a window whose top is the screen's top edge: the +// layer box then starts above the bar, so the join is not a glass edge. +// Content slides down with the body as it is revealed. +Item { + id: root + default property alias content: inner.data + property bool open: false + property bool attached: true + property real contentWidth: 300 + property real contentHeight: 200 + // Registered with the bar so it opens its border over this span. + property string drawerId: "" + property string screenName: "" + property real screenX: 0 + readonly property real ear: attached ? BarDrawers.ear : 0 + // "slide" unrolls out of the bar; "drop" falls into place and away + // downwards; "fade" fades in place; "shrink" grows from / shrinks to nothing. + property string style: "slide" + readonly property bool unrolls: style === "slide" + property real progress: open ? 1 : 0 + readonly property real revealed: unrolls ? Math.max(0, contentHeight * progress) : contentHeight + // Drop moves down on the way in and on the way out. + property real dropFrom: -1 + onOpenChanged: dropFrom = open ? -1 : 1 + readonly property bool shown: progress > 0.001 + readonly property bool settled: !anim.running && open + // Input/hover region: the full body as soon as it opens (the pointer may + // reach the drawer before the reveal finishes), the visible part while closing. + readonly property alias body: area + readonly property bool hovered: hover.hovered + // Content parent, for items reparented in at runtime. + readonly property alias container: inner + // Enter: emphasized decelerate; exit: emphasized accelerate (Material 3). + Behavior on progress { + NumberAnimation { + id: anim + duration: root.open ? Theme.duration * 1.8 : Theme.duration + easing.type: Easing.BezierSpline + easing.bezierCurve: root.open ? [0.05, 0.7, 0.1, 1, 1, 1] : [0.3, 0, 0.8, 0.15, 1, 1] + } + } + implicitWidth: contentWidth + 2 * ear + implicitHeight: contentHeight + width: implicitWidth + height: implicitHeight + + // Input/hover region stays put; only the drawn drawer animates. + Item { + id: area + x: root.ear + width: root.contentWidth + height: root.open ? root.contentHeight : root.revealed + } + // On the root so it wraps the content: a sibling under the content would + // lose hover to the content's own hover areas. + HoverHandler { + id: hover + } + Item { + id: motion + width: root.width + height: root.height + opacity: root.style === "fade" || root.style === "drop" ? root.progress : root.style === "shrink" ? Math.min(1, root.progress * 1.5) : 1 + scale: root.style === "shrink" ? Math.max(0.001, root.progress) : 1 + transformOrigin: Item.Center + transform: Translate { + y: root.style === "drop" ? (1 - root.progress) * 28 * root.dropFrom * Math.max(0.3, Theme.intensity) : 0 + } + DrawerShape { + id: shape + bodyWidth: root.contentWidth + bodyHeight: root.revealed + ear: BarDrawers.ear + attached: root.attached + } + Item { + id: hit + x: root.ear + width: root.contentWidth + height: root.revealed + clip: true + Item { + id: inner + width: root.contentWidth + height: root.contentHeight + y: root.revealed - root.contentHeight + opacity: root.unrolls ? Math.min(1, root.progress * 1.6) : 1 + } + } + } + + readonly property bool joined: attached && (unrolls ? shown : progress > 0.5) + readonly property var gapKey: [joined, screenName, Math.round(screenX), Math.round(width)] + onGapKeyChanged: syncGap() + Component.onCompleted: syncGap() + Component.onDestruction: if (drawerId) + BarDrawers.clearGap(drawerId) + function syncGap() { + if (!drawerId) + return; + if (joined && screenName) + BarDrawers.setGap(drawerId, screenName, screenX, screenX + width); + else + BarDrawers.clearGap(drawerId); + } +} diff --git a/quickshell/components/DrawerShape.qml b/quickshell/components/DrawerShape.qml new file mode 100644 index 0000000..c86e377 --- /dev/null +++ b/quickshell/components/DrawerShape.qml @@ -0,0 +1,60 @@ +import QtQuick +import QtQuick.Shapes +import "../theme" + +// Drawer body hanging from the bar: concave "ears" blend it into the bar's +// bottom edge and its top side has no border, so bar and drawer read as one +// shape. `bodyHeight` is the revealed height; detached drawers are plain cards. +Item { + id: root + property real bodyWidth: 300 + property real bodyHeight: 200 + property real ear: 16 + property real radius: Theme.radius + property bool attached: true + property color fillColor: Qt.alpha(Theme.surface, Theme.glassOpacity) + property color borderColor: Theme.border + implicitWidth: bodyWidth + (attached ? 2 * ear : 0) + implicitHeight: bodyHeight + readonly property real w: implicitWidth + readonly property real h: Math.max(0, bodyHeight) + // Ears and corners shrink while the drawer is still short. + readonly property real e: Math.min(ear, h) + readonly property real r: Math.max(0, Math.min(radius, h - e, bodyWidth / 2)) + readonly property string body: { + const W = w, E = ear, h = root.h, e = root.e, r = root.r; + return `L ${W - E} ${h - r} A ${r} ${r} 0 0 1 ${W - E - r} ${h} L ${E + r} ${h} A ${r} ${r} 0 0 1 ${E} ${h - r} L ${E} ${e}`; + } + visible: h > 0.5 + + Shape { + anchors.fill: parent + visible: root.attached + preferredRendererType: Shape.CurveRenderer + ShapePath { + fillColor: root.fillColor + strokeColor: "transparent" + strokeWidth: 0 + PathSvg { + path: `M 0 0 L ${root.w} 0 A ${root.ear} ${root.e} 0 0 0 ${root.w - root.ear} ${root.e} ${root.body} A ${root.ear} ${root.e} 0 0 0 0 0 Z` + } + } + // Outline everywhere except along the bar. + ShapePath { + fillColor: "transparent" + strokeColor: root.borderColor + strokeWidth: 1 + PathSvg { + path: `M 0 0.5 A ${root.ear} ${root.e} 0 0 1 ${root.ear} ${root.e} L ${root.ear} ${root.h - root.r} A ${root.r} ${root.r} 0 0 0 ${root.ear + root.r} ${root.h - 0.5} L ${root.w - root.ear - root.r} ${root.h - 0.5} A ${root.r} ${root.r} 0 0 0 ${root.w - root.ear} ${root.h - root.r} L ${root.w - root.ear} ${root.e} A ${root.ear} ${root.e} 0 0 1 ${root.w} 0.5` + } + } + } + Rectangle { + anchors.fill: parent + visible: !root.attached + radius: Math.min(root.radius, root.h / 2) + color: root.fillColor + border.width: 1 + border.color: root.borderColor + } +} diff --git a/quickshell/components/GlassBarSlider.qml b/quickshell/components/GlassBarSlider.qml new file mode 100644 index 0000000..8575e5d --- /dev/null +++ b/quickshell/components/GlassBarSlider.qml @@ -0,0 +1,62 @@ +import QtQuick +import QtQuick.Controls +import "../theme" + +// Thick pill slider with an icon inside the track (macOS Control Center style). +Slider { + id: root + property string glyph + property string fallback + implicitWidth: 220 + implicitHeight: 28 + padding: 0 + background: Rectangle { + x: root.leftPadding + y: root.topPadding + root.availableHeight / 2 - height / 2 + width: root.availableWidth + height: root.availableHeight + radius: height / 2 + color: Theme.surfaceVariant + border.width: root.activeFocus ? 1 : 0 + border.color: Theme.accent + Rectangle { + readonly property real knob: parent.height + width: Math.max(knob, knob + root.visualPosition * (parent.width - knob)) + height: parent.height + radius: height / 2 + color: root.enabled ? Qt.alpha(Theme.text, 0.92) : Qt.alpha(Theme.text, 0.35) + Behavior on width { + enabled: !root.pressed + NumberAnimation { + duration: Theme.duration / 2 + easing.type: Easing.OutCubic + } + } + } + Text { + anchors.left: parent.left + anchors.leftMargin: (parent.height - width) / 2 + anchors.verticalCenter: parent.verticalCenter + text: Icons.available && root.glyph ? root.glyph : root.fallback + font.family: Icons.available && root.glyph ? Icons.family : "" + font.pixelSize: Math.round(parent.height * 0.5) + color: Theme.surface + } + } + handle: Rectangle { + x: root.leftPadding + root.visualPosition * (root.availableWidth - width) + y: root.topPadding + root.availableHeight / 2 - height / 2 + width: root.availableHeight + height: root.availableHeight + radius: width / 2 + color: root.enabled ? Theme.text : Qt.alpha(Theme.text, 0.5) + border.width: 1 + border.color: Qt.alpha(Theme.surface, 0.5) + scale: root.pressed ? 1.06 : 1 + Behavior on scale { + NumberAnimation { + duration: Theme.duration / 2 + } + } + } +} diff --git a/quickshell/components/GlassButton.qml b/quickshell/components/GlassButton.qml new file mode 100644 index 0000000..e4d9c93 --- /dev/null +++ b/quickshell/components/GlassButton.qml @@ -0,0 +1,47 @@ +import QtQuick +import QtQuick.Controls +import "../theme" + +Button { + id: root + property bool accented: false + implicitWidth: Math.max(40, label.implicitWidth + 28) + implicitHeight: 36 + hoverEnabled: true + transform: Translate { + y: root.hovered && !root.down ? -Theme.intensity : 0 + Behavior on y { + NumberAnimation { + duration: Theme.duration / 2 + easing.type: Easing.OutCubic + } + } + } + scale: down ? 1 - 0.04 * Theme.intensity : 1 + Behavior on scale { + NumberAnimation { + duration: Theme.duration / 2 + easing.type: Easing.OutCubic + } + } + contentItem: Text { + id: label + text: root.text + color: root.accented ? (root.down ? Theme.accentPressedText : root.hovered ? Theme.accentHoverText : Theme.accentText) : Theme.text + font.pixelSize: 13 + horizontalAlignment: Text.AlignHCenter + verticalAlignment: Text.AlignVCenter + } + background: Rectangle { + radius: height / 2 + color: root.accented ? (root.down ? Theme.accentPressed : root.hovered ? Theme.accentHover : Theme.accent) : root.hovered ? Theme.hover : Theme.surfaceVariant + border.width: root.activeFocus ? 2 : 1 + border.color: root.activeFocus ? Theme.accent : Theme.border + Behavior on color { + ColorAnimation { + duration: Theme.duration + } + } + } + opacity: enabled ? 1 : 0.45 +} diff --git a/quickshell/components/GlassColorPicker.qml b/quickshell/components/GlassColorPicker.qml new file mode 100644 index 0000000..3ab2b5e --- /dev/null +++ b/quickshell/components/GlassColorPicker.qml @@ -0,0 +1,133 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import "../theme" + +ColumnLayout { + id: root + property color selectedColor: Theme.accent + property real hue: 0 + property real saturation: 1 + property real brightness: 1 + signal chosen(color color) + function sync() { + if (selectedColor.hsvHue >= 0) + hue = selectedColor.hsvHue; + saturation = selectedColor.hsvSaturation; + brightness = selectedColor.hsvValue; + } + function commit() { + chosen(Qt.hsva(hue, saturation, brightness, 1)); + } + onSelectedColorChanged: sync() + Component.onCompleted: sync() + Rectangle { + id: field + objectName: "colorSaturationValue" + Layout.fillWidth: true + Layout.preferredHeight: 150 + color: Qt.hsva(root.hue, 1, 1, 1) + radius: 8 + clip: true + Rectangle { + anchors.fill: parent + gradient: Gradient { + orientation: Gradient.Horizontal + GradientStop { + position: 0 + color: Qt.rgba(1, 1, 1, 1) + } + GradientStop { + position: 1 + color: Qt.rgba(1, 1, 1, 0) + } + } + } + Rectangle { + anchors.fill: parent + gradient: Gradient { + GradientStop { + position: 0 + color: Qt.rgba(0, 0, 0, 0) + } + GradientStop { + position: 1 + color: Qt.rgba(0, 0, 0, 1) + } + } + } + Rectangle { + x: root.saturation * (parent.width - 12) + y: (1 - root.brightness) * (parent.height - 12) + width: 12 + height: 12 + radius: 6 + color: Theme.transparent + border.width: 2 + border.color: Theme.text + } + MouseArea { + anchors.fill: parent + function pick(x, y) { + root.saturation = Math.max(0, Math.min(1, x / width)); + root.brightness = 1 - Math.max(0, Math.min(1, y / height)); + root.commit(); + } + onPressed: event => pick(event.x, event.y) + onPositionChanged: event => { + if (pressed) + pick(event.x, event.y); + } + } + } + Slider { + id: hueSlider + objectName: "colorHue" + Layout.fillWidth: true + from: 0 + to: 1 + value: root.hue + onMoved: { + root.hue = value; + root.commit(); + } + background: Rectangle { + x: hueSlider.leftPadding + y: hueSlider.topPadding + hueSlider.availableHeight / 2 - height / 2 + width: hueSlider.availableWidth + height: 10 + radius: 5 + gradient: Gradient { + orientation: Gradient.Horizontal + GradientStop { + position: 0 + color: Qt.hsva(0, 1, 1, 1) + } + GradientStop { + position: 0.1667 + color: Qt.hsva(0.1667, 1, 1, 1) + } + GradientStop { + position: 0.3333 + color: Qt.hsva(0.3333, 1, 1, 1) + } + GradientStop { + position: 0.5 + color: Qt.hsva(0.5, 1, 1, 1) + } + GradientStop { + position: 0.6667 + color: Qt.hsva(0.6667, 1, 1, 1) + } + GradientStop { + position: 0.8333 + color: Qt.hsva(0.8333, 1, 1, 1) + } + GradientStop { + position: 1 + color: Qt.hsva(1, 1, 1, 1) + } + } + } + } +} diff --git a/quickshell/components/GlassComboBox.qml b/quickshell/components/GlassComboBox.qml new file mode 100644 index 0000000..56acf5e --- /dev/null +++ b/quickshell/components/GlassComboBox.qml @@ -0,0 +1,66 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Controls +import "../theme" + +ComboBox { + id: root + implicitWidth: 180 + implicitHeight: 38 + leftPadding: 12 + rightPadding: 30 + background: Rectangle { + radius: 10 + color: root.hovered ? Theme.hover : Theme.surfaceVariant + border.color: root.activeFocus ? Theme.accent : Theme.border + } + contentItem: Text { + text: root.displayText + color: Theme.text + verticalAlignment: Text.AlignVCenter + elide: Text.ElideRight + font: root.font + } + indicator: Text { + text: "⌄" + color: Theme.textSecondary + anchors.right: parent.right + anchors.rightMargin: 12 + anchors.verticalCenter: parent.verticalCenter + } + delegate: ItemDelegate { + id: entry + required property var modelData + required property int index + width: root.width - 16 + highlighted: root.highlightedIndex === index + contentItem: Text { + text: root.textRole ? entry.modelData[root.textRole] : entry.modelData + color: Theme.text + elide: Text.ElideRight + font: root.font + } + background: Rectangle { + radius: 8 + color: entry.highlighted ? Qt.alpha(Theme.accent, 0.2) : Theme.transparent + } + } + popup: Popup { + y: root.height + 6 + // Stay inside the window: panel-sized layer surfaces clip anything outside. + margins: 6 + width: root.width + padding: 8 + implicitHeight: Math.min(contentItem.implicitHeight + 16, 300) + contentItem: ListView { + clip: true + implicitHeight: contentHeight + model: root.popup.visible ? root.delegateModel : null + currentIndex: root.highlightedIndex + ScrollIndicator.vertical: ScrollIndicator {} + } + background: GlassPanel { + surfaceOpacity: Math.max(Theme.panelOpacity, 0.85) + } + } +} diff --git a/quickshell/components/GlassIcon.qml b/quickshell/components/GlassIcon.qml new file mode 100644 index 0000000..6062158 --- /dev/null +++ b/quickshell/components/GlassIcon.qml @@ -0,0 +1,46 @@ +import QtQuick +import "../theme" + +// Icon tile: a Nerd Font glyph when one is installed, otherwise the fallback text. +Rectangle { + id: root + property string glyph: "" + property string fallback: "" + // An image (e.g. the project crest) replaces the glyph when set. + property url image: "" + property bool active: false + property int size: 30 + property int glyphSize: Math.round(size * 0.5) + property color glyphColor: active ? Theme.accentText : Theme.text + implicitWidth: size + implicitHeight: size + radius: Math.min(size / 2, Math.max(6, Theme.radius * 0.4)) + color: active ? Theme.accent : Theme.surfaceVariant + border.width: active ? 0 : 1 + border.color: Theme.hairline + Behavior on color { + ColorAnimation { + duration: Theme.duration + } + } + Image { + anchors.fill: parent + anchors.margins: Math.round(root.size * 0.12) + visible: root.image.toString() !== "" + source: root.image + sourceSize: Qt.size(root.size * 2, root.size * 2) + fillMode: Image.PreserveAspectFit + smooth: true + mipmap: true + asynchronous: true + } + Text { + anchors.centerIn: parent + visible: root.image.toString() === "" + text: Icons.available && root.glyph ? root.glyph : root.fallback + font.family: Icons.available && root.glyph ? Icons.family : "" + font.pixelSize: Icons.available && root.glyph ? root.glyphSize : Math.round(root.glyphSize * 0.9) + font.weight: Font.DemiBold + color: root.glyphColor + } +} diff --git a/quickshell/components/GlassIconButton.qml b/quickshell/components/GlassIconButton.qml new file mode 100644 index 0000000..f607785 --- /dev/null +++ b/quickshell/components/GlassIconButton.qml @@ -0,0 +1,2 @@ +import QtQuick +GlassButton { implicitWidth: 36; implicitHeight: 36 } diff --git a/quickshell/components/GlassMenu.qml b/quickshell/components/GlassMenu.qml new file mode 100644 index 0000000..556fd40 --- /dev/null +++ b/quickshell/components/GlassMenu.qml @@ -0,0 +1,7 @@ +import QtQuick +GlassPopup { + default property alias entries: content.data + property alias contentItem: content + implicitWidth: 280 + Item { id: content; anchors.fill: parent; anchors.margins: 8 } +} diff --git a/quickshell/components/GlassMenuItem.qml b/quickshell/components/GlassMenuItem.qml new file mode 100644 index 0000000..acb8538 --- /dev/null +++ b/quickshell/components/GlassMenuItem.qml @@ -0,0 +1,53 @@ +import QtQuick +import Quickshell +import "../theme" +Item { + id: root + property string text: "" + property string iconSource: "" + property bool separator: false + property bool actionEnabled: true + property bool selected: false + property bool submenu: false + property int buttonType: QsMenuButtonType.None + property int checkState: Qt.Unchecked + signal invoked() + signal entered() + implicitWidth: 264 + implicitHeight: separator ? 9 : 34 + Accessible.role: separator ? Accessible.Separator : Accessible.MenuItem + Accessible.name: text + Accessible.checkable: buttonType !== QsMenuButtonType.None + Accessible.checked: checkState === Qt.Checked + Accessible.onPressAction: if (actionEnabled && !separator) invoked() + Rectangle { anchors.verticalCenter: parent.verticalCenter; width: parent.width; height: 1; color: Theme.border; visible: root.separator } + Rectangle { + anchors.fill: parent; radius: 9; visible: !root.separator + color: root.selected && root.actionEnabled ? Qt.alpha(Theme.accent, 0.22) : Theme.transparent + Behavior on color { ColorAnimation { duration: Theme.duration / 2 } } + } + Row { + anchors.verticalCenter: parent.verticalCenter; x: 8; spacing: 8; visible: !root.separator + opacity: root.actionEnabled ? 1 : 0.4 + Item { + width: 18; height: 18 + Rectangle { + anchors.centerIn: parent; width: 14; height: 14 + radius: root.buttonType === QsMenuButtonType.RadioButton ? 7 : 3 + visible: root.buttonType !== QsMenuButtonType.None + color: Theme.transparent; border.width: 1 + border.color: root.checkState === Qt.Unchecked ? Theme.textSecondary : Theme.accent + Rectangle { anchors.centerIn: parent; width: 6; height: 6; radius: 3; color: Theme.accent; visible: root.buttonType === QsMenuButtonType.RadioButton && root.checkState === Qt.Checked } + Text { anchors.centerIn: parent; text: root.checkState === Qt.PartiallyChecked ? "−" : "✓"; font.pixelSize: 12; color: Theme.accent; visible: root.buttonType !== QsMenuButtonType.RadioButton && root.checkState !== Qt.Unchecked } + } + Image { anchors.fill: parent; source: root.iconSource; sourceSize.width: 18; sourceSize.height: 18; visible: root.buttonType === QsMenuButtonType.None; fillMode: Image.PreserveAspectFit } + } + Text { width: root.width - 70; text: root.text; textFormat: Text.PlainText; elide: Text.ElideRight; color: Theme.text; font.pixelSize: 13; height: 18; verticalAlignment: Text.AlignVCenter } + Text { text: root.submenu ? "›" : ""; color: Theme.textSecondary; font.pixelSize: 16 } + } + MouseArea { + anchors.fill: parent; hoverEnabled: true; enabled: !root.separator + onEntered: root.entered() + onClicked: if (root.actionEnabled) root.invoked() + } +} diff --git a/quickshell/components/GlassPanel.qml b/quickshell/components/GlassPanel.qml new file mode 100644 index 0000000..5a52a4a --- /dev/null +++ b/quickshell/components/GlassPanel.qml @@ -0,0 +1,48 @@ +import QtQuick +import "../theme" + +Rectangle { + id: root + property real surfaceOpacity: Theme.glassOpacity + radius: Theme.radius + color: Qt.alpha(Theme.surface, surfaceOpacity) + border.width: 1 + border.color: Theme.border + Rectangle { + z: -1 + anchors.fill: parent + anchors.topMargin: 4 + anchors.bottomMargin: -4 + radius: root.radius + color: Theme.shadow + visible: Theme.shadows + } + Rectangle { + anchors.fill: parent + radius: root.radius + visible: Theme.highlights + gradient: Gradient { + GradientStop { + position: 0 + color: Qt.alpha(Theme.text, 0.035) + } + GradientStop { + position: 0.55 + color: Theme.transparent + } + GradientStop { + position: 1 + color: Qt.alpha(Theme.shadow, 0.03) + } + } + } + Rectangle { + anchors.top: parent.top + anchors.topMargin: 1 + anchors.horizontalCenter: parent.horizontalCenter + width: Math.max(0, parent.width - root.radius * 2) + height: 1 + color: Theme.border + visible: Theme.highlights + } +} diff --git a/quickshell/components/GlassPill.qml b/quickshell/components/GlassPill.qml new file mode 100644 index 0000000..de1e363 --- /dev/null +++ b/quickshell/components/GlassPill.qml @@ -0,0 +1,2 @@ +import QtQuick +GlassPanel { radius: height / 2 } diff --git a/quickshell/components/GlassPopup.qml b/quickshell/components/GlassPopup.qml new file mode 100644 index 0000000..b1fa52d --- /dev/null +++ b/quickshell/components/GlassPopup.qml @@ -0,0 +1,31 @@ +import QtQuick +import "../theme" + +GlassPanel { + id: root + surfaceOpacity: Theme.panelOpacity + property bool opened: false + visible: opened || opacity > 0.01 + opacity: opened ? 1 : 0 + scale: opened ? 1 : 1 - 0.06 * Theme.intensity + transform: Translate { + y: root.opened ? 0 : -6 * Theme.intensity + Behavior on y { + NumberAnimation { + duration: Theme.duration + easing.type: Easing.OutCubic + } + } + } + Behavior on opacity { + NumberAnimation { + duration: Theme.duration + } + } + Behavior on scale { + NumberAnimation { + duration: Theme.duration + easing.type: Easing.OutCubic + } + } +} diff --git a/quickshell/components/GlassSegmented.qml b/quickshell/components/GlassSegmented.qml new file mode 100644 index 0000000..2e6a3b4 --- /dev/null +++ b/quickshell/components/GlassSegmented.qml @@ -0,0 +1,83 @@ +pragma ComponentBehavior: Bound +import QtQuick +import "../theme" + +// Pill-shaped single choice with a sliding accent indicator. +Rectangle { + id: root + property var model: [] + property int currentIndex: -1 + signal activated(int index, string value) + // Prettify config keywords ("top-left"); leave names such as "DP-4" untouched. + function label(value) { + const raw = String(value); + if (!/^[a-z][a-z0-9_-]*$/.test(raw)) + return raw; + const text = raw.replace(/[-_]/g, " "); + return text.charAt(0).toUpperCase() + text.slice(1); + } + implicitWidth: row.implicitWidth + 8 + implicitHeight: 34 + radius: height / 2 + color: Theme.surfaceVariant + border.width: 1 + border.color: Theme.border + Rectangle { + readonly property Item target: root.currentIndex >= 0 && root.currentIndex < segments.count ? segments.itemAt(root.currentIndex) : null + visible: target !== null + x: target ? row.x + target.x : 4 + y: 4 + width: target ? target.width : 0 + height: root.height - 8 + radius: height / 2 + color: Theme.accent + Behavior on x { + NumberAnimation { + duration: Theme.duration + easing.type: Easing.OutCubic + } + } + Behavior on width { + NumberAnimation { + duration: Theme.duration + easing.type: Easing.OutCubic + } + } + } + Row { + id: row + anchors.centerIn: parent + Repeater { + id: segments + model: root.model + Item { + id: segment + required property var modelData + required property int index + readonly property bool selected: root.currentIndex === index + width: Math.max(52, caption.implicitWidth + 24) + height: root.height - 8 + Text { + id: caption + anchors.centerIn: parent + text: root.label(segment.modelData) + font.pixelSize: 12 + font.weight: segment.selected ? Font.DemiBold : Font.Normal + color: segment.selected ? Theme.accentText : area.containsMouse ? Theme.text : Theme.textSecondary + Behavior on color { + ColorAnimation { + duration: Theme.duration / 2 + } + } + } + MouseArea { + id: area + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: root.activated(segment.index, String(segment.modelData)) + } + } + } + } +} diff --git a/quickshell/components/GlassSlider.qml b/quickshell/components/GlassSlider.qml new file mode 100644 index 0000000..26d2aaa --- /dev/null +++ b/quickshell/components/GlassSlider.qml @@ -0,0 +1,18 @@ +import QtQuick +import QtQuick.Controls +import "../theme" +Slider { + id: root + implicitWidth: 220; implicitHeight: 32 + background: Rectangle { + x: root.leftPadding; y: root.topPadding + root.availableHeight / 2 - height / 2 + width: root.availableWidth; height: 6; radius: 3; color: Theme.surfaceVariant + Rectangle { width: root.visualPosition * parent.width; height: parent.height; radius: 3; color: Theme.accent } + } + handle: Rectangle { + x: root.leftPadding + root.visualPosition * (root.availableWidth - width) + y: root.topPadding + root.availableHeight / 2 - height / 2 + width: 18; height: 18; radius: 9; color: Theme.text + border.width: root.activeFocus ? 2 : 1; border.color: Theme.accent + } +} diff --git a/quickshell/components/GlassTextArea.qml b/quickshell/components/GlassTextArea.qml new file mode 100644 index 0000000..d16487f --- /dev/null +++ b/quickshell/components/GlassTextArea.qml @@ -0,0 +1,18 @@ +import QtQuick +import QtQuick.Controls +import "../theme" + +TextArea { + id: root + color: Theme.text + placeholderTextColor: Theme.textSecondary + selectionColor: Theme.accent + selectedTextColor: Theme.accentText + selectByMouse: true + padding: 10 + background: Rectangle { + radius: 10 + color: Theme.surfaceVariant + border.color: root.activeFocus ? Theme.accent : Theme.border + } +} diff --git a/quickshell/components/GlassTextField.qml b/quickshell/components/GlassTextField.qml new file mode 100644 index 0000000..00f03a3 --- /dev/null +++ b/quickshell/components/GlassTextField.qml @@ -0,0 +1,18 @@ +import QtQuick +import QtQuick.Controls +import "../theme" + +TextField { + id: root + color: Theme.text + placeholderTextColor: Theme.textSecondary + selectionColor: Theme.accent + selectedTextColor: Theme.accentText + selectByMouse: true + padding: 10 + background: Rectangle { + radius: 10 + color: Theme.surfaceVariant + border.color: root.activeFocus ? Theme.accent : Theme.border + } +} diff --git a/quickshell/components/GlassToggle.qml b/quickshell/components/GlassToggle.qml new file mode 100644 index 0000000..cec4efc --- /dev/null +++ b/quickshell/components/GlassToggle.qml @@ -0,0 +1,17 @@ +import QtQuick +import QtQuick.Controls +import "../theme" +Switch { + id: root + implicitWidth: 52; implicitHeight: 32 + indicator: Rectangle { + implicitWidth: 52; implicitHeight: 30; radius: 15 + color: root.checked ? Theme.accent : Theme.surfaceVariant + border.width: 1; border.color: root.activeFocus ? Theme.accent : Theme.border + Rectangle { + x: root.checked ? 25 : 4; y: 4; width: 22; height: 22; radius: 11 + color: root.checked ? Theme.accentText : Theme.text + Behavior on x { NumberAnimation { duration: Theme.duration; easing.type: Easing.OutCubic } } + } + } +} diff --git a/quickshell/config/cava.conf b/quickshell/config/cava.conf new file mode 100644 index 0000000..91f7f9e --- /dev/null +++ b/quickshell/config/cava.conf @@ -0,0 +1,11 @@ +# Dedicated raw output; leave input selection to Cava's compiled default. +[general] +framerate = 30 +bars = 24 +[output] +method = raw +raw_target = /dev/stdout +data_format = ascii +ascii_max_range = 1000 +bar_delimiter = 59 +frame_delimiter = 10 diff --git a/quickshell/config/defaults.json b/quickshell/config/defaults.json new file mode 100644 index 0000000..163e87a --- /dev/null +++ b/quickshell/config/defaults.json @@ -0,0 +1,248 @@ +{ + "schemaVersion": 3, + "appearance": { + "accentSource": "system", + "customAccent": "#a0a0a0", + "glassTint": "#000000", + "glassOpacity": 0.76, + "borderOpacity": 0.18, + "radius": 22, + "highlights": true, + "shadows": true, + "panelOpacity": 0.86 + }, + "animation": { + "duration": 220, + "reducedMotion": false, + "intensity": 1 + }, + "matugen": { + "regenerateOnWallpaperChange": true, + "scheme": "scheme-tonal-spot", + "contrast": 0, + "executable": "matugen" + }, + "bar": { + "margin": 10, + "height": 48, + "modules": [ + { + "id": "settings", + "position": "left", + "enabled": true + }, + { + "id": "workspaces", + "position": "left", + "enabled": true + }, + { + "id": "clock", + "position": "center", + "enabled": true + }, + { + "id": "tray", + "position": "right", + "enabled": true + }, + { + "id": "system", + "position": "right", + "enabled": true + } + ], + "clock": { + "showDate": true, + "use24Hour": true, + "showSeconds": false + }, + "workspaces": { + "count": 9, + "style": "numbers" + }, + "cava": { + "bars": 12, + "style": "bars", + "hideWhenIdle": true + }, + "screens": {} + }, + "tray": { + "enabled": true, + "hoverMenus": true, + "hoverDelay": 400, + "iconSize": 20, + "spacing": 8, + "background": "pill" + }, + "dock": { + "enabled": true, + "monitor": "primary", + "position": "bottom", + "visibility": "always", + "pinnedApps": [], + "iconSize": 48, + "spacing": 8, + "margin": 12, + "magnification": true, + "magnificationStrength": 0.35, + "showRunningApps": true, + "runningIndicators": true, + "tooltips": true, + "animationSpeed": 1, + "appOverrides": {}, + "terminalCommand": [] + }, + "lock": { + "enabled": true, + "backdrop": "wallpaper", + "glass": true, + "media": true, + "powerButtons": true, + "pamService": "" + }, + "desktopWidgets": { + "version": 1, + "grid": false, + "items": [] + }, + "osd": { + "enabled": true, + "position": "top-right", + "timeout": 1600, + "step": 5, + "animation": "slide" + }, + "media": { + "showAlbumArt": true, + "showProgress": true, + "showAlbum": true, + "showCava": false, + "preferredPlayer": "automatic" + }, + "metrics": { + "interval": 2, + "storagePaths": [ + "/" + ], + "networkInterface": "auto", + "gpu": "auto" + }, + "wallpaper": { + "directories": [], + "byMonitor": {}, + "paletteMonitor": "primary", + "backend": "native", + "command": [], + "providerPaths": {}, + "history": [] + }, + "controlCenter": { + "version": 1, + "width": 400, + "modules": [ + { + "id": "connectivity", + "enabled": true + }, + { + "id": "audio", + "enabled": true + }, + { + "id": "brightness", + "enabled": true + }, + { + "id": "nightLight", + "enabled": true + }, + { + "id": "dnd", + "enabled": true + }, + { + "id": "profiles", + "enabled": true + }, + { + "id": "media", + "enabled": true + }, + { + "id": "power", + "enabled": true + } + ] + }, + "launcher": { + "recentFiles": false, + "width": 680, + "maxResults": 50, + "showDescriptions": true + }, + "system": { + "brightness": { + "device": "auto", + "statusCommand": [], + "setCommand": [] + }, + "nightLight": { + "temperature": 4000, + "statusCommand": [], + "setCommand": [] + }, + "power": { + "lockCommand": [] + } + }, + "hyprglass": { + "enabled": false, + "layers": true, + "values": { + "blur_strength": 0.45, + "blur_iterations": 2, + "refraction_strength": 3, + "chromatic_aberration": 0.45, + "fresnel_strength": 0.5, + "specular_strength": 0.8, + "edge_thickness": 0.065, + "lens_distortion": 0.25, + "brightness": 0.95, + "contrast": 1, + "saturation": 1, + "vibrancy": 0.15, + "adaptive_dim": 0.2 + }, + "effectEnabled": true + }, + "dashboard": { + "enabled": true, + "position": "top-center", + "openFromClock": true, + "rememberTab": true, + "easyEffects": true, + "tabs": [ + { + "id": "dashboard", + "enabled": true + }, + { + "id": "media", + "enabled": true + }, + { + "id": "performance", + "enabled": true + }, + { + "id": "power", + "enabled": true + } + ] + }, + "plugins": { + "enabled": [] + } +} diff --git a/quickshell/controlcenter/CCTile.qml b/quickshell/controlcenter/CCTile.qml new file mode 100644 index 0000000..b24f994 --- /dev/null +++ b/quickshell/controlcenter/CCTile.qml @@ -0,0 +1,60 @@ +import QtQuick +import QtQuick.Layouts +import "../theme" + +// Small Control Center tile: round toggle, title and state; the whole tile toggles. +ControlCard { + id: root + property string glyph + property string fallback + property string detail + property bool checked: false + signal clicked + padding: 10 + heading: false + opacity: enabled ? 1 : 0.55 + color: area.containsMouse && enabled ? Theme.hover : Theme.fill + Accessible.role: Accessible.CheckBox + Accessible.name: title + Accessible.checked: checked + MouseArea { + id: area + parent: root + z: -1 + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: root.clicked() + } + RowLayout { + Layout.fillWidth: true + spacing: 10 + CCToggle { + glyph: root.glyph + fallback: root.fallback + checked: root.checked + enabled: root.enabled + onClicked: root.clicked() + } + ColumnLayout { + Layout.fillWidth: true + spacing: 0 + Text { + text: root.title + color: Theme.text + font.pixelSize: 12 + font.weight: Font.DemiBold + elide: Text.ElideRight + Layout.fillWidth: true + } + Text { + text: root.detail + visible: text !== "" + color: Theme.textSecondary + font.pixelSize: 11 + elide: Text.ElideRight + Layout.fillWidth: true + } + } + } +} diff --git a/quickshell/controlcenter/CCToggle.qml b/quickshell/controlcenter/CCToggle.qml new file mode 100644 index 0000000..15cee4c --- /dev/null +++ b/quickshell/controlcenter/CCToggle.qml @@ -0,0 +1,43 @@ +import QtQuick +import "../components" +import "../theme" + +// Round icon toggle; filled with the accent while on. +Item { + id: root + property string glyph + property string fallback + property bool checked: false + property int size: 34 + signal clicked + implicitWidth: size + implicitHeight: size + opacity: enabled ? 1 : 0.45 + Accessible.role: Accessible.CheckBox + Accessible.checked: checked + GlassIcon { + anchors.fill: parent + size: root.size + radius: root.size / 2 + glyph: root.glyph + fallback: root.fallback + active: root.checked + color: root.checked ? Theme.accent : area.containsMouse ? Theme.hover : Theme.surfaceVariant + border.width: root.checked ? 0 : 1 + border.color: Theme.hairline + scale: area.pressed ? 0.92 : 1 + Behavior on scale { + NumberAnimation { + duration: Theme.duration / 2 + easing.type: Easing.OutCubic + } + } + } + MouseArea { + id: area + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: root.clicked() + } +} diff --git a/quickshell/controlcenter/ControlCard.qml b/quickshell/controlcenter/ControlCard.qml new file mode 100644 index 0000000..bb8c7d9 --- /dev/null +++ b/quickshell/controlcenter/ControlCard.qml @@ -0,0 +1,35 @@ +import QtQuick +import QtQuick.Layouts +import "../theme" + +// Rounded Control Center module (macOS style); also embedded by Settings pages. +Rectangle { + id: root + default property alias controls: body.data + property string title + property bool heading: title !== "" + property int padding: 12 + implicitWidth: 360 + implicitHeight: body.implicitHeight + padding * 2 + radius: Math.max(12, Theme.radius * 0.75) + color: Theme.fill + border.width: 1 + border.color: Theme.hairline + ColumnLayout { + id: body + anchors { + left: parent.left + right: parent.right + top: parent.top + margins: root.padding + } + spacing: 10 + Text { + visible: root.heading + text: root.title + color: Theme.text + font.pixelSize: 13 + font.weight: Font.DemiBold + } + } +} diff --git a/quickshell/controlcenter/ControlCenter.qml b/quickshell/controlcenter/ControlCenter.qml new file mode 100644 index 0000000..d42056d --- /dev/null +++ b/quickshell/controlcenter/ControlCenter.qml @@ -0,0 +1,302 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import Quickshell +import Quickshell.Io +import Quickshell.Wayland +import "../components" +import "../services" +import "../core" +import "../theme" + +// macOS-style Control Center. The layer surface is sized to the panel so +// compositor glass (HyprGlass) shapes its edges to the panel, not the screen. +// qmllint disable uncreatable-type +PanelWindow { + id: root + screen: ScreenService.current(ShellState.controlCenterScreen) + anchors { + top: true + right: true + } + readonly property int screenWidth: screen ? screen.width : 1920 + readonly property int screenHeight: screen ? screen.height : 1080 + // Drops out of the bar's right side; the right ear stays on its straight edge. + readonly property real rightInset: BarDrawers.margin + BarDrawers.radius + // Panel position on the output, for tests and diagnostics. + readonly property real panelScreenX: screenWidth - rightInset - width + panel.ear + readonly property real panelScreenY: BarDrawers.bottom + // The layer starts at the screen top so the bar join is inside its box. + // Margins is present at runtime but unresolved in 0.3.1 qmltypes. + // qmllint disable unqualified unresolved-type + margins { + right: root.rightInset + } + // qmllint enable unqualified unresolved-type + implicitWidth: Math.round(panel.width) + implicitHeight: Math.round(BarDrawers.bottom + panel.contentHeight) + visible: ShellState.controlCenterOpen || panel.shown + color: Theme.transparent + exclusionMode: ExclusionMode.Ignore + WlrLayershell.layer: WlrLayer.Overlay + WlrLayershell.namespace: "glassMxrph-controlcenter" + WlrLayershell.keyboardFocus: ShellState.controlCenterOpen ? WlrKeyboardFocus.Exclusive : WlrKeyboardFocus.None + Component.onCompleted: ShellState.controlCenterWindow = root + Component.onDestruction: ShellState.controlCenterWindow = null + + // Connectivity and the small tiles share one block (connectivity left, tiles + // stacked right), placed where the first of them appears; other modules + // span the full width in their configured order. + readonly property var smallTiles: ["dnd", "nightLight", "profiles"] + readonly property var blocks: { + if (!ConfigService.ready) + return []; + const ids = ConfigService.data.controlCenter.modules.filter(m => m.enabled && !!ControlRegistry.entry(m.id)).map(m => m.id); + const grouped = ids.filter(id => id === "connectivity" || smallTiles.includes(id)); + const result = []; + let placed = false; + for (const id of ids) { + if (!grouped.includes(id)) { + result.push({ + kind: "full", + ids: [id] + }); + } else if (!placed) { + placed = true; + const tiles = grouped.filter(g => g !== "connectivity"); + if (!grouped.includes("connectivity")) + result.push({ + kind: "grid", + ids: tiles + }); + else if (tiles.length === 0) + result.push({ + kind: "full", + ids: ["connectivity"] + }); + else + result.push({ + kind: "split", + ids: tiles + }); + } + } + return result; + } + + component ModuleSlot: Loader { + property string moduleId + Layout.fillWidth: true + Layout.preferredWidth: 1 + active: ShellState.controlCenterOpen + source: moduleId ? ControlRegistry.entry(moduleId).source : "" + } + component HeaderButton: Rectangle { + id: headerButton + property string glyph + property string fallback + signal clicked + implicitWidth: 28 + implicitHeight: 28 + radius: 14 + color: headerArea.containsMouse ? Qt.alpha(Theme.text, 0.12) : Theme.transparent + Accessible.role: Accessible.Button + GlassIcon { + anchors.centerIn: parent + size: 28 + glyphSize: 14 + glyph: headerButton.glyph + fallback: headerButton.fallback + color: Theme.transparent + border.width: 0 + glyphColor: Theme.textSecondary + } + MouseArea { + id: headerArea + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: headerButton.clicked() + } + } + + // Hyprland routes every pointer event to a layer with exclusive keyboard + // focus, so clicks outside the panel arrive here with out-of-bounds + // coordinates. Qt Quick still delivers them to items extending past the + // window, so this catcher (behind the panel) dismisses on outside clicks. + MouseArea { + objectName: "controlCenterOutside" + x: -20000 + y: -20000 + width: 40000 + height: 40000 + onPressed: ShellState.controlCenterOpen = false + } + + BarDrawer { + id: panel + objectName: "controlCenterSurface" + readonly property real targetWidth: Math.min(ConfigService.ready ? ConfigService.data.controlCenter.width : 400, root.screenWidth - 2 * root.rightInset - 2 * ear) + readonly property real targetHeight: Math.min(content.implicitHeight + 28, root.screenHeight - BarDrawers.bottom - 20) + y: BarDrawers.bottom + open: ShellState.controlCenterOpen + contentWidth: targetWidth + contentHeight: targetHeight + drawerId: "controlcenter" + screenName: root.screen ? root.screen.name : "" + screenX: root.screenWidth - root.rightInset - width + focus: open + onOpenChanged: if (open) + forceActiveFocus() + Keys.onEscapePressed: { + if (PowerService.pending) + PowerService.cancel(); + else + ShellState.controlCenterOpen = false; + } + Behavior on contentHeight { + enabled: panel.settled + NumberAnimation { + duration: Theme.duration + easing.type: Easing.OutCubic + } + } + MouseArea { + anchors.fill: parent + } + ScrollView { + anchors.fill: parent + anchors.margins: 14 + clip: true + contentWidth: panel.targetWidth - 28 + ColumnLayout { + id: content + width: panel.targetWidth - 28 + spacing: 10 + RowLayout { + Layout.fillWidth: true + Layout.leftMargin: 4 + spacing: 2 + Text { + text: "Control Center" + color: Theme.text + font.pixelSize: 14 + font.weight: Font.DemiBold + Layout.fillWidth: true + } + HeaderButton { + glyph: "󰒓" + fallback: "⚙" + onClicked: ShellState.openSettings("controlcenter") + Accessible.name: "Control Center settings" + } + HeaderButton { + glyph: "󰅖" + fallback: "×" + onClicked: ShellState.controlCenterOpen = false + Accessible.name: "Close Control Center" + } + } + Repeater { + model: root.blocks + Item { + id: block + required property var modelData + Layout.fillWidth: true + implicitHeight: block.modelData.kind === "full" ? full.implicitHeight : block.modelData.kind === "split" ? split.implicitHeight : grid.implicitHeight + ModuleSlot { + id: full + visible: block.modelData.kind === "full" + width: parent.width + moduleId: block.modelData.kind === "full" ? block.modelData.ids[0] : "" + active: visible && ShellState.controlCenterOpen + } + RowLayout { + id: split + visible: block.modelData.kind === "split" + width: parent.width + spacing: 10 + ModuleSlot { + moduleId: "connectivity" + active: split.visible && ShellState.controlCenterOpen + Layout.fillHeight: true + } + ColumnLayout { + Layout.fillWidth: true + Layout.preferredWidth: 1 + Layout.alignment: Qt.AlignTop + spacing: 10 + Repeater { + model: block.modelData.kind === "split" ? block.modelData.ids : [] + ModuleSlot { + required property string modelData + moduleId: modelData + } + } + } + } + GridLayout { + id: grid + visible: block.modelData.kind === "grid" + width: parent.width + columns: 2 + columnSpacing: 10 + rowSpacing: 10 + Repeater { + model: block.modelData.kind === "grid" ? block.modelData.ids : [] + ModuleSlot { + required property string modelData + moduleId: modelData + } + } + } + } + } + Text { + visible: SystemService.acting + text: "Updating system controls…" + color: Theme.textSecondary + font.pixelSize: 11 + Layout.fillWidth: true + Layout.leftMargin: 4 + } + Text { + visible: !!SystemService.error + text: SystemService.error + color: Theme.urgent + font.pixelSize: 11 + wrapMode: Text.Wrap + Layout.fillWidth: true + Layout.leftMargin: 4 + } + GlassButton { + visible: root.blocks.length === 0 + text: "Add modules" + onClicked: ShellState.openSettings("controlcenter") + } + } + } + } + IpcHandler { + target: "controlcenter" + function toggle(): void { + ShellState.toggleControlCenter(); + } + function open(): void { + ShellState.openControlCenter(); + } + function close(): void { + ShellState.controlCenterOpen = false; + } + function status(): string { + return JSON.stringify({ + opened: ShellState.controlCenterOpen, + screen: root.screen ? root.screen.name : "", + busy: SystemService.busy, + error: SystemService.error, + pendingPower: PowerService.pending + }); + } + } +} diff --git a/quickshell/controlcenter/ControlRegistry.qml b/quickshell/controlcenter/ControlRegistry.qml new file mode 100644 index 0000000..0e6e20b --- /dev/null +++ b/quickshell/controlcenter/ControlRegistry.qml @@ -0,0 +1,44 @@ +pragma Singleton +import QtQuick +import Quickshell + +Singleton { + function entry(id) { + return Object.prototype.hasOwnProperty.call(modules, id) ? modules[id] : null; + } + readonly property var modules: ({ + metrics: {title:"System Metrics", source:Qt.resolvedUrl("modules/Metrics.qml")}, + connectivity: { + title: "Connectivity", + source: Qt.resolvedUrl("modules/Connectivity.qml") + }, + audio: { + title: "Audio", + source: Qt.resolvedUrl("modules/Audio.qml") + }, + brightness: { + title: "Brightness", + source: Qt.resolvedUrl("modules/Brightness.qml") + }, + nightLight: { + title: "Night Light", + source: Qt.resolvedUrl("modules/NightLight.qml") + }, + dnd: { + title: "Do Not Disturb", + source: Qt.resolvedUrl("modules/Dnd.qml") + }, + profiles: { + title: "Power profile", + source: Qt.resolvedUrl("modules/Profiles.qml") + }, + media: { + title: "Media", + source: Qt.resolvedUrl("modules/Media.qml") + }, + power: { + title: "Power", + source: Qt.resolvedUrl("modules/Power.qml") + } + }) +} diff --git a/quickshell/controlcenter/SystemTile.qml b/quickshell/controlcenter/SystemTile.qml new file mode 100644 index 0000000..e7a95ca --- /dev/null +++ b/quickshell/controlcenter/SystemTile.qml @@ -0,0 +1,28 @@ +import QtQuick +import QtQuick.Layouts +import "../components" +import "../theme" + +GlassButton { + id: root + property string title + property string detail + implicitHeight: 74 + contentItem: ColumnLayout { + spacing: 4 + Text { + text: root.title + color: root.accented ? Theme.accentText : Theme.text + font.weight: Font.DemiBold + Layout.fillWidth: true + elide: Text.ElideRight + } + Text { + text: root.detail + color: root.accented ? Theme.accentText : Theme.textSecondary + font.pixelSize: 11 + Layout.fillWidth: true + elide: Text.ElideRight + } + } +} diff --git a/quickshell/controlcenter/modules/Audio.qml b/quickshell/controlcenter/modules/Audio.qml new file mode 100644 index 0000000..e3fb0f2 --- /dev/null +++ b/quickshell/controlcenter/modules/Audio.qml @@ -0,0 +1,158 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Layouts +import ".." +import "../../components" +import "../../services" +import "../../theme" + +// Output and microphone levels; the chevron reveals device selection. +ControlCard { + id: root + property bool detailed: false + property bool expanded: detailed + RowLayout { + Layout.fillWidth: true + Text { + text: "Sound" + color: Theme.text + font.pixelSize: 13 + font.weight: Font.DemiBold + Layout.fillWidth: true + } + Rectangle { + objectName: "audioDevices" + visible: !root.detailed && AudioService.available + implicitWidth: 24 + implicitHeight: 24 + radius: 12 + color: chevron.containsMouse ? Qt.alpha(Theme.text, 0.12) : Theme.transparent + Accessible.name: root.expanded ? "Hide audio devices" : "Show audio devices" + Accessible.role: Accessible.Button + Text { + anchors.centerIn: parent + text: "›" + color: Theme.textSecondary + font.pixelSize: 18 + rotation: root.expanded ? 90 : 0 + Behavior on rotation { + NumberAnimation { + duration: Theme.duration + easing.type: Easing.OutCubic + } + } + } + MouseArea { + id: chevron + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: root.expanded = !root.expanded + } + } + } + Repeater { + model: [false, true] + RowLayout { + id: channel + required property bool modelData + readonly property var node: modelData ? AudioService.source : AudioService.sink + readonly property bool muted: !!node && !!node.audio && node.audio.muted + Layout.fillWidth: true + spacing: 10 + CCToggle { + objectName: channel.modelData ? "microphoneMute" : "volumeMute" + size: 28 + glyph: channel.modelData ? (channel.muted ? "󰍭" : "󰍬") : (channel.muted ? "󰖁" : "󰕾") + fallback: channel.muted ? "×" : (channel.modelData ? "M" : "♪") + checked: channel.muted + enabled: !!channel.node && !!channel.node.audio + onClicked: AudioService.mute(channel.modelData) + Accessible.name: channel.modelData ? "Mute microphone" : "Mute output" + } + GlassBarSlider { + objectName: channel.modelData ? "microphoneSlider" : "volumeSlider" + Layout.fillWidth: true + from: 0 + to: 1 + stepSize: 0.01 + enabled: !!channel.node && !!channel.node.audio + value: channel.node && channel.node.audio ? channel.node.audio.volume : 0 + onMoved: AudioService.volume(channel.modelData, value) + Accessible.name: channel.modelData ? "Microphone level" : "Output volume" + } + Text { + text: channel.node && channel.node.audio ? Math.round(channel.node.audio.volume * 100) + "%" : "—" + color: Theme.textSecondary + font.pixelSize: 11 + horizontalAlignment: Text.AlignRight + Layout.preferredWidth: 34 + } + } + } + Repeater { + model: root.expanded ? [false, true] : [] + ColumnLayout { + id: devices + required property bool modelData + readonly property var nodes: modelData ? AudioService.inputs : AudioService.outputs + readonly property var current: modelData ? AudioService.source : AudioService.sink + Layout.fillWidth: true + spacing: 2 + Text { + text: devices.modelData ? "INPUT" : "OUTPUT" + color: Theme.textSecondary + font.pixelSize: 10 + font.weight: Font.DemiBold + font.letterSpacing: 1.1 + Layout.topMargin: 4 + } + Repeater { + model: devices.nodes + Rectangle { + id: device + required property var modelData + required property int index + readonly property bool selected: modelData === devices.current + Layout.fillWidth: true + implicitHeight: 30 + radius: 8 + color: deviceArea.containsMouse ? Qt.alpha(Theme.text, 0.08) : Theme.transparent + RowLayout { + anchors.fill: parent + anchors.leftMargin: 6 + anchors.rightMargin: 6 + spacing: 8 + Text { + text: device.selected ? "✓" : "" + color: Theme.accent + font.pixelSize: 12 + Layout.preferredWidth: 14 + } + Text { + text: device.modelData.description || device.modelData.name + color: device.selected ? Theme.text : Qt.alpha(Theme.text, 0.8) + font.pixelSize: 12 + font.weight: device.selected ? Font.DemiBold : Font.Normal + elide: Text.ElideRight + Layout.fillWidth: true + } + } + MouseArea { + id: deviceArea + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: AudioService.select(devices.modelData, device.index) + } + } + } + } + } + Text { + visible: !AudioService.available + text: "PipeWire is unavailable" + color: Theme.textSecondary + font.pixelSize: 11 + } +} diff --git a/quickshell/controlcenter/modules/Brightness.qml b/quickshell/controlcenter/modules/Brightness.qml new file mode 100644 index 0000000..48b4847 --- /dev/null +++ b/quickshell/controlcenter/modules/Brightness.qml @@ -0,0 +1,44 @@ +import QtQuick +import QtQuick.Layouts +import ".." +import "../../components" +import "../../services" +import "../../theme" + +ControlCard { + id: root + readonly property var info: SystemService.state.brightness || ({ + available: false + }) + title: "Display" + GlassBarSlider { + objectName: "brightnessSlider" + Layout.fillWidth: true + glyph: "󰃠" + fallback: "☀" + from: 1 + to: 100 + stepSize: 1 + value: root.info.value || 1 + enabled: !!root.info.available && !SystemService.acting + onPressedChanged: if (!pressed && enabled) { + SystemService.action("brightness", value, false); + value = Qt.binding(() => root.info.value || 1); + } + Keys.onReleased: event => { + if (event.key === Qt.Key_Left || event.key === Qt.Key_Right) { + SystemService.action("brightness", value, false); + value = Qt.binding(() => root.info.value || 1); + } + } + Accessible.name: "Display brightness" + } + Text { + visible: !root.info.available + text: root.info.notice || "No brightness provider" + color: Theme.textSecondary + font.pixelSize: 11 + wrapMode: Text.Wrap + Layout.fillWidth: true + } +} diff --git a/quickshell/controlcenter/modules/Connectivity.qml b/quickshell/controlcenter/modules/Connectivity.qml new file mode 100644 index 0000000..5eb73a5 --- /dev/null +++ b/quickshell/controlcenter/modules/Connectivity.qml @@ -0,0 +1,89 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Layouts +import ".." +import "../../services" +import "../../core" +import "../../theme" + +// Wi-Fi, Bluetooth and live throughput; labels open the matching Settings page. +ControlCard { + id: root + Component.onCompleted: MetricsService.consumers++ + Component.onDestruction: MetricsService.consumers-- + component Entry: RowLayout { + id: entry + property alias toggle: toggle + property string title + property string detail + property string page + Layout.fillWidth: true + spacing: 10 + CCToggle { + id: toggle + } + Item { + Layout.fillWidth: true + implicitHeight: labels.implicitHeight + ColumnLayout { + id: labels + anchors.left: parent.left + anchors.right: parent.right + spacing: 0 + Text { + text: entry.title + color: Theme.text + font.pixelSize: 12 + font.weight: Font.DemiBold + elide: Text.ElideRight + Layout.fillWidth: true + } + Text { + text: entry.detail + color: Theme.textSecondary + font.pixelSize: 11 + elide: Text.ElideRight + Layout.fillWidth: true + } + } + MouseArea { + anchors.fill: parent + cursorShape: Qt.PointingHandCursor + onClicked: ShellState.openSettings(entry.page) + } + } + } + Entry { + title: "Wi-Fi" + detail: !NetworkService.available ? "No Wi-Fi adapter" : !NetworkService.backend.wifiHardwareEnabled ? "Hardware blocked" : NetworkService.enabled ? NetworkService.summary : "Off" + page: "network" + toggle.objectName: "wifiToggle" + toggle.glyph: NetworkService.enabled ? "󰖩" : "󰖪" + toggle.fallback: "W" + toggle.checked: NetworkService.available && NetworkService.enabled + toggle.enabled: NetworkService.available && NetworkService.backend.wifiHardwareEnabled + toggle.onClicked: NetworkService.toggle() + toggle.Accessible.name: "Wi-Fi" + } + Entry { + title: "Bluetooth" + detail: !BluetoothService.adapter ? "No adapter" : !BluetoothService.canToggle ? "Hardware blocked" : BluetoothService.summary + page: "bluetooth" + toggle.objectName: "bluetoothToggle" + toggle.glyph: BluetoothService.enabled ? "󰂯" : "󰂲" + toggle.fallback: "B" + toggle.checked: BluetoothService.enabled + toggle.enabled: BluetoothService.canToggle + toggle.onClicked: BluetoothService.toggle() + toggle.Accessible.name: "Bluetooth" + } + Entry { + title: "Network" + detail: "↓ " + MetricsService.bytes(MetricsService.network.download) + "/s ↑ " + MetricsService.bytes(MetricsService.network.upload) + "/s" + page: "metrics" + toggle.glyph: "󰛳" + toggle.fallback: "N" + toggle.onClicked: ShellState.openSettings("network") + toggle.Accessible.name: "Network settings" + } +} diff --git a/quickshell/controlcenter/modules/Dnd.qml b/quickshell/controlcenter/modules/Dnd.qml new file mode 100644 index 0000000..dc7b199 --- /dev/null +++ b/quickshell/controlcenter/modules/Dnd.qml @@ -0,0 +1,18 @@ +import QtQuick +import ".." +import "../../services" + +CCTile { + readonly property var info: SystemService.state.dnd || ({ + available: false + }) + objectName: "dndToggle" + title: "Do Not Disturb" + detail: !info.available ? "No SwayNC running" : info.enabled ? "On" : "Off" + glyph: "󰽥" + fallback: "☾" + // Shows acknowledged provider state; a failed request leaves it unchanged. + checked: !!info.enabled + enabled: !!info.available && !SystemService.acting + onClicked: SystemService.action("dnd", !info.enabled, false) +} diff --git a/quickshell/controlcenter/modules/Media.qml b/quickshell/controlcenter/modules/Media.qml new file mode 100644 index 0000000..34227ed --- /dev/null +++ b/quickshell/controlcenter/modules/Media.qml @@ -0,0 +1,11 @@ +import QtQuick +import "../../media" +import "../../theme" + +// Shared player and controls, styled as a Control Center module. +MediaCard { + compact: true + radius: Math.max(12, Theme.radius * 0.75) + color: Theme.fill + border.color: Theme.hairline +} diff --git a/quickshell/controlcenter/modules/Metrics.qml b/quickshell/controlcenter/modules/Metrics.qml new file mode 100644 index 0000000..21201ce --- /dev/null +++ b/quickshell/controlcenter/modules/Metrics.qml @@ -0,0 +1,10 @@ +import QtQuick +import "../../metrics" +import "../../theme" + +MetricsCard { + compact: true + radius: Math.max(12, Theme.radius * 0.75) + color: Theme.fill + border.color: Theme.hairline +} diff --git a/quickshell/controlcenter/modules/NightLight.qml b/quickshell/controlcenter/modules/NightLight.qml new file mode 100644 index 0000000..4d3b5ef --- /dev/null +++ b/quickshell/controlcenter/modules/NightLight.qml @@ -0,0 +1,18 @@ +import QtQuick +import ".." +import "../../services" + +CCTile { + readonly property var info: SystemService.state.nightLight || ({ + available: false + }) + objectName: "nightLightToggle" + title: "Night Light" + detail: !info.available ? "No gamma provider" : info.enabled ? "On" : "Off" + glyph: "󰖔" + fallback: "N" + // Shows acknowledged provider state; a failed request leaves it unchanged. + checked: !!info.enabled + enabled: !!info.available && !SystemService.acting + onClicked: SystemService.action("nightLight", !info.enabled, false) +} diff --git a/quickshell/controlcenter/modules/Power.qml b/quickshell/controlcenter/modules/Power.qml new file mode 100644 index 0000000..a732a4c --- /dev/null +++ b/quickshell/controlcenter/modules/Power.qml @@ -0,0 +1,91 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Layouts +import ".." +import "../../components" +import "../../services" +import "../../theme" + +ControlCard { + id: root + Component.onDestruction: PowerService.cancel() + RowLayout { + Layout.fillWidth: true + spacing: 4 + Repeater { + model: [ + { + id: "lock", + glyph: "󰌾" + }, + { + id: "logout", + glyph: "󰍃" + }, + { + id: "suspend", + glyph: "󰤄" + }, + { + id: "reboot", + glyph: "󰜉" + }, + { + id: "shutdown", + glyph: "󰐥" + } + ] + ColumnLayout { + id: action + required property var modelData + readonly property string label: modelData.id === "logout" ? "Log out" : modelData.id === "shutdown" ? "Shut down" : modelData.id.charAt(0).toUpperCase() + modelData.id.slice(1) + Layout.fillWidth: true + Layout.preferredWidth: 1 + spacing: 4 + CCToggle { + objectName: "power-" + action.modelData.id + Layout.alignment: Qt.AlignHCenter + size: 38 + glyph: action.modelData.glyph + fallback: action.label.charAt(0) + checked: PowerService.pending === action.modelData.id + enabled: (action.modelData.id === "lock" && ConfigService.ready && ConfigService.data.lock.enabled) || (!!SystemService.state.power && !!SystemService.state.power[action.modelData.id] && !SystemService.acting) + onClicked: PowerService.request(action.modelData.id) + Accessible.name: action.label + } + Text { + text: action.label + color: Theme.textSecondary + font.pixelSize: 10 + elide: Text.ElideRight + horizontalAlignment: Text.AlignHCenter + Layout.fillWidth: true + } + } + } + } + RowLayout { + visible: PowerService.pending !== "" + Layout.fillWidth: true + spacing: 8 + Text { + text: "Confirm " + PowerService.pending + "? Unsaved work may be lost." + color: Theme.text + font.pixelSize: 12 + wrapMode: Text.Wrap + Layout.fillWidth: true + } + GlassButton { + objectName: "powerCancel" + text: "Cancel" + onClicked: PowerService.cancel() + } + GlassButton { + objectName: "powerConfirm" + text: "Confirm" + accented: true + enabled: !SystemService.acting + onClicked: PowerService.confirm() + } + } +} diff --git a/quickshell/controlcenter/modules/Profiles.qml b/quickshell/controlcenter/modules/Profiles.qml new file mode 100644 index 0000000..a736d0d --- /dev/null +++ b/quickshell/controlcenter/modules/Profiles.qml @@ -0,0 +1,23 @@ +import QtQuick +import ".." +import "../../services" + +// Clicking cycles through the available power profiles. +CCTile { + id: root + readonly property var info: SystemService.state.profiles || ({ + available: false, + profiles: [] + }) + readonly property var profiles: info.profiles || [] + readonly property string current: info.current || "" + objectName: "profileTile" + title: "Power profile" + detail: !info.available ? "Unavailable" : current ? current.charAt(0).toUpperCase() + current.slice(1).replace(/-/g, " ") : "—" + glyph: current === "power-saver" ? "󰌪" : current === "performance" ? "󰓅" : "󰾅" + fallback: "P" + checked: info.available && current !== "" && current !== "balanced" + enabled: !!info.available && profiles.length > 1 && !SystemService.acting + onClicked: SystemService.action("profile", profiles[(profiles.indexOf(current) + 1) % profiles.length], false) + Accessible.name: "Power profile: " + detail +} diff --git a/quickshell/controlcenter/qmldir b/quickshell/controlcenter/qmldir new file mode 100644 index 0000000..119645e --- /dev/null +++ b/quickshell/controlcenter/qmldir @@ -0,0 +1,6 @@ +singleton ControlRegistry 1.0 ControlRegistry.qml +ControlCenter 1.0 ControlCenter.qml +ControlCard 1.0 ControlCard.qml +SystemTile 1.0 SystemTile.qml +CCToggle 1.0 CCToggle.qml +CCTile 1.0 CCTile.qml diff --git a/quickshell/core/BarDrawers.qml b/quickshell/core/BarDrawers.qml new file mode 100644 index 0000000..f3693dd --- /dev/null +++ b/quickshell/core/BarDrawers.qml @@ -0,0 +1,56 @@ +pragma Singleton +import QtQuick +import Quickshell +import "../services" +import "../theme" + +// Caelestia-style drawers: popups that grow out of the bar's bottom edge as one +// continuous shape. Drawers register the span they occupy so the bar can open +// its border there; geometry helpers keep every drawer on the bar's straight edge. +Singleton { + id: root + readonly property int margin: ConfigService.ready ? ConfigService.data.bar.margin : 10 + readonly property int height: ConfigService.ready ? ConfigService.data.bar.height : 48 + // Screen y of the bar's bottom edge, where drawers attach. + readonly property int bottom: margin + height + readonly property real radius: Math.min(Theme.radius, height / 2) + // Concave fillet joining a drawer to the bar. + readonly property real ear: Math.max(8, Math.min(18, Theme.radius * 0.8)) + // The bar window reaches this far below the bar so its glass edge never + // lands on the join (HyprGlass refracts at layer box edges). + readonly property int overhang: 28 + // screen name -> [{id, x0, x1}] in screen coordinates. + property var gaps: ({}) + function setGap(id, screenName, x0, x1) { + const next = Object.assign({}, gaps); + for (const key in next) + next[key] = next[key].filter(g => g.id !== id); + if (screenName) + next[screenName] = (next[screenName] || []).concat([ + { + id: id, + x0: x0, + x1: x1 + } + ]); + gaps = next; + } + function clearGap(id) { + setGap(id, "", 0, 0); + } + function gapsFor(screenName) { + return gaps[screenName] || []; + } + // Left edge (screen x) for a drawer of `outerWidth` (body plus both ears) + // centred on `centerX`, kept within the bar's straight bottom edge. + function clampX(centerX, outerWidth, screenWidth) { + const lo = margin + radius, hi = screenWidth - margin - radius - outerWidth; + return Math.round(Math.max(lo, Math.min(centerX - outerWidth / 2, hi))); + } + function leftX() { + return Math.round(margin + radius); + } + function rightX(outerWidth, screenWidth) { + return Math.round(screenWidth - margin - radius - outerWidth); + } +} diff --git a/quickshell/core/BarLayout.qml b/quickshell/core/BarLayout.qml new file mode 100644 index 0000000..0b9e258 --- /dev/null +++ b/quickshell/core/BarLayout.qml @@ -0,0 +1,42 @@ +pragma Singleton +import QtQuick +import Quickshell +import "../services" + +// Bar module layouts. Screens listed in `bar.screens` have their own module +// list (e.g. a narrow vertical monitor); every other screen uses `bar.modules`. +Singleton { + id: root + readonly property var screens: ConfigService.ready ? (ConfigService.data.bar.screens || ({})) : ({}) + function hasOwn(screenName) { + return !!screenName && !!screens[screenName] && Array.isArray(screens[screenName].modules); + } + function modulesFor(screenName) { + if (!ConfigService.ready) + return []; + return hasOwn(screenName) ? screens[screenName].modules : ConfigService.data.bar.modules; + } + // Saves to the screen's own layout when it has one, else the shared layout. + function save(screenName, modules) { + if (!hasOwn(screenName)) + return ConfigService.setValue("bar.modules", modules); + const next = Object.assign({}, screens); + next[screenName] = Object.assign({}, next[screenName], { + modules: modules + }); + return ConfigService.setValue("bar.screens", next); + } + // A new screen layout starts as a copy of the shared one. + function setOwn(screenName, own) { + if (!screenName || own === hasOwn(screenName)) + return false; + const next = Object.assign({}, screens); + if (own) + next[screenName] = { + modules: ConfigService.data.bar.modules.map(m => Object.assign({}, m)) + }; + else + delete next[screenName]; + return ConfigService.setValue("bar.screens", next); + } +} diff --git a/quickshell/core/DashboardRegistry.qml b/quickshell/core/DashboardRegistry.qml new file mode 100644 index 0000000..7171c7c --- /dev/null +++ b/quickshell/core/DashboardRegistry.qml @@ -0,0 +1,40 @@ +pragma Singleton +import QtQuick +import Quickshell + +// Dashboard tabs. Order and visibility come from `dashboard.tabs` in the config. +Singleton { + readonly property var tabs: ({ + dashboard: { + title: "Dashboard", + description: "User, clock, calendar, resources and now playing", + glyph: "󰕮", + fallback: "◫", + source: Qt.resolvedUrl("../dashboard/tabs/OverviewTab.qml") + }, + media: { + title: "Media", + description: "Player controls and the EasyEffects equalizer", + glyph: "󰝚", + fallback: "♪", + source: Qt.resolvedUrl("../dashboard/tabs/MediaTab.qml") + }, + performance: { + title: "Performance", + description: "CPU, GPU, memory, storage and network", + glyph: "󰓅", + fallback: "%", + source: Qt.resolvedUrl("../dashboard/tabs/PerformanceTab.qml") + }, + power: { + title: "Power", + description: "Lock, restart and shut down", + glyph: "󰐥", + fallback: "⏻", + source: Qt.resolvedUrl("../dashboard/tabs/PowerTab.qml") + } + }) + function entry(id) { + return tabs[id] || null; + } +} diff --git a/quickshell/core/ModuleRegistry.qml b/quickshell/core/ModuleRegistry.qml new file mode 100644 index 0000000..43f559b --- /dev/null +++ b/quickshell/core/ModuleRegistry.qml @@ -0,0 +1,72 @@ +pragma Singleton +import QtQuick +import Quickshell +import "../services" +Singleton { + // Shared pill height for bar modules: 36px, shrinking to fit shorter bars. + readonly property int pillHeight: ConfigService.ready ? Math.max(24, Math.min(36, ConfigService.data.bar.height - 6)) : 36 + readonly property var modules: ({ + cpu: Qt.resolvedUrl("../bar/modules/MetricsModule.qml"), + cpuTemperature: Qt.resolvedUrl("../bar/modules/MetricsModule.qml"), + gpu: Qt.resolvedUrl("../bar/modules/MetricsModule.qml"), + gpuTemperature: Qt.resolvedUrl("../bar/modules/MetricsModule.qml"), + ram: Qt.resolvedUrl("../bar/modules/MetricsModule.qml"), + storage: Qt.resolvedUrl("../bar/modules/MetricsModule.qml"), + networkThroughput: Qt.resolvedUrl("../bar/modules/MetricsModule.qml"), + activeWindow: Qt.resolvedUrl("../bar/modules/ActiveWindowModule.qml"), + cava: Qt.resolvedUrl("../bar/modules/CavaModule.qml"), + nowPlaying: Qt.resolvedUrl("../bar/modules/NowPlayingModule.qml"), + settings: Qt.resolvedUrl("../bar/modules/SettingsModule.qml"), + workspaces: Qt.resolvedUrl("../bar/modules/WorkspacesModule.qml"), + clock: Qt.resolvedUrl("../bar/modules/ClockModule.qml"), + tray: Qt.resolvedUrl("../bar/modules/TrayModule.qml"), + system: Qt.resolvedUrl("../bar/modules/SystemModule.qml"), + volume: Qt.resolvedUrl("../bar/modules/VolumeModule.qml") + }) + // Installed plugin bar widgets are modules named "plugin:". + function isPlugin(id) { return String(id).startsWith("plugin:"); } + function source(id) { return isPlugin(id) ? Qt.resolvedUrl("../bar/modules/PluginModule.qml") : modules[id] || ""; } + // Every module that can be added: built-ins plus enabled plugin widgets. + readonly property var available: Object.keys(modules).concat(PluginService.barModules) + // Readable names for the Settings → Bar editor. + readonly property var titles: ({ + activeWindow: "Windows", cava: "Visualizer", clock: "Clock", cpu: "CPU", cpuTemperature: "CPU temp", + gpu: "GPU", gpuTemperature: "GPU temp", networkThroughput: "Network", nowPlaying: "Now playing", + ram: "Memory", settings: "Settings", storage: "Storage", system: "System", tray: "Tray", + volume: "Volume", workspaces: "Workspaces" + }) + function title(id) { return isPlugin(id) ? PluginService.title(String(id).slice(7)) : titles[id] || id; } + // Per-module options edited from the cog on each card in Settings → Bar. + // Stored on the module entry, so per-screen layouts can differ. + readonly property var optionSchemas: ({ + activeWindow: [ + { key: "transition", label: "On switch", choices: ["fade", "slide", "pop", "none"], fallback: "fade" }, + { key: "labels", label: "Names", choices: ["all", "focused", "icons"], fallback: "all" }, + { key: "collapse", label: "Icons after", choices: ["3", "4", "6", "never"], fallback: "3" }, + { key: "labelWidth", label: "Name width", choices: ["short", "medium", "long"], fallback: "medium" }, + { key: "preview", label: "Hover preview", choices: ["on", "off"], fallback: "on" } + ] + }) + // Modules whose options already live on a settings page: the cog jumps there. + readonly property var settingsLinks: ({ + clock: { page: "bar", setting: "Show date" }, + workspaces: { page: "bar", setting: "Workspace style" }, + cava: { page: "media", setting: "Visualizer bars" }, + nowPlaying: { page: "media", setting: "Now playing" }, + tray: { page: "tray", setting: "" }, + volume: { page: "osd", setting: "Step" }, + system: { page: "controlcenter", setting: "" }, + cpu: { page: "metrics", setting: "" }, + cpuTemperature: { page: "metrics", setting: "" }, + gpu: { page: "metrics", setting: "" }, + gpuTemperature: { page: "metrics", setting: "" }, + ram: { page: "metrics", setting: "" }, + storage: { page: "metrics", setting: "" }, + networkThroughput: { page: "metrics", setting: "" } + }) + function option(entry, key) { + const schema = (optionSchemas[entry.id] || []).find(o => o.key === key); + const value = entry.options ? entry.options[key] : undefined; + return schema && schema.choices.includes(value) ? value : schema ? schema.fallback : value; + } +} diff --git a/quickshell/core/PopoutState.qml b/quickshell/core/PopoutState.qml new file mode 100644 index 0000000..e652daa --- /dev/null +++ b/quickshell/core/PopoutState.qml @@ -0,0 +1,141 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Io +import "../services" + +// Shared bar hover popout (Caelestia-style): one surface that morphs between +// anchors. The first hover waits for the hover delay; once a popout or tray menu +// is open, hovering another anchor switches to it immediately. +Singleton { + id: root + property bool open: false + property Item anchor: null + property string kind: "" + property string text: "" + // Kind-specific data, e.g. the window a preview shows. + property var payload: null + property bool popoutHovered: false + property Item hoveredAnchor: null + property var pending: null + property var window: null + // A popout or a tray menu is already showing, so the next hover is instant. + readonly property bool warm: open || TrayService.opened + readonly property int delay: TrayService.options.hoverDelay + + function hover(anchor, kind, text, payload) { + hoveredAnchor = anchor; + leave.stop(); + pending = { + anchor: anchor, + kind: kind, + text: text || "", + payload: payload === undefined ? null : payload + }; + if (!kind) { + intent.stop(); + if (open) + close(); + } else if (warm) + show(); + else + intent.restart(); + } + function unhover(anchor) { + if (hoveredAnchor === anchor) + hoveredAnchor = null; + if (pending && pending.anchor === anchor && !open) + intent.stop(); + leave.restart(); + } + function toggle(anchor, kind, text, payload) { + if (open && root.anchor === anchor) + return close(); + pending = { + anchor: anchor, + kind: kind, + text: text || "", + payload: payload === undefined ? null : payload + }; + show(); + } + function show() { + const p = pending; + intent.stop(); + if (!p || !p.anchor || !p.kind) + return; + anchor = p.anchor; + kind = p.kind; + text = p.text; + payload = p.payload; + open = true; + TrayService.close(); + } + function close() { + open = false; + intent.stop(); + leave.stop(); + } + function setPopoutHovered(inside) { + popoutHovered = inside; + if (inside) + leave.stop(); + else + leave.restart(); + } + onAnchorChanged: if (!anchor) + close() + Timer { + id: intent + interval: root.delay + onTriggered: if (root.hoveredAnchor && root.pending && root.pending.anchor === root.hoveredAnchor) + root.show() + } + // Grace period for crossing the gap between the bar and the popout. + Timer { + id: leave + interval: 260 + onTriggered: if (!root.hoveredAnchor && !root.popoutHovered) + root.close() + } + Connections { + target: TrayService + function onOpenedChanged() { + if (TrayService.opened) + root.close(); + } + } + Connections { + target: ShellState + function onControlCenterOpenChanged() { + if (ShellState.controlCenterOpen) + root.close(); + } + function onSettingsOpenChanged() { + if (ShellState.settingsOpen) + root.close(); + } + function onLauncherOpenChanged() { + if (ShellState.launcherOpen) + root.close(); + } + } + IpcHandler { + target: "popout" + function close(): void { + root.close(); + } + function status(): string { + return JSON.stringify({ + open: root.open, + kind: root.kind, + text: root.text, + anchor: root.anchor ? root.anchor.objectName : "", + visible: !!root.window && root.window.visible, + screen: root.window && root.window.screen ? root.window.screen.name : "", + width: root.window ? root.window.implicitWidth : 0, + height: root.window ? root.window.implicitHeight : 0 + }); + } + } +} diff --git a/quickshell/core/ScreenService.qml b/quickshell/core/ScreenService.qml new file mode 100644 index 0000000..2675050 --- /dev/null +++ b/quickshell/core/ScreenService.qml @@ -0,0 +1,24 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Hyprland + +Singleton { + id: root + property string focusedName: "" + Connections { + target: Hyprland + function onRawEvent(event) { + if (event.name === "focusedmon" || event.name === "focusedmonv2") + root.focusedName = event.parse(2)[0]; + } + } + readonly property var active: Quickshell.screens.find(s => s.name === (focusedName || (Hyprland.focusedMonitor ? Hyprland.focusedMonitor.name : ""))) || primary + readonly property var primary: Quickshell.screens.find(s => s.x === 0 && s.y === 0) || Quickshell.screens[0] || null + function current(candidate) { + return Quickshell.screens.find(s => s === candidate) || active; + } + function resolve(name) { + return (name === "primary" ? primary : Quickshell.screens.find(s => s.name === name)) || primary; + } +} diff --git a/quickshell/core/SettingsRegistry.qml b/quickshell/core/SettingsRegistry.qml new file mode 100644 index 0000000..d70ebf7 --- /dev/null +++ b/quickshell/core/SettingsRegistry.qml @@ -0,0 +1,293 @@ +pragma Singleton +import QtQuick +import Quickshell + +Singleton { + // Sidebar groups, in display order. + readonly property var groups: [ + { + id: "info", + title: "" + }, + { + id: "personalize", + title: "Personalize" + }, + { + id: "shell", + title: "Shell" + }, + { + id: "system", + title: "System" + } + ] + // `keywords` lists setting titles on the page; search results jump to and highlight them. + readonly property var pages: [ + { + id: "appearance", + title: "Appearance", + command: "appearance", + description: "Accent, glass and motion", + phase: 5, + available: true, + group: "personalize", + icon: "󰏘", + keywords: ["Accent source", "Custom accent", "Matugen", "Scheme", "Contrast", "Glass tint", "Regenerate on wallpaper change", "Glass opacity", "Panel opacity", "Border opacity", "Corner radius", "Animation duration", "Animation intensity", "Reduced motion", "Shadows", "Glass highlights", "HyprGlass", "Blur", "Refraction", "Vibrancy"] + }, + { + id: "wallpaper", + title: "Wallpaper", + command: "wallpaper", + description: "Wallpaper picker and palette generation", + phase: 5, + available: true, + group: "personalize", + icon: "󰸉", + keywords: ["Wallpaper picker", "Apply to monitor", "Backend", "Palette monitor", "Wallpaper folders", "Gallery"] + }, + { + id: "widgets", + title: "Desktop widgets", + command: "widgets", + description: "Clocks, system usage, weather and more on the desktop", + phase: 9, + available: true, + group: "personalize", + icon: "󰕰", + keywords: ["Edit widgets", "Add widget", "Snap to grid", "Clock widget", "Calendar", "Weather", "Note", "Visualizer"] + }, + { + id: "bar", + title: "Bar", + command: "bar", + description: "Bar modules and tray preferences", + phase: 5, + available: true, + group: "shell", + icon: "󰕮", + keywords: ["Bar height", "Margin", "Modules", "Show date", "24-hour time", "Show seconds", "Workspace count", "Workspace style", "Pacman", "Roman numerals", "Clock"] + }, + { + id: "tray", + title: "Bar / Tray", + command: "tray", + description: "Tray icons and application menus", + phase: 2, + available: true, + group: "shell", + icon: "󰀻", + keywords: ["System tray", "Hover menus", "Hover delay", "Icon size", "Spacing", "Background"] + }, + { + id: "dock", + title: "Dock", + command: "dock", + description: "Pinned apps, visibility and placement", + phase: 3, + available: true, + group: "shell", + icon: "󱂩", + keywords: ["Enable dock", "Monitor", "Position", "Visibility", "Icon size", "Spacing", "Margin", "Magnification", "Magnification strength", "Animation speed", "Show running apps", "Running indicators", "Tooltips", "Terminal launcher", "Pinned applications"] + }, + { + id: "launcher", + title: "Launcher", + command: "launcher", + description: "Search and command palette preferences", + phase: 4, + available: true, + group: "shell", + icon: "󰵆", + keywords: ["Width", "Maximum results", "Show descriptions"] + }, + { + id: "controlcenter", + title: "Control Center", + command: "controlcenter", + description: "System controls and modules", + phase: 7, + available: true, + group: "shell", + icon: "󰔡", + keywords: ["Panel width", "Modules"] + }, + { + id: "dashboard", + title: "Dashboard", + command: "dashboard", + description: "Tabbed dashboard: overview, media, performance and power", + phase: 9, + available: true, + group: "shell", + icon: "󰕮", + keywords: ["Dashboard", "Placement", "Position", "Tab order", "Open from clock", "Remember last tab", "Equalizer", "EasyEffects", "Power menu"] + }, + { + id: "plugins", + title: "Plugins", + command: "plugins", + description: "Omarchy and Noctalia plugins in the glassMxrph style", + phase: 9, + available: true, + group: "shell", + icon: "󰐱", + keywords: ["Plugins", "Install plugin", "Omarchy", "Noctalia", "Marketplace", "Add to bar", "Remove plugin"] + }, + { + id: "osd", + title: "On-screen display", + command: "osd", + description: "Volume and brightness overlay", + phase: 9, + available: true, + group: "shell", + icon: "󰍩", + keywords: ["Animation", "OSD", "Volume overlay", "Show overlay", "Position", "Duration", "Step"] + }, + { + id: "media", + title: "Media", + command: "media", + description: "Music widget and player preferences", + phase: 6, + available: true, + group: "shell", + icon: "󰝚", + keywords: ["Now playing", "Visualizer", "Cava", "Visualizer bars", "Visualizer style", "Hide while paused", "Album artwork", "Track progress", "Album name", "Visualizer in cards", "Preferred player"] + }, + { + id: "metrics", + title: "System Metrics", + command: "metrics", + description: "Sensors, desktop widget and diagnostics", + phase: 8, + available: true, + group: "shell", + icon: "󰓅", + keywords: ["Desktop widget", "Monitor", "Position", "Widget scale", "Sampling interval", "GPU", "Network interface", "Storage paths"] + }, + { + id: "displays", + title: "Displays", + command: "display", + description: "Display preferences", + phase: 5, + available: true, + group: "system", + icon: "󰍹", + keywords: ["Brightness", "Backlight device", "Night Light", "Night temperature", "Providers"] + }, + { + id: "audio", + title: "Audio", + command: "audio", + description: "Playback and microphone controls", + phase: 7, + available: true, + group: "system", + icon: "󰕾", + keywords: ["Volume", "Microphone", "Output device", "Input device"] + }, + { + id: "network", + title: "Network", + command: "network", + description: "Network connections", + phase: 7, + available: true, + group: "system", + icon: "󰖩", + keywords: ["Wi-Fi", "Advanced connections", "VPN"] + }, + { + id: "bluetooth", + title: "Bluetooth", + command: "bluetooth", + description: "Bluetooth devices", + phase: 7, + available: true, + group: "system", + icon: "󰂯", + keywords: ["Adapter", "Devices", "Pairing"] + }, + { + id: "lock", + title: "Lock screen", + command: "lock", + description: "Glass lock screen and password check", + phase: 9, + available: true, + group: "system", + icon: "󰌾", + keywords: ["Lock now", "Preview lock screen", "Test password", "Backdrop", "Glass", "PAM", "Now Playing on lock screen", "Power buttons"] + }, + { + id: "notifications", + title: "Notifications", + command: "notifications", + description: "Notification preferences", + phase: 5, + available: true, + group: "system", + icon: "󰂚", + keywords: ["Do not disturb"] + }, + { + id: "power", + title: "Power", + command: "power", + description: "Power preferences", + phase: 7, + available: true, + group: "system", + icon: "󰐥", + keywords: ["Power profile", "Lock command", "Suspend", "Reboot", "Shut down"] + }, + { + id: "about", + title: "GlassMxrph", + command: "about", + description: "About glassMxrph, versions and environment", + phase: 1, + available: true, + group: "info", + icon: "󰋽", + image: Qt.resolvedUrl("../assets/glassmxrph-256.png"), + keywords: ["About", "Version", "GlassMxrph"] + } + ] + function page(id) { + return pages.find(p => p.id === id || p.command === id) || null; + } + // Page and setting matches for the settings search, best first. + function search(text) { + const query = String(text || "").trim().toLowerCase(); + if (!query) + return []; + const results = []; + for (const p of pages) { + const title = p.title.toLowerCase(); + if (title.includes(query) || p.description.toLowerCase().includes(query)) + results.push({ + page: p.id, + title: p.title, + detail: p.description, + icon: p.icon, + setting: "", + rank: title.startsWith(query) ? 0 : 1 + }); + for (const keyword of p.keywords || []) + if (keyword.toLowerCase().includes(query)) + results.push({ + page: p.id, + title: keyword, + detail: p.title, + icon: p.icon, + setting: keyword, + rank: keyword.toLowerCase().startsWith(query) ? 2 : 3 + }); + } + return results.sort((a, b) => a.rank - b.rank).slice(0, 40); + } +} diff --git a/quickshell/core/ShellState.qml b/quickshell/core/ShellState.qml new file mode 100644 index 0000000..aabeb73 --- /dev/null +++ b/quickshell/core/ShellState.qml @@ -0,0 +1,112 @@ +pragma Singleton +import QtQuick +import Quickshell + +Singleton { + property bool wallpaperPickerOpen: false + property var wallpaperScreen: null + property var wallpaperWindow: null + function openWallpaperPicker() { + settingsOpen=false;launcherOpen=false;controlCenterOpen=false;dashboardOpen=false; + wallpaperScreen=activeScreen();wallpaperPickerOpen=true; + } + property var systemPills: [] + property bool controlCenterOpen: false + property var controlCenterScreen: null + property var controlCenterWindow: null + function openControlCenter() { + wallpaperPickerOpen=false; + dashboardOpen = false; + if (controlCenterOpen) + return; + launcherOpen = false; + settingsOpen = false; + controlCenterScreen = activeScreen(); + controlCenterOpen = true; + } + function toggleControlCenter() { + if (controlCenterOpen) + controlCenterOpen = false; + else + openControlCenter(); + } + // Caelestia-style dashboard; `dashboardTab` is a tab id, not an index. + property bool dashboardOpen: false + property var dashboardScreen: null + property var dashboardWindow: null + property string dashboardTab: "" + function openDashboard(tab) { + wallpaperPickerOpen = false; + controlCenterOpen = false; + launcherOpen = false; + settingsOpen = false; + if (tab) + dashboardTab = tab; + if (!dashboardOpen) + dashboardScreen = activeScreen(); + dashboardOpen = true; + } + function toggleDashboard(tab) { + if (dashboardOpen && (!tab || tab === dashboardTab)) + dashboardOpen = false; + else + openDashboard(tab); + } + property bool launcherOpen: false + property var launcherScreen: null + function activeScreen() { + return ScreenService.active; + } + function openLauncher() { + wallpaperPickerOpen=false; + dashboardOpen = false; + if (launcherOpen) + return; + controlCenterOpen = false; + settingsOpen = false; + launcherScreen = activeScreen(); + launcherOpen = true; + } + function toggleLauncher() { + if (launcherOpen) + launcherOpen = false; + else + openLauncher(); + } + property var settingsWindow: null + property bool settingsOpen: false + property string settingsPage: "appearance" + // Setting title flashed after a settings search jump; the serial re-triggers repeats. + property string settingsHighlight: "" + property int settingsHighlightSerial: 0 + function revealSetting(page, title) { + openSettings(page); + settingsHighlight = title || ""; + settingsHighlightSerial++; + } + property var targetScreen: null + property var osdWindow: null + // Raised by Lock buttons when the built-in lock screen is enabled. + signal lockRequested + function requestLock() { + lockRequested(); + } + function openSettings(page) { + wallpaperPickerOpen=false; + dashboardOpen = false; + controlCenterOpen = false; + launcherOpen = false; + const destination = SettingsRegistry.page(page || "appearance"); + settingsPage = destination ? destination.id : "about"; + if (!settingsOpen) { + targetScreen = activeScreen(); + } + settingsOpen = true; + } + function toggleSettings() { + if (settingsOpen) + settingsOpen = false; + else + openSettings("appearance"); + } +} diff --git a/quickshell/core/qmldir b/quickshell/core/qmldir new file mode 100644 index 0000000..5d1db24 --- /dev/null +++ b/quickshell/core/qmldir @@ -0,0 +1,8 @@ +singleton ModuleRegistry 1.0 ModuleRegistry.qml +singleton ShellState 1.0 ShellState.qml +singleton ScreenService 1.0 ScreenService.qml +singleton SettingsRegistry 1.0 SettingsRegistry.qml +singleton PopoutState 1.0 PopoutState.qml +singleton DashboardRegistry 1.0 DashboardRegistry.qml +singleton BarDrawers 1.0 BarDrawers.qml +singleton BarLayout 1.0 BarLayout.qml diff --git a/quickshell/dashboard/DashButton.qml b/quickshell/dashboard/DashButton.qml new file mode 100644 index 0000000..c5b1d67 --- /dev/null +++ b/quickshell/dashboard/DashButton.qml @@ -0,0 +1,54 @@ +import QtQuick +import "../theme" + +// Round glyph button used by the media controls and the power tab. +Rectangle { + id: root + property string glyph + property string fallback + property int size: 36 + property real glyphScale: 0.45 + property bool accented: false + property bool active: false + property bool danger: false + property bool interactive: true + signal clicked + implicitWidth: size + implicitHeight: size + radius: size / 2 + opacity: interactive ? 1 : 0.4 + color: accented ? (area.pressed ? Theme.accentPressed : area.containsMouse ? Theme.accentHover : Theme.accent) + : danger && area.containsMouse ? Qt.alpha("#ff5f57", 0.85) + : active ? Qt.alpha(Theme.accent, 0.28) + : area.containsMouse ? Theme.hover : Theme.fill + border.width: accented ? 0 : 1 + border.color: active ? Qt.alpha(Theme.accent, 0.6) : Theme.hairline + scale: area.pressed ? 1 - 0.06 * Theme.intensity : 1 + Behavior on color { + ColorAnimation { + duration: Theme.duration / 2 + } + } + Behavior on scale { + NumberAnimation { + duration: Theme.duration / 2 + easing.type: Easing.OutCubic + } + } + Text { + anchors.centerIn: parent + text: Icons.available && root.glyph ? root.glyph : root.fallback + font.family: Icons.available && root.glyph ? Icons.family : "" + font.pixelSize: Math.round(root.size * root.glyphScale) + color: root.accented ? Theme.accentText : root.active ? Theme.accentVivid : Theme.text + } + MouseArea { + id: area + anchors.fill: parent + hoverEnabled: true + enabled: root.interactive + cursorShape: Qt.PointingHandCursor + onClicked: root.clicked() + } + Accessible.role: Accessible.Button +} diff --git a/quickshell/dashboard/DashCard.qml b/quickshell/dashboard/DashCard.qml new file mode 100644 index 0000000..208f01a --- /dev/null +++ b/quickshell/dashboard/DashCard.qml @@ -0,0 +1,10 @@ +import QtQuick +import "../theme" + +// Inner dashboard card: a tinted, hairline-bordered plate on the glass panel. +Rectangle { + radius: Math.max(12, Theme.radius * 0.75) + color: Theme.surfaceVariant + border.width: 1 + border.color: Theme.hairline +} diff --git a/quickshell/dashboard/Dashboard.qml b/quickshell/dashboard/Dashboard.qml new file mode 100644 index 0000000..d7270a3 --- /dev/null +++ b/quickshell/dashboard/Dashboard.qml @@ -0,0 +1,294 @@ +pragma ComponentBehavior: Bound +import QtQuick +import Quickshell +import Quickshell.Io +import Quickshell.Wayland +import "../components" +import "../core" +import "../services" +import "../theme" + +// Caelestia-style dashboard: tabbed glass panel below the bar. The layer is +// sized to the panel (HyprGlass shapes glass from the layer box) and morphs as +// tabs of different sizes slide in. +// qmllint disable uncreatable-type +PanelWindow { + // qmllint enable uncreatable-type + id: root + screen: ScreenService.current(ShellState.dashboardScreen) + readonly property var options: ConfigService.ready ? ConfigService.data.dashboard : null + readonly property string position: options ? options.position : "top-center" + readonly property var tabs: options ? options.tabs.filter(t => t.enabled && !!DashboardRegistry.entry(t.id)).map(t => t.id) : [] + readonly property int index: Math.max(0, tabs.indexOf(ShellState.dashboardTab)) + readonly property string currentId: tabs[index] || "" + readonly property int padding: 16 + readonly property real screenWidth: screen ? screen.width : 1920 + readonly property real screenHeight: screen ? screen.height : 1080 + function select(i) { + if (tabs.length) + ShellState.dashboardTab = tabs[(i + tabs.length) % tabs.length]; + } + // Top placements hang from the bar as a drawer; "center" floats. + readonly property bool attached: position !== "center" + anchors { + top: root.attached + left: root.position === "top-left" + right: root.position === "top-right" + } + // The layer starts at the screen top so the bar join is inside its box. + // Margins is present at runtime but unresolved in 0.3.1 qmltypes. + // qmllint disable unqualified unresolved-type + margins { + left: BarDrawers.margin + BarDrawers.radius + right: BarDrawers.margin + BarDrawers.radius + } + // qmllint enable unqualified unresolved-type + implicitWidth: Math.max(120, Math.round(panel.width)) + implicitHeight: Math.max(60, Math.round((attached ? BarDrawers.bottom : 0) + panel.contentHeight)) + visible: ShellState.dashboardOpen || panel.shown + color: Theme.transparent + exclusionMode: ExclusionMode.Ignore + WlrLayershell.layer: WlrLayer.Overlay + WlrLayershell.namespace: "glassMxrph-dashboard" + WlrLayershell.keyboardFocus: ShellState.dashboardOpen ? WlrKeyboardFocus.Exclusive : WlrKeyboardFocus.None + Component.onCompleted: ShellState.dashboardWindow = root + Component.onDestruction: ShellState.dashboardWindow = null + Connections { + target: ShellState + function onDashboardOpenChanged() { + if (!ShellState.dashboardOpen) { + PowerService.cancel(); + if (root.options && !root.options.rememberTab) + ShellState.dashboardTab = ""; + } + } + } + onOptionsChanged: if (options && !options.enabled) + ShellState.dashboardOpen = false + + // Exclusive focus routes outside clicks here (see ControlCenter). + MouseArea { + objectName: "dashboardOutside" + x: -20000 + y: -20000 + width: 40000 + height: 40000 + onPressed: ShellState.dashboardOpen = false + } + + BarDrawer { + id: panel + objectName: "dashboardSurface" + y: root.attached ? BarDrawers.bottom : 0 + open: ShellState.dashboardOpen + attached: root.attached + drawerId: "dashboard" + screenName: root.screen ? root.screen.name : "" + screenX: root.position === "top-left" ? BarDrawers.margin + BarDrawers.radius : root.position === "top-right" ? root.screenWidth - BarDrawers.margin - BarDrawers.radius - width : (root.screenWidth - width) / 2 + readonly property Loader page: { + pages.count; + return pages.itemAt(root.index) as Loader; + } + readonly property Item pageItem: page ? page.item as Item : null + readonly property real pageWidth: pageItem ? pageItem.implicitWidth : 600 + readonly property real pageHeight: pageItem ? pageItem.implicitHeight : 300 + readonly property bool morph: progress > 0.05 && Theme.duration > 0 + readonly property real sideSpace: 2 * (BarDrawers.margin + BarDrawers.radius + ear) + contentWidth: Math.min(root.screenWidth - sideSpace, pageWidth + 2 * root.padding) + contentHeight: Math.min(root.screenHeight - BarDrawers.bottom - 20, tabBar.height + pageHeight + 3 * root.padding) + Behavior on contentWidth { + enabled: panel.morph + NumberAnimation { + duration: Theme.duration * 1.4 + easing.type: Easing.BezierSpline + easing.bezierCurve: [0.2, 0, 0, 1, 1, 1] + } + } + Behavior on contentHeight { + enabled: panel.morph + NumberAnimation { + duration: Theme.duration * 1.4 + easing.type: Easing.BezierSpline + easing.bezierCurve: [0.2, 0, 0, 1, 1, 1] + } + } + focus: ShellState.dashboardOpen + Keys.onEscapePressed: ShellState.dashboardOpen = false + Keys.onLeftPressed: root.select(root.index - 1) + Keys.onRightPressed: root.select(root.index + 1) + Keys.onTabPressed: root.select(root.index + 1) + Keys.onBacktabPressed: root.select(root.index - 1) + Keys.onPressed: event => { + const n = event.key - Qt.Key_1; + if (n >= 0 && n < root.tabs.length) { + root.select(n); + event.accepted = true; + } + } + + Item { + id: tabBar + objectName: "dashboardTabs" + x: root.padding + y: root.padding + width: panel.contentWidth - 2 * root.padding + height: 46 + readonly property real tabWidth: root.tabs.length ? width / root.tabs.length : width + Row { + anchors.fill: parent + Repeater { + model: root.tabs + Item { + id: tab + required property string modelData + required property int index + readonly property var entry: DashboardRegistry.entry(modelData) + readonly property bool current: root.index === index + objectName: "dashTab-" + modelData + width: tabBar.tabWidth + height: tabBar.height - 4 + Rectangle { + anchors.fill: parent + anchors.margins: 2 + radius: height / 2 + color: tabArea.containsMouse && !tab.current ? Theme.hover : Theme.transparent + Behavior on color { + ColorAnimation { + duration: Theme.duration / 2 + } + } + } + Row { + anchors.centerIn: parent + spacing: 8 + Text { + anchors.verticalCenter: parent.verticalCenter + text: Icons.available ? tab.entry.glyph : tab.entry.fallback + font.family: Icons.available ? Icons.family : "" + font.pixelSize: 16 + color: tab.current ? Theme.accentVivid : Theme.textSecondary + Behavior on color { + ColorAnimation { + duration: Theme.duration + } + } + } + Text { + anchors.verticalCenter: parent.verticalCenter + text: tab.entry.title + font.pixelSize: 13 + font.weight: tab.current ? Font.DemiBold : Font.Normal + color: tab.current ? Theme.text : Theme.textSecondary + } + } + MouseArea { + id: tabArea + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: root.select(tab.index) + onWheel: event => root.select(root.index + (event.angleDelta.y < 0 ? 1 : -1)) + } + Accessible.role: Accessible.PageTab + Accessible.name: entry.title + } + } + } + Rectangle { + id: indicator + anchors.bottom: parent.bottom + height: 3 + radius: 1.5 + width: Math.min(tabBar.tabWidth * 0.5, 72) + x: tabBar.tabWidth * root.index + (tabBar.tabWidth - width) / 2 + color: Theme.accentVivid + Behavior on x { + enabled: panel.morph + NumberAnimation { + duration: Theme.duration * 1.3 + easing.type: Easing.OutCubic + } + } + } + Rectangle { + anchors.top: parent.bottom + anchors.topMargin: 0 + width: parent.width + height: 1 + color: Theme.hairline + } + } + + // Pages sit side by side; the strip slides to the current one. + Item { + id: viewport + objectName: "dashboardViewport" + x: root.padding + y: tabBar.y + tabBar.height + root.padding + width: panel.contentWidth - 2 * root.padding + height: panel.contentHeight - y - root.padding + clip: true + Row { + id: strip + spacing: root.padding * 2 + x: panel.page ? -panel.page.x : 0 + Behavior on x { + enabled: panel.morph + NumberAnimation { + duration: Theme.duration * 1.3 + easing.type: Easing.OutCubic + } + } + Repeater { + id: pages + model: root.tabs + Loader { + id: pageLoader + required property string modelData + required property int index + objectName: "dashPage-" + modelData + active: ShellState.dashboardOpen || panel.visible + source: DashboardRegistry.entry(modelData).source + // Off-screen tabs fade so the slide reads as a swap. + opacity: root.index === index ? 1 : 0.25 + Behavior on opacity { + NumberAnimation { + duration: Theme.duration + } + } + onLoaded: { + item.current = Qt.binding(() => ShellState.dashboardOpen && root.index === pageLoader.index); + if ("showEqualizer" in item) + item.showEqualizer = Qt.binding(() => !!root.options && root.options.easyEffects); + } + } + } + } + } + } + + IpcHandler { + target: "dashboard" + function toggle(tab: string): void { + ShellState.toggleDashboard(tab); + } + function open(tab: string): void { + ShellState.openDashboard(tab); + } + function close(): void { + ShellState.dashboardOpen = false; + } + function status(): string { + return JSON.stringify({ + open: ShellState.dashboardOpen, + visible: root.visible, + tab: root.currentId, + tabs: root.tabs, + position: root.position, + screen: root.screen ? root.screen.name : "", + width: root.implicitWidth, + height: root.implicitHeight + }); + } + } +} diff --git a/quickshell/dashboard/Equalizer.qml b/quickshell/dashboard/Equalizer.qml new file mode 100644 index 0000000..6d47279 --- /dev/null +++ b/quickshell/dashboard/Equalizer.qml @@ -0,0 +1,206 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Layouts +import "../components" +import "../services" +import "../theme" + +// EasyEffects equalizer (serpantinum-style): ten ±12 dB bands, eight presets. +// Presets apply at once; dragged bands wait for Apply. +DashCard { + id: root + objectName: "dashEqualizer" + readonly property bool usable: EasyEffectsService.installed + implicitWidth: 400 + implicitHeight: body.implicitHeight + 32 + function freq(f) { + return f >= 1000 ? f / 1000 + "k" : String(f); + } + ColumnLayout { + id: body + anchors.left: parent.left + anchors.right: parent.right + anchors.top: parent.top + anchors.margins: 16 + spacing: 12 + RowLayout { + Layout.fillWidth: true + spacing: 10 + ColumnLayout { + Layout.fillWidth: true + spacing: 0 + Text { + text: "Equalizer" + color: Theme.text + font.pixelSize: 15 + font.weight: Font.DemiBold + } + Text { + text: !EasyEffectsService.known ? "Checking EasyEffects…" : !root.usable ? "EasyEffects is not installed" : EasyEffectsService.error ? EasyEffectsService.error : !EasyEffectsService.running ? "EasyEffects · starts on apply" : EasyEffectsService.bypass ? "EasyEffects · bypassed" : "EasyEffects · " + EasyEffectsService.preset + color: EasyEffectsService.error ? Theme.urgent : Theme.textSecondary + font.pixelSize: 11 + elide: Text.ElideRight + Layout.fillWidth: true + } + } + GlassToggle { + objectName: "eqEnabled" + enabled: root.usable && EasyEffectsService.running + checked: !EasyEffectsService.bypass + onToggled: EasyEffectsService.setBypass(!checked) + Accessible.name: "Effects enabled" + } + GlassButton { + objectName: "eqApply" + implicitHeight: 30 + text: EasyEffectsService.busy ? "Applying…" : EasyEffectsService.pending ? "Apply" : "Saved" + accented: EasyEffectsService.pending + enabled: root.usable && EasyEffectsService.pending && !EasyEffectsService.busy + onClicked: EasyEffectsService.apply() + } + } + Row { + id: bands + Layout.alignment: Qt.AlignHCenter + spacing: 6 + opacity: root.usable ? 1 : 0.45 + Repeater { + model: 10 + Band {} + } + } + GridLayout { + Layout.fillWidth: true + columns: 4 + rowSpacing: 6 + columnSpacing: 6 + opacity: root.usable ? 1 : 0.45 + Repeater { + model: EasyEffectsService.presetNames + Rectangle { + id: chip + required property string modelData + readonly property bool active: EasyEffectsService.preset === modelData + objectName: "eqPreset-" + modelData + Layout.fillWidth: true + Layout.preferredWidth: 1 + implicitHeight: 28 + radius: 14 + color: active ? Theme.accent : chipArea.containsMouse ? Theme.hover : Theme.fill + border.width: active ? 0 : 1 + border.color: Theme.hairline + Behavior on color { + ColorAnimation { + duration: Theme.duration + } + } + Text { + anchors.centerIn: parent + text: chip.modelData + color: chip.active ? Theme.accentText : Theme.text + font.pixelSize: 12 + } + MouseArea { + id: chipArea + anchors.fill: parent + hoverEnabled: true + enabled: root.usable + cursorShape: Qt.PointingHandCursor + onClicked: EasyEffectsService.usePreset(chip.modelData) + } + } + } + } + } + + // Vertical ±12 dB slider: drag or scroll; the fill grows from the 0 dB line. + component Band: Column { + id: band + required property int index + readonly property real gain: EasyEffectsService.bands[index] || 0 + objectName: "eqBand" + index + spacing: 4 + Text { + anchors.horizontalCenter: parent.horizontalCenter + text: (band.gain > 0 ? "+" : "") + Math.round(band.gain) + color: band.gain === 0 ? Theme.textSecondary : Theme.text + font.pixelSize: 10 + font.features: { + "tnum": 1 + } + } + Item { + id: track + width: 30 + height: 120 + readonly property real zero: height / 2 + property real shown: band.gain + Behavior on shown { + enabled: !drag.pressed + NumberAnimation { + duration: Theme.duration * 1.5 + easing.type: Easing.OutCubic + } + } + readonly property real knobY: zero - shown / 12 * (height / 2 - 8) + Rectangle { + anchors.horizontalCenter: parent.horizontalCenter + width: 6 + height: parent.height + radius: 3 + color: Qt.alpha(Theme.text, 0.1) + } + Rectangle { + anchors.horizontalCenter: parent.horizontalCenter + width: 6 + y: Math.min(track.zero, track.knobY) + height: Math.abs(track.knobY - track.zero) + radius: 3 + color: Theme.accentVivid + } + Rectangle { + anchors.horizontalCenter: parent.horizontalCenter + width: 14 + height: 1 + y: track.zero + color: Theme.hairline + } + Rectangle { + anchors.horizontalCenter: parent.horizontalCenter + y: track.knobY - height / 2 + width: drag.pressed ? 20 : 16 + height: width + radius: width / 2 + color: Theme.text + border.width: 2 + border.color: Theme.accentVivid + Behavior on width { + NumberAnimation { + duration: Theme.duration / 2 + } + } + } + MouseArea { + id: drag + anchors.fill: parent + enabled: root.usable + cursorShape: Qt.SizeVerCursor + function set(y) { + EasyEffectsService.setBand(band.index, (track.zero - y) / (track.height / 2 - 8) * 12); + } + onPressed: event => set(event.y) + onPositionChanged: event => { + if (pressed) + set(event.y); + } + onWheel: event => EasyEffectsService.setBand(band.index, band.gain + (event.angleDelta.y > 0 ? 1 : -1)) + } + } + Text { + anchors.horizontalCenter: parent.horizontalCenter + text: root.freq(EasyEffectsService.frequencies[band.index] || 0) + color: Theme.textSecondary + font.pixelSize: 10 + } + } +} diff --git a/quickshell/dashboard/Gauge.qml b/quickshell/dashboard/Gauge.qml new file mode 100644 index 0000000..698ea79 --- /dev/null +++ b/quickshell/dashboard/Gauge.qml @@ -0,0 +1,74 @@ +import QtQuick +import "../theme" + +// Ring gauge (0–100) with a centred label; null values draw an empty ring. +Item { + id: root + property var value: null + property int size: 92 + property real thickness: 8 + property color color: Theme.accentVivid + property string label: value === null || value === undefined || !Number.isFinite(value) ? "—" : Math.round(value) + "%" + property string caption: "" + implicitWidth: size + implicitHeight: size + readonly property real target: Number.isFinite(value) ? Math.max(0, Math.min(100, value)) : 0 + // Only visible jumps animate: easing every small sample change kept the + // window rendering at the display's refresh rate. + property real shown + property bool easeJump: false + Component.onCompleted: shown = target + onTargetChanged: { + easeJump = Math.abs(target - shown) >= 2; + shown = target; + } + Behavior on shown { + enabled: root.easeJump + NumberAnimation { + duration: Theme.duration * 2 + easing.type: Easing.OutCubic + } + } + onShownChanged: canvas.requestPaint() + onColorChanged: canvas.requestPaint() + Canvas { + id: canvas + anchors.fill: parent + onPaint: { + const c = getContext("2d"), r = (width - root.thickness) / 2, start = Math.PI * 0.75, sweep = Math.PI * 1.5; + c.reset(); + c.lineCap = "round"; + c.lineWidth = root.thickness; + c.strokeStyle = Qt.alpha(Theme.text, 0.1); + c.beginPath(); + c.arc(width / 2, height / 2, r, start, start + sweep); + c.stroke(); + if (root.shown > 0) { + c.strokeStyle = root.color; + c.beginPath(); + c.arc(width / 2, height / 2, r, start, start + sweep * root.shown / 100); + c.stroke(); + } + } + } + Column { + anchors.centerIn: parent + Text { + anchors.horizontalCenter: parent.horizontalCenter + text: root.label + color: Theme.text + font.pixelSize: Math.round(root.size * 0.21) + font.weight: Font.DemiBold + font.features: { + "tnum": 1 + } + } + Text { + anchors.horizontalCenter: parent.horizontalCenter + visible: text !== "" + text: root.caption + color: Theme.textSecondary + font.pixelSize: Math.max(9, Math.round(root.size * 0.11)) + } + } +} diff --git a/quickshell/dashboard/Sparkline.qml b/quickshell/dashboard/Sparkline.qml new file mode 100644 index 0000000..e7393ec --- /dev/null +++ b/quickshell/dashboard/Sparkline.qml @@ -0,0 +1,39 @@ +import QtQuick +import "../theme" + +// Filled line graph of the last samples; `max` 0 scales to the largest value. +Canvas { + id: root + property var values: [] + property real max: 100 + property color color: Theme.accentVivid + property int samples: 60 + onValuesChanged: requestPaint() + onColorChanged: requestPaint() + onWidthChanged: requestPaint() + onHeightChanged: requestPaint() + onPaint: { + const c = getContext("2d"); + c.reset(); + const v = values.filter(x => x !== null && x !== undefined && Number.isFinite(x)); + if (v.length < 2) + return; + const top = root.max > 0 ? root.max : Math.max(1, ...v) * 1.15, step = width / (root.samples - 1), offset = width - (v.length - 1) * step; + const y = x => height - 2 - (height - 4) * Math.min(1, x / top); + c.beginPath(); + c.moveTo(offset, height); + v.forEach((x, i) => c.lineTo(offset + i * step, y(x))); + c.lineTo(offset + (v.length - 1) * step, height); + c.closePath(); + const g = c.createLinearGradient(0, 0, 0, height); + g.addColorStop(0, Qt.alpha(root.color, 0.35)); + g.addColorStop(1, Qt.alpha(root.color, 0)); + c.fillStyle = g; + c.fill(); + c.beginPath(); + v.forEach((x, i) => i ? c.lineTo(offset + i * step, y(x)) : c.moveTo(offset, y(x))); + c.strokeStyle = root.color; + c.lineWidth = 1.6; + c.stroke(); + } +} diff --git a/quickshell/dashboard/tabs/MediaTab.qml b/quickshell/dashboard/tabs/MediaTab.qml new file mode 100644 index 0000000..17a3644 --- /dev/null +++ b/quickshell/dashboard/tabs/MediaTab.qml @@ -0,0 +1,282 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Layouts +import Quickshell.Services.Mpris +import Quickshell.Widgets +import ".." +import "../../components" +import "../../services" +import "../../theme" + +// Now playing with full transport controls, a Cava strip and the EasyEffects equalizer. +Item { + id: root + property bool current: false + property bool showEqualizer: true + implicitWidth: row.implicitWidth + implicitHeight: row.implicitHeight + readonly property var player: MediaService.player + // Streams report no length or absurd ones; show them as live. + readonly property bool live: MediaService.length <= 0 || MediaService.length > 7 * 86400 + property bool subscribed: false + onCurrentChanged: sync() + Component.onCompleted: sync() + Component.onDestruction: if (subscribed) { + MediaService.progressConsumers--; + CavaService.widgetConsumers--; + } + function sync() { + if (current === subscribed) + return; + MediaService.progressConsumers += current ? 1 : -1; + CavaService.widgetConsumers += current ? 1 : -1; + subscribed = current; + if (current) + EasyEffectsService.refresh(); + } + + RowLayout { + id: row + spacing: 12 + DashCard { + id: playerCard + objectName: "dashPlayer" + Layout.preferredWidth: 400 + Layout.preferredHeight: Math.max(330 + (MediaService.players.length > 1 ? 30 : 0), root.showEqualizer ? equalizer.implicitHeight : 0) + RowLayout { + anchors.fill: parent + anchors.margins: 18 + spacing: 18 + ClippingRectangle { + Layout.alignment: Qt.AlignTop + Layout.preferredWidth: 150 + Layout.preferredHeight: 150 + radius: 20 + color: Theme.fill + Text { + anchors.centerIn: parent + visible: art.status !== Image.Ready + text: Icons.available ? "󰝚" : "♪" + font.family: Icons.available ? Icons.family : "" + font.pixelSize: 52 + color: Theme.textSecondary + } + Image { + id: art + anchors.fill: parent + source: MediaService.artwork + sourceSize: Qt.size(300, 300) + fillMode: Image.PreserveAspectCrop + asynchronous: true + opacity: status === Image.Ready ? 1 : 0 + Behavior on opacity { + NumberAnimation { + duration: Theme.duration + } + } + } + } + ColumnLayout { + Layout.fillWidth: true + Layout.fillHeight: true + spacing: 4 + Text { + Layout.fillWidth: true + text: MediaService.title + color: Theme.text + font.pixelSize: 18 + font.weight: Font.DemiBold + elide: Text.ElideRight + maximumLineCount: 2 + wrapMode: Text.Wrap + } + Text { + Layout.fillWidth: true + text: MediaService.artist + color: Theme.textSecondary + font.pixelSize: 13 + elide: Text.ElideRight + } + Text { + Layout.fillWidth: true + visible: text !== "" + text: MediaService.album + color: Theme.textSecondary + opacity: 0.75 + font.pixelSize: 12 + elide: Text.ElideRight + } + // Cava bars for system audio while playing. The fixed-size + // wrapper keeps bar heights out of the layout: otherwise each + // Cava frame re-polished the column and rendered twice. + Item { + Layout.fillWidth: true + Layout.topMargin: 8 + Layout.preferredHeight: 34 + Row { + anchors.fill: parent + spacing: 3 + opacity: MediaService.playing ? 1 : 0.25 + Behavior on opacity { + NumberAnimation { + duration: Theme.duration + } + } + Repeater { + model: 24 + Rectangle { + required property int index + anchors.bottom: parent.bottom + width: 4 + radius: 2 + height: Math.max(3, 34 * (MediaService.playing ? (CavaService.bars[index] || 0) : 0.05)) + color: Qt.alpha(Theme.accentVivid, 0.85) + // No height Behavior: Cava already smooths at 30 fps, and + // interpolating raised rendering to the display rate. + } + } + } + } + Item { + Layout.fillHeight: true + } + } + } + ColumnLayout { + anchors.left: parent.left + anchors.right: parent.right + anchors.bottom: parent.bottom + anchors.margins: 18 + spacing: 6 + GlassSlider { + objectName: "dashSeek" + Layout.fillWidth: true + from: 0 + to: root.live ? 1 : Math.max(1, MediaService.length) + value: root.live ? 0 : MediaService.position + enabled: MediaService.seekable && !root.live + opacity: root.live ? 0.4 : 1 + onMoved: MediaService.seek(value) + } + RowLayout { + Layout.fillWidth: true + Layout.topMargin: -6 + Text { + text: MediaService.time(MediaService.position) + color: Theme.textSecondary + font.pixelSize: 11 + font.features: { + "tnum": 1 + } + } + Item { + Layout.fillWidth: true + } + Text { + text: root.live ? "LIVE" : MediaService.time(MediaService.length) + color: Theme.textSecondary + font.pixelSize: 11 + font.features: { + "tnum": 1 + } + } + } + Row { + Layout.alignment: Qt.AlignHCenter + spacing: 12 + DashButton { + objectName: "dashShuffle" + anchors.verticalCenter: parent.verticalCenter + glyph: "󰒝" + fallback: "⤨" + size: 34 + active: !!root.player && root.player.shuffle + interactive: !!root.player && root.player.shuffleSupported && root.player.canControl + onClicked: root.player.shuffle = !root.player.shuffle + Accessible.name: "Shuffle" + } + DashButton { + anchors.verticalCenter: parent.verticalCenter + glyph: "󰒮" + fallback: "‹" + size: 40 + interactive: !!root.player && root.player.canGoPrevious + onClicked: MediaService.previous() + Accessible.name: "Previous track" + } + DashButton { + objectName: "dashToggle" + size: 54 + accented: true + glyph: MediaService.playing ? "󰏤" : "󰐊" + fallback: MediaService.playing ? "Ⅱ" : "▶" + interactive: !!root.player && root.player.canTogglePlaying + onClicked: MediaService.toggle() + Accessible.name: "Play or pause" + } + DashButton { + anchors.verticalCenter: parent.verticalCenter + glyph: "󰒭" + fallback: "›" + size: 40 + interactive: !!root.player && root.player.canGoNext + onClicked: MediaService.next() + Accessible.name: "Next track" + } + DashButton { + objectName: "dashLoop" + anchors.verticalCenter: parent.verticalCenter + glyph: !!root.player && root.player.loopState === MprisLoopState.Track ? "󰑘" : "󰑖" + fallback: "↻" + size: 34 + active: !!root.player && root.player.loopState !== MprisLoopState.None + interactive: !!root.player && root.player.loopSupported && root.player.canControl + onClicked: root.player.loopState = root.player.loopState === MprisLoopState.None ? MprisLoopState.Playlist : root.player.loopState === MprisLoopState.Playlist ? MprisLoopState.Track : MprisLoopState.None + Accessible.name: "Repeat" + } + } + // Player chooser when several MPRIS players are present. + Flow { + Layout.fillWidth: true + Layout.topMargin: 4 + spacing: 6 + visible: MediaService.players.length > 1 + Repeater { + model: MediaService.players + Rectangle { + id: chip + required property var modelData + readonly property bool active: MediaService.player === modelData + implicitWidth: chipText.implicitWidth + 20 + implicitHeight: 24 + radius: 12 + color: active ? Qt.alpha(Theme.accent, 0.3) : chipArea.containsMouse ? Theme.hover : Theme.fill + border.width: 1 + border.color: active ? Qt.alpha(Theme.accent, 0.6) : Theme.hairline + Text { + id: chipText + anchors.centerIn: parent + text: chip.modelData.identity || chip.modelData.dbusName + color: Theme.text + font.pixelSize: 11 + } + MouseArea { + id: chipArea + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: MediaService.choose(chip.modelData.dbusName) + } + } + } + } + } + } + Equalizer { + id: equalizer + visible: root.showEqualizer + Layout.alignment: Qt.AlignTop + Layout.preferredHeight: Math.max(implicitHeight, playerCard.Layout.preferredHeight) + } + } +} diff --git a/quickshell/dashboard/tabs/OverviewTab.qml b/quickshell/dashboard/tabs/OverviewTab.qml new file mode 100644 index 0000000..3e5dbaa --- /dev/null +++ b/quickshell/dashboard/tabs/OverviewTab.qml @@ -0,0 +1,266 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Layouts +import Quickshell +import Quickshell.Widgets +import ".." +import "../../widgets/faces" as Faces +import "../../services" +import "../../theme" + +// User, clock, calendar, resource bars and a compact player. +Item { + id: root + property bool current: false + implicitWidth: row.implicitWidth + implicitHeight: row.implicitHeight + // Collectors only run while this tab is on screen. + readonly property bool live: current + property bool subscribed: false + onLiveChanged: sync() + Component.onCompleted: sync() + Component.onDestruction: if (subscribed) { + MetricsService.consumers--; + MediaService.progressConsumers--; + } + function sync() { + if (live === subscribed) + return; + MetricsService.consumers += live ? 1 : -1; + MediaService.progressConsumers += live ? 1 : -1; + subscribed = live; + } + readonly property var disk: (MetricsService.snapshot.storage || []).find(s => s.available) || ({}) + + RowLayout { + id: row + spacing: 12 + ColumnLayout { + spacing: 12 + Layout.preferredWidth: 260 + DashCard { + Layout.fillWidth: true + Layout.preferredHeight: 112 + Faces.UserFace { + anchors.fill: parent + } + } + DashCard { + id: clockCard + Layout.fillWidth: true + Layout.preferredHeight: 172 + SystemClock { + id: clock + precision: SystemClock.Minutes + } + readonly property bool use24: ConfigService.ready && ConfigService.data.bar.clock.use24Hour + Column { + anchors.centerIn: parent + spacing: 2 + Text { + anchors.horizontalCenter: parent.horizontalCenter + text: Qt.formatDateTime(clock.date, clockCard.use24 ? "HH:mm" : "h:mm") + color: Theme.text + font.pixelSize: 58 + font.weight: Font.Light + font.features: { + "tnum": 1 + } + } + Text { + anchors.horizontalCenter: parent.horizontalCenter + text: Qt.formatDateTime(clock.date, "dddd, d MMMM") + color: Theme.textSecondary + font.pixelSize: 13 + } + } + } + } + DashCard { + Layout.preferredWidth: 280 + Layout.preferredHeight: 296 + Faces.CalendarFace { + anchors.fill: parent + } + } + DashCard { + Layout.preferredWidth: 132 + Layout.preferredHeight: 296 + Row { + anchors.centerIn: parent + spacing: 14 + ResourceBar { + value: MetricsService.cpu.percent + glyph: "󰻠" + fallback: "C" + label: "CPU" + } + ResourceBar { + value: MetricsService.ram.percent + glyph: "󰍛" + fallback: "M" + label: "Memory" + } + ResourceBar { + value: root.disk.percent + glyph: "󰋊" + fallback: "D" + label: "Disk" + } + } + } + DashCard { + Layout.preferredWidth: 220 + Layout.preferredHeight: 296 + ColumnLayout { + anchors.fill: parent + anchors.margins: 16 + spacing: 8 + ClippingRectangle { + Layout.alignment: Qt.AlignHCenter + Layout.preferredWidth: 132 + Layout.preferredHeight: 132 + radius: 18 + color: Theme.fill + Text { + anchors.centerIn: parent + visible: art.status !== Image.Ready + text: Icons.available ? "󰝚" : "♪" + font.family: Icons.available ? Icons.family : "" + font.pixelSize: 44 + color: Theme.textSecondary + } + Image { + id: art + anchors.fill: parent + source: MediaService.artwork + sourceSize: Qt.size(264, 264) + fillMode: Image.PreserveAspectCrop + asynchronous: true + opacity: status === Image.Ready ? 1 : 0 + Behavior on opacity { + NumberAnimation { + duration: Theme.duration + } + } + } + } + Text { + Layout.fillWidth: true + text: MediaService.title + color: Theme.text + font.pixelSize: 14 + font.weight: Font.DemiBold + horizontalAlignment: Text.AlignHCenter + elide: Text.ElideRight + } + Text { + Layout.fillWidth: true + Layout.topMargin: -6 + text: MediaService.artist + color: Theme.textSecondary + font.pixelSize: 12 + horizontalAlignment: Text.AlignHCenter + elide: Text.ElideRight + } + Rectangle { + Layout.fillWidth: true + Layout.preferredHeight: 4 + radius: 2 + color: Qt.alpha(Theme.text, 0.12) + Rectangle { + width: MediaService.length > 0 && MediaService.length < 7 * 86400 ? parent.width * Math.min(1, MediaService.position / MediaService.length) : 0 + height: parent.height + radius: 2 + color: Theme.accentVivid + } + } + Row { + Layout.alignment: Qt.AlignHCenter + spacing: 10 + DashButton { + anchors.verticalCenter: parent.verticalCenter + glyph: "󰒮" + fallback: "‹" + interactive: !!MediaService.player && MediaService.player.canGoPrevious + onClicked: MediaService.previous() + Accessible.name: "Previous track" + } + DashButton { + size: 44 + accented: true + glyph: MediaService.playing ? "󰏤" : "󰐊" + fallback: MediaService.playing ? "Ⅱ" : "▶" + interactive: !!MediaService.player && MediaService.player.canTogglePlaying + onClicked: MediaService.toggle() + Accessible.name: "Play or pause" + } + DashButton { + anchors.verticalCenter: parent.verticalCenter + glyph: "󰒭" + fallback: "›" + interactive: !!MediaService.player && MediaService.player.canGoNext + onClicked: MediaService.next() + Accessible.name: "Next track" + } + } + } + } + } + + component ResourceBar: Column { + id: bar + property var value: null + property string glyph + property string fallback + property string label + spacing: 8 + readonly property real target: Number.isFinite(value) ? Math.max(0, Math.min(100, value)) : 0 + // Only visible jumps animate (see Gauge). + property real shown + property bool easeJump: false + Component.onCompleted: shown = target + onTargetChanged: { + easeJump = Math.abs(target - shown) >= 2; + shown = target; + } + Text { + anchors.horizontalCenter: parent.horizontalCenter + text: Number.isFinite(bar.value) ? Math.round(bar.value) + "%" : "—" + color: Theme.text + font.pixelSize: 11 + font.features: { + "tnum": 1 + } + } + Rectangle { + anchors.horizontalCenter: parent.horizontalCenter + width: 10 + height: 196 + radius: 5 + color: Qt.alpha(Theme.text, 0.1) + Rectangle { + anchors.bottom: parent.bottom + width: parent.width + height: Math.max(parent.width, parent.height * bar.shown / 100) + radius: 5 + color: bar.shown > 85 ? Theme.urgent : Theme.accentVivid + Behavior on height { + enabled: bar.easeJump + NumberAnimation { + duration: Theme.duration * 2 + easing.type: Easing.OutCubic + } + } + } + } + Text { + anchors.horizontalCenter: parent.horizontalCenter + text: Icons.available ? bar.glyph : bar.fallback + font.family: Icons.available ? Icons.family : "" + font.pixelSize: 15 + color: Theme.textSecondary + Accessible.name: bar.label + } + } +} diff --git a/quickshell/dashboard/tabs/PerformanceTab.qml b/quickshell/dashboard/tabs/PerformanceTab.qml new file mode 100644 index 0000000..12b5b2e --- /dev/null +++ b/quickshell/dashboard/tabs/PerformanceTab.qml @@ -0,0 +1,277 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Layouts +import ".." +import "../../services" +import "../../theme" + +// CPU/GPU gauges with history, memory, storage and network throughput. +Item { + id: root + property bool current: false + implicitWidth: grid.implicitWidth + implicitHeight: grid.implicitHeight + property bool subscribed: false + onCurrentChanged: sync() + Component.onCompleted: sync() + Component.onDestruction: if (subscribed) + MetricsService.consumers-- + function sync() { + if (current === subscribed) + return; + MetricsService.consumers += current ? 1 : -1; + subscribed = current; + } + readonly property var gpu: MetricsService.gpu + readonly property bool hasGpu: gpu.percent !== undefined && gpu.percent !== null + readonly property var cpuHistory: MetricsService.history.map(h => h.cpu) + function temp(v) { + return Number.isFinite(v) ? Math.round(v) + "°C" : "—"; + } + function ghz(mhz) { + return Number.isFinite(mhz) ? (mhz / 1000).toFixed(2) + " GHz" : ""; + } + + GridLayout { + id: grid + columns: 6 + rowSpacing: 12 + columnSpacing: 12 + Hero { + Layout.columnSpan: root.hasGpu ? 3 : 6 + glyph: "󰻠" + title: "CPU" + subtitle: MetricsService.cpu.name || "Processor" + value: MetricsService.cpu.percent + details: [root.temp(MetricsService.cpu.temperature), root.ghz(MetricsService.cpu.frequency)].filter(s => s && s !== "—").join(" · ") || "Temperature unavailable" + history: root.cpuHistory + } + Hero { + visible: root.hasGpu + Layout.columnSpan: 3 + glyph: "󰢮" + title: "GPU" + subtitle: root.gpu.name || "Graphics" + value: root.gpu.percent + details: [root.temp(root.gpu.temperature), Number.isFinite(root.gpu.used) && Number.isFinite(root.gpu.total) ? MetricsService.bytes(root.gpu.used) + " / " + MetricsService.bytes(root.gpu.total) : ""].filter(s => s && s !== "—").join(" · ") + history: [] + } + DashCard { + Layout.columnSpan: 2 + Layout.fillWidth: true + Layout.preferredWidth: 220 + Layout.preferredHeight: 150 + RowLayout { + anchors.fill: parent + anchors.margins: 16 + spacing: 14 + Gauge { + size: 96 + value: MetricsService.ram.percent + color: Theme.accentVivid + } + ColumnLayout { + Layout.fillWidth: true + spacing: 2 + Header { + glyph: "󰍛" + title: "Memory" + } + Text { + Layout.fillWidth: true + text: MetricsService.bytes(MetricsService.ram.used) + color: Theme.text + font.pixelSize: 16 + font.weight: Font.DemiBold + elide: Text.ElideRight + } + Text { + Layout.fillWidth: true + text: "of " + MetricsService.bytes(MetricsService.ram.total) + color: Theme.textSecondary + font.pixelSize: 11 + elide: Text.ElideRight + } + } + } + } + DashCard { + Layout.columnSpan: 2 + Layout.fillWidth: true + Layout.preferredWidth: 220 + Layout.preferredHeight: 150 + ColumnLayout { + anchors.fill: parent + anchors.margins: 16 + spacing: 8 + Header { + glyph: "󰋊" + title: "Storage" + } + Repeater { + model: (MetricsService.snapshot.storage || []).slice(0, 3) + ColumnLayout { + id: disk + required property var modelData + Layout.fillWidth: true + spacing: 3 + RowLayout { + Layout.fillWidth: true + Text { + text: disk.modelData.path + color: Theme.text + font.pixelSize: 11 + elide: Text.ElideMiddle + Layout.fillWidth: true + } + Text { + text: disk.modelData.available ? MetricsService.bytes(disk.modelData.free) + " free" : "Unavailable" + color: Theme.textSecondary + font.pixelSize: 10 + } + } + Rectangle { + Layout.fillWidth: true + Layout.preferredHeight: 6 + radius: 3 + color: Qt.alpha(Theme.text, 0.1) + Rectangle { + width: parent.width * Math.min(1, (disk.modelData.percent || 0) / 100) + height: parent.height + radius: 3 + color: (disk.modelData.percent || 0) > 90 ? Theme.urgent : Theme.accentVivid + } + } + } + } + Item { + Layout.fillHeight: true + } + } + } + DashCard { + Layout.columnSpan: 2 + Layout.fillWidth: true + Layout.preferredWidth: 220 + Layout.preferredHeight: 150 + ColumnLayout { + anchors.fill: parent + anchors.margins: 16 + spacing: 4 + Header { + glyph: "󰛳" + title: "Network" + } + RowLayout { + Layout.fillWidth: true + Text { + text: "↓ " + MetricsService.bytes(MetricsService.network.download) + "/s" + color: Theme.text + font.pixelSize: 12 + font.features: { + "tnum": 1 + } + Layout.fillWidth: true + } + Text { + text: "↑ " + MetricsService.bytes(MetricsService.network.upload) + "/s" + color: Theme.textSecondary + font.pixelSize: 12 + font.features: { + "tnum": 1 + } + } + } + Item { + Layout.fillWidth: true + Layout.fillHeight: true + Sparkline { + anchors.fill: parent + max: 0 + values: MetricsService.history.map(h => h.down) + } + Sparkline { + anchors.fill: parent + max: 0 + color: Theme.textSecondary + values: MetricsService.history.map(h => h.up) + } + } + } + } + } + + component Header: RowLayout { + id: header + property string glyph + property string title + spacing: 6 + Text { + text: Icons.available ? header.glyph : "" + visible: Icons.available + font.family: Icons.family + font.pixelSize: 14 + color: Theme.textSecondary + } + Text { + text: header.title + color: Theme.textSecondary + font.pixelSize: 12 + font.weight: Font.DemiBold + } + } + component Hero: DashCard { + id: hero + property string glyph + property string title + property string subtitle + property var value: null + property string details + property var history: [] + Layout.fillWidth: true + Layout.preferredWidth: 340 + Layout.preferredHeight: 150 + RowLayout { + anchors.fill: parent + anchors.margins: 16 + spacing: 16 + Gauge { + size: 108 + value: hero.value + caption: hero.title + color: Number.isFinite(hero.value) && hero.value > 85 ? Theme.urgent : Theme.accentVivid + } + ColumnLayout { + Layout.fillWidth: true + Layout.fillHeight: true + spacing: 2 + Header { + glyph: hero.glyph + title: hero.title + } + Text { + Layout.fillWidth: true + text: hero.subtitle + color: Theme.text + font.pixelSize: 13 + font.weight: Font.DemiBold + elide: Text.ElideRight + } + Text { + Layout.fillWidth: true + text: hero.details + color: Theme.textSecondary + font.pixelSize: 11 + elide: Text.ElideRight + } + Sparkline { + Layout.fillWidth: true + Layout.fillHeight: true + Layout.topMargin: 4 + visible: hero.history.length > 0 + values: hero.history + } + } + } + } +} diff --git a/quickshell/dashboard/tabs/PowerTab.qml b/quickshell/dashboard/tabs/PowerTab.qml new file mode 100644 index 0000000..b7ffbff --- /dev/null +++ b/quickshell/dashboard/tabs/PowerTab.qml @@ -0,0 +1,166 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Layouts +import Quickshell +import Quickshell.Io +import ".." +import "../../components" +import "../../core" +import "../../services" +import "../../theme" + +// Lock, restart and shut down. Restart and shut down ask for confirmation. +Item { + id: root + property bool current: false + implicitWidth: card.implicitWidth + implicitHeight: card.implicitHeight + onCurrentChanged: if (!current) + PowerService.cancel() + FileView { + id: uptime + path: "/proc/uptime" + } + Timer { + interval: 60000 + running: root.current + repeat: true + triggeredOnStart: true + onTriggered: uptime.reload() + } + readonly property string uptimeText: { + const seconds = parseFloat(uptime.text()); + if (!Number.isFinite(seconds)) + return ""; + const d = Math.floor(seconds / 86400), h = Math.floor(seconds % 86400 / 3600), m = Math.floor(seconds % 3600 / 60); + return "Up " + (d ? d + "d " : "") + (d || h ? h + "h " : "") + m + "m"; + } + readonly property var actions: [ + { + id: "lock", + label: "Lock", + glyph: "󰌾", + fallback: "L" + }, + { + id: "reboot", + label: "Restart", + glyph: "󰜉", + fallback: "R" + }, + { + id: "shutdown", + label: "Shut down", + glyph: "󰐥", + fallback: "⏻" + } + ] + function available(id) { + if (id === "lock" && ConfigService.ready && ConfigService.data.lock.enabled) + return true; + return !!SystemService.state.power && !!SystemService.state.power[id] && !SystemService.acting; + } + function run(id) { + if (id === "lock") + ShellState.dashboardOpen = false; + PowerService.request(id); + } + + DashCard { + id: card + implicitWidth: 520 + implicitHeight: body.implicitHeight + 48 + ColumnLayout { + id: body + anchors.left: parent.left + anchors.right: parent.right + anchors.top: parent.top + anchors.margins: 24 + spacing: 20 + ColumnLayout { + Layout.fillWidth: true + spacing: 2 + Text { + text: (Quickshell.env("USER") || "user") + "@" + hostname.text().trim() + color: Theme.text + font.pixelSize: 16 + font.weight: Font.DemiBold + FileView { + id: hostname + path: "/etc/hostname" + } + } + Text { + text: root.uptimeText + color: Theme.textSecondary + font.pixelSize: 12 + } + } + Row { + Layout.alignment: Qt.AlignHCenter + Layout.topMargin: 4 + spacing: 56 + Repeater { + model: root.actions + Column { + id: action + required property var modelData + readonly property bool armed: PowerService.pending === modelData.id + spacing: 10 + DashButton { + objectName: "dashPower-" + action.modelData.id + anchors.horizontalCenter: parent.horizontalCenter + size: 84 + glyphScale: 0.36 + glyph: action.modelData.glyph + fallback: action.modelData.fallback + active: action.armed + danger: action.modelData.id !== "lock" + interactive: root.available(action.modelData.id) + onClicked: root.run(action.modelData.id) + Accessible.name: action.modelData.label + } + Text { + anchors.horizontalCenter: parent.horizontalCenter + text: action.modelData.label + color: action.armed ? Theme.text : Theme.textSecondary + font.pixelSize: 13 + } + } + } + } + RowLayout { + id: confirm + Layout.fillWidth: true + spacing: 8 + readonly property var pending: root.actions.find(a => a.id === PowerService.pending) + opacity: pending ? 1 : 0 + visible: opacity > 0 + Behavior on opacity { + NumberAnimation { + duration: Theme.duration + } + } + Text { + text: confirm.pending ? confirm.pending.label + " now? Unsaved work may be lost." : "" + color: Theme.text + font.pixelSize: 12 + wrapMode: Text.Wrap + Layout.fillWidth: true + } + GlassButton { + objectName: "dashPowerCancel" + text: "Cancel" + onClicked: PowerService.cancel() + } + GlassButton { + objectName: "dashPowerConfirm" + text: confirm.pending ? confirm.pending.label : "Confirm" + accented: true + enabled: !SystemService.acting + onClicked: PowerService.confirm() + } + } + } + } +} diff --git a/quickshell/dock/Dock.qml b/quickshell/dock/Dock.qml new file mode 100644 index 0000000..56d1137 --- /dev/null +++ b/quickshell/dock/Dock.qml @@ -0,0 +1,156 @@ +pragma ComponentBehavior: Bound +import QtQuick +import Quickshell +import Quickshell.Wayland +import "../components" +import "../services" +import "../core" +import "../theme" +import "DockGeometry.js" as Geometry + +// Quickshell selects the concrete layer window at runtime. +// qmllint disable uncreatable-type +PanelWindow { + // qmllint enable uncreatable-type + id: root + screen: ScreenService.resolve(DockModel.options.monitor) + readonly property var options: DockModel.options + readonly property string position: options.position || "bottom" + readonly property bool vertical: position !== "bottom" + readonly property real thickness: (options.iconSize || 48) * (1 + (options.magnification ? options.magnificationStrength : 0)) + 32 + readonly property int motionDuration: Math.round(Theme.duration / (options.animationSpeed || 1)) + property int hoveredIndex: -1 + property bool shown: true + readonly property bool pointerInside: hover.hovered + readonly property bool held: pointerInside || DockState.opened || DockState.draggingId !== "" + readonly property var dockRect: ({ + x: screen.x + (vertical ? position === "left" ? options.margin : screen.width - thickness - options.margin : (screen.width - width) / 2), + y: screen.y + (vertical ? (screen.height - height) / 2 : screen.height - thickness - options.margin), + width: vertical ? thickness : width, + height: vertical ? height : thickness + }) + readonly property bool overlap: options.visibility === "intelligent" && Geometry.obstructed(dockRect, screen.name, HyprlandService.windows, HyprlandService.visibleWorkspaces) + readonly property bool wantVisible: options.visibility === "always" || held || (options.visibility === "intelligent" && !overlap) + onWantVisibleChanged: updateVisibility() + function updateVisibility() { + if (wantVisible) { + hideTimer.stop(); + shown = true; + } else + hideTimer.restart(); + } + function dropPin(source, x, y) { + for (const target of DockState.icons) { + if (target.dockWindow !== root || !target.group.pinned || target === source) + continue; + const point = target.mapFromItem(source, x, y); + if (point.x >= 0 && point.y >= 0 && point.x < target.width && point.y < target.height) { + DockModel.reorder(source.group.id, target.group.id); + return; + } + } + } + Component.onCompleted: { + DockState.docks = DockState.docks.concat([root]); + updateVisibility(); + } + Component.onDestruction: DockState.docks = DockState.docks.filter(d => d !== root) + anchors { + bottom: !root.vertical + left: root.position === "left" + right: root.position === "right" + } + implicitWidth: vertical ? thickness + options.margin : Math.min(screen.width * 0.9, Math.max(120, grid.implicitWidth + 24)) + implicitHeight: vertical ? Math.min(screen.height * 0.85, Math.max(120, grid.implicitHeight + 24)) : thickness + options.margin + color: Theme.transparent + exclusionMode: ExclusionMode.Ignore + WlrLayershell.namespace: "glassMxrph-dock" + WlrLayershell.layer: WlrLayer.Overlay + mask: Region { + item: root.shown ? root.contentItem : sensor + } + HoverHandler { + id: hover + } + Item { + id: sensor + x: root.position === "right" ? root.width - 3 : 0 + y: root.vertical ? 0 : root.height - 3 + width: root.vertical ? 3 : root.width + height: root.vertical ? root.height : 3 + } + Timer { + id: hideTimer + interval: 400 + onTriggered: if (!root.wantVisible) + root.shown = false + } + GlassPanel { + id: panel + objectName: "dockSurface" + width: root.vertical ? root.thickness : root.width + height: root.vertical ? root.height : root.thickness + x: root.vertical && root.position === "left" ? root.options.margin : 0 + y: 0 + opacity: root.shown ? 1 : 0 + transform: Translate { + x: root.shown || !root.vertical ? 0 : root.position === "left" ? -root.width : root.width + y: root.shown || root.vertical ? 0 : root.height + Behavior on x { + NumberAnimation { + duration: root.motionDuration + easing.type: Easing.OutCubic + } + } + Behavior on y { + NumberAnimation { + duration: root.motionDuration + easing.type: Easing.OutCubic + } + } + } + Behavior on opacity { + NumberAnimation { + duration: root.motionDuration + } + } + Flickable { + id: view + anchors.fill: parent + anchors.margins: 10 + clip: true + contentWidth: root.vertical ? width : grid.implicitWidth + contentHeight: root.vertical ? grid.implicitHeight : height + boundsBehavior: Flickable.StopAtBounds + flickableDirection: root.vertical ? Flickable.VerticalFlick : Flickable.HorizontalFlick + Grid { + id: grid + columns: root.vertical ? 1 : Math.max(1, DockModel.items.length) + spacing: root.options.spacing + x: root.vertical ? (view.width - width) / 2 : 0 + y: root.vertical ? 0 : (view.height - height) / 2 + Repeater { + model: ScriptModel { + values: DockModel.items + objectProp: "id" + } + DockItem { + dockWindow: root + } + } + } + Text { + anchors.centerIn: parent + visible: DockModel.items.length === 0 + text: "Add apps" + color: Theme.textSecondary + font.pixelSize: 13 + } + MouseArea { + anchors.fill: parent + enabled: DockModel.items.length === 0 + onClicked: ShellState.openSettings("dock") + } + } + } +} diff --git a/quickshell/dock/DockContextMenu.qml b/quickshell/dock/DockContextMenu.qml new file mode 100644 index 0000000..92f1444 --- /dev/null +++ b/quickshell/dock/DockContextMenu.qml @@ -0,0 +1,173 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Controls +import Quickshell +import Quickshell.Hyprland +import "../components" +import "../services" +import "../theme" +import "../core" + +PopupWindow { + id: root + readonly property var group: DockState.group + property bool contentOpen: false + property int selectedIndex: -1 + readonly property var rows: { + if (!group) + return []; + if (DockState.chooser) + return chooser.rows; + let rows = []; + if (group.entry) + rows.push({ + id: "open", + text: "Open", + kind: "open", + enabled: true + }); + rows = rows.concat(chooser.rows); + if (group.entry && group.entry.actions.length) { + rows.push({ + id: "actions-separator", + separator: true + }); + for (const action of group.entry.actions) + rows.push({ + id: "action:" + action.id, + text: action.name, + kind: "action", + action: action, + enabled: true + }); + } + rows.push({ + id: "pin-separator", + separator: true + }); + if (group.pinned) + rows.push({ + id: "unpin", + text: "Unpin", + kind: "unpin", + enabled: true + }); + else if (group.entry) + rows.push({ + id: "pin", + text: "Pin to dock", + kind: "pin", + enabled: true + }); + if (group.windows.length) { + rows.push({ + id: "close-separator", + separator: true + }); + for (const window of group.windows) + rows.push({ + id: "close:" + window.address, + text: "Close · " + (window.title || group.name), + kind: "close", + address: window.address, + enabled: true + }); + } + return rows; + } + function invoke(index) { + const row = rows[index]; + if (!row || row.separator || !row.enabled || !group) + return; + const entry = group.entry; + DockState.close(); + if (row.kind === "focus") + Qt.callLater(() => HyprlandService.focusWindow(row.address)); + else if (row.kind === "close") + HyprlandService.closeWindow(row.address); + else if (row.kind === "open" || row.kind === "action") { + if (!ApplicationsService.launch(entry, row.action || null)) + ShellState.openSettings("dock"); + } else if (row.kind === "pin") + DockModel.pin(group.id); + else if (row.kind === "unpin") + DockModel.unpin(group.id); + } + function move(direction) { + const start = selectedIndex < 0 ? (direction > 0 ? -1 : 0) : selectedIndex; + for (let i = 1; i <= rows.length; i++) { + const n = (start + direction * i + rows.length) % rows.length; + if (!rows[n].separator) { + selectedIndex = n; + list.positionViewAtIndex(n, ListView.Contain); + return; + } + } + } + anchor.item: DockState.anchorItem + // Quickshell 0.3.1 exports the enums but omits flags types from metadata. + // qmllint disable missing-type + anchor.edges: DockModel.options.position === "bottom" ? Edges.Top : DockModel.options.position === "left" ? Edges.Right : Edges.Left + anchor.gravity: DockModel.options.position === "bottom" ? Edges.Top : DockModel.options.position === "left" ? Edges.Right : Edges.Left + anchor.adjustment: PopupAdjustment.Flip | PopupAdjustment.Slide + // qmllint enable missing-type + color: Theme.transparent + implicitWidth: 320 + implicitHeight: Math.min(screen ? screen.height - 100 : 600, Math.max(70, list.contentHeight + 28)) + visible: DockState.opened || surface.visible + Component.onCompleted: DockState.menuWindow = root + Component.onDestruction: DockState.menuWindow = null + Connections { + target: DockState + function onOpenedChanged() { + root.contentOpen = DockState.opened; + if (DockState.opened) { + root.selectedIndex = -1; + surface.forceActiveFocus(); + } + } + } + WindowChooser { + id: chooser + group: root.group + } + HyprlandFocusGrab { + windows: [root] + active: DockState.opened + onCleared: DockState.close() + } + GlassMenu { + id: surface + anchors.fill: parent + anchors.margins: 4 + opened: root.contentOpen + focus: true + Keys.onEscapePressed: DockState.close() + Keys.onDownPressed: root.move(1) + Keys.onUpPressed: root.move(-1) + Keys.onReturnPressed: root.invoke(root.selectedIndex) + Keys.onEnterPressed: root.invoke(root.selectedIndex) + ListView { + id: list + objectName: "dockMenuList" + anchors.fill: parent + clip: true + model: root.rows + boundsBehavior: Flickable.StopAtBounds + ScrollBar.vertical: ScrollBar {} + delegate: GlassMenuItem { + required property var modelData + required property int index + width: list.width + text: modelData.text || "" + separator: !!modelData.separator + actionEnabled: modelData.enabled === true + selected: root.selectedIndex === index + buttonType: modelData.checked ? QsMenuButtonType.RadioButton : QsMenuButtonType.None + checkState: modelData.checked ? Qt.Checked : Qt.Unchecked + onEntered: root.selectedIndex = index + onInvoked: root.invoke(index) + } + } + } +} diff --git a/quickshell/dock/DockGeometry.js b/quickshell/dock/DockGeometry.js new file mode 100644 index 0000000..6c6c43f --- /dev/null +++ b/quickshell/dock/DockGeometry.js @@ -0,0 +1,4 @@ +function intersects(a,b) { return a.x < b.x+b.width && a.x+a.width > b.x && a.y < b.y+b.height && a.y+a.height > b.y; } +function obstructed(rect, monitor, windows, workspaces) { + return windows.some(w => !w.hidden && w.monitor === monitor && (workspaces.includes(w.workspace) || w.active) && (w.fullscreen || intersects(rect,w))); +} diff --git a/quickshell/dock/DockItem.qml b/quickshell/dock/DockItem.qml new file mode 100644 index 0000000..adc8fbb --- /dev/null +++ b/quickshell/dock/DockItem.qml @@ -0,0 +1,139 @@ +import QtQuick +import QtQuick.Controls +import "../services" +import "../theme" + +Item { + id: root + required property var modelData + required property int index + required property var dockWindow + readonly property var group: DockModel.find(modelData.id) || modelData + readonly property bool vertical: dockWindow.vertical + readonly property var options: DockModel.options + readonly property real influence: Theme.intensity > 0 && options.magnification && dockWindow.hoveredIndex >= 0 && !DockState.draggingId ? Math.max(0, 1 - Math.abs(index - dockWindow.hoveredIndex) / 2.5) : 0 + readonly property real magnification: 1 + options.magnificationStrength * influence * Theme.intensity + property bool dragging: false + property point pressedAt + property real offsetX: 0 + property real offsetY: 0 + width: vertical ? dockWindow.thickness - 20 : options.iconSize + 12 + options.iconSize * influence * 0.2 + height: vertical ? options.iconSize + 12 + options.iconSize * influence * 0.2 : dockWindow.thickness - 20 + Behavior on width { + NumberAnimation { + duration: root.dockWindow.motionDuration + } + } + Behavior on height { + NumberAnimation { + duration: root.dockWindow.motionDuration + } + } + Component.onCompleted: DockState.icons = DockState.icons.concat([root]) + Component.onDestruction: DockState.removeIcon(root) + Item { + id: visual + anchors.centerIn: parent + width: root.options.iconSize + height: width + scale: mouse.pressed && !root.dragging ? 1 - 0.08 * Theme.intensity : root.magnification + transform: Translate { + x: root.offsetX + y: root.offsetY + } + Behavior on scale { + NumberAnimation { + duration: root.dockWindow.motionDuration + easing.type: Easing.OutCubic + } + } + Image { + id: icon + anchors.fill: parent + source: ApplicationsService.icon(root.group.entry) + sourceSize.width: root.options.iconSize * 2 + sourceSize.height: root.options.iconSize * 2 + fillMode: Image.PreserveAspectFit + } + Rectangle { + anchors.fill: parent + radius: 12 + color: Theme.surfaceVariant + visible: icon.source.toString() === "" || icon.status === Image.Error + Text { + anchors.centerIn: parent + text: root.group.name.slice(0, 2).toUpperCase() + color: Theme.text + font.pixelSize: 16 + } + } + } + Rectangle { + width: root.group.focused ? 15 : 5 + height: 4 + radius: 2 + x: root.vertical ? (root.options.position === "left" ? 3 : root.width - width - 3) : (root.width - width) / 2 + y: root.vertical ? (root.height - height) / 2 : root.height - height - 3 + color: root.group.focused ? Theme.accent : Theme.textSecondary + visible: root.options.runningIndicators && root.group.windows.length > 0 + Behavior on width { + NumberAnimation { + duration: root.dockWindow.motionDuration + } + } + } + MouseArea { + id: mouse + anchors.fill: parent + hoverEnabled: true + acceptedButtons: Qt.LeftButton | Qt.RightButton + preventStealing: root.group.pinned + onEntered: root.dockWindow.hoveredIndex = root.index + onExited: if (!pressed) + root.dockWindow.hoveredIndex = -1 + onPressed: event => { + root.pressedAt = Qt.point(event.x, event.y); + root.dragging = false; + } + onPositionChanged: event => { + if (!pressed || pressedButtons !== Qt.LeftButton || !root.group.pinned) + return; + const dx = event.x - root.pressedAt.x, dy = event.y - root.pressedAt.y; + if (root.dragging || Math.hypot(dx, dy) > 8) { + root.dragging = true; + DockState.draggingId = root.group.id; + root.offsetX = dx; + root.offsetY = dy; + } + } + onReleased: event => { + if (root.dragging) + root.dockWindow.dropPin(root, event.x, event.y); + root.offsetX = 0; + root.offsetY = 0; + DockState.draggingId = ""; + } + onCanceled: { + root.offsetX = 0; + root.offsetY = 0; + root.dragging = false; + DockState.draggingId = ""; + } + onClicked: event => { + if (root.dragging) { + root.dragging = false; + return; + } + if (event.button === Qt.RightButton) + DockState.open(root.group.id, root, false); + else + DockState.click(root.group.id, root); + } + } + Accessible.role: Accessible.Button + Accessible.name: group.name + Accessible.onPressAction: DockState.click(group.id, root) + ToolTip.visible: options.tooltips && mouse.containsMouse && !DockState.opened && !dragging + ToolTip.delay: 500 + ToolTip.text: group.name + (group.windows.length ? " · " + group.windows.length + " window(s)" : group.entry ? "" : " · unavailable") +} diff --git a/quickshell/dock/DockModel.qml b/quickshell/dock/DockModel.qml new file mode 100644 index 0000000..fc3f034 --- /dev/null +++ b/quickshell/dock/DockModel.qml @@ -0,0 +1,32 @@ +pragma Singleton +import QtQuick +import Quickshell +import "../services" +import "../services/AppMatching.js" as Matching + +Singleton { + readonly property var options: ConfigService.ready ? ConfigService.data.dock : ({ + enabled: false, + pinnedApps: [], + showRunningApps: true, + appOverrides: {} + }) + readonly property var items: ConfigService.ready ? Matching.group(ApplicationsService.entries, HyprlandService.windows, options.pinnedApps, options.appOverrides, options.showRunningApps) : [] + function find(id) { + return items.find(i => i.id === id) || null; + } + function pin(id) { + const entry = ApplicationsService.byId(id); + if (!entry) + return false; + if (options.pinnedApps.some(p => Matching.canonical(p) === Matching.canonical(entry.id))) + return true; + return ConfigService.setValue("dock.pinnedApps", options.pinnedApps.concat([Matching.canonical(entry.id) + ".desktop"])); + } + function unpin(id) { + return ConfigService.setValue("dock.pinnedApps", options.pinnedApps.filter(p => Matching.canonical(p) !== Matching.canonical(id))); + } + function reorder(source, target) { + return ConfigService.setValue("dock.pinnedApps", Matching.reorder(options.pinnedApps, source, target)); + } +} diff --git a/quickshell/dock/DockState.qml b/quickshell/dock/DockState.qml new file mode 100644 index 0000000..960738d --- /dev/null +++ b/quickshell/dock/DockState.qml @@ -0,0 +1,112 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Io +import "../services" +import "../core" + +Singleton { + id: root + property bool opened: false + property bool chooser: false + property string appId: "" + property Item anchorItem: null + property var docks: [] + property var icons: [] + property var menuWindow: null + property string draggingId: "" + readonly property var group: DockModel.find(appId) + onGroupChanged: if (!group) + close() + function open(id, item, windowsOnly) { + if (!DockModel.find(id)) + return; + TrayService.close(); + ShellState.controlCenterOpen = false; + ShellState.launcherOpen = false; + ShellState.settingsOpen = false; + appId = id; + anchorItem = item; + chooser = windowsOnly; + opened = true; + } + function close() { + opened = false; + } + function click(id, item) { + const group = DockModel.find(id); + if (!group) + return; + if (!group.windows.length) { + if (!ApplicationsService.launch(group.entry, null)) + ShellState.openSettings("dock"); + } else if (group.windows.length === 1) + HyprlandService.focusWindow(group.windows[0].address); + else + open(id, item, true); + } + function removeIcon(icon) { + if (anchorItem === icon) + close(); + icons = icons.filter(i => i !== icon); + } + Connections { + target: ShellState + function onControlCenterOpenChanged() { + if (ShellState.controlCenterOpen) + root.close(); + } + function onLauncherOpenChanged() { + if (ShellState.launcherOpen) + root.close(); + } + function onSettingsOpenChanged() { + if (ShellState.settingsOpen) + root.close(); + } + } + Connections { + target: TrayService + function onOpenedChanged() { + if (TrayService.opened) + root.close(); + } + } + IpcHandler { + target: "dock" + function status(): string { + return JSON.stringify({ + items: DockModel.items.map(i => ({ + id: i.id, + pinned: i.pinned, + running: i.windows.length, + focused: i.focused, + matched: !!i.entry + })), + opened: root.opened, + chooser: root.chooser, + docks: root.docks.map(d => ({ + screen: d.screen.name, + shown: d.shown, + position: d.position, + overlap: d.overlap, + width: d.width, + height: d.height + })), + error: ApplicationsService.error + }); + } + function pin(id: string): bool { + return DockModel.pin(id); + } + function unpin(id: string): bool { + return DockModel.unpin(id); + } + function move(source: string, target: string): bool { + return DockModel.reorder(source, target); + } + function settings(): void { + ShellState.openSettings("dock"); + } + } +} diff --git a/quickshell/dock/WindowChooser.qml b/quickshell/dock/WindowChooser.qml new file mode 100644 index 0000000..95c79ba --- /dev/null +++ b/quickshell/dock/WindowChooser.qml @@ -0,0 +1,13 @@ +import QtQuick + +QtObject { + property var group: null + readonly property var rows: group ? group.windows.map(w => ({ + id: "focus:" + w.address, + text: w.title || group.name, + kind: "focus", + address: w.address, + checked: w.active, + enabled: true + })) : [] +} diff --git a/quickshell/dock/qmldir b/quickshell/dock/qmldir new file mode 100644 index 0000000..93717fa --- /dev/null +++ b/quickshell/dock/qmldir @@ -0,0 +1,6 @@ +singleton DockModel 1.0 DockModel.qml +singleton DockState 1.0 DockState.qml +Dock 1.0 Dock.qml +DockItem 1.0 DockItem.qml +DockContextMenu 1.0 DockContextMenu.qml +WindowChooser 1.0 WindowChooser.qml diff --git a/quickshell/helpers/cava.py b/quickshell/helpers/cava.py new file mode 100644 index 0000000..ca73236 --- /dev/null +++ b/quickshell/helpers/cava.py @@ -0,0 +1,9 @@ +#!/usr/bin/env python3 +"""Exec the optional visualizer; report an absent executable without a QML warning.""" +import os +import sys +try: + os.execvp('cava', ['cava', '-p', sys.argv[1]]) +except OSError as error: + print('Cava unavailable: ' + str(error), file=sys.stderr) + sys.exit(127) diff --git a/quickshell/helpers/desktop.py b/quickshell/helpers/desktop.py new file mode 100644 index 0000000..e9512e2 --- /dev/null +++ b/quickshell/helpers/desktop.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +"""One-shot filesystem/provider adapter. JSON in argv, JSON out; never shell-evaluates input.""" +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import sys +import tempfile + +SCHEMES=['scheme-content','scheme-expressive','scheme-fidelity','scheme-fruit-salad','scheme-monochrome','scheme-neutral','scheme-rainbow','scheme-tonal-spot','scheme-vibrant','scheme-smart'] +IMAGES={'.png','.jpg','.jpeg','.webp','.bmp'} + +def run(argv,timeout=15): + p=subprocess.run(argv,capture_output=True,text=True,timeout=timeout,stdin=subprocess.DEVNULL) + if p.returncode:raise ValueError((p.stderr or p.stdout or 'Provider failed').strip()[-700:]) + return p.stdout.strip() + +def image_path(value): + path=Path(value).expanduser().resolve(strict=True) + if not path.is_file() or path.suffix.lower() not in IMAGES:raise ValueError('Select a supported still image') + return path + +def probe_matugen(executable): + version=run([executable,'--version']) + if not re.search(r'\b4\.2\.\d+\b',version):raise ValueError('This adapter supports Matugen 4.2.x; found '+version) + return version + +def palette(req): + executable=req.get('executable','matugen');version=probe_matugen(executable) + path=image_path(req['path']);scheme=req.get('scheme','scheme-tonal-spot');contrast=req.get('contrast',0) + if scheme not in SCHEMES or not isinstance(contrast,(int,float)) or not -1<=contrast<=1:raise ValueError('Unsupported Matugen options') + # The dedicated config has no hooks, app templates or wallpaper command. + with tempfile.TemporaryDirectory(prefix='glassmxrph-matugen-') as tmp: + base=Path(tmp);template=base/'palette.json';output=base/'generated.json';config=base/'config.toml' + template.write_text('{"accent":"{{colors.primary.default.hex}}","accentText":"{{colors.on_primary.default.hex}}","accentContainer":"{{colors.primary_container.default.hex}}"}') + config.write_text('[config]\n\n[templates.glassmxrph]\ninput_path = '+json.dumps(str(template))+'\noutput_path = '+json.dumps(str(output))+'\n') + run([executable,'--config',str(config),'--mode','dark','--type',scheme,'--contrast='+str(contrast),'--source-color-index','0','image',str(path)],timeout=60) + result=json.loads(output.read_text()) + if not all(re.fullmatch(r'#[0-9a-fA-F]{6}',result.get(k,'')) for k in ['accent','accentText','accentContainer']):raise ValueError('Matugen generated an invalid palette') + return {'palette':result,'version':version,'path':str(path)} + +def current(backend,monitor): + if backend=='serpantinum':return run(['serpantinum','ipc','call','wallpaper','getWallpaperPath',monitor],5) + if backend=='awww': + for line in run(['awww','query'],5).splitlines(): + if line.startswith(monitor+':') and 'image: ' in line:return line.split('image: ',1)[1] + return '' + return '' + +def provider(req): + backend=req.get('backend','auto');monitor=req.get('monitor','') + if backend=='auto': + for candidate in ['serpantinum','awww']: + if shutil.which(candidate): + try:return {'backend':candidate,'current':current(candidate,monitor)} + except (ValueError,subprocess.TimeoutExpired):pass + return {'backend':'none','current':'','notice':'No supported running wallpaper provider. Choose a custom command or start your existing wallpaper service.'} + if backend in ['serpantinum','awww']:return {'backend':backend,'current':current(backend,monitor)} + if backend=='native':return {'backend':'native','current':req.get('current','')} + if backend=='custom':return {'backend':'custom','current':req.get('current','')} + raise ValueError('Unsupported wallpaper backend') + +def apply(req): + path=image_path(req['path']);monitor=req['monitor'] + if not re.fullmatch(r'[\w.-]+',monitor):raise ValueError('Invalid output name') + backend=provider(req)['backend'] + if backend=='native':return {'backend':'native','path':str(path),'url':path.as_uri(),'providerPath':str(path)} + if backend=='serpantinum': + # This provider interpolates filenames into shell commands. Pass a safe owned copy. + base=Path(os.environ.get('XDG_CACHE_HOME',Path.home()/'.cache'))/'glassMxrph/wallpapers' + base.mkdir(parents=True,exist_ok=True) + if "'" in str(base) or '\n' in str(base):raise ValueError('Serpantinum cannot safely handle this cache path') + dest=base/(hashlib.sha256(path.read_bytes()).hexdigest()+path.suffix.lower()) + if not dest.exists():shutil.copyfile(path,dest) + run(['serpantinum','ipc','call','wallpaper','setWallpaper',monitor,str(dest),'fade']) + # IPC only acknowledges dispatch: poll read-only state for provider acceptance. + import time + for _ in range(20): + if current(backend,monitor)==str(dest):return {'backend':backend,'path':str(path),'providerPath':str(dest)} + time.sleep(.1) + raise ValueError('Wallpaper provider did not acknowledge the selected image') + if backend=='awww':run(['awww','img','--outputs',monitor,'--transition-type','fade',str(path)]) + elif backend=='custom': + command=req.get('command',[]) + if not isinstance(command,list) or not command or not all(isinstance(x,str) for x in command):raise ValueError('Custom command must be an argument array') + if not any('{path}' in x for x in command):raise ValueError('Custom command needs a {path} argument') + run([x.replace('{path}',str(path)).replace('{monitor}',monitor) for x in command]) + else:raise ValueError('No active wallpaper provider') + return {'backend':backend,'path':str(path),'providerPath':str(path)} + +def scan(req): + found={};errors=[] + for directory in (req.get('directories') or [str(Path.home()/'Pictures/Wallpapers')]): + base=Path(directory).expanduser() + try: + for entry in base.iterdir(): + if entry.is_file() and entry.suffix.lower() in IMAGES: + resolved=entry.resolve();found[str(resolved)]={'path':str(resolved),'url':resolved.as_uri(),'name':entry.name} + if len(found)>=1000:break + except OSError as error:errors.append(str(error)) + if len(found)>=1000:break + return {'images':sorted(found.values(),key=lambda x:x['name'].casefold()),'notice':'; '.join(errors),'limited':len(found)>=1000} + +def dispatch(req): + action=req['action'] + if action=='palette':return palette(req) + if action=='matugen-probe':return {'version':probe_matugen(req.get('executable','matugen')),'schemes':SCHEMES} + if action=='provider':return provider(req) + if action=='apply':return apply(req) + if action=='scan':return scan(req) + raise ValueError('Unknown adapter request') + +if __name__=='__main__': + try:print(json.dumps({'ok':True,**dispatch(json.loads(sys.argv[1]))})) + except (ValueError,OSError,KeyError,subprocess.TimeoutExpired) as error:print(json.dumps({'ok':False,'error':str(error)})) diff --git a/quickshell/helpers/easyeffects.py b/quickshell/helpers/easyeffects.py new file mode 100644 index 0000000..f74c210 --- /dev/null +++ b/quickshell/helpers/easyeffects.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python3 +"""EasyEffects 10-band equalizer bridge. Prints one JSON status object. + +status installed/running/bypass plus the saved equalizer +apply GAINS NAME save gains (JSON list of 10 dB values) and load them as the + "glassmxrph_eq" output preset, starting the service if needed +bypass on|off global EasyEffects bypass +""" +import json, os, re, shutil, subprocess, sys, time +from pathlib import Path + +PRESET = 'glassmxrph_eq' +FREQUENCIES = [32, 63, 125, 250, 500, 1000, 2000, 4000, 8000, 16000] +STATE = Path(os.environ.get('XDG_STATE_HOME') or Path.home() / '.local/state') / 'glassMxrph/equalizer.json' + + +def binary(): + return os.environ.get('GLASSMXRPH_EASYEFFECTS') or shutil.which('easyeffects') + + +def run(*args, timeout=4): + try: + return subprocess.run([binary(), *args], capture_output=True, text=True, timeout=timeout) + except (OSError, subprocess.TimeoutExpired): + return None + + +def version(): + p = run('--version') + m = re.search(r'(\d+)\.(\d+)', (p.stdout + p.stderr) if p else '') + return (int(m.group(1)), int(m.group(2))) if m else (8, 0) + + +def running(): + # Nix wraps the binary as .easyeffects-wrapped; match the executable name only. + for proc in Path('/proc').glob('[0-9]*'): + try: + argv0 = (proc / 'cmdline').read_bytes().split(b'\0', 1)[0].decode(errors='ignore') + except OSError: + continue + if re.fullmatch(r'\.?easyeffects(-wrapped)?', os.path.basename(argv0)): + return True + return False + + +def load_state(): + try: + data = json.loads(STATE.read_text()) + bands = [max(-12.0, min(12.0, float(v))) for v in data['bands']][:10] + if len(bands) == 10: + return dict(bands=bands, preset=str(data.get('preset', 'Custom'))) + except (OSError, ValueError, KeyError, TypeError): + pass + return dict(bands=[0.0] * 10, preset='Flat') + + +def preset_dir(): + # EasyEffects 8 keeps presets under XDG data; 7.x used XDG config. + if version() >= (8, 0): + return Path(os.environ.get('XDG_DATA_HOME') or Path.home() / '.local/share') / 'easyeffects/output' + return Path(os.environ.get('XDG_CONFIG_HOME') or Path.home() / '.config') / 'easyeffects/output' + + +def write_preset(bands): + band = lambda f, g: dict(frequency=f, gain=g, mode='Bell', mute=False, q=1.41, solo=False, width=1.0, slope='x1') + channel = {f'band{i}': band(f, bands[i]) for i, f in enumerate(FREQUENCIES)} + preset = {'output': {'blocklist': [], 'plugins_order': ['equalizer'], 'equalizer': { + 'bypass': False, 'input-gain': 0.0, 'output-gain': 0.0, 'left': channel, 'right': channel, + 'mode': 'IIR', 'num-bands': len(FREQUENCIES), 'split-channels': False}}} + directory = preset_dir() + directory.mkdir(parents=True, exist_ok=True) + tmp = directory / f'.{PRESET}.json.tmp' + tmp.write_text(json.dumps(preset, indent=4)) + tmp.replace(directory / f'{PRESET}.json') + + +def ensure_service(): + if running(): + return True + # Service mode keeps it in the background; loading a preset without a running + # instance would open the full window instead. + flag = '--service-mode' if version() >= (8, 0) else '--gapplication-service' + try: + subprocess.Popen([binary(), flag, '-w'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) + except OSError: + return False + for _ in range(30): + if running(): + time.sleep(0.6) + return True + time.sleep(0.1) + return False + + +def bypassed(): + if not running(): + return False + p = run('-b', '3') + text = (p.stdout if p else '').strip().lower() + return text in ('1', 'true', 'on', 'enabled') + + +def status(error=''): + installed = bool(binary()) + state = load_state() + alive = installed and running() + return dict(installed=installed, running=alive, bypass=installed and alive and bypassed(), bands=state['bands'], + preset=state['preset'], frequencies=FREQUENCIES, error=error) + + +def main(): + command = sys.argv[1] if len(sys.argv) > 1 else 'status' + error = '' + if command == 'apply' and binary(): + try: + bands = [max(-12.0, min(12.0, float(v))) for v in json.loads(sys.argv[2])][:10] + if len(bands) != 10: + raise ValueError('expected 10 bands') + STATE.parent.mkdir(parents=True, exist_ok=True) + STATE.write_text(json.dumps(dict(bands=bands, preset=sys.argv[3] if len(sys.argv) > 3 else 'Custom'))) + write_preset(bands) + if not ensure_service(): + error = 'EasyEffects did not start' + elif not (p := run('-l', PRESET)) or p.returncode != 0: + error = 'EasyEffects rejected the preset' + except (ValueError, IndexError, OSError) as e: + error = str(e) + elif command == 'bypass' and binary(): + if running(): + run('-b', '1' if (sys.argv[2:] or ['on'])[0] == 'on' else '2') + else: + error = 'EasyEffects is not running' + print(json.dumps(status(error))) + + +if __name__ == '__main__': + main() diff --git a/quickshell/helpers/glass.py b/quickshell/helpers/glass.py new file mode 100644 index 0000000..a173e12 --- /dev/null +++ b/quickshell/helpers/glass.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +"""Global HyprGlass controls using verified live scalar options, with a restore journal.""" +import json,math,os,subprocess,sys +from pathlib import Path + +PREFIX='plugin:hyprglass:' +RANGES={'blur_strength':(0,5),'blur_iterations':(1,5),'refraction_strength':(0,8), + 'chromatic_aberration':(0,1),'fresnel_strength':(0,1),'specular_strength':(0,1), + 'edge_thickness':(0,.15),'lens_distortion':(0,1),'brightness':(.2,2), + 'contrast':(.2,2),'saturation':(0,2),'vibrancy':(0,1),'adaptive_dim':(0,1)} +GHOSTTY={'blur_strength':.45,'blur_iterations':2,'refraction_strength':3, + 'chromatic_aberration':.45,'fresnel_strength':.5,'specular_strength':.8, + 'edge_thickness':.065,'lens_distortion':.25,'brightness':.95, + 'contrast':1,'saturation':1,'vibrancy':.15,'adaptive_dim':.2} + + +def run(args): + p=subprocess.run(['hyprctl',*args],text=True,capture_output=True,timeout=4) + if p.returncode:raise ValueError((p.stderr or p.stdout).strip()[:350]) + return p.stdout.strip() + +def get(key): + data=json.loads(run(['-j','getoption',PREFIX+key])) + for field in ['str','int','float']: + if field in data:return data[field] + raise ValueError('HyprGlass option unavailable: '+key) + +def put(key,value): + result=run(['keyword',PREFIX+key,str(value)]) + if result!='ok':raise ValueError(result[:350]) + if get(key)!=value:raise ValueError('HyprGlass did not accept '+key) + +def values(options): + controls=options.get('values',{}) + if set(controls)!=set(RANGES):raise ValueError('Incomplete glass settings') + for key,(low,high) in RANGES.items(): + v=controls[key] + if type(v) not in (int,float) or not math.isfinite(v) or not low<=v<=high:raise ValueError('Invalid '+key) + if not float(controls['blur_iterations']).is_integer():raise ValueError('Blur passes must be an integer') + if type(options.get('layers')) is not bool or type(options.get('effectEnabled',True)) is not bool:raise ValueError('Invalid glass toggle') + # "default" is the plugin's documented fallback: custom presets otherwise + # override scalar sliders, and live preset definitions are only committed at reload. + result={} + for key,v in controls.items(): + result['dark:'+key]=v + result['light:'+key]=v + result.update({'dark:tint_color':0xffffff08,'light:tint_color':0xffffff08, + 'dark:glass_opacity':1,'light:glass_opacity':1, + 'default_preset':'default','default_theme':'dark','layers:preset':'default','layers:mask_mode':'alpha', + 'layers:enabled':int(options['layers'] and options.get('effectEnabled',True)),'enabled':int(options.get('effectEnabled',True))}) + return result + +def journal_path(): + return Path(os.environ.get('XDG_STATE_HOME',Path.home()/'.local/state'))/'glassMxrph/glass-restore.json' + +def save(path,data): + path.parent.mkdir(parents=True,exist_ok=True) + temp=path.with_suffix('.tmp');temp.write_text(json.dumps(data));temp.replace(path) + +def probe(): + try: + return dict(available=True,preset=get('default_preset'),enabled=bool(get('enabled')),layers=bool(get('layers:enabled')), + namespaces=get('layers:namespaces'),exclusions=get('layers:exclude_namespaces'),overrides=get('layers:namespace_presets')) + except (OSError,ValueError,subprocess.TimeoutExpired):return dict(available=False) + +def dispatch(req): + action=req.get('action') + if action=='probe':return probe() + path=journal_path();session=os.environ.get('HYPRLAND_INSTANCE_SIGNATURE','') + journal=json.loads(path.read_text()) if path.exists() else {} + if journal.get('session')!=session or req.get('reloaded'):journal={} + if action=='restore': + skipped=[] + for key,old in reversed(list(journal.get('before',{}).items())): + if get(key)==journal['after'].get(key):put(key,old) + else:skipped.append(key) + path.unlink(missing_ok=True) + return dict(**probe(),notice='Restored previous glass settings.' if not skipped else 'Preserved externally changed options: '+', '.join(skipped)) + if action!='apply':raise ValueError('Unknown glass request') + target=values(req['options']) + current={key:get(key) for key in target} + before=journal.get('before',current) + # Persist before writing so a partial operation can be restored after a crash. + record=dict(session=session,before=before,after=target) + save(path,record) + changed=[] + try: + for key,value in target.items(): + if current[key]!=value: + changed.append(key);put(key,value) + except Exception: + rollback_failed=False + for key in reversed(changed): + try:put(key,current[key]) + except Exception:rollback_failed=True + if not rollback_failed: + if journal:save(path,journal) + else:path.unlink(missing_ok=True) + raise + return dict(**probe(),notice='Global glass applied. Explicit per-application and per-layer preset rules still take priority.') + +if __name__=='__main__': + try:print(json.dumps(dict(ok=True,**dispatch(json.loads(sys.argv[1]))))) + except (OSError,ValueError,KeyError,subprocess.TimeoutExpired) as e:print(json.dumps(dict(ok=False,error=str(e)))) diff --git a/quickshell/helpers/marketplace.py b/quickshell/helpers/marketplace.py new file mode 100644 index 0000000..4daeb6c --- /dev/null +++ b/quickshell/helpers/marketplace.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python3 +"""Plugin marketplace browser. Prints one JSON object. + +search [QUERY] [CATEGORY] [SORT] [OFFSET] [LIMIT] [VERIFIED_ONLY] [SOURCE] + page of listings; SORT is popular | recent | name; SOURCE is + omarchy (plugins.omarchy.org) or noctalia (noctalia-plugins registry) +refresh download the catalog again + +The catalog and the registry's automated security review are cached in +$XDG_CACHE_HOME/glassMxrph and refreshed every six hours. Installs use the +commit the marketplace last validated, not the repository's current HEAD. +""" +import json, os, sys, time, urllib.request +from pathlib import Path + +CATALOG_URL = 'https://plugins.omarchy.org/catalog.json' +REGISTRY_URL = 'https://raw.githubusercontent.com/omacom/omarchy-plugin-marketplace/main/registry.json' +SITE = 'https://plugins.omarchy.org/' +CACHE = Path(os.environ.get('XDG_CACHE_HOME') or Path.home() / '.cache') / 'glassMxrph' +INDEX = CACHE / 'omarchy-marketplace.json' +NOCTALIA_REGISTRY = 'https://raw.githubusercontent.com/noctalia-dev/noctalia-plugins/main/registry.json' +NOCTALIA_REPO = 'https://github.com/noctalia-dev/noctalia-plugins' +NOCTALIA_INDEX = CACHE / 'noctalia-marketplace.json' +MAX_AGE = 6 * 3600 +# What glassMxrph can host today (see compat/omarchy). +SUPPORT = {'Bar widget': 'supported', 'Panel': 'supported', 'Service': 'supported', 'Plugin': 'supported', + 'Overlay': 'partial', 'Menu': 'partial', 'Bar': 'unsupported', 'Suite': 'unsupported'} + + +def download(url): + request = urllib.request.Request(url, headers={'User-Agent': 'glassMxrph'}) + with urllib.request.urlopen(request, timeout=60) as response: + return json.load(response) + + +def build_index(): + catalog = download(CATALOG_URL) + review = {} + try: + for source in download(REGISTRY_URL).get('sources', []): + baseline = source.get('automatedSecurityBaseline') or {} + review[source.get('repo', '').rstrip('/').removesuffix('.git').lower()] = dict( + outcome=baseline.get('outcome', ''), capabilities=baseline.get('capabilities', [])) + except (OSError, ValueError): + pass # The security review is extra detail; browsing works without it. + items = [] + for p in catalog.get('plugins', []): + repo = p.get('repo', '') + sec = review.get(repo.rstrip('/').removesuffix('.git').lower(), {}) + kind = p.get('kind') or 'Plugin' + builtin = p.get('id', '').startswith('omarchy.') + items.append(dict( + id=p.get('id', ''), name=p.get('name') or p.get('id', ''), description=p.get('description', ''), + author=p.get('author', ''), version=p.get('version', ''), category=p.get('category', 'Other'), + tags=p.get('tags', []), kind=kind, + # Omarchy's own built-ins use the reserved omarchy.* ids and are not installable. + support='unsupported' if builtin else SUPPORT.get(kind, 'partial'), + stars=p.get('stars', 0) or 0, verified=p.get('verificationStatus') == 'verified', + installable=bool(p.get('installAvailable')) and not builtin, + note='Built into Omarchy' if builtin else p.get('installNote', ''), + repo=repo, commit=p.get('upstreamValidatedCommit') or p.get('listingValidatedCommit') or '', + manifestPath=p.get('manifestPath', ''), license=p.get('license', ''), + accent=p.get('accent', ''), initials=p.get('initials', ''), + updated=p.get('versionUpdatedAt') or p.get('repositoryUpdatedAt') or p.get('listedAt') or '', + review=sec.get('outcome', ''), capabilities=sec.get('capabilities', []), + page=SITE + '#' + p.get('id', ''))) + CACHE.mkdir(parents=True, exist_ok=True) + tmp = INDEX.with_suffix('.tmp') + tmp.write_text(json.dumps(dict(fetchedAt=int(time.time()), items=items))) + tmp.replace(INDEX) + + +def build_noctalia_index(): + """Noctalia v4's registry: one repository, a folder per plugin id.""" + registry = download(NOCTALIA_REGISTRY) + items = [] + for p in registry.get('plugins', []): + tags = p.get('tags') or [] + items.append(dict( + id=p.get('id', ''), name=p.get('name') or p.get('id', ''), description=p.get('description', ''), + author=p.get('author', ''), version=p.get('version', ''), category=tags[0] if tags else 'Other', + tags=tags, kind='Noctalia v4', support='partial', stars=0, verified=bool(p.get('official')), + installable=True, note='Noctalia v4 plugin, run through the compatibility layer', + repo=p.get('repository') or NOCTALIA_REPO, commit='', manifestPath=p.get('id', '') + '/manifest.json', + license=p.get('license', ''), accent='', initials='', updated=p.get('lastUpdated', ''), + review='', capabilities=[], official=bool(p.get('official')), + page=NOCTALIA_REPO + '/tree/main/' + p.get('id', ''))) + CACHE.mkdir(parents=True, exist_ok=True) + tmp = NOCTALIA_INDEX.with_suffix('.tmp') + tmp.write_text(json.dumps(dict(fetchedAt=int(time.time()), items=items))) + tmp.replace(NOCTALIA_INDEX) + + +def load(force=False, source='omarchy'): + index, build = (NOCTALIA_INDEX, build_noctalia_index) if source == 'noctalia' else (INDEX, build_index) + fresh = index.is_file() and time.time() - index.stat().st_mtime < MAX_AGE + if force or not fresh: + try: + build() + except (OSError, ValueError) as e: + if not index.is_file(): + raise + stale = json.loads(index.read_text()) + stale['warning'] = 'Showing the cached catalog: ' + str(e) + return stale + return json.loads(index.read_text()) + + +def search(data, query, category, sort, offset, limit, verified_only): + words = [w for w in query.lower().split() if w] + items = data['items'] + if category and category != 'all': + items = [i for i in items if i['category'] == category] + if verified_only: + items = [i for i in items if i['verified']] + if words: + def score(i): + hay = ' '.join([i['name'], i['id'], i['description'], i['author'], ' '.join(i['tags'])]).lower() + if not all(w in hay for w in words): + return -1 + return sum(3 if w in i['name'].lower() else 1 for w in words) + scored = [(score(i), i) for i in items] + items = [i for s, i in sorted(scored, key=lambda x: (-x[0], -x[1]['stars'])) if s >= 0] + elif sort == 'recent': + items = sorted(items, key=lambda i: i['updated'], reverse=True) + elif sort == 'name': + items = sorted(items, key=lambda i: i['name'].lower()) + else: + items = sorted(items, key=lambda i: (i['verified'], i['stars']), reverse=True) + categories = sorted({i['category'] for i in data['items']}) + return dict(ok=True, total=len(items), offset=offset, items=items[offset:offset + limit], + categories=categories, fetchedAt=data.get('fetchedAt', 0), warning=data.get('warning', '')) + + +def main(): + args = sys.argv[1:] or ['search'] + try: + if args[0] == 'refresh': + data = load(force=True, source=args[1] if len(args) > 1 else 'omarchy') + result = dict(ok=True, total=len(data['items']), fetchedAt=data.get('fetchedAt', 0)) + else: + get = lambda n, d: args[n] if len(args) > n and args[n] != '' else d + result = search(load(source=get(7, 'omarchy')), get(1, ''), get(2, 'all'), get(3, 'popular'), int(get(4, '0')), + min(100, int(get(5, '30'))), get(6, 'false') == 'true') + except (OSError, ValueError) as e: + result = dict(ok=False, error='Could not load the plugin catalog: ' + str(e), items=[], total=0, categories=[]) + print(json.dumps(result)) + + +if __name__ == '__main__': + main() diff --git a/quickshell/helpers/metrics.py b/quickshell/helpers/metrics.py new file mode 100644 index 0000000..22b7fdf --- /dev/null +++ b/quickshell/helpers/metrics.py @@ -0,0 +1,194 @@ +#!/usr/bin/env python3 +"""Read-only Linux telemetry. One streaming process owns all sampling/deltas.""" +import csv +import json +import math +import os +from pathlib import Path +import re +import shutil +import subprocess +import sys +import time + + +def read(path): + try: + return Path(path).read_text().strip() + except OSError: + return '' + + +def number(value, divisor=1): + try: + result = float(value) / divisor + return result if math.isfinite(result) and result >= 0 else None + except (ValueError, TypeError): + return None + + +def cpu_counts(text): + row = next(line for line in text.splitlines() if line.startswith('cpu ')) + v = [int(n) for n in row.split()[1:9]] # guest already included in user/nice + return sum(v), v[3] + (v[4] if len(v) > 4 else 0) + + +def cpu_percent(previous, current): + if previous is None: + return None + total, idle = current[0] - previous[0], current[1] - previous[1] + return max(0, min(100, 100 * (total - idle) / total)) if total > 0 and idle >= 0 else None + + +def memory(text): + v = {line.split(':')[0]: int(line.split()[1]) * 1024 for line in text.splitlines() if ':' in line} + total, available = v.get('MemTotal', 0), v.get('MemAvailable') + if not total or available is None: + return {'available': False} + used = max(0, total - available) + return dict(available=True, total=total, used=used, free=available, percent=100 * used / total) + + +def net_counts(text): + result = {} + for line in text.splitlines(): + if ':' not in line: + continue + name, data = line.rsplit(':', 1) + fields = data.split() + if len(fields) >= 16: + result[name.strip()] = (int(fields[0]), int(fields[8])) + return result + + +def net_rates(previous, current, elapsed): + return {name: {'download': max(0, values[0] - previous[name][0]) / elapsed, + 'upload': max(0, values[1] - previous[name][1]) / elapsed} + for name, values in current.items() if name in previous and elapsed > 0} + + +def nvidia_rows(text): + result = [] + for row in csv.reader(text.splitlines(), skipinitialspace=True): + if len(row) != 8: + continue + uid, name, busy, temp, used, total, clock, power = row + result.append(dict(id=uid, name=name, provider='nvidia-smi', percent=number(busy), + temperature=number(temp), used=number(used, 1 / 1048576), + total=number(total, 1 / 1048576), frequency=number(clock), power=number(power))) + return result + + +class Collector: + def __init__(self, options): + self.options = options + self.previous_cpu = None + self.previous_net = {} + self.previous_time = None + self.gpus = [] + self.gpu_time = -100 + self.storage = [] + self.storage_time = -100 + self.nvidia = shutil.which('nvidia-smi') + self.cpu_name = next((line.split(':', 1)[1].strip() for line in read('/proc/cpuinfo').splitlines() + if line.startswith('model name')), 'CPU') + + def gpu(self): + result = [] + if self.nvidia: + try: + p = subprocess.run([self.nvidia, '--query-gpu=uuid,name,utilization.gpu,temperature.gpu,memory.used,memory.total,clocks.gr,power.draw', + '--format=csv,noheader,nounits'], capture_output=True, text=True, timeout=2) + if p.returncode == 0: + result.extend(nvidia_rows(p.stdout)) + except (OSError, subprocess.TimeoutExpired): + pass + for device in sorted(Path('/sys/class/drm').glob('card[0-9]*/device')): + if not re.fullmatch(r'card\d+', device.parent.name): + continue + vendor = read(device / 'vendor') + if vendor == '0x10de': + continue # NVIDIA handled above, no duplicate device + hwm = next(iter(device.glob('hwmon/hwmon*')), None) + def sensor(name, divisor=1): + return number(read(hwm / name), divisor) if hwm else None + result.append(dict(id=str(device.resolve()), name=read(device / 'product_name') or + ('AMD' if vendor == '0x1002' else 'Intel' if vendor == '0x8086' else 'GPU') + ' · ' + device.parent.name, + provider='sysfs', percent=number(read(device / 'gpu_busy_percent')), + temperature=sensor('temp1_input', 1000), used=number(read(device / 'mem_info_vram_used')), + total=number(read(device / 'mem_info_vram_total')), frequency=sensor('freq1_input', 1000000), + power=sensor('power1_average', 1000000))) + return result + + def sample(self): + now = time.monotonic() + warnings = [] + cpu = dict(name=self.cpu_name, percent=None, temperature=None, frequency=None, power=None) + try: + counts = cpu_counts(read('/proc/stat')) + cpu['percent'] = cpu_percent(self.previous_cpu, counts) + self.previous_cpu = counts + except (ValueError, StopIteration, IndexError): + warnings.append('CPU counters unavailable') + frequencies = [number(line.split(':', 1)[1]) for line in read('/proc/cpuinfo').splitlines() if line.startswith('cpu MHz')] + frequencies = [v for v in frequencies if v is not None] + cpu['frequency'] = sum(frequencies) / len(frequencies) if frequencies else None + temperatures = [] + for hw in Path('/sys/class/hwmon').glob('hwmon*'): + if read(hw / 'name') in ('k10temp', 'coretemp', 'zenpower', 'cpu_thermal'): + temperatures += [number(read(p), 1000) for p in hw.glob('temp*_input')] + temperatures = [v for v in temperatures if v is not None] + cpu['temperature'] = max(temperatures) if temperatures else None + try: + ram = memory(read('/proc/meminfo')) + except (ValueError, IndexError): + ram = {'available': False} + current = net_counts(read('/proc/net/dev')) + rates = net_rates(self.previous_net, current, now - self.previous_time) if self.previous_time else {} + interfaces = [] + for name in sorted(current): + if name == 'lo': + continue + values = rates.get(name, {'download': None, 'upload': None}) + interfaces.append(dict(name=name, **values)) + selected = self.options.get('networkInterface', 'auto') + # Auto uses physical interfaces; excludes VPN/bridge/veth double counting. + names = [i['name'] for i in interfaces if (Path('/sys/class/net') / i['name'] / 'device').exists()] if selected == 'auto' else [selected] + valid = [rates[n] for n in names if n in rates] + network = dict(interfaces=interfaces, selected=names, + download=sum(v['download'] for v in valid) if valid else None, + upload=sum(v['upload'] for v in valid) if valid else None) + self.previous_net, self.previous_time = current, now + if now - self.gpu_time >= max(5, self.options.get('interval', 2)): + self.gpus, self.gpu_time = self.gpu(), now + if now - self.storage_time >= 15: + self.storage = [] + for path in self.options.get('storagePaths', ['/']): + try: + s = os.statvfs(path) + total, free, available = s.f_blocks * s.f_frsize, s.f_bfree * s.f_frsize, s.f_bavail * s.f_frsize + used = total - free + self.storage.append(dict(path=path, available=True, total=total, used=used, free=free, + availableBytes=available, percent=100 * used / total if total else 0)) + except OSError: + self.storage.append(dict(path=path, available=False)) + self.storage_time = now + return dict(cpu=cpu, ram=ram, gpus=self.gpus, storage=self.storage, network=network, + timestamp=time.time(), warnings=warnings) + + +def main(): + options = json.loads(sys.argv[1]) if len(sys.argv) > 1 else {} + interval = min(30, max(1, float(options.get('interval', 2)))) + collector = Collector(options) + while True: + started = time.monotonic() + print(json.dumps(collector.sample(), allow_nan=False), flush=True) + time.sleep(max(.1, interval - (time.monotonic() - started))) + + +if __name__ == '__main__': + try: + main() + except (BrokenPipeError, KeyboardInterrupt): + pass diff --git a/quickshell/helpers/plugins.py b/quickshell/helpers/plugins.py new file mode 100644 index 0000000..38ea81a --- /dev/null +++ b/quickshell/helpers/plugins.py @@ -0,0 +1,265 @@ +#!/usr/bin/env python3 +"""glassMxrph plugin store. Prints one JSON object. + +list installed plugins with validation results +install SOURCE [COMMIT] [ID] git URL (cloned, optionally pinned) or a local folder; + a repository may hold several plugins (ID picks one) +remove ID delete an installed plugin + +Omarchy plugins are copied into the store and their `import qs.Ui` / +`import qs.Commons` lines are pointed at glassMxrph's compatibility layer +(qs.compat.omarchy.*). Plugins run unsandboxed inside the shell, like in +Omarchy: nothing here makes them safe, it only checks they are well formed. +""" +import json, os, re, shutil, subprocess, sys, tempfile, time +from pathlib import Path + +STORE = Path(os.environ.get('XDG_DATA_HOME') or Path.home() / '.local/share') / 'glassMxrph/plugins' +KINDS = {'bar-widget': 'barWidget', 'panel': 'panel', 'overlay': 'overlay', 'menu': 'menu', 'service': 'service', 'bar': 'bar'} +# Noctalia v4 entry points -> plugin kinds (main.qml is a headless service). +NOCTALIA_KINDS = {'barWidget': 'bar-widget', 'panel': 'panel', 'main': 'service', 'settings': 'settings', + 'desktopWidget': 'desktop-widget', 'desktopWidgetSettings': 'desktop-widget-settings', + 'controlCenterWidget': 'control-center-widget', 'launcherProvider': 'launcher-provider'} +COMPAT = Path(__file__).resolve().parent.parent / 'compat' +ID_RE = re.compile(r'^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$') +META = '.glassmxrph.json' +REWRITES = {'qs.Ui': 'qs.compat.omarchy.Ui', 'qs.Commons': 'qs.compat.omarchy.Commons'} + + +def ecosystem(manifest): + if not isinstance(manifest, dict): + return 'omarchy' + if 'schemaVersion' in manifest or 'kinds' in manifest: + return 'omarchy' + entry = manifest.get('entryPoints') + if 'minNoctaliaVersion' in manifest or (isinstance(entry, dict) and set(entry) & set(NOCTALIA_KINDS)): + return 'noctalia' + return 'omarchy' + + +def plugin_kinds(manifest): + """(kind, entry file) pairs for either format.""" + entry = (manifest or {}).get('entryPoints') or {} + if ecosystem(manifest) == 'noctalia': + return [(NOCTALIA_KINDS[k], v) for k, v in entry.items() if k in NOCTALIA_KINDS] + return [(k, entry.get(KINDS[k])) for k in (manifest or {}).get('kinds') or [] if k in KINDS] + + +def compat_modules(eco): + """qs.* module names the compatibility layer provides for an ecosystem.""" + root = COMPAT / eco + mods = set() + for d in root.rglob('*'): + if d.is_dir() and any(f.suffix == '.qml' for f in d.iterdir()): + mods.add('qs.compat.' + eco + '.' + '.'.join(d.relative_to(root).parts)) + return mods +HEX = re.compile(r'["\']#[0-9A-Fa-f]{6}(?:[0-9A-Fa-f]{2})?["\']') + + +def safe_rel(path): + p = Path(path) + return bool(path) and not p.is_absolute() and '..' not in p.parts + + +def validate(directory): + """Problems with a plugin folder (Omarchy's `plugin validate` rules, or + Noctalia's manifest rules).""" + problems = [] + try: + manifest = json.loads((directory / 'manifest.json').read_text()) + except (OSError, ValueError) as e: + return None, ['manifest.json does not parse: ' + str(e)] + eco = ecosystem(manifest) + if eco == 'omarchy' and manifest.get('schemaVersion') != 1: + problems.append('schemaVersion must be 1') + pid = manifest.get('id') + if not isinstance(pid, str) or not ID_RE.match(pid): + problems.append('invalid id') + elif pid.startswith('omarchy.') or pid.startswith('glassmxrph.'): + problems.append('reserved id prefix') + for key in ('name', 'version'): + if not isinstance(manifest.get(key), str) or not manifest.get(key): + problems.append('missing ' + key) + if eco == 'omarchy': + kinds = manifest.get('kinds') + if not isinstance(kinds, list) or not kinds or any(k not in KINDS for k in kinds): + problems.append('kinds must be a non-empty list of ' + ', '.join(KINDS)) + elif not plugin_kinds(manifest): + problems.append('entryPoints must name at least one of ' + ', '.join(NOCTALIA_KINDS)) + for kind, rel in plugin_kinds(manifest): + if not isinstance(rel, str) or not safe_rel(rel): + problems.append(f'entry point for {kind} must be a safe relative path') + elif not (directory / rel).is_file(): + problems.append(f'entry point file missing: {rel}') + for path in directory.rglob('*'): + if '.git' in path.parts: + continue + if path.is_symlink(): + problems.append('symlinks are not allowed: ' + str(path.relative_to(directory))) + return manifest, problems + + +COMPAT_BIN = Path(__file__).resolve().parent.parent / 'compat/omarchy/bin' + + +def scan_sources(directory, eco='omarchy'): + """Imports the compatibility layer lacks and hard-coded colors, for the report.""" + supported = compat_modules(eco) + unsupported, custom_colors = set(), 0 + for path in directory.rglob('*'): + if path.suffix not in ('.qml', '.js') or '.git' in path.parts: + continue + text = path.read_text(errors='ignore') + for m in re.finditer(r'^\s*import\s+(qs\.[A-Za-z0-9_.]+)', text, re.M): + if m.group(1) not in supported: + unsupported.add(m.group(1)) + custom_colors += len(HEX.findall(text)) + return sorted(unsupported), custom_colors + + +def missing_commands(directory): + """omarchy-* helper commands the plugin runs that glassMxrph does not provide.""" + used = set() + for path in directory.rglob('*'): + if path.is_file() and '.git' not in path.parts and path.suffix in ('.qml', '.js', '.sh', '.py', ''): + used |= set(re.findall(r'\b(omarchy-[a-z0-9-]+)\b', path.read_text(errors='ignore'))) + return sorted(c for c in used if not (COMPAT_BIN / c).is_file() and not shutil.which(c)) + + +SHEBANGS = re.compile(r'^#!\s*/(?:usr/)?bin/(bash|zsh|python3?|perl|node)\b') + + +def portable_shebangs(directory): + """NixOS has no /bin/bash or /usr/bin/python3: run interpreters from PATH.""" + for path in directory.rglob('*'): + if not path.is_file() or path.is_symlink() or '.git' in path.parts: + continue + try: + with path.open('rb') as f: + head = f.read(64) + if not head.startswith(b'#!'): + continue + text = path.read_text() + except (OSError, UnicodeDecodeError): + continue + new = SHEBANGS.sub(lambda m: '#!/usr/bin/env ' + m.group(1), text, count=1) + if new != text: + mode = path.stat().st_mode + path.write_text(new) + path.chmod(mode) + + +def rewrite_imports(directory, eco='omarchy'): + for path in directory.rglob('*'): + if path.suffix != '.qml' or '.git' in path.parts: + continue + text = path.read_text(errors='ignore') + new = text + if eco == 'noctalia': + new = re.sub(r'^(\s*import\s+)qs\.(Commons|Widgets|Services|Modules)\b', r'\g<1>qs.compat.noctalia.\g<2>', new, flags=re.M) + else: + for old, compat in REWRITES.items(): + new = re.sub(r'^(\s*import\s+)' + re.escape(old) + r'(\s*)$', r'\g<1>' + compat + r'\g<2>', new, flags=re.M) + if new != text: + path.write_text(new) + + +def describe(directory): + manifest, problems = validate(directory) + meta = {} + try: + meta = json.loads((directory / META).read_text()) + except (OSError, ValueError): + pass + pairs = plugin_kinds(manifest) + urls = {kind: (directory / rel).as_uri() for kind, rel in pairs if isinstance(rel, str) and safe_rel(rel)} + preview = directory / 'preview.png' + return dict(id=(manifest or {}).get('id') or directory.name, dir=str(directory), manifest=manifest or {}, + kinds=[kind for kind, _ in pairs], + problems=problems, entryUrls=urls, preview=preview.as_uri() if preview.is_file() else '', + ecosystem=meta.get('ecosystem', ecosystem(manifest)), source=meta.get('source', ''), commit=meta.get('commit', ''), + installedAt=meta.get('installedAt', 0), unsupportedImports=meta.get('unsupportedImports', []), + customColors=meta.get('customColors', 0), missingCommands=missing_commands(directory)) + + +def plugin_dirs(root): + if (root / 'manifest.json').is_file(): + return [root] + return sorted(p.parent for p in root.rglob('manifest.json') if '.git' not in p.parts and len(p.relative_to(root).parts) <= 3) + + +def install(source, commit='', only_id=''): + STORE.mkdir(parents=True, exist_ok=True) + work = Path(tempfile.mkdtemp(prefix='glassmxrph-plugin-')) + try: + if re.match(r'^(https://|git@|ssh://)', source): + subprocess.run(['git', 'clone', '--quiet', '--filter=blob:none', source, str(work / 'src')], check=True, + capture_output=True, text=True, timeout=180) + if commit: + subprocess.run(['git', '-C', str(work / 'src'), 'checkout', '--quiet', commit], check=True, + capture_output=True, text=True, timeout=60) + commit = subprocess.run(['git', '-C', str(work / 'src'), 'rev-parse', 'HEAD'], capture_output=True, + text=True).stdout.strip() + root = work / 'src' + else: + root = Path(source).expanduser().resolve() + if not root.is_dir(): + raise ValueError('not a folder or git URL: ' + source) + found = plugin_dirs(root) + if not found: + raise ValueError('no manifest.json found') + installed, rejected = [], [] + for directory in found: + manifest, problems = validate(directory) + if only_id and (manifest or {}).get('id') != only_id: + continue + if problems: + rejected.append(dict(dir=str(directory.relative_to(root)) or '.', problems=problems)) + continue + target = STORE / manifest['id'] + staging = STORE / ('.staging-' + manifest['id']) + if staging.exists(): + shutil.rmtree(staging) + shutil.copytree(directory, staging, ignore=shutil.ignore_patterns('.git'), symlinks=True) + eco = ecosystem(manifest) + _, colors = scan_sources(staging, eco) + rewrite_imports(staging, eco) + portable_shebangs(staging) + unsupported, _ = scan_sources(staging, eco) + (staging / META).write_text(json.dumps(dict(ecosystem=eco, source=source, commit=commit, + installedAt=int(time.time()), unsupportedImports=unsupported, + customColors=colors), indent=2)) + if target.exists(): + shutil.rmtree(target) + staging.rename(target) + installed.append(manifest['id']) + missing = 'plugin ' + only_id + ' not found in ' + source if only_id and not installed and not rejected else '' + return dict(ok=bool(installed), installed=installed, rejected=rejected, + error='' if installed else missing or 'no valid plugin in ' + source) + finally: + shutil.rmtree(work, ignore_errors=True) + + +def main(): + command = sys.argv[1] if len(sys.argv) > 1 else 'list' + try: + if command == 'install': + result = install(sys.argv[2], sys.argv[3] if len(sys.argv) > 3 else '', sys.argv[4] if len(sys.argv) > 4 else '') + elif command == 'remove': + pid = sys.argv[2] + if not ID_RE.match(pid) or not (STORE / pid).is_dir(): + raise ValueError('not installed: ' + pid) + shutil.rmtree(STORE / pid) + result = dict(ok=True, removed=pid) + else: + result = dict(ok=True) + result['plugins'] = [describe(d) for d in sorted(STORE.iterdir()) if d.is_dir() and not d.name.startswith('.')] if STORE.is_dir() else [] + except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e: + result = dict(ok=False, error=(getattr(e, 'stderr', '') or str(e)).strip()[-400:], plugins=[]) + except (OSError, ValueError, IndexError) as e: + result = dict(ok=False, error=str(e), plugins=[]) + print(json.dumps(result)) + + +if __name__ == '__main__': + main() diff --git a/quickshell/helpers/system.py b/quickshell/helpers/system.py new file mode 100644 index 0000000..d1bf744 --- /dev/null +++ b/quickshell/helpers/system.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +"""Small system adapters. JSON protocol, argv-only execution, no daemon installation.""" +import concurrent.futures +import json +import math +import os +from pathlib import Path +import re +import shutil +import subprocess +import sys + +def run(args, timeout=4): + result = subprocess.run(args, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=timeout, env=dict(os.environ, LC_ALL='C')) + if result.returncode: + raise ValueError((result.stderr or result.stdout or 'Command failed').strip()[-500:]) + return result.stdout.strip() + +def bus(scope, *args): + return json.loads(run(['busctl', '--'+scope, '--auto-start=no', '--timeout=3', '--json=short', *args]))['data'] + +def command(args, **values): + if not isinstance(args, list) or not args or any(not isinstance(a, str) or not a for a in args): + raise ValueError('Configure a nonempty command argument array') + return [re.sub(r'\{(value|enabled)\}', lambda m: str(values.get(m[1], m[0])).lower(), a) for a in args] + +def bounded(value, minimum, maximum): + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or not minimum <= value <= maximum: + raise ValueError('Value outside supported range') + return value + +def backlights(): + result=[] + for path in sorted(Path('/sys/class/backlight').glob('*')): + maximum=int((path/'max_brightness').read_text()) + if maximum > 0: + result.append({'id':path.name, 'value':100*int((path/'brightness').read_text())/maximum}) + return result + +def brightness(options): + if options.get('statusCommand'): + data=json.loads(run(command(options['statusCommand']))) + bounded(data['value'], 0, 100) + if 'available' in data and type(data['available']) is not bool:raise ValueError('Provider availability must be a boolean') + return dict(data, available=bool(data.get('available', True)), provider='custom', devices=[]) + devices=backlights() + device=next((d for d in devices if d['id']==options.get('device')), devices[0] if devices and options.get('device','auto')=='auto' else None) + return {'available':bool(device) and bool(shutil.which('brightnessctl')), 'value':device['value'] if device else 0, 'device':device['id'] if device else '', 'devices':devices, 'provider':'brightnessctl', 'notice':'' if device else 'No selected backlight device. External displays need a configured brightness provider.'} + +def night(options): + if options.get('statusCommand'): + data=json.loads(run(command(options['statusCommand']))) + if 'available' in data and type(data['available']) is not bool:raise ValueError('Provider availability must be a boolean') + if type(data.get('enabled')) is not bool:raise ValueError('Night Light status must include enabled: true/false') + return dict(data, available=bool(data.get('available',True)), provider='custom') + temp=bus('user','get-property','rs.wl-gammarelay','/','rs.wl.gammarelay','Temperature') + return {'available':True,'enabled':temp<6500,'temperature':temp,'provider':'wl-gammarelay'} + +def notifications(): + value=bus('user','call','org.erikreider.swaync.cc','/org/erikreider/swaync/cc','org.erikreider.swaync.cc','GetDnd')[0] + if type(value) is not bool:raise ValueError('SwayNC did not return a DND state') + return {'available':True,'enabled':value} + +def profiles(): + service='net.hadess.PowerProfiles';path='/net/hadess/PowerProfiles' + values=bus('system','get-property',service,path,service,'Profiles') + current=bus('system','get-property',service,path,service,'ActiveProfile') + return {'available':True,'current':current,'profiles':[p['Profile']['data'] for p in values]} + +def lock_command(options): + if options.get('lockCommand'):return command(options['lockCommand']) + if shutil.which('serpantinum'):return ['serpantinum','lock'] + if shutil.which('hyprlock'):return ['hyprlock'] + return [] + +def power(options): + result={'available':True,'lock':bool(lock_command(options)),'logout':bool(os.environ.get('HYPRLAND_INSTANCE_SIGNATURE')) and bool(shutil.which('hyprctl'))} + for key,method in [('suspend','CanSuspend'),('reboot','CanReboot'),('shutdown','CanPowerOff')]: + try:result[key]=bus('system','call','org.freedesktop.login1','/org/freedesktop/login1','org.freedesktop.login1.Manager',method)[0] in ['yes','challenge'] + except (ValueError,OSError,subprocess.TimeoutExpired):result[key]=False + return result + +def safely(fn): + try:return fn() + except (ValueError,OSError,KeyError,TypeError,subprocess.TimeoutExpired) as error:return {'available':False,'notice':str(error)} + +def snapshot(options, features=None): + jobs={'brightness':lambda:brightness(options['brightness']), 'nightLight':lambda:night(options['nightLight']), 'dnd':notifications, 'profiles':profiles, 'power':lambda:power(options['power'])} + if features is not None:jobs={key:fn for key,fn in jobs.items() if key in features} + if not jobs:return {} + with concurrent.futures.ThreadPoolExecutor(max_workers=len(jobs)) as pool: + return dict(zip(jobs,pool.map(safely,jobs.values()))) + +def action(req): + options=req['options'];kind=req['action'];value=req.get('value') + if kind=='brightness': + value=round(bounded(value,1,100)) + spec=options['brightness'] + if spec.get('setCommand'):run(command(spec['setCommand'],value=value)) + else: + state=brightness(spec) + if not state['available'] or state['provider']!='brightnessctl':raise ValueError('No writable brightness provider') + run(['brightnessctl','--class=backlight','--device='+state['device'],'set',str(value)+'%']) + elif kind=='nightLight': + if type(value) is not bool:raise ValueError('Night Light expects a boolean') + spec=options['nightLight'] + if spec.get('setCommand'):run(command(spec['setCommand'],enabled=value,value=spec['temperature'] if value else 6500)) + else: + night(spec) # Require a running provider; never auto-start a second gamma daemon. + temperature=round(bounded(spec['temperature'],1000,6500)) if value else 6500 + run(['busctl','--user','--auto-start=no','--timeout=3','set-property','rs.wl-gammarelay','/','rs.wl.gammarelay','Temperature','q',str(temperature)]) + elif kind=='dnd': + if type(value) is not bool:raise ValueError('DND expects a boolean') + notifications() + run(['busctl','--user','--auto-start=no','--timeout=3','call','org.erikreider.swaync.cc','/org/erikreider/swaync/cc','org.erikreider.swaync.cc','SetDnd','b',str(value).lower()]) + elif kind=='profile': + if value not in profiles()['profiles']:raise ValueError('Unsupported power profile') + run(['busctl','--system','--auto-start=no','--timeout=3','set-property','net.hadess.PowerProfiles','/net/hadess/PowerProfiles','net.hadess.PowerProfiles','ActiveProfile','s',value]) + elif kind=='power': + if value not in ['lock','logout','suspend','reboot','shutdown']:raise ValueError('Unsupported power action') + if value in ['logout','reboot','shutdown'] and req.get('confirmed') is not True:raise ValueError('Explicit confirmation required') + if not power(options['power']).get(value):raise ValueError('Power action unavailable') + if value=='lock':subprocess.Popen(lock_command(options['power']),stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,start_new_session=True) + elif value=='logout':run(['hyprctl','dispatch','exit']) + else:run(['busctl','--system','--auto-start=no','--timeout=10','call','org.freedesktop.login1','/org/freedesktop/login1','org.freedesktop.login1.Manager',{'suspend':'Suspend','reboot':'Reboot','shutdown':'PowerOff'}[value],'b','true'],15) + elif kind=='manager': + executable={'network':'nm-connection-editor','bluetooth':'blueman-manager'}.get(value) + if not executable or not shutil.which(executable):raise ValueError('The existing connection manager is not installed') + subprocess.Popen([executable],stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,start_new_session=True) + else:raise ValueError('Unsupported action') + return {'state':snapshot(options)} + +def main(req): + if req.get('op')=='status':return {'state':snapshot(req['options'],req.get('features'))} + if req.get('op')=='action':return action(req) + raise ValueError('Unsupported operation') + +if __name__=='__main__': + try:print(json.dumps(dict(ok=True,**main(json.loads(sys.argv[1]))))) + except (ValueError,OSError,KeyError,TypeError,subprocess.TimeoutExpired) as error: + print(json.dumps({'ok':False,'error':str(error)})) + sys.exit(1) diff --git a/quickshell/helpers/weather.py b/quickshell/helpers/weather.py new file mode 100644 index 0000000..462eea9 --- /dev/null +++ b/quickshell/helpers/weather.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python3 +"""Current weather from wttr.in as compact JSON: {ok, place, temperature, feels, code, description}.""" +import json, sys, urllib.parse, urllib.request + +def main(): + location = sys.argv[1] if len(sys.argv) > 1 else '' + url = 'https://wttr.in/' + urllib.parse.quote(location) + '?format=j1' + try: + with urllib.request.urlopen(urllib.request.Request(url, headers={'User-Agent': 'glassMxrph'}), timeout=12) as response: + data = json.load(response) + now = data['current_condition'][0] + area = (data.get('nearest_area') or [{}])[0] + place = (area.get('areaName') or [{'value': ''}])[0]['value'] + print(json.dumps(dict(ok=True, place=place or location, celsius=float(now['temp_C']), feelsCelsius=float(now['FeelsLikeC']), + code=int(now['weatherCode']), description=now['weatherDesc'][0]['value'].strip(), + humidity=int(now['humidity']), wind=float(now['windspeedKmph'])))) + except Exception as error: # Network, HTTP and format errors all surface as a message. + print(json.dumps(dict(ok=False, error=str(error)))) + +if __name__ == '__main__': + main() diff --git a/quickshell/launcher/AppSearch.qml b/quickshell/launcher/AppSearch.qml new file mode 100644 index 0000000..ce0b254 --- /dev/null +++ b/quickshell/launcher/AppSearch.qml @@ -0,0 +1,37 @@ +import QtQuick +import "../services" +import "SearchLogic.js" as Search + +QtObject { + property string query: "" + property int limit: 50 + property bool enabled: false + readonly property var indexed: Search.index(ApplicationsService.launchable.map(entry => ({ + id: entry.id, + title: entry.name, + description: entry.genericName || entry.comment || entry.id, + entry: entry, + fields: [ + { + text: entry.name + }, + { + text: entry.genericName, + penalty: 150 + }, + { + text: entry.id, + penalty: 300 + }, + { + text: entry.keywords.join(" "), + penalty: 200 + }, + { + text: entry.comment, + penalty: 500 + } + ] + }))) + readonly property var results: enabled ? Search.rank(indexed, query, limit) : [] +} diff --git a/quickshell/launcher/CommandRegistry.qml b/quickshell/launcher/CommandRegistry.qml new file mode 100644 index 0000000..521c815 --- /dev/null +++ b/quickshell/launcher/CommandRegistry.qml @@ -0,0 +1,36 @@ +pragma Singleton +import QtQuick +import Quickshell +import "../core" + +Singleton { + id: root + property var extensions: [] + readonly property var commands: SettingsRegistry.pages.map(page => ({ + id: page.command, + title: page.title, + description: page.description, + page: page.id, + available: page.available + })).concat(extensions) + // Extensions are registered by trusted QML code, never interpreted from search text. + function registerCommand(command) { + if (!command || !/^[a-z][a-z0-9-]*$/.test(command.id) || !command.title || typeof command.run !== "function" || commands.some(c => c.id === command.id)) + return false; + extensions = extensions.concat([command]); + return true; + } + function unregisterCommand(id) { + extensions = extensions.filter(c => c.id !== id); + } + function execute(id) { + const command = commands.find(c => c.id === id); + if (!command) + return false; + if (command.run) + command.run(); + else + ShellState.openSettings(command.page); + return true; + } +} diff --git a/quickshell/launcher/CommandSearch.qml b/quickshell/launcher/CommandSearch.qml new file mode 100644 index 0000000..fa541b4 --- /dev/null +++ b/quickshell/launcher/CommandSearch.qml @@ -0,0 +1,27 @@ +import QtQuick +import "SearchLogic.js" as Search + +QtObject { + property string query: "" + property int limit: 50 + property bool enabled: false + readonly property var indexed: Search.index(CommandRegistry.commands.map(command => ({ + id: command.id, + title: command.title, + description: command.description || "Shell command", + command: true, + fields: [ + { + text: command.id + }, + { + text: command.title + }, + { + text: command.description, + penalty: 500 + } + ] + }))) + readonly property var results: enabled ? Search.rank(indexed, query.replace(/^\s*>/, ""), limit) : [] +} diff --git a/quickshell/launcher/Launcher.qml b/quickshell/launcher/Launcher.qml new file mode 100644 index 0000000..2c1f61a --- /dev/null +++ b/quickshell/launcher/Launcher.qml @@ -0,0 +1,449 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import Quickshell +import Quickshell.Wayland +import "../components" +import "../services" +import "../theme" +import "../core" + +// Spotlight-style launcher: opens as a single search bar in the upper third. +// Typing shows ranked results below it; the magnifying glass (or ↓ in an +// empty bar) browses every application as an icon grid; > lists commands. +// Runtime selects the concrete Wayland layer implementation. +// qmllint disable uncreatable-type +PanelWindow { + // qmllint enable uncreatable-type + id: root + screen: ScreenService.current(ShellState.launcherScreen) + anchors { + top: true + bottom: true + left: true + right: true + } + visible: ShellState.launcherOpen || panel.opacity > 0.01 + color: Theme.transparent + exclusionMode: ExclusionMode.Ignore + WlrLayershell.namespace: "glassMxrph-launcher" + WlrLayershell.layer: WlrLayer.Overlay + WlrLayershell.keyboardFocus: ShellState.launcherOpen ? WlrKeyboardFocus.Exclusive : WlrKeyboardFocus.None + readonly property var options: ConfigService.ready ? ConfigService.data.launcher : ({ + width: 680, + maxResults: 50, + showDescriptions: true + }) + readonly property string query: search.text.trim() + readonly property bool commandMode: query.startsWith(">") + property bool browsing: false + readonly property bool showList: query !== "" + readonly property bool showGrid: !showList && browsing + readonly property var allApps: ApplicationsService.launchable.map(entry => ({ + id: entry.id, + title: entry.name, + description: entry.genericName || entry.comment || entry.id, + entry: entry + })) + readonly property var results: showList ? (commandMode ? commands.results : apps.results) : showGrid ? allApps : [] + property int selectedIndex: 0 + property string launchError: "" + readonly property real targetWidth: Math.min(options.width, root.width - 40) + readonly property int barHeight: 60 + readonly property real maxBodyHeight: Math.min(460, root.height * 0.78 - barHeight - (root.height * 0.22)) + readonly property real bodyHeight: showList ? Math.min(maxBodyHeight, Math.max(84, list.contentHeight + 46 + (launchError ? 22 : 0))) : showGrid ? Math.min(maxBodyHeight, grid.contentHeight + 46) : 0 + readonly property int gridColumns: Math.max(1, Math.floor((targetWidth - 24) / 112)) + onResultsChanged: { + selectedIndex = 0; + list.contentY = 0; + grid.contentY = 0; + } + function select(offset) { + if (!results.length) + return; + selectedIndex = Math.max(0, Math.min(results.length - 1, selectedIndex + offset)); + if (showGrid) + grid.positionViewAtIndex(selectedIndex, GridView.Contain); + else + list.positionViewAtIndex(selectedIndex, ListView.Contain); + } + function activate(index) { + const result = results[index]; + if (!result) + return; + if (result.command) { + ShellState.launcherOpen = false; + CommandRegistry.execute(result.id); + } else if (ApplicationsService.launch(result.entry, null)) + ShellState.launcherOpen = false; + else + launchError = ApplicationsService.error; + } + function toggleBrowse() { + browsing = !browsing; + if (browsing) + search.clear(); + selectedIndex = 0; + search.forceActiveFocus(); + } + Component.onCompleted: LauncherState.window = root + Component.onDestruction: LauncherState.window = null + Connections { + target: ShellState + function onLauncherOpenChanged() { + if (ShellState.launcherOpen) { + search.text = ""; + root.browsing = false; + root.launchError = ""; + root.selectedIndex = 0; + Qt.callLater(() => search.forceActiveFocus()); + } + } + } + AppSearch { + id: apps + enabled: ShellState.launcherOpen && root.showList && !root.commandMode + query: search.text + limit: root.options.maxResults + } + CommandSearch { + id: commands + enabled: ShellState.launcherOpen && root.commandMode + query: search.text + limit: root.options.maxResults + } + MouseArea { + anchors.fill: parent + onClicked: ShellState.launcherOpen = false + } + GlassPanel { + id: panel + objectName: "launcherSurface" + x: Math.round((root.width - width) / 2) + y: Math.round(root.height * 0.22) + width: ShellState.launcherOpen ? root.targetWidth : Math.min(320, root.targetWidth) + height: root.barHeight + root.bodyHeight + radius: Math.min(Theme.radius + 6, root.barHeight / 2) + opacity: ShellState.launcherOpen ? 1 : 0 + scale: ShellState.launcherOpen ? 1 : 1 - 0.04 * Theme.intensity + clip: true + Behavior on width { + NumberAnimation { + duration: Theme.duration + easing.type: Easing.OutCubic + } + } + Behavior on height { + NumberAnimation { + duration: Theme.duration + easing.type: Easing.OutCubic + } + } + Behavior on opacity { + NumberAnimation { + duration: Theme.duration + } + } + Behavior on scale { + NumberAnimation { + duration: Theme.duration + easing.type: Easing.OutCubic + } + } + MouseArea { + anchors.fill: parent + } // Consume inside clicks without dismissing. + + // Search bar + RowLayout { + id: bar + anchors.left: parent.left + anchors.right: parent.right + anchors.top: parent.top + height: root.barHeight + anchors.leftMargin: 12 + anchors.rightMargin: 18 + spacing: 10 + Rectangle { + objectName: "launcherBrowse" + Layout.preferredWidth: 38 + Layout.preferredHeight: 38 + radius: 12 + color: root.browsing ? Theme.accent : browseArea.containsMouse ? Theme.hover : Theme.transparent + Accessible.role: Accessible.Button + Accessible.name: root.browsing ? "Hide applications" : "Show all applications" + Behavior on color { + ColorAnimation { + duration: Theme.duration / 2 + } + } + Text { + anchors.centerIn: parent + text: root.commandMode ? ">" : Icons.available ? "󰍉" : "⌕" + font.family: Icons.available && !root.commandMode ? Icons.family : "" + color: root.browsing ? Theme.accentText : Theme.textSecondary + font.pixelSize: 20 + } + MouseArea { + id: browseArea + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: root.toggleBrowse() + } + ToolTip.visible: browseArea.containsMouse + ToolTip.delay: 600 + ToolTip.text: root.browsing ? "Hide applications" : "All applications" + } + TextField { + id: search + objectName: "launcherSearch" + Layout.fillWidth: true + Layout.preferredHeight: 40 + placeholderText: root.browsing ? "Search applications" : "Spotlight Search" + color: Theme.text + placeholderTextColor: Theme.textSecondary + selectByMouse: true + font.pixelSize: 22 + font.weight: Font.Light + background: Item {} + padding: 0 + maximumLength: 256 + onTextEdited: root.launchError = "" + Keys.onEscapePressed: { + if (text !== "") + clear(); + else if (root.browsing) + root.browsing = false; + else + ShellState.launcherOpen = false; + } + Keys.onDownPressed: { + if (!root.showList && !root.browsing) + root.browsing = true; + else + root.select(root.showGrid ? root.gridColumns : 1); + } + Keys.onUpPressed: root.select(root.showGrid ? -root.gridColumns : -1) + Keys.onRightPressed: event => { + if (root.showGrid || event.modifiers & Qt.ControlModifier) + root.select(1); + else + event.accepted = false; + } + Keys.onLeftPressed: event => { + if (root.showGrid || event.modifiers & Qt.ControlModifier) + root.select(-1); + else + event.accepted = false; + } + Keys.onTabPressed: root.select(1) + Keys.onBacktabPressed: root.select(-1) + Keys.onReturnPressed: root.activate(root.selectedIndex) + Keys.onEnterPressed: root.activate(root.selectedIndex) + } + } + + // Results (typing) or the application grid (magnifying glass). + Item { + id: body + anchors.left: parent.left + anchors.right: parent.right + anchors.top: bar.bottom + anchors.bottom: parent.bottom + visible: root.bodyHeight > 0 || panel.height > root.barHeight + 1 + Rectangle { + anchors.left: parent.left + anchors.right: parent.right + anchors.leftMargin: 14 + anchors.rightMargin: 14 + height: 1 + color: Theme.border + } + Text { + id: section + x: 22 + y: 12 + text: root.showGrid ? "Applications" : root.commandMode ? "Settings" : root.results.length ? "Top hits" : "" + color: Theme.textSecondary + font.pixelSize: 11 + font.weight: Font.DemiBold + } + ListView { + id: list + objectName: "launcherResults" + visible: root.showList + anchors.fill: parent + anchors.topMargin: 32 + anchors.leftMargin: 8 + anchors.rightMargin: 8 + anchors.bottomMargin: root.launchError ? 30 : 8 + clip: true + model: root.showList ? root.results : [] + spacing: 2 + boundsBehavior: Flickable.StopAtBounds + ScrollBar.vertical: ScrollBar {} + delegate: Rectangle { + id: resultRow + required property var modelData + required property int index + readonly property bool selected: root.selectedIndex === index + width: list.width + height: 46 + radius: 10 + color: selected ? Theme.accent : mouse.containsMouse ? Theme.hover : Theme.transparent + RowLayout { + anchors.fill: parent + anchors.leftMargin: 10 + anchors.rightMargin: 12 + spacing: 12 + Item { + Layout.preferredWidth: 30 + Layout.preferredHeight: 30 + Image { + id: icon + anchors.fill: parent + source: resultRow.modelData.entry ? ApplicationsService.icon(resultRow.modelData.entry) : "" + sourceSize: Qt.size(60, 60) + fillMode: Image.PreserveAspectFit + } + Text { + anchors.centerIn: parent + visible: icon.source.toString() === "" || icon.status === Image.Error + text: resultRow.modelData.command ? "⚙" : resultRow.modelData.title.slice(0, 2).toUpperCase() + color: resultRow.selected ? Theme.accentText : Theme.textSecondary + font.pixelSize: 16 + } + } + Text { + text: resultRow.modelData.title + elide: Text.ElideRight + color: resultRow.selected ? Theme.accentText : Theme.text + font.pixelSize: 14 + font.weight: Font.Medium + } + Text { + visible: root.options.showDescriptions + text: "— " + resultRow.modelData.description + Layout.fillWidth: true + elide: Text.ElideRight + color: resultRow.selected ? Qt.alpha(Theme.accentText, 0.75) : Theme.textSecondary + font.pixelSize: 12 + } + Item { + visible: !root.options.showDescriptions + Layout.fillWidth: true + } + Text { + text: resultRow.modelData.command ? "Settings" : "Application" + color: resultRow.selected ? Qt.alpha(Theme.accentText, 0.75) : Theme.textSecondary + font.pixelSize: 11 + } + } + MouseArea { + id: mouse + anchors.fill: parent + hoverEnabled: true + // Hover highlights locally; only keys change keyboard selection. + // Layout/scroll movement under a stationary pointer must not steal it. + onClicked: root.activate(resultRow.index) + } + Accessible.role: Accessible.Button + Accessible.name: modelData.title + Accessible.onPressAction: root.activate(index) + } + } + GridView { + id: grid + objectName: "launcherApps" + visible: root.showGrid + anchors.fill: parent + anchors.topMargin: 32 + anchors.leftMargin: 12 + anchors.rightMargin: 12 + anchors.bottomMargin: 10 + clip: true + model: root.showGrid ? root.results : [] + cellWidth: Math.floor(width / root.gridColumns) + cellHeight: 100 + boundsBehavior: Flickable.StopAtBounds + ScrollBar.vertical: ScrollBar {} + delegate: Item { + id: tile + required property var modelData + required property int index + readonly property bool selected: root.selectedIndex === index + width: grid.cellWidth + height: grid.cellHeight + Rectangle { + anchors.fill: parent + anchors.margins: 4 + radius: 14 + color: tile.selected ? Qt.alpha(Theme.accent, 0.35) : tileArea.containsMouse ? Theme.hover : Theme.transparent + border.width: tile.selected ? 1 : 0 + border.color: Theme.accentVivid + } + Column { + anchors.centerIn: parent + spacing: 6 + Image { + id: tileIcon + anchors.horizontalCenter: parent.horizontalCenter + width: 52 + height: 52 + source: ApplicationsService.icon(tile.modelData.entry) + sourceSize: Qt.size(104, 104) + fillMode: Image.PreserveAspectFit + asynchronous: true + Text { + anchors.centerIn: parent + visible: tileIcon.source.toString() === "" || tileIcon.status === Image.Error + text: tile.modelData.title.slice(0, 2).toUpperCase() + color: Theme.textSecondary + font.pixelSize: 18 + } + } + Text { + anchors.horizontalCenter: parent.horizontalCenter + width: grid.cellWidth - 12 + horizontalAlignment: Text.AlignHCenter + text: tile.modelData.title + elide: Text.ElideRight + color: Theme.text + font.pixelSize: 11 + } + } + MouseArea { + id: tileArea + anchors.fill: parent + hoverEnabled: true + onClicked: root.activate(tile.index) + } + Accessible.role: Accessible.Button + Accessible.name: modelData.title + Accessible.onPressAction: root.activate(index) + } + } + Text { + anchors.centerIn: parent + anchors.verticalCenterOffset: 12 + visible: root.showList && root.results.length === 0 + text: root.commandMode ? "No matching settings" : "No results" + color: Theme.textSecondary + font.pixelSize: 13 + } + Text { + anchors.left: parent.left + anchors.right: parent.right + anchors.bottom: parent.bottom + anchors.margins: 12 + visible: !!root.launchError + elide: Text.ElideRight + text: root.launchError + color: Theme.urgent + font.pixelSize: 12 + } + } + } +} diff --git a/quickshell/launcher/LauncherState.qml b/quickshell/launcher/LauncherState.qml new file mode 100644 index 0000000..7c6d66f --- /dev/null +++ b/quickshell/launcher/LauncherState.qml @@ -0,0 +1,29 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Io +import "../core" + +Singleton { + id: root + property var window: null + IpcHandler { + target: "launcher" + function toggle(): void { + ShellState.toggleLauncher(); + } + function open(): void { + ShellState.openLauncher(); + } + function close(): void { + ShellState.launcherOpen = false; + } + function status(): string { + return JSON.stringify({ + opened: ShellState.launcherOpen, + screen: root.window && root.window.screen ? root.window.screen.name : "", + ready: !!root.window + }); + } + } +} diff --git a/quickshell/launcher/SearchLogic.js b/quickshell/launcher/SearchLogic.js new file mode 100644 index 0000000..dc7d4d7 --- /dev/null +++ b/quickshell/launcher/SearchLogic.js @@ -0,0 +1,39 @@ +// Pure ranking logic shared by application and command search. No process execution. +function normalize(text) { + return String(text || "").normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase().trim(); +} +function score(text, needle) { + if (!needle) return 0; + if (text === needle) return 10000; + if (text.startsWith(needle)) return 8000 - Math.min(text.length, 500); + const inside = text.indexOf(needle); + if (inside >= 0) return 6000 - inside * 4 - Math.min(text.length, 500); + let cursor = 0, previous = -1, value = 1000; + for (const letter of needle) { + const index = text.indexOf(letter, cursor); + if (index < 0) return -Infinity; + value += index === previous + 1 ? 30 : 0; + if (index === 0 || /[\s._/-]/.test(text[index - 1])) value += 45; + value -= index - cursor; + previous = index; cursor = index + 1; + } + return value - Math.min(text.length, 500); +} +function index(items) { + return items.map(item => ({item:item,fields:item.fields.map(field => ({text:normalize(field.text),penalty:field.penalty || 0}))})); +} +function rank(indexed, query, limit) { + const tokens = normalize(query).split(/\s+/).filter(Boolean); + const matches = []; + for (const row of indexed) { + let total = 0; + for (const token of tokens) { + const best = Math.max(...row.fields.map(field => score(field.text,token) - field.penalty)); + if (!Number.isFinite(best)) {total=-Infinity;break;} + total += best; + } + if (Number.isFinite(total)) matches.push({item:row.item,score:total}); + } + matches.sort((a,b) => b.score-a.score || a.item.title.localeCompare(b.item.title) || a.item.id.localeCompare(b.item.id)); + return matches.slice(0,limit).map(row => row.item); +} diff --git a/quickshell/launcher/qmldir b/quickshell/launcher/qmldir new file mode 100644 index 0000000..98b5dfc --- /dev/null +++ b/quickshell/launcher/qmldir @@ -0,0 +1,5 @@ +singleton CommandRegistry 1.0 CommandRegistry.qml +singleton LauncherState 1.0 LauncherState.qml +AppSearch 1.0 AppSearch.qml +CommandSearch 1.0 CommandSearch.qml +Launcher 1.0 Launcher.qml diff --git a/quickshell/lock/GlassSurface.qml b/quickshell/lock/GlassSurface.qml new file mode 100644 index 0000000..b35fbf1 --- /dev/null +++ b/quickshell/lock/GlassSurface.qml @@ -0,0 +1,82 @@ +import QtQuick +import QtQuick.Effects + +// Liquid glass over the lock screen backdrop (see shaders/glass.frag). +// Must be a direct child of the item that `backdrop` covers, so its own x/y +// map straight onto the backdrop. The shape is a rounded rectangle unless +// `shape` children are supplied (drawn opaque, e.g. white Text). +Item { + id: root + required property var backdrop // ShaderEffectSource of the frosted backdrop + required property Item space // item the backdrop covers (this item's parent) + property real radius: Math.min(width, height) / 2 + property bool glass: true + property color tint: "#000000" + property real tintAmount: 0.18 + property real brightness: LockState.glass.brightness + default property alias shape: shapeHolder.data + readonly property bool customShape: shapeHolder.children.length > 1 + + Item { + id: shapeHolder + anchors.fill: parent + Rectangle { + anchors.fill: parent + radius: root.radius + visible: !root.customShape && root.glass + } + } + // With glass off the custom shape stays visible as-is (e.g. white clock digits). + ShaderEffectSource { + id: maskSource + sourceItem: shapeHolder + hideSource: root.glass + visible: false + } + MultiEffect { + id: heightEffect + anchors.fill: parent + source: maskSource + blurEnabled: true + blur: 1 + blurMax: Math.round(LockState.glass.edge) + autoPaddingEnabled: false + visible: false + } + ShaderEffectSource { + id: heightSource + sourceItem: heightEffect + hideSource: true + visible: false + } + ShaderEffect { + anchors.fill: parent + visible: root.glass && root.space.width > 0 + property variant backdropMap: root.backdrop + property variant maskMap: maskSource + property variant heightMap: heightSource + property vector4d sourceRect: Qt.vector4d(root.x / root.space.width, root.y / root.space.height, root.width / root.space.width, root.height / root.space.height) + property point pixelStep: Qt.point(1 / Math.max(1, root.width), 1 / Math.max(1, root.height)) + property real refraction: LockState.glass.refraction + property real dispersion: LockState.glass.dispersion + property real fresnel: LockState.glass.fresnel + property real specular: LockState.glass.specular + property real brightness: root.brightness + property real saturation: LockState.glass.saturation + property vector4d tint: Qt.vector4d(root.tint.r, root.tint.g, root.tint.b, root.tintAmount) + fragmentShader: Qt.resolvedUrl("shaders/glass.frag.qsb") + } + // Without glass: a plain translucent surface with a hairline. + Item { + anchors.fill: parent + visible: !root.glass + Rectangle { + anchors.fill: parent + visible: !root.customShape + radius: root.radius + color: Qt.alpha("#ffffff", 0.16) + border.width: 1 + border.color: Qt.alpha("#ffffff", 0.25) + } + } +} diff --git a/quickshell/lock/Lock.qml b/quickshell/lock/Lock.qml new file mode 100644 index 0000000..7795626 --- /dev/null +++ b/quickshell/lock/Lock.qml @@ -0,0 +1,45 @@ +pragma ComponentBehavior: Bound +import QtQuick +import Quickshell +import Quickshell.Wayland + +// The session lock (ext-session-lock: one surface per output) plus the +// preview, which shows the same UI in ordinary overlay windows. +Scope { + WlSessionLock { + locked: LockState.locked + WlSessionLockSurface { + id: surface + color: "#000000" + LockSurface { + anchors.fill: parent + screenName: surface.screen ? surface.screen.name : "" + } + } + } + Variants { + model: LockState.previewing ? Quickshell.screens : [] + // qmllint disable uncreatable-type + PanelWindow { + id: previewWindow + required property var modelData + screen: modelData + anchors { + top: true + bottom: true + left: true + right: true + } + color: "#000000" + exclusionMode: ExclusionMode.Ignore + WlrLayershell.layer: WlrLayer.Overlay + WlrLayershell.namespace: "glassMxrph-lock-preview" + WlrLayershell.keyboardFocus: WlrKeyboardFocus.Exclusive + LockSurface { + anchors.fill: parent + screenName: previewWindow.modelData.name + preview: true + } + } + } +} diff --git a/quickshell/lock/LockState.qml b/quickshell/lock/LockState.qml new file mode 100644 index 0000000..e31f746 --- /dev/null +++ b/quickshell/lock/LockState.qml @@ -0,0 +1,233 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Io +import Quickshell.Services.Pam +import "../services" +import "../core" + +// Lock screen state and authentication. Every attempt starts a fresh PAM +// conversation (the bundled pam/password.conf, or a system service when +// lock.pamService is set) and answers its password prompt. +Singleton { + id: root + readonly property var options: ConfigService.ready ? ConfigService.data.lock : ({ + enabled: true, + backdrop: "wallpaper", + glass: true, + media: true, + powerButtons: true, + pamService: "" + }) + property bool locked: false + // A preview runs the same UI in ordinary windows: nothing is locked and a + // correct password simply closes it. Used by Settings and for testing. + property bool previewing: false + property bool unlocking: false + property string primary: "" + property string status: "" + property bool busy: false + property int failures: 0 + property string purpose: "" + property var pending: null + property string testResult: "" + property var shots: ({}) + // Live lock surfaces, for diagnostics and tests. + property var surfaces: [] + property string realName: "" + // Active keyboard layout, read from Hyprland when the lock screen shows. + property string layout: "" + readonly property bool shown: locked || previewing + readonly property string runtimeDir: (Quickshell.env("XDG_RUNTIME_DIR") || "/tmp") + "/glassMxrph" + + // Glass parameters follow the desktop's HyprGlass values for a matching look. + readonly property var glass: { + const v = ConfigService.ready ? ConfigService.data.hyprglass.values : {}; + const pick = (key, fallback) => Number.isFinite(v[key]) ? v[key] : fallback; + return { + refraction: pick("refraction_strength", 3) * 6, + dispersion: Math.min(0.6, pick("chromatic_aberration", 0.45) * 0.35), + fresnel: pick("fresnel_strength", 0.5), + specular: pick("specular_strength", 0.8), + edge: Math.max(10, pick("edge_thickness", 0.065) * 300), + frost: Math.min(1, pick("blur_strength", 0.45) / 1.2 + 0.25), + brightness: pick("brightness", 0.95), + saturation: pick("saturation", 1) * (1 + pick("vibrancy", 0.15)) + }; + } + + function lock() { + if (locked || grab.running) + return; + previewing = false; + ShellState.settingsOpen = false; + ShellState.controlCenterOpen = false; + ShellState.launcherOpen = false; + primary = ScreenService.active ? ScreenService.active.name : ""; + status = ""; + if (options.backdrop === "screenshot") { + grab.names = Quickshell.screens.map(s => s.name).filter(n => /^[\w.-]+$/.test(n)); + grab.running = true; + grabTimeout.restart(); + } else + locked = true; + } + function preview() { + if (locked) + return; + ShellState.settingsOpen = false; + primary = ScreenService.active ? ScreenService.active.name : ""; + status = ""; + previewing = true; + } + function cancelPreview() { + if (previewing && !busy) { + previewing = false; + status = ""; + } + } + function submit(password, why) { + if (busy || !password) + return false; + purpose = why || (previewing ? "preview" : "unlock"); + pending = password; + busy = true; + status = ""; + if (!pam.start()) { + busy = false; + pending = null; + status = "Authentication is unavailable"; + if (purpose === "test") + testResult = "error"; + return false; + } + return true; + } + function test(password) { + testResult = ""; + return submit(password, "test"); + } + function finishUnlock() { + unlocking = true; + unlockTimer.restart(); + } + + Connections { + target: ShellState + function onLockRequested() { + root.lock(); + } + } + PamContext { + id: pam + config: root.options.pamService || "password.conf" + configDirectory: root.options.pamService ? "/etc/pam.d" : Qt.resolvedUrl("pam") + onPamMessage: { + if (responseRequired && root.pending !== null) { + respond(root.pending); + root.pending = null; + } + } + onCompleted: result => { + root.busy = false; + root.pending = null; + const ok = result === PamResult.Success; + if (root.purpose === "test") { + root.testResult = ok ? "accepted" : "rejected"; + return; + } + if (ok) + root.finishUnlock(); + else { + root.failures++; + root.status = result === PamResult.Error ? "Authentication error" : "Incorrect password"; + } + } + } + Timer { + id: unlockTimer + interval: 420 + onTriggered: { + root.locked = false; + root.previewing = false; + root.unlocking = false; + root.status = ""; + if (Object.keys(root.shots).length) { + Quickshell.execDetached(["rm", "-f"].concat(Object.values(root.shots))); + root.shots = {}; + } + } + } + // Screenshot backdrops: one grim capture per output, then lock (or lock anyway after a timeout). + Process { + id: grab + property var names: [] + command: ["sh", "-c", "mkdir -p \"$1\" && shift && dir=\"$1\" && shift && for name; do grim -l 0 -o \"$name\" \"$dir/lock-$name.png\" & done; wait", "sh", root.runtimeDir, root.runtimeDir].concat(names) + // Quickshell 0.3.1 omits QProcess::ExitStatus from its type metadata. + // qmllint disable signal-handler-parameters + onExited: { + grabTimeout.stop(); + const shots = {}; + for (const name of names) + shots[name] = root.runtimeDir + "/lock-" + name + ".png"; + root.shots = shots; + root.locked = true; + } + // qmllint enable signal-handler-parameters + } + Timer { + id: grabTimeout + interval: 1500 + onTriggered: { + grab.running = false; + root.locked = true; + } + } + onShownChanged: if (shown) + layoutProbe.running = true + Process { + id: layoutProbe + command: ["hyprctl", "devices", "-j"] + stdout: StdioCollector { + onStreamFinished: { + try { + const keyboards = JSON.parse(text).keyboards || []; + const main = keyboards.find(k => k.main) || keyboards[0]; + root.layout = main && main.active_keymap ? main.active_keymap.slice(0, 2).toUpperCase() : ""; + } catch (e) { + root.layout = ""; + } + } + } + } + Process { + running: true + command: ["sh", "-c", "getent passwd \"$USER\" | cut -d: -f5 | cut -d, -f1"] + stdout: StdioCollector { + onStreamFinished: root.realName = text.trim() + } + } + + IpcHandler { + target: "lock" + function lock(): void { + root.lock(); + } + function preview(): void { + root.preview(); + } + function closePreview(): void { + root.cancelPreview(); + } + function status(): string { + return JSON.stringify({ + locked: root.locked, + previewing: root.previewing, + busy: root.busy, + status: root.status, + primary: root.primary, + testResult: root.testResult + }); + } + } +} diff --git a/quickshell/lock/LockSurface.qml b/quickshell/lock/LockSurface.qml new file mode 100644 index 0000000..e755671 --- /dev/null +++ b/quickshell/lock/LockSurface.qml @@ -0,0 +1,651 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Effects +import QtQuick.Layouts +import Quickshell +import Quickshell.Services.UPower +import "../services" +import "../theme" + +// One output of the lock screen, in the style of the macOS lock screen: date +// and a large glass clock at the top, Now Playing below it, and the avatar, +// name and password capsule near the bottom with power controls underneath. +// Secondary outputs show only the backdrop and the clock. +Item { + id: root + required property string screenName + property bool preview: false + readonly property bool primary: screenName === LockState.primary || !Quickshell.screens.some(s => s.name === LockState.primary) + readonly property var byMonitor: ConfigService.ready ? ConfigService.data.wallpaper.byMonitor : ({}) + readonly property string backdropPath: LockState.options.backdrop === "screenshot" && LockState.shots[screenName] ? LockState.shots[screenName] : (byMonitor[screenName] || Object.values(byMonitor)[0] || "") + readonly property bool glass: LockState.options.glass + // Interface scale: about 1 on a 1500×1050 logical output, never below 0.85 + // (so portrait outputs keep readable controls) or above 1.3. + readonly property real unit: Math.max(0.85, Math.min(1.3, Math.min(width / 1500, height / 1050))) + function s(value) { + return Math.round(value * unit); + } + property bool active: false + function wake() { + active = true; + idle.restart(); + } + + focus: true + opacity: LockState.unlocking ? 0 : 1 + scale: LockState.unlocking ? 1.04 : 1 + Behavior on opacity { + NumberAnimation { + duration: 380 + easing.type: Easing.OutCubic + } + } + Behavior on scale { + NumberAnimation { + duration: 380 + easing.type: Easing.OutCubic + } + } + Keys.onPressed: event => { + root.wake(); + if (event.key === Qt.Key_Escape) { + if (root.preview) + LockState.cancelPreview(); + else + field.text = ""; + event.accepted = true; + } else if (root.primary && !field.activeFocus) { + field.forceActiveFocus(); + if (event.text && event.text.length === 1 && event.text >= " ") { + field.insert(field.cursorPosition, event.text); + event.accepted = true; + } + } + } + Component.onCompleted: { + LockState.surfaces = LockState.surfaces.concat([root]); + if (primary) + field.forceActiveFocus(); + } + Component.onDestruction: LockState.surfaces = LockState.surfaces.filter(s => s !== root) + Timer { + id: idle + interval: 20000 + onTriggered: root.active = false + } + SystemClock { + id: clock + precision: SystemClock.Minutes + } + + // Backdrop: wallpaper (or the pre-lock screenshot), lightly blurred while typing. + Rectangle { + anchors.fill: parent + gradient: Gradient { + GradientStop { + position: 0 + color: Qt.darker(Theme.accent, 2.2) + } + GradientStop { + position: 1 + color: "#050507" + } + } + } + Image { + id: wallpaper + anchors.fill: parent + visible: false + source: root.backdropPath ? "file://" + encodeURI(root.backdropPath).replace(/#/g, "%23").replace(/\?/g, "%3F") : "" + sourceSize: Qt.size(root.width, root.height) + fillMode: Image.PreserveAspectCrop + cache: false + } + MultiEffect { + anchors.fill: parent + source: wallpaper + visible: wallpaper.status === Image.Ready + blurEnabled: true + blurMax: 48 + blur: root.active && root.primary ? 0.35 : 0 + brightness: root.active ? -0.06 : 0 + Behavior on blur { + NumberAnimation { + duration: 350 + easing.type: Easing.OutCubic + } + } + } + Rectangle { + anchors.fill: parent + gradient: Gradient { + GradientStop { + position: 0 + color: "#4d000000" + } + GradientStop { + position: 0.32 + color: "#00000000" + } + GradientStop { + position: 0.62 + color: "#00000000" + } + GradientStop { + position: 1 + color: "#80000000" + } + } + } + // Frosted copy of the backdrop that every glass surface refracts. + MultiEffect { + id: frost + anchors.fill: parent + visible: false + source: wallpaper.status === Image.Ready ? wallpaper : null + blurEnabled: true + blurMax: 64 + blur: LockState.glass.frost + saturation: 0.15 + } + ShaderEffectSource { + id: frostSource + sourceItem: frost + hideSource: true + visible: false + } + MouseArea { + anchors.fill: parent + hoverEnabled: true + onPositionChanged: root.wake() + onPressed: { + root.wake(); + if (root.primary) + field.forceActiveFocus(); + } + } + + // Date and glass clock. + Text { + id: date + anchors.horizontalCenter: parent.horizontalCenter + y: root.height * 0.085 + text: Qt.formatDate(clock.date, "dddd d MMMM") + color: Qt.alpha("#ffffff", 0.92) + font.pixelSize: root.s(24) + font.weight: Font.DemiBold + layer.enabled: true + layer.effect: MultiEffect { + shadowEnabled: true + shadowColor: "#66000000" + shadowBlur: 0.5 + } + } + GlassSurface { + id: clockGlass + objectName: "lockClock" + backdrop: frostSource + space: root + glass: root.glass && wallpaper.status === Image.Ready + x: Math.round((root.width - width) / 2) + y: date.y + date.height - root.s(6) + width: digits.implicitWidth + root.s(24) + height: digits.implicitHeight + brightness: 1.3 + tint: "#ffffff" + tintAmount: 0.2 + Text { + id: digits + anchors.centerIn: parent + text: Qt.formatTime(clock.date, ConfigService.ready && !ConfigService.data.bar.clock.use24Hour ? "h:mm" : "HH:mm") + color: "#ffffff" + font.pixelSize: Math.min(root.s(176), root.height * 0.2) + font.weight: Font.Bold + font.letterSpacing: -root.s(3) + } + } + Text { + visible: root.preview && root.primary + anchors.horizontalCenter: parent.horizontalCenter + y: root.s(18) + text: "Preview · type your password to test it, or press Esc to close" + color: Qt.alpha("#ffffff", 0.75) + font.pixelSize: root.s(12) + } + + // Status: keyboard layout, Wi-Fi and battery. + Row { + visible: root.primary + anchors.right: parent.right + anchors.top: parent.top + anchors.margins: root.s(18) + spacing: root.s(14) + Text { + visible: LockState.layout !== "" + text: LockState.layout + color: "#ffffff" + font.pixelSize: root.s(13) + font.weight: Font.DemiBold + } + Text { + visible: NetworkService.available + text: Icons.available ? (NetworkService.enabled ? "󰖩" : "󰖪") : (NetworkService.enabled ? "Wi-Fi" : "Wi-Fi off") + font.family: Icons.available ? Icons.family : "" + color: "#ffffff" + font.pixelSize: root.s(15) + } + Text { + readonly property var battery: UPower.displayDevice + visible: battery.ready && battery.isLaptopBattery + text: Math.round(battery.percentage * 100) + "%" + (battery.state === UPowerDeviceState.Charging ? " ⚡" : "") + color: "#ffffff" + font.pixelSize: root.s(13) + font.weight: Font.DemiBold + } + } + + // Now Playing. + GlassSurface { + id: nowPlaying + readonly property bool shown: root.primary && LockState.options.media && !!MediaService.player + visible: shown + backdrop: frostSource + space: root + glass: root.glass && wallpaper.status === Image.Ready + x: Math.round((root.width - width) / 2) + y: clockGlass.y + clockGlass.height + root.s(22) + width: root.s(380) + height: root.s(74) + radius: root.s(24) + // Darker material keeps white text readable over bright wallpapers. + tint: "#000000" + tintAmount: 0.45 + brightness: 0.8 + } + RowLayout { + visible: nowPlaying.shown + x: nowPlaying.x + root.s(12) + y: nowPlaying.y + width: nowPlaying.width - root.s(24) + height: nowPlaying.height + spacing: root.s(12) + Rectangle { + Layout.preferredWidth: root.s(50) + Layout.preferredHeight: root.s(50) + radius: root.s(10) + color: Qt.alpha("#ffffff", 0.15) + clip: true + Image { + anchors.fill: parent + source: MediaService.artwork + fillMode: Image.PreserveAspectCrop + asynchronous: true + sourceSize: Qt.size(120, 120) + } + } + ColumnLayout { + Layout.fillWidth: true + spacing: 0 + Text { + text: MediaService.title + color: "#ffffff" + font.pixelSize: root.s(14) + font.weight: Font.DemiBold + elide: Text.ElideRight + Layout.fillWidth: true + } + Text { + text: MediaService.artist + color: Qt.alpha("#ffffff", 0.7) + font.pixelSize: root.s(12) + elide: Text.ElideRight + Layout.fillWidth: true + } + } + Repeater { + model: [ + { + glyph: "󰒮", + fallback: "‹‹", + run: () => MediaService.previous() + }, + { + glyph: MediaService.playing ? "󰏤" : "󰐊", + fallback: MediaService.playing ? "❚❚" : "▶", + run: () => MediaService.toggle() + }, + { + glyph: "󰒭", + fallback: "››", + run: () => MediaService.next() + } + ] + Rectangle { + id: control + required property var modelData + Layout.preferredWidth: root.s(32) + Layout.preferredHeight: root.s(32) + radius: width / 2 + color: controlArea.containsMouse ? Qt.alpha("#ffffff", 0.18) : "transparent" + Text { + anchors.centerIn: parent + text: Icons.available ? control.modelData.glyph : control.modelData.fallback + font.family: Icons.available ? Icons.family : "" + color: "#ffffff" + font.pixelSize: root.s(18) + } + MouseArea { + id: controlArea + anchors.fill: parent + hoverEnabled: true + onClicked: control.modelData.run() + } + } + } + } + + // Avatar, name and password. + Item { + id: avatar + visible: root.primary + width: root.s(84) + height: width + x: Math.round((root.width - width) / 2) + y: root.height - root.s(LockState.options.powerButtons ? 330 : 250) + readonly property var candidates: ["file://" + Quickshell.env("HOME") + "/.face", "file://" + Quickshell.env("HOME") + "/.face.icon", "file:///var/lib/AccountsService/icons/" + (Quickshell.env("USER") || "")] + property int candidate: 0 + Image { + id: face + anchors.fill: parent + visible: false + source: avatar.candidate < avatar.candidates.length ? avatar.candidates[avatar.candidate] : "" + sourceSize: Qt.size(200, 200) + fillMode: Image.PreserveAspectCrop + onStatusChanged: if (status === Image.Error) + avatar.candidate++ + } + Rectangle { + id: faceMask + anchors.fill: parent + radius: width / 2 + visible: false + layer.enabled: true + } + MultiEffect { + anchors.fill: parent + source: face + maskEnabled: true + maskSource: faceMask + visible: face.status === Image.Ready + } + Rectangle { + anchors.fill: parent + radius: width / 2 + visible: face.status !== Image.Ready + color: Qt.alpha("#ffffff", 0.22) + Text { + anchors.centerIn: parent + text: (LockState.realName || Quickshell.env("USER") || "?").charAt(0).toUpperCase() + color: "#ffffff" + font.pixelSize: parent.width * 0.42 + font.weight: Font.DemiBold + } + } + Rectangle { + anchors.fill: parent + anchors.margins: -root.s(3) + radius: width / 2 + color: "transparent" + border.width: root.s(2) + border.color: Qt.alpha("#ffffff", 0.35) + } + } + Text { + id: userName + visible: root.primary + anchors.horizontalCenter: parent.horizontalCenter + y: avatar.y + avatar.height + root.s(12) + text: LockState.realName || Quickshell.env("USER") || "" + color: "#ffffff" + font.pixelSize: root.s(17) + font.weight: Font.DemiBold + layer.enabled: true + layer.effect: MultiEffect { + shadowEnabled: true + shadowColor: "#66000000" + shadowBlur: 0.4 + } + } + property real shake: 0 + SequentialAnimation { + id: shakeAnimation + NumberAnimation { + target: root + property: "shake" + to: -root.s(14) + duration: 50 + } + NumberAnimation { + target: root + property: "shake" + to: root.s(12) + duration: 70 + } + NumberAnimation { + target: root + property: "shake" + to: -root.s(8) + duration: 70 + } + NumberAnimation { + target: root + property: "shake" + to: root.s(4) + duration: 60 + } + NumberAnimation { + target: root + property: "shake" + to: 0 + duration: 50 + } + } + Connections { + target: LockState + function onFailuresChanged() { + field.text = ""; + shakeAnimation.restart(); + } + } + GlassSurface { + id: fieldGlass + objectName: "lockField" + visible: root.primary + backdrop: frostSource + space: root + glass: root.glass && wallpaper.status === Image.Ready + width: root.s(250) + height: root.s(36) + x: Math.round((root.width - width) / 2 + root.shake) + y: userName.y + userName.height + root.s(14) + tint: "#ffffff" + tintAmount: 0.16 + brightness: 1.2 + } + Item { + visible: root.primary + x: fieldGlass.x + y: fieldGlass.y + width: fieldGlass.width + height: fieldGlass.height + TextInput { + id: field + objectName: "lockPassword" + anchors.left: parent.left + anchors.right: submit.left + anchors.leftMargin: root.s(16) + anchors.rightMargin: root.s(6) + anchors.verticalCenter: parent.verticalCenter + echoMode: TextInput.Password + passwordCharacter: "●" + color: "#ffffff" + selectionColor: Qt.alpha("#ffffff", 0.3) + font.pixelSize: root.s(13) + font.letterSpacing: root.s(1) + enabled: !LockState.busy && !LockState.unlocking + clip: true + onTextChanged: root.wake() + onAccepted: LockState.submit(text, root.preview ? "preview" : "unlock") + Text { + anchors.verticalCenter: parent.verticalCenter + visible: !field.text + text: LockState.busy ? "Checking…" : "Enter Password" + color: Qt.alpha("#ffffff", 0.6) + font.pixelSize: root.s(13) + } + } + Rectangle { + id: submit + anchors.right: parent.right + anchors.rightMargin: root.s(5) + anchors.verticalCenter: parent.verticalCenter + width: parent.height - root.s(10) + height: width + radius: width / 2 + visible: field.text.length > 0 || LockState.busy + color: submitArea.containsMouse ? Qt.alpha("#ffffff", 0.35) : Qt.alpha("#ffffff", 0.22) + Text { + anchors.centerIn: parent + visible: !LockState.busy + text: Icons.available ? "󰁔" : "→" + font.family: Icons.available ? Icons.family : "" + color: "#ffffff" + font.pixelSize: root.s(14) + } + Rectangle { + anchors.centerIn: parent + visible: LockState.busy + width: parent.width * 0.55 + height: width + radius: width / 2 + color: "transparent" + border.width: root.s(2) + border.color: "#ffffff" + opacity: 0.8 + RotationAnimation on rotation { + running: LockState.busy + from: 0 + to: 360 + duration: 900 + loops: Animation.Infinite + } + Rectangle { + width: parent.width / 2 + height: parent.height / 2 + color: "#000000" + opacity: 0.6 + } + } + MouseArea { + id: submitArea + anchors.fill: parent + hoverEnabled: true + onClicked: LockState.submit(field.text, root.preview ? "preview" : "unlock") + } + } + } + Text { + visible: root.primary + anchors.horizontalCenter: parent.horizontalCenter + y: fieldGlass.y + fieldGlass.height + root.s(12) + text: LockState.status || (root.preview ? "Your password is checked but nothing is locked" : "") + color: Qt.alpha("#ffffff", LockState.status ? 0.95 : 0.65) + font.pixelSize: root.s(12) + font.weight: LockState.status ? Font.DemiBold : Font.Normal + } + + // Power controls, as on the macOS login window. Inert in preview. + readonly property var powerActions: root.primary && LockState.options.powerButtons ? [ + { + id: "suspend", + label: "Sleep", + glyph: "󰤄" + }, + { + id: "reboot", + label: "Restart", + glyph: "󰜉" + }, + { + id: "shutdown", + label: "Shut Down", + glyph: "󰐥" + } + ] : [] + function powerAvailable(id) { + return !!SystemService.state.power && !!SystemService.state.power[id]; + } + function powerX(index) { + return Math.round(width / 2 + (index - 1) * s(104) - s(23)); + } + Repeater { + model: root.powerActions + GlassSurface { + required property var modelData + required property int index + objectName: "lockPower-" + modelData.id + backdrop: frostSource + space: root + glass: root.glass && wallpaper.status === Image.Ready + width: root.s(46) + height: width + x: root.powerX(index) + y: root.height - root.s(118) + tint: "#ffffff" + tintAmount: 0.16 + brightness: 1.2 + opacity: root.powerAvailable(modelData.id) ? 1 : 0.4 + } + } + Repeater { + model: root.powerActions + Item { + id: power + required property var modelData + required property int index + x: root.powerX(index) + y: root.height - root.s(118) + width: root.s(46) + height: width + opacity: root.powerAvailable(modelData.id) ? 1 : 0.4 + Rectangle { + anchors.fill: parent + radius: width / 2 + color: Qt.alpha("#ffffff", powerArea.containsMouse && powerArea.enabled ? 0.18 : 0) + } + Text { + anchors.centerIn: parent + text: Icons.available ? power.modelData.glyph : power.modelData.label.charAt(0) + font.family: Icons.available ? Icons.family : "" + color: "#ffffff" + font.pixelSize: root.s(20) + } + Text { + anchors.horizontalCenter: parent.horizontalCenter + anchors.top: parent.bottom + anchors.topMargin: root.s(8) + text: power.modelData.label + color: Qt.alpha("#ffffff", 0.85) + font.pixelSize: root.s(12) + } + MouseArea { + id: powerArea + anchors.fill: parent + hoverEnabled: true + enabled: root.powerAvailable(power.modelData.id) && !root.preview + cursorShape: Qt.PointingHandCursor + onClicked: SystemService.action("power", power.modelData.id, true) + } + } + } +} diff --git a/quickshell/lock/pam/password.conf b/quickshell/lock/pam/password.conf new file mode 100644 index 0000000..7e5d75a --- /dev/null +++ b/quickshell/lock/pam/password.conf @@ -0,0 +1 @@ +auth required pam_unix.so diff --git a/quickshell/lock/qmldir b/quickshell/lock/qmldir new file mode 100644 index 0000000..78c668a --- /dev/null +++ b/quickshell/lock/qmldir @@ -0,0 +1,4 @@ +singleton LockState 1.0 LockState.qml +Lock 1.0 Lock.qml +LockSurface 1.0 LockSurface.qml +GlassSurface 1.0 GlassSurface.qml diff --git a/quickshell/lock/shaders/glass.frag b/quickshell/lock/shaders/glass.frag new file mode 100644 index 0000000..85595bb --- /dev/null +++ b/quickshell/lock/shaders/glass.frag @@ -0,0 +1,62 @@ +#version 440 +// Liquid glass for the lock screen, where compositor glass (HyprGlass) does not +// reach session-lock surfaces. A shape mask and its blurred copy (a height +// field) give an edge profile; the frosted backdrop is refracted towards the +// rim with RGB dispersion, plus a fresnel rim and a light-facing highlight. +// Rebuild glass.frag.qsb with scripts/build-shaders after editing. +layout(location = 0) in vec2 qt_TexCoord0; +layout(location = 0) out vec4 fragColor; + +layout(std140, binding = 0) uniform buf { + mat4 qt_Matrix; + float qt_Opacity; + vec4 sourceRect; // backdrop UV rect covered by this item + vec2 pixelStep; // 1 / item size in pixels + float refraction; // edge displacement in pixels + float dispersion; // RGB split, fraction of the displacement + float fresnel; + float specular; + float brightness; + float saturation; + vec4 tint; // rgb tint, a = amount +}; + +layout(binding = 1) uniform sampler2D backdropMap; +layout(binding = 2) uniform sampler2D maskMap; +layout(binding = 3) uniform sampler2D heightMap; + +vec3 backdropAt(vec2 uv) { + return texture(backdropMap, sourceRect.xy + clamp(uv, 0.0, 1.0) * sourceRect.zw).rgb; +} + +void main() { + vec2 uv = qt_TexCoord0; + float shape = texture(maskMap, uv).a; + if (shape < 0.002) { + fragColor = vec4(0.0); + return; + } + float h = texture(heightMap, uv).a; + vec2 e = pixelStep * 2.0; + vec2 slope = vec2(texture(heightMap, uv + vec2(e.x, 0.0)).a - texture(heightMap, uv - vec2(e.x, 0.0)).a, + texture(heightMap, uv + vec2(0.0, e.y)).a - texture(heightMap, uv - vec2(0.0, e.y)).a); + float rim = 1.0 - smoothstep(0.0, 1.0, h); + vec2 inward = length(slope) > 1e-5 ? normalize(slope) : vec2(0.0); + + // Pull the backdrop in from the rim, as a convex lens would. + vec2 offset = inward * refraction * rim * rim * pixelStep; + vec3 color = vec3(backdropAt(uv + offset * (1.0 + dispersion)).r, + backdropAt(uv + offset).g, + backdropAt(uv + offset * (1.0 - dispersion)).b); + + float luma = dot(color, vec3(0.2126, 0.7152, 0.0722)); + color = mix(vec3(luma), color, saturation) * brightness; + color = mix(color, tint.rgb, tint.a); + + color += vec3(fresnel) * pow(rim, 3.0) * 0.55; + // Light from the top left catches the rim facing it. + float facing = max(0.0, dot(inward, normalize(vec2(1.0, 1.0)))); + color += vec3(specular) * pow(rim, 4.0) * facing * 0.9; + + fragColor = vec4(clamp(color, 0.0, 1.0), 1.0) * shape * qt_Opacity; +} diff --git a/quickshell/lock/shaders/glass.frag.qsb b/quickshell/lock/shaders/glass.frag.qsb new file mode 100644 index 0000000..6f6d5b1 Binary files /dev/null and b/quickshell/lock/shaders/glass.frag.qsb differ diff --git a/quickshell/media/CavaView.qml b/quickshell/media/CavaView.qml new file mode 100644 index 0000000..45485ba --- /dev/null +++ b/quickshell/media/CavaView.qml @@ -0,0 +1,42 @@ +pragma ComponentBehavior: Bound +import QtQuick +import "../services" +import "../theme" + +Item { + id: root + implicitHeight: 28 + property bool mounted: false + property bool subscribed: false + function sync() { + const next = mounted && visible; + if (next !== subscribed) { + CavaService.consumers += next ? 1 : -1; + subscribed = next; + } + } + Component.onCompleted: { + mounted = true; + sync(); + } + Component.onDestruction: { + if (subscribed) + CavaService.consumers--; + } + onVisibleChanged: sync() + Row { + anchors.fill: parent + spacing: 3 + Repeater { + model: 24 + Rectangle { + required property int index + width: Math.max(1, (root.width - 69) / 24) + height: Math.max(2, root.height * (CavaService.bars[index] || 0)) + y: root.height - height + radius: 2 + color: Theme.accent + } + } + } +} diff --git a/quickshell/media/MediaCard.qml b/quickshell/media/MediaCard.qml new file mode 100644 index 0000000..a121746 --- /dev/null +++ b/quickshell/media/MediaCard.qml @@ -0,0 +1,203 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Layouts +import "../components" +import "../services" +import "../theme" + +GlassPanel { + id: root + objectName: "mediaCard" + property bool compact: false + property bool mounted: false + property bool subscribed: false + readonly property bool showProgress: ConfigService.ready && ConfigService.data.media.showProgress + implicitWidth: compact ? 340 : 480 + implicitHeight: body.implicitHeight + 36 + function sync() { + const next = mounted && visible && showProgress; + if (next !== subscribed) { + MediaService.progressConsumers += next ? 1 : -1; + subscribed = next; + } + } + Component.onCompleted: { + mounted = true; + sync(); + } + Component.onDestruction: { + if (subscribed) + MediaService.progressConsumers--; + } + onVisibleChanged: sync() + onShowProgressChanged: sync() + Connections { + target: MediaService + function onTitleChanged() { + if (root.visible && Theme.duration > 0) + transition.restart(); + } + } + ParallelAnimation { + id: transition + NumberAnimation { + target: metadata + property: "opacity" + from: 0.55 + to: 1 + duration: Theme.duration + } + NumberAnimation { + target: movement + property: "y" + from: 5 * Theme.intensity + to: 0 + duration: Theme.duration + easing.type: Easing.OutCubic + } + } + ColumnLayout { + id: body + anchors { + left: parent.left + right: parent.right + top: parent.top + margins: 18 + } + spacing: 10 + RowLayout { + spacing: 16 + Rectangle { + visible: ConfigService.ready && ConfigService.data.media.showAlbumArt + Layout.preferredWidth: root.compact ? 64 : 112 + Layout.preferredHeight: width + radius: 12 + color: Theme.surfaceVariant + clip: true + Text { + anchors.centerIn: parent + text: "♫" + font.pixelSize: 34 + color: Theme.textSecondary + visible: art.status !== Image.Ready + } + Image { + id: art + anchors.fill: parent + source: MediaService.artwork + sourceSize.width: 256 + sourceSize.height: 256 + asynchronous: true + retainWhileLoading: true + fillMode: Image.PreserveAspectCrop + opacity: status === Image.Ready ? 1 : 0 + Behavior on opacity { + NumberAnimation { + duration: Theme.duration + } + } + } + } + ColumnLayout { + id: metadata + transform: Translate { + id: movement + } + Layout.fillWidth: true + spacing: 5 + Text { + text: MediaService.title + color: Theme.text + font.pixelSize: root.compact ? 15 : 19 + font.weight: Font.DemiBold + elide: Text.ElideRight + Layout.fillWidth: true + } + Text { + text: MediaService.artist + color: Theme.textSecondary + font.pixelSize: 13 + elide: Text.ElideRight + Layout.fillWidth: true + } + Text { + visible: !root.compact && ConfigService.ready && ConfigService.data.media.showAlbum && !!text + text: MediaService.album + color: Theme.textSecondary + elide: Text.ElideRight + Layout.fillWidth: true + } + RowLayout { + GlassButton { + objectName: "mediaPrevious" + text: "⏮" + enabled: !!MediaService.player && MediaService.player.canControl && MediaService.player.canGoPrevious + onClicked: MediaService.previous() + Accessible.name: "Previous track" + } + GlassButton { + objectName: "mediaToggle" + text: MediaService.playing ? "Ⅱ" : "▶" + accented: true + enabled: !!MediaService.player && MediaService.player.canControl && MediaService.player.canTogglePlaying + onClicked: MediaService.toggle() + Accessible.name: MediaService.playing ? "Pause" : "Play" + } + GlassButton { + objectName: "mediaNext" + text: "⏭" + enabled: !!MediaService.player && MediaService.player.canControl && MediaService.player.canGoNext + onClicked: MediaService.next() + Accessible.name: "Next track" + } + } + } + } + RowLayout { + visible: root.showProgress && MediaService.length > 0 + Text { + text: MediaService.time(MediaService.position) + color: Theme.textSecondary + font.pixelSize: 11 + } + GlassSlider { + Layout.fillWidth: true + from: 0 + to: Math.max(1, MediaService.length) + value: MediaService.position + enabled: MediaService.seekable + onMoved: MediaService.seek(value) + Accessible.name: "Track position" + } + Text { + text: "−" + MediaService.time(MediaService.length - MediaService.position) + color: Theme.textSecondary + font.pixelSize: 11 + } + } + GlassComboBox { + visible: MediaService.players.length > 1 + Layout.fillWidth: true + model: MediaService.players.map(p => ({ + name: p.identity || p.dbusName, + id: p.dbusName + })) + textRole: "name" + currentIndex: MediaService.players.indexOf(MediaService.player) + onActivated: MediaService.choose(MediaService.players[currentIndex].dbusName) + Accessible.name: "Media player" + } + CavaView { + Layout.fillWidth: true + visible: ConfigService.ready && ConfigService.data.media.showCava + } + Text { + visible: !!CavaService.error && ConfigService.ready && ConfigService.data.media.showCava + text: CavaService.error + color: Theme.textSecondary + wrapMode: Text.Wrap + Layout.fillWidth: true + font.pixelSize: 11 + } + } +} diff --git a/quickshell/menus/TrayIcon.qml b/quickshell/menus/TrayIcon.qml new file mode 100644 index 0000000..34a93df --- /dev/null +++ b/quickshell/menus/TrayIcon.qml @@ -0,0 +1,85 @@ +import QtQuick +import Quickshell +import Quickshell.Services.SystemTray +import "../core" +import "../services" +import "../theme" +Item { + id: root + objectName: "trayIcon" + required property var trayItem + readonly property var containingWindow: root.QsWindow.window + property var barScreen + // Tray pill this icon sits in. Menus and tooltips are placed under it so + // they do not jump sideways while moving between icons. + property var group: null + readonly property Item placement: group || root + readonly property bool pointerInside: mouse.containsMouse || (!!group && group.hovered) + readonly property bool menuActive: TrayService.opened && TrayService.anchorItem === root + width: TrayService.options.iconSize + 12; height: ModuleRegistry.pillHeight + Component.onCompleted: TrayService.registerIcon(root) + Component.onDestruction: TrayService.unregisterIcon(root) + readonly property string label: trayItem ? (trayItem.tooltipTitle || trayItem.title || trayItem.id) : "" + readonly property bool hoverMenu: TrayService.options.hoverMenus && !!trayItem && trayItem.hasMenu + // Once a menu or bar popout is open, hovering another icon switches instantly + // (keeping a click-opened menu sticky); otherwise wait for the hover delay. + function enter() { + if (menuActive) return; + if (!hoverMenu) { PopoutState.hover(root, label ? "tooltip" : "", label); return; } + if (PopoutState.warm) openMenu(TrayService.opened ? TrayService.closeOnLeave : true); + else intent.restart(); + } + function leave() { intent.stop(); PopoutState.unhover(root); } + function openMenu(hover) { + intent.stop(); + return TrayService.open(trayItem, root, hover); + } + function click(button, modifiers) { + intent.stop(); + PopoutState.close(); + if (!trayItem) return; + if (button === Qt.RightButton || (button === Qt.LeftButton && trayItem.onlyMenu)) { + if ((modifiers & Qt.ShiftModifier) || !trayItem.hasMenu) { + TrayService.close(); + const window = root.containingWindow; + const point = root.mapToItem(window.contentItem, 0, root.height); + trayItem.display(window, point.x, point.y); + } else openMenu(false); + } else { + TrayService.close(); + if (button === Qt.MiddleButton) trayItem.secondaryActivate(); else trayItem.activate(); + } + } + Rectangle { + anchors.fill: parent; radius: height / 2 + color: root.menuActive ? Qt.alpha(Theme.accent, 0.2) : root.pointerInside ? Qt.alpha(Theme.text, 0.12) : TrayService.options.background === "icons" ? Theme.surfaceVariant : Theme.transparent + border.width: root.menuActive ? 1 : 0; border.color: Theme.border + Behavior on color { ColorAnimation { duration: Theme.duration } } + } + Image { + anchors.centerIn: parent; width: TrayService.options.iconSize; height: width + source: root.trayItem ? root.trayItem.icon : "" + sourceSize.width: width; sourceSize.height: height + fillMode: Image.PreserveAspectFit + scale: mouse.pressed ? 0.92 : 1 + Behavior on scale { NumberAnimation { duration: Theme.duration / 2 } } + } + Rectangle { + anchors.bottom: parent.bottom; anchors.horizontalCenter: parent.horizontalCenter + width: 4; height: 4; radius: 2; color: Theme.urgent + visible: root.trayItem && root.trayItem.status === Status.NeedsAttention + } + MouseArea { + id: mouse; anchors.fill: parent; hoverEnabled: true + acceptedButtons: Qt.LeftButton | Qt.RightButton | Qt.MiddleButton + cursorShape: Qt.PointingHandCursor + onEntered: root.enter() + onExited: root.leave() + // Moving over an icon also starts the hover, in case no enter event + // arrived (e.g. the pointer was already there when a menu closed). + onPositionChanged: if (!root.menuActive && !intent.running && !TrayService.opened && root.hoverMenu) intent.restart() + onClicked: event => root.click(event.button, event.modifiers) + onWheel: event => { if (root.trayItem) root.trayItem.scroll(event.angleDelta.y || event.angleDelta.x, event.angleDelta.y === 0); } + } + Timer { id: intent; interval: TrayService.options.hoverDelay; onTriggered: if (mouse.containsMouse && TrayService.options.hoverMenus) root.openMenu(true) } +} diff --git a/quickshell/menus/TrayMenu.qml b/quickshell/menus/TrayMenu.qml new file mode 100644 index 0000000..63540e5 --- /dev/null +++ b/quickshell/menus/TrayMenu.qml @@ -0,0 +1,183 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Controls +import Quickshell +import Quickshell.Wayland +import "../components" +import "../core" +import "../services" +import "../theme" +// A layer surface is required for HyprGlass; xdg popups bypass its layer renderer. +// qmllint disable uncreatable-type +PanelWindow { + // qmllint enable uncreatable-type + id: root + property var menuHandle: null + property Item anchorItem: null + property bool isRoot: true + property bool opened: false + property int depth: 0 + property var parentMenu: null + property int selectedIndex: -1 + property var childEntry: null + property Item childAnchor: null + property bool contentOpen: false + readonly property var entries: opener.children.values + readonly property var anchorWindow: anchorItem ? anchorItem.QsWindow.window : null + screen: anchorWindow ? anchorWindow.screen : null + anchors { top: true; left: true } + exclusionMode: ExclusionMode.Ignore + WlrLayershell.namespace: "glassMxrph-tray" + WlrLayershell.layer: WlrLayer.Overlay + WlrLayershell.keyboardFocus: WlrKeyboardFocus.OnDemand + readonly property point anchorPoint: anchorItem && anchorWindow + ? anchorItem.mapToItem(anchorWindow.contentItem, 0, 0) : Qt.point(0, 0) + // Root menus centre under the icon's placement item (the whole tray pill). + readonly property var anchorObject: anchorItem + readonly property Item placementItem: anchorObject ? (anchorObject.placement || anchorObject) : null + readonly property real placementCenter: placementItem && anchorWindow + ? placementItem.mapToItem(anchorWindow.contentItem, placementItem.width / 2, 0).x : 0 + readonly property real availableWidth: screen ? screen.width : 1280 + readonly property real availableHeight: screen ? screen.height : 720 + readonly property real desiredX: { + if (!parentMenu) return placementCenter - implicitWidth / 2; + // A drawer parent's ears are not part of its body. + const inset = parentMenu.isRoot ? BarDrawers.ear : 0; + const right = parentMenu.margins.left + parentMenu.width - inset - 4; + return right + implicitWidth <= availableWidth - 4 + ? right : parentMenu.margins.left + inset - implicitWidth + 4; + } + // Quickshell 0.3.1 qmllint cannot resolve the exported Margins value type. + // qmllint disable unqualified unresolved-type + margins.left: Math.round(animX) + // The root menu is a drawer hanging from the bar; its layer starts at the screen top. + margins.top: isRoot ? 0 : Math.round(Math.max(4, Math.min( + parentMenu ? parentMenu.margins.top + anchorPoint.y + : anchorPoint.y + (anchorItem ? anchorItem.height : 0), + availableHeight - implicitHeight - 4))) + // qmllint enable unqualified unresolved-type + color: Theme.transparent + readonly property int menuWidth: 280 + implicitWidth: isRoot ? menuWidth + 2 * BarDrawers.ear : menuWidth + 8 + // Switching icons while open glides the menu over instead of reopening it; + // the previous height is held while the next DBus menu is still loading. + readonly property bool morph: isRoot && contentOpen && drawerSurface.progress > 0.05 && Theme.duration > 0 + readonly property real targetX: isRoot ? BarDrawers.clampX(desiredX + implicitWidth / 2, implicitWidth, availableWidth) : Math.max(4, Math.min(desiredX, availableWidth - implicitWidth - 4)) + readonly property real contentTarget: Math.min((screen ? screen.height : 720) - 80 - (isRoot ? BarDrawers.bottom : 0), Math.max(50, list.contentHeight + 16)) + property real heldHeight: 58 + readonly property real targetHeight: entries.length === 0 && emptyTimer.running && morph ? heldHeight : contentTarget + onContentTargetChanged: if (entries.length > 0) heldHeight = contentTarget + property real animX: targetX + property real animH: targetHeight + Behavior on animX { enabled: root.morph; NumberAnimation { duration: Theme.duration * 1.2; easing.type: Easing.OutCubic } } + Behavior on animH { enabled: root.morph; NumberAnimation { duration: Theme.duration; easing.type: Easing.OutCubic } } + implicitHeight: Math.round(animH + (isRoot ? BarDrawers.bottom : 8)) + Region { + id: drawerMask + item: drawerSurface.body + } + mask: isRoot ? drawerMask : null + onMenuHandleChanged: if (opened && isRoot) { emptyTimer.restart(); swap.restart(); } + visible: opened || surface.visible || drawerSurface.shown + onOpenedChanged: { + if (opened) { selectedIndex = -1; childEntry = null; emptyTimer.restart(); Qt.callLater(() => { contentOpen = true; menuBody.forceActiveFocus(); }); } + else { contentOpen = false; childEntry = null; submenuTimer.stop(); emptyTimer.stop(); } + } + Component.onCompleted: { TrayService.registerWindow(root); if (opened) { contentOpen = true; emptyTimer.restart(); } } + Component.onDestruction: TrayService.unregisterWindow(root) + onEntriesChanged: { childEntry = null; selectedIndex = -1; } + function dismissChild() { childEntry = null; menuBody.forceActiveFocus(); } + function select(index, keyboard) { + selectedIndex = index; + const entry = entries[index]; + if (childEntry !== entry) childEntry = null; + submenuTimer.stop(); + if (entry && entry.enabled && entry.hasChildren && !keyboard) submenuTimer.restart(); + } + function move(direction) { + for (let i = 1; i <= entries.length; ++i) { + const next = (selectedIndex + direction * i + entries.length) % entries.length; + if (entries[next].enabled && !entries[next].isSeparator) { select(next, true); list.positionViewAtIndex(next, ListView.Contain); return; } + } + } + function invoke(index) { + const entry = entries[index]; + if (!entry || entry.isSeparator || !entry.enabled) return false; + if (entry.hasChildren) { openChild(index); return true; } + entry.triggered(); TrayService.close(); return true; + } + function openChild(index) { + const entry = entries[index]; + if (!entry || !entry.enabled || !entry.hasChildren) return; + list.positionViewAtIndex(index, ListView.Contain); + childAnchor = list.itemAtIndex(index); + if (childAnchor) childEntry = entry; + } + function snapshot() { return {depth:depth, screen:screen ? screen.name : "", entries:entries.map(e => ({text:e.text, enabled:e.enabled, separator:e.isSeparator, buttonType:e.buttonType, checkState:e.checkState, hasChildren:e.hasChildren, icon:e.icon !== ""}))}; } + QsMenuOpener { id: opener; menu: root.opened ? root.menuHandle : null } + Timer { id: submenuTimer; interval: 180; onTriggered: root.openChild(root.selectedIndex) } + Timer { id: emptyTimer; interval: 1500 } + NumberAnimation { id: swap; target: list; property: "opacity"; from: 0.2; to: 1; duration: Theme.duration; easing.type: Easing.OutCubic } + // Submenus float beside their parent as glass cards. + GlassMenu { + id: surface; objectName: root.isRoot ? "" : "trayMenuSurface" + visible: !root.isRoot && (opened || opacity > 0.01) + anchors.fill: parent; anchors.margins: 4 + opened: root.contentOpen && !root.isRoot + transformOrigin: Item.TopLeft + } + BarDrawer { + id: drawerSurface; objectName: root.isRoot ? "trayMenuSurface" : "" + visible: root.isRoot + y: BarDrawers.bottom + // Open (and take input) at once: a click-opened menu's focus grab needs + // an input region as soon as the menu maps. + open: root.opened && root.isRoot + contentWidth: root.menuWidth + contentHeight: Math.round(root.animH) + drawerId: root.isRoot ? "tray" : "" + screenName: root.screen ? root.screen.name : "" + screenX: root.animX + onHoveredChanged: if (root.isRoot) TrayService.setHovered(root, hovered) + } + // Shared menu body, placed in whichever surface this menu uses. + Item { + id: menuBody + parent: root.isRoot ? drawerSurface.container : surface.contentItem + anchors.fill: parent + anchors.margins: root.isRoot ? 8 : 0 + focus: true + Keys.onEscapePressed: TrayService.close() + Keys.onDownPressed: root.move(1) + Keys.onUpPressed: root.move(-1) + Keys.onReturnPressed: root.invoke(root.selectedIndex) + Keys.onEnterPressed: root.invoke(root.selectedIndex) + Keys.onRightPressed: root.openChild(root.selectedIndex) + Keys.onLeftPressed: if (root.parentMenu) root.parentMenu.dismissChild() + HoverHandler { enabled: !root.isRoot; onHoveredChanged: TrayService.setHovered(root, hovered) } + ListView { + id: list; objectName: "trayMenuList"; anchors.fill: parent; clip: true + model: opener.children; boundsBehavior: Flickable.StopAtBounds + ScrollBar.vertical: ScrollBar {} + onContentYChanged: root.childEntry = null + delegate: TrayMenuItem { + required property var modelData + required property int index + entry: modelData; width: list.width + selected: root.selectedIndex === index + onEntered: root.select(index, false) + onInvoked: root.invoke(index) + } + } + Text { anchors.centerIn: parent; visible: root.entries.length === 0; text: emptyTimer.running ? "Loading application menu…" : "No menu entries"; color: Theme.textSecondary; font.pixelSize: 12 } + } + Loader { + active: root.opened && root.childEntry !== null + source: active ? Qt.resolvedUrl("TraySubMenu.qml") : "" + onLoaded: { + item.menuHandle = Qt.binding(() => root.childEntry); + item.anchorItem = Qt.binding(() => root.childAnchor); + item.parentMenu = root; item.depth = root.depth + 1; item.opened = true; + } + } +} diff --git a/quickshell/menus/TrayMenuItem.qml b/quickshell/menus/TrayMenuItem.qml new file mode 100644 index 0000000..475a4c1 --- /dev/null +++ b/quickshell/menus/TrayMenuItem.qml @@ -0,0 +1,13 @@ +import QtQuick +import "../components" +GlassMenuItem { + required property var entry + // DBusMenu labels use ampersands for mnemonics. Keep escaped ampersands. + text: entry ? entry.text.replace(/&&/g, "\u0000").replace(/&/g, "").replace(/\u0000/g, "&") : "" + iconSource: entry ? entry.icon : "" + separator: !entry || entry.isSeparator + actionEnabled: !!entry && entry.enabled + submenu: !!entry && entry.hasChildren + buttonType: entry ? entry.buttonType : 0 + checkState: entry ? entry.checkState : Qt.Unchecked +} diff --git a/quickshell/menus/TrayMenus.qml b/quickshell/menus/TrayMenus.qml new file mode 100644 index 0000000..f034224 --- /dev/null +++ b/quickshell/menus/TrayMenus.qml @@ -0,0 +1,18 @@ +import QtQuick +import Quickshell +import Quickshell.Hyprland +import "../services" +Scope { + TrayMenu { + menuHandle: TrayService.currentItem ? TrayService.currentItem.menu : null + anchorItem: TrayService.anchorItem + opened: TrayService.opened + } + HyprlandFocusGrab { + // Hover-opened menus never take keyboard focus from the focused app, and + // without a grab the bar keeps receiving hover for instant handover. + windows: TrayService.windows + active: TrayService.grabbing + onCleared: TrayService.close() + } +} diff --git a/quickshell/menus/TraySubMenu.qml b/quickshell/menus/TraySubMenu.qml new file mode 100644 index 0000000..583d28c --- /dev/null +++ b/quickshell/menus/TraySubMenu.qml @@ -0,0 +1,2 @@ +import QtQuick +TrayMenu { isRoot: false } diff --git a/quickshell/metrics/MetricGauge.qml b/quickshell/metrics/MetricGauge.qml new file mode 100644 index 0000000..26af124 --- /dev/null +++ b/quickshell/metrics/MetricGauge.qml @@ -0,0 +1,57 @@ +import QtQuick +import "../theme" +import "../services" + +Item { + id: root + property string label + property var value + implicitWidth: 100 + implicitHeight: 106 + Canvas { + id: ring + anchors.horizontalCenter: parent.horizontalCenter + width: 82 + height: 82 + property color accent: Theme.accent + property color track: Theme.border + property var reading: root.value + onAccentChanged: requestPaint() + onTrackChanged: requestPaint() + onReadingChanged: requestPaint() + onPaint: { + const c = getContext("2d"); + c.reset(); + c.lineWidth = 6; + c.lineCap = "round"; + c.strokeStyle = track; + c.beginPath(); + c.arc(41, 41, 35, 0, Math.PI * 2); + c.stroke(); + if (!MetricsService.stale && reading !== null && reading !== undefined) { + c.strokeStyle = accent; + c.beginPath(); + c.arc(41, 41, 35, -Math.PI / 2, -Math.PI / 2 + Math.PI * 2 * Math.max(0, Math.min(100, reading)) / 100); + c.stroke(); + } + } + Connections { + target: MetricsService + function onStaleChanged() { + ring.requestPaint(); + } + } + Text { + anchors.centerIn: parent + text: MetricsService.value(root.value, "%") + color: Theme.text + font.pixelSize: 18 + } + } + Text { + anchors.bottom: parent.bottom + anchors.horizontalCenter: parent.horizontalCenter + text: root.label + color: Theme.textSecondary + } +} diff --git a/quickshell/metrics/MetricsCard.qml b/quickshell/metrics/MetricsCard.qml new file mode 100644 index 0000000..c6ae5c3 --- /dev/null +++ b/quickshell/metrics/MetricsCard.qml @@ -0,0 +1,171 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Layouts +import "../components" +import "../theme" +import "../services" +import "../core" + +GlassPanel { + id: root + objectName: "metricsCard" + property bool compact: false + implicitWidth: 390 + implicitHeight: body.implicitHeight + 32 + Component.onCompleted: MetricsService.consumers++ + Component.onDestruction: MetricsService.consumers-- + ColumnLayout { + id: body + anchors { + left: parent.left + right: parent.right + top: parent.top + margins: 16 + } + spacing: 12 + RowLayout { + Text { + text: "System" + color: Theme.text + font.pixelSize: 18 + Layout.fillWidth: true + } + GlassIconButton { + text: "⚙" + onClicked: ShellState.openSettings("metrics") + Accessible.name: "Metrics settings" + } + } + RowLayout { + Layout.fillWidth: true + MetricGauge { + label: "CPU" + value: MetricsService.cpu.percent + Layout.fillWidth: true + } + MetricGauge { + label: "GPU" + value: MetricsService.gpu.percent + Layout.fillWidth: true + } + MetricGauge { + label: "RAM" + value: MetricsService.ram.percent + Layout.fillWidth: true + } + } + Canvas { + id: graph + visible: !root.compact + Layout.fillWidth: true + Layout.preferredHeight: visible ? 36 : 0 + property var values: MetricsService.history + property color stroke: Theme.accent + onValuesChanged: if (visible) + requestPaint() + onStrokeChanged: requestPaint() + onWidthChanged: requestPaint() + onPaint: { + const c = getContext("2d"); + c.reset(); + c.strokeStyle = stroke; + c.lineWidth = 1.5; + c.beginPath(); + let started = false; + for (let i = 0; i < values.length; i++) { + if (values[i].cpu == null) { + started = false; + continue; + } + const x = i * width / 59, y = height * (1 - values[i].cpu / 100); + if (!started) { + c.moveTo(x, y); + started = true; + } else + c.lineTo(x, y); + } + c.stroke(); + } + Accessible.name: "CPU utilization history" + } + Text { + visible: !root.compact + text: MetricsService.cpu.name || "CPU" + color: Theme.textSecondary + elide: Text.ElideRight + Layout.fillWidth: true + } + Text { + text: "CPU " + MetricsService.value(MetricsService.cpu.temperature, " °C") + " · " + MetricsService.value((MetricsService.cpu.frequency == null ? null : MetricsService.cpu.frequency / 1000), " GHz", 2) + color: Theme.textSecondary + Layout.fillWidth: true + } + Text { + visible: !root.compact + text: MetricsService.gpu.name || "No GPU telemetry" + color: Theme.textSecondary + elide: Text.ElideRight + Layout.fillWidth: true + } + Text { + visible: !root.compact + text: "GPU " + MetricsService.value(MetricsService.gpu.temperature, " °C") + " · " + MetricsService.value(MetricsService.gpu.frequency, " MHz") + " · " + MetricsService.value(MetricsService.gpu.power, " W", 1) + color: Theme.textSecondary + Layout.fillWidth: true + } + Text { + visible: !root.compact + text: "VRAM " + MetricsService.bytes(MetricsService.gpu.used) + " / " + MetricsService.bytes(MetricsService.gpu.total) + color: Theme.textSecondary + Layout.fillWidth: true + } + Text { + text: "RAM " + MetricsService.bytes(MetricsService.ram.used) + " / " + MetricsService.bytes(MetricsService.ram.total) + color: Theme.textSecondary + Layout.fillWidth: true + } + Repeater { + model: root.compact ? [] : (MetricsService.snapshot.storage || []) + ColumnLayout { + id: disk + required property var modelData + Layout.fillWidth: true + Text { + text: disk.modelData.path + " · " + (disk.modelData.available ? MetricsService.bytes(disk.modelData.used) + " / " + MetricsService.bytes(disk.modelData.total) : "Unavailable") + color: Theme.text + elide: Text.ElideMiddle + Layout.fillWidth: true + } + Rectangle { + Layout.fillWidth: true + implicitHeight: 5 + radius: 3 + color: Theme.border + Rectangle { + width: parent.width * (MetricsService.stale ? 0 : (disk.modelData.percent || 0) / 100) + height: parent.height + radius: 3 + color: Theme.accent + } + } + Text { + text: "Free " + MetricsService.bytes(disk.modelData.free) + color: Theme.textSecondary + visible: disk.modelData.available + } + } + } + Text { + text: "↓ " + MetricsService.bytes(MetricsService.network.download) + "/s ↑ " + MetricsService.bytes(MetricsService.network.upload) + "/s" + color: Theme.text + Layout.fillWidth: true + } + Text { + visible: MetricsService.stale || !!MetricsService.error + text: MetricsService.error || "Waiting for metrics…" + color: Theme.textSecondary + wrapMode: Text.Wrap + Layout.fillWidth: true + } + } +} diff --git a/quickshell/osd/Osd.qml b/quickshell/osd/Osd.qml new file mode 100644 index 0000000..9c9d020 --- /dev/null +++ b/quickshell/osd/Osd.qml @@ -0,0 +1,315 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import Quickshell +import Quickshell.Io +import Quickshell.Wayland +import "../components" +import "../services" +import "../core" +import "../theme" + +// macOS-style level HUD: a compact glass capsule for volume, microphone and +// brightness. It follows changes from any source (keys, wpctl, the bar), can be +// dragged, and stays while hovered. The surface is sized to the capsule so +// compositor glass shapes its edges to it. +// qmllint disable uncreatable-type +PanelWindow { + id: root + readonly property var options: ConfigService.ready ? ConfigService.data.osd : ({ + enabled: false, + position: "top-right", + timeout: 1600, + step: 5 + }) + property var targetScreen: null + screen: ScreenService.current(targetScreen) + property bool shown: false + property string kind: "volume" + readonly property var node: kind === "microphone" ? AudioService.source : AudioService.sink + readonly property var brightness: SystemService.state.brightness || ({ + available: false + }) + readonly property bool muted: kind !== "brightness" && !!node && !!node.audio && node.audio.muted + readonly property real level: kind === "brightness" ? (brightness.value || 0) / 100 : node && node.audio ? node.audio.volume : 0 + readonly property string title: kind === "brightness" ? "Display" : kind === "microphone" ? "Microphone" : "Sound" + readonly property string detail: kind === "brightness" ? (brightness.device || "Brightness") : node ? (node.description || node.name || "") : "" + readonly property string glyph: kind === "brightness" ? "󰃠" : kind === "microphone" ? (muted ? "󰍭" : "󰍬") : muted || level === 0 ? "󰖁" : level < 0.34 ? "󰕿" : level < 0.67 ? "󰖀" : "󰕾" + + // Top positions drop out of the bar as a drawer; bottom-center floats. + readonly property bool attached: options.position !== "bottom-center" + anchors { + top: root.attached + bottom: !root.attached + right: root.options.position === "top-right" + } + // Margins is present at runtime but unresolved in 0.3.1 qmltypes. + // qmllint disable unqualified unresolved-type + margins { + right: BarDrawers.margin + BarDrawers.radius + bottom: 96 + } + // qmllint enable unqualified unresolved-type + implicitWidth: Math.round(card.width) + implicitHeight: (attached ? BarDrawers.bottom : 0) + 74 + // Only the capsule takes input; the strip over the bar passes through. + mask: Region { + item: card.body + } + visible: shown || card.shown + color: Theme.transparent + exclusionMode: ExclusionMode.Ignore + WlrLayershell.layer: WlrLayer.Overlay + WlrLayershell.namespace: "glassMxrph-osd" + WlrLayershell.keyboardFocus: WlrKeyboardFocus.None + Component.onCompleted: ShellState.osdWindow = root + Component.onDestruction: ShellState.osdWindow = null + + // Initial values and default-device switches are not user changes. + property bool armed: false + function rearm() { + armed = false; + armTimer.restart(); + } + Timer { + id: armTimer + running: true + interval: 1500 + onTriggered: root.armed = true + } + function show(next) { + // Control Center already shows these levels. + if (!options.enabled || !armed || ShellState.controlCenterOpen) + return; + if (!shown) + targetScreen = ScreenService.active; + kind = next; + shown = true; + hideTimer.restart(); + } + Timer { + id: hideTimer + interval: root.options.timeout + onTriggered: { + if (hover.hovered || bar.pressed) + restart(); + else + root.shown = false; + } + } + Connections { + target: AudioService + function onSinkChanged() { + root.rearm(); + } + function onSourceChanged() { + root.rearm(); + } + } + Connections { + target: AudioService.sink ? AudioService.sink.audio : null + function onVolumeChanged() { + root.show("volume"); + } + function onMutedChanged() { + root.show("volume"); + } + } + Connections { + target: AudioService.source ? AudioService.source.audio : null + function onMutedChanged() { + root.show("microphone"); + } + } + property var lastBrightness: undefined + Connections { + target: SystemService + function onStateChanged() { + const value = SystemService.state.brightness ? SystemService.state.brightness.value : undefined; + if (value !== undefined && root.lastBrightness !== undefined && value !== root.lastBrightness) + root.show("brightness"); + root.lastBrightness = value; + } + } + + function step(direction) { + return direction * root.options.step / 100; + } + function changeVolume(input, direction) { + const target = input ? AudioService.source : AudioService.sink; + if (target && target.audio) { + if (direction > 0) + target.audio.muted = false; + AudioService.volume(input, target.audio.volume + step(direction)); + } + show(input ? "microphone" : "volume"); + } + function changeBrightness(direction) { + if (brightness.available) + SystemService.action("brightness", Math.max(1, Math.min(100, Math.round((brightness.value || 0) + step(direction) * 100))), false); + show("brightness"); + } + + BarDrawer { + id: card + objectName: "osdSurface" + y: root.attached ? BarDrawers.bottom : 0 + open: root.shown + attached: root.attached + style: root.options.animation || "slide" + contentWidth: 320 + contentHeight: 74 + drawerId: "osd" + screenName: root.screen ? root.screen.name : "" + screenX: root.options.position === "top-right" ? (root.screen ? root.screen.width : 1920) - BarDrawers.margin - BarDrawers.radius - width : ((root.screen ? root.screen.width : 1920) - width) / 2 + HoverHandler { + id: hover + } + RowLayout { + anchors.fill: parent + anchors.leftMargin: 14 + anchors.rightMargin: 18 + spacing: 12 + GlassIcon { + size: 42 + radius: 21 + glyph: root.glyph + fallback: root.kind === "brightness" ? "☀" : root.muted ? "×" : "♪" + glyphSize: 20 + active: root.muted + color: root.muted ? Qt.alpha(Theme.urgent, 0.85) : Theme.surfaceVariant + glyphColor: root.muted ? Theme.surface : Theme.text + } + ColumnLayout { + Layout.fillWidth: true + spacing: 4 + RowLayout { + Layout.fillWidth: true + spacing: 8 + ColumnLayout { + Layout.fillWidth: true + spacing: 0 + Text { + text: root.title + color: Theme.text + font.pixelSize: 13 + font.weight: Font.DemiBold + } + Text { + text: root.detail + visible: text !== "" + color: Theme.textSecondary + font.pixelSize: 10 + elide: Text.ElideRight + Layout.fillWidth: true + } + } + Text { + objectName: "osdValue" + text: root.muted ? "Muted" : Math.round(root.level * 100) + "%" + color: root.muted ? Theme.urgent : Theme.textSecondary + font.pixelSize: 12 + font.features: { + "tnum": 1 + } + } + } + // Thin level bar; dragging adjusts the level directly. + Slider { + id: bar + objectName: "osdSlider" + Layout.fillWidth: true + implicitHeight: 14 + padding: 0 + from: 0 + to: 1 + value: root.level + enabled: root.kind !== "brightness" || !!root.brightness.available + onMoved: { + if (root.kind !== "brightness") + AudioService.volume(root.kind === "microphone", value); + hideTimer.restart(); + } + onPressedChanged: if (!pressed && root.kind === "brightness") { + SystemService.action("brightness", Math.max(1, Math.round(value * 100)), false); + value = Qt.binding(() => root.level); + } + background: Rectangle { + y: bar.availableHeight / 2 - height / 2 + width: bar.availableWidth + height: 6 + radius: 3 + color: Theme.surfaceVariant + border.width: 1 + border.color: Theme.hairline + Rectangle { + width: bar.visualPosition * parent.width + height: parent.height + radius: 3 + color: root.muted ? Qt.alpha(Theme.text, 0.35) : Theme.text + Behavior on width { + enabled: !bar.pressed + NumberAnimation { + duration: Theme.duration / 2 + easing.type: Easing.OutCubic + } + } + } + } + handle: Rectangle { + x: bar.visualPosition * (bar.availableWidth - width) + y: bar.availableHeight / 2 - height / 2 + width: 14 + height: 14 + radius: 7 + color: Theme.text + opacity: hover.hovered || bar.pressed ? 1 : 0 + Behavior on opacity { + NumberAnimation { + duration: Theme.duration / 2 + } + } + } + } + } + } + } + + IpcHandler { + target: "osd" + function volumeUp(): void { + root.changeVolume(false, 1); + } + function volumeDown(): void { + root.changeVolume(false, -1); + } + function mute(): void { + AudioService.mute(false); + root.show("volume"); + } + function micMute(): void { + AudioService.mute(true); + root.show("microphone"); + } + function brightnessUp(): void { + root.changeBrightness(1); + } + function brightnessDown(): void { + root.changeBrightness(-1); + } + // Not "show": that name collides with the `quickshell ipc show` subcommand. + function open(kind: string): void { + root.show(["volume", "microphone", "brightness"].includes(kind) ? kind : "volume"); + } + function status(): string { + return JSON.stringify({ + shown: root.shown, + kind: root.kind, + level: root.level, + muted: root.muted, + screen: root.screen ? root.screen.name : "" + }); + } + } +} diff --git a/quickshell/plugins/PluginHost.qml b/quickshell/plugins/PluginHost.qml new file mode 100644 index 0000000..dcf6ab5 --- /dev/null +++ b/quickshell/plugins/PluginHost.qml @@ -0,0 +1,99 @@ +pragma ComponentBehavior: Bound +import QtQuick +import Quickshell +import "../services" +import "../compat/noctalia/Host" as NoctaliaHost +// Not referenced by name: importing the directory makes Quickshell index the +// Noctalia compatibility modules (see the Loader below). +// qmllint disable unused-imports +import "../compat/noctalia" as NoctaliaCompat +// qmllint enable unused-imports + +// Loads enabled plugins that are not bar widgets: services stay loaded while +// enabled; panels, overlays and menus load when summoned (or always, with +// "keepLoaded") and receive open(payload), like in Omarchy. Bar widgets are +// hosted by bar/modules/PluginModule.qml. +Scope { + id: root + // The directory import above puts the Noctalia compatibility modules in + // Quickshell's qs.* index; loading them by URL keeps any failure there a + // warning instead of breaking the whole shell. + Loader { + active: PluginService.plugins.some(p => p.ecosystem === "noctalia" && PluginService.isEnabled(p.id)) + source: active ? Qt.resolvedUrl("../compat/noctalia/Modules.qml") : "" + } + readonly property var hosted: PluginService.plugins.filter(p => PluginService.isEnabled(p.id)).map(p => p.id) + + Instantiator { + model: root.hosted + delegate: Scope { + id: slot + required property string modelData + readonly property string pluginId: modelData + readonly property var kinds: PluginService.kinds(pluginId) + readonly property var manifest: (PluginService.plugin(pluginId) || {}).manifest || {} + readonly property bool noctalia: PluginService.ecosystem(pluginId) === "noctalia" + + Loader { + id: serviceLoader + active: slot.kinds.includes("service") + // Noctalia's Main.qml gets its pluginApi at creation. + onActiveChanged: { + if (!active) { + const next = Object.assign({}, PluginService.services); + delete next[slot.pluginId]; + PluginService.services = next; + } else if (slot.noctalia) { + setSource(PluginService.entryUrl(slot.pluginId, "service"), { + pluginApi: PluginService.noctaliaApi(slot.pluginId) + }); + } else { + source = PluginService.entryUrl(slot.pluginId, "service"); + } + } + Component.onCompleted: if (active) + activeChanged() + onLoaded: { + if (slot.noctalia) { + // Noctalia Main.qml: shared state reached via pluginApi.mainInstance. + const napi = PluginService.noctaliaApi(slot.pluginId); + if (napi) + napi.mainInstance = item; + } else { + if ("shell" in item) + item.shell = PluginService.shellFor(slot.pluginId); + if ("pluginId" in item) + item.pluginId = slot.pluginId; + } + const next = Object.assign({}, PluginService.services); + next[slot.pluginId] = item; + PluginService.services = next; + } + + } + // First matching surface kind (panel, overlay or menu). + readonly property string surfaceKind: ["panel", "overlay", "menu"].find(k => kinds.includes(k)) || "" + Loader { + id: surfaceLoader + active: !slot.noctalia && slot.surfaceKind !== "" && (slot.manifest.keepLoaded === true || PluginService.openSurfaces[slot.pluginId] === true) + source: active ? PluginService.entryUrl(slot.pluginId, slot.surfaceKind) : "" + onLoaded: { + if ("shell" in item) + item.shell = PluginService.shellFor(slot.pluginId); + if ("pluginId" in item) + item.pluginId = slot.pluginId; + PluginService.registerSurface(slot.pluginId, item); + } + } + // Noctalia panels: a glassMxrph bar drawer driven by pluginApi.openPanel(). + Loader { + active: slot.noctalia && slot.kinds.includes("panel") + sourceComponent: NoctaliaHost.PanelHost { + api: PluginService.noctaliaApi(slot.pluginId) + source: PluginService.entryUrl(slot.pluginId, "panel") + } + } + Component.onDestruction: PluginService.registerSurface(slot.pluginId, null) + } + } +} diff --git a/quickshell/services/AppMatching.js b/quickshell/services/AppMatching.js new file mode 100644 index 0000000..ac441c1 --- /dev/null +++ b/quickshell/services/AppMatching.js @@ -0,0 +1,60 @@ +function canonical(id) { return String(id || "").replace(/\.desktop$/i, ""); } +function normalized(id) { return canonical(id).toLowerCase(); } +// Lookup tables for one catalog array. Hyprland emits events (title changes) +// several times a second; scanning every entry per window per event dominated +// idle JavaScript time. The catalog array is replaced, not mutated, on change. +let indexedEntries = null, index = null; +function lookup(entries) { + if (entries === indexedEntries) return index; + const add = (map, key, entry) => { if (!map.has(key)) map.set(key, []); map.get(key).push(entry); }; + index = {canonical: new Map(), normalized: new Map(), startup: new Map()}; + for (const e of entries) { + if (!index.canonical.has(canonical(e.id))) index.canonical.set(canonical(e.id), e); + add(index.normalized, normalized(e.id), e); + if (e.startupClass) add(index.startup, e.startupClass.toLowerCase(), e); + } + indexedEntries = entries; + return index; +} +function match(appId, initialClass, entries, overrides) { + const candidates = [appId, initialClass].filter(Boolean); + const table = lookup(entries); + for (const key of candidates) { + const override = overrides[key]; + if (override) return table.canonical.get(canonical(override)) || null; + } + for (const key of candidates) { + const exact = table.normalized.get(normalized(key)) || []; + if (exact.length === 1) return exact[0]; + const startup = table.startup.get(key.toLowerCase()) || []; + if (startup.length === 1) return startup[0]; + } + return null; // Never guess from titles, substrings, or an ambiguous class. +} +function group(entries, windows, pinned, overrides, showRunning) { + const result = [], byId = new Map(); + function add(id, entry, isPinned, label) { + const row = {id:id, entry:entry, pinned:isPinned, name:entry ? entry.name : label || id, windows:[], focused:false}; + byId.set(id, row); result.push(row); return row; + } + for (const id of pinned) { + const key = canonical(id); + if (!byId.has(key)) add(key, lookup(entries).canonical.get(key) || null, true); + } + for (const window of windows) { + const entry = match(window.appId, window.initialClass, entries, overrides); + const id = entry ? canonical(entry.id) : "window:" + (window.appId || window.initialClass || window.address); + let row = byId.get(id); + if (!row && showRunning) row = add(id, entry, false, window.appId || window.title); + if (row) { row.windows.push(window); row.focused = row.focused || window.active; } + } + return result; +} +function reorder(pinned, source, target) { + const result = pinned.slice(); + const from = result.findIndex(id => canonical(id) === canonical(source)); + const to = result.findIndex(id => canonical(id) === canonical(target)); + if (from < 0 || to < 0 || from === to) return result; + result.splice(to, 0, result.splice(from, 1)[0]); + return result; +} diff --git a/quickshell/services/ApplicationsService.qml b/quickshell/services/ApplicationsService.qml new file mode 100644 index 0000000..23ec203 --- /dev/null +++ b/quickshell/services/ApplicationsService.qml @@ -0,0 +1,39 @@ +pragma Singleton +import QtQuick +import Quickshell +import "AppMatching.js" as Matching + +Singleton { + id: root + readonly property var entries: DesktopEntries.applications.values + readonly property var launchable: entries.filter(e => !e.noDisplay).slice().sort((a, b) => a.name.localeCompare(b.name)) + property string error: "" + function byId(id) { + return entries.find(e => Matching.canonical(e.id) === Matching.canonical(id)) || null; + } + function icon(entry) { + return entry && entry.icon ? Quickshell.iconPath(entry.icon, true) : ""; + } + function launch(entry, action) { + if (!entry) { + error = "This desktop entry is no longer installed."; + return false; + } + if (entry.runInTerminal) { + const terminal = ConfigService.data.dock.terminalCommand; + if (!terminal.length) { + error = "Set dock.terminalCommand to a terminal command argument array before launching terminal applications."; + return false; + } + Quickshell.execDetached({ + command: terminal.concat(action ? action.command : entry.command), + workingDirectory: entry.workingDirectory + }); + } else if (action) + action.execute(); + else + entry.execute(); + error = ""; + return true; + } +} diff --git a/quickshell/services/AudioService.qml b/quickshell/services/AudioService.qml new file mode 100644 index 0000000..42119c6 --- /dev/null +++ b/quickshell/services/AudioService.qml @@ -0,0 +1,41 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Services.Pipewire + +Singleton { + id: root + property var backend: Pipewire + readonly property var sink: backend.defaultAudioSink + readonly property var source: backend.defaultAudioSource + readonly property var outputs: backend.nodes.values.filter(n => n.audio && n.isSink && !n.isStream) + readonly property var inputs: backend.nodes.values.filter(n => n.audio && !n.isSink && !n.isStream) + readonly property bool available: backend.ready + PwObjectTracker { + objects: root.backend === Pipewire ? [root.sink, root.source].filter(n => n !== null) : [] + } + function volume(input, value) { + const node = input ? source : sink; + if (!node || !node.audio || !Number.isFinite(value)) + return false; + node.audio.volume = Math.max(0, Math.min(1, value)); + return true; + } + function mute(input) { + const node = input ? source : sink; + if (!node || !node.audio) + return false; + node.audio.muted = !node.audio.muted; + return true; + } + function select(input, index) { + const node = (input ? inputs : outputs)[index]; + if (!node) + return false; + if (input) + backend.preferredDefaultAudioSource = node; + else + backend.preferredDefaultAudioSink = node; + return true; + } +} diff --git a/quickshell/services/BluetoothService.qml b/quickshell/services/BluetoothService.qml new file mode 100644 index 0000000..9af4238 --- /dev/null +++ b/quickshell/services/BluetoothService.qml @@ -0,0 +1,54 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Bluetooth + +Singleton { + id: root + property var backend: Bluetooth + property string adapterId: "" + readonly property var adapters: backend.adapters.values + readonly property var adapter: adapters.find(a => a.adapterId === adapterId) || backend.defaultAdapter + readonly property var devices: adapter ? adapter.devices.values : [] + readonly property bool canToggle: !!adapter && adapter.state !== BluetoothAdapterState.Blocked + readonly property bool enabled: !!adapter && adapter.enabled + readonly property string summary: devices.filter(d => d.connected).map(d => d.name).join(", ") || (enabled ? "On" : "Off") + property string error: "" + property var pending: null + function toggle() { + if (!adapter || adapter.state === BluetoothAdapterState.Blocked) + return false; + error = ""; + adapter.enabled = !enabled; + return true; + } + function connectDevice(device) { + if (!device || !device.paired || !enabled || pending) + return false; + error = ""; + pending = device; + timeout.restart(); + if (device.connected) + device.disconnect(); + else + device.connect(); + return true; + } + Connections { + target: root.pending + function onStateChanged() { + if (root.pending && (root.pending.state === BluetoothDeviceState.Connected || root.pending.state === BluetoothDeviceState.Disconnected)) { + timeout.stop(); + root.pending = null; + } + } + } + Timer { + id: timeout + interval: 15000 + onTriggered: { + root.error = "No connection confirmation received. Open the Bluetooth manager for details."; + root.pending = null; + } + } +} diff --git a/quickshell/services/CavaService.qml b/quickshell/services/CavaService.qml new file mode 100644 index 0000000..5f5cd90 --- /dev/null +++ b/quickshell/services/CavaService.qml @@ -0,0 +1,60 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Io + +Singleton { + id: root + property int consumers: 0 + // Desktop visualizer widgets request Cava regardless of the media card's toggle. + property int widgetConsumers: 0 + property var bars: Array(24).fill(0) + property string error: "" + property int frames: 0 + property bool failed: false + readonly property bool wanted: ConfigService.ready && MediaService.playing && ((ConfigService.data.media.showCava && consumers > 0) || widgetConsumers > 0) + onWantedChanged: { + if (!wanted) { + failed = false; + error = ""; + bars = Array(24).fill(0); + } + } + Process { + id: process + command: ["python3", Quickshell.shellPath("helpers/cava.py"), Quickshell.shellPath("config/cava.conf")] + running: root.wanted && !root.failed + stdout: SplitParser { + onRead: data => { + const values = data.trim().split(";").filter(v => v.length).map(Number); + if (values.length === 24 && values.every(v => Number.isFinite(v) && v >= 0 && v <= 1000)) { + root.bars = values.map(v => v / 1000); + root.frames++; + } + } + } + stderr: StdioCollector { + id: errors + } + // Quickshell 0.3.1 metadata omits QProcess::ExitStatus. + // qmllint disable signal-handler-parameters + onExited: code => { + if (root.wanted) { + root.failed = true; + root.error = errors.text.trim().slice(0, 300) || "Cava stopped (" + code + ")"; + } + } + } + IpcHandler { + target: "cava" + function status(): string { + return JSON.stringify({ + running: process.running, + error: root.error, + bars: root.bars, + frames: root.frames, + consumers: root.consumers + }); + } + } +} diff --git a/quickshell/services/ConfigLogic.js b/quickshell/services/ConfigLogic.js new file mode 100644 index 0000000..0ac32d9 --- /dev/null +++ b/quickshell/services/ConfigLogic.js @@ -0,0 +1,135 @@ +function merge(defaults, user) { + if (Array.isArray(defaults)) { + if (user !== undefined && !Array.isArray(user)) throw Error("Expected a configuration array"); + return user === undefined ? defaults.slice() : user.slice(); + } + if (defaults && typeof defaults === "object") { + if (user !== undefined && (!user || typeof user !== "object" || Array.isArray(user))) throw Error("Expected a configuration object"); + const result = Object.assign({}, user && typeof user === "object" && !Array.isArray(user) ? user : {}); + for (const key of Object.keys(defaults)) result[key] = merge(defaults[key], result[key]); + return result; + } + return user === undefined ? defaults : user; +} +function validate(c) { + if (!c || typeof c !== "object" || Array.isArray(c)) throw Error("Configuration must be an object"); + if (c.schemaVersion !== 3) throw Error("Unsupported configuration version"); + if (!["system", "custom", "matugen"].includes(c.appearance.accentSource)) throw Error("Invalid accent source"); + if (!/^#[0-9a-fA-F]{6}$/.test(c.appearance.customAccent)) throw Error("Accent must be #RRGGBB"); + if (!/^#[0-9a-fA-F]{6}$/.test(c.appearance.glassTint)) throw Error("Glass tint must be #RRGGBB"); + for (const [key, min, max] of [["glassOpacity",0.15,1],["borderOpacity",0,1],["radius",0,48]]) { + const n = c.appearance[key]; + if (typeof n !== "number" || !Number.isFinite(n) || n < min || n > max) throw Error("Invalid " + key); + } + if (typeof c.animation.reducedMotion !== "boolean" || !Number.isFinite(c.animation.duration) || c.animation.duration < 0 || c.animation.duration > 1000) throw Error("Invalid animation settings"); + if (!Number.isFinite(c.bar.height) || c.bar.height < 32 || c.bar.height > 80 || !Number.isFinite(c.bar.margin) || c.bar.margin < 0 || c.bar.margin > 100) throw Error("Invalid bar geometry"); + if(!Number.isInteger(c.bar.workspaces.count) || c.bar.workspaces.count<1 || c.bar.workspaces.count>20 || !["numbers","roman","dots","pacman"].includes(c.bar.workspaces.style) || ["showDate","use24Hour","showSeconds"].some(k=>typeof c.bar.clock[k]!=="boolean"))throw Error("Invalid bar module options"); + const cava=c.bar.cava; + if(!cava || !Number.isInteger(cava.bars) || cava.bars<4 || cava.bars>24 || !["bars","mirror"].includes(cava.style) || typeof cava.hideWhenIdle!=="boolean")throw Error("Invalid bar visualizer preferences"); + const validModules = list => { + const seen = new Set(); + if (!Array.isArray(list)) throw Error("Bar modules must be an array"); + for (const m of list) { + if (!m || typeof m.id !== "string" || seen.has(m.id) || !["left","center","right"].includes(m.position) || typeof m.enabled !== "boolean") throw Error("Invalid bar module"); + // Optional per-module options (the cog in Settings → Bar). + if (m.options !== undefined && (!m.options || typeof m.options !== "object" || Array.isArray(m.options))) throw Error("Invalid bar module options"); + seen.add(m.id); + } + }; + validModules(c.bar.modules); + // Per-screen layouts: screen name -> {modules}. + if (!c.bar.screens || typeof c.bar.screens !== "object" || Array.isArray(c.bar.screens)) throw Error("Invalid per-screen bar layouts"); + for (const name of Object.keys(c.bar.screens)) { + const entry = c.bar.screens[name]; + if (!name || !entry || typeof entry !== "object") throw Error("Invalid per-screen bar layout"); + validModules(entry.modules); + } + if (typeof c.tray.enabled !== "boolean" || typeof c.tray.hoverMenus !== "boolean") throw Error("Invalid tray toggle"); + for (const [key, min, max] of [["hoverDelay", 100, 2000], ["iconSize", 16, 32], ["spacing", 0, 24]]) { + if (!Number.isInteger(c.tray[key]) || c.tray[key] < min || c.tray[key] > max) throw Error("Invalid tray " + key); + } + if (!["pill", "transparent", "icons"].includes(c.tray.background)) throw Error("Invalid tray background"); + if (!["bottom", "left", "right"].includes(c.dock.position) || !["always", "auto", "intelligent"].includes(c.dock.visibility)) throw Error("Invalid dock position/visibility"); + if (typeof c.dock.monitor !== "string" || !c.dock.monitor.length) throw Error("Invalid dock monitor"); + for (const key of ["enabled", "magnification", "showRunningApps", "runningIndicators", "tooltips"]) if (typeof c.dock[key] !== "boolean") throw Error("Invalid dock " + key); + for (const [key,min,max] of [["iconSize",24,80],["spacing",0,24],["margin",0,80],["magnificationStrength",0,0.8],["animationSpeed",0.25,3]]) { + if (!Number.isFinite(c.dock[key]) || c.dock[key] < min || c.dock[key] > max) throw Error("Invalid dock " + key); + } + if (!Array.isArray(c.dock.pinnedApps) || c.dock.pinnedApps.some(id => typeof id !== "string" || !id.length || id.includes("/")) || new Set(c.dock.pinnedApps.map(id => id.replace(/\.desktop$/i, ""))).size !== c.dock.pinnedApps.length) throw Error("Invalid pinned apps"); + if (!Array.isArray(c.dock.terminalCommand) || c.dock.terminalCommand.some(arg => typeof arg !== "string")) throw Error("Terminal command must be an argument array"); + if (!c.dock.appOverrides || typeof c.dock.appOverrides !== "object" || Array.isArray(c.dock.appOverrides) || Object.values(c.dock.appOverrides).some(id => typeof id !== "string")) throw Error("Invalid app matching overrides"); + if (!Number.isInteger(c.launcher.maxResults) || c.launcher.maxResults<10 || c.launcher.maxResults>100 || !Number.isFinite(c.launcher.width) || c.launcher.width<420 || c.launcher.width>960 || typeof c.launcher.showDescriptions!=="boolean" || typeof c.launcher.recentFiles!=="boolean") throw Error("Invalid launcher preferences"); + for (const key of ["highlights","shadows"]) if(typeof c.appearance[key]!=="boolean")throw Error("Invalid appearance toggle"); + if(!Number.isFinite(c.appearance.panelOpacity) || c.appearance.panelOpacity<0.15 || c.appearance.panelOpacity>1)throw Error("Invalid panel opacity"); + if(!Number.isFinite(c.animation.intensity) || c.animation.intensity<0 || c.animation.intensity>1)throw Error("Invalid animation intensity"); + if(typeof c.matugen.executable!=="string" || !c.matugen.executable.trim() || typeof c.matugen.regenerateOnWallpaperChange!=="boolean" || !Number.isFinite(c.matugen.contrast) || c.matugen.contrast < -1 || c.matugen.contrast>1)throw Error("Invalid Matugen options"); + if(!["scheme-content","scheme-expressive","scheme-fidelity","scheme-fruit-salad","scheme-monochrome","scheme-neutral","scheme-rainbow","scheme-tonal-spot","scheme-vibrant","scheme-smart"].includes(c.matugen.scheme))throw Error("Unsupported Matugen scheme"); + if(!["native","auto","serpantinum","awww","custom"].includes(c.wallpaper.backend) || !Array.isArray(c.wallpaper.directories) || c.wallpaper.directories.some(p=>typeof p!=="string" || !p.length) || !Array.isArray(c.wallpaper.command) || c.wallpaper.command.some(a=>typeof a!=="string") || typeof c.wallpaper.paletteMonitor!=="string")throw Error("Invalid wallpaper preferences"); + if(!c.wallpaper.byMonitor || typeof c.wallpaper.byMonitor!=="object" || Array.isArray(c.wallpaper.byMonitor) || Object.values(c.wallpaper.byMonitor).some(p=>typeof p!=="string"))throw Error("Invalid wallpaper map"); + if(!c.wallpaper.providerPaths || typeof c.wallpaper.providerPaths!=="object" || Array.isArray(c.wallpaper.providerPaths) || Object.values(c.wallpaper.providerPaths).some(p=>typeof p!=="string"))throw Error("Invalid provider wallpaper map"); + for(const key of ["showAlbumArt","showProgress","showAlbum","showCava"])if(typeof c.media[key]!=="boolean")throw Error("Invalid media toggle"); + if(typeof c.media.preferredPlayer!=="string")throw Error("Invalid media preferences"); + const lock=c.lock; + if(!lock || ["enabled","glass","media","powerButtons"].some(k=>typeof lock[k]!=="boolean") || !["wallpaper","screenshot"].includes(lock.backdrop) || typeof lock.pamService!=="string" || !/^[A-Za-z0-9._-]{0,64}$/.test(lock.pamService))throw Error("Invalid lock screen preferences"); + const dw=c.desktopWidgets; + if(!dw || dw.version!==1 || typeof dw.grid!=="boolean" || !Array.isArray(dw.items))throw Error("Invalid desktop widgets"); + const widgetIds=new Set(); + for(const w of dw.items) { + // Unknown types are preserved (and skipped when rendering) for forward compatibility. + if(!w || typeof w.id!=="string" || !/^[a-z0-9-]{1,40}$/.test(w.id) || widgetIds.has(w.id) || typeof w.type!=="string" || typeof w.variant!=="string" || typeof w.monitor!=="string" || ![w.x,w.y,w.w,w.h,w.opacity].every(Number.isFinite) || w.w<40 || w.h<40 || w.w>4000 || w.h>4000 || w.opacity<0.1 || w.opacity>1 || (w.options!==undefined && (!w.options || typeof w.options!=="object" || Array.isArray(w.options))))throw Error("Invalid desktop widget"); + widgetIds.add(w.id); + } + if(!c.plugins || !Array.isArray(c.plugins.enabled) || c.plugins.enabled.some(id=>typeof id!=="string" || !id))throw Error("Invalid plugin preferences"); + const dash=c.dashboard; + if(!dash || ["enabled","openFromClock","rememberTab","easyEffects"].some(k=>typeof dash[k]!=="boolean") || !["top-left","top-center","top-right","center"].includes(dash.position) || !Array.isArray(dash.tabs))throw Error("Invalid dashboard preferences"); + const dashTabs=new Set(); + for(const t of dash.tabs) { if(!t || typeof t.id!=="string" || dashTabs.has(t.id) || typeof t.enabled!=="boolean")throw Error("Invalid dashboard tab"); dashTabs.add(t.id); } + if(typeof c.osd.enabled!=="boolean" || !["slide","drop","fade","shrink"].includes(c.osd.animation) || !["top-right","top-center","bottom-center"].includes(c.osd.position) || !Number.isInteger(c.osd.timeout) || c.osd.timeout<500 || c.osd.timeout>5000 || !Number.isInteger(c.osd.step) || c.osd.step<1 || c.osd.step>20)throw Error("Invalid OSD preferences"); + if(c.controlCenter.version !== 1 || !Number.isFinite(c.controlCenter.width) || c.controlCenter.width < 320 || c.controlCenter.width > 600 || !Array.isArray(c.controlCenter.modules))throw Error("Invalid Control Center configuration"); + const controlIds=new Set(); + for(const m of c.controlCenter.modules) { if(!m || typeof m.id!=="string" || controlIds.has(m.id) || typeof m.enabled!=="boolean")throw Error("Invalid Control Center module"); controlIds.add(m.id); } + for(const group of [c.system.brightness,c.system.nightLight]) for(const key of ["statusCommand","setCommand"])if(!Array.isArray(group[key]) || group[key].some(v=>typeof v!=="string" || !v.length))throw Error("Provider command must be an argument array"); + if(typeof c.system.brightness.device!=="string" || !c.system.brightness.device || !Number.isInteger(c.system.nightLight.temperature) || c.system.nightLight.temperature<1000 || c.system.nightLight.temperature>6500 || !Array.isArray(c.system.power.lockCommand) || c.system.power.lockCommand.some(v=>typeof v!=="string" || !v.length))throw Error("Invalid system provider settings"); + if(!Number.isInteger(c.metrics.interval) || c.metrics.interval<1 || c.metrics.interval>30)throw Error("Invalid metrics geometry or interval"); + if(!Array.isArray(c.metrics.storagePaths) || c.metrics.storagePaths.length>8 || c.metrics.storagePaths.some(p=>typeof p!=="string" || !p.startsWith("/") || p.includes("\u0000")) || new Set(c.metrics.storagePaths).size!==c.metrics.storagePaths.length || typeof c.metrics.networkInterface!=="string" || !c.metrics.networkInterface || typeof c.metrics.gpu!=="string" || !c.metrics.gpu)throw Error("Invalid metrics sources"); + if(!Array.isArray(c.wallpaper.history) || c.wallpaper.history.length>50 || c.wallpaper.history.some(p=>typeof p!=="string"))throw Error("Invalid wallpaper history"); + if(typeof c.hyprglass.enabled!=="boolean" || typeof c.hyprglass.layers!=="boolean" || typeof c.hyprglass.effectEnabled!=="boolean")throw Error("Invalid glass toggle"); + for(const [key,min,max] of [["blur_strength",0,5],["blur_iterations",1,5],["refraction_strength",0,8],["chromatic_aberration",0,1],["fresnel_strength",0,1],["specular_strength",0,1],["edge_thickness",0,.15],["lens_distortion",0,1],["brightness",.2,2],["contrast",.2,2],["saturation",0,2],["vibrancy",0,1],["adaptive_dim",0,1]])if(!Number.isFinite(c.hyprglass.values[key]) || c.hyprglass.values[key]max)throw Error("Invalid glass "+key); + if(!Number.isInteger(c.hyprglass.values.blur_iterations))throw Error("Invalid blur passes"); + return c; +} +function load(defaults, user) { + if (!user || typeof user !== "object" || Array.isArray(user)) throw Error("Configuration must be an object"); + const migrated = JSON.parse(JSON.stringify(user)); + const version = migrated.schemaVersion === undefined ? 1 : migrated.schemaVersion; + if (version !== 1 && version !== 2 && version !== 3) throw Error("Unsupported configuration version"); + if (version === 1) { + // Preserve every existing module and its order. Insert the newly available tray + // before system, or append when the user has removed that module. + if (migrated.bar && Array.isArray(migrated.bar.modules) && !migrated.bar.modules.some(m => m.id === "tray")) { + const index = migrated.bar.modules.findIndex(m => m.id === "system"); + migrated.bar.modules.splice(index < 0 ? migrated.bar.modules.length : index, 0, {id:"tray", position:"right", enabled:true}); + } + migrated.schemaVersion = 2; + } + if (migrated.controlCenter !== undefined && (!migrated.controlCenter || typeof migrated.controlCenter !== "object" || Array.isArray(migrated.controlCenter))) throw Error("Control Center must be an object"); + // Phase 1–6 saved an unused empty list. Migrate it exactly once; retain + // nonempty custom layouts and deliberate empty layouts after version 1. + if (!migrated.controlCenter || migrated.controlCenter.version === undefined) { + migrated.controlCenter = Object.assign({}, migrated.controlCenter || {}); + if (migrated.controlCenter.modules === undefined || (Array.isArray(migrated.controlCenter.modules) && migrated.controlCenter.modules.length === 0)) + migrated.controlCenter.modules = defaults.controlCenter.modules; + migrated.controlCenter.version = 1; + } + migrated.schemaVersion = 3; + return validate(merge(defaults, migrated)); +} +function update(config, path, value) { + const result = JSON.parse(JSON.stringify(config)); + const keys = path.split("."); + if (keys.some(k => ["__proto__","constructor","prototype"].includes(k))) throw Error("Invalid setting path"); + let target = result; + for (let i = 0; i < keys.length - 1; ++i) target = target[keys[i]]; + target[keys[keys.length - 1]] = value; + return validate(result); +} diff --git a/quickshell/services/ConfigService.qml b/quickshell/services/ConfigService.qml new file mode 100644 index 0000000..953ddc0 --- /dev/null +++ b/quickshell/services/ConfigService.qml @@ -0,0 +1,48 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Io +import "ConfigLogic.js" as Logic +Singleton { + id: root + readonly property string directory: (Quickshell.env("XDG_CONFIG_HOME") || Quickshell.env("HOME") + "/.config") + "/glassMxrph" + property var data: ({}) + property var defaults: ({}) + property bool ready: false + property string error: "" + property bool writable: false + function value(path) { return path.split(".").reduce((object,key)=>object ? object[key] : undefined,data); } + function setValue(path, value) { + if (!ready || !writable) return false; + try { data = Logic.update(data, path, value); error=""; saveTimer.restart(); return true; } + catch (e) { error = String(e); return false; } + } + function readUser() { + try { data = Logic.load(defaults, JSON.parse(userFile.text())); error = ""; writable = true; } + catch (e) { error = "Configuration preserved: " + e; writable = false; } + ready = true; + } + FileView { + id: defaultsFile + path: Qt.resolvedUrl("../config/defaults.json").toString().replace("file://", "") + onLoaded: { + root.defaults = JSON.parse(text()); root.data = root.defaults; + userFile.path = root.directory + "/config.json"; + } + } + FileView { + id: userFile + printErrors: false + atomicWrites: true + watchChanges: true + onLoaded: root.readUser() + onFileChanged: { saveTimer.stop(); reload(); } + onLoadFailed: error => { + root.ready = true; + if (error === FileViewError.FileNotFound) { root.writable = true; } + else { root.error = "Could not read configuration (" + error + ")"; root.writable = false; } + } + onSaveFailed: error => { root.error = "Could not save configuration (" + error + ")"; } + } + Timer { id: saveTimer; interval: 250; onTriggered: userFile.setText(JSON.stringify(root.data, null, 2) + "\n") } +} diff --git a/quickshell/services/EasyEffectsService.qml b/quickshell/services/EasyEffectsService.qml new file mode 100644 index 0000000..29926a2 --- /dev/null +++ b/quickshell/services/EasyEffectsService.qml @@ -0,0 +1,112 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Io + +// EasyEffects 10-band equalizer (serpantinum-style presets). Band edits stay +// local and "pending" until applied; presets apply immediately. +Singleton { + id: root + property bool installed: false + property bool running: false + property bool bypass: false + property var bands: Array(10).fill(0) + property var saved: Array(10).fill(0) + property string preset: "Flat" + property var frequencies: [32, 63, 125, 250, 500, 1000, 2000, 4000, 8000, 16000] + property string error: "" + property bool known: false + readonly property bool busy: job.running + readonly property bool pending: bands.some((b, i) => b !== saved[i]) + readonly property var presets: ({ + Flat: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + Bass: [5, 7, 5, 2, 1, 0, 0, 0, 1, 2], + Treble: [-2, -1, 0, 1, 2, 3, 4, 5, 6, 6], + Vocal: [-2, -1, 1, 3, 5, 5, 4, 2, 1, 0], + Pop: [2, 4, 2, 0, 1, 2, 4, 2, 1, 2], + Rock: [5, 4, 2, -1, -2, -1, 2, 4, 5, 6], + Jazz: [3, 3, 1, 1, 1, 1, 2, 1, 2, 3], + Classic: [0, 1, 2, 2, 2, 2, 1, 2, 3, 4] + }) + readonly property var presetNames: ["Flat", "Bass", "Treble", "Vocal", "Pop", "Rock", "Jazz", "Classic"] + property var queued: null + + function call(args) { + if (job.running) { + queued = args; + return; + } + job.command = ["python3", Quickshell.shellPath("helpers/easyeffects.py")].concat(args); + job.running = true; + } + function refresh() { + call(["status"]); + } + function setBand(index, gain) { + const next = bands.slice(); + next[index] = Math.round(Math.max(-12, Math.min(12, gain))); + bands = next; + preset = "Custom"; + } + function apply() { + if (installed) + call(["apply", JSON.stringify(bands), preset]); + } + function usePreset(name) { + if (!presets[name]) + return; + bands = presets[name].slice(); + preset = name; + apply(); + } + function setBypass(on) { + bypass = on; + call(["bypass", on ? "on" : "off"]); + } + Process { + id: job + stdout: StdioCollector { + onStreamFinished: { + try { + const s = JSON.parse(text); + root.installed = s.installed; + root.running = s.running; + root.bypass = s.bypass; + root.error = s.error || ""; + root.saved = s.bands; + root.frequencies = s.frequencies; + // Keep unapplied edits; otherwise follow the saved state. + if (!root.known || !root.pending) { + root.bands = s.bands.slice(); + root.preset = s.preset; + } + root.known = true; + } catch (e) { + root.error = String(e); + } + } + } + onRunningChanged: if (!running && root.queued) { + const next = root.queued; + root.queued = null; + root.call(next); + } + } + IpcHandler { + target: "equalizer" + function status(): string { + return JSON.stringify({ + installed: root.installed, + running: root.running, + bypass: root.bypass, + bands: root.bands, + preset: root.preset, + pending: root.pending, + error: root.error + }); + } + function refresh(): void { + root.refresh(); + } + } +} diff --git a/quickshell/services/GlassService.qml b/quickshell/services/GlassService.qml new file mode 100644 index 0000000..7a5ee0a --- /dev/null +++ b/quickshell/services/GlassService.qml @@ -0,0 +1,36 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Hyprland +Singleton { + id:root + property var state: ({}) + property string error:"" + property string notice:"" + readonly property bool busy:job.running + property bool pendingReload:false + function probe() {if(!busy)job.start({action:"probe"});} + function apply(reloaded) {if(!busy)job.start({action:"apply",options:ConfigService.data.hyprglass,reloaded:!!reloaded});} + function restore() {if(!busy)job.start({action:"restore"});} + Component.onCompleted: startup.start() + Timer { + id:startup + interval:200 + onTriggered:{if(!ConfigService.ready){restart();return;}if(ConfigService.data.hyprglass.enabled)root.apply(false);else root.probe();} + } + Connections { + target:Hyprland + function onRawEvent(event) {if(event.name==="configreloaded" && ConfigService.ready && ConfigService.data.hyprglass.enabled){root.pendingReload=true;reloadDelay.restart();}} + } + Timer {id:reloadDelay;interval:600;onTriggered:{if(root.busy){restart();return;}root.pendingReload=false;root.apply(true);}} + ProviderJob { + id:job + helper:"helpers/glass.py" + onFinished:(request,result)=>{ + if(!result.ok){root.error=result.error;return;} + root.error="";root.state=result;root.notice=result.notice || ""; + if(request.action==="apply")ConfigService.setValue("hyprglass.enabled",true); + if(request.action==="restore")ConfigService.setValue("hyprglass.enabled",false); + } + } +} diff --git a/quickshell/services/HyprlandService.qml b/quickshell/services/HyprlandService.qml new file mode 100644 index 0000000..9227622 --- /dev/null +++ b/quickshell/services/HyprlandService.qml @@ -0,0 +1,65 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Hyprland + +Singleton { + id: root + readonly property var visibleWorkspaces: Hyprland.workspaces.values.filter(w => w.active).map(w => w.id) + readonly property var windows: Hyprland.toplevels.values.map(t => { + const info = t.lastIpcObject || {}; + return { + address: t.address, + handle: t.wayland, + appId: t.wayland ? t.wayland.appId : info.class || "", + initialClass: info.initialClass || "", + title: t.title, + active: t.activated, + monitor: t.monitor ? t.monitor.name : "", + workspace: t.workspace ? t.workspace.id : 0, + x: info.at ? info.at[0] : 0, + y: info.at ? info.at[1] : 0, + width: info.size ? info.size[0] : 0, + height: info.size ? info.size[1] : 0, + hidden: info.hidden === true || info.mapped === false, + fullscreen: info.fullscreen === 2, + floating: info.floating === true + }; + }).filter(w => !w.hidden) + // Monitors whose desktop is hidden: a tiled or fullscreen window sits on + // their active workspace. Desktop widgets pause animation and sampling there. + readonly property var coveredMonitors: windows.filter(w => visibleWorkspaces.includes(w.workspace) && (!w.floating || w.fullscreen)).map(w => w.monitor) + readonly property bool needsGeometry: ConfigService.ready && ConfigService.data.dock.enabled && ConfigService.data.dock.visibility === "intelligent" + function focusWindow(address) { + const window = windows.find(w => w.address === address); + if (!window) + return false; + if (window.handle) + window.handle.activate(); + else if (/^(0x)?[0-9a-f]+$/i.test(address)) + Hyprland.dispatch("focuswindow address:" + (address.startsWith("0x") ? address : "0x" + address)); + else + return false; + return true; + } + function closeWindow(address) { + const window = windows.find(w => w.address === address); + if (!window) + return false; + if (window.handle) + window.handle.close(); + else if (/^(0x)?[0-9a-f]+$/i.test(address)) + Hyprland.dispatch("closewindow address:" + (address.startsWith("0x") ? address : "0x" + address)); + else + return false; + return true; + } + // Native IPC, not subprocess polling. Hyprland emits no continuous resize event. + Timer { + interval: 500 + repeat: true + running: root.needsGeometry + triggeredOnStart: true + onTriggered: Hyprland.refreshToplevels() + } +} diff --git a/quickshell/services/MediaService.qml b/quickshell/services/MediaService.qml new file mode 100644 index 0000000..78dfa70 --- /dev/null +++ b/quickshell/services/MediaService.qml @@ -0,0 +1,114 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Io +import Quickshell.Services.Mpris + +Singleton { + id: root + readonly property var players: Mpris.players.values + property string selected: "" + readonly property string preferred: ConfigService.ready ? ConfigService.data.media.preferredPlayer : "automatic" + readonly property var player: players.find(p => p.dbusName === selected) || players.find(p => p.dbusName === preferred || p.desktopEntry === preferred) || players.find(p => p.isPlaying) || players[0] || null + readonly property bool playing: !!player && player.isPlaying + readonly property string title: player ? (player.trackTitle || "Untitled track") : "Nothing playing" + readonly property string artist: player ? player.trackArtist : "Open a music or video player" + readonly property string album: player ? player.trackAlbum : "" + readonly property string artwork: player ? player.trackArtUrl : "" + readonly property real length: player && player.lengthSupported ? Math.max(0, player.length) : 0 + property real position: 0 + property int progressConsumers: 0 + readonly property bool seekable: !!player && player.canControl && player.canSeek && player.positionSupported && length > 0 + onPreferredChanged: selected = "" + onPlayerChanged: refreshPosition() + onPlayingChanged: refreshPosition() + onLengthChanged: refreshPosition() + function refreshPosition() { + position = player && player.positionSupported ? Math.max(0, Math.min(length || Infinity, player.position)) : 0; + } + function choose(name) { + if (name && !players.some(p => p.dbusName === name)) + return false; + selected = name; + return true; + } + function toggle() { + if (!player || !player.canControl || !player.canTogglePlaying) + return false; + player.togglePlaying(); + return true; + } + function previous() { + if (!player || !player.canControl || !player.canGoPrevious) + return false; + player.previous(); + return true; + } + function next() { + if (!player || !player.canControl || !player.canGoNext) + return false; + player.next(); + return true; + } + function seek(value) { + if (!seekable || !Number.isFinite(value)) + return false; + player.position = Math.max(0, Math.min(length, value)); + refreshPosition(); + return true; + } + function time(value) { + const s = Math.max(0, Math.floor(value)); + return Math.floor(s / 60) + ":" + String(s % 60).padStart(2, "0"); + } + Timer { + interval: 500 + repeat: true + running: root.playing && root.progressConsumers > 0 + onTriggered: root.refreshPosition() + } + Connections { + target: root.player + function onPositionChanged() { + root.refreshPosition(); + } + function onTrackChanged() { + root.refreshPosition(); + } + } + IpcHandler { + target: "media" + function status(): string { + return JSON.stringify({ + players: root.players.map(p => ({ + id: p.dbusName, + name: p.identity + })), + selected: root.player ? root.player.dbusName : "", + title: root.title, + artist: root.artist, + album: root.album, + artwork: root.artwork, + playing: root.playing, + position: root.position, + length: root.length, + seekable: root.seekable + }); + } + function select(name: string): bool { + return root.choose(name); + } + function toggle(): bool { + return root.toggle(); + } + function next(): bool { + return root.next(); + } + function previous(): bool { + return root.previous(); + } + function seek(seconds: real): bool { + return root.seek(seconds); + } + } +} diff --git a/quickshell/services/MetricsService.qml b/quickshell/services/MetricsService.qml new file mode 100644 index 0000000..f22f920 --- /dev/null +++ b/quickshell/services/MetricsService.qml @@ -0,0 +1,124 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Io + +Singleton { + id: root + property int consumers: 0 + property var snapshot: ({}) + property var history: [] + property string error: "" + property int retryDelay: 1000 + property double nextStart: 0 + property int samples: 0 + property double lastSample: 0 + property bool stale: true + readonly property bool wanted: ConfigService.ready && consumers > 0 + readonly property string options: ConfigService.ready ? JSON.stringify({ + interval: ConfigService.data.metrics.interval, + storagePaths: ConfigService.data.metrics.storagePaths, + networkInterface: ConfigService.data.metrics.networkInterface + }) : "{}" + readonly property var cpu: snapshot.cpu || ({}) + readonly property var ram: snapshot.ram || ({}) + readonly property var network: snapshot.network || ({}) + readonly property var gpus: snapshot.gpus || [] + readonly property var gpu: (ConfigService.data.metrics.gpu === "auto" ? gpus[0] : gpus.find(g => g.id === ConfigService.data.metrics.gpu)) || ({}) + onOptionsChanged: { + process.running = false; + root.stale = true; + root.lastSample = 0; + root.history = []; + root.nextStart = 0; + root.retryDelay = 1000; + } + // Idle shutdown keeps the last sample: consumers that pause briefly (desktop + // widgets under windows) resume with it until it ages past the stale limit. + onWantedChanged: if (!wanted) + process.running = false + function value(n, suffix, digits) { + return stale || n === undefined || n === null || !Number.isFinite(n) ? "—" : n.toFixed(digits || 0) + (suffix || ""); + } + function bytes(n) { + if (stale || n === undefined || n === null || !Number.isFinite(n)) + return "—"; + const units = ["B", "KiB", "MiB", "GiB", "TiB"]; + let i = 0; + while (n >= 1024 && i < units.length - 1) { + n /= 1024; + i++; + } + return n.toFixed(i > 1 ? 1 : 0) + " " + units[i]; + } + Timer { + interval: 1000 + repeat: true + running: root.wanted + triggeredOnStart: true + onTriggered: { + if (!process.running && Date.now() >= root.nextStart) { + process.command = ["python3", Quickshell.shellPath("helpers/metrics.py"), root.options]; + process.running = true; + } + root.stale = !root.lastSample || Date.now() - root.lastSample > Math.max(10000, ConfigService.data.metrics.interval * 3000); + } + } + Process { + id: process + stdout: SplitParser { + onRead: data => { + try { + const state = JSON.parse(data); + if (!state.cpu || !state.ram || !Array.isArray(state.gpus) || !state.network) + throw Error("Invalid metrics snapshot"); + root.snapshot = state; + root.lastSample = Date.now(); + root.stale = false; + root.error = ""; + root.samples++; + root.retryDelay = 1000; + root.history = root.history.concat([ + { + cpu: state.cpu.percent, + ram: state.ram.percent, + down: state.network ? state.network.download : null, + up: state.network ? state.network.upload : null + } + ]).slice(-60); + } catch (e) { + root.error = String(e); + } + } + } + stderr: StdioCollector { + id: errors + } + // Quickshell 0.3.1 metadata omits QProcess::ExitStatus. + // qmllint disable signal-handler-parameters + onExited: code => { + if (root.wanted) { + root.stale = true; + root.lastSample = 0; + root.nextStart = Date.now() + root.retryDelay; + root.retryDelay = Math.min(30000, root.retryDelay * 2); + root.error = errors.text.trim().slice(0, 300) || "Metrics collector stopped; retrying"; + } + } + } + IpcHandler { + target: "metrics" + function status(): string { + return JSON.stringify({ + running: process.running, + processId: process.processId, + retryDelay: root.retryDelay, + consumers: root.consumers, + samples: root.samples, + stale: root.stale, + error: root.error, + snapshot: root.snapshot + }); + } + } +} diff --git a/quickshell/services/NetworkService.qml b/quickshell/services/NetworkService.qml new file mode 100644 index 0000000..3ff2eb3 --- /dev/null +++ b/quickshell/services/NetworkService.qml @@ -0,0 +1,66 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Networking + +Singleton { + id: root + property var backend: Networking + readonly property var devices: backend.devices.values + readonly property var wifiDevices: devices.filter(d => d.type === DeviceType.Wifi) + readonly property var networks: devices.reduce((all, d) => all.concat(d.networks.values), []) + readonly property bool available: backend.backend === NetworkBackendType.NetworkManager && wifiDevices.length > 0 + readonly property bool enabled: backend.wifiEnabled + readonly property string summary: networks.filter(n => n.connected).map(n => n.name).join(", ") || (devices.some(d => d.connected) ? "Connected" : "Disconnected") + property bool scanning: false + property var pending: null + property string error: "" + onScanningChanged: syncScan() + onWifiDevicesChanged: syncScan() + function syncScan() { + wifiDevices.forEach(d => d.scannerEnabled = scanning); + } + function toggle() { + if (!available || !backend.wifiHardwareEnabled) + return false; + error = ""; + backend.wifiEnabled = !enabled; + return true; + } + function connectNetwork(network, password) { + if (!network || pending || network.stateChanging) + return false; + error = ""; + pending = network; + timeout.restart(); + if (network.connected) + network.disconnect(); + else if (password) + network.connectWithPsk(password); + else + network.connect(); + return true; + } + Connections { + target: root.pending + function onConnectionFailed(reason) { + root.error = ConnectionFailReason.toString(reason); + timeout.stop(); + root.pending = null; + } + function onStateChanged() { + if (root.pending && !root.pending.stateChanging) { + timeout.stop(); + root.pending = null; + } + } + } + Timer { + id: timeout + interval: 20000 + onTriggered: { + root.error = "No connection confirmation received. Check the network manager."; + root.pending = null; + } + } +} diff --git a/quickshell/services/PluginService.qml b/quickshell/services/PluginService.qml new file mode 100644 index 0000000..3ffaf64 --- /dev/null +++ b/quickshell/services/PluginService.qml @@ -0,0 +1,476 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Io +import "../core" +import "../compat/omarchy/Host" as OmarchyHost +import "../compat/noctalia/Host" as NoctaliaHost + +// Installed shell plugins (Omarchy format, run through the compatibility layer +// in compat/omarchy). Plugins live in $XDG_DATA_HOME/glassMxrph/plugins and run +// unsandboxed inside the shell, as they do in Omarchy. +Singleton { + id: root + property var plugins: [] + property bool loaded: false + property string error: "" + property var lastResult: ({}) + readonly property bool busy: job.running + readonly property var enabledIds: ConfigService.ready ? ConfigService.data.plugins.enabled : [] + property var queued: [] + + // Bar widget instances and service items, by plugin id (filled by the hosts). + property var widgets: ({}) + property var services: ({}) + // Noctalia panel windows by plugin id (for test drivers; no notifications). + readonly property var panelWindows: ({}) + // The single open plugin popout (Omarchy's activePopout coordinator). + property var activePopout: null + + function plugin(id) { + return plugins.find(p => p.id === id) || null; + } + function usable(id) { + const p = plugin(id); + return !!p && p.problems.length === 0; + } + function isEnabled(id) { + return enabledIds.includes(id) && usable(id); + } + function kinds(id) { + const p = plugin(id); + return p ? (p.kinds || p.manifest.kinds || []) : []; + } + function ecosystem(id) { + const p = plugin(id); + return p ? p.ecosystem : ""; + } + // Plugin whose own settings screen Settings → Plugins should show open. + property string focusedSettings: "" + function entryUrl(id, kind) { + const p = plugin(id); + return p && isEnabled(id) ? (p.entryUrls[kind] || "") : ""; + } + function title(id) { + const p = plugin(id); + if (!p) + return id; + const widget = p.ecosystem === "noctalia" ? {} : p.manifest.barWidget || {}; + return widget.displayName || p.manifest.name || id; + } + // Enabled plugins offering a bar widget, as bar module ids. + readonly property var barModules: plugins.filter(p => isEnabled(p.id) && kinds(p.id).includes("bar-widget")).map(p => "plugin:" + p.id) + function schema(id) { + const p = plugin(id); + if (p && p.ecosystem === "noctalia") + return []; + return p && p.manifest.barWidget && Array.isArray(p.manifest.barWidget.schema) ? p.manifest.barWidget.schema : []; + } + // Widget settings: manifest defaults, schema defaults, then the user's values. + function widgetSettings(id, options) { + const p = plugin(id); + const out = Object.assign({}, p && p.manifest.barWidget ? p.manifest.barWidget.defaults || {} : {}); + for (const field of schema(id)) + if (out[field.key] === undefined && field.defaultValue !== undefined) + out[field.key] = field.defaultValue; + return Object.assign(out, options || {}); + } + + function call(args) { + if (job.running) { + queued = queued.concat([args]); + return; + } + job.command = ["python3", Quickshell.shellPath("helpers/plugins.py")].concat(args); + job.running = true; + } + function refresh() { + call(["list"]); + } + function install(source, commit, only) { + error = ""; + call(["install", String(source).trim(), commit || "", only || ""]); + } + function remove(id) { + setEnabled(id, false); + // Drop its bar module from every layout. + const strip = list => list.filter(m => m.id !== "plugin:" + id); + ConfigService.setValue("bar.modules", strip(ConfigService.data.bar.modules)); + const screens = Object.assign({}, ConfigService.data.bar.screens || {}); + for (const name in screens) + screens[name] = Object.assign({}, screens[name], { + modules: strip(screens[name].modules) + }); + ConfigService.setValue("bar.screens", screens); + call(["remove", id]); + } + // Calls an optional plugin function (plugin items are untyped). + function callIfPresent(target, name) { + if (target && typeof target[name] === "function") + target[name](); + } + function setEnabled(id, on) { + const list = enabledIds.filter(x => x !== id); + if (on && usable(id)) + list.push(id); + ConfigService.setValue("plugins.enabled", list); + if (!on && activePopout && activePopout.moduleName === id) + closePopout(); + } + // Adds an enabled plugin's bar widget to the shared bar layout. + function addToBar(id) { + const p = plugin(id); + if (!p || !isEnabled(id)) + return false; + const moduleId = "plugin:" + id; + if (ConfigService.data.bar.modules.some(m => m.id === moduleId)) + return false; + const section = (p.manifest.barWidget || {}).defaultSection; + return ConfigService.setValue("bar.modules", ConfigService.data.bar.modules.concat([ + { + id: moduleId, + position: ["left", "center", "right"].includes(section) ? section : "right", + enabled: true + } + ])); + } + + // Widget registry, for summoning a plugin's panel by id. + function registerWidget(id, item) { + const next = Object.assign({}, widgets); + next[id] = (next[id] || []).filter(i => i !== item).concat([item]); + widgets = next; + } + function unregisterWidget(id, item) { + const next = Object.assign({}, widgets); + next[id] = (next[id] || []).filter(i => i !== item); + widgets = next; + } + function widgetFor(id) { + const list = widgets[id] || []; + const screen = ShellState.activeScreen(); + return list.find(w => w.QsWindow && w.QsWindow.window && screen && w.QsWindow.window.screen === screen) || list[0] || null; + } + // Panel/overlay/menu plugins (PluginHost loads them when summoned). + property var openSurfaces: ({}) + property var surfaces: ({}) + property var pendingPayloads: ({}) + function registerSurface(id, item) { + const next = Object.assign({}, surfaces); + if (item) + next[id] = item; + else + delete next[id]; + surfaces = next; + if (item && pendingPayloads[id] !== undefined) { + const payload = pendingPayloads[id]; + const rest = Object.assign({}, pendingPayloads); + delete rest[id]; + pendingPayloads = rest; + if (typeof item.open === "function") + item.open(payload); + } + } + // Bar-widget plugins open their panel through the widget; other kinds are + // loaded on demand and receive open(payload), as in Omarchy. + function summon(id, payload) { + if (!isEnabled(id)) + return false; + if (ecosystem(id) === "noctalia") { + const napi = noctaliaApi(id); + return !!napi && kinds(id).includes("panel") && napi.openPanel(ShellState.activeScreen(), napi.barWidget); + } + const w = widgetFor(id); + if (kinds(id).includes("bar-widget") && w && typeof w.open === "function") { + w.open(); + return true; + } + if (!["panel", "overlay", "menu"].some(k => kinds(id).includes(k))) + return false; + const item = surfaces[id]; + if (item && typeof item.open === "function") { + item.open(payload || ""); + return true; + } + const pending = Object.assign({}, pendingPayloads); + pending[id] = payload || ""; + pendingPayloads = pending; + const open = Object.assign({}, openSurfaces); + open[id] = true; + openSurfaces = open; + return true; + } + function hide(id) { + if (ecosystem(id) === "noctalia") + return !!noctaliaApis[id] && noctaliaApis[id].closePanel(null); + const w = widgetFor(id); + if (w && typeof w.close === "function") { + w.close(); + return true; + } + const item = surfaces[id]; + if (item && typeof item.close === "function") { + item.close(); + return true; + } + return false; + } + function toggle(id, payload) { + if (ecosystem(id) === "noctalia") { + const napi = noctaliaApi(id); + return !!napi && kinds(id).includes("panel") && napi.togglePanel(ShellState.activeScreen(), napi.barWidget); + } + const w = widgetFor(id); + if (w && typeof w.toggle === "function") { + w.toggle(); + return true; + } + const item = surfaces[id]; + if (item && item.opened === true) + return hide(id); + return summon(id, payload); + } + + // One plugin popout at a time; glassMxrph's own panels close too. + function requestPopout(owner) { + if (activePopout && activePopout !== owner && typeof activePopout.close === "function") + activePopout.close(); + activePopout = owner; + ShellState.controlCenterOpen = false; + ShellState.dashboardOpen = false; + PopoutState.close(); + TrayService.close(); + } + function releasePopout(owner) { + if (activePopout === owner) + activePopout = null; + } + function closePopout() { + if (activePopout && typeof activePopout.close === "function") + activePopout.close(); + activePopout = null; + } + + // Scoped shell object for one plugin: it can reach its own service and + // panels and update its own widget settings, nothing else. + // Cached without change notifications: shellFor() is called from bindings. + readonly property var shellApis: ({}) + function shellFor(id) { + if (shellApis[id]) + return shellApis[id]; + const owns = target => target === id || String(target).startsWith(id + ".") || String(target).startsWith(id + ":"); + const api = shellApiComponent.createObject(root, { + pluginId: id, + _serviceLookup: target => owns(target) ? (root.services[id] || null) : null, + _firstPartyServiceLookup: target => null, + _summon: (target, payload) => owns(target) ? root.summon(id, payload) : false, + _hide: target => owns(target) ? root.hide(id) : false, + _toggle: (target, payload) => owns(target) ? root.toggle(id, payload) : false, + _isOpen: target => { + const w = root.widgetFor(id); + return owns(target) && !!w && w.opened === true; + }, + _updateSettings: (target, settings) => owns(target) ? root.saveWidgetSettings(id, settings) : false + }); + shellApis[id] = api; + return api; + } + function saveWidgetSettings(id, settings) { + const moduleId = "plugin:" + id; + const apply = list => list.map(m => m.id === moduleId ? Object.assign({}, m, { + options: Object.assign({}, m.options || {}, settings || {}) + }) : m); + return ConfigService.setValue("bar.modules", apply(ConfigService.data.bar.modules)); + } + Component { + id: shellApiComponent + OmarchyHost.PluginShellApi {} + } + + // Noctalia v4: one pluginApi per plugin (cached without notifications). + readonly property var noctaliaApis: ({}) + function noctaliaApi(id) { + if (noctaliaApis[id]) + return noctaliaApis[id]; + const p = plugin(id); + if (!p || p.ecosystem !== "noctalia") + return null; + const napi = noctaliaApiComponent.createObject(root, { + pluginId: id, + pluginDir: p.dir, + manifest: p.manifest, + _currentScreen: () => ShellState.activeScreen(), + _requestPanel: owner => root.requestPopout(owner) + }); + noctaliaApis[id] = napi; + return napi; + } + Component { + id: noctaliaApiComponent + NoctaliaHost.PluginApi {} + } + + Process { + id: job + stdout: StdioCollector { + onStreamFinished: { + try { + const result = JSON.parse(text); + root.lastResult = result; + root.plugins = result.plugins || []; + root.error = result.ok ? "" : (result.error || "Plugin command failed"); + root.loaded = true; + } catch (e) { + root.error = String(e); + } + } + } + onRunningChanged: if (!running && root.queued.length) { + const next = root.queued[0]; + root.queued = root.queued.slice(1); + root.call(next); + } + } + Component.onCompleted: refresh() + + // Marketplace (plugins.omarchy.org) browsing; see helpers/marketplace.py. + property var market: ({ + items: [], + total: 0, + categories: [] + }) + property string marketError: "" + property string marketQuery: "" + property string marketCategory: "all" + property string marketSort: "popular" + property bool marketVerifiedOnly: false + // "omarchy" (plugins.omarchy.org) or "noctalia" (noctalia-plugins registry). + property string marketSource: "omarchy" + onMarketSourceChanged: { + marketCategory = "all"; + browse(false); + } + property bool marketAppend: false + readonly property bool marketBusy: browseJob.running + readonly property int marketPage: 30 + function browse(more) { + marketAppend = !!more; + const offset = more ? market.items.length : 0; + browseJob.command = ["python3", Quickshell.shellPath("helpers/marketplace.py"), "search", marketQuery, marketCategory, marketSort, String(offset), String(marketPage), marketVerifiedOnly ? "true" : "false", marketSource]; + browseJob.running = true; + } + // Installs the listing's plugin at the commit the marketplace validated. + function installListing(item) { + install(item.repo, item.commit, item.id); + } + function isInstalled(id) { + return !!plugin(id); + } + Timer { + id: browseDebounce + interval: 220 + onTriggered: root.browse(false) + } + onMarketQueryChanged: browseDebounce.restart() + onMarketCategoryChanged: browse(false) + onMarketSortChanged: browse(false) + onMarketVerifiedOnlyChanged: browse(false) + Process { + id: browseJob + stdout: StdioCollector { + onStreamFinished: { + try { + const result = JSON.parse(text); + root.marketError = result.ok ? (result.warning || "") : (result.error || "Marketplace unavailable"); + if (!result.ok) + return; + root.market = { + items: root.marketAppend ? root.market.items.concat(result.items) : result.items, + total: result.total, + categories: result.categories, + fetchedAt: result.fetchedAt + }; + } catch (e) { + root.marketError = String(e); + } + } + } + } + Connections { + target: ShellState + function onControlCenterOpenChanged() { + if (ShellState.controlCenterOpen) + root.closePopout(); + } + function onDashboardOpenChanged() { + if (ShellState.dashboardOpen) + root.closePopout(); + } + function onLauncherOpenChanged() { + if (ShellState.launcherOpen) + root.closePopout(); + } + function onSettingsOpenChanged() { + if (ShellState.settingsOpen) + root.closePopout(); + } + } + IpcHandler { + target: "plugins" + function list(): string { + return JSON.stringify(root.plugins.map(p => ({ + id: p.id, + name: p.manifest.name || p.id, + kinds: p.manifest.kinds || [], + enabled: root.isEnabled(p.id), + problems: p.problems + }))); + } + function install(source: string): void { + root.install(source, ""); + } + function remove(id: string): void { + root.remove(id); + } + function enable(id: string): void { + root.setEnabled(id, true); + } + function disable(id: string): void { + root.setEnabled(id, false); + } + function summon(id: string, payload: string): bool { + return root.summon(id, payload); + } + function toggle(id: string, payload: string): bool { + return root.toggle(id, payload); + } + // Marketplace search, as in the Browse tab. + function browse(query: string): void { + root.marketQuery = query; + } + function market(): string { + return JSON.stringify({ + busy: root.marketBusy, + total: root.market.total, + error: root.marketError, + items: root.market.items.slice(0, 10).map(i => ({ + id: i.id, + name: i.name, + kind: i.kind, + support: i.support, + verified: i.verified + })) + }); + } + function status(): string { + return JSON.stringify({ + loaded: root.loaded, + busy: root.busy, + error: root.error, + enabled: root.enabledIds, + barModules: root.barModules, + activePopout: root.activePopout ? (root.activePopout.moduleName || "?") : "" + }); + } + } +} diff --git a/quickshell/services/PowerService.qml b/quickshell/services/PowerService.qml new file mode 100644 index 0000000..69415a0 --- /dev/null +++ b/quickshell/services/PowerService.qml @@ -0,0 +1,50 @@ +pragma Singleton +import QtQuick +import Quickshell +import "../core" + +Singleton { + id: root + property string pending: "" + function request(action) { + // The built-in lock screen needs no external locker. + if (action === "lock" && ConfigService.ready && ConfigService.data.lock.enabled) { + ShellState.requestLock(); + return true; + } + if (!SystemService.state.power || !SystemService.state.power[action] || SystemService.acting) + return false; + if (["logout", "reboot", "shutdown"].includes(action)) { + pending = action; + return true; + } + if (!["lock", "suspend"].includes(action)) + return false; + + return SystemService.action("power", action, false); + } + function confirm() { + if (!pending || SystemService.acting) + return false; + const action = pending; + pending = ""; + return SystemService.action("power", action, true); + } + function cancel() { + pending = ""; + } + Connections { + target: ShellState + function onControlCenterOpenChanged() { + if (!ShellState.controlCenterOpen) + root.cancel(); + } + function onSettingsPageChanged() { + root.cancel(); + } + function onSettingsOpenChanged() { + if (!ShellState.settingsOpen) + root.cancel(); + } + } +} diff --git a/quickshell/services/ProviderJob.qml b/quickshell/services/ProviderJob.qml new file mode 100644 index 0000000..34a5e9a --- /dev/null +++ b/quickshell/services/ProviderJob.qml @@ -0,0 +1,38 @@ +import QtQuick +import Quickshell +import Quickshell.Io + +Process { + id: root + property string helper: "helpers/desktop.py" + property var request: ({}) + signal finished(var request, var result) + function start(value) { + if (running) + return false; + request = JSON.parse(JSON.stringify(value)); + command = ["python3", Quickshell.shellPath(helper), JSON.stringify(request)]; + running = true; + return true; + } + stdout: StdioCollector { + id: output + } + stderr: StdioCollector { + id: errors + } + // Quickshell 0.3.1 omits QProcess::ExitStatus from its type metadata. + // qmllint disable signal-handler-parameters + onExited: code => { + let result; + try { + result = JSON.parse(output.text); + } catch (error) { + result = { + ok: false, + error: errors.text || "Provider did not return valid JSON (exit " + code + ")" + }; + } + root.finished(root.request, result); + } +} diff --git a/quickshell/services/SettingsLogic.js b/quickshell/services/SettingsLogic.js new file mode 100644 index 0000000..3659767 --- /dev/null +++ b/quickshell/services/SettingsLogic.js @@ -0,0 +1,21 @@ +function editModule(modules,id,key,value) {return modules.map(m=>m.id===id?Object.assign({},m,{[key]:value}):m);} +function moveModule(modules,id,direction) { + const result=modules.slice(),item=result.find(m=>m.id===id); + if(!item)return result; + const lane=result.filter(m=>m.position===item.position),from=lane.findIndex(m=>m.id===id),target=lane[from+direction]; + if(!target)return result; + const a=result.findIndex(m=>m.id===id),b=result.findIndex(m=>m.id===target.id); + [result[a],result[b]]=[result[b],result[a]];return result; +} +function removeModule(modules,id) {return modules.filter(m=>m.id!==id);} +// Move one stable module ID into a lane before another ID, or append to that lane. +function dropModule(modules,id,position,before) { + if (!["left","center","right"].includes(position) || before === id) return modules.slice(); + const item=modules.find(m=>m.id===id); + if(!item)return modules.slice(); + const result=modules.filter(m=>m.id!==id); + let index=result.findIndex(m=>m.id===before && m.position===position); + if(index<0) {index=result.length;for(let i=result.length-1;i>=0;i--)if(result[i].position===position){index=i+1;break;}} + result.splice(index,0,Object.assign({},item,{position:position})); + return result; +} diff --git a/quickshell/services/SystemService.qml b/quickshell/services/SystemService.qml new file mode 100644 index 0000000..0922961 --- /dev/null +++ b/quickshell/services/SystemService.qml @@ -0,0 +1,87 @@ +pragma Singleton +import QtQuick +import Quickshell +import "../core" + +Singleton { + id: root + property string helper: "helpers/system.py" + property var state: ({}) + property string error: "" + readonly property bool busy: job.running + // A user action is in flight. Controls lock on this, not on busy: locking + // them for every background status poll flickered them every five seconds. + readonly property bool acting: (job.running && job.request.op === "action") || queued !== null + property var queued: null + readonly property var features: { + if (!ConfigService.ready) + return []; + if (ShellState.controlCenterOpen) + return ConfigService.data.controlCenter.modules.filter(m => m.enabled && ["brightness", "nightLight", "dnd", "profiles", "power"].includes(m.id)).map(m => m.id); + if (ShellState.dashboardOpen) + return ["power"]; + if (!ShellState.settingsOpen) + return []; + if (ShellState.settingsPage === "displays") + return ["brightness", "nightLight"]; + if (ShellState.settingsPage === "notifications") + return ["dnd"]; + if (ShellState.settingsPage === "power") + return ["power", "profiles"]; + return []; + } + readonly property bool observed: features.length > 0 + onFeaturesChanged: if (observed) + refresh() + onObservedChanged: if (observed) + refresh() + function refresh() { + if (ConfigService.ready && !busy) + job.start({ + op: "status", + features: features, + options: ConfigService.data.system + }); + } + function action(kind, value, confirmed) { + if (acting || !ConfigService.ready) + return false; + error = ""; + const request = { + op: "action", + action: kind, + value: value, + confirmed: confirmed === true, + options: ConfigService.data.system + }; + // A status poll is running: run the action as soon as it finishes. + if (busy) { + queued = request; + return true; + } + return job.start(request); + } + ProviderJob { + id: job + helper: root.helper + onFinished: (request, result) => { + if (result.ok) { + root.state = Object.assign({}, root.state, result.state); + if (request.op === "action") + root.error = ""; + } else + root.error = result.error || "System request failed"; + if (root.queued) { + const next = root.queued; + root.queued = null; + job.start(next); + } + } + } + Timer { + interval: 5000 + repeat: true + running: root.observed + onTriggered: root.refresh() + } +} diff --git a/quickshell/services/TrayService.qml b/quickshell/services/TrayService.qml new file mode 100644 index 0000000..5340058 --- /dev/null +++ b/quickshell/services/TrayService.qml @@ -0,0 +1,135 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Io +import Quickshell.Services.SystemTray +import "../core" + +Singleton { + id: root + readonly property var items: SystemTray.items.values + readonly property var options: ConfigService.ready ? ConfigService.data.tray : ({ + enabled: false, + hoverMenus: true, + hoverDelay: 400, + iconSize: 20, + spacing: 8, + background: "pill" + }) + property var currentItem: null + property var anchorItem: null + property bool opened: false + property bool closeOnLeave: false + property var windows: [] + // Bar windows, for test drivers and hover hand-off. + property var barWindows: [] + property var hoveredWindows: [] + property var icons: [] + // Only click-opened menus grab keyboard focus; hover menus never steal it. + readonly property bool grabbing: opened && !closeOnLeave + readonly property bool pointerInside: (anchorItem && anchorItem.pointerInside) || hoveredWindows.length > 0 + onPointerInsideChanged: updateDismissal() + onItemsChanged: if (currentItem && !items.includes(currentItem)) + close() + onCurrentItemChanged: if (!currentItem) + close() + onOptionsChanged: if (!options.enabled) + close() + function registerIcon(icon) { + icons = icons.concat([icon]); + } + function unregisterIcon(icon) { + if (anchorItem === icon) + close(); + icons = icons.filter(i => i !== icon); + } + function registerBar(window) { + barWindows = barWindows.concat([window]); + } + function unregisterBar(window) { + barWindows = barWindows.filter(w => w !== window); + } + function registerWindow(window) { + windows = windows.concat([window]); + } + function unregisterWindow(window) { + windows = windows.filter(w => w !== window); + setHovered(window, false); + } + function setHovered(window, inside) { + hoveredWindows = hoveredWindows.filter(w => w !== window); + if (inside) + hoveredWindows = hoveredWindows.concat([window]); + } + function updateDismissal() { + if (opened && closeOnLeave && !pointerInside) + leaveTimer.restart(); + else + leaveTimer.stop(); + } + function open(item, icon, hover) { + if (!options.enabled || !item || !item.hasMenu || !icon) + return false; + ShellState.controlCenterOpen = false; + ShellState.launcherOpen = false; + ShellState.settingsOpen = false; + currentItem = item; + anchorItem = icon; + closeOnLeave = hover; + opened = true; + updateDismissal(); + return true; + } + function close() { + opened = false; + leaveTimer.stop(); + } + function openById(id, monitor) { + const icon = icons.find(i => i.trayItem && i.trayItem.id === id && (!monitor || i.barScreen.name === monitor)); + return icon ? open(icon.trayItem, icon, false) : false; + } + Connections { + target: ShellState + function onControlCenterOpenChanged() { + if (ShellState.controlCenterOpen) + root.close(); + } + function onSettingsOpenChanged() { + if (ShellState.settingsOpen) + root.close(); + } + function onLauncherOpenChanged() { + if (ShellState.launcherOpen) + root.close(); + } + } + Timer { + id: leaveTimer + interval: 300 + onTriggered: if (!root.pointerInside) + root.close() + } + IpcHandler { + target: "tray" + function open(id: string, monitor: string): bool { + return root.openById(id, monitor); + } + function close(): void { + root.close(); + } + function status(): string { + return JSON.stringify({ + opened: root.opened, + grabbing: root.grabbing, + currentId: root.currentItem ? root.currentItem.id : "", + items: root.items.map(i => ({ + id: i.id, + title: i.title, + hasMenu: i.hasMenu, + onlyMenu: i.onlyMenu + })), + menus: root.windows.filter(w => w.visible).map(w => w.snapshot()) + }); + } + } +} diff --git a/quickshell/services/WallpaperService.qml b/quickshell/services/WallpaperService.qml new file mode 100644 index 0000000..ba743d2 --- /dev/null +++ b/quickshell/services/WallpaperService.qml @@ -0,0 +1,159 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Io +import "../core" + +Singleton { + id: root + property var images: [] + property var observed: ({}) + property string backend: "none" + property string error: "" + property string notice: "" + // "all" applies to every connected output in turn; "primary" or an output name targets one. + property string selectedMonitor: "all" + property var queue: [] + readonly property var output: ScreenService.resolve(selectedMonitor) + readonly property string monitor: output ? output.name : "" + readonly property var paletteOutput: ConfigService.ready ? ScreenService.resolve(ConfigService.data.wallpaper.paletteMonitor) : null + readonly property string palettePath: paletteOutput ? (observed[paletteOutput.name] || (ConfigService.ready ? ConfigService.data.wallpaper.byMonitor[paletteOutput.name] : "") || "") : "" + readonly property string currentPath: observed[monitor] || (ConfigService.ready ? ConfigService.data.wallpaper.byMonitor[monitor] : "") || "" + property var nativePending: null + readonly property bool busy: applyJob.running || nativePending !== null || queue.length > 0 + readonly property bool scanning: scanJob.running + function request(action, target) { + const name = target || monitor; + return { + action: action, + monitor: name, + backend: ConfigService.data.wallpaper.backend, + command: ConfigService.data.wallpaper.command, + current: observed[name] || ConfigService.data.wallpaper.byMonitor[name] || "" + }; + } + function refresh() { + if (ConfigService.ready && monitor) + probeJob.start(request("provider")); + } + function scan() { + if (ConfigService.ready) + scanJob.start({ + action: "scan", + directories: ConfigService.data.wallpaper.directories + }); + } + function changed(output, path) { + const next = Object.assign({}, observed); + next[output] = path; + observed = next; + } + function apply(path) { + const outputs = selectedMonitor === "all" ? Quickshell.screens.map(s => s.name) : [monitor]; + if (!ConfigService.ready || !ConfigService.writable || !outputs.length || !outputs[0] || busy) + return false; + error = ""; + queue = outputs.slice(1).map(name => ({ + path: path, + monitor: name + })); + const req = request("apply", outputs[0]); + req.path = path; + return applyJob.start(req); + } + // Starts the next queued output once the previous one has fully applied. + function applyNext() { + if (!queue.length) + return; + const next = queue[0]; + const req = request("apply", next.monitor); + req.path = next.path; + queue = queue.slice(1); + applyJob.start(req); + } + onMonitorChanged: refresh() + ProviderJob { + id: probeJob + onFinished: (request, result) => { + if (!result.ok) { + root.error = result.error; + return; + } + root.backend = result.backend; + root.notice = result.notice || ""; + if (result.current) + root.changed(request.monitor, ConfigService.data.wallpaper.providerPaths[request.monitor] === result.current ? (ConfigService.data.wallpaper.byMonitor[request.monitor] || result.current) : result.current); + } + } + ProviderJob { + id: scanJob + onFinished: (request, result) => { + if (result.ok) { + root.images = result.images; + root.notice = (result.notice || "") + (result.limited ? " Showing the first 1,000 images." : ""); + } else + root.error = result.error; + } + } + ProviderJob { + id: applyJob + onFinished: (request, result) => { + if (!result.ok) { + root.error = result.error; + root.queue = []; + return; + } + if(result.backend === "native") root.nativePending = {request:request,result:result}; + else root.finishApply(request,result); + } + } + function finishApply(request,result) { + const next = Object.assign({}, ConfigService.data.wallpaper.byMonitor); + next[request.monitor] = result.path; + ConfigService.setValue("wallpaper.byMonitor", next); + const providerPaths = Object.assign({}, ConfigService.data.wallpaper.providerPaths); + providerPaths[request.monitor] = result.providerPath; + ConfigService.setValue("wallpaper.providerPaths", providerPaths); + root.backend = result.backend; + root.changed(request.monitor, result.path); + root.error = ""; + ConfigService.setValue("wallpaper.history",[result.path].concat(ConfigService.data.wallpaper.history.filter(p=>p!==result.path)).slice(0,50)); + Qt.callLater(root.applyNext); + } + Image { + visible:false + asynchronous:true + sourceSize:Qt.size(32,32) + source:root.nativePending ? root.nativePending.result.url : "" + onStatusChanged: { + if(!root.nativePending)return; + if(status===Image.Ready) {const pending=root.nativePending;root.nativePending=null;root.finishApply(pending.request,pending.result);} + else if(status===Image.Error) {root.error="Could not decode this wallpaper";root.nativePending=null;root.queue=[];} + } + } + IpcHandler { + target: "wallpaper" + function picker(): void {ShellState.openWallpaperPicker();} + function changed(monitor: string, path: string): void { + root.changed(monitor, path); + } + function refresh(): void { + root.refresh(); + root.scan(); + } + function apply(path: string): bool { + return root.apply(path); + } + function status(): string { + return JSON.stringify({ + backend: root.backend, + current: root.currentPath, + palettePath: root.palettePath, + busy: root.busy, + images: root.images.length, + error: root.error, + notice: root.notice + }); + } + } +} diff --git a/quickshell/services/WidgetLogic.js b/quickshell/services/WidgetLogic.js new file mode 100644 index 0000000..363513b --- /dev/null +++ b/quickshell/services/WidgetLogic.js @@ -0,0 +1,67 @@ +// Pure helpers for desktop widgets: item edits, move snapping and resizing. +// Rects are {x, y, w, h} in output-local logical pixels. + +function newId(items) { + let id; + do id = "w-" + Date.now().toString(36) + "-" + Math.floor(Math.random() * 1296).toString(36); + while (items.some(i => i.id === id)); + return id; +} +function addItem(items, item) {return items.concat([item]);} +function updateItem(items, id, patch) {return items.map(i => i.id === id ? Object.assign({}, i, patch) : i);} +function removeItem(items, id) {return items.filter(i => i.id !== id);} + +function clampRect(r, bounds) { + const w = Math.min(r.w, bounds.w), h = Math.min(r.h, bounds.h); + return {x: Math.max(0, Math.min(bounds.w - w, r.x)), y: Math.max(0, Math.min(bounds.h - h, r.y)), w: w, h: h}; +} + +// Snap a moved rect to the grid, or to screen edges/centre and other widgets' +// edges/centres within `threshold`. Returns the rect plus guide lines to draw. +function snapMove(r, others, bounds, grid, threshold) { + let x = r.x, y = r.y; + const guides = {x: [], y: []}; + if (grid > 0) { + x = Math.round(x / grid) * grid; + y = Math.round(y / grid) * grid; + } else { + const xs = [0, bounds.w / 2, bounds.w], ys = [0, bounds.h / 2, bounds.h]; + for (const o of others) { + xs.push(o.x, o.x + o.w / 2, o.x + o.w); + ys.push(o.y, o.y + o.h / 2, o.y + o.h); + } + const best = (start, size, lines) => { + let found = null; + for (const line of lines) + for (const offset of [0, size / 2, size]) { + const delta = line - (start + offset); + if (Math.abs(delta) <= threshold && (!found || Math.abs(delta) < Math.abs(found.delta))) + found = {delta: delta, line: line}; + } + return found; + }; + const bx = best(x, r.w, xs), by = best(y, r.h, ys); + if (bx) {x += bx.delta; guides.x.push(bx.line);} + if (by) {y += by.delta; guides.y.push(by.line);} + } + const c = clampRect({x: x, y: y, w: r.w, h: r.h}, bounds); + return {x: c.x, y: c.y, w: c.w, h: c.h, guides: guides}; +} + +// Resize from `start` by a pointer delta on the given edges ({left,right,top,bottom}), +// honouring minimum/maximum sizes, the grid and the output bounds. +function resizeRect(start, dx, dy, edges, limits, bounds, grid) { + const snap = v => grid > 0 ? Math.round(v / grid) * grid : v; + let left = start.x, top = start.y, right = start.x + start.w, bottom = start.y + start.h; + if (edges.left) left = snap(Math.max(0, start.x + dx)); + if (edges.right) right = snap(Math.min(bounds.w, start.x + start.w + dx)); + if (edges.top) top = snap(Math.max(0, start.y + dy)); + if (edges.bottom) bottom = snap(Math.min(bounds.h, start.y + start.h + dy)); + const fit = (a, b, lo, hi, moveA) => { + const size = Math.max(lo, Math.min(hi, b - a)); + return moveA ? [b - size, b] : [a, a + size]; + }; + [left, right] = fit(left, right, limits.minW, limits.maxW, !!edges.left); + [top, bottom] = fit(top, bottom, limits.minH, limits.maxH, !!edges.top); + return clampRect({x: left, y: top, w: right - left, h: bottom - top}, bounds); +} diff --git a/quickshell/services/qmldir b/quickshell/services/qmldir new file mode 100644 index 0000000..c76a5b1 --- /dev/null +++ b/quickshell/services/qmldir @@ -0,0 +1,17 @@ +singleton ConfigService 1.0 ConfigService.qml +singleton TrayService 1.0 TrayService.qml +singleton ApplicationsService 1.0 ApplicationsService.qml +singleton HyprlandService 1.0 HyprlandService.qml +ProviderJob 1.0 ProviderJob.qml +singleton WallpaperService 1.0 WallpaperService.qml +singleton MediaService 1.0 MediaService.qml +singleton CavaService 1.0 CavaService.qml +singleton AudioService 1.0 AudioService.qml +singleton NetworkService 1.0 NetworkService.qml +singleton BluetoothService 1.0 BluetoothService.qml +singleton SystemService 1.0 SystemService.qml +singleton PowerService 1.0 PowerService.qml +singleton MetricsService 1.0 MetricsService.qml +singleton GlassService 1.0 GlassService.qml +singleton EasyEffectsService 1.0 EasyEffectsService.qml +singleton PluginService 1.0 PluginService.qml diff --git a/quickshell/settings/Settings.qml b/quickshell/settings/Settings.qml new file mode 100644 index 0000000..ae6c6eb --- /dev/null +++ b/quickshell/settings/Settings.qml @@ -0,0 +1,862 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import Quickshell +import Quickshell.Wayland +import "../components" +import "../services" +import "../theme" +import "../core" +import "controls" +import "pages" as Pages + +// The layer surface is sized to the panel so compositor glass (HyprGlass) +// shapes its refraction edges to the panel instead of to the whole screen. +// While dragging it temporarily spans the screen, giving a stable pointer frame. +// Runtime selects the concrete layer window. +// qmllint disable uncreatable-type +PanelWindow { + // qmllint enable uncreatable-type + id: root + screen: ScreenService.current(ShellState.targetScreen) + visible: ShellState.settingsOpen || panel.opacity > 0.01 + anchors { + top: true + left: true + bottom: root.dragging + right: root.dragging + } + // Margins is present at runtime but unresolved in 0.3.1 qmltypes. + // qmllint disable unqualified unresolved-type + margins { + left: root.dragging ? 0 : root.panelX + top: root.dragging ? 0 : root.panelY + } + // qmllint enable unqualified unresolved-type + implicitWidth: panel.width + implicitHeight: panel.height + color: Theme.transparent + exclusionMode: ExclusionMode.Ignore + WlrLayershell.namespace: "glassMxrph-settings" + WlrLayershell.layer: WlrLayer.Overlay + WlrLayershell.keyboardFocus: ShellState.settingsOpen ? WlrKeyboardFocus.Exclusive : WlrKeyboardFocus.None + Component.onCompleted: ShellState.settingsWindow = root + Component.onDestruction: ShellState.settingsWindow = null + + readonly property int screenWidth: screen ? screen.width : 1920 + readonly property int screenHeight: screen ? screen.height : 1080 + readonly property bool wide: panel.width >= 780 + + // Placement: centred until the user drags the panel; double-click a header to recentre. + property bool placed: false + property real placedX: 0 + property real placedY: 0 + readonly property real panelX: Math.round(placed ? Math.max(0, Math.min(screenWidth - panel.width, placedX)) : (screenWidth - panel.width) / 2) + readonly property real panelY: Math.round(placed ? Math.max(0, Math.min(screenHeight - panel.height, placedY)) : (screenHeight - panel.height) / 2) + property bool dragging: false + // True once the compositor has actually resized the surface to the screen. + readonly property bool spanning: width > panel.width + 1 + property point dragStart + property point dragOrigin + function screenPoint(item, x, y) { + const p = item.mapToItem(null, x, y); + return spanning ? p : Qt.point(p.x + dragOrigin.x, p.y + dragOrigin.y); + } + function beginDrag(item, x, y) { + dragOrigin = Qt.point(panelX, panelY); + dragStart = screenPoint(item, x, y); + placedX = panelX; + placedY = panelY; + placed = true; + dragging = true; + } + function moveDrag(item, x, y) { + if (!dragging) + return; + const p = screenPoint(item, x, y); + placedX = dragOrigin.x + p.x - dragStart.x; + placedY = dragOrigin.y + p.y - dragStart.y; + } + function endDrag() { + dragging = false; + } + function recenter() { + placed = false; + } + readonly property var currentPage: SettingsRegistry.page(ShellState.settingsPage) || SettingsRegistry.page("about") + readonly property var currentGroup: SettingsRegistry.groups.find(g => g.id === currentPage.group) || null + + // Sidebar entries: group captions followed by their pages. + readonly property int captionHeight: 30 + readonly property int gapHeight: 12 + readonly property int itemHeight: 40 + readonly property int itemSpacing: 2 + readonly property var navEntries: { + const entries = []; + for (const group of SettingsRegistry.groups) { + const pages = SettingsRegistry.pages.filter(p => p.group === group.id); + if (pages.length === 0) + continue; + entries.push({ + kind: group.title ? "caption" : "gap", + title: group.title + }); + for (const p of pages) + entries.push({ + kind: "page", + page: p + }); + } + return entries; + } + function entryHeight(entry) { + return entry.kind === "page" ? itemHeight : entry.kind === "caption" ? captionHeight : gapHeight; + } + function entryY(pageId) { + let y = 0; + for (const entry of navEntries) { + if (entry.kind === "page" && entry.page.id === pageId) + return y; + y += entryHeight(entry) + itemSpacing; + } + return -1; + } + function step(direction) { + const ids = SettingsRegistry.pages.map(p => p.id); + const index = ids.indexOf(ShellState.settingsPage); + ShellState.openSettings(ids[(index + direction + ids.length) % ids.length]); + } + + // Search + property bool searchActive: false + property int searchIndex: 0 + readonly property var searchResults: SettingsRegistry.search(searchField.text) + function openSearch() { + searchActive = true; + searchField.forceActiveFocus(); + } + function closeSearch() { + searchActive = false; + searchField.clear(); + panel.forceActiveFocus(); + } + function chooseResult(result) { + if (!result) + return; + closeSearch(); + ShellState.revealSetting(result.page, result.setting); + } + onSearchResultsChanged: searchIndex = 0 + // Keep the selected sidebar entry in view. + function revealNavEntry() { + const y = entryY(ShellState.settingsPage); + if (y < 0 || nav.height <= 0) + return; + if (y < nav.contentY) + nav.contentY = y; + else if (y + itemHeight > nav.contentY + nav.height) + nav.contentY = Math.min(nav.contentHeight - nav.height, y + itemHeight - nav.height); + } + Connections { + target: ShellState + function onSettingsOpenChanged() { + if (!ShellState.settingsOpen && root.searchActive) + root.closeSearch(); + if (ShellState.settingsOpen) + Qt.callLater(root.revealNavEntry); + } + } + Timer { + // Clear the reveal request once matching rows have flashed. + running: ShellState.settingsHighlight !== "" + interval: 3000 + onTriggered: ShellState.settingsHighlight = "" + } + + // Drag handle for moving the panel; double-click recentres it. + component DragArea: MouseArea { + id: handle + anchors.fill: parent + cursorShape: pressed ? Qt.ClosedHandCursor : Qt.OpenHandCursor + onPressed: mouse => root.beginDrag(handle, mouse.x, mouse.y) + onPositionChanged: mouse => root.moveDrag(handle, mouse.x, mouse.y) + onReleased: root.endDrag() + onCanceled: root.endDrag() + onDoubleClicked: root.recenter() + } + + // Hyprland routes every pointer event to a layer with exclusive keyboard + // focus, so clicks outside the panel arrive here with out-of-bounds + // coordinates. Qt Quick still delivers them to items extending past the + // window, so this catcher (behind the panel) dismisses on outside clicks. + MouseArea { + objectName: "settingsOutside" + x: -20000 + y: -20000 + width: 40000 + height: 40000 + onPressed: ShellState.settingsOpen = false + } + GlassPopup { + id: panel + objectName: "settingsSurface" + opened: ShellState.settingsOpen + x: root.spanning ? root.panelX : 0 + y: root.spanning ? root.panelY : 0 + width: Math.min(1080, root.screenWidth - 40) + height: Math.min(780, root.screenHeight - 40) + focus: ShellState.settingsOpen + onOpenedChanged: if (opened) + forceActiveFocus() + Keys.onEscapePressed: ShellState.settingsOpen = false + Keys.onPressed: event => { + if (event.modifiers & Qt.ControlModifier) { + if (event.key === Qt.Key_F) { + root.openSearch(); + event.accepted = true; + } else if (event.key === Qt.Key_PageDown || event.key === Qt.Key_Tab) { + root.step(1); + event.accepted = true; + } else if (event.key === Qt.Key_PageUp || event.key === Qt.Key_Backtab) { + root.step(-1); + event.accepted = true; + } + } + } + MouseArea { + anchors.fill: parent + } + RowLayout { + anchors.fill: parent + spacing: 0 + + // Sidebar + Rectangle { + id: sidebar + visible: root.wide + Layout.fillHeight: true + Layout.preferredWidth: 252 + topLeftRadius: panel.radius + bottomLeftRadius: panel.radius + color: Qt.alpha(Theme.tint, 0.15) + ColumnLayout { + anchors.fill: parent + anchors.margins: 14 + spacing: 12 + + Item { + Layout.fillWidth: true + Layout.preferredHeight: 36 + DragArea { + objectName: "settingsDragHandle" + } + Text { + anchors.left: parent.left + anchors.leftMargin: 6 + anchors.verticalCenter: parent.verticalCenter + text: "Settings" + color: Theme.text + font.pixelSize: 17 + font.weight: Font.DemiBold + opacity: root.searchActive ? 0 : 1 + scale: root.searchActive ? 0.92 : 1 + visible: opacity > 0.01 + Behavior on opacity { + NumberAnimation { + duration: Theme.duration + easing.type: Easing.OutCubic + } + } + Behavior on scale { + NumberAnimation { + duration: Theme.duration + easing.type: Easing.OutCubic + } + } + } + // The search button widens into the search field. + Item { + id: searchMorph + property real progress: root.searchActive ? 1 : 0 + Behavior on progress { + NumberAnimation { + duration: Theme.duration + easing.type: Easing.OutCubic + } + } + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + width: 36 + (parent.width - 36) * progress + height: 36 + clip: true + GlassTextField { + id: searchField + objectName: "settingsSearch" + anchors.fill: parent + leftPadding: 36 + rightPadding: 36 + placeholderText: "Search settings…" + opacity: searchMorph.progress + enabled: root.searchActive + background: Rectangle { + radius: height / 2 + color: Theme.surfaceVariant + border.color: searchField.activeFocus ? Theme.accent : Theme.border + } + Keys.onEscapePressed: root.closeSearch() + Keys.onDownPressed: root.searchIndex = Math.min(root.searchResults.length - 1, root.searchIndex + 1) + Keys.onUpPressed: root.searchIndex = Math.max(0, root.searchIndex - 1) + Keys.onReturnPressed: root.chooseResult(root.searchResults[root.searchIndex]) + Keys.onEnterPressed: root.chooseResult(root.searchResults[root.searchIndex]) + } + Rectangle { + width: 36 + height: 36 + radius: 18 + color: !root.searchActive && searchButton.containsMouse ? Qt.alpha(Theme.text, 0.1) : Theme.transparent + GlassIcon { + anchors.centerIn: parent + glyph: "󰍉" + fallback: "⌕" + size: 28 + glyphSize: 16 + color: Theme.transparent + border.width: 0 + glyphColor: root.searchActive ? Theme.textSecondary : Theme.text + } + MouseArea { + id: searchButton + objectName: "settingsSearchButton" + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: root.searchActive ? searchField.forceActiveFocus() : root.openSearch() + } + } + Rectangle { + anchors.right: parent.right + width: 36 + height: 36 + radius: 18 + visible: searchMorph.progress > 0.5 + opacity: searchMorph.progress + color: closeSearchArea.containsMouse ? Qt.alpha(Theme.text, 0.1) : Theme.transparent + Text { + anchors.centerIn: parent + text: "×" + color: Theme.textSecondary + font.pixelSize: 18 + } + MouseArea { + id: closeSearchArea + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: root.closeSearch() + } + } + } + } + + Item { + Layout.fillWidth: true + Layout.fillHeight: true + + // Navigation + Flickable { + id: nav + anchors.fill: parent + clip: true + contentHeight: navColumn.implicitHeight + boundsBehavior: Flickable.StopAtBounds + opacity: root.searchActive ? 0 : 1 + visible: opacity > 0.01 + Behavior on opacity { + NumberAnimation { + duration: Theme.duration + } + } + ScrollBar.vertical: ScrollBar { + policy: ScrollBar.AsNeeded + opacity: active ? 1 : 0 + Behavior on opacity { + NumberAnimation { + duration: Theme.duration + } + } + contentItem: Rectangle { + implicitWidth: 3 + radius: 2 + color: Qt.alpha(Theme.text, 0.2) + } + } + Rectangle { + id: activeHighlight + readonly property real target: root.entryY(ShellState.settingsPage) + visible: target >= 0 + width: nav.width + height: root.itemHeight + y: target + radius: Math.max(10, Theme.radius * 0.55) + color: Theme.accent + Behavior on y { + NumberAnimation { + duration: Theme.duration * 1.3 + easing.type: Easing.OutQuint + } + } + } + Column { + id: navColumn + width: nav.width + spacing: root.itemSpacing + Repeater { + model: root.navEntries + Item { + id: entry + required property var modelData + readonly property bool isPage: modelData.kind === "page" + readonly property bool selected: isPage && modelData.page.id === ShellState.settingsPage + width: navColumn.width + height: root.entryHeight(modelData) + Text { + visible: entry.modelData.kind === "caption" + anchors.left: parent.left + anchors.leftMargin: 8 + anchors.bottom: parent.bottom + anchors.bottomMargin: 6 + text: String(entry.modelData.title || "").toUpperCase() + color: Theme.textSecondary + font.pixelSize: 10 + font.weight: Font.DemiBold + font.letterSpacing: 1.2 + } + Rectangle { + visible: entry.isPage + anchors.fill: parent + radius: activeHighlight.radius + color: !entry.selected && itemArea.containsMouse ? Qt.alpha(Theme.text, 0.07) : Theme.transparent + scale: itemArea.pressed ? 0.98 : 1 + Behavior on color { + ColorAnimation { + duration: Theme.duration / 2 + } + } + Behavior on scale { + NumberAnimation { + duration: Theme.duration + easing.type: Easing.OutQuint + } + } + RowLayout { + anchors.fill: parent + // Selected items shift right as the highlight lands. + anchors.leftMargin: 6 + (entry.selected ? 3 * Theme.intensity : 0) + anchors.rightMargin: 10 + spacing: 10 + Behavior on anchors.leftMargin { + NumberAnimation { + duration: Theme.duration * 1.3 + easing.type: Easing.OutQuint + } + } + GlassIcon { + glyph: entry.isPage ? entry.modelData.page.icon : "" + image: entry.isPage ? entry.modelData.page.image || "" : "" + fallback: entry.isPage ? entry.modelData.page.title.charAt(0) : "" + size: 28 + glyphSize: 15 + color: entry.selected ? Qt.alpha(Theme.accentText, 0.14) : Theme.surfaceVariant + glyphColor: entry.selected ? Theme.accentText : Theme.text + } + Text { + text: entry.isPage ? entry.modelData.page.title : "" + color: entry.selected ? Theme.accentText : itemArea.containsMouse ? Theme.text : Qt.alpha(Theme.text, 0.82) + font.pixelSize: 13 + font.weight: entry.selected ? Font.DemiBold : Font.Medium + elide: Text.ElideRight + Layout.fillWidth: true + Behavior on color { + ColorAnimation { + duration: Theme.duration / 2 + } + } + } + } + MouseArea { + id: itemArea + objectName: entry.isPage ? "settingsNav-" + entry.modelData.page.id : "" + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: ShellState.openSettings(entry.modelData.page.id) + } + } + } + } + } + } + + // Search results + ListView { + id: results + objectName: "settingsSearchResults" + anchors.fill: parent + clip: true + spacing: 4 + model: root.searchResults + currentIndex: root.searchIndex + opacity: root.searchActive ? 1 : 0 + visible: opacity > 0.01 + boundsBehavior: Flickable.StopAtBounds + highlightFollowsCurrentItem: false + onCurrentIndexChanged: positionViewAtIndex(currentIndex, ListView.Contain) + Behavior on opacity { + NumberAnimation { + duration: Theme.duration + } + } + delegate: Rectangle { + id: result + required property var modelData + required property int index + readonly property bool selected: index === root.searchIndex + width: results.width + height: 50 + radius: Math.max(10, Theme.radius * 0.55) + color: selected ? Theme.accent : resultArea.containsMouse ? Qt.alpha(Theme.text, 0.08) : Theme.fill + Behavior on color { + ColorAnimation { + duration: Theme.duration / 2 + } + } + RowLayout { + anchors.fill: parent + anchors.leftMargin: 8 + (result.selected ? 3 : 0) + anchors.rightMargin: 10 + spacing: 10 + Behavior on anchors.leftMargin { + NumberAnimation { + duration: Theme.duration + easing.type: Easing.OutQuint + } + } + GlassIcon { + glyph: result.modelData.icon + image: result.modelData.image || "" + fallback: result.modelData.detail.charAt(0) + size: 28 + glyphSize: 14 + color: result.selected ? Qt.alpha(Theme.accentText, 0.14) : Theme.surfaceVariant + glyphColor: result.selected ? Theme.accentText : Theme.text + } + ColumnLayout { + Layout.fillWidth: true + spacing: 1 + Text { + text: result.modelData.title + color: result.selected ? Theme.accentText : Theme.text + font.pixelSize: 12 + font.weight: Font.DemiBold + elide: Text.ElideRight + Layout.fillWidth: true + } + Text { + text: result.modelData.setting ? "in " + result.modelData.detail : result.modelData.detail + color: result.selected ? Qt.alpha(Theme.accentText, 0.75) : Theme.textSecondary + font.pixelSize: 10 + elide: Text.ElideRight + Layout.fillWidth: true + } + } + } + MouseArea { + id: resultArea + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onEntered: root.searchIndex = result.index + onClicked: root.chooseResult(result.modelData) + } + } + Text { + anchors.centerIn: parent + visible: root.searchActive && results.count === 0 + width: parent.width - 20 + horizontalAlignment: Text.AlignHCenter + wrapMode: Text.Wrap + text: searchField.text.trim() ? "No settings match “" + searchField.text.trim() + "”" : "Type to search pages and settings" + color: Theme.textSecondary + font.pixelSize: 12 + } + } + } + + Text { + Layout.fillWidth: true + Layout.leftMargin: 6 + text: root.searchActive ? "↑↓ select · Enter open · Esc back" : "Ctrl+F search · Ctrl+Tab next page" + color: Qt.alpha(Theme.textSecondary, 0.8) + font.pixelSize: 10 + elide: Text.ElideRight + } + } + } + Rectangle { + visible: root.wide + Layout.fillHeight: true + Layout.preferredWidth: 1 + color: Theme.border + } + + // Content + ColumnLayout { + Layout.fillWidth: true + Layout.fillHeight: true + Layout.margins: 24 + Layout.rightMargin: 14 + spacing: 18 + // Page header, also a drag handle for the panel. + Item { + Layout.fillWidth: true + implicitHeight: pageHeader.implicitHeight + DragArea {} + RowLayout { + id: pageHeader + anchors.fill: parent + anchors.rightMargin: 10 + spacing: 14 + GlassIcon { + glyph: root.currentPage.icon + image: root.currentPage.image || "" + fallback: root.currentPage.title.charAt(0) + active: true + size: 46 + glyphSize: 22 + } + ColumnLayout { + Layout.fillWidth: true + spacing: 1 + Text { + visible: !!root.currentGroup && root.currentGroup.title !== "" + text: root.currentGroup ? root.currentGroup.title.toUpperCase() : "" + color: Theme.textSecondary + font.pixelSize: 10 + font.weight: Font.DemiBold + font.letterSpacing: 1.2 + } + Text { + text: root.currentPage.title + color: Theme.text + font.pixelSize: 22 + font.weight: Font.DemiBold + Layout.fillWidth: true + elide: Text.ElideRight + } + Text { + text: root.currentPage.description + color: Theme.textSecondary + font.pixelSize: 12 + Layout.fillWidth: true + elide: Text.ElideRight + } + } + GlassIconButton { + text: "×" + onClicked: ShellState.settingsOpen = false + Accessible.name: "Close settings" + } + } + } + GlassComboBox { + visible: !root.wide + Layout.fillWidth: true + Layout.rightMargin: 10 + model: SettingsRegistry.pages + textRole: "title" + valueRole: "id" + currentIndex: SettingsRegistry.pages.findIndex(p => p.id === ShellState.settingsPage) + onActivated: ShellState.openSettings(currentValue) + } + Item { + id: pageHost + Layout.fillWidth: true + Layout.fillHeight: true + clip: true + property real enter: 1 + NumberAnimation { + id: enterAnimation + target: pageHost + property: "enter" + from: 0 + to: 1 + duration: Theme.duration * 1.4 + easing.type: Easing.OutCubic + } + Connections { + target: ShellState + function onSettingsPageChanged() { + enterAnimation.restart(); + Qt.callLater(root.revealNavEntry); + } + } + Loader { + id: page + objectName: "settingsPageLoader" + width: parent.width + height: parent.height + y: (1 - pageHost.enter) * 14 * Theme.intensity + opacity: pageHost.enter + active: ConfigService.ready && ShellState.settingsOpen + sourceComponent: { + switch (ShellState.settingsPage) { + case "metrics": + return metrics; + case "appearance": + return appearance; + case "wallpaper": + return wallpaper; + case "widgets": + return widgets; + case "bar": + return bar; + case "tray": + return tray; + case "dock": + return dock; + case "media": + return media; + case "osd": + return osd; + case "dashboard": + return dashboardPage; + case "plugins": + return pluginsPage; + case "launcher": + return launcher; + case "controlcenter": + return controlcenter; + case "network": + return network; + case "bluetooth": + return bluetooth; + case "audio": + return audio; + case "displays": + return displays; + case "notifications": + return notifications; + case "power": + return power; + case "lock": + return lockPage; + default: + return about; + } + } + } + } + Text { + visible: ConfigService.error !== "" + text: ConfigService.error + color: Theme.urgent + wrapMode: Text.Wrap + Layout.fillWidth: true + } + } + } + } + Component { + id: metrics + Pages.Metrics {} + } + Component { + id: appearance + Pages.Appearance {} + } + Component { + id: wallpaper + Pages.Wallpaper {} + } + Component { + id: widgets + Pages.Widgets {} + } + Component { + id: bar + Pages.Bar {} + } + Component { + id: tray + SettingsPage { + Pages.Tray { + Layout.fillWidth: true + } + } + } + Component { + id: dock + Pages.Dock {} + } + Component { + id: media + Pages.Media {} + } + Component { + id: osd + Pages.Osd {} + } + Component { + id: launcher + SettingsPage { + Pages.Launcher { + Layout.fillWidth: true + } + } + } + Component { + id: controlcenter + Pages.ControlCenter {} + } + Component { + id: network + Pages.Network {} + } + Component { + id: bluetooth + Pages.Bluetooth {} + } + Component { + id: audio + Pages.Audio {} + } + Component { + id: displays + Pages.Displays {} + } + Component { + id: notifications + Pages.Notifications {} + } + Component { + id: power + Pages.Power {} + } + Component { + id: pluginsPage + Pages.Plugins {} + } + Component { + id: dashboardPage + Pages.Dashboard {} + } + Component { + id: lockPage + Pages.Lock {} + } + Component { + id: about + Pages.About {} + } +} diff --git a/quickshell/settings/controls/BarEditor.qml b/quickshell/settings/controls/BarEditor.qml new file mode 100644 index 0000000..69160e9 --- /dev/null +++ b/quickshell/settings/controls/BarEditor.qml @@ -0,0 +1,256 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Layouts +import QtQuick.Controls +import "../../components" +import "../../core" +import "../../services" +import "../../theme" +import "../../services/SettingsLogic.js" as Logic +Item { + id: root + objectName:"barEditor" + implicitHeight: lanes.implicitHeight + property var laneItems: [] + property string dragging: "" + property string targetLane: "" + property string beforeId: "" + // Screen whose layout is edited; "" or a screen without its own layout edits the shared one. + property string screenName: "" + // Card whose options panel (cog) is open. + property string expandedId: "" + // Option fields for a module: built-in choice lists, or a plugin's + // manifest schema (boolean / integer / number / string / choices). + function fieldsFor(id) { + if (!ModuleRegistry.isPlugin(id)) + return (ModuleRegistry.optionSchemas[id] || []).map(f => Object.assign({type:"choice"}, f)); + return PluginService.schema(String(id).slice(7)).filter(f => f && f.key).map(f => { + const choices = Array.isArray(f.choices) ? f.choices : Array.isArray(f.options) ? f.options.map(o => typeof o === "object" ? o.value : o) : null; + return Object.assign({}, f, {label: f.label || f.key, type: choices ? "choice" : (f.type || "string"), choices: choices || []}); + }); + } + function valueOf(entry, field) { + if (!ModuleRegistry.isPlugin(entry.id)) + return ModuleRegistry.option(entry, field.key); + return PluginService.widgetSettings(String(entry.id).slice(7), entry.options)[field.key]; + } + function setOption(entry, key, value) { + root.save(Logic.editModule(root.modules, entry.id, "options", Object.assign({}, entry.options || {}, {[key]: value}))); + } + readonly property var modules: BarLayout.modulesFor(screenName) + function save(list) { + BarLayout.save(screenName, list); + } + function updateDrag(source,x,y) { + const p=source.mapToItem(root,x,y); + ghost.x=p.x-70;ghost.y=p.y-22; + targetLane="";beforeId=""; + for(let i=0;ilane.width || local.y<0 || local.y>lane.height)continue; + targetLane=lane.modelData; + for(let j=0;jroot.save(Logic.dropModule(root.modules,id,lane,before))); + } + RowLayout { + id: lanes + anchors.left:parent.left;anchors.right:parent.right + spacing:12 + Repeater { + id: laneRepeater + model:["left","center","right"] + GlassPanel { + id: lane + Component.onCompleted: root.laneItems=root.laneItems.concat([lane]) + Component.onDestruction: root.laneItems=root.laneItems.filter(l=>l!==lane) + required property string modelData + property alias cards: cards + objectName:"bar-lane-"+modelData + Layout.fillWidth:true + Layout.minimumWidth:130 + Layout.fillHeight:true + implicitHeight:column.implicitHeight+32 + border.color:root.targetLane===modelData ? Theme.accent : Theme.border + ColumnLayout { + id:column + anchors {left:parent.left;right:parent.right;top:parent.top;margins:10} + spacing:8 + Text {text:lane.modelData.toUpperCase();color:Theme.textSecondary;font.pixelSize:11} + Repeater { + id:cards + model:root.modules.filter(m=>m.position===lane.modelData) + GlassPanel { + id:card + required property var modelData + readonly property var schema:root.fieldsFor(modelData.id) + readonly property var link:ModuleRegistry.settingsLinks[modelData.id] || null + readonly property bool expanded:root.expandedId===modelData.id && schema.length>0 + Layout.fillWidth:true + implicitHeight:52+(expanded ? optionsColumn.implicitHeight+4 : 0) + Behavior on implicitHeight {NumberAnimation {duration:Theme.duration;easing.type:Easing.OutCubic}} + clip:true + radius:12 + HoverHandler {id:cardHover} + opacity:root.dragging===modelData.id ? 0.35 : 1 + Rectangle {anchors.top:parent.top;width:parent.width;height:3;radius:2;color:Theme.accent;visible:root.targetLane===lane.modelData && root.beforeId===card.modelData.id} + RowLayout { + anchors {left:parent.left;right:parent.right;top:parent.top;margins:7} + height:38;spacing:5 + Item { + Layout.preferredWidth:24;Layout.fillHeight:true + activeFocusOnTab:true + Accessible.name:"Move "+card.modelData.id + Accessible.role:Accessible.Button + Text {anchors.centerIn:parent;text:"⠿";color:parent.activeFocus ? Theme.accent : Theme.textSecondary;font.pixelSize:24} + MouseArea { + id:grip + objectName:"bar-drag-"+card.modelData.id + anchors.fill:parent + preventStealing:true + cursorShape:pressed ? Qt.ClosedHandCursor : Qt.OpenHandCursor + property point start + onPressed:event=>{start=Qt.point(event.x,event.y);parent.forceActiveFocus();} + onPositionChanged:event=>{ + if(!pressed)return; + if(!root.dragging && Math.hypot(event.x-start.x,event.y-start.y)<8)return; + root.dragging=card.modelData.id;root.updateDrag(grip,event.x,event.y); + } + onReleased:root.finish() + onCanceled:{root.dragging="";root.targetLane="";} + } + Keys.onPressed:event=>{ + if(event.key===Qt.Key_Escape) {root.dragging="";root.targetLane="";event.accepted=true;} + else if(event.modifiers & Qt.ControlModifier && [Qt.Key_Up,Qt.Key_Down].includes(event.key)) { + root.save(Logic.moveModule(root.modules,card.modelData.id,event.key===Qt.Key_Up?-1:1));event.accepted=true; + } else if(event.modifiers & Qt.AltModifier && [Qt.Key_Left,Qt.Key_Right].includes(event.key)) { + const index=["left","center","right"].indexOf(lane.modelData)+(event.key===Qt.Key_Left?-1:1); + if(index>=0 && index<3)root.save(Logic.dropModule(root.modules,card.modelData.id,["left","center","right"][index],""));event.accepted=true; + } + } + } + Text {text:ModuleRegistry.title(card.modelData.id);color:Theme.text;Layout.fillWidth:true;elide:Text.ElideRight;font.pixelSize:12} + // Cog: module options inline, or the page that holds them. + Rectangle { + objectName:"bar-options-"+card.modelData.id + visible:card.schema.length>0 || !!card.link + implicitWidth:26;implicitHeight:26;radius:13 + color:card.expanded ? Qt.alpha(Theme.accent,0.3) : cogArea.containsMouse ? Theme.hover : Qt.alpha(Theme.text,0.06) + Accessible.name:"Options for "+card.modelData.id + Accessible.role:Accessible.Button + Text {anchors.centerIn:parent;text:Icons.available ? "󰒓" : "⚙";font.family:Icons.available ? Icons.family : "";color:card.expanded || cogArea.containsMouse ? Theme.text : Theme.textSecondary;font.pixelSize:13} + MouseArea { + id:cogArea + anchors.fill:parent + hoverEnabled:true + cursorShape:Qt.PointingHandCursor + onClicked:{ + if(card.schema.length>0)root.expandedId=card.expanded ? "" : card.modelData.id; + else if(card.link)ShellState.revealSetting(card.link.page,card.link.setting); + } + } + } + GlassToggle {objectName:"bar-enable-"+card.modelData.id;checked:card.modelData.enabled;onToggled:root.save(Logic.editModule(root.modules,card.modelData.id,"enabled",checked))} + // Removed modules return to the "+" list below the lanes. + Rectangle { + objectName:"bar-remove-"+card.modelData.id + // Shown on hover so narrow lanes keep room for the name. + visible:cardHover.hovered || card.activeFocus + implicitWidth:26;implicitHeight:26;radius:13 + color:removeArea.containsMouse ? Qt.alpha(Theme.urgent,0.25) : Qt.alpha(Theme.text,0.06) + Accessible.name:"Remove "+card.modelData.id + Accessible.role:Accessible.Button + Text {anchors.centerIn:parent;text:"×";color:removeArea.containsMouse ? Theme.text : Theme.textSecondary;font.pixelSize:16} + MouseArea { + id:removeArea + anchors.fill:parent + hoverEnabled:true + cursorShape:Qt.PointingHandCursor + onClicked:root.save(Logic.removeModule(root.modules,card.modelData.id)) + } + } + } + ColumnLayout { + id:optionsColumn + visible:card.expanded + anchors {left:parent.left;right:parent.right;top:parent.top;topMargin:50;leftMargin:12;rightMargin:10} + spacing:6 + Repeater { + model:card.schema + RowLayout { + id:optionRow + required property var modelData + readonly property var value:root.valueOf(card.modelData,modelData) + Layout.fillWidth:true + spacing:8 + Text {text:optionRow.modelData.label;color:Theme.textSecondary;font.pixelSize:11;Layout.fillWidth:true;elide:Text.ElideRight + HoverHandler {id:labelHover} + ToolTip.visible:labelHover.hovered && !!optionRow.modelData.description + ToolTip.text:optionRow.modelData.description || "" + ToolTip.delay:600} + GlassComboBox { + objectName:"bar-option-"+card.modelData.id+"-"+optionRow.modelData.key + visible:optionRow.modelData.type==="choice" + Layout.preferredWidth:110 + implicitHeight:30 + model:optionRow.modelData.choices.map(c=>({text:String(c).charAt(0).toUpperCase()+String(c).slice(1),value:c})) + textRole:"text" + valueRole:"value" + currentIndex:optionRow.modelData.choices.indexOf(optionRow.value) + onActivated:root.setOption(card.modelData,optionRow.modelData.key,currentValue) + } + GlassToggle { + visible:optionRow.modelData.type==="boolean" + checked:optionRow.value===true + onToggled:root.setOption(card.modelData,optionRow.modelData.key,checked) + } + Text { + visible:optionRow.modelData.type==="integer" || optionRow.modelData.type==="number" + text:optionRow.value===undefined ? "" : String(optionRow.value) + color:Theme.text;font.pixelSize:11 + Layout.preferredWidth:26;horizontalAlignment:Text.AlignRight + } + GlassSlider { + visible:optionRow.modelData.type==="integer" || optionRow.modelData.type==="number" + Layout.preferredWidth:90 + implicitHeight:26 + from:Number(optionRow.modelData.min !== undefined ? optionRow.modelData.min : 0) + to:Number(optionRow.modelData.max !== undefined ? optionRow.modelData.max : 100) + stepSize:Number(optionRow.modelData.step || (optionRow.modelData.type==="integer" ? 1 : 0.1)) + value:Number(optionRow.value || 0) + onMoved:root.setOption(card.modelData,optionRow.modelData.key,optionRow.modelData.type==="integer" ? Math.round(value) : value) + } + GlassTextField { + visible:optionRow.modelData.type==="string" + Layout.preferredWidth:110 + implicitHeight:30 + text:optionRow.value===undefined ? "" : String(optionRow.value) + onEditingFinished:root.setOption(card.modelData,optionRow.modelData.key,text) + } + } + } + } + } + } + Rectangle {Layout.fillWidth:true;implicitHeight:3;radius:2;color:root.targetLane===lane.modelData && !root.beforeId ? Theme.accent : Theme.transparent} + Text {text:cards.count ? "Drop to append" : "Drop a module here";color:Theme.textSecondary;font.pixelSize:11;Layout.fillWidth:true;wrapMode:Text.Wrap} + } + } + } + } + GlassPill { + id:ghost + z:100 + visible:!!root.dragging + width:140;height:44 + color:Theme.surfaceVariant;border.color:Theme.accent + Text {anchors.centerIn:parent;text:root.dragging;color:Theme.text} + } +} diff --git a/quickshell/settings/controls/CommandPreference.qml b/quickshell/settings/controls/CommandPreference.qml new file mode 100644 index 0000000..efa4ee6 --- /dev/null +++ b/quickshell/settings/controls/CommandPreference.qml @@ -0,0 +1,41 @@ +import QtQuick +import QtQuick.Layouts +import "../../components" +import "../../services" +import "../../theme" + +ColumnLayout { + id: root + property string label + property string setting + property string error: "" + Layout.fillWidth: true + Text { + text: root.label + color: Theme.textSecondary + Layout.fillWidth: true + wrapMode: Text.Wrap + } + GlassTextField { + Layout.fillWidth: true + text: JSON.stringify(ConfigService.value(root.setting)) + onEditingFinished: { + try { + if (ConfigService.setValue(root.setting, JSON.parse(text))) { + root.error = ""; + SystemService.refresh(); + } else + root.error = ConfigService.error; + } catch (e) { + root.error = "Enter a JSON array of command arguments"; + } + } + } + Text { + visible: !!root.error + text: root.error + color: Theme.urgent + wrapMode: Text.Wrap + Layout.fillWidth: true + } +} diff --git a/quickshell/settings/controls/GlassSettings.qml b/quickshell/settings/controls/GlassSettings.qml new file mode 100644 index 0000000..968cc68 --- /dev/null +++ b/quickshell/settings/controls/GlassSettings.qml @@ -0,0 +1,30 @@ +import QtQuick +import QtQuick.Layouts +import "../../components" +import "../../services" +ColumnLayout { + id:root + spacing:2 + SettingNote {text:GlassService.state.available ? "Global glass controls apply to the shell and other translucent applications. Explicit app/preset rules keep priority. Changes apply when you press Apply at the top of this page." : "HyprGlass is not available. Install a version matching your compositor to use these controls."} + SettingRow { + title:"Liquid glass preset" + description:"Ghostty-like refraction with lighter shell surfaces" + icon:"󰂵" + GlassButton { + objectName:"glassMatchGhostty" + text:"Match Ghostty’s liquid glass" + onClicked:{ + const values={blur_strength:0.45,blur_iterations:2,refraction_strength:3,chromatic_aberration:0.45,fresnel_strength:0.5,specular_strength:0.8,edge_thickness:0.065,lens_distortion:0.25,brightness:0.95,contrast:1,saturation:1,vibrancy:0.15,adaptive_dim:0.2}; + ConfigService.setValue("hyprglass.values",values); + ConfigService.setValue("appearance.glassOpacity",0.3);ConfigService.setValue("appearance.panelOpacity",0.3); + } + } + } + PreferenceToggle {label:"Enable global glass";setting:"hyprglass.effectEnabled"} + PreferenceToggle {label:"Glass on shell/layers";setting:"hyprglass.layers"} + Repeater { + model:[{key:"blur_strength",label:"Blur",max:5},{key:"blur_iterations",label:"Blur passes",min:1,max:5,step:1},{key:"refraction_strength",label:"Refraction",max:8},{key:"chromatic_aberration",label:"Spectral highlights",max:1},{key:"fresnel_strength",label:"Edge glow",max:1},{key:"specular_strength",label:"Specular highlights",max:1},{key:"edge_thickness",label:"Rim thickness",max:0.15,step:0.005},{key:"lens_distortion",label:"Lens distortion",max:1},{key:"brightness",label:"Brightness",min:0.2,max:2},{key:"contrast",label:"Contrast",min:0.2,max:2},{key:"saturation",label:"Saturation",max:2},{key:"vibrancy",label:"Vibrancy",max:1},{key:"adaptive_dim",label:"Adaptive dimming",max:1}] + PreferenceSlider {required property var modelData;label:modelData.label;setting:"hyprglass.values."+modelData.key;from:modelData.min || 0;to:modelData.max;step:modelData.step || 0.01} + } + SettingNote {visible:!!GlassService.state.namespaces || !!GlassService.state.exclusions || !!GlassService.state.overrides;text:"Existing layer allow/exclude lists or preset overrides are active. Those compositor rules remain authoritative."} +} diff --git a/quickshell/settings/controls/PreferenceChoice.qml b/quickshell/settings/controls/PreferenceChoice.qml new file mode 100644 index 0000000..96c00bd --- /dev/null +++ b/quickshell/settings/controls/PreferenceChoice.qml @@ -0,0 +1,26 @@ +import QtQuick +import QtQuick.Layouts +import "../../components" +import "../../services" + +// Few short choices render as a segmented control, longer lists as a menu. +SettingRow { + id: root + property string label + property var choices: [] + readonly property bool segmented: choices.length > 1 && choices.length <= 4 && choices.join("").length <= 34 + title: label + GlassSegmented { + visible: root.segmented + model: root.choices + currentIndex: root.choices.indexOf(ConfigService.value(root.setting)) + onActivated: (index, value) => ConfigService.setValue(root.setting, value) + } + GlassComboBox { + visible: !root.segmented + Layout.preferredWidth: 240 + model: root.choices + currentIndex: Math.max(0, root.choices.indexOf(ConfigService.value(root.setting))) + onActivated: ConfigService.setValue(root.setting, currentText) + } +} diff --git a/quickshell/settings/controls/PreferenceSlider.qml b/quickshell/settings/controls/PreferenceSlider.qml new file mode 100644 index 0000000..ef836aa --- /dev/null +++ b/quickshell/settings/controls/PreferenceSlider.qml @@ -0,0 +1,33 @@ +import QtQuick +import QtQuick.Layouts +import "../../services" +import "../../theme" +import "../../components" + +SettingRow { + id: root + property string label + property real from: 0 + property real to: 1 + property real step: 0.01 + property string unit + title: label + GlassSlider { + Layout.preferredWidth: 240 + from: root.from + to: root.to + stepSize: root.step + value: Number(ConfigService.value(root.setting)) + onMoved: ConfigService.setValue(root.setting, Number((Math.round(value / root.step) * root.step).toFixed(6))) + } + Text { + text: Number(ConfigService.value(root.setting)).toFixed(root.step < 0.01 ? 3 : root.step < 1 ? 2 : 0) + root.unit + color: Theme.textSecondary + font.pixelSize: 12 + font.features: { + "tnum": 1 + } + horizontalAlignment: Text.AlignRight + Layout.preferredWidth: 52 + } +} diff --git a/quickshell/settings/controls/PreferenceToggle.qml b/quickshell/settings/controls/PreferenceToggle.qml new file mode 100644 index 0000000..06b53ae --- /dev/null +++ b/quickshell/settings/controls/PreferenceToggle.qml @@ -0,0 +1,15 @@ +import QtQuick +import "../../services" +import "../../components" + +SettingRow { + id: root + property string label + title: label + clickable: enabled + onClicked: ConfigService.setValue(setting, !ConfigService.value(setting)) + GlassToggle { + checked: !!ConfigService.value(root.setting) + onToggled: ConfigService.setValue(root.setting, checked) + } +} diff --git a/quickshell/settings/controls/SettingNote.qml b/quickshell/settings/controls/SettingNote.qml new file mode 100644 index 0000000..91dfda5 --- /dev/null +++ b/quickshell/settings/controls/SettingNote.qml @@ -0,0 +1,17 @@ +import QtQuick +import QtQuick.Layouts +import "../../theme" + +// Secondary explanatory text inside a settings section. +Text { + property bool warning: false + color: warning ? Theme.urgent : Theme.textSecondary + font.pixelSize: 11 + wrapMode: Text.Wrap + visible: text !== "" + Layout.fillWidth: true + Layout.leftMargin: 12 + Layout.rightMargin: 12 + Layout.topMargin: 2 + Layout.bottomMargin: 4 +} diff --git a/quickshell/settings/controls/SettingRow.qml b/quickshell/settings/controls/SettingRow.qml new file mode 100644 index 0000000..af2f247 --- /dev/null +++ b/quickshell/settings/controls/SettingRow.qml @@ -0,0 +1,182 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import "../../components" +import "../../core" +import "../../services" +import "../../theme" + +// One setting: optional icon, title and description on the left, control on the right. +// Wide controls go in `below`. A bound `setting` gains a reset-to-default button once changed. +Item { + id: root + property string title + property string description + property string icon + property string setting + property bool clickable: false + default property alias control: controls.data + property alias below: belowColumn.data + signal clicked + readonly property var defaultValue: setting ? setting.split(".").reduce((object, key) => object ? object[key] : undefined, ConfigService.defaults) : undefined + readonly property bool modified: defaultValue !== undefined && JSON.stringify(ConfigService.value(setting)) !== JSON.stringify(defaultValue) + property real flash: 0 + Layout.fillWidth: true + implicitHeight: Math.max(52, content.implicitHeight + 20) + opacity: enabled ? 1 : 0.5 + + function matches(text) { + const a = title.toLowerCase(), b = String(text).toLowerCase(); + return !!a && !!b && (a === b || a.startsWith(b) || b.startsWith(a)); + } + function reveal() { + // Untyped walk: the nearest Flickable ancestor scrolls the row into view. + let parent = Object(root.parent); + while (parent) { + if (parent.contentY !== undefined && parent.contentItem && parent.contentHeight > parent.height) { + const position = root.mapToItem(parent.contentItem, 0, 0); + parent.contentY = Math.max(0, Math.min(parent.contentHeight - parent.height, position.y - parent.height / 3)); + break; + } + parent = parent.parent; + } + highlight.restart(); + } + function checkHighlight() { + if (ShellState.settingsHighlight && root.matches(ShellState.settingsHighlight)) + Qt.callLater(root.reveal); + } + Component.onCompleted: checkHighlight() + Connections { + target: ShellState + function onSettingsHighlightSerialChanged() { + root.checkHighlight(); + } + } + SequentialAnimation { + id: highlight + PauseAnimation { + duration: 160 + } + NumberAnimation { + target: root + property: "flash" + to: 1 + duration: 320 + easing.type: Easing.OutCubic + } + PauseAnimation { + duration: 1200 + } + NumberAnimation { + target: root + property: "flash" + to: 0 + duration: 800 + easing.type: Easing.InOutSine + } + } + + Rectangle { + anchors.fill: parent + radius: Math.max(8, Theme.radius * 0.5) + color: area.containsMouse && root.clickable ? Qt.alpha(Theme.text, 0.07) : area.containsMouse ? Qt.alpha(Theme.text, 0.035) : Theme.transparent + Behavior on color { + ColorAnimation { + duration: Theme.duration / 2 + } + } + Rectangle { + anchors.fill: parent + radius: parent.radius + color: Theme.accent + opacity: root.flash * 0.22 + border.width: root.flash > 0 ? 1 : 0 + border.color: Qt.alpha(Theme.accent, root.flash) + } + } + MouseArea { + id: area + anchors.fill: parent + hoverEnabled: true + acceptedButtons: root.clickable ? Qt.LeftButton : Qt.NoButton + cursorShape: root.clickable ? Qt.PointingHandCursor : Qt.ArrowCursor + onClicked: root.clicked() + } + ColumnLayout { + id: content + anchors.left: parent.left + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + anchors.leftMargin: 12 + anchors.rightMargin: 12 + spacing: 10 + RowLayout { + Layout.fillWidth: true + spacing: 12 + GlassIcon { + visible: root.icon !== "" + glyph: root.icon + fallback: root.title.charAt(0) + size: 32 + } + ColumnLayout { + Layout.fillWidth: true + Layout.minimumWidth: 120 + spacing: 2 + Text { + text: root.title + visible: text !== "" + color: Theme.text + font.pixelSize: 13 + font.weight: Font.Medium + wrapMode: Text.Wrap + Layout.fillWidth: true + } + Text { + text: root.description + visible: text !== "" + color: Theme.textSecondary + font.pixelSize: 11 + wrapMode: Text.Wrap + Layout.fillWidth: true + } + } + Rectangle { + objectName: "reset-" + root.setting + ToolTip.visible: resetArea.containsMouse + ToolTip.delay: 500 + ToolTip.text: "Reset to default" + visible: root.modified + implicitWidth: 26 + implicitHeight: 26 + radius: 13 + color: resetArea.containsMouse ? Qt.alpha(Theme.accent, 0.25) : Qt.alpha(Theme.text, 0.06) + Text { + anchors.centerIn: parent + text: "↺" + color: resetArea.containsMouse ? Theme.text : Theme.textSecondary + font.pixelSize: 14 + } + MouseArea { + id: resetArea + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: ConfigService.setValue(root.setting, JSON.parse(JSON.stringify(root.defaultValue))) + } + } + RowLayout { + id: controls + spacing: 8 + Layout.alignment: Qt.AlignRight | Qt.AlignVCenter + } + } + ColumnLayout { + id: belowColumn + visible: children.length > 0 + Layout.fillWidth: true + spacing: 8 + } + } +} diff --git a/quickshell/settings/controls/SettingsPage.qml b/quickshell/settings/controls/SettingsPage.qml new file mode 100644 index 0000000..e1f5bd5 --- /dev/null +++ b/quickshell/settings/controls/SettingsPage.qml @@ -0,0 +1,24 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import "../../theme" + +ScrollView { + id: root + default property alias content: column.data + clip: true + contentWidth: availableWidth + ScrollBar.vertical: ScrollBar { + policy: ScrollBar.AsNeeded + contentItem: Rectangle { + implicitWidth: 4 + radius: 2 + color: Qt.alpha(Theme.text, 0.25) + } + } + ColumnLayout { + id: column + width: root.availableWidth - 14 + spacing: 22 + } +} diff --git a/quickshell/settings/controls/SettingsSection.qml b/quickshell/settings/controls/SettingsSection.qml new file mode 100644 index 0000000..dc88db9 --- /dev/null +++ b/quickshell/settings/controls/SettingsSection.qml @@ -0,0 +1,53 @@ +import QtQuick +import QtQuick.Layouts +import "../../theme" + +// Titled card grouping related settings. `padded` suits free-form content +// (buttons, notes, previews); rows carry their own padding. +ColumnLayout { + id: root + property string title + property string description + property bool padded: false + default property alias content: body.data + Layout.fillWidth: true + spacing: 8 + ColumnLayout { + visible: root.title !== "" || root.description !== "" + Layout.fillWidth: true + Layout.leftMargin: 4 + spacing: 2 + Text { + text: root.title + visible: text !== "" + color: Theme.text + font.pixelSize: 14 + font.weight: Font.DemiBold + Layout.fillWidth: true + } + Text { + text: root.description + visible: text !== "" + color: Theme.textSecondary + font.pixelSize: 11 + wrapMode: Text.Wrap + Layout.fillWidth: true + } + } + Rectangle { + Layout.fillWidth: true + implicitHeight: body.implicitHeight + (root.padded ? 28 : 8) + radius: Math.max(10, Theme.radius * 0.7) + color: Theme.fill + border.width: 1 + border.color: Theme.hairline + ColumnLayout { + id: body + anchors.left: parent.left + anchors.right: parent.right + anchors.top: parent.top + anchors.margins: root.padded ? 14 : 4 + spacing: root.padded ? 10 : 2 + } + } +} diff --git a/quickshell/settings/pages/About.qml b/quickshell/settings/pages/About.qml new file mode 100644 index 0000000..0ecf30f --- /dev/null +++ b/quickshell/settings/pages/About.qml @@ -0,0 +1,85 @@ +import QtQuick +import QtQuick.Layouts +import "../controls" +import "../../services" +import "../../theme" + +SettingsPage { + SettingsSection { + padded: true + RowLayout { + Layout.fillWidth: true + spacing: 16 + Image { + objectName: "aboutCrest" + Layout.preferredWidth: 96 + Layout.preferredHeight: 96 + source: Qt.resolvedUrl("../../assets/glassmxrph-256.png") + sourceSize: Qt.size(192, 192) + fillMode: Image.PreserveAspectFit + smooth: true + mipmap: true + } + ColumnLayout { + Layout.fillWidth: true + spacing: 3 + Text { + text: "GlassMxrph" + color: Theme.text + font.pixelSize: 26 + font.weight: Font.DemiBold + } + Text { + text: "Portable Quickshell desktop suite for Hyprland" + color: Theme.textSecondary + font.pixelSize: 12 + wrapMode: Text.Wrap + Layout.fillWidth: true + } + } + } + } + SettingsSection { + title: "Environment" + SettingRow { + title: "Quickshell" + description: "Tested release" + Text { + text: "0.3.1" + color: Theme.textSecondary + } + } + SettingRow { + title: "Compositor" + description: "Tested release" + Text { + text: "Hyprland 0.56.2" + color: Theme.textSecondary + } + } + SettingRow { + title: "Icons" + description: Icons.available ? "Using the installed " + Icons.family : "Install a Nerd Font (e.g. Symbols Nerd Font) for icon glyphs" + Text { + text: Icons.available ? "Nerd Font" : "Letters" + color: Theme.textSecondary + } + } + SettingRow { + title: "Configuration" + description: ConfigService.directory + "/config.json" + Text { + text: ConfigService.writable ? "Writable" : "Read-only" + color: ConfigService.writable ? Theme.textSecondary : Theme.urgent + } + } + } + SettingsSection { + title: "Status" + padded: true + SettingNote { + Layout.leftMargin: 0 + text: "Phase 9 · Glass and interaction polish. MPRIS media and system controls are available. Shared system metrics are available. HyprGlass is optional; host integration is separate." + } + } +} diff --git a/quickshell/settings/pages/Appearance.qml b/quickshell/settings/pages/Appearance.qml new file mode 100644 index 0000000..af66eba --- /dev/null +++ b/quickshell/settings/pages/Appearance.qml @@ -0,0 +1,280 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import "../controls" +import "../../components" +import "../../services" +import "../../theme" + +// HyprGlass actions stay pinned above the scrolling preferences. +ColumnLayout { + spacing: 14 + Component.onCompleted: GlassService.probe() + Rectangle { + objectName: "glassActions" + Layout.fillWidth: true + Layout.rightMargin: 14 + implicitHeight: actions.implicitHeight + 20 + radius: Math.max(10, Theme.radius * 0.7) + color: Qt.alpha(Theme.accent, 0.12) + border.width: 1 + border.color: Qt.alpha(Theme.accent, 0.35) + RowLayout { + id: actions + anchors.fill: parent + anchors.margins: 10 + anchors.leftMargin: 12 + spacing: 12 + GlassIcon { + glyph: "󰂵" + fallback: "G" + size: 32 + } + ColumnLayout { + Layout.fillWidth: true + spacing: 1 + Text { + text: "HyprGlass" + color: Theme.text + font.pixelSize: 13 + font.weight: Font.Medium + } + Text { + text: GlassService.error || GlassService.notice || (GlassService.state.available ? "Glass changes reach the desktop and apps when applied" : "HyprGlass is not available for this compositor") + color: GlassService.error ? Theme.urgent : Theme.textSecondary + font.pixelSize: 11 + wrapMode: Text.Wrap + Layout.fillWidth: true + } + } + GlassButton { + objectName: "glassRestore" + text: "Restore previous" + enabled: !GlassService.busy + onClicked: GlassService.restore() + } + GlassButton { + objectName: "glassApply" + text: GlassService.busy ? "Applying…" : "Apply" + accented: true + enabled: !!GlassService.state.available && !GlassService.busy + onClicked: GlassService.apply(false) + } + } + } + SettingsPage { + Layout.fillWidth: true + Layout.fillHeight: true + SettingsSection { + title: "Accent" + PreferenceChoice { + label: "Accent source" + description: "Pick a colour, generate one from the wallpaper, or follow the system" + icon: "󰏘" + setting: "appearance.accentSource" + choices: ["custom", "matugen", "system"] + } + SettingRow { + visible: ThemeManager.source === "custom" + title: "Custom accent" + description: "Hex colour used across the shell" + setting: "appearance.customAccent" + GlassTextField { + Layout.preferredWidth: 120 + color: Theme.text + selectByMouse: true + text: ConfigService.data.appearance.customAccent + validator: RegularExpressionValidator { + regularExpression: /#[0-9a-fA-F]{6}/ + } + onEditingFinished: if (acceptableInput) + ConfigService.setValue("appearance.customAccent", text) + } + below: GlassColorPicker { + Layout.fillWidth: true + selectedColor: ConfigService.data.appearance.customAccent + onChosen: color => ConfigService.setValue("appearance.customAccent", color.toString()) + } + } + SettingNote { + text: ThemeManager.status !== ThemeManager.source ? ThemeManager.status : "" + } + } + SettingsSection { + visible: ThemeManager.source === "matugen" + title: "Matugen" + description: MatugenService.version || "Select an installed Matugen 4.2.x executable" + SettingRow { + title: "Executable" + description: "matugen or an absolute executable path" + GlassTextField { + Layout.preferredWidth: 220 + text: ConfigService.data.matugen.executable + placeholderText: "matugen" + onEditingFinished: ConfigService.setValue("matugen.executable", text) + } + GlassButton { + text: "Check" + onClicked: MatugenService.probe() + } + } + PreferenceChoice { + label: "Scheme" + setting: "matugen.scheme" + choices: MatugenService.schemes + enabled: choices.length > 0 + } + PreferenceSlider { + label: "Contrast" + setting: "matugen.contrast" + from: -1 + to: 1 + step: 0.1 + enabled: MatugenService.version !== "" + } + PreferenceToggle { + label: "Regenerate on wallpaper change" + setting: "matugen.regenerateOnWallpaperChange" + } + SettingRow { + title: "Palette" + description: MatugenService.busy ? "Generating from the current wallpaper…" : "Generate a new palette from the current wallpaper" + GlassButton { + text: MatugenService.busy ? "Generating…" : "Regenerate" + enabled: !MatugenService.busy + onClicked: MatugenService.regenerate() + } + } + SettingNote { + warning: true + text: MatugenService.error + } + } + SettingsSection { + title: "Surfaces" + description: "Transparency and shape of the shell’s own panels" + SettingRow { + title: "Glass tint" + description: "Colour behind the glass, like Ghostty’s background. Black matches a black Ghostty background." + icon: "󰏘" + setting: "appearance.glassTint" + Repeater { + model: [ + { + name: "Black", + value: "#000000" + }, + { + name: "Graphite", + value: "#1b1b1b" + }, + { + name: "Slate", + value: "#171b20" + } + ] + Rectangle { + id: swatch + required property var modelData + readonly property bool selected: ConfigService.data.appearance.glassTint.toLowerCase() === modelData.value + objectName: "glassTint-" + modelData.name.toLowerCase() + implicitWidth: 26 + implicitHeight: 26 + radius: 13 + color: modelData.value + border.width: selected ? 2 : 1 + border.color: selected ? Theme.accent : Theme.border + ToolTip.visible: swatchArea.containsMouse + ToolTip.delay: 400 + ToolTip.text: modelData.name + MouseArea { + id: swatchArea + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: ConfigService.setValue("appearance.glassTint", swatch.modelData.value) + } + } + } + GlassTextField { + Layout.preferredWidth: 96 + text: ConfigService.data.appearance.glassTint + validator: RegularExpressionValidator { + regularExpression: /#[0-9a-fA-F]{6}/ + } + onEditingFinished: if (acceptableInput) + ConfigService.setValue("appearance.glassTint", text) + } + } + PreferenceSlider { + label: "Glass opacity" + description: "Bar, dock and cards" + icon: "󰂵" + setting: "appearance.glassOpacity" + from: 0.15 + } + PreferenceSlider { + label: "Panel opacity" + description: "Popups, launcher and settings" + icon: "󰕮" + setting: "appearance.panelOpacity" + from: 0.15 + } + PreferenceSlider { + label: "Border opacity" + icon: "󰢡" + setting: "appearance.borderOpacity" + } + PreferenceSlider { + label: "Corner radius" + icon: "󰢡" + setting: "appearance.radius" + to: 48 + step: 1 + unit: " px" + } + PreferenceToggle { + label: "Shadows" + icon: "󰘷" + setting: "appearance.shadows" + } + PreferenceToggle { + label: "Glass highlights" + description: "Subtle top sheen and rim light" + icon: "󰖨" + setting: "appearance.highlights" + } + } + SettingsSection { + title: "Motion" + PreferenceSlider { + label: "Animation duration" + icon: "󰔟" + setting: "animation.duration" + to: 1000 + step: 10 + unit: " ms" + } + PreferenceSlider { + label: "Animation intensity" + description: "Distance of slides, lifts and scale effects" + icon: "󰑓" + setting: "animation.intensity" + } + PreferenceToggle { + label: "Reduced motion" + description: "Disable animations everywhere" + icon: "󰒲" + setting: "animation.reducedMotion" + } + } + SettingsSection { + title: "HyprGlass" + description: "Compositor glass for the desktop and applications. Surface opacity above controls the shell’s own transparency." + GlassSettings { + Layout.fillWidth: true + } + } + } +} diff --git a/quickshell/settings/pages/Audio.qml b/quickshell/settings/pages/Audio.qml new file mode 100644 index 0000000..0c704bf --- /dev/null +++ b/quickshell/settings/pages/Audio.qml @@ -0,0 +1,16 @@ +import QtQuick +import QtQuick.Layouts +import "../controls" +import "../../controlcenter/modules" as Modules +import "../../services" + +SettingsPage { + Modules.Audio { + detailed: true + Layout.fillWidth: true + } + SettingNote { + warning: true + text: SystemService.error + } +} diff --git a/quickshell/settings/pages/Bar.qml b/quickshell/settings/pages/Bar.qml new file mode 100644 index 0000000..87ba5b9 --- /dev/null +++ b/quickshell/settings/pages/Bar.qml @@ -0,0 +1,183 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Layouts +import Quickshell +import "../controls" +import "../../components" +import "../../core" +import "../../theme" +import "../../services/SettingsLogic.js" as Logic +import "../../bar/modules" as Bar + +SettingsPage { + id: root + // Screen whose bar is being edited; "" is the shared layout. + property string editScreen: "" + readonly property bool ownLayout: BarLayout.hasOwn(editScreen) + readonly property var modules: BarLayout.modulesFor(editScreen) + function edit(id, key, value) { + BarLayout.save(editScreen, Logic.editModule(modules, id, key, value)); + } + function move(id, direction) { + BarLayout.save(editScreen, Logic.moveModule(modules, id, direction)); + } + SettingsSection { + title: "Layout" + PreferenceSlider { + label: "Bar height" + icon: "󰕮" + setting: "bar.height" + from: 32 + to: 80 + step: 1 + unit: " px" + } + PreferenceSlider { + label: "Margin" + description: "Gap between the bar and the screen edge" + icon: "󰹑" + setting: "bar.margin" + from: 0 + to: 100 + step: 1 + unit: " px" + } + } + SettingsSection { + title: "Modules" + description: "Drag a module by its grip to reorder it or move it between lanes. Keyboard: Ctrl+↑/↓ reorders; Alt+←/→ changes lane." + padded: true + RowLayout { + Layout.fillWidth: true + spacing: 12 + Text { + text: "Screen" + color: Theme.textSecondary + font.pixelSize: 12 + } + GlassSegmented { + objectName: "barScreenPicker" + model: ["all screens"].concat(Quickshell.screens.map(s => s.name)) + currentIndex: root.editScreen ? model.indexOf(root.editScreen) : 0 + onActivated: (index, value) => root.editScreen = index === 0 ? "" : value + } + Item { + Layout.fillWidth: true + } + Text { + visible: root.editScreen !== "" + text: "Separate layout" + color: Theme.text + font.pixelSize: 12 + } + GlassToggle { + objectName: "barOwnLayout" + visible: root.editScreen !== "" + checked: root.ownLayout + onToggled: BarLayout.setOwn(root.editScreen, checked) + } + } + SettingNote { + Layout.leftMargin: 0 + text: root.editScreen === "" ? (Object.keys(BarLayout.screens).length ? "Shared layout, used by every screen without its own: " + Quickshell.screens.map(s => s.name).filter(n => !BarLayout.hasOwn(n)).join(", ") : "One layout for every screen. Pick a screen to give it its own modules.") : root.ownLayout ? root.editScreen + " has its own modules; changes here only affect that bar." : root.editScreen + " uses the shared layout. Turn on Separate layout to change its modules on their own." + } + BarEditor { + Layout.fillWidth: true + screenName: root.editScreen + opacity: root.editScreen === "" || root.ownLayout ? 1 : 0.45 + enabled: root.editScreen === "" || root.ownLayout + } + Flow { + Layout.fillWidth: true + spacing: 8 + visible: addRepeater.count > 0 + Repeater { + id: addRepeater + model: root.editScreen === "" || root.ownLayout ? ModuleRegistry.available.filter(id => !root.modules.some(m => m.id === id)) : [] + GlassButton { + required property string modelData + text: "+ " + ModuleRegistry.title(modelData) + onClicked: BarLayout.save(root.editScreen, root.modules.concat([ + { + id: modelData, + position: modelData === "activeWindow" ? "center" : "right", + enabled: true + } + ])) + } + } + } + SettingNote { + Layout.leftMargin: 0 + text: "The system button opens Control Center. Metrics pills share the collector configured under System Metrics." + } + } + SettingsSection { + title: "Clock" + PreferenceToggle { + label: "Show date" + icon: "󰃭" + setting: "bar.clock.showDate" + } + PreferenceToggle { + label: "24-hour time" + icon: "󰥔" + setting: "bar.clock.use24Hour" + } + PreferenceToggle { + label: "Show seconds" + icon: "󰔛" + setting: "bar.clock.showSeconds" + } + } + SettingsSection { + title: "Workspaces" + PreferenceChoice { + label: "Workspace style" + description: "Numbers, roman numerals, dots (filled when occupied) or Pac-Man" + icon: "󰏘" + setting: "bar.workspaces.style" + choices: ["numbers", "roman", "dots", "pacman"] + } + SettingRow { + title: "Preview" + description: "Live workspaces; the outline marks a workspace shown on another monitor" + icon: "󰈈" + // Below the text with the full card width; scaled down when wider (e.g. 20 roman numerals). + below: Item { + id: previewBox + Layout.fillWidth: true + implicitHeight: preview.height * preview.scale + Bar.WorkspacesModule { + id: preview + objectName: "workspacesPreview" + barScreen: ScreenService.active + transformOrigin: Item.TopLeft + scale: Math.min(1, previewBox.width / width) + } + } + } + PreferenceSlider { + label: "Workspace count" + icon: "󰕰" + setting: "bar.workspaces.count" + from: 1 + to: 20 + step: 1 + } + } + SettingsSection { + SettingRow { + title: "Tray" + description: "Tray icons, hover menus and background" + icon: "󰀻" + clickable: true + onClicked: ShellState.openSettings("tray") + Text { + text: "›" + color: Theme.textSecondary + font.pixelSize: 20 + } + } + } +} diff --git a/quickshell/settings/pages/Bluetooth.qml b/quickshell/settings/pages/Bluetooth.qml new file mode 100644 index 0000000..1f22095 --- /dev/null +++ b/quickshell/settings/pages/Bluetooth.qml @@ -0,0 +1,76 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Layouts +import Quickshell.Bluetooth +import "../controls" +import "../../components" +import "../../services" + +SettingsPage { + SettingsSection { + SettingRow { + title: "Bluetooth" + description: BluetoothService.adapter ? BluetoothService.summary : "No Bluetooth adapter" + icon: "󰂯" + GlassToggle { + checked: BluetoothService.enabled + enabled: !!BluetoothService.adapter && BluetoothService.adapter.state !== BluetoothAdapterState.Blocked + onClicked: { + BluetoothService.toggle(); + checked = Qt.binding(() => BluetoothService.enabled); + } + Accessible.name: "Bluetooth power" + } + } + SettingRow { + title: "Adapter" + icon: "󰂰" + GlassComboBox { + Layout.preferredWidth: 240 + model: BluetoothService.adapters.map(a => a.name) + currentIndex: BluetoothService.adapters.indexOf(BluetoothService.adapter) + enabled: BluetoothService.adapters.length > 0 + onActivated: BluetoothService.adapterId = BluetoothService.adapters[currentIndex].adapterId + } + } + SettingRow { + title: "Pairing" + description: "Pairing and PIN confirmation use the existing Bluetooth manager. Paired devices can connect here." + icon: "󰒓" + GlassButton { + text: "Pair devices…" + enabled: !SystemService.acting + onClicked: SystemService.action("manager", "bluetooth", false) + } + } + } + SettingsSection { + title: "Devices" + visible: devices.count > 0 + Repeater { + id: devices + model: BluetoothService.devices.filter(d => d.paired) + SettingRow { + id: entry + required property var modelData + title: modelData.name + description: BluetoothDeviceState.toString(modelData.state) + (modelData.batteryAvailable ? " · " + Math.round(modelData.battery * 100) + "%" : "") + icon: modelData.connected ? "󰂱" : "󰂯" + GlassButton { + text: entry.modelData.connected ? "Disconnect" : "Connect" + accented: !entry.modelData.connected + enabled: BluetoothService.enabled && !BluetoothService.pending + onClicked: BluetoothService.connectDevice(entry.modelData) + } + } + } + } + SettingNote { + warning: true + text: BluetoothService.error + } + SettingNote { + warning: true + text: SystemService.error + } +} diff --git a/quickshell/settings/pages/ControlCenter.qml b/quickshell/settings/pages/ControlCenter.qml new file mode 100644 index 0000000..7c3e7e4 --- /dev/null +++ b/quickshell/settings/pages/ControlCenter.qml @@ -0,0 +1,91 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Layouts +import "../controls" +import "../../controlcenter" +import "../../components" +import "../../services" + +SettingsPage { + id: root + function edit(index, enabled) { + const list = ConfigService.data.controlCenter.modules.map(m => Object.assign({}, m)); + list[index].enabled = enabled; + ConfigService.setValue("controlCenter.modules", list); + } + function move(index, step) { + const list = ConfigService.data.controlCenter.modules.slice(); + const to = index + step; + if (to < 0 || to >= list.length) + return; + const entry = list.splice(index, 1)[0]; + list.splice(to, 0, entry); + ConfigService.setValue("controlCenter.modules", list); + } + SettingsSection { + title: "Panel" + PreferenceSlider { + label: "Panel width" + icon: "󰹑" + setting: "controlCenter.width" + from: 320 + to: 600 + step: 10 + unit: " px" + } + } + SettingsSection { + title: "Modules" + description: "Enable, disable and order the Control Center cards" + Repeater { + model: ConfigService.data.controlCenter.modules + SettingRow { + id: card + required property var modelData + required property int index + readonly property var entry: ControlRegistry.entry(modelData.id) + title: entry ? entry.title : modelData.id + " (unavailable)" + GlassIconButton { + objectName: "control-up-" + card.modelData.id + text: "↑" + enabled: card.index > 0 + onClicked: root.move(card.index, -1) + } + GlassIconButton { + objectName: "control-down-" + card.modelData.id + text: "↓" + enabled: card.index < ConfigService.data.controlCenter.modules.length - 1 + onClicked: root.move(card.index, 1) + } + GlassToggle { + objectName: "control-enable-" + card.modelData.id + checked: card.modelData.enabled + onClicked: root.edit(card.index, checked) + } + } + } + Flow { + Layout.fillWidth: true + Layout.margins: 8 + spacing: 8 + visible: addRepeater.count > 0 + Repeater { + id: addRepeater + model: Object.keys(ControlRegistry.modules).filter(id => !ConfigService.data.controlCenter.modules.some(m => m.id === id)) + GlassButton { + required property string modelData + text: "+ " + ControlRegistry.modules[modelData].title + onClicked: ConfigService.setValue("controlCenter.modules", ConfigService.data.controlCenter.modules.concat([ + { + id: modelData, + enabled: true + } + ])) + } + } + } + } + SettingNote { + text: "Super+X can use the documented IPC binding. Existing keybinds are unchanged." + } +} diff --git a/quickshell/settings/pages/Dashboard.qml b/quickshell/settings/pages/Dashboard.qml new file mode 100644 index 0000000..943ef56 --- /dev/null +++ b/quickshell/settings/pages/Dashboard.qml @@ -0,0 +1,206 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Layouts +import "../controls" +import "../../components" +import "../../core" +import "../../services" +import "../../theme" + +SettingsPage { + id: root + readonly property var options: ConfigService.data.dashboard + readonly property var placements: ["top-left", "top-center", "top-right", "center"] + function edit(index, enabled) { + const list = options.tabs.map(t => Object.assign({}, t)); + list[index].enabled = enabled; + ConfigService.setValue("dashboard.tabs", list); + } + function move(index, step) { + const list = options.tabs.slice(); + const to = index + step; + if (to < 0 || to >= list.length) + return; + const entry = list.splice(index, 1)[0]; + list.splice(to, 0, entry); + ConfigService.setValue("dashboard.tabs", list); + } + SettingsSection { + title: "Dashboard" + description: "A tabbed glass panel below the bar. Open it from the clock, with “glassmxrph dashboard [tab]”, or bind that to a key. ←/→, Tab and 1–4 switch tabs." + PreferenceToggle { + label: "Enable dashboard" + icon: "󰕮" + setting: "dashboard.enabled" + } + PreferenceToggle { + label: "Open from clock" + description: "Click the bar clock to toggle it" + icon: "󰥔" + setting: "dashboard.openFromClock" + } + PreferenceToggle { + label: "Remember last tab" + description: "Otherwise it opens on the first tab" + icon: "󰋚" + setting: "dashboard.rememberTab" + } + SettingRow { + title: "Preview" + icon: "󰈈" + GlassButton { + objectName: "dashboardOpenButton" + text: "Open dashboard" + enabled: root.options.enabled + onClicked: ShellState.openDashboard("") + } + } + } + SettingsSection { + title: "Placement" + PreferenceChoice { + label: "Position" + icon: "󰹑" + setting: "dashboard.position" + choices: root.placements + } + SettingRow { + title: "Screen" + description: "Click a spot to move the dashboard" + icon: "󰍹" + below: Item { + Layout.fillWidth: true + implicitHeight: 150 + // Miniature screen with the bar and the four possible spots. + Rectangle { + id: screenPreview + objectName: "dashboardPlacementPreview" + anchors.horizontalCenter: parent.horizontalCenter + width: 240 + height: 140 + radius: 10 + color: Theme.fill + border.width: 1 + border.color: Theme.hairline + Rectangle { + x: 6 + y: 6 + width: parent.width - 12 + height: 8 + radius: 4 + color: Theme.surfaceVariant + border.width: 1 + border.color: Theme.hairline + } + Repeater { + model: root.placements + Rectangle { + id: spot + required property string modelData + readonly property bool active: root.options.position === modelData + objectName: "dashboardSpot-" + modelData + width: 64 + height: 38 + radius: 7 + x: modelData === "top-left" ? 10 : modelData === "top-right" ? screenPreview.width - width - 10 : (screenPreview.width - width) / 2 + y: modelData === "center" ? 76 : 22 + color: active ? Qt.alpha(Theme.accent, 0.55) : spotArea.containsMouse ? Theme.hover : Theme.transparent + border.width: 1 + border.color: active ? Theme.accentVivid : Qt.alpha(Theme.text, 0.18) + z: active ? 2 : 1 + Behavior on color { + ColorAnimation { + duration: Theme.duration + } + } + Text { + anchors.centerIn: parent + visible: spot.active || spotArea.containsMouse + text: spot.modelData + color: Theme.text + font.pixelSize: 10 + } + MouseArea { + id: spotArea + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: ConfigService.setValue("dashboard.position", spot.modelData) + } + } + } + } + } + } + } + SettingsSection { + title: "Tabs" + description: "Order and visibility of the dashboard tabs" + Repeater { + model: root.options.tabs + SettingRow { + id: tabRow + required property var modelData + required property int index + readonly property var entry: DashboardRegistry.entry(modelData.id) + title: entry ? entry.title : modelData.id + " (unavailable)" + description: entry ? entry.description : "" + icon: entry ? entry.glyph : "" + GlassIconButton { + objectName: "dash-up-" + tabRow.modelData.id + text: "↑" + enabled: tabRow.index > 0 + onClicked: root.move(tabRow.index, -1) + Accessible.name: "Move " + tabRow.title + " up" + } + GlassIconButton { + objectName: "dash-down-" + tabRow.modelData.id + text: "↓" + enabled: tabRow.index < root.options.tabs.length - 1 + onClicked: root.move(tabRow.index, 1) + Accessible.name: "Move " + tabRow.title + " down" + } + GlassToggle { + objectName: "dash-enable-" + tabRow.modelData.id + checked: tabRow.modelData.enabled + // Keep at least one tab. + enabled: !checked || root.options.tabs.filter(t => t.enabled).length > 1 + onClicked: root.edit(tabRow.index, checked) + } + } + } + Flow { + Layout.fillWidth: true + Layout.margins: 8 + spacing: 8 + visible: addRepeater.count > 0 + Repeater { + id: addRepeater + model: Object.keys(DashboardRegistry.tabs).filter(id => !root.options.tabs.some(t => t.id === id)) + GlassButton { + required property string modelData + text: "+ " + DashboardRegistry.tabs[modelData].title + onClicked: ConfigService.setValue("dashboard.tabs", root.options.tabs.concat([ + { + id: modelData, + enabled: true + } + ])) + } + } + } + } + SettingsSection { + title: "Media" + PreferenceToggle { + label: "EasyEffects equalizer" + description: EasyEffectsService.known && !EasyEffectsService.installed ? "EasyEffects is not installed" : "Ten-band equalizer and presets in the Media tab" + icon: "󰺢" + setting: "dashboard.easyEffects" + } + } + SettingNote { + text: "The equalizer writes its own EasyEffects output preset, glassmxrph_eq, and starts EasyEffects in service mode when you apply. Restart and Shut down ask for confirmation." + } + Component.onCompleted: EasyEffectsService.refresh() +} diff --git a/quickshell/settings/pages/Displays.qml b/quickshell/settings/pages/Displays.qml new file mode 100644 index 0000000..038f7a0 --- /dev/null +++ b/quickshell/settings/pages/Displays.qml @@ -0,0 +1,69 @@ +import QtQuick +import QtQuick.Layouts +import "../controls" +import "../../controlcenter/modules" as Modules +import "../../components" +import "../../services" + +SettingsPage { + SettingNote { + Layout.leftMargin: 4 + text: "Backlight brightness and Night Light. Display modes remain managed by Hyprland." + } + Modules.Brightness { + Layout.fillWidth: true + } + Modules.NightLight { + Layout.fillWidth: true + } + SettingsSection { + title: "Brightness" + PreferenceChoice { + label: "Backlight device" + icon: "󰃠" + setting: "system.brightness.device" + choices: ["auto"].concat(SystemService.state.brightness && SystemService.state.brightness.devices ? SystemService.state.brightness.devices.map(d => d.id) : []) + } + } + SettingsSection { + title: "Night Light" + PreferenceSlider { + label: "Night temperature" + icon: "󰖔" + setting: "system.nightLight.temperature" + from: 1000 + to: 6500 + step: 100 + unit: " K" + } + } + SettingsSection { + title: "Providers" + description: "Optional providers: status commands return JSON; set commands accept {value} (brightness percent or temperature) and {enabled} (Night Light boolean). Empty arrays use brightnessctl and an already running wl-gammarelay. Commands run only when a control is used or while its panel is open." + padded: true + CommandPreference { + label: "Brightness status arguments" + setting: "system.brightness.statusCommand" + } + CommandPreference { + label: "Brightness set arguments" + setting: "system.brightness.setCommand" + } + CommandPreference { + label: "Night Light status arguments" + setting: "system.nightLight.statusCommand" + } + CommandPreference { + label: "Night Light set arguments" + setting: "system.nightLight.setCommand" + } + GlassButton { + text: "Refresh providers" + onClicked: SystemService.refresh() + } + } + SettingNote { + warning: true + text: SystemService.error + } +} diff --git a/quickshell/settings/pages/Dock.qml b/quickshell/settings/pages/Dock.qml new file mode 100644 index 0000000..e1b5250 --- /dev/null +++ b/quickshell/settings/pages/Dock.qml @@ -0,0 +1,211 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Layouts +import Quickshell +import "../controls" +import "../../components" +import "../../services" +import "../../dock" + +SettingsPage { + id: root + readonly property var options: DockModel.options + SettingNote { + warning: true + text: ApplicationsService.error + } + SettingsSection { + PreferenceToggle { + label: "Enable dock" + description: "Floating dock with pinned and running applications" + icon: "󱂩" + setting: "dock.enabled" + } + } + SettingsSection { + title: "Placement" + enabled: root.options.enabled + PreferenceChoice { + label: "Monitor" + icon: "󰍹" + setting: "dock.monitor" + choices: ["primary"].concat(Quickshell.screens.map(s => s.name)) + } + PreferenceChoice { + label: "Position" + icon: "󰹑" + setting: "dock.position" + choices: ["bottom", "left", "right"] + } + PreferenceChoice { + label: "Visibility" + description: "Intelligent hides only when a window overlaps the dock" + icon: "󰈈" + setting: "dock.visibility" + choices: ["always", "auto", "intelligent"] + } + } + SettingsSection { + title: "Appearance" + enabled: root.options.enabled + PreferenceSlider { + label: "Icon size" + icon: "󰀻" + setting: "dock.iconSize" + from: 24 + to: 80 + step: 1 + unit: " px" + } + PreferenceSlider { + label: "Spacing" + icon: "󰡏" + setting: "dock.spacing" + from: 0 + to: 24 + step: 1 + unit: " px" + } + PreferenceSlider { + label: "Margin" + icon: "󰹑" + setting: "dock.margin" + from: 0 + to: 80 + step: 1 + unit: " px" + } + PreferenceToggle { + label: "Magnification" + description: "Enlarge icons near the pointer" + icon: "󰍉" + setting: "dock.magnification" + } + PreferenceSlider { + label: "Magnification strength" + icon: "󰍉" + setting: "dock.magnificationStrength" + enabled: root.options.magnification + from: 0 + to: 0.8 + step: 0.05 + } + PreferenceSlider { + label: "Animation speed" + icon: "󰔟" + setting: "dock.animationSpeed" + from: 0.25 + to: 3 + step: 0.05 + unit: "×" + } + } + SettingsSection { + title: "Behaviour" + enabled: root.options.enabled + PreferenceToggle { + label: "Show running apps" + description: "Include unpinned applications with open windows" + icon: "󰖯" + setting: "dock.showRunningApps" + } + PreferenceToggle { + label: "Running indicators" + icon: "󰧞" + setting: "dock.runningIndicators" + } + PreferenceToggle { + label: "Tooltips" + icon: "󰍡" + setting: "dock.tooltips" + } + SettingRow { + title: "Terminal launcher" + description: "JSON argument array for Terminal=true apps: your terminal executable and its execute flag. No terminal is assumed." + icon: "󰆍" + setting: "dock.terminalCommand" + GlassTextField { + Layout.preferredWidth: 240 + text: JSON.stringify(root.options.terminalCommand) + placeholderText: "[]" + onEditingFinished: { + try { + ConfigService.setValue("dock.terminalCommand", JSON.parse(text)); + } catch (error) { + ApplicationsService.error = "Terminal launcher must be a JSON argument array."; + } + } + } + } + } + SettingsSection { + title: "Pinned applications" + description: "Drag pinned icons in the dock, or use the arrows below." + Repeater { + model: root.options.pinnedApps + SettingRow { + id: pinned + required property string modelData + required property int index + readonly property var entry: ApplicationsService.byId(modelData) + title: entry ? entry.name : modelData + " (unavailable)" + Image { + source: ApplicationsService.icon(pinned.entry) + sourceSize.width: 28 + sourceSize.height: 28 + Layout.preferredWidth: 28 + Layout.preferredHeight: 28 + Layout.rightMargin: 4 + } + GlassIconButton { + text: "↑" + enabled: pinned.index > 0 + onClicked: DockModel.reorder(pinned.modelData, root.options.pinnedApps[pinned.index - 1]) + } + GlassIconButton { + text: "↓" + enabled: pinned.index < root.options.pinnedApps.length - 1 + onClicked: DockModel.reorder(pinned.modelData, root.options.pinnedApps[pinned.index + 1]) + } + GlassButton { + text: "Unpin" + onClicked: DockModel.unpin(pinned.modelData) + } + } + } + SettingNote { + visible: root.options.pinnedApps.length === 0 + text: "No pinned applications yet." + } + } + SettingsSection { + title: "Pin an application" + GlassTextField { + id: search + placeholderText: "Find an application to pin…" + Layout.fillWidth: true + Layout.margins: 8 + } + Repeater { + model: ApplicationsService.launchable.filter(e => e.name.toLowerCase().includes(search.text.toLowerCase()) && !root.options.pinnedApps.some(id => id.replace(/\.desktop$/i, "") === e.id.replace(/\.desktop$/i, ""))).slice(0, 30) + SettingRow { + id: app + required property var modelData + title: modelData.name + description: modelData.comment || "" + Image { + source: ApplicationsService.icon(app.modelData) + sourceSize.width: 28 + sourceSize.height: 28 + Layout.preferredWidth: 28 + Layout.preferredHeight: 28 + Layout.rightMargin: 4 + } + GlassButton { + text: "Pin" + onClicked: DockModel.pin(app.modelData.id) + } + } + } + } +} diff --git a/quickshell/settings/pages/Launcher.qml b/quickshell/settings/pages/Launcher.qml new file mode 100644 index 0000000..936c77f --- /dev/null +++ b/quickshell/settings/pages/Launcher.qml @@ -0,0 +1,37 @@ +import QtQuick +import QtQuick.Layouts +import "../controls" + +ColumnLayout { + spacing: 22 + SettingsSection { + title: "Search" + description: "Search installed applications, or type > to find a Settings command. The launcher opens on the active monitor." + PreferenceSlider { + label: "Width" + icon: "󰹑" + setting: "launcher.width" + from: 420 + to: 960 + step: 20 + unit: " px" + } + PreferenceSlider { + label: "Maximum results" + icon: "󰒺" + setting: "launcher.maxResults" + from: 10 + to: 100 + step: 1 + } + PreferenceToggle { + label: "Show descriptions" + description: "Show application comments under their names" + icon: "󰦨" + setting: "launcher.showDescriptions" + } + } + SettingNote { + text: "Super+D / Super+Space: binding instructions are in docs/phase-4.md. Existing shortcuts have not been changed. Recent files are not indexed in this phase." + } +} diff --git a/quickshell/settings/pages/Lock.qml b/quickshell/settings/pages/Lock.qml new file mode 100644 index 0000000..2d66644 --- /dev/null +++ b/quickshell/settings/pages/Lock.qml @@ -0,0 +1,118 @@ +import QtQuick +import QtQuick.Layouts +import "../controls" +import "../../components" +import "../../lock" +import "../../theme" +import "../../services" + +SettingsPage { + SettingsSection { + SettingRow { + title: "Lock screen" + description: "Check your password below before locking for the first time." + icon: "󰌾" + GlassButton { + objectName: "lockPreview" + text: "Preview" + onClicked: LockState.preview() + } + GlassButton { + objectName: "lockNow" + text: "Lock now" + accented: true + onClicked: LockState.lock() + } + } + SettingRow { + title: "Test password" + description: LockState.testResult === "accepted" ? "Password accepted. Unlocking will work." : LockState.testResult === "rejected" ? "Password rejected. Check it, or the PAM service below." : LockState.testResult === "error" ? "Authentication is unavailable with this PAM service." : "Runs the same authentication as the lock screen, without locking." + icon: "󰌆" + GlassTextField { + id: testPassword + objectName: "lockTestPassword" + Layout.preferredWidth: 200 + echoMode: TextInput.Password + placeholderText: "Password" + enabled: !LockState.busy + onAccepted: { + LockState.test(text); + clear(); + } + } + GlassButton { + text: LockState.busy ? "Checking…" : "Test" + enabled: !LockState.busy && testPassword.text !== "" + onClicked: { + LockState.test(testPassword.text); + testPassword.clear(); + } + } + } + PreferenceToggle { + label: "Use for Lock buttons" + description: "Control Center and the power menu lock with this screen instead of an external locker" + icon: "󰌾" + setting: "lock.enabled" + } + } + SettingsSection { + title: "Appearance" + PreferenceChoice { + label: "Backdrop" + description: "Your wallpaper, like macOS, or a snapshot of the desktop taken when locking" + icon: "󰸉" + setting: "lock.backdrop" + choices: ["wallpaper", "screenshot"] + } + PreferenceToggle { + label: "Liquid glass" + description: "Refraction, dispersion and highlights rendered on the lock screen itself, using your HyprGlass values" + icon: "󰂵" + setting: "lock.glass" + } + PreferenceToggle { + label: "Now Playing" + icon: "󰝚" + setting: "lock.media" + } + PreferenceToggle { + label: "Power buttons" + description: "Sleep, Restart and Shut Down below the password field" + icon: "󰐥" + setting: "lock.powerButtons" + } + } + SettingsSection { + title: "Authentication" + SettingRow { + title: "PAM service" + description: "Blank uses the bundled password check (pam_unix). Or name a service in /etc/pam.d, such as hyprlock." + icon: "󰒃" + setting: "lock.pamService" + GlassTextField { + Layout.preferredWidth: 160 + text: LockState.options.pamService + placeholderText: "bundled" + onEditingFinished: ConfigService.setValue("lock.pamService", text.trim()) + } + } + } + SettingsSection { + title: "Keybinds and recovery" + padded: true + Text { + Layout.fillWidth: true + wrapMode: Text.Wrap + color: Theme.text + font.family: "monospace" + font.pixelSize: 11 + textFormat: Text.PlainText + text: "bind = SUPER, L, exec, glassmxrph lock\n# hypridle: general { lock_cmd = glassmxrph lock }" + } + SettingNote { + Layout.leftMargin: 0 + text: "If the shell ever stops while locked, Hyprland keeps the session locked. From another TTY (Ctrl+Alt+F3): hyprctl --instance 0 'keyword misc:allow_session_lock_restore 1', then start glassMxrph again and lock/unlock once." + } + } +} diff --git a/quickshell/settings/pages/Media.qml b/quickshell/settings/pages/Media.qml new file mode 100644 index 0000000..82e884c --- /dev/null +++ b/quickshell/settings/pages/Media.qml @@ -0,0 +1,126 @@ +import QtQuick +import QtQuick.Layouts +import "../controls" +import "../../components" +import "../../services" +import "../../media" +import "../../services/SettingsLogic.js" as Logic + +SettingsPage { + id: root + function moduleOn(id) { + return ConfigService.data.bar.modules.some(m => m.id === id && m.enabled); + } + // Adds the module to the centre lane the first time, then just toggles it. + function setModule(id, on) { + const modules = ConfigService.data.bar.modules; + if (modules.some(m => m.id === id)) + ConfigService.setValue("bar.modules", Logic.editModule(modules, id, "enabled", on)); + else if (on) + ConfigService.setValue("bar.modules", modules.concat([ + { + id: id, + position: "center", + enabled: true + } + ])); + } + SettingsSection { + description: "Shared playback controls for all compatible MPRIS players." + padded: true + MediaCard { + compact: true + Layout.fillWidth: true + } + } + SettingsSection { + title: "Bar" + description: "Playback and an audio visualizer in the bar. Cava shows system audio, not only the selected player, and only runs while something plays." + SettingRow { + title: "Now playing" + description: "Play/pause and the current track" + icon: "󰎈" + GlassToggle { + objectName: "mediaBarNowPlaying" + checked: root.moduleOn("nowPlaying") + onToggled: root.setModule("nowPlaying", checked) + } + } + SettingRow { + title: "Visualizer" + description: CavaService.error ? "Cava: " + CavaService.error : "Cava bars; click opens the dashboard's Media tab" + icon: "󰺢" + GlassToggle { + objectName: "mediaBarCava" + checked: root.moduleOn("cava") + onToggled: root.setModule("cava", checked) + } + } + PreferenceSlider { + label: "Visualizer bars" + icon: "󰐕" + setting: "bar.cava.bars" + from: 4 + to: 24 + step: 1 + enabled: root.moduleOn("cava") + } + PreferenceChoice { + label: "Visualizer style" + icon: "󰺢" + setting: "bar.cava.style" + choices: ["bars", "mirror"] + enabled: root.moduleOn("cava") + } + PreferenceToggle { + label: "Hide while paused" + description: "Collapse the visualizer when nothing is playing" + icon: "󰏤" + setting: "bar.cava.hideWhenIdle" + enabled: root.moduleOn("cava") + } + } + SettingsSection { + title: "Media cards" + description: "The player in the Control Center, dashboard and this page" + PreferenceToggle { + label: "Album artwork" + icon: "󰀥" + setting: "media.showAlbumArt" + } + PreferenceToggle { + label: "Track progress" + icon: "󰦖" + setting: "media.showProgress" + } + PreferenceToggle { + label: "Album name" + icon: "󰎆" + setting: "media.showAlbum" + } + PreferenceToggle { + label: "Visualizer in cards" + description: "Cava bars under the track" + icon: "󰺢" + setting: "media.showCava" + } + } + SettingsSection { + title: "Player" + PreferenceChoice { + label: "Preferred player" + icon: "󰐊" + setting: "media.preferredPlayer" + choices: ["automatic"].concat(MediaService.players.map(p => p.dbusName)).concat(MediaService.players.some(p => p.dbusName === ConfigService.data.media.preferredPlayer) || ConfigService.data.media.preferredPlayer === "automatic" ? [] : [ConfigService.data.media.preferredPlayer]) + } + SettingRow { + title: "Player ID" + description: "Preferred MPRIS player ID, or automatic" + GlassTextField { + Layout.preferredWidth: 240 + text: ConfigService.data.media.preferredPlayer + onEditingFinished: ConfigService.setValue("media.preferredPlayer", text || "automatic") + } + } + } +} diff --git a/quickshell/settings/pages/Metrics.qml b/quickshell/settings/pages/Metrics.qml new file mode 100644 index 0000000..a5a86f9 --- /dev/null +++ b/quickshell/settings/pages/Metrics.qml @@ -0,0 +1,78 @@ +import QtQuick +import QtQuick.Layouts +import "../controls" +import "../../components" +import "../../services" +import "../../metrics" + +SettingsPage { + SettingsSection { + padded: true + MetricsCard { + Layout.fillWidth: true + } + } + SettingsSection { + title: "Collection" + description: "GPU updates at most every 5 seconds; storage every 15 seconds. All views share one collector." + PreferenceSlider { + label: "Sampling interval" + icon: "󰔟" + setting: "metrics.interval" + from: 1 + to: 30 + step: 1 + unit: " s" + } + SettingRow { + title: "GPU" + icon: "󰢮" + setting: "metrics.gpu" + GlassComboBox { + Layout.preferredWidth: 240 + model: [ + { + id: "auto", + name: "Automatic" + } + ].concat(MetricsService.gpus).concat(ConfigService.data.metrics.gpu === "auto" || MetricsService.gpus.some(g => g.id === ConfigService.data.metrics.gpu) ? [] : [ + { + id: ConfigService.data.metrics.gpu, + name: "Unavailable · " + ConfigService.data.metrics.gpu + } + ]) + textRole: "name" + valueRole: "id" + currentIndex: model.findIndex(g => g.id === ConfigService.data.metrics.gpu) + onActivated: ConfigService.setValue("metrics.gpu", currentValue) + } + } + PreferenceChoice { + label: "Network interface" + description: "Auto totals physical interfaces to avoid counting VPN/bridge traffic twice" + icon: "󰛳" + setting: "metrics.networkInterface" + choices: Array.from(new Set(["auto", ConfigService.data.metrics.networkInterface].concat((MetricsService.network.interfaces || []).map(i => i.name)))) + } + SettingRow { + title: "Storage paths" + description: "JSON array, up to eight local paths. Remote filesystem paths can block the collector." + icon: "󰋊" + setting: "metrics.storagePaths" + GlassTextField { + Layout.preferredWidth: 240 + text: JSON.stringify(ConfigService.data.metrics.storagePaths) + onEditingFinished: { + try { + ConfigService.setValue("metrics.storagePaths", JSON.parse(text)); + } catch (e) { + text = JSON.stringify(ConfigService.data.metrics.storagePaths); + } + } + } + } + } + SettingNote { + text: "Missing sensor values are shown as —. CPU temperature is the hottest supported CPU hwmon sensor. RAM usage excludes available cache; storage free includes reserved blocks." + } +} diff --git a/quickshell/settings/pages/Network.qml b/quickshell/settings/pages/Network.qml new file mode 100644 index 0000000..1bc24cd --- /dev/null +++ b/quickshell/settings/pages/Network.qml @@ -0,0 +1,81 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Layouts +import Quickshell.Networking +import "../controls" +import "../../components" +import "../../services" + +SettingsPage { + Component.onCompleted: NetworkService.scanning = true + Component.onDestruction: NetworkService.scanning = false + SettingsSection { + SettingRow { + title: "Wi-Fi" + description: NetworkService.available ? NetworkService.summary : "No Wi-Fi adapter. Wired connections and advanced options are available in your network manager." + icon: "󰖩" + GlassToggle { + checked: NetworkService.enabled + enabled: NetworkService.available && NetworkService.backend.wifiHardwareEnabled + onClicked: { + NetworkService.toggle(); + checked = Qt.binding(() => NetworkService.enabled); + } + Accessible.name: "Wi-Fi" + } + } + SettingRow { + title: "Advanced connections" + description: "VPN, enterprise and wired settings in your network manager" + icon: "󰒓" + GlassButton { + text: "Open…" + enabled: !SystemService.acting + onClicked: SystemService.action("manager", "network", false) + } + } + } + SettingsSection { + title: "Networks" + visible: networks.count > 0 + Repeater { + id: networks + model: NetworkService.networks + SettingRow { + id: entry + required property var modelData + readonly property bool psk: [WifiSecurityType.WpaPsk, WifiSecurityType.Wpa2Psk, WifiSecurityType.Sae].includes(modelData.security) + readonly property bool supported: modelData.known || modelData.device.type === DeviceType.Wired || modelData.security === WifiSecurityType.Open || psk + title: modelData.name + " · " + modelData.device.name + description: modelData.connected ? "Connected" : modelData.stateChanging ? "Connecting…" : modelData.known ? "Saved connection" : supported ? "Available" : "Use advanced connections for this security type" + icon: modelData.connected ? "󰤨" : "󰤟" + GlassTextField { + id: password + visible: entry.psk && !entry.modelData.known && !entry.modelData.connected + echoMode: TextInput.Password + placeholderText: "Wi-Fi password" + Layout.preferredWidth: 180 + inputMethodHints: Qt.ImhSensitiveData | Qt.ImhNoPredictiveText + Accessible.name: "Wi-Fi password" + } + GlassButton { + text: entry.modelData.connected ? "Disconnect" : "Connect" + accented: !entry.modelData.connected + enabled: entry.supported && !entry.modelData.stateChanging && !NetworkService.pending + onClicked: { + NetworkService.connectNetwork(entry.modelData, password.text); + password.clear(); + } + } + } + } + } + SettingNote { + warning: true + text: NetworkService.error + } + SettingNote { + warning: true + text: SystemService.error + } +} diff --git a/quickshell/settings/pages/Notifications.qml b/quickshell/settings/pages/Notifications.qml new file mode 100644 index 0000000..de8e82a --- /dev/null +++ b/quickshell/settings/pages/Notifications.qml @@ -0,0 +1,15 @@ +import QtQuick +import QtQuick.Layouts +import "../controls" +import "../../controlcenter/modules" as Modules +import "../../services" + +SettingsPage { + Modules.Dnd { + Layout.fillWidth: true + } + SettingNote { + warning: true + text: SystemService.error + } +} diff --git a/quickshell/settings/pages/Osd.qml b/quickshell/settings/pages/Osd.qml new file mode 100644 index 0000000..fcdbd56 --- /dev/null +++ b/quickshell/settings/pages/Osd.qml @@ -0,0 +1,84 @@ +import QtQuick +import QtQuick.Layouts +import "../controls" +import "../../components" +import "../../core" +import "../../theme" + +SettingsPage { + SettingsSection { + title: "Overlay" + description: "A glass capsule shows volume, microphone and brightness changes from any source, including existing keybinds." + PreferenceToggle { + label: "Show overlay" + description: "Hidden while Control Center is open" + icon: "󰍩" + setting: "osd.enabled" + } + PreferenceChoice { + label: "Position" + icon: "󰹑" + setting: "osd.position" + choices: ["top-right", "top-center", "bottom-center"] + } + PreferenceChoice { + label: "Animation" + description: "Slide out of the bar, drop down, fade, or shrink to nothing" + icon: "󰕮" + setting: "osd.animation" + choices: ["slide", "drop", "fade", "shrink"] + } + PreferenceSlider { + label: "Duration" + description: "Stays open while hovered or dragged" + icon: "󰔟" + setting: "osd.timeout" + from: 500 + to: 5000 + step: 100 + unit: " ms" + } + PreferenceSlider { + label: "Step" + description: "Change per key press or scroll on the bar volume module" + icon: "󰁝" + setting: "osd.step" + from: 1 + to: 20 + step: 1 + unit: "%" + } + SettingRow { + title: "Preview" + icon: "󰈈" + Repeater { + model: ["volume", "microphone", "brightness"] + GlassButton { + required property string modelData + objectName: "osdPreview-" + modelData + text: modelData.charAt(0).toUpperCase() + modelData.slice(1) + onClicked: if (ShellState.osdWindow) + ShellState.osdWindow.show(modelData) + } + } + } + } + SettingsSection { + title: "Keybinds" + description: "Volume changed by wpctl or pamixer already shows the overlay. These commands also change the level and work for brightness:" + padded: true + Text { + Layout.fillWidth: true + wrapMode: Text.Wrap + color: Theme.text + font.family: "monospace" + font.pixelSize: 11 + textFormat: Text.PlainText + text: "bindel = , XF86AudioRaiseVolume, exec, glassmxrph osd volumeUp\nbindel = , XF86AudioLowerVolume, exec, glassmxrph osd volumeDown\nbindl = , XF86AudioMute, exec, glassmxrph osd mute\nbindl = , XF86AudioMicMute, exec, glassmxrph osd micMute\nbindel = , XF86MonBrightnessUp, exec, glassmxrph osd brightnessUp\nbindel = , XF86MonBrightnessDown, exec, glassmxrph osd brightnessDown" + } + SettingNote { + Layout.leftMargin: 0 + text: "Use the full path to scripts/glassmxrph in your clone if it is not on PATH. Existing keybinds are not changed." + } + } +} diff --git a/quickshell/settings/pages/Plugins.qml b/quickshell/settings/pages/Plugins.qml new file mode 100644 index 0000000..2927e8b --- /dev/null +++ b/quickshell/settings/pages/Plugins.qml @@ -0,0 +1,560 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Layouts +import "../controls" +import "../../components" +import "../../services" +import "../../theme" + +SettingsPage { + id: root + // Plugin awaiting removal confirmation. + property string confirmRemove: "" + // Marketplace listing awaiting install confirmation. + property string confirmInstall: "" + // Plugin whose own settings screen is open (Noctalia Settings.qml); + // "open plugin settings" from a plugin sets it. + property string openSettings: PluginService.focusedSettings + onOpenSettingsChanged: if (openSettings) + tab = "installed" + property string tab: "installed" + onTabChanged: if (tab === "browse" && PluginService.market.items.length === 0) + PluginService.browse(false) + Component.onCompleted: PluginService.refresh() + readonly property var capabilityLabels: ({ + "privilege": "Uses sudo", + "package-manager": "Installs packages", + "service-management": "Manages services", + "installer": "Runs installers", + "network": "Uses the network", + "credentials": "Handles credentials", + "filesystem": "Writes files" + }) + readonly property var accents: ({ + "violet": "#8b5cf6", + "purple": "#a855f7", + "blue": "#3b82f6", + "sky": "#0ea5e9", + "cyan": "#06b6d4", + "teal": "#14b8a6", + "green": "#22c55e", + "lime": "#84cc16", + "yellow": "#eab308", + "amber": "#f59e0b", + "orange": "#f97316", + "red": "#ef4444", + "rose": "#f43f5e", + "pink": "#ec4899", + "slate": "#64748b" + }) + + SettingsSection { + title: "Plugins" + description: "Shell plugins from Omarchy (plugins.omarchy.org) and Noctalia v4. Their bar widgets sit in the bar like built-in modules and their panels open as bar drawers, styled by glassMxrph." + GlassSegmented { + objectName: "pluginTabs" + Layout.leftMargin: 14 + Layout.bottomMargin: 4 + model: ["installed", "browse"] + currentIndex: model.indexOf(root.tab) + onActivated: (index, value) => root.tab = value + } + SettingNote { + Layout.leftMargin: 0 + text: "Plugins run inside the shell with your user's permissions, the same as in Omarchy and Noctalia: a plugin can read your files and run commands. Only install plugins from authors you trust, and use View source to check what one does." + } + } + SettingsSection { + visible: root.tab === "installed" + title: "Add a plugin" + description: "A git URL or a local folder holding an Omarchy or Noctalia v4 plugin. Repositories with several plugins install them all." + SettingRow { + title: "Source" + icon: "󰊢" + GlassTextField { + id: sourceField + objectName: "pluginSource" + Layout.preferredWidth: 300 + placeholderText: "https://github.com/user/plugin" + onAccepted: installButton.clicked() + } + GlassButton { + id: installButton + objectName: "pluginInstall" + text: PluginService.busy ? "Installing…" : "Install" + accented: true + enabled: !PluginService.busy && sourceField.text.trim() !== "" + onClicked: PluginService.install(sourceField.text, "") + } + } + Text { + Layout.fillWidth: true + Layout.leftMargin: 14 + Layout.bottomMargin: 8 + visible: text !== "" + wrapMode: Text.Wrap + font.pixelSize: 12 + color: PluginService.error ? Theme.urgent : Theme.textSecondary + text: { + if (PluginService.error) + return PluginService.error; + const r = PluginService.lastResult || {}; + const parts = []; + if (r.installed && r.installed.length) + parts.push("Installed " + r.installed.join(", ") + ". Turn it on below."); + if (r.rejected && r.rejected.length) + parts.push("Skipped " + r.rejected.map(x => x.dir + " (" + x.problems.join("; ") + ")").join(", ")); + return parts.join(" "); + } + } + } + SettingsSection { + visible: root.tab === "installed" + title: "Installed" + description: PluginService.plugins.length ? "Turn a plugin on to load it. Bar widgets then appear under Bar → Modules (and can go on a single screen); their options are on the module's cog." : "" + Text { + visible: PluginService.loaded && PluginService.plugins.length === 0 + Layout.fillWidth: true + Layout.margins: 14 + text: "No plugins installed yet." + color: Theme.textSecondary + font.pixelSize: 12 + } + Repeater { + model: PluginService.plugins + SettingRow { + id: row + required property var modelData + readonly property var manifest: modelData.manifest || {} + readonly property bool enabledNow: PluginService.isEnabled(modelData.id) + readonly property bool inBar: ConfigService.data.bar.modules.some(m => m.id === "plugin:" + modelData.id) + objectName: "plugin-" + modelData.id + title: manifest.name || modelData.id + description: [manifest.description || "", [manifest.version ? "v" + manifest.version : "", manifest.author || ""].filter(x => x).join(" · ")].filter(x => x).join("\n") + icon: "󰐱" + GlassButton { + objectName: "plugin-add-" + row.modelData.id + visible: row.enabledNow && (row.manifest.kinds || []).includes("bar-widget") && !row.inBar + text: "Add to bar" + onClicked: PluginService.addToBar(row.modelData.id) + } + GlassButton { + objectName: "plugin-settings-" + row.modelData.id + visible: row.enabledNow && (row.modelData.kinds || []).includes("settings") + text: root.openSettings === row.modelData.id ? "Close settings" : "Settings" + accented: root.openSettings === row.modelData.id + onClicked: root.openSettings = root.openSettings === row.modelData.id ? "" : row.modelData.id + } + GlassButton { + objectName: "plugin-source-" + row.modelData.id + text: "View source" + onClicked: Qt.openUrlExternally(/^https?:\/\//.test(row.modelData.source) ? row.modelData.source : "file://" + row.modelData.dir) + } + GlassButton { + objectName: "plugin-remove-" + row.modelData.id + text: root.confirmRemove === row.modelData.id ? "Confirm remove" : "Remove" + accented: root.confirmRemove === row.modelData.id + onClicked: { + if (root.confirmRemove === row.modelData.id) { + root.confirmRemove = ""; + PluginService.remove(row.modelData.id); + } else + root.confirmRemove = row.modelData.id; + } + } + GlassToggle { + objectName: "plugin-enable-" + row.modelData.id + checked: row.enabledNow + enabled: row.modelData.problems.length === 0 + onToggled: PluginService.setEnabled(row.modelData.id, checked) + } + below: ColumnLayout { + Layout.fillWidth: true + spacing: 10 + Flow { + Layout.fillWidth: true + spacing: 6 + Repeater { + model: [ + { + text: row.modelData.ecosystem === "noctalia" ? "Noctalia" : "Omarchy", + tone: "plain" + } + ].concat((row.modelData.kinds || []).map(k => ({ + text: k, + tone: "plain" + }))).concat(row.modelData.problems.map(p => ({ + text: p, + tone: "bad" + }))).concat(row.modelData.unsupportedImports.map(i => ({ + text: "Needs " + i + " (not supported)", + tone: "bad" + }))).concat((row.modelData.missingCommands || []).map(c => ({ + text: "Missing " + c, + tone: "warn" + }))).concat(row.modelData.customColors > 0 ? [ + { + text: "Custom colors · " + row.modelData.customColors, + tone: "warn" + } + ] : []).concat(row.modelData.commit ? [ + { + text: "Pinned " + row.modelData.commit.slice(0, 8), + tone: "plain" + } + ] : []) + Rectangle { + id: badge + required property var modelData + implicitWidth: badgeText.implicitWidth + 16 + implicitHeight: 22 + radius: 11 + color: badge.modelData.tone === "bad" ? Qt.alpha(Theme.urgent, 0.2) : badge.modelData.tone === "warn" ? Qt.alpha(Theme.urgent, 0.12) : Theme.fill + border.width: 1 + border.color: Theme.hairline + Text { + id: badgeText + anchors.centerIn: parent + text: badge.modelData.text + color: badge.modelData.tone === "plain" ? Theme.textSecondary : Theme.urgent + font.pixelSize: 11 + } + } + } + Text { + visible: !!row.modelData.source + text: row.modelData.source + color: Theme.textSecondary + font.pixelSize: 11 + elide: Text.ElideMiddle + width: Math.min(implicitWidth, 360) + height: 22 + verticalAlignment: Text.AlignVCenter + } + } + // The plugin's own settings screen (Noctalia Settings.qml), with + // its pluginApi; Save calls the plugin's saveSettings(). + Rectangle { + Layout.fillWidth: true + visible: root.openSettings === row.modelData.id + implicitHeight: visible ? settingsColumn.implicitHeight + 24 : 0 + radius: 12 + color: Theme.fill + border.width: 1 + border.color: Theme.hairline + ColumnLayout { + id: settingsColumn + anchors.left: parent.left + anchors.right: parent.right + anchors.top: parent.top + anchors.margins: 12 + spacing: 10 + Loader { + id: pluginSettings + Layout.fillWidth: true + active: root.openSettings === row.modelData.id + onActiveChanged: if (active) + setSource(row.modelData.entryUrls.settings, { + pluginApi: PluginService.noctaliaApi(row.modelData.id) + }) + } + RowLayout { + Layout.fillWidth: true + Item { + Layout.fillWidth: true + } + GlassButton { + text: "Cancel" + onClicked: root.openSettings = "" + } + GlassButton { + objectName: "plugin-settings-save-" + row.modelData.id + text: "Save" + accented: true + onClicked: { + PluginService.callIfPresent(pluginSettings.item, "saveSettings"); + root.openSettings = ""; + } + } + } + } + } + } + } + } + } + SettingNote { + visible: root.tab === "installed" + text: "Custom colors: the plugin draws some of its own colors, so those parts keep the plugin's look instead of your theme. Everything drawn with the plugin toolkit (buttons, toggles, panels, tooltips) uses the glassMxrph style." + } + SettingsSection { + visible: root.tab === "browse" + title: PluginService.marketSource === "noctalia" ? "Noctalia plugins" : "plugins.omarchy.org" + description: !PluginService.market.total ? "Community plugins." : PluginService.marketSource === "noctalia" ? PluginService.market.total + " Noctalia v4 plugins, run through glassMxrph's compatibility layer: most bar widgets, panels and settings work; some plugins rely on Noctalia parts glassMxrph does not have (the Installed tab lists them)." : PluginService.market.total + " plugins. Installs use the commit the marketplace last validated. Verified means the marketplace's automated review passed at that commit." + GlassSegmented { + objectName: "marketSource" + Layout.leftMargin: 12 + Layout.topMargin: 6 + model: ["omarchy", "noctalia"] + currentIndex: model.indexOf(PluginService.marketSource) + onActivated: (index, value) => PluginService.marketSource = value + } + RowLayout { + Layout.fillWidth: true + Layout.margins: 12 + spacing: 8 + GlassTextField { + objectName: "marketSearch" + Layout.fillWidth: true + placeholderText: "Search plugins" + text: PluginService.marketQuery + onTextChanged: PluginService.marketQuery = text + } + GlassComboBox { + objectName: "marketCategory" + Layout.preferredWidth: 160 + model: ["all"].concat(PluginService.market.categories || []) + displayText: currentText === "all" ? "All categories" : currentText + currentIndex: Math.max(0, model.indexOf(PluginService.marketCategory)) + onActivated: PluginService.marketCategory = currentText + } + } + RowLayout { + Layout.fillWidth: true + Layout.leftMargin: 12 + Layout.rightMargin: 12 + Layout.bottomMargin: 10 + spacing: 10 + GlassSegmented { + objectName: "marketSort" + model: ["popular", "recent", "name"] + currentIndex: model.indexOf(PluginService.marketSort) + onActivated: (index, value) => PluginService.marketSort = value + } + Item { + Layout.fillWidth: true + } + Text { + text: "Verified only" + color: Theme.text + font.pixelSize: 12 + } + GlassToggle { + objectName: "marketVerified" + checked: PluginService.marketVerifiedOnly + onToggled: PluginService.marketVerifiedOnly = checked + } + } + } + SettingsSection { + visible: root.tab === "browse" + Text { + Layout.fillWidth: true + Layout.margins: 14 + visible: text !== "" + wrapMode: Text.Wrap + font.pixelSize: 12 + color: PluginService.marketError || PluginService.error ? Theme.urgent : Theme.textSecondary + text: PluginService.error || PluginService.marketError || ((PluginService.lastResult.installed || []).length ? "Installed " + PluginService.lastResult.installed.join(", ") + ". Turn it on under Installed." : "") || (PluginService.marketBusy && PluginService.market.items.length === 0 ? "Loading the plugin catalog…" : PluginService.market.total === 0 && !PluginService.marketBusy ? "No plugins match." : "") + } + Repeater { + model: PluginService.market.items + Item { + id: listing + required property var modelData + readonly property bool installed: PluginService.isInstalled(modelData.id) + readonly property bool confirming: root.confirmInstall === modelData.id + readonly property bool usable: modelData.installable && modelData.support !== "unsupported" + objectName: "listing-" + modelData.id + Layout.fillWidth: true + implicitHeight: card.implicitHeight + 16 + ColumnLayout { + id: card + anchors.left: parent.left + anchors.right: parent.right + anchors.top: parent.top + anchors.margins: 12 + spacing: 6 + RowLayout { + Layout.fillWidth: true + spacing: 12 + Rectangle { + Layout.alignment: Qt.AlignTop + implicitWidth: 40 + implicitHeight: 40 + radius: 12 + color: Qt.alpha(root.accents[listing.modelData.accent] || Theme.accent, 0.35) + border.width: 1 + border.color: Qt.alpha(root.accents[listing.modelData.accent] || Theme.accent, 0.6) + Text { + anchors.centerIn: parent + text: listing.modelData.initials || listing.modelData.name.slice(0, 2).toUpperCase() + color: Theme.text + font.pixelSize: 14 + font.weight: Font.DemiBold + } + } + ColumnLayout { + Layout.fillWidth: true + spacing: 2 + Text { + Layout.fillWidth: true + text: listing.modelData.name + color: Theme.text + font.pixelSize: 14 + font.weight: Font.DemiBold + elide: Text.ElideRight + } + Text { + Layout.fillWidth: true + text: [listing.modelData.author ? "by " + listing.modelData.author : "", listing.modelData.version ? "v" + listing.modelData.version : "", "★ " + listing.modelData.stars].filter(x => x).join(" · ") + color: Theme.textSecondary + font.pixelSize: 11 + elide: Text.ElideRight + } + } + GlassButton { + objectName: "listing-page-" + listing.modelData.id + text: "Details" + onClicked: Qt.openUrlExternally(listing.modelData.page) + } + GlassButton { + objectName: "listing-install-" + listing.modelData.id + text: listing.installed ? "Installed" : !listing.usable ? "Not available" : listing.confirming ? "Cancel" : "Install" + enabled: !listing.installed && listing.usable && !PluginService.busy + onClicked: root.confirmInstall = listing.confirming ? "" : listing.modelData.id + } + } + Text { + Layout.fillWidth: true + visible: text !== "" + text: listing.modelData.description + color: Theme.text + opacity: 0.85 + font.pixelSize: 12 + wrapMode: Text.Wrap + maximumLineCount: 2 + elide: Text.ElideRight + } + Flow { + Layout.fillWidth: true + spacing: 6 + Repeater { + model: [ + { + text: listing.modelData.kind, + tone: "plain" + }, + { + text: listing.modelData.kind === "Noctalia v4" ? "Best effort" : listing.modelData.support === "supported" ? "Works in glassMxrph" : listing.modelData.support === "partial" ? "Partly supported" : "Not supported", + tone: listing.modelData.support === "supported" ? "good" : listing.modelData.support === "partial" ? "warn" : "bad" + }, + { + text: listing.modelData.official ? "Official" : listing.modelData.kind === "Noctalia v4" ? "Community" : listing.modelData.verified ? "Verified" : "Unverified", + tone: listing.modelData.official || listing.modelData.verified ? "good" : listing.modelData.kind === "Noctalia v4" ? "plain" : "warn" + } + ].concat((listing.modelData.capabilities || []).map(c => ({ + text: root.capabilityLabels[c] || c, + tone: "warn" + }))).concat([ + { + text: listing.modelData.category, + tone: "plain" + } + ]) + Rectangle { + id: tag + required property var modelData + implicitWidth: tagText.implicitWidth + 16 + implicitHeight: 22 + radius: 11 + color: tag.modelData.tone === "good" ? Qt.alpha(Theme.accent, 0.22) : tag.modelData.tone === "bad" ? Qt.alpha(Theme.urgent, 0.2) : tag.modelData.tone === "warn" ? Qt.alpha(Theme.urgent, 0.12) : Theme.fill + border.width: 1 + border.color: Theme.hairline + Text { + id: tagText + anchors.centerIn: parent + text: tag.modelData.text + color: tag.modelData.tone === "plain" ? Theme.textSecondary : tag.modelData.tone === "good" ? Theme.text : Theme.urgent + font.pixelSize: 11 + } + } + } + } + // Install confirmation: exactly what will be cloned, and the trust warning. + Rectangle { + Layout.fillWidth: true + visible: listing.confirming + implicitHeight: confirmBody.implicitHeight + 20 + radius: 12 + color: Theme.fill + border.width: 1 + border.color: Theme.hairline + ColumnLayout { + id: confirmBody + anchors.left: parent.left + anchors.right: parent.right + anchors.top: parent.top + anchors.margins: 10 + spacing: 8 + Text { + Layout.fillWidth: true + wrapMode: Text.Wrap + color: Theme.text + font.pixelSize: 12 + text: "Install " + listing.modelData.name + " from " + listing.modelData.repo + (listing.modelData.commit ? " at commit " + listing.modelData.commit.slice(0, 10) : " (current version)") + "? It will run inside the shell with your permissions" + ((listing.modelData.capabilities || []).length ? " and its review flagged: " + listing.modelData.capabilities.map(c => (root.capabilityLabels[c] || c).toLowerCase()).join(", ") : "") + "." + } + RowLayout { + Layout.fillWidth: true + spacing: 8 + Text { + Layout.fillWidth: true + visible: listing.modelData.support === "partial" + text: listing.modelData.kind === "Noctalia v4" ? "Noctalia plugins are best effort: check its badges under Installed." : "Overlay and menu plugins keep some of their own styling." + color: Theme.textSecondary + font.pixelSize: 11 + wrapMode: Text.Wrap + } + Item { + Layout.fillWidth: listing.modelData.support !== "partial" + } + GlassButton { + text: "View source" + onClicked: Qt.openUrlExternally(listing.modelData.repo) + } + GlassButton { + objectName: "listing-confirm-" + listing.modelData.id + text: PluginService.busy ? "Installing…" : "Install" + accented: true + enabled: !PluginService.busy + onClicked: { + root.confirmInstall = ""; + PluginService.installListing(listing.modelData); + } + } + } + } + } + } + Rectangle { + anchors.bottom: parent.bottom + anchors.left: parent.left + anchors.right: parent.right + anchors.leftMargin: 12 + anchors.rightMargin: 12 + height: 1 + color: Theme.hairline + } + } + } + GlassButton { + objectName: "marketMore" + Layout.alignment: Qt.AlignHCenter + Layout.margins: 10 + visible: PluginService.market.items.length < PluginService.market.total + text: PluginService.marketBusy ? "Loading…" : "Show more (" + (PluginService.market.total - PluginService.market.items.length) + ")" + enabled: !PluginService.marketBusy + onClicked: PluginService.browse(true) + } + } +} diff --git a/quickshell/settings/pages/Power.qml b/quickshell/settings/pages/Power.qml new file mode 100644 index 0000000..d79126d --- /dev/null +++ b/quickshell/settings/pages/Power.qml @@ -0,0 +1,26 @@ +import QtQuick +import QtQuick.Layouts +import "../controls" +import "../../controlcenter/modules" as Modules +import "../../services" + +SettingsPage { + Modules.Power { + Layout.fillWidth: true + } + Modules.Profiles { + Layout.fillWidth: true + } + SettingsSection { + title: "Lock screen" + padded: true + CommandPreference { + label: "Lock command arguments (empty = detected existing locker)" + setting: "system.power.lockCommand" + } + } + SettingNote { + warning: true + text: SystemService.error + } +} diff --git a/quickshell/settings/pages/Tray.qml b/quickshell/settings/pages/Tray.qml new file mode 100644 index 0000000..4014779 --- /dev/null +++ b/quickshell/settings/pages/Tray.qml @@ -0,0 +1,31 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Layouts +import "../controls" +import "../../components" +import "../../services" +import "../../theme" +ColumnLayout { + spacing: 22 + SettingsSection { + title: "Tray" + PreferenceToggle { label: "System tray"; description: "Show StatusNotifier applications in the bar"; icon: "󰀻"; setting: "tray.enabled" } + PreferenceToggle { label: "Hover menus"; description: "Open application menus on hover"; icon: "󰍜"; setting: "tray.hoverMenus" } + PreferenceChoice { label: "Background"; icon: "󰆧"; setting: "tray.background"; choices: ["pill", "transparent", "icons"] } + } + SettingsSection { + title: "Sizing" + Repeater { + model: [{key:"hoverDelay",label:"Hover delay",min:100,max:2000,step:50,unit:" ms"},{key:"iconSize",label:"Icon size",min:16,max:32,step:1,unit:" px"},{key:"spacing",label:"Spacing",min:0,max:24,step:1,unit:" px"}] + SettingRow { + id: sizing + required property var modelData + title: modelData.label + setting: "tray." + modelData.key + GlassSlider { Layout.preferredWidth: 240; from: sizing.modelData.min; to: sizing.modelData.max; stepSize: sizing.modelData.step; value: TrayService.options[sizing.modelData.key]; onMoved: ConfigService.setValue("tray." + sizing.modelData.key, Math.round(value)) } + Text { text: TrayService.options[sizing.modelData.key] + sizing.modelData.unit; color: Theme.textSecondary; font.pixelSize: 12; horizontalAlignment: Text.AlignRight; Layout.preferredWidth: 52 } + } + } + } + SettingNote { text: "Right-click opens the application menu. Shift + right-click uses the native menu. Only registered tray applications appear." } +} diff --git a/quickshell/settings/pages/Wallpaper.qml b/quickshell/settings/pages/Wallpaper.qml new file mode 100644 index 0000000..d249a60 --- /dev/null +++ b/quickshell/settings/pages/Wallpaper.qml @@ -0,0 +1,211 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import Quickshell +import "../controls" +import "../../components" +import "../../services" +import "../../theme" +import "../../core" + +SettingsPage { + id: root + property string selected: "" + Component.onCompleted: { + WallpaperService.refresh(); + WallpaperService.scan(); + } + SettingsSection { + SettingRow { + title: "Wallpaper picker" + description: "Browse large wallpaper cards, search your folders and revisit recent wallpapers. The built-in backend works without Serpantinum." + icon: "󰸉" + GlassButton { + objectName: "openWallpaperPicker" + text: "Open picker" + accented: true + onClicked: ShellState.openWallpaperPicker() + } + } + } + SettingsSection { + title: "Gallery" + description: "Select an image, then apply it to the chosen monitor" + padded: true + GridView { + id: grid + objectName: "wallpaperGrid" + Layout.fillWidth: true + Layout.preferredHeight: 300 + clip: true + model: WallpaperService.images + cellWidth: Math.max(140, width / Math.max(1, Math.floor(width / 170))) + cellHeight: 125 + ScrollBar.vertical: ScrollBar {} + delegate: Rectangle { + id: tile + required property var modelData + readonly property bool chosen: root.selected === modelData.path + width: grid.cellWidth - 8 + height: 117 + radius: Math.max(8, Theme.radius * 0.55) + color: tileArea.containsMouse ? Theme.hover : Theme.surfaceVariant + border.width: chosen ? 2 : 1 + border.color: chosen ? Theme.accent : Theme.border + scale: tileArea.containsMouse ? 1 + 0.02 * Theme.intensity : 1 + Behavior on scale { + NumberAnimation { + duration: Theme.duration + easing.type: Easing.OutCubic + } + } + Image { + anchors { + top: parent.top + left: parent.left + right: parent.right + margins: 4 + } + height: 82 + source: tile.modelData.url + sourceSize: Qt.size(220, 140) + asynchronous: true + fillMode: Image.PreserveAspectCrop + clip: true + } + Text { + anchors { + bottom: parent.bottom + left: parent.left + right: parent.right + margins: 8 + } + text: (WallpaperService.currentPath === tile.modelData.path ? "✓ " : "") + tile.modelData.name + color: Theme.text + elide: Text.ElideMiddle + font.pixelSize: 12 + } + MouseArea { + id: tileArea + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: root.selected = tile.modelData.path + } + } + } + Text { + visible: WallpaperService.images.length === 0 + text: WallpaperService.scanning ? "Loading images…" : "Add a folder containing PNG, JPEG, WebP or BMP images." + color: Theme.textSecondary + wrapMode: Text.Wrap + Layout.fillWidth: true + } + RowLayout { + Layout.fillWidth: true + Text { + text: WallpaperService.error || WallpaperService.notice + color: WallpaperService.error ? Theme.urgent : Theme.textSecondary + font.pixelSize: 11 + wrapMode: Text.Wrap + Layout.fillWidth: true + } + GlassButton { + objectName: "wallpaperApply" + text: WallpaperService.busy ? "Applying…" : "Apply selected wallpaper" + accented: root.selected !== "" + enabled: root.selected !== "" && !WallpaperService.busy + onClicked: WallpaperService.apply(root.selected) + } + } + } + SettingsSection { + title: "Wallpaper folders" + description: "One absolute path per line" + padded: true + GlassTextArea { + id: folders + Layout.fillWidth: true + Layout.preferredHeight: 72 + text: ConfigService.data.wallpaper.directories.join("\n") + wrapMode: TextEdit.NoWrap + selectByMouse: true + } + RowLayout { + GlassButton { + text: "Save folders" + onClicked: { + if (ConfigService.setValue("wallpaper.directories", folders.text.split("\n").map(s => s.trim()).filter(Boolean))) + WallpaperService.scan(); + } + } + GlassButton { + text: "Use Pictures" + onClicked: { + ConfigService.setValue("wallpaper.directories", [Quickshell.env("HOME") + "/Pictures"]); + WallpaperService.scan(); + } + } + GlassButton { + text: "Refresh" + enabled: !WallpaperService.scanning + onClicked: { + WallpaperService.refresh(); + WallpaperService.scan(); + } + } + } + } + SettingsSection { + title: "Output" + description: "Detected: " + WallpaperService.backend + " · Current: " + (WallpaperService.currentPath || "unknown") + SettingRow { + title: "Apply to monitor" + description: "“all” sets every connected display" + icon: "󰍹" + GlassComboBox { + Layout.preferredWidth: 240 + model: ["all", "primary"].concat(Quickshell.screens.map(s => s.name)) + currentIndex: Math.max(0, model.indexOf(WallpaperService.selectedMonitor)) + onActivated: WallpaperService.selectedMonitor = currentText + } + } + PreferenceChoice { + label: "Backend" + description: "Tool that sets the wallpaper" + icon: "󰒓" + setting: "wallpaper.backend" + choices: ["native", "auto", "serpantinum", "awww", "custom"] + } + SettingRow { + visible: ConfigService.data.wallpaper.backend === "custom" + title: "Custom command" + description: "JSON argument array; {path} and {monitor} are substituted" + setting: "wallpaper.command" + GlassTextField { + Layout.preferredWidth: 280 + text: JSON.stringify(ConfigService.data.wallpaper.command) + placeholderText: '["your-tool", "{path}", "{monitor}"]' + onEditingFinished: { + try { + ConfigService.setValue("wallpaper.command", JSON.parse(text)); + } catch (error) { + WallpaperService.error = "Custom command must be a JSON argument array."; + } + } + } + } + PreferenceChoice { + label: "Palette monitor" + description: "Wallpaper used for Matugen palette generation" + icon: "󰏘" + setting: "wallpaper.paletteMonitor" + choices: ["primary"].concat(Quickshell.screens.map(s => s.name)) + } + SettingNote { + visible: WallpaperService.backend === "serpantinum" + text: "Serpantinum applies its own wallpaper hooks. glassMxrph generates its palette separately without app hooks." + } + } +} diff --git a/quickshell/settings/pages/Widgets.qml b/quickshell/settings/pages/Widgets.qml new file mode 100644 index 0000000..d012a39 --- /dev/null +++ b/quickshell/settings/pages/Widgets.qml @@ -0,0 +1,54 @@ +pragma ComponentBehavior: Bound +import QtQuick +import "../controls" +import "../../components" +import "../../widgets" + +SettingsPage { + SettingsSection { + SettingRow { + title: "Edit widgets" + description: "Add, move and resize widgets on the desktop. You can also right-click any widget, or run glassmxrph widgets." + icon: "󰕰" + GlassButton { + objectName: "editWidgets" + text: "Edit desktop" + accented: true + onClicked: WidgetState.edit("") + } + } + PreferenceToggle { + label: "Snap to grid" + description: "20 px grid while editing; otherwise widgets snap to edges, centres and each other" + icon: "󰕰" + setting: "desktopWidgets.grid" + } + } + SettingsSection { + title: "Your widgets" + description: WidgetState.items.length ? "" : "No widgets yet. Choose Edit desktop to add some." + Repeater { + model: WidgetState.items + SettingRow { + id: entry + required property var modelData + readonly property var type: WidgetRegistry.type(modelData.type) + title: type ? type.name + (type.variants ? " · " + type.variants[modelData.variant] : "") : modelData.type + " (unavailable)" + description: modelData.monitor + " · " + modelData.w + "×" + modelData.h + " at " + modelData.x + ", " + modelData.y + icon: type ? type.icon : "?" + GlassButton { + text: "Edit" + onClicked: WidgetState.edit(entry.modelData.id) + } + GlassButton { + objectName: "removeWidget-" + entry.modelData.id + text: "Remove" + onClicked: WidgetState.remove(entry.modelData.id) + } + } + } + } + SettingNote { + text: "The Music widget and System Metrics pages keep their existing corner widgets; desktop widgets are independent and can be placed anywhere." + } +} diff --git a/quickshell/shell.qml b/quickshell/shell.qml new file mode 100644 index 0000000..585189f --- /dev/null +++ b/quickshell/shell.qml @@ -0,0 +1,126 @@ +//@ pragma UseQApplication +//@ pragma Env QT_QUICK_CONTROLS_STYLE=Basic +import QtQuick +import Quickshell +import Quickshell.Io +import "services" +import "core" +import "theme" +import "bar" +import "settings" +import "menus" +import "dock" +import "launcher" +import "widgets" +import "wallpaper" +import "controlcenter" +import "dashboard" +import "osd" +import "lock" +import "plugins" + +ShellRoot { + readonly property var sharedGlass: GlassService + readonly property var sharedMedia: MediaService + Variants { + model: ConfigService.ready ? Quickshell.screens : [] + Bar {} + } + Variants { + model: ConfigService.ready && ConfigService.data.wallpaper.backend === "native" ? Quickshell.screens.filter(s=>!!ConfigService.data.wallpaper.byMonitor[s.name]) : [] + WallpaperBackground {} + } + DesktopWidgets {} + WallpaperPicker {} + ControlCenter {} + Dashboard {} + PluginHost {} + Osd {} + Lock {} + Settings {} + Launcher {} + TrayMenus {} + BarPopout {} + Loader { + active: ConfigService.ready && ConfigService.data.dock.enabled + sourceComponent: Component { + Dock {} + } + } + DockContextMenu {} + Loader { + active: Quickshell.env("GLASSMXRPH_METRICS_TESTING") === "1" + source: active ? Qt.resolvedUrl("testing/MetricsDriver.qml") : "" + } + Loader { + active: Quickshell.env("GLASSMXRPH_POLISH_TESTING") === "1" + source: active ? Qt.resolvedUrl("testing/PolishDriver.qml") : "" + } + // Test-only input driver; QtTest is not a runtime dependency. + Loader { + active: Quickshell.env("GLASSMXRPH_TESTING") === "1" + source: active ? Qt.resolvedUrl("testing/TrayDriver.qml") : "" + } + Loader { + active: Quickshell.env("GLASSMXRPH_DOCK_TESTING") === "1" + source: active ? Qt.resolvedUrl("testing/DockDriver.qml") : "" + } + Loader { + active: Quickshell.env("GLASSMXRPH_LAUNCHER_TESTING") === "1" + source: active ? Qt.resolvedUrl("testing/LauncherDriver.qml") : "" + } + Loader { + active: Quickshell.env("GLASSMXRPH_PLUGIN_TESTING") === "1" + source: active ? Qt.resolvedUrl("testing/PluginDriver.qml") : "" + } + Loader { + active: Quickshell.env("GLASSMXRPH_DASHBOARD_TESTING") === "1" + source: active ? Qt.resolvedUrl("testing/DashboardDriver.qml") : "" + } + Loader { + active: Quickshell.env("GLASSMXRPH_SETTINGS_TESTING") === "1" + source: active ? Qt.resolvedUrl("testing/SettingsDriver.qml") : "" + } + Loader { + active: Quickshell.env("GLASSMXRPH_MEDIA_TESTING") === "1" + source: active ? Qt.resolvedUrl("testing/MediaDriver.qml") : "" + } + Loader { + active: Quickshell.env("GLASSMXRPH_CONTROL_TESTING") === "1" + source: active ? Qt.resolvedUrl("testing/ControlDriver.qml") : "" + } + IpcHandler { + target: "shell" + function settings(): void { + ShellState.toggleSettings(); + } + function openSettings(page: string): void { + ShellState.openSettings(page); + } + function close(): void { + ShellState.wallpaperPickerOpen = false; + ShellState.controlCenterOpen = false; + ShellState.dashboardOpen = false; + ShellState.settingsOpen = false; + ShellState.launcherOpen = false; + } + function setPreference(path: string, json: string): bool { + try { + return ConfigService.setValue(path, JSON.parse(json)); + } catch (e) { + return false; + } + } + function status(): string { + return JSON.stringify({ + ready: ConfigService.ready, + error: ConfigService.error, + accent: Theme.accent.toString(), + settingsOpen: ShellState.settingsOpen, + settingsPage: ShellState.settingsPage, + launcherOpen: ShellState.launcherOpen, + accentSource: ConfigService.ready ? ConfigService.data.appearance.accentSource : "loading" + }); + } + } +} diff --git a/quickshell/testing/ControlDriver.qml b/quickshell/testing/ControlDriver.qml new file mode 100644 index 0000000..205f35b --- /dev/null +++ b/quickshell/testing/ControlDriver.qml @@ -0,0 +1,227 @@ +import QtQuick +import QtTest +import Quickshell +import Quickshell.Io +import Quickshell.Networking +import Quickshell.Bluetooth +import "../core" +import "../services" + +Item { + id: root + parent: ShellState.controlCenterWindow ? ShellState.controlCenterWindow.contentItem : null + TestCase { + id: input + name: "ControlInput" + when: false + } + property QtObject audioNode: QtObject { + property string name: "fixture-output" + property string description: "Fixture audio" + property bool isSink: true + property bool isStream: false + property QtObject audio: QtObject { + property real volume: 0.4 + property bool muted: false + } + } + property QtObject audioInput: QtObject { + property string name: "fixture-input" + property string description: "Fixture microphone" + property bool isSink: false + property bool isStream: false + property QtObject audio: QtObject { + property real volume: 0.6 + property bool muted: false + } + } + property QtObject audioBackend: QtObject { + property bool ready: true + property var defaultAudioSink: root.audioNode + property var defaultAudioSource: root.audioInput + property var preferredDefaultAudioSink: root.audioNode + property var preferredDefaultAudioSource: root.audioInput + property QtObject nodes: QtObject { + property var values: [root.audioNode, root.audioInput] + } + } + property QtObject wifi: QtObject { + id: fixtureWifi + property int type: DeviceType.Wifi + property string name: "fixture-wifi" + property bool connected: fixtureNetwork.connected + property bool scannerEnabled: false + property QtObject networks: QtObject { + property var values: [root.network] + } + } + property QtObject network: QtObject { + id: fixtureNetwork + property string name: "Fixture network" + property var device: root.wifi + property bool known: true + property bool connected: false + property int state: ConnectionState.Disconnected + property bool stateChanging: false + property int security: WifiSecurityType.Wpa2Psk + signal connectionFailed(int reason) + function connect() { + connected = true; + state = ConnectionState.Connected; + } + function disconnect() { + connected = false; + state = ConnectionState.Disconnected; + } + function connectWithPsk(password) { + connect(); + } + } + property QtObject networkBackend: QtObject { + property int backend: NetworkBackendType.NetworkManager + property bool wifiEnabled: true + property bool wifiHardwareEnabled: true + property QtObject devices: QtObject { + property var values: [root.wifi] + } + } + property QtObject btDevice: QtObject { + property string name: "Fixture headphones" + property bool connected: false + property bool paired: true + property int state: BluetoothDeviceState.Disconnected + property bool batteryAvailable: true + property real battery: 0.8 + function connect() { + connected = true; + state = BluetoothDeviceState.Connected; + } + function disconnect() { + connected = false; + state = BluetoothDeviceState.Disconnected; + } + } + property QtObject btAdapter: QtObject { + property string name: "Fixture Bluetooth" + property string adapterId: "fixture" + property bool enabled: true + property int state: BluetoothAdapterState.Enabled + property QtObject devices: QtObject { + property var values: [root.btDevice] + } + } + property QtObject btBackend: QtObject { + property var defaultAdapter: root.btAdapter + property QtObject adapters: QtObject { + property var values: [root.btAdapter] + } + } + function child(name) { + return input.findChild(ShellState.controlCenterWindow.contentItem, name); + } + function reveal(item) { + let parent = item.parent; + while (parent) { + if (parent.contentY !== undefined && parent.contentItem && parent.contentHeight > parent.height) { + const pos = item.mapToItem(parent.contentItem, 0, 0); + parent.contentY = Math.max(0, Math.min(parent.contentHeight - parent.height, pos.y - parent.height / 2)); + } + parent = parent.parent; + } + input.wait(40); + } + IpcHandler { + target: "controlTest" + function inject(): bool { + if (SystemService.busy) + return false; + AudioService.backend = root.audioBackend; + NetworkService.backend = root.networkBackend; + BluetoothService.backend = root.btBackend; + SystemService.helper = "testing/recording_system.py"; + SystemService.refresh(); + return true; + } + function click(name: string): bool { + const item = root.child(name); + if (!item || !item.enabled) + return false; + root.reveal(item); + input.mouseClick(item, item.width / 2, item.height / 2); + return true; + } + function slider(name: string): bool { + const item = root.child(name); + if (!item || !item.enabled) + return false; + root.reveal(item); + input.mouseClick(item, item.width * .75, item.height / 2); + return true; + } + function clickSystem(): bool { + const pill = ShellState.systemPills.find(p => p.barScreen === ScreenService.active) || ShellState.systemPills[0]; + if (!pill) + return false; + input.mouseClick(pill, pill.width / 2, pill.height / 2); + return true; + } + function settingsClick(name: string): bool { + const item = input.findChild(ShellState.settingsWindow.contentItem, name); + if (!item || !item.enabled) + return false; + root.reveal(item); + input.mouseClick(item, item.width / 2, item.height / 2); + return true; + } + function value(name: string): real { + const item = root.child(name); + return item ? item.value : -1; + } + function checked(name: string): bool { + const item = root.child(name); + return item ? item.checked : false; + } + function pressEscape(): void { + input.keyClick(Qt.Key_Escape); + } + function outside(): void { + // Outside the panel-sized surface, as Hyprland delivers it. + input.mouseClick(ShellState.controlCenterWindow.contentItem, -40, ShellState.controlCenterWindow.height / 2); + } + function screenshot(path: string): bool { + return root.child("controlCenterSurface").grabToImage(result => result.saveToFile(path)); + } + function snapshot(): string { + const panel = root.child("controlCenterSurface"); + return JSON.stringify({ + settingsVisible: ShellState.settingsWindow.visible, + modules: ConfigService.data.controlCenter.modules, + windowVisible: ShellState.controlCenterWindow.visible, + panelVisible: panel.visible, + panelOpacity: panel.opacity, + opened: ShellState.controlCenterOpen, + state: SystemService.state, + error: SystemService.error, + busy: SystemService.busy, + power: PowerService.pending, + wifi: NetworkService.enabled, + bluetooth: BluetoothService.enabled, + volume: AudioService.sink && AudioService.sink.audio ? AudioService.sink.audio.volume : -1, + muted: AudioService.sink && AudioService.sink.audio ? AudioService.sink.audio.muted : false, + microphone: AudioService.source && AudioService.source.audio ? AudioService.source.audio.muted : false, + scan: fixtureWifi.scannerEnabled, + active: ScreenService.active.name, + screens: Quickshell.screens.map(s => s.name), + x: ShellState.controlCenterWindow.panelScreenX, + y: ShellState.controlCenterWindow.panelScreenY, + width: panel.width, + height: panel.height, + screenWidth: ShellState.controlCenterWindow.screenWidth, + screenHeight: ShellState.controlCenterWindow.screenHeight + }); + } + function connectFixtures(): bool { + return NetworkService.connectNetwork(root.network, "") && BluetoothService.connectDevice(root.btDevice); + } + } +} diff --git a/quickshell/testing/DashboardDriver.qml b/quickshell/testing/DashboardDriver.qml new file mode 100644 index 0000000..ee14f51 --- /dev/null +++ b/quickshell/testing/DashboardDriver.qml @@ -0,0 +1,53 @@ +import QtQuick +import QtTest +import Quickshell.Io +import "../core" + +// Test hooks for the dashboard: screenshots, named clicks and key presses. +Item { + id: root + parent: ShellState.dashboardWindow ? ShellState.dashboardWindow.contentItem : null + TestCase { + id: input + name: "DashboardDriver" + when: false + } + function find(name) { + return ShellState.dashboardWindow ? input.findChild(ShellState.dashboardWindow.contentItem, name) : null; + } + IpcHandler { + target: "dashboardTest" + function screenshot(path: string): bool { + const surface = root.find("dashboardSurface"); + return !!surface && surface.grabToImage(result => result.saveToFile(path)); + } + function click(name: string): bool { + const item = root.find(name); + if (!item || !item.visible) + return false; + input.mouseClick(item, item.width / 2, item.height / 2); + return true; + } + function key(key: int): void { + input.keyClick(key); + } + function outside(): void { + input.mouseClick(ShellState.dashboardWindow.contentItem, -40, -40); + } + function settingsClick(name: string): bool { + const item = ShellState.settingsWindow ? input.findChild(ShellState.settingsWindow.contentItem, name) : null; + if (!item || !item.visible || !item.enabled) + return false; + // Scroll the settings page so the control is under the pointer. + for (let p = item.parent; p; p = p.parent) + if (p.contentY !== undefined && p.contentItem && p.contentHeight > p.height) + p.contentY = Math.max(0, Math.min(p.contentHeight - p.height, item.mapToItem(p.contentItem, 0, 0).y - p.height / 2)); + input.wait(60); + input.mouseClick(item, item.width / 2, item.height / 2); + return true; + } + function settingsScreenshot(path: string): bool { + return !!ShellState.settingsWindow && input.findChild(ShellState.settingsWindow.contentItem, "settingsPageLoader").grabToImage(result => result.saveToFile(path)); + } + } +} diff --git a/quickshell/testing/DockDriver.qml b/quickshell/testing/DockDriver.qml new file mode 100644 index 0000000..6ff890c --- /dev/null +++ b/quickshell/testing/DockDriver.qml @@ -0,0 +1,95 @@ +import QtQuick +import QtTest +import Quickshell +import Quickshell.Io +import "../dock" +import "../services" + +Item { + id: root + parent: DockState.menuWindow ? DockState.menuWindow.contentItem : null + function icon(id) { + return DockState.icons.find(i => i.group.id === id); + } + TestCase { + id: input + name: "DockInputDriver" + when: false + } + IpcHandler { + target: "dockTest" + function screens(): string { + return JSON.stringify(Quickshell.screens.map(s => s.name)); + } + function click(id: string, button: int): bool { + const i = root.icon(id); + if (!i) + return false; + input.mouseClick(i, i.width / 2, i.height / 2, button); + return true; + } + function rows(): string { + return JSON.stringify(DockState.menuWindow.rows.map(r => ({ + id: r.id, + text: r.text, + separator: !!r.separator + }))); + } + function row(id: string): bool { + const menu = DockState.menuWindow, index = menu.rows.findIndex(r => r.id === id); + if (index < 0) + return false; + const list = input.findChild(menu.contentItem, "dockMenuList"); + list.positionViewAtIndex(index, ListView.Contain); + const item = list.itemAtIndex(index); + if (!item) + return false; + input.mouseClick(item, item.width / 2, item.height / 2); + return true; + } + function drag(from: string, to: string): bool { + const a = root.icon(from), b = root.icon(to); + if (!a || !b) + return false; + const p = a.mapFromItem(b, b.width / 2, b.height / 2); + input.mousePress(a, a.width / 2, a.height / 2, Qt.LeftButton); + input.mouseMove(a, p.x, p.y, 80); + input.mouseRelease(a, p.x, p.y, Qt.LeftButton); + return true; + } + function hover(inside: bool): bool { + const d = DockState.docks[0]; + if (!d) + return false; + input.mouseMove(d.contentItem, inside ? d.width / 2 : -10, inside ? d.height - 1 : -10); + return true; + } + function pressEscape(): void { + input.keyClick(Qt.Key_Escape); + } + function snapshot(): string { + return JSON.stringify({ + windows: HyprlandService.windows.filter(w => w.appId.startsWith("org.glassMxrph.DockFixture")).map(w => ({ + address: w.address, + active: w.active, + appId: w.appId, + monitor: w.monitor, + width: w.width, + height: w.height + })), + icons: DockState.icons.map(i => ({ + id: i.group.id, + width: i.width, + height: i.height + })), + error: ApplicationsService.error + }); + } + function screenshot(path: string): bool { + const d = DockState.docks[0]; + if (!d) + return false; + return input.findChild(d.contentItem, "dockSurface").grabToImage(result => result.saveToFile(path)); + } + } +} diff --git a/quickshell/testing/LauncherDriver.qml b/quickshell/testing/LauncherDriver.qml new file mode 100644 index 0000000..e565eb1 --- /dev/null +++ b/quickshell/testing/LauncherDriver.qml @@ -0,0 +1,107 @@ +import QtQuick +import QtTest +import Quickshell.Io +import "../launcher" +import "../core" +import "../theme" + +Item { + id: root + parent: LauncherState.window ? LauncherState.window.contentItem : null + function search() { + return input.findChild(LauncherState.window.contentItem, "launcherSearch"); + } + TestCase { + id: input + name: "LauncherInputDriver" + when: false + } + // The panel grows to fit results; wait for it to settle before pointing. + function settle(): void { + const panel = input.findChild(LauncherState.window.contentItem, "launcherSurface"); + let last = -1; + for (let i = 0; i < 40 && panel.height !== last; i++) { + last = panel.height; + input.wait(Math.max(50, Theme.duration / 2)); + } + } + IpcHandler { + target: "launcherTest" + function query(text: string): void { + const field = root.search(); + field.text = text; + field.forceActiveFocus(); + } + function key(key: int): void { + input.keyClick(key); + } + function typeAscii(text: string): void { + for (let i = 0; i < text.length; i++) + input.keyClick(text.charAt(i).toUpperCase().charCodeAt(0)); + } + function snapshot(): string { + const w = LauncherState.window, panel = input.findChild(w.contentItem, "launcherSurface"); + return JSON.stringify({ + activeMonitor: ScreenService.active ? ScreenService.active.name : "", + opened: ShellState.launcherOpen, + screen: w.screen.name, + screenWidth: w.width, + screenHeight: w.height, + x: panel.x, + y: panel.y, + width: panel.width, + height: panel.height, + visible: w.visible, + query: root.search().text, + focused: root.search().activeFocus, + selected: w.selectedIndex, + results: w.results.map(r => ({ + id: r.id, + title: r.title, + command: !!r.command + })), + error: w.launchError + }); + } + function click(index: int): bool { + root.settle(); + const list = input.findChild(LauncherState.window.contentItem, "launcherResults"); + list.positionViewAtIndex(index, ListView.Contain); + const row = list.itemAtIndex(index); + if (!row) + return false; + input.mouseClick(row, row.width / 2, row.height / 2); + return true; + } + function hover(index: int): bool { + root.settle(); + const list = input.findChild(LauncherState.window.contentItem, "launcherResults"); + const row = list.itemAtIndex(index); + if (!row) + return false; + input.mouseMove(row, row.width / 2, row.height / 2); + return true; + } + function outside(): void { + input.mouseClick(LauncherState.window.contentItem, 5, 5); + } + function browse(): void { + LauncherState.window.toggleBrowse(); + } + function screenshot(path: string): bool { + return input.findChild(LauncherState.window.contentItem, "launcherSurface").grabToImage(result => result.saveToFile(path)); + } + function extension(add: bool): bool { + if (!add) { + CommandRegistry.unregisterCommand("fixture"); + return true; + } + return CommandRegistry.registerCommand({ + id: "fixture", + title: "Fixture command", + description: "Test extension", + run: () => ShellState.openSettings("about") + }); + } + } +} diff --git a/quickshell/testing/MediaDriver.qml b/quickshell/testing/MediaDriver.qml new file mode 100644 index 0000000..e7c23d3 --- /dev/null +++ b/quickshell/testing/MediaDriver.qml @@ -0,0 +1,42 @@ +import QtQuick +import QtTest +import Quickshell.Io +import "../core" +import "../services" + +Item { + id: root + // The media card lives in Settings → Media; tests open that page first. + parent: ShellState.settingsWindow ? ShellState.settingsWindow.contentItem : null + TestCase { + id: input + name: "MediaInputDriver" + when: false + } + Loader { + source: "../controlcenter/modules/Media.qml" + visible: false + } + IpcHandler { + target: "mediaTest" + function click(name: string): bool { + if (!ShellState.settingsWindow) + return false; + const item = input.findChild(ShellState.settingsWindow.contentItem, name); + if (!item || !item.enabled) + return false; + input.mouseClick(item, item.width / 2, item.height / 2); + return true; + } + function screenshot(path: string): bool { + if (!ShellState.settingsWindow) + return false; + return input.findChild(ShellState.settingsWindow.contentItem, "mediaCard").grabToImage(result => result.saveToFile(path)); + } + function status(): string { + return JSON.stringify({ + progressConsumers: MediaService.progressConsumers + }); + } + } +} diff --git a/quickshell/testing/MetricsDriver.qml b/quickshell/testing/MetricsDriver.qml new file mode 100644 index 0000000..0809b4d --- /dev/null +++ b/quickshell/testing/MetricsDriver.qml @@ -0,0 +1,23 @@ +import QtQuick +import QtTest +import Quickshell.Io +import "../core" + +Item { + id: root + TestCase { + id: input + name: "MetricsDriver" + when: false + } + IpcHandler { + target: "metricsTest" + function screenshot(path: string): bool { + // The metrics card lives in Settings → Metrics. + if (!ShellState.settingsWindow) + return false; + const card = input.findChild(ShellState.settingsWindow.contentItem, "metricsCard"); + return !!card && card.grabToImage(result => result.saveToFile(path)); + } + } +} diff --git a/quickshell/testing/PluginDriver.qml b/quickshell/testing/PluginDriver.qml new file mode 100644 index 0000000..5d7c5a3 --- /dev/null +++ b/quickshell/testing/PluginDriver.qml @@ -0,0 +1,24 @@ +import QtQuick +import QtTest +import Quickshell.Io +import "../services" + +// Test hooks for plugins: off-screen screenshots of plugin panels. +Item { + id: root + TestCase { + id: input + name: "PluginDriver" + when: false + } + IpcHandler { + target: "pluginTest" + function panelScreenshot(id: string, path: string): bool { + const w = PluginService.panelWindows[id]; + if (!w || !w.visible) + return false; + const surface = input.findChild(w.contentItem, "noctaliaPanelSurface"); + return !!surface && surface.grabToImage(result => result.saveToFile(path)); + } + } +} diff --git a/quickshell/testing/PolishDriver.qml b/quickshell/testing/PolishDriver.qml new file mode 100644 index 0000000..7c2de32 --- /dev/null +++ b/quickshell/testing/PolishDriver.qml @@ -0,0 +1,38 @@ +import QtQuick +import Quickshell.Io +import "../theme" +import "../core" +import "../dock" + +Item { + IpcHandler { + target: "polishTest" + function staleScreens(): void { + ShellState.targetScreen = { + name: "removed-test-output" + }; + ShellState.launcherScreen = { + name: "removed-test-output" + }; + ShellState.controlCenterScreen = { + name: "removed-test-output" + }; + } + function snapshot(): string { + return JSON.stringify({ + intensity: Theme.intensity, + duration: Theme.duration, + accent: Theme.accent.toString(), + foreground: Theme.accentText.toString(), + active: ScreenService.active.name, + settingsScreen: ShellState.settingsWindow.screen.name, + controlScreen: ShellState.controlCenterWindow.screen.name, + dock: DockState.icons.map(i => ({ + influence: i.influence, + magnification: i.magnification + })), + systemPills: ShellState.systemPills.length + }); + } + } +} diff --git a/quickshell/testing/SettingsDriver.qml b/quickshell/testing/SettingsDriver.qml new file mode 100644 index 0000000..021acbc --- /dev/null +++ b/quickshell/testing/SettingsDriver.qml @@ -0,0 +1,190 @@ +import QtQuick +import QtTest +import Quickshell.Io +import "../core" +import "../services" +import "../theme" +import "../widgets" +import "../lock" + +Item { + id: root + property var lastDrag: ({}) + parent: ShellState.settingsWindow ? ShellState.settingsWindow.contentItem : null + TestCase { + id: input + name: "SettingsInputDriver" + when: false + } + function child(name) { + return input.findChild(ShellState.settingsWindow.contentItem, name); + } + function reveal(item) { + let parent = item.parent; + while (parent) { + if (parent.contentY !== undefined && parent.contentItem && parent.contentHeight > parent.height) { + const position = item.mapToItem(parent.contentItem, 0, 0); + parent.contentY = Math.max(0, Math.min(parent.contentHeight - parent.height, position.y - parent.height / 2)); + } + parent = parent.parent; + } + input.wait(40); + } + IpcHandler { + target: "settingsTest" + function snapshot(): string { + return JSON.stringify({ + lastDrag:root.lastDrag, + picker:ShellState.wallpaperPickerOpen, + pickerScreen:ShellState.wallpaperWindow.screen.name, + glass:GlassService.state,glassError:GlassService.error,glassBusy:GlassService.busy, + page: ShellState.settingsPage, + data: ConfigService.data, + palette: MatugenService.accent.toString(), + theme: Theme.accent.toString(), + busy: MatugenService.busy, + error: MatugenService.error, + wallpaper: WallpaperService.currentPath, + images: WallpaperService.images, + backend: WallpaperService.backend + }); + } + function color(): bool { + const item = root.child("colorSaturationValue"); + if (!item) + return false; + input.mouseClick(item, item.width * .65, item.height * .35); + return true; + } + function click(name: string): bool { + const item = root.child(name); + if (!item) + return false; + root.reveal(item); + input.mouseClick(item, item.width / 2, item.height / 2); + return true; + } + function dragModule(id: string, lane: string, before: string): bool { + const source=root.child("bar-drag-"+id); + const target=root.child(before ? "bar-drag-"+before : "bar-lane-"+lane); + if(!source || !target)return false; + root.reveal(source); + const end=source.mapFromItem(target,target.width/2,before ? 2 : target.height-10); + input.mousePress(source,source.width/2,source.height/2); + input.mouseMove(source,source.width/2+12,source.height/2,40); + input.mouseMove(source,end.x,end.y,80); + input.wait(80); + const editor=root.child("barEditor");root.lastDrag={id:id,lane:editor.targetLane,before:editor.beforeId,dragging:editor.dragging,x:end.x,y:end.y}; + input.mouseRelease(source,end.x,end.y); + input.wait(80); + return true; + } + function wallpaper(index: int): bool { + const grid = root.child("wallpaperGrid"); + grid.positionViewAtIndex(index, GridView.Contain); + const item = grid.itemAtIndex(index); + if (!item) + return false; + root.reveal(item); + input.mouseClick(item, item.width / 2, item.height / 2); + return true; + } + function search(text: string): int { + ShellState.settingsWindow.openSearch(); + root.child("settingsSearch").text = text; + return ShellState.settingsWindow.searchResults.length; + } + function dragPanel(dx: int, dy: int): string { + const win = ShellState.settingsWindow; + const handle = root.child("settingsDragHandle"); + const start = {x: win.panelX, y: win.panelY}; + const p = handle.mapToItem(null, handle.width / 4, handle.height / 2); + input.mousePress(win.contentItem, p.x, p.y); + for (let i = 0; i < 40 && !win.spanning; i++) + input.wait(25); + const spanned = win.spanning; + input.mouseMove(win.contentItem, start.x + p.x + dx, start.y + p.y + dy, 30); + input.mouseRelease(win.contentItem, start.x + p.x + dx, start.y + p.y + dy); + for (let i = 0; i < 40 && win.spanning; i++) + input.wait(25); + return JSON.stringify({start: start, end: {x: win.panelX, y: win.panelY}, spanned: spanned, spanningAfter: win.spanning, width: win.width, height: win.height}); + } + function searchChoose(index: int): bool { + const result = ShellState.settingsWindow.searchResults[index]; + ShellState.settingsWindow.chooseResult(result); + return !!result; + } + function pickerQuery(text: string): void {input.findChild(ShellState.wallpaperWindow.contentItem,"wallpaperSearch").text=text;} + function pickerSelect(index: int): bool { + const view=input.findChild(ShellState.wallpaperWindow.contentItem,"wallpaperCarousel"); + view.positionViewAtIndex(index,ListView.Contain);input.wait(50); + const item=view.itemAtIndex(index);if(!item)return false; + input.mouseClick(item,item.width/2,item.height/2);input.keyClick(Qt.Key_Return);return true; + } + function pickerScreenshot(path: string): bool {return input.findChild(ShellState.wallpaperWindow.contentItem,"wallpaperPickerSurface").grabToImage(result=>result.saveToFile(path));} + function geometry(name: string): string { + const item = root.child(name); + if (!item) + return "{}"; + const p = item.mapToItem(null, 0, 0); + const parentWidth = item.parent ? item.parent.width : -1; + const chain = []; + for (let node = item.parent, i = 0; node && i < 12; node = node.parent, i++) + chain.push(String(node).split("(")[0] + ":" + Math.round(node.width) + "@" + Math.round(node.mapToItem(null, 0, 0).x)); + return JSON.stringify({x: p.x, width: item.width, scale: item.scale, visualWidth: item.width * item.scale, parentWidth: parentWidth, chain: chain}); + } + function widgetScreenshot(id: string, path: string): bool { + const surface = WidgetState.surfaces[id]; + return !!surface && surface.grabToImage(result => result.saveToFile(path)); + } + function lockScreenshot(index: int, path: string): bool { + const surface = LockState.surfaces[index]; + return !!surface && surface.grabToImage(result => result.saveToFile(path)); + } + function lockSubmit(text: string): bool { + return LockState.submit(text, LockState.previewing ? "preview" : "test"); + } + function lockTest(text: string): bool { + return LockState.test(text); + } + function widgetEdit(id: string): void { + WidgetState.edit(id); + } + function widgetDrag(id: string, dx: int, dy: int): string { + for (const editor of WidgetState.editors) { + const frame = input.findChild(editor, "widgetMove-" + id); + if (!frame) + continue; + // Coordinates relative to the (static) editor; the frame moves while dragging. + const p = frame.mapToItem(editor, 20, 20); + input.mousePress(editor, p.x, p.y); + input.mouseMove(editor, p.x + dx / 2, p.y + dy / 2, 30); + input.mouseMove(editor, p.x + dx, p.y + dy, 30); + input.mouseRelease(editor, p.x + dx, p.y + dy); + input.wait(400); + return JSON.stringify(WidgetState.item(id)); + } + return "{}"; + } + function editorScreenshot(index: int, path: string): bool { + const editor = WidgetState.editors[index]; + return !!editor && editor.grabToImage(result => result.saveToFile(path)); + } + function barScreenshot(path: string): bool { + return barScreenshotAt(0, path); + } + function barScreenshotAt(index: int, path: string): bool { + const pill = ShellState.systemPills[index]; + // Pill → Loader → ModuleRow → bar surface. + const surface = pill ? pill.parent.parent.parent : null; + return !!surface && surface.grabToImage(result => result.saveToFile(path)); + } + function osdScreenshot(path: string): bool { + const surface = input.findChild(ShellState.osdWindow.contentItem, "osdSurface"); + return !!surface && surface.grabToImage(result => result.saveToFile(path)); + } + function screenshot(path: string): bool { + return root.child("settingsSurface").grabToImage(result => result.saveToFile(path)); + } + } +} diff --git a/quickshell/testing/TrayDriver.qml b/quickshell/testing/TrayDriver.qml new file mode 100644 index 0000000..35f40a9 --- /dev/null +++ b/quickshell/testing/TrayDriver.qml @@ -0,0 +1,65 @@ +import QtQuick +import QtTest +import Quickshell +import Quickshell.Io +import "../core" +import "../services" +Item { + id: root + parent: TrayService.windows.length ? TrayService.windows[0].contentItem : null + function icon(id, monitor) { return TrayService.icons.find(i => i.trayItem.id === id && (!monitor || i.barScreen.name === monitor)); } + function menu(depth) { return TrayService.windows.find(w => w.visible && w.depth === depth); } + TestCase { id: input; name: "TrayInputDriver"; when: false } + IpcHandler { + target: "trayTest" + function screens(): string { return JSON.stringify(Quickshell.screens.map(s => s.name)); } + function hover(id: string, monitor: string): bool { + const icon = root.icon(id, monitor); if (!icon) return false; + input.mouseMove(icon, icon.width / 2, icon.height / 2); return true; + } + function leave(id: string, monitor: string): bool { + const icon = root.icon(id, monitor); if (!icon) return false; + input.mouseMove(icon.containingWindow.contentItem, 2, 2); return true; + } + function click(id: string, button: int): bool { + const icon = root.icon(id, ""); if (!icon) return false; + input.mouseClick(icon, icon.width / 2, icon.height / 2, button); return true; + } + function row(depth: int, index: int, click: bool): bool { + const menu = root.menu(depth); if (!menu) return false; + // Rows of a drawer are only clickable once revealed. + const surface = input.findChild(menu.contentItem, "trayMenuSurface"); + for (let i = 0; i < 40 && surface && surface.settled === false; i++) input.wait(25); + const list = input.findChild(menu.contentItem, "trayMenuList"); + list.positionViewAtIndex(index, ListView.Contain); + const item = list.itemAtIndex(index); if (!item) return false; + if (click) input.mouseClick(item, item.width / 2, item.height / 2); + else input.mouseMove(item, item.width / 2, item.height / 2); + return true; + } + // Bar modules by objectName, e.g. the active window pill. + function hoverModule(name: string): bool { + const bar = TrayService.barWindows[0]; if (!bar) return false; + const item = input.findChild(bar.contentItem, name); if (!item) return false; + input.mouseMove(item, item.width / 2, item.height / 2); return true; + } + function leaveBar(): bool { + for (const bar of TrayService.barWindows) input.mouseMove(bar.contentItem, 2, 2); + return TrayService.barWindows.length > 0; + } + function popoutScreenshot(path: string): bool { + if (!PopoutState.window) return false; + return input.findChild(PopoutState.window.contentItem, "barPopoutSurface").grabToImage(result => result.saveToFile(path)); + } + function probe(id: string): string { + const icon = root.icon(id, ""); + const w = icon ? icon.containingWindow : null; + return JSON.stringify({inside: !!icon && icon.pointerInside, screen: icon ? icon.barScreen.name : "", active: !!w && w.active, grabber: !!w && !!w.mouseGrabberItem}); + } + function pressEscape(): void { input.keyClick(Qt.Key_Escape); } + function screenshot(path: string): bool { + const menu = root.menu(0); if (!menu) return false; + return input.findChild(menu.contentItem, "trayMenuSurface").grabToImage(result => result.saveToFile(path)); + } + } +} diff --git a/quickshell/testing/recording_system.py b/quickshell/testing/recording_system.py new file mode 100644 index 0000000..3773bfd --- /dev/null +++ b/quickshell/testing/recording_system.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python3 +"""Test-only system adapter. Never executes commands or accesses system buses.""" +import json,os,sys +from pathlib import Path +base=Path(os.environ['GLASSMXRPH_SYSTEM_EVENTS']);saved=base.with_suffix('.state.json') +default={'brightness':{'available':True,'value':40,'devices':[]},'nightLight':{'available':True,'enabled':False},'dnd':{'available':True,'enabled':False},'profiles':{'available':True,'current':'balanced','profiles':['power-saver','balanced','performance']},'power':{'available':True,'lock':True,'logout':True,'suspend':True,'reboot':True,'shutdown':True}} +state=json.loads(saved.read_text()) if saved.exists() else default +req=json.loads(sys.argv[1]) +if req['op']=='action' and base.with_suffix('.fail').exists(): + print(json.dumps({'ok':False,'error':'Synthetic provider failure'}));sys.exit(1) +if req['op']=='action': + with base.open('a') as f:f.write(json.dumps(req)+'\n') + kind=req['action'];value=req.get('value') + if kind in ['nightLight','dnd']:state[kind]['enabled']=value + elif kind=='brightness':state[kind]['value']=value + elif kind=='profile':state['profiles']['current']=value + saved.write_text(json.dumps(state)) +print(json.dumps({'ok':True,'state':state})) diff --git a/quickshell/theme/ColorLogic.js b/quickshell/theme/ColorLogic.js new file mode 100644 index 0000000..0c24acd --- /dev/null +++ b/quickshell/theme/ColorLogic.js @@ -0,0 +1,6 @@ +function luminance(r,g,b) { + const channel=v=>v<=0.04045 ? v/12.92 : Math.pow((v+0.055)/1.055,2.4); + return 0.2126*channel(r)+0.7152*channel(g)+0.0722*channel(b); +} +function contrast(a,b) {return (Math.max(a,b)+0.05)/(Math.min(a,b)+0.05);} +function darkForeground(r,g,b) {const l=luminance(r,g,b);return contrast(l,0)>=contrast(l,1);} diff --git a/quickshell/theme/Icons.qml b/quickshell/theme/Icons.qml new file mode 100644 index 0000000..eef0c28 --- /dev/null +++ b/quickshell/theme/Icons.qml @@ -0,0 +1,12 @@ +pragma Singleton +import QtQuick +import Quickshell + +// Nerd Font glyphs are optional; callers supply a plain-text fallback. +Singleton { + readonly property string family: { + const families = Qt.fontFamilies(); + return families.find(f => f === "Symbols Nerd Font") || families.find(f => /Nerd Font/.test(f) && !/Mono/.test(f)) || families.find(f => /Nerd Font/.test(f)) || ""; + } + readonly property bool available: family !== "" +} diff --git a/quickshell/theme/MatugenService.qml b/quickshell/theme/MatugenService.qml new file mode 100644 index 0000000..3fe8f0e --- /dev/null +++ b/quickshell/theme/MatugenService.qml @@ -0,0 +1,146 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Io +import "../services" + +Singleton { + id: root + property color accent: "transparent" + property color accentText: "transparent" + property bool available: false + property string error: "" + property string version: "" + property var schemes: [] + property int generation: 0 + property var pending: null + readonly property bool busy: worker.running || pending !== null + readonly property string palettePath: (Quickshell.env("XDG_STATE_HOME") || Quickshell.env("HOME") + "/.local/state") + "/glassMxrph/palette.json" + readonly property string optionsKey: ConfigService.ready ? JSON.stringify([ConfigService.data.appearance.accentSource, ConfigService.data.matugen.executable, ConfigService.data.matugen.scheme, ConfigService.data.matugen.contrast]) : "" + readonly property string sourcePath: WallpaperService.palettePath + onOptionsKeyChanged: { + generation++; + pending = null; + if (ConfigService.ready && ConfigService.data.appearance.accentSource === "matugen") { + probe(); + if (sourcePath) + regenerate(); + else + WallpaperService.refresh(); + } + } + onSourcePathChanged: if (ConfigService.ready && ConfigService.data.matugen.regenerateOnWallpaperChange) + regenerate() + function probe() { + if (ConfigService.ready) + probeJob.start({ + action: "matugen-probe", + executable: ConfigService.data.matugen.executable + }); + } + function regenerate() { + if (!ConfigService.ready || ConfigService.data.appearance.accentSource !== "matugen") + return false; + if (!sourcePath) { + error = "Select a wallpaper, then regenerate its palette."; + return false; + } + generation++; + pending = { + action: "palette", + generation: generation, + path: sourcePath, + executable: ConfigService.data.matugen.executable, + scheme: ConfigService.data.matugen.scheme, + contrast: ConfigService.data.matugen.contrast + }; + debounce.restart(); + return true; + } + function launchPending() { + if (!worker.running && pending) { + const next = pending; + pending = null; + worker.start(next); + } + } + Timer { + id: debounce + interval: 200 + onTriggered: root.launchPending() + } + ProviderJob { + id: probeJob + onFinished: (request, result) => { + if (request.executable !== ConfigService.data.matugen.executable) { + Qt.callLater(root.probe); + return; + } + if (result.ok) { + root.version = result.version; + root.schemes = result.schemes; + } else { + root.version = ""; + root.schemes = []; + root.error = result.error; + } + } + } + ProviderJob { + id: worker + onFinished: (request, result) => { + if (request.generation === root.generation) { + if (result.ok) { + root.version = result.version; + palette.setText(JSON.stringify(result.palette) + "\n"); + root.error = ""; + } else + root.error = result.error; + } + Qt.callLater(root.launchPending); + } + } + FileView { + id: palette + path: root.palettePath + watchChanges: true + atomicWrites: true + printErrors: false + onFileChanged: reload() + onSaved: root.loadPalette() + onLoaded: root.loadPalette() + onSaveFailed: error => root.error = "Could not save generated palette (" + error + ")" + } + function loadPalette() { + try { + const data = JSON.parse(palette.text()); + if (!/^#[0-9a-fA-F]{6}$/.test(data.accent)) + throw Error("Invalid palette accent"); + if (data.accentText !== undefined && !/^#[0-9a-fA-F]{6}$/.test(data.accentText)) + throw Error("Invalid palette accent text"); + root.accent = data.accent; + root.accentText = data.accentText || "transparent"; + root.available = true; + root.error = ""; + } catch (error) { + root.error = String(error); + } + } + + IpcHandler { + target: "theme" + function regenerate(): bool { + return root.regenerate(); + } + function status(): string { + return JSON.stringify({ + generation: root.generation, + busy: root.busy, + error: root.error, + available: root.available, + version: root.version, + accent: root.accent.toString() + }); + } + } +} diff --git a/quickshell/theme/Theme.qml b/quickshell/theme/Theme.qml new file mode 100644 index 0000000..e571ae1 --- /dev/null +++ b/quickshell/theme/Theme.qml @@ -0,0 +1,53 @@ +pragma Singleton +import QtQuick +import Quickshell +import "../services" +import "ColorLogic.js" as ColorLogic + +Singleton { + id: root + property color accent: ThemeManager.accent + Behavior on accent { + ColorAnimation { + duration: Theme.duration + } + } + readonly property color accentHover: Qt.lighter(accent, 1.12) + // Same hue, lifted so dark accents stay visible as fills on dark glass. + readonly property color accentVivid: accent.hslLightness < 0.5 ? Qt.hsla(accent.hslHue, accent.hslSaturation, 0.6, 1) : accent + readonly property color accentPressed: Qt.darker(accent, 1.12) + readonly property color accentDarkText: "#000000" + readonly property color accentLightText: "#ffffff" + readonly property color accentText: textOn(accent) + readonly property color accentHoverText: textOn(accentHover) + readonly property color accentPressedText: textOn(accentPressed) + function textOn(background) { + const palette = MatugenService.accentText; + const base = ColorLogic.luminance(background.r, background.g, background.b); + if (ThemeManager.source === "matugen" && MatugenService.available && palette.a > 0 && ColorLogic.contrast(base, ColorLogic.luminance(palette.r, palette.g, palette.b)) >= 4.5) + return palette; + return ColorLogic.darkForeground(background.r, background.g, background.b) ? accentDarkText : accentLightText; + } + // Glass tint, like Ghostty's `background`: panels use it at the configured + // opacity, controls and cards are translucent shades of it (never grey overlays). + readonly property color tint: ConfigService.ready && /^#[0-9a-fA-F]{6}$/.test(ConfigService.data.appearance.glassTint) ? ConfigService.data.appearance.glassTint : "#000000" + readonly property color surface: tint + readonly property color surfaceVariant: Qt.alpha(tint, 0.38) + readonly property color fill: Qt.alpha(tint, 0.22) + readonly property color hover: Qt.alpha(text, 0.09) + readonly property color hairline: Qt.alpha(text, 0.08) + readonly property color text: "#f6f6f6" + readonly property color textSecondary: "#bdbdbd" + readonly property color transparent: "transparent" + readonly property color urgent: "#f6b86b" + readonly property color shadow: "#10000000" + readonly property real panelOpacity: ConfigService.ready ? ConfigService.data.appearance.panelOpacity : 0.86 + readonly property real intensity: ConfigService.ready ? (ConfigService.data.animation.reducedMotion ? 0 : ConfigService.data.animation.intensity) : 1 + readonly property real glassOpacity: ConfigService.ready ? ConfigService.data.appearance.glassOpacity : 0.76 + readonly property real borderOpacity: ConfigService.ready ? ConfigService.data.appearance.borderOpacity : 0.18 + readonly property real radius: ConfigService.ready ? ConfigService.data.appearance.radius : 22 + readonly property color border: Qt.alpha(text, borderOpacity) + readonly property bool highlights: !ConfigService.ready || ConfigService.data.appearance.highlights + readonly property bool shadows: !ConfigService.ready || ConfigService.data.appearance.shadows + readonly property int duration: ConfigService.ready ? (ConfigService.data.animation.reducedMotion ? 0 : ConfigService.data.animation.duration) : 220 +} diff --git a/quickshell/theme/ThemeManager.qml b/quickshell/theme/ThemeManager.qml new file mode 100644 index 0000000..1cdc206 --- /dev/null +++ b/quickshell/theme/ThemeManager.qml @@ -0,0 +1,10 @@ +pragma Singleton +import QtQuick +import Quickshell +import "../services" +Singleton { + SystemPalette { id: systemPalette; colorGroup: SystemPalette.Active } + readonly property string source: ConfigService.ready ? ConfigService.data.appearance.accentSource : "system" + readonly property color accent: source === "custom" ? ConfigService.data.appearance.customAccent : source === "matugen" && MatugenService.available ? MatugenService.accent : systemPalette.highlight + readonly property string status: source === "matugen" ? (MatugenService.busy ? "Generating wallpaper palette…" : MatugenService.available ? "Wallpaper palette · neutral glass surfaces" : "Waiting for a wallpaper palette; using system accent") : source +} diff --git a/quickshell/theme/qmldir b/quickshell/theme/qmldir new file mode 100644 index 0000000..93d5a2f --- /dev/null +++ b/quickshell/theme/qmldir @@ -0,0 +1,4 @@ +singleton MatugenService 1.0 MatugenService.qml +singleton Theme 1.0 Theme.qml +singleton ThemeManager 1.0 ThemeManager.qml +singleton Icons 1.0 Icons.qml diff --git a/quickshell/wallpaper/WallpaperBackground.qml b/quickshell/wallpaper/WallpaperBackground.qml new file mode 100644 index 0000000..cf5b891 --- /dev/null +++ b/quickshell/wallpaper/WallpaperBackground.qml @@ -0,0 +1,25 @@ +import QtQuick +import Quickshell +import Quickshell.Wayland +import "../services" +import "../theme" +// qmllint disable uncreatable-type +PanelWindow { + id:root + required property var modelData + screen:modelData + anchors {top:true;bottom:true;left:true;right:true} + color:Theme.surface + exclusionMode:ExclusionMode.Ignore + WlrLayershell.layer:WlrLayer.Background + WlrLayershell.namespace:"glassMxrph-wallpaper" + mask:Region {} + Image { + anchors.fill:parent + source:ConfigService.ready && ConfigService.data.wallpaper.byMonitor[root.modelData.name] ? "file://"+encodeURI(ConfigService.data.wallpaper.byMonitor[root.modelData.name]).replace(/#/g,"%23").replace(/\?/g,"%3F") : "" + sourceSize:Qt.size(parent.width,parent.height) + asynchronous:true + retainWhileLoading:true + fillMode:Image.PreserveAspectCrop + } +} diff --git a/quickshell/wallpaper/WallpaperPicker.qml b/quickshell/wallpaper/WallpaperPicker.qml new file mode 100644 index 0000000..7a39b17 --- /dev/null +++ b/quickshell/wallpaper/WallpaperPicker.qml @@ -0,0 +1,116 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import Quickshell +import Quickshell.Wayland +import "../components" +import "../services" +import "../core" +import "../theme" +// qmllint disable uncreatable-type +PanelWindow { + id:root + screen:ScreenService.current(ShellState.wallpaperScreen) + // Hangs from the middle of the bar as a drawer; the layer starts at the + // screen top so the bar join is inside its box. + anchors {top:true} + readonly property real screenWidth:screen ? screen.width : 1920 + readonly property real screenHeight:screen ? screen.height : 1080 + implicitWidth:Math.round(surface.width) + implicitHeight:Math.round(BarDrawers.bottom+surface.contentHeight) + visible:ShellState.wallpaperPickerOpen || surface.shown + color:Theme.transparent + exclusionMode:ExclusionMode.Ignore + WlrLayershell.namespace:"glassMxrph-wallpaper-picker" + WlrLayershell.layer:WlrLayer.Overlay + WlrLayershell.keyboardFocus:ShellState.wallpaperPickerOpen ? WlrKeyboardFocus.Exclusive : WlrKeyboardFocus.None + Component.onCompleted:ShellState.wallpaperWindow=root + Component.onDestruction:ShellState.wallpaperWindow=null + property string filter:"all" + readonly property var results:WallpaperService.images.filter(i=>(filter!=="history" || ConfigService.data.wallpaper.history.includes(i.path)) && (!search.text || i.name.toLowerCase().includes(search.text.toLowerCase()))) + function applyCurrent() {if(root.results[view.currentIndex])WallpaperService.apply(root.results[view.currentIndex].path);} + Connections { + target:ShellState + function onWallpaperPickerOpenChanged() { + if(ShellState.wallpaperPickerOpen) { + WallpaperService.refresh();WallpaperService.scan(); + Qt.callLater(()=>view.forceActiveFocus()); + } + } + } + // Exclusive focus routes outside clicks here (see ControlCenter). + MouseArea {x:-20000;y:-20000;width:40000;height:40000;onPressed:ShellState.wallpaperPickerOpen=false} + BarDrawer { + id:surface + objectName:"wallpaperPickerSurface" + y:BarDrawers.bottom + open:ShellState.wallpaperPickerOpen + contentWidth:Math.min(1240,root.screenWidth-2*(BarDrawers.margin+BarDrawers.radius+ear)) + contentHeight:Math.min(590,root.screenHeight-BarDrawers.bottom-40) + drawerId:"wallpaper" + screenName:root.screen ? root.screen.name : "" + screenX:(root.screenWidth-width)/2 + MouseArea {anchors.fill:parent} + ColumnLayout { + anchors.fill:parent;anchors.margins:22;spacing:18 + RowLayout { + Layout.fillWidth:true + Text {text:"Wallpapers";color:Theme.text;font.pixelSize:24;Layout.fillWidth:true} + GlassComboBox { + Layout.preferredWidth:160 + model:["all","primary"].concat(Quickshell.screens.map(s=>s.name)) + currentIndex:Math.max(0,model.indexOf(WallpaperService.selectedMonitor)) + onActivated:WallpaperService.selectedMonitor=currentText + } + GlassIconButton {text:"⚙";onClicked:ShellState.openSettings("wallpaper");Accessible.name:"Wallpaper settings"} + GlassIconButton {text:"×";onClicked:ShellState.wallpaperPickerOpen=false;Accessible.name:"Close picker"} + } + RowLayout { + GlassButton {text:"All";accented:root.filter==="all";onClicked:root.filter="all"} + GlassButton {text:"History";accented:root.filter==="history";onClicked:root.filter="history"} + GlassTextField {id:search;objectName:"wallpaperSearch";Layout.fillWidth:true;placeholderText:"Search wallpapers…";onTextChanged:view.currentIndex=0;Keys.onEscapePressed:ShellState.wallpaperPickerOpen=false;Keys.onDownPressed:view.forceActiveFocus()} + GlassIconButton {text:"↻";onClicked:WallpaperService.scan();Accessible.name:"Refresh wallpapers"} + } + ListView { + id:view + objectName:"wallpaperCarousel" + Layout.fillWidth:true;Layout.fillHeight:true + orientation:ListView.Horizontal + spacing:14 + clip:true + model:root.results + snapMode:ListView.SnapToItem + boundsBehavior:Flickable.StopAtBounds + highlightMoveDuration:Theme.duration + preferredHighlightBegin:width/2-125 + preferredHighlightEnd:width/2+125 + highlightRangeMode:ListView.ApplyRange + keyNavigationEnabled:true + ScrollBar.horizontal:ScrollBar {} + Keys.onReturnPressed:root.applyCurrent() + Keys.onEnterPressed:root.applyCurrent() + Keys.onEscapePressed:ShellState.wallpaperPickerOpen=false + delegate:GlassPanel { + id:tile + required property var modelData + required property int index + width:250;height:view.height-10 + radius:18 + border.width:2 + border.color:view.currentIndex===index ? Theme.accent : Theme.border + Image {anchors.fill:parent;anchors.margins:6;source:tile.modelData.url;sourceSize:Qt.size(500,700);asynchronous:true;fillMode:Image.PreserveAspectCrop;clip:true} + Rectangle {anchors.bottom:parent.bottom;anchors.left:parent.left;anchors.right:parent.right;anchors.margins:6;height:42;color:Qt.alpha(Theme.surface,0.85) + Text {anchors.fill:parent;anchors.margins:10;text:(WallpaperService.currentPath===tile.modelData.path?"✓ ":"")+tile.modelData.name;color:Theme.text;elide:Text.ElideMiddle} + } + MouseArea {anchors.fill:parent;onClicked:{view.currentIndex=tile.index;view.forceActiveFocus();}onDoubleClicked:WallpaperService.apply(tile.modelData.path)} + } + } + Text {visible:!root.results.length;text:WallpaperService.scanning ? "Loading wallpapers…" : "No wallpapers here. Choose a folder in Wallpaper settings.";color:Theme.textSecondary;Layout.fillWidth:true;wrapMode:Text.Wrap} + RowLayout { + Text {text:WallpaperService.error || (WallpaperService.busy?"Applying wallpaper…":"← → Browse · Enter or double-click to apply · Esc Close");color:WallpaperService.error?Theme.urgent:Theme.textSecondary;Layout.fillWidth:true;wrapMode:Text.Wrap} + GlassButton {objectName:"pickerApply";text:"Apply wallpaper";accented:true;enabled:root.results.length>0 && !WallpaperService.busy;onClicked:root.applyCurrent()} + } + } + } +} diff --git a/quickshell/widgets/DesktopWidget.qml b/quickshell/widgets/DesktopWidget.qml new file mode 100644 index 0000000..2185a28 --- /dev/null +++ b/quickshell/widgets/DesktopWidget.qml @@ -0,0 +1,75 @@ +pragma ComponentBehavior: Bound +import QtQuick +import Quickshell +import Quickshell.Wayland +import "../components" +import "../services" +import "../theme" + +// One desktop widget: its own layer surface on the desktop (Bottom) layer, +// sized and placed from its item (or the live draft while it is edited). +// Right-click opens the widget editor with this widget selected. +// qmllint disable uncreatable-type +PanelWindow { + id: root + required property string modelData + readonly property string widgetId: modelData + readonly property var item: WidgetState.item(widgetId) + readonly property var type: item ? WidgetRegistry.type(item.type) : null + readonly property var geometry: WidgetState.rect(widgetId) + readonly property bool transparentFace: !!item && WidgetRegistry.transparent(item.type, item.variant) + // Kept separate from `screen`, which Quickshell itself assigns on show + // (reading it in `visible` would loop). + readonly property var output: item ? Quickshell.screens.find(s => s.name === item.monitor) || null : null + screen: output + readonly property bool desktopShown: WidgetState.editing || !output || !HyprlandService.coveredMonitors.includes(output.name) + visible: !!item && !!type && !!output + anchors { + top: true + left: true + } + // Margins is present at runtime but unresolved in 0.3.1 qmltypes. + // qmllint disable unqualified unresolved-type + margins { + left: Math.round(root.geometry.x) + top: Math.round(root.geometry.y) + } + // qmllint enable unqualified unresolved-type + implicitWidth: Math.max(1, Math.round(geometry.w)) + implicitHeight: Math.max(1, Math.round(geometry.h)) + color: Theme.transparent + exclusionMode: ExclusionMode.Ignore + WlrLayershell.layer: WlrLayer.Bottom + WlrLayershell.namespace: "glassMxrph-widget-" + (item ? item.type : "unknown") + WlrLayershell.keyboardFocus: type && type.keyboard ? WlrKeyboardFocus.OnDemand : WlrKeyboardFocus.None + Component.onCompleted: WidgetState.surfaces[widgetId] = content + Component.onDestruction: delete WidgetState.surfaces[widgetId] + + Item { + id: content + anchors.fill: parent + opacity: root.item ? root.item.opacity : 1 + GlassPanel { + anchors.fill: parent + visible: !root.transparentFace + } + Loader { + id: face + anchors.fill: parent + active: !!root.item && !!root.type + source: root.item ? WidgetRegistry.source(root.item.type) : "" + onLoaded: { + item.widgetId = Qt.binding(() => root.widgetId); + item.kind = Qt.binding(() => root.item ? root.item.type : ""); + item.variant = Qt.binding(() => root.item ? root.item.variant : ""); + item.options = Qt.binding(() => root.item && root.item.options ? root.item.options : ({})); + item.desktopVisible = Qt.binding(() => root.desktopShown); + } + } + MouseArea { + anchors.fill: parent + acceptedButtons: Qt.RightButton + onClicked: WidgetState.edit(root.widgetId) + } + } +} diff --git a/quickshell/widgets/DesktopWidgets.qml b/quickshell/widgets/DesktopWidgets.qml new file mode 100644 index 0000000..a8f4e2d --- /dev/null +++ b/quickshell/widgets/DesktopWidgets.qml @@ -0,0 +1,25 @@ +import QtQuick +import Quickshell + +// One surface per configured desktop widget. The model is the list of ids, so +// editing an item updates its existing surface instead of recreating it. +Scope { + id: root + // Widgets are created shortly after startup: building many faces while + // Quickshell 0.3.1 parses its first Hyprland client list makes a crash in + // HyprlandToplevel::updateFromObject far more likely. + property bool started: false + Timer { + running: true + interval: 1500 + onTriggered: root.started = true + } + Variants { + model: root.started ? WidgetState.items.filter(i => !!WidgetRegistry.type(i.type)).map(i => i.id) : [] + DesktopWidget {} + } + Variants { + model: WidgetState.editing ? Quickshell.screens : [] + WidgetEditor {} + } +} diff --git a/quickshell/widgets/WidgetEditor.qml b/quickshell/widgets/WidgetEditor.qml new file mode 100644 index 0000000..e902df5 --- /dev/null +++ b/quickshell/widgets/WidgetEditor.qml @@ -0,0 +1,554 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Layouts +import Quickshell +import Quickshell.Wayland +import "../components" +import "../services" +import "../theme" +import "../services/WidgetLogic.js" as Logic + +// Desktop widget editor for one output (after Serpantinum's widget redactor): +// drag to move, handles to resize, snapping guides or a grid, a toolbar to add +// widgets and an inspector for the selected one. The real widget surfaces sit +// below and follow every change live. +// qmllint disable uncreatable-type +PanelWindow { + id: root + required property var modelData + screen: modelData + anchors { + top: true + bottom: true + left: true + right: true + } + color: Theme.transparent + exclusionMode: ExclusionMode.Ignore + WlrLayershell.layer: WlrLayer.Overlay + WlrLayershell.namespace: "glassMxrph-widget-editor" + WlrLayershell.keyboardFocus: WlrKeyboardFocus.Exclusive + Component.onCompleted: WidgetState.editors = WidgetState.editors.concat([keys]) + Component.onDestruction: WidgetState.editors = WidgetState.editors.filter(e => e !== keys) + + readonly property var bounds: ({ + w: width, + h: height + }) + readonly property var onScreen: WidgetState.items.filter(i => i.monitor === screen.name && !!WidgetRegistry.type(i.type)) + readonly property var selectedItem: WidgetState.item(WidgetState.selected) + readonly property var selectedType: selectedItem ? WidgetRegistry.type(selectedItem.type) : null + readonly property bool selectionHere: !!selectedItem && selectedItem.monitor === screen.name + readonly property var selectedRect: selectionHere ? WidgetState.rect(selectedItem.id) : null + // Move the toolbar and inspector to the top when they would cover the selection. + readonly property bool chromeOnTop: !!selectedRect && height > 0 && selectedRect.y + selectedRect.h > height - 280 + readonly property int gridStep: WidgetState.grid ? WidgetState.gridSize : 0 + property var guides: ({ + x: [], + y: [] + }) + function others(id) { + return onScreen.filter(i => i.id !== id).map(i => WidgetState.rect(i.id)); + } + function nudge(dx, dy) { + if (!selectionHere) + return; + const r = WidgetState.rect(selectedItem.id); + WidgetState.setDraft(selectedItem.id, Logic.clampRect({ + x: r.x + dx, + y: r.y + dy, + w: r.w, + h: r.h + }, bounds)); + WidgetState.commit(selectedItem.id); + } + + Item { + id: keys + anchors.fill: parent + focus: true + Component.onCompleted: forceActiveFocus() + Keys.onPressed: event => { + const step = event.modifiers & Qt.ShiftModifier ? 10 : 1; + if (event.key === Qt.Key_Escape) { + if (WidgetState.selected) + WidgetState.selected = ""; + else + WidgetState.done(); + } else if ((event.key === Qt.Key_Delete || event.key === Qt.Key_Backspace) && root.selectionHere) + WidgetState.remove(root.selectedItem.id); + else if (event.key === Qt.Key_Left) + root.nudge(-step, 0); + else if (event.key === Qt.Key_Right) + root.nudge(step, 0); + else if (event.key === Qt.Key_Up) + root.nudge(0, -step); + else if (event.key === Qt.Key_Down) + root.nudge(0, step); + else + return; + event.accepted = true; + } + + Rectangle { + anchors.fill: parent + color: Qt.alpha("#000000", 0.3) + } + Canvas { + id: gridLines + anchors.fill: parent + visible: WidgetState.grid + readonly property color line: Qt.alpha(Theme.text, 0.07) + onVisibleChanged: requestPaint() + onPaint: { + const ctx = getContext("2d"); + ctx.reset(); + ctx.strokeStyle = line; + ctx.lineWidth = 1; + ctx.beginPath(); + for (let x = WidgetState.gridSize; x < width; x += WidgetState.gridSize) { + ctx.moveTo(x + 0.5, 0); + ctx.lineTo(x + 0.5, height); + } + for (let y = WidgetState.gridSize; y < height; y += WidgetState.gridSize) { + ctx.moveTo(0, y + 0.5); + ctx.lineTo(width, y + 0.5); + } + ctx.stroke(); + } + } + MouseArea { + anchors.fill: parent + onPressed: { + WidgetState.selected = ""; + keys.forceActiveFocus(); + } + } + Repeater { + model: root.guides.x + Rectangle { + required property real modelData + x: modelData + width: 1 + height: parent.height + color: Theme.accent + } + } + Repeater { + model: root.guides.y + Rectangle { + required property real modelData + y: modelData + height: 1 + width: parent.width + color: Theme.accent + } + } + + // One frame per widget on this output. + Repeater { + model: root.onScreen.map(i => i.id) + Item { + id: proxy + required property string modelData + readonly property var item: WidgetState.item(modelData) + readonly property var geometry: WidgetState.rect(modelData) + readonly property bool selected: WidgetState.selected === modelData + x: geometry.x + y: geometry.y + width: geometry.w + height: geometry.h + z: selected ? 2 : 1 + + Rectangle { + anchors.fill: parent + radius: Math.min(Theme.radius, width / 2, height / 2) + color: proxy.selected ? Qt.alpha(Theme.accent, 0.1) : move.containsMouse ? Qt.alpha(Theme.text, 0.06) : Theme.transparent + border.width: proxy.selected ? 2 : 1 + border.color: proxy.selected ? Theme.accent : Qt.alpha(Theme.text, move.containsMouse ? 0.6 : 0.3) + } + Rectangle { + visible: proxy.selected || move.containsMouse + y: proxy.y > 30 ? -26 : proxy.height + 4 + implicitWidth: label.implicitWidth + 16 + implicitHeight: 22 + radius: 11 + color: proxy.selected ? Theme.accent : Qt.alpha(Theme.tint, 0.75) + Text { + id: label + anchors.centerIn: parent + text: proxy.item ? WidgetRegistry.type(proxy.item.type).name + " " + Math.round(proxy.geometry.w) + "×" + Math.round(proxy.geometry.h) : "" + color: proxy.selected ? Theme.accentText : Theme.text + font.pixelSize: 11 + } + } + MouseArea { + id: move + objectName: "widgetMove-" + proxy.modelData + anchors.fill: parent + hoverEnabled: true + cursorShape: pressed ? Qt.ClosedHandCursor : Qt.OpenHandCursor + property point start + property var startRect + onPressed: mouse => { + WidgetState.selected = proxy.modelData; + keys.forceActiveFocus(); + start = mapToItem(null, mouse.x, mouse.y); + startRect = proxy.geometry; + } + onPositionChanged: mouse => { + if (!pressed) + return; + const p = mapToItem(null, mouse.x, mouse.y); + const snapped = Logic.snapMove({ + x: startRect.x + p.x - start.x, + y: startRect.y + p.y - start.y, + w: startRect.w, + h: startRect.h + }, root.others(proxy.modelData), root.bounds, root.gridStep, 10); + WidgetState.setDraft(proxy.modelData, snapped); + root.guides = snapped.guides; + } + onReleased: { + WidgetState.commit(proxy.modelData); + root.guides = { + x: [], + y: [] + }; + } + } + // Corner and edge handles. + Repeater { + model: proxy.selected ? [ + { + fx: 0, + fy: 0, + edges: { + left: true, + top: true + }, + cursor: Qt.SizeFDiagCursor + }, + { + fx: 0.5, + fy: 0, + edges: { + top: true + }, + cursor: Qt.SizeVerCursor + }, + { + fx: 1, + fy: 0, + edges: { + right: true, + top: true + }, + cursor: Qt.SizeBDiagCursor + }, + { + fx: 1, + fy: 0.5, + edges: { + right: true + }, + cursor: Qt.SizeHorCursor + }, + { + fx: 1, + fy: 1, + edges: { + right: true, + bottom: true + }, + cursor: Qt.SizeFDiagCursor + }, + { + fx: 0.5, + fy: 1, + edges: { + bottom: true + }, + cursor: Qt.SizeVerCursor + }, + { + fx: 0, + fy: 1, + edges: { + left: true, + bottom: true + }, + cursor: Qt.SizeBDiagCursor + }, + { + fx: 0, + fy: 0.5, + edges: { + left: true + }, + cursor: Qt.SizeHorCursor + } + ] : [] + Rectangle { + id: handle + required property var modelData + x: proxy.width * modelData.fx - width / 2 + y: proxy.height * modelData.fy - height / 2 + width: 14 + height: 14 + radius: 7 + color: Theme.text + border.width: 2 + border.color: Theme.accent + MouseArea { + anchors.fill: parent + anchors.margins: -4 + cursorShape: handle.modelData.cursor + property point start + property var startRect + onPressed: mouse => { + start = mapToItem(null, mouse.x, mouse.y); + startRect = proxy.geometry; + } + onPositionChanged: mouse => { + if (!pressed) + return; + const p = mapToItem(null, mouse.x, mouse.y); + WidgetState.setDraft(proxy.modelData, Logic.resizeRect(startRect, p.x - start.x, p.y - start.y, handle.modelData.edges, WidgetState.limits(proxy.item.type), root.bounds, root.gridStep)); + } + onReleased: WidgetState.commit(proxy.modelData) + } + } + } + } + } + + // Toolbar and inspector, stacked at the bottom (or top, away from the selection). + Column { + id: chrome + // Above every widget frame. + z: 10 + anchors.horizontalCenter: parent.horizontalCenter + // Plain y (not switched anchors, which do not reliably reset). + y: root.chromeOnTop ? (ConfigService.ready ? ConfigService.data.bar.margin + ConfigService.data.bar.height : 48) + 20 : parent.height - height - 28 + width: Math.min(root.width - 48, 900) + spacing: 12 + + // Inspector for the selected widget. + GlassPanel { + id: inspector + objectName: "widgetInspector" + visible: root.selectionHere + surfaceOpacity: Math.max(Theme.panelOpacity, 0.8) + anchors.horizontalCenter: parent.horizontalCenter + width: Math.min(chrome.width, 520) + height: inspectorBody.implicitHeight + 28 + MouseArea { + anchors.fill: parent + } + ColumnLayout { + id: inspectorBody + anchors.left: parent.left + anchors.right: parent.right + anchors.top: parent.top + anchors.margins: 14 + spacing: 10 + RowLayout { + Layout.fillWidth: true + spacing: 10 + GlassIcon { + size: 32 + glyph: root.selectedType ? root.selectedType.icon : "" + fallback: root.selectedType ? root.selectedType.name.charAt(0) : "" + active: true + } + Text { + text: root.selectedType ? root.selectedType.name : "" + color: Theme.text + font.pixelSize: 14 + font.weight: Font.DemiBold + Layout.fillWidth: true + } + GlassButton { + text: "Duplicate" + onClicked: WidgetState.duplicate(root.selectedItem.id) + } + GlassButton { + objectName: "widgetDelete" + text: "Delete" + onClicked: WidgetState.remove(root.selectedItem.id) + } + } + RowLayout { + visible: !!root.selectedItem && WidgetRegistry.variants(root.selectedItem.type).length > 1 + Layout.fillWidth: true + Text { + text: "Style" + color: Theme.textSecondary + font.pixelSize: 12 + Layout.preferredWidth: 70 + } + GlassSegmented { + model: root.selectedItem ? WidgetRegistry.variants(root.selectedItem.type) : [] + currentIndex: root.selectedItem ? model.indexOf(root.selectedItem.variant) : -1 + onActivated: (index, value) => WidgetState.update(root.selectedItem.id, { + variant: value + }) + } + Item { + Layout.fillWidth: true + } + } + RowLayout { + Layout.fillWidth: true + Text { + text: "Opacity" + color: Theme.textSecondary + font.pixelSize: 12 + Layout.preferredWidth: 70 + } + GlassSlider { + Layout.fillWidth: true + from: 0.1 + to: 1 + stepSize: 0.05 + value: root.selectedItem ? root.selectedItem.opacity : 1 + onMoved: WidgetState.update(root.selectedItem.id, { + opacity: Math.round(value * 100) / 100 + }) + } + Text { + text: root.selectedItem ? Math.round(root.selectedItem.opacity * 100) + "%" : "" + color: Theme.textSecondary + font.pixelSize: 12 + Layout.preferredWidth: 40 + horizontalAlignment: Text.AlignRight + } + } + Repeater { + model: root.selectedType && root.selectedType.options ? root.selectedType.options : [] + RowLayout { + id: option + required property var modelData + readonly property var current: root.selectedItem && root.selectedItem.options ? root.selectedItem.options[modelData.id] : undefined + Layout.fillWidth: true + Text { + text: option.modelData.label + color: Theme.textSecondary + font.pixelSize: 12 + Layout.fillWidth: option.modelData.kind === "toggle" + Layout.preferredWidth: option.modelData.kind === "toggle" ? -1 : 150 + wrapMode: Text.Wrap + } + GlassToggle { + visible: option.modelData.kind === "toggle" + checked: !!option.current + onToggled: WidgetState.setOption(root.selectedItem.id, option.modelData.id, checked) + } + GlassTextField { + visible: option.modelData.kind === "text" + Layout.fillWidth: true + text: option.current || "" + onEditingFinished: WidgetState.setOption(root.selectedItem.id, option.modelData.id, text.trim()) + Keys.onEscapePressed: keys.forceActiveFocus() + } + } + } + } + } + + // Add widgets, grid toggle and Done. + GlassPanel { + objectName: "widgetToolbar" + surfaceOpacity: Math.max(Theme.panelOpacity, 0.8) + width: chrome.width + height: toolbarBody.implicitHeight + 24 + MouseArea { + anchors.fill: parent + } + ColumnLayout { + id: toolbarBody + anchors.left: parent.left + anchors.right: parent.right + anchors.top: parent.top + anchors.margins: 12 + spacing: 10 + Flow { + Layout.preferredWidth: chrome.width - 24 + Layout.fillWidth: true + spacing: 6 + Repeater { + model: WidgetRegistry.order + Rectangle { + id: adder + required property string modelData + readonly property var type: WidgetRegistry.type(modelData) + objectName: "widgetAdd-" + modelData + width: 64 + height: 62 + radius: 12 + color: addArea.containsMouse ? Theme.hover : Theme.transparent + Column { + anchors.centerIn: parent + spacing: 4 + GlassIcon { + anchors.horizontalCenter: parent.horizontalCenter + size: 34 + glyph: adder.type.icon + fallback: adder.type.name.charAt(0) + } + Text { + anchors.horizontalCenter: parent.horizontalCenter + width: 60 + horizontalAlignment: Text.AlignHCenter + elide: Text.ElideRight + text: adder.type.name + color: Theme.textSecondary + font.pixelSize: 10 + } + } + MouseArea { + id: addArea + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: { + WidgetState.add(adder.modelData, root.screen.name); + keys.forceActiveFocus(); + } + } + } + } + } + RowLayout { + Layout.fillWidth: true + spacing: 10 + Text { + text: "Drag to move · handles resize · arrows nudge · Delete removes · Esc finishes" + color: Theme.textSecondary + font.pixelSize: 11 + elide: Text.ElideRight + Layout.fillWidth: true + } + Text { + text: "Snap to grid" + color: Theme.text + font.pixelSize: 12 + } + GlassToggle { + objectName: "widgetGrid" + checked: WidgetState.grid + onToggled: ConfigService.setValue("desktopWidgets.grid", checked) + } + GlassButton { + objectName: "widgetDone" + text: "Done" + accented: true + onClicked: WidgetState.done() + } + } + } + } + } + } +} diff --git a/quickshell/widgets/WidgetRegistry.qml b/quickshell/widgets/WidgetRegistry.qml new file mode 100644 index 0000000..27ccb48 --- /dev/null +++ b/quickshell/widgets/WidgetRegistry.qml @@ -0,0 +1,173 @@ +pragma Singleton +import QtQuick +import Quickshell + +// Desktop widget types. Sizes are logical pixels; `variants` maps id -> label; +// `options` lists editable per-widget options shown in the editor inspector; +// `background: false` draws the face without the glass card. +Singleton { + readonly property var order: ["clock", "calendar", "weather", "music", "visualizer", "cpu", "ram", "gpu", "temp", "disk", "network", "user", "image", "note"] + readonly property var types: ({ + clock: { + name: "Clock", + icon: "󰥔", + file: "faces/ClockFace.qml", + size: [260, 130], + min: [140, 70], + variants: { + digital: "Digital", + analog: "Analog", + minimal: "Minimal" + }, + transparent: ["minimal"], + options: [ + { + id: "seconds", + label: "Show seconds", + kind: "toggle" + } + ] + }, + calendar: { + name: "Calendar", + icon: "󰃭", + file: "faces/CalendarFace.qml", + size: [270, 260], + min: [210, 200] + }, + weather: { + name: "Weather", + icon: "󰖐", + file: "faces/WeatherFace.qml", + size: [270, 140], + min: [180, 100], + options: [ + { + id: "location", + label: "Location (blank = automatic)", + kind: "text" + }, + { + id: "fahrenheit", + label: "Fahrenheit", + kind: "toggle" + } + ] + }, + music: { + name: "Music", + icon: "󰝚", + file: "faces/MusicFace.qml", + size: [380, 160], + min: [320, 140] + }, + visualizer: { + name: "Visualizer", + icon: "󰺢", + file: "faces/VisualizerFace.qml", + size: [420, 120], + min: [140, 50], + variants: { + bars: "Bars", + mirror: "Mirror" + }, + transparent: ["bars", "mirror"] + }, + cpu: { + name: "CPU", + icon: "󰻠", + file: "faces/UsageFace.qml", + size: [180, 130], + min: [110, 80] + }, + ram: { + name: "Memory", + icon: "󰍛", + file: "faces/UsageFace.qml", + size: [180, 130], + min: [110, 80] + }, + gpu: { + name: "GPU", + icon: "󰢮", + file: "faces/UsageFace.qml", + size: [180, 130], + min: [110, 80] + }, + temp: { + name: "CPU temp", + icon: "󰔏", + file: "faces/UsageFace.qml", + size: [180, 130], + min: [110, 80] + }, + disk: { + name: "Disk", + icon: "󰋊", + file: "faces/UsageFace.qml", + size: [180, 130], + min: [110, 80] + }, + network: { + name: "Network", + icon: "󰛳", + file: "faces/NetworkFace.qml", + size: [270, 140], + min: [180, 100] + }, + user: { + name: "User", + icon: "󰀄", + file: "faces/UserFace.qml", + size: [290, 120], + min: [230, 100] + }, + image: { + name: "Image", + icon: "󰋩", + file: "faces/ImageFace.qml", + size: [300, 200], + min: [60, 60], + variants: { + rounded: "Rounded", + rect: "Square", + round: "Circle" + }, + transparent: ["rounded", "rect", "round"], + options: [ + { + id: "path", + label: "Image file", + kind: "text" + } + ] + }, + note: { + name: "Note", + icon: "󰎚", + file: "faces/NoteFace.qml", + size: [240, 200], + min: [150, 100], + keyboard: true + } + }) + function type(id) { + return Object.prototype.hasOwnProperty.call(types, id) ? types[id] : null; + } + function variants(id) { + const t = type(id); + return t && t.variants ? Object.keys(t.variants) : []; + } + function defaultVariant(id) { + const v = variants(id); + return v.length ? v[0] : "default"; + } + function transparent(id, variant) { + const t = type(id); + return !!t && !!t.transparent && t.transparent.includes(variant); + } + function source(id) { + const t = type(id); + return t ? Qt.resolvedUrl(t.file) : ""; + } +} diff --git a/quickshell/widgets/WidgetState.qml b/quickshell/widgets/WidgetState.qml new file mode 100644 index 0000000..c97496c --- /dev/null +++ b/quickshell/widgets/WidgetState.qml @@ -0,0 +1,181 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Io +import "../services" +import "../core" +import "../services/WidgetLogic.js" as Logic + +// Desktop widget items plus editor state. While a widget is dragged or resized +// its geometry lives in `drafts`, so the real surface follows live; the result +// is written to the configuration on release. +Singleton { + id: root + readonly property var items: ConfigService.ready ? ConfigService.data.desktopWidgets.items : [] + readonly property bool grid: ConfigService.ready && ConfigService.data.desktopWidgets.grid + readonly property int gridSize: 20 + property bool editing: false + property string selected: "" + property var drafts: ({}) + // Live surfaces by widget id and editor windows, for diagnostics and tests. + property var surfaces: ({}) + property var editors: [] + + function item(id) { + return items.find(i => i.id === id) || null; + } + function rect(id) { + const draft = drafts[id]; + if (draft) + return draft; + const i = item(id); + return i ? { + x: i.x, + y: i.y, + w: i.w, + h: i.h + } : { + x: 0, + y: 0, + w: 0, + h: 0 + }; + } + function limits(type) { + const t = WidgetRegistry.type(type); + return { + minW: t ? t.min[0] : 60, + minH: t ? t.min[1] : 60, + maxW: 4000, + maxH: 4000 + }; + } + function setDraft(id, r) { + const next = Object.assign({}, drafts); + next[id] = { + x: r.x, + y: r.y, + w: r.w, + h: r.h + }; + drafts = next; + } + function commit(id) { + const r = drafts[id]; + if (!r) + return; + update(id, { + x: Math.round(r.x), + y: Math.round(r.y), + w: Math.round(r.w), + h: Math.round(r.h) + }); + const next = Object.assign({}, drafts); + delete next[id]; + drafts = next; + } + function update(id, patch) { + return ConfigService.setValue("desktopWidgets.items", Logic.updateItem(items, id, patch)); + } + function setOption(id, key, value) { + const i = item(id); + if (!i) + return false; + const options = Object.assign({}, i.options || {}); + options[key] = value; + return update(id, { + options: options + }); + } + // Adds a widget centred on the given output and selects it. + function add(type, monitor) { + const t = WidgetRegistry.type(type); + const screen = Quickshell.screens.find(s => s.name === monitor) || ScreenService.active; + if (!t || !screen) + return ""; + const id = Logic.newId(items); + let x = Math.round((screen.width - t.size[0]) / 2), y = Math.round((screen.height - t.size[1]) / 2); + if (grid) { + x = Math.round(x / gridSize) * gridSize; + y = Math.round(y / gridSize) * gridSize; + } + // Offset when another widget already sits exactly there. + while (items.some(i => i.monitor === screen.name && i.x === x && i.y === y)) { + x += 24; + y += 24; + } + const added = ConfigService.setValue("desktopWidgets.items", Logic.addItem(items, { + id: id, + type: type, + variant: WidgetRegistry.defaultVariant(type), + monitor: screen.name, + x: x, + y: y, + w: t.size[0], + h: t.size[1], + opacity: 1, + options: {} + })); + if (added) + selected = id; + return added ? id : ""; + } + function duplicate(id) { + const i = item(id); + if (!i) + return ""; + const copy = Object.assign({}, i, { + id: Logic.newId(items), + x: i.x + 24, + y: i.y + 24, + options: Object.assign({}, i.options || {}) + }); + if (ConfigService.setValue("desktopWidgets.items", Logic.addItem(items, copy))) + selected = copy.id; + return copy.id; + } + function remove(id) { + if (selected === id) + selected = ""; + return ConfigService.setValue("desktopWidgets.items", Logic.removeItem(items, id)); + } + function edit(id) { + ShellState.settingsOpen = false; + ShellState.controlCenterOpen = false; + ShellState.launcherOpen = false; + ShellState.wallpaperPickerOpen = false; + selected = id || ""; + editing = true; + } + function done() { + editing = false; + selected = ""; + drafts = {}; + } + + IpcHandler { + target: "widgets" + function edit(): void { + root.edit(""); + } + function toggle(): void { + if (root.editing) + root.done(); + else + root.edit(""); + } + function done(): void { + root.done(); + } + function add(type: string): string { + return root.add(type, ScreenService.active ? ScreenService.active.name : ""); + } + function list(): string { + return JSON.stringify({ + editing: root.editing, + selected: root.selected, + items: root.items + }); + } + } +} diff --git a/quickshell/widgets/faces/CalendarFace.qml b/quickshell/widgets/faces/CalendarFace.qml new file mode 100644 index 0000000..ff42309 --- /dev/null +++ b/quickshell/widgets/faces/CalendarFace.qml @@ -0,0 +1,112 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Layouts +import Quickshell +import "../../theme" + +// Month view starting on the locale's first weekday; arrows browse months. +Face { + id: root + SystemClock { + id: clock + precision: SystemClock.Minutes + } + property int offset: 0 + readonly property date today: clock.date + readonly property date shown: new Date(today.getFullYear(), today.getMonth() + offset, 1) + readonly property int firstDay: Qt.locale().firstDayOfWeek % 7 + readonly property var cells: { + const start = (shown.getDay() - firstDay + 7) % 7; + const result = []; + for (let i = 0; i < 42; i++) + result.push(new Date(shown.getFullYear(), shown.getMonth(), 1 - start + i)); + return result; + } + ColumnLayout { + anchors.fill: parent + anchors.margins: 14 + spacing: 6 + RowLayout { + Layout.fillWidth: true + Text { + text: Qt.formatDate(root.shown, "MMMM yyyy") + color: Theme.text + font.pixelSize: 14 + font.weight: Font.DemiBold + Layout.fillWidth: true + } + Repeater { + model: [-1, 1] + Rectangle { + id: arrow + required property int modelData + implicitWidth: 22 + implicitHeight: 22 + radius: 11 + color: arrowArea.containsMouse ? Theme.hover : Theme.transparent + Text { + anchors.centerIn: parent + text: arrow.modelData < 0 ? "‹" : "›" + color: Theme.textSecondary + font.pixelSize: 16 + } + MouseArea { + id: arrowArea + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: root.offset += arrow.modelData + } + } + } + } + GridLayout { + Layout.fillWidth: true + Layout.fillHeight: true + columns: 7 + rowSpacing: 0 + columnSpacing: 0 + Repeater { + model: 7 + Text { + required property int index + text: Qt.locale().dayName((root.firstDay + index) % 7, Locale.NarrowFormat) + color: Theme.textSecondary + font.pixelSize: 10 + font.weight: Font.DemiBold + horizontalAlignment: Text.AlignHCenter + Layout.fillWidth: true + } + } + Repeater { + model: root.cells + Item { + id: cell + required property date modelData + readonly property bool isToday: modelData.toDateString() === root.today.toDateString() + readonly property bool inMonth: modelData.getMonth() === root.shown.getMonth() + Layout.fillWidth: true + Layout.fillHeight: true + Rectangle { + anchors.centerIn: parent + width: Math.min(parent.width, parent.height) - 2 + height: width + radius: width / 2 + color: Theme.accent + visible: cell.isToday + } + Text { + anchors.centerIn: parent + text: cell.modelData.getDate() + color: cell.isToday ? Theme.accentText : Theme.text + opacity: cell.inMonth ? 1 : 0.3 + font.pixelSize: 11 + font.weight: cell.isToday ? Font.DemiBold : Font.Normal + } + } + } + } + } + // Jump back to the current month when the day changes. + onTodayChanged: offset = 0 +} diff --git a/quickshell/widgets/faces/ClockFace.qml b/quickshell/widgets/faces/ClockFace.qml new file mode 100644 index 0000000..b8e17e9 --- /dev/null +++ b/quickshell/widgets/faces/ClockFace.qml @@ -0,0 +1,125 @@ +import QtQuick +import QtQuick.Effects +import Quickshell +import "../../services" +import "../../theme" + +Face { + id: root + readonly property bool seconds: !!options.seconds + SystemClock { + id: clock + precision: root.seconds || root.variant === "analog" ? SystemClock.Seconds : SystemClock.Minutes + } + // Follows the bar clock's 12/24-hour preference. + readonly property string timeFormat: (ConfigService.ready && !ConfigService.data.bar.clock.use24Hour ? "h:mm" : "HH:mm") + (seconds ? ":ss" : "") + + // Digital: large time with the date below. + Column { + visible: root.variant === "digital" + anchors.centerIn: parent + spacing: root.height * 0.02 + Text { + anchors.horizontalCenter: parent.horizontalCenter + text: Qt.formatTime(clock.date, root.timeFormat) + color: Theme.text + font.pixelSize: Math.min(root.height * 0.42, root.width / (root.seconds ? 4.4 : 3)) + font.weight: Font.Light + font.features: { + "tnum": 1 + } + } + Text { + anchors.horizontalCenter: parent.horizontalCenter + text: Qt.formatDate(clock.date, "dddd, d MMMM") + color: Theme.textSecondary + font.pixelSize: Math.max(10, root.height * 0.11) + } + } + + // Minimal: no card; large thin time and the weekday, readable on any wallpaper. + Item { + id: minimal + visible: root.variant === "minimal" + anchors.fill: parent + layer.enabled: visible + layer.effect: MultiEffect { + shadowEnabled: true + shadowColor: "#99000000" + shadowBlur: 0.6 + shadowVerticalOffset: 2 + } + Column { + anchors.left: parent.left + anchors.leftMargin: root.width * 0.04 + anchors.verticalCenter: parent.verticalCenter + Text { + text: Qt.formatTime(clock.date, root.timeFormat) + color: Theme.text + font.pixelSize: Math.min(root.height * 0.55, root.width / (root.seconds ? 4.2 : 2.9)) + font.weight: Font.Thin + font.features: { + "tnum": 1 + } + } + Text { + text: Qt.formatDate(clock.date, "dddd d MMMM").toUpperCase() + color: Theme.text + opacity: 0.85 + font.pixelSize: Math.max(10, root.height * 0.1) + font.letterSpacing: 2 + font.weight: Font.DemiBold + } + } + } + + // Analog: ticks and hands; the second hand follows the seconds option. + Canvas { + id: dial + visible: root.variant === "analog" + anchors.centerIn: parent + width: Math.min(root.width, root.height) - 16 + height: width + readonly property var time: clock.date + readonly property color hand: Theme.text + readonly property color accent: Theme.accentVivid + onTimeChanged: requestPaint() + onVisibleChanged: if (visible) + requestPaint() + onWidthChanged: requestPaint() + onPaint: { + const ctx = getContext("2d"); + ctx.reset(); + const r = width / 2; + ctx.translate(r, r); + for (let i = 0; i < 60; i++) { + const a = i * Math.PI / 30, major = i % 5 === 0; + ctx.beginPath(); + ctx.moveTo(Math.sin(a) * r * (major ? 0.82 : 0.9), -Math.cos(a) * r * (major ? 0.82 : 0.9)); + ctx.lineTo(Math.sin(a) * r * 0.96, -Math.cos(a) * r * 0.96); + ctx.strokeStyle = Qt.alpha(hand, major ? 0.85 : 0.3); + ctx.lineWidth = major ? Math.max(1.5, r * 0.035) : 1; + ctx.lineCap = "round"; + ctx.stroke(); + } + const d = time, h = d.getHours() % 12, m = d.getMinutes(), s = d.getSeconds(); + const handAt = (angle, length, widthFactor, color) => { + ctx.beginPath(); + ctx.moveTo(-Math.sin(angle) * r * 0.1, Math.cos(angle) * r * 0.1); + ctx.lineTo(Math.sin(angle) * r * length, -Math.cos(angle) * r * length); + ctx.strokeStyle = color; + ctx.lineWidth = Math.max(1.5, r * widthFactor); + ctx.lineCap = "round"; + ctx.stroke(); + }; + handAt((h + m / 60) * Math.PI / 6, 0.5, 0.06, hand); + handAt((m + s / 60) * Math.PI / 30, 0.74, 0.04, hand); + if (root.seconds) + handAt(s * Math.PI / 30, 0.8, 0.015, accent); + ctx.beginPath(); + ctx.arc(0, 0, Math.max(3, r * 0.05), 0, 2 * Math.PI); + ctx.fillStyle = accent; + ctx.fill(); + } + } +} diff --git a/quickshell/widgets/faces/Face.qml b/quickshell/widgets/faces/Face.qml new file mode 100644 index 0000000..5c5a89e --- /dev/null +++ b/quickshell/widgets/faces/Face.qml @@ -0,0 +1,28 @@ +import QtQuick +import "../../services" + +// Base for desktop widget faces; DesktopWidget binds these after loading. +Item { + id: face + property string widgetId + property string kind + property string variant + property var options: ({}) + // False while windows cover this widget's desktop: faces pause motion and sampling. + property bool desktopVisible: true + // Faces showing live metrics keep the shared collector running only while shown. + property bool usesMetrics: false + readonly property bool sampling: usesMetrics && desktopVisible + property bool counted: false + function count(next) { + if (next !== counted) { + MetricsService.consumers += next ? 1 : -1; + counted = next; + } + } + onSamplingChanged: count(sampling) + Component.onCompleted: count(sampling) + Component.onDestruction: count(false) + // Reference size for typography that scales with the widget. + readonly property real unit: Math.min(width, height * 2) +} diff --git a/quickshell/widgets/faces/ImageFace.qml b/quickshell/widgets/faces/ImageFace.qml new file mode 100644 index 0000000..84758c2 --- /dev/null +++ b/quickshell/widgets/faces/ImageFace.qml @@ -0,0 +1,54 @@ +import QtQuick +import QtQuick.Effects +import "../../theme" + +// A picture from disk: rounded, square or circular. +Face { + id: root + readonly property string path: options.path || "" + Image { + id: picture + anchors.fill: parent + visible: false + source: root.path ? "file://" + encodeURI(root.path).replace(/#/g, "%23").replace(/\?/g, "%3F") : "" + sourceSize: Qt.size(Math.max(1, root.width) * 2, Math.max(1, root.height) * 2) + fillMode: Image.PreserveAspectCrop + asynchronous: true + } + Item { + id: shape + anchors.centerIn: parent + width: root.variant === "round" ? Math.min(root.width, root.height) : root.width + height: root.variant === "round" ? width : root.height + visible: false + layer.enabled: true + Rectangle { + anchors.fill: parent + radius: root.variant === "round" ? width / 2 : root.variant === "rect" ? 0 : Theme.radius + } + } + MultiEffect { + anchors.fill: parent + source: picture + maskEnabled: true + maskSource: shape + visible: picture.status === Image.Ready + } + Rectangle { + anchors.fill: shape + visible: picture.status !== Image.Ready + radius: root.variant === "round" ? width / 2 : root.variant === "rect" ? 0 : Theme.radius + color: Theme.fill + border.width: 1 + border.color: Theme.border + Text { + anchors.centerIn: parent + width: parent.width - 20 + horizontalAlignment: Text.AlignHCenter + wrapMode: Text.Wrap + text: root.path ? "Cannot load image" : "Right-click to choose an image" + color: Theme.textSecondary + font.pixelSize: 11 + } + } +} diff --git a/quickshell/widgets/faces/MusicFace.qml b/quickshell/widgets/faces/MusicFace.qml new file mode 100644 index 0000000..bd6d9ca --- /dev/null +++ b/quickshell/widgets/faces/MusicFace.qml @@ -0,0 +1,13 @@ +import QtQuick +import "../../media" +import "../../theme" + +// The shared media card, drawn on the widget's own glass. +Face { + MediaCard { + anchors.fill: parent + compact: true + color: Theme.transparent + border.width: 0 + } +} diff --git a/quickshell/widgets/faces/NetworkFace.qml b/quickshell/widgets/faces/NetworkFace.qml new file mode 100644 index 0000000..015e8e8 --- /dev/null +++ b/quickshell/widgets/faces/NetworkFace.qml @@ -0,0 +1,115 @@ +import QtQuick +import QtQuick.Layouts +import "../../components" +import "../../services" +import "../../theme" + +// Live download/upload rates with a one-minute history graph. +Face { + id: root + usesMetrics: true + readonly property var samples: MetricsService.history + ColumnLayout { + anchors.fill: parent + anchors.margins: 12 + spacing: 6 + RowLayout { + Layout.fillWidth: true + spacing: 6 + GlassIcon { + size: 22 + glyphSize: 12 + glyph: "󰛳" + fallback: "N" + color: Theme.transparent + border.width: 0 + } + Text { + text: "Network" + color: Theme.text + font.pixelSize: 12 + font.weight: Font.DemiBold + Layout.fillWidth: true + } + } + RowLayout { + Layout.fillWidth: true + spacing: 14 + Repeater { + model: [ + { + label: "↓", + value: MetricsService.network.download, + color: Theme.accentVivid + }, + { + label: "↑", + value: MetricsService.network.upload, + color: Theme.text + } + ] + Row { + id: rate + required property var modelData + spacing: 4 + Text { + text: rate.modelData.label + color: rate.modelData.color + font.pixelSize: 15 + font.weight: Font.DemiBold + } + Text { + text: MetricsService.bytes(rate.modelData.value) + "/s" + color: Theme.text + font.pixelSize: 15 + font.weight: Font.Light + font.features: { + "tnum": 1 + } + } + } + } + } + Canvas { + id: graph + Layout.fillWidth: true + Layout.fillHeight: true + readonly property var samples: root.samples + readonly property color down: Theme.accentVivid + readonly property color up: Theme.text + onSamplesChanged: requestPaint() + onWidthChanged: requestPaint() + onHeightChanged: requestPaint() + onPaint: { + const ctx = getContext("2d"); + ctx.reset(); + const values = samples.filter(s => Number.isFinite(s.down) && Number.isFinite(s.up)); + if (values.length < 2) + return; + const peak = Math.max(1024, ...values.map(s => Math.max(s.down, s.up))); + const step = width / 59; + const offset = width - (values.length - 1) * step; + for (const [key, color, alpha] of [["down", down, 0.3], ["up", up, 0.12]]) { + ctx.beginPath(); + ctx.moveTo(offset, height); + values.forEach((s, i) => ctx.lineTo(offset + i * step, height - s[key] / peak * (height - 2))); + ctx.lineTo(offset + (values.length - 1) * step, height); + ctx.closePath(); + ctx.fillStyle = Qt.alpha(color, alpha); + ctx.fill(); + ctx.beginPath(); + values.forEach((s, i) => { + const y = height - s[key] / peak * (height - 2); + if (i === 0) + ctx.moveTo(offset, y); + else + ctx.lineTo(offset + i * step, y); + }); + ctx.strokeStyle = Qt.alpha(color, 0.9); + ctx.lineWidth = 1.5; + ctx.stroke(); + } + } + } + } +} diff --git a/quickshell/widgets/faces/NoteFace.qml b/quickshell/widgets/faces/NoteFace.qml new file mode 100644 index 0000000..1740096 --- /dev/null +++ b/quickshell/widgets/faces/NoteFace.qml @@ -0,0 +1,32 @@ +import QtQuick +import QtQuick.Controls +import "../../theme" +import ".." + +// Sticky note; text is saved shortly after typing stops. +Face { + id: root + ScrollView { + anchors.fill: parent + anchors.margins: 12 + TextArea { + id: editor + text: root.options.text || "" + placeholderText: "Write a note…" + placeholderTextColor: Theme.textSecondary + color: Theme.text + selectionColor: Theme.accent + selectedTextColor: Theme.accentText + wrapMode: TextEdit.Wrap + font.pixelSize: 13 + background: null + onTextChanged: if (activeFocus) + save.restart() + } + } + Timer { + id: save + interval: 700 + onTriggered: WidgetState.setOption(root.widgetId, "text", editor.text) + } +} diff --git a/quickshell/widgets/faces/UsageFace.qml b/quickshell/widgets/faces/UsageFace.qml new file mode 100644 index 0000000..5cf3e6f --- /dev/null +++ b/quickshell/widgets/faces/UsageFace.qml @@ -0,0 +1,166 @@ +import QtQuick +import "../../components" +import "../../services" +import "../../theme" + +// CPU, memory, GPU, CPU temperature and disk: a liquid fill rising with the +// value (after Serpantinum's usage cards), with title, value and detail. +Face { + id: root + usesMetrics: true + readonly property var disk: (MetricsService.snapshot.storage || [])[0] || ({}) + readonly property var raw: { + switch (kind) { + case "cpu": + return { + title: "CPU", + icon: "󰻠", + value: MetricsService.cpu.percent, + text: MetricsService.value(MetricsService.cpu.percent, "%"), + detail: Number.isFinite(MetricsService.cpu.frequency) ? (MetricsService.cpu.frequency / 1000).toFixed(1) + " GHz" : "" + }; + case "ram": + return { + title: "Memory", + icon: "󰍛", + value: MetricsService.ram.percent, + text: MetricsService.value(MetricsService.ram.percent, "%"), + detail: MetricsService.ram.available ? MetricsService.bytes(MetricsService.ram.used) + " of " + MetricsService.bytes(MetricsService.ram.total) : "" + }; + case "gpu": + return { + title: "GPU", + icon: "󰢮", + value: MetricsService.gpu.percent, + text: MetricsService.value(MetricsService.gpu.percent, "%"), + detail: MetricsService.gpu.name || "No GPU telemetry" + }; + case "temp": + return { + title: "CPU temp", + icon: "󰔏", + value: MetricsService.cpu.temperature, + text: MetricsService.value(MetricsService.cpu.temperature, "°C"), + detail: MetricsService.cpu.name || "" + }; + default: + return { + title: "Disk", + icon: "󰋊", + value: root.disk.percent, + text: MetricsService.value(root.disk.percent, "%"), + detail: root.disk.available ? MetricsService.bytes(root.disk.free) + " free · " + root.disk.path : "" + }; + } + } + readonly property real level: Number.isFinite(raw.value) ? Math.max(0, Math.min(1, raw.value / 100)) : 0 + // The wave moves only while easing to a visibly different reading (12 fps, + // at least `settleTicks` steps), then holds still; small changes repaint + // once. An endless wave kept every usage widget repainting and the + // compositor recompositing the glass behind it. + readonly property bool animated: Theme.intensity > 0 + readonly property int settleTicks: 18 + property real shownLevel: level + property real phase: 0 + property int ticks: 0 + onLevelChanged: { + if (!animated || !desktopVisible || (!wave.running && Math.abs(level - shownLevel) < 0.02)) { + shownLevel = level; + return; + } + ticks = 0; + wave.start(); + } + Timer { + id: wave + interval: 83 + repeat: true + onTriggered: { + root.phase = (root.phase + Math.PI * 2 * interval / 2400) % (Math.PI * 2); + const gap = root.level - root.shownLevel; + root.shownLevel = Math.abs(gap) < 0.002 ? root.level : root.shownLevel + gap * 0.3; + if ((++root.ticks >= root.settleTicks && root.shownLevel === root.level) || !root.desktopVisible || !root.animated) + stop(); + } + } + readonly property bool compact: height < 100 || width < 140 + + Canvas { + id: liquid + anchors.fill: parent + readonly property real level: root.shownLevel + readonly property real phase: root.phase + readonly property color fill: Theme.accentVivid + readonly property real radius: Theme.radius + onLevelChanged: requestPaint() + onPhaseChanged: requestPaint() + onFillChanged: requestPaint() + onPaint: { + const ctx = getContext("2d"); + ctx.reset(); + const w = width, h = height, r = Math.min(radius, h / 2, w / 2); + ctx.beginPath(); + ctx.roundedRect(0, 0, w, h, r, r); + ctx.clip(); + const surface = h * (1 - level), amp = Math.max(2, h * 0.035); + for (const [shift, alpha] of [[Math.PI, 0.18], [0, 0.38]]) { + ctx.beginPath(); + ctx.moveTo(0, h); + for (let x = 0; x <= w; x += 4) + ctx.lineTo(x, surface + Math.sin(x / w * Math.PI * 2 + phase + shift) * amp); + ctx.lineTo(w, h); + ctx.closePath(); + ctx.fillStyle = Qt.alpha(fill, alpha); + ctx.fill(); + } + } + } + Column { + anchors.left: parent.left + anchors.top: parent.top + anchors.margins: 12 + spacing: 2 + Row { + spacing: 6 + GlassIcon { + size: 22 + glyphSize: 12 + glyph: root.raw.icon + fallback: root.raw.title.charAt(0) + color: Theme.transparent + border.width: 0 + } + Text { + anchors.verticalCenter: parent.verticalCenter + text: root.raw.title + color: Theme.text + font.pixelSize: 12 + font.weight: Font.DemiBold + } + } + } + Column { + anchors.left: parent.left + anchors.right: parent.right + anchors.bottom: parent.bottom + anchors.margins: 12 + spacing: 0 + Text { + text: root.raw.text + color: Theme.text + font.pixelSize: Math.max(18, Math.min(root.height * 0.3, root.width * 0.24)) + font.weight: Font.Light + font.features: { + "tnum": 1 + } + } + Text { + visible: !root.compact && text !== "" + width: parent.width + text: root.raw.detail + color: Theme.textSecondary + font.pixelSize: 10 + elide: Text.ElideRight + } + } +} diff --git a/quickshell/widgets/faces/UserFace.qml b/quickshell/widgets/faces/UserFace.qml new file mode 100644 index 0000000..4e73a3a --- /dev/null +++ b/quickshell/widgets/faces/UserFace.qml @@ -0,0 +1,117 @@ +import QtQuick +import QtQuick.Effects +import QtQuick.Layouts +import Quickshell +import Quickshell.Io +import "../../theme" + +// Avatar (~/.face or AccountsService), greeting, user@host and uptime. +Face { + id: root + readonly property string user: Quickshell.env("USER") || "user" + readonly property var avatars: ["file://" + Quickshell.env("HOME") + "/.face", "file://" + Quickshell.env("HOME") + "/.face.icon", "file:///var/lib/AccountsService/icons/" + user] + property int avatarIndex: 0 + SystemClock { + id: clock + precision: SystemClock.Minutes + } + readonly property string greeting: { + const h = clock.date.getHours(); + return h < 5 ? "Good night" : h < 12 ? "Good morning" : h < 18 ? "Good afternoon" : "Good evening"; + } + FileView { + id: hostname + path: "/etc/hostname" + } + FileView { + id: uptime + path: "/proc/uptime" + } + Timer { + interval: 60000 + running: root.visible && root.desktopVisible + repeat: true + onTriggered: uptime.reload() + } + onDesktopVisibleChanged: if (desktopVisible) + uptime.reload() + readonly property string uptimeText: { + const seconds = parseFloat(uptime.text()); + if (!Number.isFinite(seconds)) + return ""; + const d = Math.floor(seconds / 86400), h = Math.floor(seconds % 86400 / 3600), m = Math.floor(seconds % 3600 / 60); + return "up " + (d ? d + "d " : "") + (d || h ? h + "h " : "") + m + "m"; + } + RowLayout { + anchors.fill: parent + anchors.margins: 14 + spacing: 14 + Item { + readonly property real size: Math.min(root.height - 28, 80) + Layout.preferredWidth: size + Layout.preferredHeight: size + Image { + id: avatar + anchors.fill: parent + source: root.avatarIndex < root.avatars.length ? root.avatars[root.avatarIndex] : "" + sourceSize: Qt.size(160, 160) + fillMode: Image.PreserveAspectCrop + asynchronous: true + visible: false + onStatusChanged: if (status === Image.Error) + root.avatarIndex++ + } + Rectangle { + id: mask + anchors.fill: parent + radius: width / 2 + visible: false + layer.enabled: true + } + MultiEffect { + anchors.fill: parent + source: avatar + maskEnabled: true + maskSource: mask + visible: avatar.status === Image.Ready + } + Rectangle { + anchors.fill: parent + radius: width / 2 + visible: avatar.status !== Image.Ready + color: Theme.accent + Text { + anchors.centerIn: parent + text: root.user.charAt(0).toUpperCase() + color: Theme.accentText + font.pixelSize: parent.width * 0.45 + font.weight: Font.DemiBold + } + } + } + ColumnLayout { + Layout.fillWidth: true + spacing: 1 + Text { + text: root.greeting + "," + color: Theme.textSecondary + font.pixelSize: 12 + } + Text { + text: root.user.charAt(0).toUpperCase() + root.user.slice(1) + color: Theme.text + font.pixelSize: Math.max(16, root.height * 0.18) + font.weight: Font.DemiBold + elide: Text.ElideRight + Layout.fillWidth: true + } + Text { + text: root.user + "@" + hostname.text().trim() + (root.uptimeText ? " · " + root.uptimeText : "") + color: Theme.textSecondary + font.pixelSize: 10 + elide: Text.ElideRight + Layout.fillWidth: true + } + } + } +} diff --git a/quickshell/widgets/faces/VisualizerFace.qml b/quickshell/widgets/faces/VisualizerFace.qml new file mode 100644 index 0000000..fba6ad3 --- /dev/null +++ b/quickshell/widgets/faces/VisualizerFace.qml @@ -0,0 +1,40 @@ +pragma ComponentBehavior: Bound +import QtQuick +import "../../services" +import "../../theme" + +// Cava bars for system audio: rising bars, or mirrored around the centre line. +Face { + id: root + Component.onCompleted: CavaService.widgetConsumers++ + Component.onDestruction: CavaService.widgetConsumers-- + readonly property bool mirror: variant === "mirror" + Row { + id: bars + anchors.fill: parent + anchors.margins: 6 + spacing: Math.max(2, width / 24 * 0.3) + Repeater { + model: 24 + Item { + id: column + required property int index + readonly property real level: Math.max(0.03, CavaService.bars[index] || 0) + width: (bars.width - bars.spacing * 23) / 24 + height: bars.height + Rectangle { + width: parent.width + height: Math.max(width, column.height * column.level) + y: root.mirror ? (column.height - height) / 2 : column.height - height + radius: width / 2 + color: Qt.alpha(Theme.accentVivid, 0.55 + column.level * 0.45) + Behavior on height { + NumberAnimation { + duration: 60 + } + } + } + } + } + } +} diff --git a/quickshell/widgets/faces/WeatherFace.qml b/quickshell/widgets/faces/WeatherFace.qml new file mode 100644 index 0000000..d5931cc --- /dev/null +++ b/quickshell/widgets/faces/WeatherFace.qml @@ -0,0 +1,100 @@ +import QtQuick +import QtQuick.Layouts +import Quickshell +import Quickshell.Io +import "../../components" +import "../../theme" + +// Current conditions from wttr.in, refreshed every 30 minutes. +Face { + id: root + readonly property string location: options.location || "" + readonly property bool fahrenheit: !!options.fahrenheit + property var current: null + property string error: "" + function temperature(celsius) { + return Math.round(fahrenheit ? celsius * 9 / 5 + 32 : celsius) + "°"; + } + // WWO weather codes used by wttr.in. + function glyph(code) { + if (code === 113) + return "󰖙"; + if (code === 116) + return "󰖕"; + if (code === 119 || code === 122) + return "󰖐"; + if ([143, 248, 260].includes(code)) + return "󰖑"; + if ([200, 386, 389, 392, 395].includes(code)) + return "󰖓"; + if ([179, 182, 185, 227, 230, 317, 320, 323, 326, 329, 332, 335, 338, 350, 362, 365, 368, 371, 374, 377].includes(code)) + return "󰖘"; + return "󰖗"; + } + Process { + id: fetch + command: ["python3", Quickshell.shellPath("helpers/weather.py"), root.location] + stdout: StdioCollector { + onStreamFinished: { + try { + const result = JSON.parse(text); + if (result.ok) { + root.current = result; + root.error = ""; + } else + root.error = "Weather unavailable"; + } catch (e) { + root.error = "Weather unavailable"; + } + } + } + } + Timer { + interval: 30 * 60 * 1000 + running: root.visible + repeat: true + triggeredOnStart: true + onTriggered: if (!fetch.running) + fetch.running = true + } + onLocationChanged: if (!fetch.running) + fetch.running = true + RowLayout { + anchors.fill: parent + anchors.margins: 14 + spacing: 12 + GlassIcon { + size: Math.min(root.height - 28, 64) + glyphSize: size * 0.62 + glyph: root.current ? root.glyph(root.current.code) : "󰖐" + fallback: "☁" + color: Theme.transparent + border.width: 0 + } + ColumnLayout { + Layout.fillWidth: true + spacing: 0 + Text { + text: root.current ? root.temperature(root.current.celsius) : "—" + color: Theme.text + font.pixelSize: Math.max(20, root.height * 0.3) + font.weight: Font.Light + } + Text { + text: root.current ? root.current.description : root.error || "Loading…" + color: Theme.text + font.pixelSize: 12 + elide: Text.ElideRight + Layout.fillWidth: true + } + Text { + visible: !!root.current && root.height > 110 + text: root.current ? root.current.place + " · feels " + root.temperature(root.current.feelsCelsius) : "" + color: Theme.textSecondary + font.pixelSize: 10 + elide: Text.ElideRight + Layout.fillWidth: true + } + } + } +} diff --git a/quickshell/widgets/faces/qmldir b/quickshell/widgets/faces/qmldir new file mode 100644 index 0000000..94e8efa --- /dev/null +++ b/quickshell/widgets/faces/qmldir @@ -0,0 +1 @@ +Face 1.0 Face.qml diff --git a/quickshell/widgets/qmldir b/quickshell/widgets/qmldir new file mode 100644 index 0000000..ff45ae4 --- /dev/null +++ b/quickshell/widgets/qmldir @@ -0,0 +1,5 @@ +singleton WidgetRegistry 1.0 WidgetRegistry.qml +singleton WidgetState 1.0 WidgetState.qml +DesktopWidget 1.0 DesktopWidget.qml +DesktopWidgets 1.0 DesktopWidgets.qml +WidgetEditor 1.0 WidgetEditor.qml diff --git a/scripts/build-shaders b/scripts/build-shaders new file mode 100755 index 0000000..83a901e --- /dev/null +++ b/scripts/build-shaders @@ -0,0 +1,9 @@ +#!/bin/sh +# Rebuild Qt shader packs (.qsb) from GLSL sources. Requires qsb from Qt Shader +# Tools matching the runtime Qt major version; with Nix: +# nix shell nixpkgs#qt6.qtshadertools -c ./scripts/build-shaders +set -eu +project_dir=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +for source in "$project_dir"/quickshell/lock/shaders/*.frag; do + qsb --glsl "100 es,120,150" --hlsl 50 --msl 12 -o "$source.qsb" "$source" +done diff --git a/scripts/doctor.py b/scripts/doctor.py new file mode 100644 index 0000000..b96ff70 --- /dev/null +++ b/scripts/doctor.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python3 +"""Read-only environment diagnostics. Never starts a shell or changes the session.""" +import json +import os +import shutil +import subprocess +import sys + + +def query(args): + try: + p=subprocess.run(args,capture_output=True,text=True,timeout=4) + return (p.stdout or p.stderr).strip()[:1600] if p.returncode==0 else 'Unavailable' + except (OSError,subprocess.TimeoutExpired):return 'Unavailable' + + +def report(): + required={name:bool(shutil.which(name)) for name in ['quickshell','python3','hyprctl']} + return dict(required=required, + session=dict(wayland=bool(os.environ.get('WAYLAND_DISPLAY')),hyprland=bool(os.environ.get('HYPRLAND_INSTANCE_SIGNATURE')),dbus=bool(os.environ.get('DBUS_SESSION_BUS_ADDRESS'))), + versions=dict(quickshell=query(['quickshell','--version']),hyprland=query(['hyprctl','version']).splitlines()[0]), + hyprglass=dict(plugins=query(['hyprctl','plugin','list']),layers=query(['hyprctl','getoption','plugin:hyprglass:layers:enabled'])), + optional={name:bool(shutil.which(name)) for name in ['matugen','cava','nvidia-smi','brightnessctl','busctl','nm-connection-editor','blueman-manager']}, + note='Command discovery only: QML module availability, service capabilities and compositor rules still require runtime validation. No changes made.') + +if __name__=='__main__': + result=report();print(json.dumps(result,indent=2)) + sys.exit(0 if all(result['required'].values()) and all(result['session'].values()) else 1) diff --git a/scripts/glassmxrph b/scripts/glassmxrph new file mode 100755 index 0000000..7b8de58 --- /dev/null +++ b/scripts/glassmxrph @@ -0,0 +1,65 @@ +#!/bin/sh +set -eu +project_dir=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +case "${1:-run}" in + doctor) + exec python3 "$project_dir/scripts/doctor.py" + ;; + run) + for glassmxrph_dependency in quickshell python3; do + command -v "$glassmxrph_dependency" >/dev/null 2>&1 || { echo "glassMxrph requires $glassmxrph_dependency on PATH" >&2; exit 127; } + done + # Qt may need the database root when /etc/localtime points outside /usr/share. + # Honor an explicit TZDIR and derive only from an existing zoneinfo symlink. + if [ -z "${TZDIR:-}" ]; then + glassmxrph_timezone_path=$(readlink -f /etc/localtime 2>/dev/null || true) + case "$glassmxrph_timezone_path" in + */zoneinfo/*) TZDIR="${glassmxrph_timezone_path%/zoneinfo/*}/zoneinfo"; export TZDIR ;; + esac + fi + mkdir -p "${XDG_CONFIG_HOME:-$HOME/.config}/glassMxrph" "${XDG_STATE_HOME:-$HOME/.local/state}/glassMxrph" + # Portable Omarchy helper commands that shell plugins call. + export PATH="$project_dir/quickshell/compat/omarchy/bin:$PATH" + exec quickshell --no-duplicate --path "$project_dir/quickshell" + ;; + wallpaper) + exec quickshell ipc --path "$project_dir/quickshell" call wallpaper picker + ;; + controlcenter) + exec quickshell ipc --path "$project_dir/quickshell" call controlcenter toggle + ;; + launcher) + exec quickshell ipc --path "$project_dir/quickshell" call launcher toggle + ;; + plugin) + # glassmxrph plugin [list|install SOURCE|remove ID|enable ID|disable ID|summon ID|toggle ID] + action=${2:-list} + case "$action" in + summon|toggle) exec quickshell ipc --path "$project_dir/quickshell" call plugins "$action" "${3:?plugin id}" "${4:-}" ;; + list|status) exec quickshell ipc --path "$project_dir/quickshell" call plugins "$action" ;; + *) exec quickshell ipc --path "$project_dir/quickshell" call plugins "$action" "${3:?argument required}" ;; + esac + ;; + dashboard) + # glassmxrph dashboard [dashboard|media|performance|power] + exec quickshell ipc --path "$project_dir/quickshell" call dashboard toggle "${2:-}" + ;; + lock) + exec quickshell ipc --path "$project_dir/quickshell" call lock lock + ;; + widgets) + exec quickshell ipc --path "$project_dir/quickshell" call widgets toggle + ;; + osd) + # glassmxrph osd [volumeUp|volumeDown|mute|micMute|brightnessUp|brightnessDown|open KIND] + action=${2:-open} + if [ "$action" = open ] || [ "$action" = show ]; then + exec quickshell ipc --path "$project_dir/quickshell" call osd open "${3:-volume}" + fi + exec quickshell ipc --path "$project_dir/quickshell" call osd "$action" + ;; + settings|close|status) + exec quickshell ipc --path "$project_dir/quickshell" call shell "$1" + ;; + *) echo 'Usage: glassmxrph [run|wallpaper|launcher|dashboard [TAB]|plugin ACTION|controlcenter|lock|widgets|osd ACTION|settings|close|status|doctor]' >&2; exit 2 ;; +esac diff --git a/scripts/validate b/scripts/validate new file mode 100755 index 0000000..8299c69 --- /dev/null +++ b/scripts/validate @@ -0,0 +1,15 @@ +#!/bin/sh +set -eu +project_dir=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +node "$project_dir/tests/config.test.cjs" +node "$project_dir/tests/polish.test.cjs" +node "$project_dir/tests/dock.test.cjs" +node "$project_dir/tests/launcher.test.cjs" +node "$project_dir/tests/widgets.test.cjs" +python3 "$project_dir/tests/providers_test.py" +python3 "$project_dir/tests/system_providers_test.py" +python3 "$project_dir/tests/metrics_test.py" +python3 "$project_dir/tests/glass_test.py" +# compat/ holds vendored third-party UI kits (qs.compat.* imports qmllint cannot +# resolve); they are exercised by the plugin runtime test instead. +find "$project_dir/quickshell" -name '*.qml' -not -path '*/compat/*' -exec qmllint -E "$@" {} + diff --git a/tests/config.test.cjs b/tests/config.test.cjs new file mode 100644 index 0000000..78d766c --- /dev/null +++ b/tests/config.test.cjs @@ -0,0 +1,98 @@ +const fs = require('node:fs'); +const vm = require('node:vm'); +const assert = require('node:assert/strict'); +const path = require('node:path'); +const root = path.join(__dirname, '..'); +const api = vm.createContext({}); +vm.runInContext(fs.readFileSync(path.join(root, 'quickshell/services/ConfigLogic.js'), 'utf8'), api); +const defaults = JSON.parse(fs.readFileSync(path.join(root, 'quickshell/config/defaults.json'))); +const loaded = api.load(defaults, {appearance: {customAccent: '#123456'}, futureOption: 42, dock: {pinnedApps: ['example.desktop']}}); +assert.equal(loaded.appearance.customAccent, '#123456'); +assert.equal(loaded.appearance.glassOpacity, defaults.appearance.glassOpacity); +assert.equal(loaded.futureOption, 42); +assert.equal(loaded.dock.pinnedApps[0], 'example.desktop'); +assert.throws(() => api.load(defaults, {schemaVersion: 99})); +assert.throws(() => api.load(defaults, {appearance: {glassOpacity: 4}})); +assert.throws(() => api.load(defaults, {bar: {modules: [{id:'clock',position:'bad',enabled:true}]}})); +assert.throws(() => api.load(defaults, [])); +const edited = api.update(loaded, 'appearance.customAccent', '#abcdef'); +assert.equal(loaded.appearance.customAccent, '#123456'); +assert.equal(edited.appearance.customAccent, '#abcdef'); +assert.equal(loaded.appearance.glassTint, '#000000'); +assert.equal(loaded.osd.position, 'top-right');assert.equal(loaded.bar.workspaces.style, 'numbers'); +const widget={id:'w-1',type:'clock',variant:'digital',monitor:'DP-1',x:10,y:20,w:260,h:130,opacity:1,options:{}}; +assert.deepEqual(loaded.desktopWidgets.items,[]); +assert.equal(loaded.lock.backdrop,'wallpaper');assert.equal(loaded.lock.pamService,'');assert.equal(api.update(loaded,'lock.pamService','hyprlock').lock.pamService,'hyprlock'); +for(const [k,v] of [['lock.backdrop','video'],['lock.pamService','../etc/shadow'],['lock.glass','yes']])assert.throws(()=>api.update(loaded,k,v),/lock screen/);assert.equal(api.update(loaded,'desktopWidgets.items',[widget,Object.assign({},widget,{id:'w-2',type:'future'})]).desktopWidgets.items.length,2); +for(const bad of [[widget,widget],[Object.assign({},widget,{w:10})],[Object.assign({},widget,{opacity:2})],[Object.assign({},widget,{id:'Bad id'})],[Object.assign({},widget,{options:[]})]])assert.throws(()=>api.update(loaded,'desktopWidgets.items',bad),/desktop widget/);assert.equal(api.update(loaded, 'bar.workspaces.style', 'pacman').bar.workspaces.style, 'pacman');assert.throws(() => api.update(loaded, 'bar.workspaces.style', 'emoji'), /bar module options/);assert.throws(() => api.update(loaded, 'osd.position', 'left'), /OSD/);assert.throws(() => api.update(loaded, 'osd.timeout', 50), /OSD/);assert.throws(() => api.update(loaded, 'appearance.glassTint', 'grey'), /Glass tint/); +assert.throws(() => api.update(loaded, '__proto__.polluted', true)); +console.log('Configuration preservation, validation and update tests passed.'); + +const originalModules = [{id:'clock',position:'left',enabled:false},{id:'system',position:'center',enabled:true}]; +const migrated = api.load(defaults, {schemaVersion:1,bar:{modules:originalModules},tray:{hoverDelay:650},dock:{pinnedApps:['custom.desktop']}}); +assert.equal(migrated.schemaVersion, 3); +assert.equal(migrated.bar.modules[0].id, 'clock'); +assert.equal(migrated.bar.modules[0].position, 'left'); +assert.equal(migrated.bar.modules[0].enabled, false); +assert.equal(migrated.bar.modules[1].id, 'tray'); +assert.equal(migrated.bar.modules[2].position, 'center'); +assert.equal(originalModules.length, 2); +assert.equal(migrated.tray.hoverDelay, 650); +assert.equal(migrated.dock.pinnedApps[0], 'custom.desktop'); +assert.equal(api.load(defaults, migrated).bar.modules.length, 3); +const removed = api.load(defaults, {schemaVersion:2,bar:{modules:originalModules}}); +assert.equal(removed.bar.modules.length, 2); // never re-add a deliberately removed module +assert.throws(() => api.load(defaults, {tray:{hoverDelay:-10}})); +assert.throws(() => api.load(defaults, {tray:{iconSize:100}})); +assert.throws(() => api.load(defaults, {tray:{enabled:'yes'}})); +assert.throws(() => api.load(defaults, {tray:{background:'invalid'}})); +console.log('Phase 2 migration and tray validation tests passed.'); +const phase3=api.load(defaults,{schemaVersion:2,dock:{enabled:false,pinnedApps:['my.desktop'],monitor:'external',visibility:'auto'},future:{keep:true}}); +assert.equal(phase3.schemaVersion,3);assert.equal(phase3.dock.enabled,false);assert.equal(phase3.dock.pinnedApps[0],'my.desktop');assert.equal(phase3.dock.monitor,'external');assert.equal(phase3.dock.iconSize,48);assert(phase3.future.keep); +for(const dock of [{position:'top'},{visibility:'bad'},{iconSize:0},{pinnedApps:['a','a.desktop']},{terminalCommand:'sh'},{appOverrides:{a:42}}]) assert.throws(()=>api.load(defaults,{dock})); +console.log('Phase 3 migration and dock validation tests passed.'); +const phase4=api.load(defaults,{schemaVersion:3,launcher:{recentFiles:false,unknown:'keep'},dock:{pinnedApps:['preserved.desktop']}}); +assert.equal(phase4.launcher.width,680);assert.equal(phase4.launcher.unknown,'keep');assert.equal(phase4.dock.pinnedApps[0],'preserved.desktop'); +for (const launcher of [{width:10},{maxResults:0},{maxResults:2.5},{showDescriptions:'yes'},{recentFiles:42}]) assert.throws(()=>api.load(defaults,{launcher})); +console.log('Launcher default merging and preference validation passed.'); +const phase5=api.load(defaults,{schemaVersion:3,appearance:{customAccent:'#112233'},wallpaper:{directories:['/pictures'],byMonitor:{screen:'/pictures/a.png'}},media:{showAlbum:false},bar:{modules:originalModules}}); +assert.equal(phase5.appearance.panelOpacity,0.86);assert.equal(phase5.wallpaper.backend,'native');assert.equal(phase5.wallpaper.byMonitor.screen,'/pictures/a.png');assert.equal(phase5.media.showAlbum,false);assert.equal(phase5.media.showAlbumArt,true);assert.equal(phase5.bar.modules.length,2); +for(const data of [{matugen:{contrast:2}},{matugen:{scheme:'invented'}},{wallpaper:{command:'sh -c'}},{media:{showCava:'yes'}},{appearance:{panelOpacity:2}},{bar:{workspaces:{count:0}}}])assert.throws(()=>api.load(defaults,data)); +const settings=vm.createContext({});vm.runInContext(fs.readFileSync(path.join(root,'quickshell/services/SettingsLogic.js'),'utf8'),settings); +const modules=[{id:'a',position:'left',enabled:true,custom:{keep:true}},{id:'middle',position:'center',enabled:true},{id:'b',position:'left',enabled:false}]; +const moved=settings.moveModule(modules,'b',-1);assert.equal(moved[0].id,'b');assert.equal(moved[1].id,'middle');assert(moved[2].custom.keep);assert.equal(modules[0].id,'a'); +const withoutMiddle=settings.removeModule(modules,'middle');assert.deepEqual(withoutMiddle.map(m=>m.id),['a','b']);assert.equal(modules.length,3); +const assigned=settings.editModule(modules,'a','position','right');assert.equal(assigned[0].position,'right');assert(assigned[0].custom.keep);assert.equal(modules[0].position,'left'); +console.log('Phase 5 preference merging, validation and immutable bar editing/removal passed.'); + +assert.throws(() => api.update(phase5, 'bar.modules', {}), /must be an array/); +assert.equal(api.update(phase5, 'bar.modules', [{id:'nowPlaying',position:'right',enabled:true}]).bar.modules[0].id, 'nowPlaying'); +const phase7=api.load(defaults,{schemaVersion:3,controlCenter:{modules:[]},dock:{pinnedApps:['keep.desktop']},future:{keep:true}}); +assert.equal(phase7.controlCenter.version,1);assert(phase7.controlCenter.modules.length>0);assert.equal(phase7.dock.pinnedApps[0],'keep.desktop');assert(phase7.future.keep); +assert.equal(api.load(defaults,{controlCenter:{version:1,modules:[]}}).controlCenter.modules.length,0); +const customCenter=api.load(defaults,{controlCenter:{modules:[{id:'custom',enabled:false,metadata:'preserved'}]}}); +assert.equal(customCenter.controlCenter.modules[0].metadata,'preserved');assert.equal(customCenter.controlCenter.modules.length,1); +for(const controlCenter of [{version:2},{version:1,width:100},{version:1,modules:[{id:'audio',enabled:true},{id:'audio',enabled:false}]}])assert.throws(()=>api.load(defaults,{controlCenter})); +for(const system of [{brightness:{setCommand:'sh -c'}},{nightLight:{temperature:0}},{power:{lockCommand:['']}}])assert.throws(()=>api.load(defaults,{system})); +console.log('Phase 7 one-time module migration, intentional empty layouts, provider validation and preservation passed.'); + +for(const controlCenter of [null,[],{modules:null},{modules:''}])assert.throws(()=>api.load(defaults,{controlCenter})); + +const metricConfig=api.load(defaults,{schemaVersion:3,metrics:{interval:5,networkInterface:'custom',future:42}}); +assert.equal(metricConfig.metrics.interval,5); +assert.equal(metricConfig.metrics.networkInterface,'custom'); +assert.equal(metricConfig.metrics.future,42); +assert.equal(metricConfig.metrics.gpu,'auto'); +for(const value of [0,31,1.5,'2'])assert.throws(()=>api.update(metricConfig,'metrics.interval',value)); +for(const value of [['relative'],['/','/'],null])assert.throws(()=>api.update(metricConfig,'metrics.storagePaths',value)); +assert.equal(api.update(metricConfig,'metrics.storagePaths',[]).metrics.storagePaths.length,0); +console.log('Phase 8 metrics defaults, preservation, source and interval validation passed.'); +const dropped=settings.dropModule(modules,'b','center','middle'); +assert.equal(dropped.find(m=>m.id==='b').position,'center'); +assert.equal(dropped.find(m=>m.id==='b').enabled,false); +assert.equal(dropped.findIndex(m=>m.id==='b')+1,dropped.findIndex(m=>m.id==='middle')); +assert.equal(modules[2].position,'left'); +assert.equal(settings.dropModule(modules,'a','right','').find(m=>m.id==='a').custom.keep,true); +assert.throws(()=>api.load(defaults,{hyprglass:{values:{blur_iterations:2.5}}})); +assert.throws(()=>api.load(defaults,{hyprglass:{values:{refraction_strength:99}}})); +console.log('Drag/drop preserves module options and validates global glass preferences.'); diff --git a/tests/controlcenter_runtime.py b/tests/controlcenter_runtime.py new file mode 100644 index 0000000..c74c614 --- /dev/null +++ b/tests/controlcenter_runtime.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python3 +"""Real Wayland/read-only native discovery, then recording adapters for all writes.""" +import json,os,subprocess,tempfile,time +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1] +BASE=['quickshell','ipc','--path',str(ROOT/'quickshell'),'call'] +def ipc(target,method,*args): + r=subprocess.run(BASE+[target,method,*map(str,args)],capture_output=True,text=True) + return json.loads(r.stdout) if r.returncode==0 and r.stdout.strip() else None +def state():return ipc('controlTest','snapshot') or {} +def wait(check,label): + end=time.monotonic()+15 + while time.monotonic()s['screenWidth']/2 and s['x']+s['width']<=s['screenWidth'] and s['y']+s['height']<=s['screenHeight'] + wait(lambda:ipc('controlTest','inject'),'inject recording adapters') + wait(lambda:not state()['busy'] and state()['state']['brightness']['available'],'fixture providers') + assert ipc('controlTest','click','volumeMute');wait(lambda:state()['muted'],'mute click') + assert ipc('controlTest','slider','volumeSlider');wait(lambda:state()['volume']>.6,'volume slider') + assert ipc('controlTest','click','microphoneMute');wait(lambda:state()['microphone'],'microphone click') + assert ipc('controlTest','click','wifiToggle');wait(lambda:not state()['wifi'],'Wi-Fi toggle') + assert ipc('controlTest','click','bluetoothToggle');wait(lambda:not state()['bluetooth'],'Bluetooth toggle') + assert ipc('controlTest','click','bluetoothToggle') + assert ipc('controlTest','connectFixtures') + for name,key in [('nightLightToggle','nightLight'),('dndToggle','dnd')]: + assert ipc('controlTest','click',name) + wait(lambda:not state()['busy'] and state()['state'][key]['enabled'],key+' readback') + failure=events.with_suffix('.fail');failure.touch() + assert ipc('controlTest','click','dndToggle') + wait(lambda:not state()['busy'] and bool(state()['error']),'provider error') + assert state()['state']['dnd']['enabled'] and ipc('controlTest','checked','dndToggle'),'Failed request changed displayed real state' + assert ipc('controlTest','slider','brightnessSlider') + wait(lambda:not state()['busy'] and bool(state()['error']),'brightness error') + assert ipc('controlTest','value','brightnessSlider')==state()['state']['brightness']['value'],'Failed brightness request changed display' + failure.unlink();assert ipc('controlTest','click','dndToggle') + wait(lambda:not state()['busy'] and not state()['error'] and not state()['state']['dnd']['enabled'],'provider recovery') + assert ipc('controlTest','slider','brightnessSlider') + wait(lambda:not state()['busy'] and state()['state']['brightness']['value']>60,'brightness readback') + assert ipc('controlTest','click','power-reboot');assert state()['power']=='reboot' + assert not any(json.loads(line)['action']=='power' for line in events.read_text().splitlines()) + assert ipc('controlTest','click','powerCancel');assert state()['power']=='' + assert ipc('controlTest','click','power-shutdown');ipc('controlTest','pressEscape');wait(lambda:state()['power']=='','Escape cancels pending power') + assert ipc('controlcenter','status')['opened'] + assert ipc('controlTest','click','power-reboot');assert ipc('controlTest','click','powerConfirm') + wait(lambda:not state()['busy'],'recorded confirmation') + actions=[json.loads(line) for line in events.read_text().splitlines()] + power=[a for a in actions if a['action']=='power'];assert len(power)==1 and power[0]['value']=='reboot' and power[0]['confirmed'] is True + ipc('controlcenter','close');time.sleep(.3);ipc('controlcenter','open');time.sleep(.35) + assert ipc('controlTest','screenshot',str(ROOT/'.cache/controlcenter-preview.png')) + ipc('controlTest','outside');wait(lambda:not state()['windowVisible'],'outside closes') + for monitor in monitors: + subprocess.run(['hyprctl','dispatch','focusmonitor',monitor['name']],check=True,capture_output=True) + wait(lambda:state()['active']==monitor['name'],'active monitor event') + ipc('controlcenter','open');wait(lambda:state()['windowVisible'],'mapped on output');time.sleep(.3) + assert ipc('controlcenter','status')['screen']==monitor['name'] + s=state();assert s['x']>=0 and s['x']+s['width']<=s['screenWidth'] and s['y']+s['height']<=s['screenHeight'] + ipc('controlcenter','close');wait(lambda:not state()['windowVisible'],'close before monitor switch') + pref('animation.reducedMotion',True) + for _ in range(3): + ipc('controlcenter','open');wait(lambda:state()['windowVisible'],'reduced motion open') + ipc('controlcenter','close');wait(lambda:not state()['windowVisible'],'reduced motion close') + pref('animation.reducedMotion',False) + ipc('controlcenter','open');ipc('launcher','open');wait(lambda:not ipc('controlcenter','status')['opened'],'launcher exclusivity');ipc('launcher','close') + ipc('shell','openSettings','controlcenter');wait(lambda:state()['settingsVisible'],'module editor opens');time.sleep(.3) + assert ipc('controlTest','settingsClick','control-down-connectivity') + wait(lambda:state()['modules'][1]['id']=='connectivity','visual module reorder') + assert ipc('controlTest','settingsClick','control-enable-audio') + wait(lambda:not next(m for m in state()['modules'] if m['id']=='audio')['enabled'],'visual module toggle') + ipc('shell','close');wait(lambda:not state()['settingsVisible'],'settings closes') + for page in ['controlcenter','audio','network','bluetooth','displays','notifications','power']: + ipc('shell','openSettings',page);time.sleep(.3) + wait(lambda:not state()['scan'],'network scan released') + ipc('shell','close');pref('controlCenter.modules',[]) + ipc('controlcenter','open');time.sleep(.3);ipc('controlTest','pressEscape');wait(lambda:not ipc('controlcenter','status')['opened'],'Escape closes empty panel') + wait(lambda:json.loads(cfg.read_text())['controlCenter']['modules']==[],'module persistence') + finally: + shell.terminate();shell.wait(timeout=5) + if original:subprocess.run(['hyprctl','dispatch','focusmonitor',original],capture_output=True) + text=log.read_text();assert 'WARN' not in text and 'ERROR' not in text,text +print('PASS: native read-only discovery, active-monitor placement, system pill, recording audio/network/Bluetooth/display/DND actions, power confirmation/cancel, outside/Escape/exclusivity, settings, clean logs.') diff --git a/tests/customization_runtime.py b/tests/customization_runtime.py new file mode 100644 index 0000000..a34b880 --- /dev/null +++ b/tests/customization_runtime.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +"""Native wallpaper and DnD on Wayland; global glass writes go to a recording hyprctl.""" +import importlib.util,json,os,shutil,struct,subprocess,tempfile,time,zlib +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1] +BASE=['quickshell','ipc','--path',str(ROOT/'quickshell'),'call'] +def ipc(target,method,*args): + p=subprocess.run(BASE+[target,method,*map(str,args)],text=True,capture_output=True,timeout=5) + return json.loads(p.stdout) if p.returncode==0 and p.stdout.strip() else None +def state():return ipc('settingsTest','snapshot') or {} +def wait(fn): + end=time.monotonic()+20 + while time.monotonic()search.rank(index,q,n); +assert.equal(results('editor')[0].id,'edit');assert.equal(results('edtr')[0].id,'edit'); +assert.equal(results('EDITEUR')[0].id,'photo');assert.equal(results('web bro')[0].id,'web'); +assert.equal(results('internet')[0].id,'web');assert.equal(results('text editor')[0].id,'edit'); +assert.equal(results('doesnotexist').length,0);assert.equal(results('; rm -rf /').length,0); +assert.equal(results('',2).length,2);assert.equal(results(' ').length,4); +assert.equal(results('editor impossible').length,0); +assert.equal(items[0].title,'Editor');assert(search.score('dock','dock')>search.score('docker','dock')); +console.log('Launcher ranking: exact/prefix/fuzzy, accents/case, keywords, multi-token, limits and no-match tests passed.'); diff --git a/tests/launcher_runtime.py b/tests/launcher_runtime.py new file mode 100644 index 0000000..60a5fc7 --- /dev/null +++ b/tests/launcher_runtime.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Opt-in live launcher test. Temporary desktop entries/preferences; no real apps launched.""" +import json +import os +from pathlib import Path +import subprocess +import tempfile +import time + +ROOT=Path(__file__).resolve().parents[1] +BASE=['quickshell','ipc','--path',str(ROOT/'quickshell'),'call'] +ESC,DOWN,UP,ENTER=0x01000000,0x01000015,0x01000013,0x01000004 + +def ipc(target,method,*args): + p=subprocess.run(BASE+[target,method,*map(str,args)],capture_output=True,text=True) + return json.loads(p.stdout) if p.returncode==0 and p.stdout.strip() else None + +def eventually(check,label,timeout=8): + end=time.monotonic()+timeout + while time.monotonic()') + eventually(lambda:{r['id'] for r in snapshot()['results']}=={'about','appearance','audio','bar','tray','bluetooth','controlcenter','display','dock','launcher','media','metrics','network','notifications','power','wallpaper','widgets','osd','lock','dashboard','plugins'},'all commands registered') + time.sleep(.3);assert ipc('launcherTest','screenshot',str(ROOT/'.cache/launcher-preview.png')) + for text,page in [('>metrics','metrics'),('>wall','wallpaper'),('>dock','dock'),('>media','media'),('>tray','tray'),('>display','displays'),('>launcher','launcher'),('>appearance','appearance'),('>bar','bar'),('>network','network'),('>bluetooth','bluetooth'),('>audio','audio'),('>controlcenter','controlcenter'),('>notifications','notifications'),('>power','power'),('>about','about')]: + query(text) + ipc('launcherTest','key',ENTER) + eventually(lambda:ipc('shell','status')['settingsOpen'] and ipc('shell','status')['settingsPage']==page,'command destination '+page) + assert not snapshot()['opened'] + open_launcher() + assert not ipc('shell','status')['settingsOpen'] + query('>command-that-does-not-exist') + assert not snapshot()['results'] + ipc('launcherTest','key',ENTER);assert snapshot()['opened'] + assert ipc('launcherTest','extension','true') + assert not ipc('launcherTest','extension','true'),'Duplicate command accepted' + query('>fixture');ipc('launcherTest','key',ENTER) + eventually(lambda:ipc('shell','status')['settingsPage']=='about','extension execution') + ipc('launcherTest','extension','false');ipc('shell','close') + # Reduced motion and rapid reversals must settle without hidden keyboard grabs. + assert ipc('shell','setPreference','animation.reducedMotion','true') + for _ in range(6):ipc('launcher','toggle') + eventually(lambda:not snapshot()['opened'] and not snapshot()['visible'],'rapid toggle settles') + open_launcher();assert centered() + ipc('shell','close') + eventually(lambda:not snapshot()['opened'],'shared close IPC') + finally: + if shell and shell.poll() is None:shell.terminate();shell.wait(timeout=5) + if original:subprocess.run(['hyprctl','dispatch','focusmonitor',original],capture_output=True) + text=log.read_text() + assert 'WARN' not in text and 'ERROR' not in text,text +print('PASS: centered active-monitor placement, keyboard/text/mouse input, fuzzy/keyword search, NoDisplay filtering, native launch/errors, all commands and extension lifecycle, settings routes, outside/Escape, reduced motion, rapid toggles, clean logs.') diff --git a/tests/media_runtime.py b/tests/media_runtime.py new file mode 100644 index 0000000..e9f3526 --- /dev/null +++ b/tests/media_runtime.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +"""Run with dbus-run-session, real Wayland and dbus-python/PyGObject.""" +import json,os,subprocess,tempfile,time,shutil +from pathlib import Path +import dbus +ROOT=Path(__file__).resolve().parents[1] +BASE=['quickshell','ipc','--path',str(ROOT/'quickshell'),'call'] +def ipc(target,method,*args): + r=subprocess.run(BASE+[target,method,*map(str,args)],capture_output=True,text=True) + return json.loads(r.stdout) if r.returncode==0 and r.stdout.strip() else None +def state():return ipc('media','status') or {} +def wait(check,label): + end=time.monotonic()+12 + while time.monotonic()=45,'play and seek seconds') + records=[json.loads(s) for s in events.read_text().splitlines()] + assert {'play','next','previous','seek'} <= {e['method'] for e in records} + assert next(e for e in records if e['method']=='seek')['position']==45000000 + update('fixtureOne',{'CanSeek':False,'CanGoNext':False,'CanGoPrevious':False,'CanPause':False,'Title':'Updated song'}) + wait(lambda:state()['title']=='Updated song' and not state()['seekable'],'metadata/capabilities') + assert ipc('media','next') is False and ipc('media','previous') is False and ipc('media','seek',10) is False + pref('media.preferredPlayer','org.mpris.MediaPlayer2.fixtureTwo') + wait(lambda:state()['selected'].endswith('fixtureTwo'),'preferred player') + pref('bar.modules',[{'id':'nowPlaying','position':'right','enabled':True}]) + ipc('shell','openSettings','media');time.sleep(.5) + assert ipc('mediaTest','click','mediaToggle') + wait(lambda:not state()['playing'],'widget pause click') + assert ipc('mediaTest','click','mediaToggle') + wait(lambda:state()['playing'],'widget play click') + pref('media.showCava',True) + wait(lambda:ipc('cava','status')['running'],'Cava starts') + wait(lambda:ipc('cava','status')['frames']>2,'Cava frame shape') + assert ipc('mediaTest','screenshot',str(ROOT/'.cache/music-preview.png')) + time.sleep(.2) + update('fixtureTwo',{'PlaybackStatus':'Paused'}) + wait(lambda:not ipc('cava','status')['running'],'Cava stops on pause') + update('fixtureTwo',{'PlaybackStatus':'Playing'}) + wait(lambda:ipc('cava','status')['running'],'Cava resumes') + ipc('shell','close') + wait(lambda:not ipc('cava','status')['running'],'Cava stops without visible views') + ipc('shell','openSettings','media') + wait(lambda:ipc('cava','status')['running'],'Cava restarts with visible card') + pref('media.showCava',False) + wait(lambda:not ipc('cava','status')['running'],'Cava stops') + fail.touch();pref('media.showCava',True) + wait(lambda:bool(ipc('cava','status')['error']) and not ipc('cava','status')['running'],'Cava failure fallback') + time.sleep(.3);assert not ipc('cava','status')['running'],'Cava restarted after failure' + pref('media.showCava',False);fail.unlink();pref('media.showCava',True) + wait(lambda:ipc('cava','status')['running'] and not ipc('cava','status')['error'],'Cava recovery') + pref('media.showCava',False) + pref('media.showAlbumArt',False);pref('media.showProgress',False) + update('fixtureTwo',{'NoLength':True}) + wait(lambda:state()['length']==0 and not state()['seekable'],'unknown length stream') + children[1].terminate();children[1].wait(timeout=5) + wait(lambda:len(state()['players'])==1 and state()['selected'].endswith('fixtureOne'),'disconnect fallback') + children[0].terminate();children[0].wait(timeout=5) + wait(lambda:len(state()['players'])==0 and state()['title']=='Nothing playing','last player removal') + finally: + for proc in children: + if proc.poll() is None:proc.terminate();proc.wait(timeout=5) + shell.terminate();shell.wait(timeout=5) + text=log.read_text();assert 'WARN' not in text and 'ERROR' not in text,text +print('PASS: empty state, two-player discovery/selection/fallback, metadata, capability guards, playback DBus actions, seek units, settings/bar, Cava lifecycle, clean runtime logs.') diff --git a/tests/metrics_runtime.py b/tests/metrics_runtime.py new file mode 100644 index 0000000..ab97c88 --- /dev/null +++ b/tests/metrics_runtime.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""Read-only live metrics integration with isolated preferences; no hardware writes.""" +import json +import os +from pathlib import Path +import subprocess +import tempfile +import time +ROOT=Path(__file__).resolve().parents[1] +SHELL=ROOT/'quickshell' +def ipc(target,method,*args): + p=subprocess.run(['quickshell','ipc','--path',str(SHELL),'call',target,method,*args],capture_output=True,text=True,timeout=5) + if p.returncode:return None + try:return json.loads(p.stdout) + except ValueError:return p.stdout.strip() +def wait(check,timeout=15): + end=time.monotonic()+timeout + while time.monotonic()=2) + assert ipc('metricsTest','screenshot',str(ROOT/'.cache/metrics-preview.png')) is True + wait(lambda:(ROOT/'.cache/metrics-preview.png').exists()) + s=state();assert not s['error'] and not s['stale'],s + assert 0<=s['snapshot']['cpu']['percent']<=100,s + assert s['snapshot']['ram']['total']>0,s + ipc('shell','close') + wait(lambda:state().get('consumers')==0 and not state().get('running')) + before=state()['samples'];time.sleep(2.2);assert state()['samples']==before + monitors=json.loads(subprocess.check_output(['hyprctl','-j','monitors'])) + pref('bar.modules',[{'id':k,'enabled':True,'position':'right'} for k in ['cpu','gpu','ram','storage','cpuTemperature','gpuTemperature','networkThroughput']]) + wait(lambda:state().get('consumers')==7*len(monitors) and state().get('samples',0)>before) + pref('bar.modules',[]) + ipc('shell','openSettings','metrics') + wait(lambda:state().get('consumers')==1) + pref('metrics.interval',1) + pref('metrics.storagePaths',['/','/missing-glassmxrph-test']) + wait(lambda:len(state().get('snapshot',{}).get('storage',[]))==2) + assert not state()['snapshot']['storage'][1]['available'] + pref('metrics.networkInterface','missing-glassmxrph-test') + wait(lambda:state().get('snapshot',{}).get('network',{}).get('selected')==['missing-glassmxrph-test']) + assert state()['snapshot']['network']['download'] is None + pref('controlCenter.modules',[{'id':'metrics','enabled':True}]) + ipc('controlcenter','open') + wait(lambda:state().get('consumers')==1) + ipc('controlcenter','close') + wait(lambda:state().get('consumers')==0 and not state().get('running')) + # Desktop widgets sample only while their desktop is uncovered: no + # tiled or fullscreen window on the monitor's active workspace. + clients=json.loads(subprocess.check_output(['hyprctl','-j','clients'])) + active={m['activeWorkspace']['id'] for m in monitors} + covered={c['monitor'] for c in clients if c['workspace']['id'] in active and (not c['floating'] or c['fullscreen'])} + widget=lambda m:{'version':1,'grid':False,'items':[{'id':'cpu-1','type':'cpu','variant':'','monitor':m['name'],'x':40,'y':40,'w':180,'h':130,'opacity':1}]} + hidden=[m for m in monitors if m['id'] in covered] + shown=[m for m in monitors if m['id'] not in covered] + if hidden: + pref('desktopWidgets',widget(hidden[0])) + time.sleep(3) + assert state().get('consumers')==0 and not state().get('running'),state() + if shown: + pref('desktopWidgets',widget(shown[0])) + wait(lambda:state().get('consumers')>=1 and state().get('running')) + config=Path(tmp)/'config/glassMxrph/config.json' + wait(lambda:config.exists() and json.loads(config.read_text())['metrics']['interval']==1) + finally: + p.terminate();p.wait(timeout=8) + (ROOT/'.cache/phase8-runtime.log').write_text(log.read_text()) + text=log.read_text() + assert 'WARN' not in text and 'ERROR' not in text,text +print('PASS: live counters, shared bar/settings/Control Center consumers, idle shutdown/restart, source changes, unavailable sources, persistence and clean QML/DBus logs.') diff --git a/tests/metrics_test.py b/tests/metrics_test.py new file mode 100644 index 0000000..d91eb4a --- /dev/null +++ b/tests/metrics_test.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 +import importlib.util +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch +spec = importlib.util.spec_from_file_location('metrics', Path(__file__).resolve().parents[1] / 'quickshell/helpers/metrics.py') +m = importlib.util.module_from_spec(spec) +spec.loader.exec_module(m) + +class MetricsTests(unittest.TestCase): + def test_cpu_guest_not_double_counted_and_resets(self): + self.assertEqual(m.cpu_counts('cpu 10 20 30 40 5 6 7 8 100 200'), (126,45)) + self.assertIsNone(m.cpu_percent(None,(100,20))) + self.assertEqual(m.cpu_percent((100,20),(200,70)),50) + self.assertIsNone(m.cpu_percent((200,70),(100,20))) + self.assertIsNone(m.cpu_percent((100,20),(200,10))) + + def test_ram_available_cache(self): + r=m.memory('MemTotal: 100 kB\nMemFree: 10 kB\nMemAvailable: 40 kB') + self.assertEqual(r['used'],60*1024) + self.assertEqual(r['percent'],60) + self.assertFalse(m.memory('MemTotal: 100 kB')['available']) + + def test_network_time_reset_and_new_interface(self): + current=m.net_counts(' eth0: 100 0 0 0 0 0 0 0 200 0 0 0 0 0 0 0') + self.assertEqual(m.net_rates({'eth0':(50,100)},current,2)['eth0'],{'download':25,'upload':50}) + self.assertEqual(m.net_rates({'eth0':(500,500)},current,2)['eth0'],{'download':0,'upload':0}) + self.assertEqual(m.net_rates({},current,2),{}) + self.assertEqual(m.net_rates(current,current,0),{}) + + def test_nvidia_partial_sensor_and_invalid_numbers(self): + result=m.nvidia_rows('GPU-1, NVIDIA Example, 30, 60, 1024, 8192, 1200, [N/A]\nGPU-2, Other, N/A, N/A, N/A, N/A, N/A, N/A') + self.assertEqual(len(result),2) + self.assertEqual(result[0]['used'],1024**3) + self.assertIsNone(result[0]['power']) + self.assertIsNone(result[1]['percent']) + for value in ['nan','inf','-1','N/A']: + self.assertIsNone(m.number(value)) + + def test_missing_sources_and_storage_path_failure(self): + with patch.object(m,'read',return_value=''),patch.object(m.shutil,'which',return_value=None): + c=m.Collector({'storagePaths':['/definitely/missing/glassmxrph']}) + with patch.object(c,'gpu',return_value=[]): + result=c.sample() + self.assertIsNone(result['cpu']['percent']) + self.assertFalse(result['ram']['available']) + self.assertFalse(result['storage'][0]['available']) + self.assertTrue(result['warnings']) + + def test_amd_units(self): + with tempfile.TemporaryDirectory() as temp: + base=Path(temp)/'card1/device';hw=base/'hwmon/hwmon1';hw.mkdir(parents=True) + for file,value in {'vendor':'0x1002','gpu_busy_percent':'25','mem_info_vram_used':'1024','mem_info_vram_total':'4096'}.items(): + (base/file).write_text(value) + for file,value in {'temp1_input':'52000','freq1_input':'1500000000','power1_average':'23000000'}.items(): + (hw/file).write_text(value) + c=m.Collector({});c.nvidia=None + original=m.Path.glob + def glob(p, pattern): + return iter([base]) if str(p)=='/sys/class/drm' else original(p,pattern) + with patch.object(m.Path,'glob',glob): + gpu=c.gpu()[0] + self.assertEqual((gpu['temperature'],gpu['frequency'],gpu['power']), (52,1500,23)) + +if __name__=='__main__':unittest.main() diff --git a/tests/mpris_fixture.py b/tests/mpris_fixture.py new file mode 100644 index 0000000..f05cc46 --- /dev/null +++ b/tests/mpris_fixture.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python3 +"""Synthetic MPRIS player; run only on the test's private session bus.""" +import json,sys +from pathlib import Path +import dbus,dbus.service +from dbus.mainloop.glib import DBusGMainLoop +from gi.repository import GLib +DBusGMainLoop(set_as_default=True) +bus=dbus.SessionBus();name=dbus.service.BusName('org.mpris.MediaPlayer2.'+sys.argv[1],bus) +ROOT='org.mpris.MediaPlayer2';PLAYER=ROOT+'.Player';PROPS='org.freedesktop.DBus.Properties';TEST='org.glassMxrph.Test' +events=Path(sys.argv[2]) +art=events.parent/'art.svg' +art.write_text('') +def record(method,**args): + with events.open('a') as f:f.write(json.dumps(dict(method=method,**args))+'\n') +class Player(dbus.service.Object): + def __init__(self): + super().__init__(bus,'/org/mpris/MediaPlayer2') + self.root={'Identity':sys.argv[1],'DesktopEntry':sys.argv[1],'CanQuit':False,'CanRaise':False,'HasTrackList':False,'SupportedUriSchemes':dbus.Array([],signature='s'),'SupportedMimeTypes':dbus.Array([],signature='s')} + self.props={'PlaybackStatus':'Paused','LoopStatus':'None','Rate':1.0,'Shuffle':False,'Volume':0.5,'Position':dbus.Int64(12000000),'MinimumRate':1.0,'MaximumRate':1.0,'CanGoNext':True,'CanGoPrevious':True,'CanPlay':True,'CanPause':True,'CanSeek':True,'CanControl':True,'Metadata':self.metadata('Fixture song')} + def metadata(self,title):return dbus.Dictionary({'mpris:trackid':dbus.ObjectPath('/track/one'),'mpris:length':dbus.Int64(180000000),'xesam:title':title,'xesam:artist':dbus.Array(['Fixture artist'],signature='s'),'xesam:album':'Fixture album','mpris:artUrl':art.as_uri()},signature='sv') + @dbus.service.method(PROPS,in_signature='s',out_signature='a{sv}') + def GetAll(self,interface):return self.root if interface==ROOT else self.props if interface==PLAYER else {} + @dbus.service.method(PROPS,in_signature='ss',out_signature='v') + def Get(self,interface,key):return self.GetAll(interface)[key] + @dbus.service.method(PROPS,in_signature='ssv') + def Set(self,interface,key,value):self.props[key]=value;self.PropertiesChanged(PLAYER,{key:value},[]) + @dbus.service.signal(PROPS,signature='sa{sv}as') + def PropertiesChanged(self,interface,changed,invalidated):pass + @dbus.service.signal(PLAYER,signature='x') + def Seeked(self,position):pass + @dbus.service.method(PLAYER) + def PlayPause(self): + record('toggle');self.props['PlaybackStatus']='Paused' if self.props['PlaybackStatus']=='Playing' else 'Playing';self.PropertiesChanged(PLAYER,{'PlaybackStatus':self.props['PlaybackStatus']},[]) + @dbus.service.method(PLAYER) + def Play(self): + record('play');self.props['PlaybackStatus']='Playing';self.PropertiesChanged(PLAYER,{'PlaybackStatus':'Playing'},[]) + @dbus.service.method(PLAYER) + def Pause(self): + record('pause');self.props['PlaybackStatus']='Paused';self.PropertiesChanged(PLAYER,{'PlaybackStatus':'Paused'},[]) + @dbus.service.method(PLAYER) + def Next(self):record('next') + @dbus.service.method(PLAYER) + def Previous(self):record('previous') + @dbus.service.method(PLAYER,in_signature='ox') + def SetPosition(self,track,position):record('seek',track=str(track),position=int(position));self.props['Position']=position;self.Seeked(position) + @dbus.service.method(PLAYER,in_signature='x') + def Seek(self,offset):self.SetPosition('/track/one',self.props['Position']+offset) + @dbus.service.method(TEST,in_signature='s') + def Update(self,payload): + changes=json.loads(payload) + if 'Title' in changes:changes['Metadata']=self.metadata(changes.pop('Title')) + if changes.pop('NoLength',False): + changes['Metadata']=self.metadata('Live stream');del changes['Metadata']['mpris:length'] + self.props.update(changes);self.PropertiesChanged(PLAYER,changes,[]) +player=Player();GLib.MainLoop().run() diff --git a/tests/polish.test.cjs b/tests/polish.test.cjs new file mode 100644 index 0000000..d1e93b5 --- /dev/null +++ b/tests/polish.test.cjs @@ -0,0 +1,10 @@ +const fs=require('node:fs'),vm=require('node:vm'),path=require('node:path'),assert=require('node:assert/strict'); +const color=vm.createContext({}); +vm.runInContext(fs.readFileSync(path.join(__dirname,'../quickshell/theme/ColorLogic.js'),'utf8'),color); +for(let r=0;r<=255;r+=15)for(let g=0;g<=255;g+=15)for(let b=0;b<=255;b+=15){ + const l=color.luminance(r/255,g/255,b/255),dark=color.darkForeground(r/255,g/255,b/255); + assert(color.contrast(l,dark?0:1)>=4.5,`${r},${g},${b}`); +} +assert.equal(color.luminance(0,0,0),0); +assert.equal(color.luminance(1,1,1),1); +console.log('Phase 9: accent foreground contrast passes 4.5:1 over RGB grid.'); diff --git a/tests/polish_runtime.py b/tests/polish_runtime.py new file mode 100644 index 0000000..c60385b --- /dev/null +++ b/tests/polish_runtime.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +"""Isolated read-only session: motion, palette recovery, output fallback and collector recovery.""" +import json,os,signal,subprocess,tempfile,time +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1] +def ipc(target,method,*args): + p=subprocess.run(['quickshell','ipc','--path',str(ROOT/'quickshell'),'call',target,method,*args],capture_output=True,text=True,timeout=5) + return json.loads(p.stdout) if p.returncode==0 and p.stdout.strip() else None +def wait(check): + end=time.monotonic()+15 + while time.monotonic()=2) + old=ipc('metrics','status');pid=old['processId'] + assert str(ROOT/'quickshell/helpers/metrics.py').encode() in Path(f'/proc/{pid}/cmdline').read_bytes().split(b'\0') + os.kill(pid,signal.SIGTERM) + wait(lambda:ipc('metrics','status')['stale']) + wait(lambda:ipc('metrics','status')['processId']!=pid and ipc('metrics','status')['samples']>old['samples']) + assert not ipc('metrics','status')['error'] + ipc('shell','close') + pref('animation.reducedMotion',False) + wait(lambda:ipc('polishTest','snapshot')['duration']>0) + ipc('shell','openSettings','appearance');ipc('shell','close') + finally: + proc.terminate();proc.wait(timeout=8) + text=log.read_text();assert 'WARN' not in text and 'ERROR' not in text,text +print('PASS: reduced motion, rapid popup routing, stale-screen fallback, palette error recovery, accent contrast, collector termination/recovery and clean logs.') diff --git a/tests/providers_test.py b/tests/providers_test.py new file mode 100644 index 0000000..864fb5e --- /dev/null +++ b/tests/providers_test.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 +"""Filesystem and argument safety checks; no real wallpaper service is modified.""" +import importlib.util,json,subprocess,sys,tempfile,unittest +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1] +spec=importlib.util.spec_from_file_location('desktop',ROOT/'quickshell/helpers/desktop.py');desktop=importlib.util.module_from_spec(spec);spec.loader.exec_module(desktop) +class Providers(unittest.TestCase): + def test_scan_and_argument_boundaries(self): + with tempfile.TemporaryDirectory(prefix='glassmxrph-provider-') as directory: + root=Path(directory);image=root/"a ' quoted ; $(echo nope).png";image.write_bytes(b'fixture') + (root/'ignore.txt').write_text('no image') + result=desktop.scan({'directories':[directory,directory,str(root/'missing')]}) + self.assertEqual(len(result['images']),1);self.assertIn('%20',result['images'][0]['url']);self.assertTrue(result['notice']) + record=root/'record.json';helper=root/'record.py';helper.write_text('import json,pathlib,sys\npathlib.Path(sys.argv[1]).write_text(json.dumps(sys.argv[2:]))\n') + result=desktop.apply({'backend':'custom','monitor':'TEST-1','path':str(image),'command':[sys.executable,str(helper),str(record),'{path}','{monitor}']}) + self.assertEqual(json.loads(record.read_text()),[str(image),'TEST-1']);self.assertEqual(result['path'],str(image)) + with self.assertRaises(ValueError):desktop.apply({'backend':'custom','monitor':'TEST-1','path':str(image),'command':['tool']}) + with self.assertRaises(ValueError):desktop.apply({'backend':'custom','monitor':'bad; command','path':str(image),'command':[]}) + def test_errors_are_json(self): + p=subprocess.run([sys.executable,str(ROOT/'quickshell/helpers/desktop.py'),json.dumps({'action':'palette','executable':'/missing/matugen','path':'/missing'})],capture_output=True,text=True,check=True) + self.assertFalse(json.loads(p.stdout)['ok']);self.assertEqual(p.stderr,'') +if __name__=='__main__':unittest.main() diff --git a/tests/runtime.py b/tests/runtime.py new file mode 100644 index 0000000..ebbf52a --- /dev/null +++ b/tests/runtime.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +"""Opt-in real Wayland smoke test. Run with no glassMxrph instance active.""" +import json +import os +from pathlib import Path +import subprocess +import tempfile +import time + +ROOT = Path(__file__).resolve().parents[1] +SHELL = ROOT / 'quickshell' + +def ipc(method, *args): + return subprocess.run(['quickshell', 'ipc', '--path', str(SHELL), 'call', 'shell', method, *args], text=True, capture_output=True) + +def eventually(check, timeout=8): + end = time.monotonic() + timeout + while time.monotonic() < end: + try: + if check(): + return + except (ValueError, KeyError, FileNotFoundError): + pass + time.sleep(.1) + raise AssertionError('Runtime condition timed out') + +def status(): + result = ipc('status') + return json.loads(result.stdout) if result.returncode == 0 else {} + +if ipc('status').returncode == 0: + raise SystemExit('Stop the existing glassMxrph instance before this isolated test.') + +with tempfile.TemporaryDirectory(prefix='glassmxrph-runtime-') as tmp: + env = dict(os.environ, XDG_CONFIG_HOME=tmp + '/config', XDG_STATE_HOME=tmp + '/state') + config = Path(tmp) / 'config/glassMxrph/config.json' + palette = Path(tmp) / 'state/glassMxrph/palette.json' + log = Path(tmp) / 'runtime.log' + with log.open('w') as output: + proc = subprocess.Popen([str(ROOT / 'scripts/glassmxrph'), 'run'], env=env, stdout=output, stderr=subprocess.STDOUT) + try: + eventually(lambda: status().get('ready')) + duplicate = subprocess.run([str(ROOT / 'scripts/glassmxrph'), 'run'], env=env, capture_output=True, timeout=5) + assert duplicate.returncode == 0, duplicate.stderr + assert ipc('setPreference', 'appearance.customAccent', '"#167d9a"').stdout.strip() == 'true' + assert ipc('setPreference', 'appearance.accentSource', '"custom"').stdout.strip() == 'true' + eventually(lambda: config.exists() and json.loads(config.read_text())['appearance']['customAccent'] == '#167d9a') + eventually(lambda: status().get('accent') == '#167d9a') + palette.write_text(json.dumps({'accent':'#d29442'})) + assert ipc('setPreference', 'appearance.accentSource', '"matugen"').stdout.strip() == 'true' + eventually(lambda: status().get('accent') == '#d29442') + palette.write_text(json.dumps({'accent':'#32966b'})) + eventually(lambda: status().get('accent') == '#32966b') + ipc('openSettings', 'appearance') + eventually(lambda: status().get('settingsOpen')) + ipc('close') + eventually(lambda: status().get('settingsOpen') is False) + # Corrupt external edits must not destroy valid in-memory settings or overwrite the file. + eventually(lambda: json.loads(config.read_text())['appearance']['accentSource'] == 'matugen') + config.write_text('{broken') + eventually(lambda: bool(status().get('error'))) + assert ipc('setPreference', 'appearance.customAccent', '"#ffffff"').stdout.strip() == 'false' + assert config.read_text() == '{broken' + proc.terminate() + proc.wait(timeout=5) + finally: + if proc.poll() is None: + proc.terminate() + proc.wait(timeout=5) + text = log.read_text() + assert 'WARN' not in text and 'ERROR' not in text, text + print('PASS: live Wayland, duplicate prevention, preference persistence, live palette updates, settings IPC, corrupt-file protection, clean runtime logs.') diff --git a/tests/settings_runtime.py b/tests/settings_runtime.py new file mode 100644 index 0000000..e8e374f --- /dev/null +++ b/tests/settings_runtime.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +"""Real settings/palette integration using disposable images and a recording wallpaper backend.""" +import json,os,struct,subprocess,tempfile,time,zlib,shutil +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1] +BASE=['quickshell','ipc','--path',str(ROOT/'quickshell'),'call'] +def ipc(target,method,*args): + r=subprocess.run(BASE+[target,method,*map(str,args)],capture_output=True,text=True) + return json.loads(r.stdout) if r.returncode==0 and r.stdout.strip() else None +def state():return ipc('settingsTest','snapshot') or {} +def eventually(check,label,timeout=12): + end=time.monotonic()+timeout + while time.monotonic()') + +def record(kind, **values): + with events.open('a') as file: + file.write(json.dumps(dict(kind=kind, **values)) + '\n') + +SNI = 'org.kde.StatusNotifierItem' +MENU = 'com.canonical.dbusmenu' +PROPS = 'org.freedesktop.DBus.Properties' + +class TrayItem(dbus.service.Object): + def __init__(self, path, identifier, menu): + super().__init__(bus, path) + self.identifier = identifier + self.menu = menu + + def properties(self): + props = {'Category':'ApplicationStatus', 'Id':self.identifier, 'Title':self.identifier, + 'Status':'Active', 'IconName':str(icon_path), 'IconPixmap':dbus.Array([], signature='(iiay)'), + 'AttentionIconName':str(icon_path), 'AttentionIconPixmap':dbus.Array([], signature='(iiay)'), + 'OverlayIconName':'', 'OverlayIconPixmap':dbus.Array([], signature='(iiay)'), + 'ItemIsMenu':False, + 'ToolTip':dbus.Struct((str(icon_path), dbus.Array([], signature='(iiay)'), self.identifier, 'Test fixture'), signature='sa(iiay)ss')} + if self.menu: props['Menu'] = dbus.ObjectPath('/Menu') + return props + + @dbus.service.method(PROPS, in_signature='s', out_signature='a{sv}') + def GetAll(self, interface): return self.properties() if interface == SNI else {} + @dbus.service.method(PROPS, in_signature='ss', out_signature='v') + def Get(self, interface, name): return self.properties()[name] + @dbus.service.method(SNI, in_signature='ii') + def Activate(self, x, y): record('activate', item=self.identifier) + @dbus.service.method(SNI, in_signature='ii') + def SecondaryActivate(self, x, y): record('secondary', item=self.identifier) + @dbus.service.method(SNI, in_signature='ii') + def ContextMenu(self, x, y): record('context', item=self.identifier) + @dbus.service.method(SNI, in_signature='is') + def Scroll(self, delta, orientation): record('scroll', delta=delta, orientation=orientation) + +class Menu(dbus.service.Object): + def __init__(self): + super().__init__(bus, '/Menu') + self.props = { + 0:{'children-display':'submenu'}, + 1:{'label':'&Open fixture', 'icon-name':str(icon_path)}, + 2:{'type':'separator'}, + 3:{'label':'Disabled action', 'enabled':False}, + 4:{'label':'Checked option', 'toggle-type':'checkmark', 'toggle-state':dbus.Int32(1)}, + 5:{'label':'Radio option', 'toggle-type':'radio', 'toggle-state':dbus.Int32(0)}, + 6:{'label':'Submenu', 'children-display':'submenu'}, + 7:{'label':'Nested action'}, + 8:{'label':'Deeper submenu', 'children-display':'submenu'}, + 9:{'label':'Deep action'}, + 10:{'label':'Hidden action', 'visible':False}, + } + self.children = {0:[1,2,3,4,5,6,10],6:[7,8],8:[9]} + + def layout(self, ident, depth): + children = [] if depth == 0 else [dbus.Struct(self.layout(i, depth-1 if depth > 0 else -1), signature='ia{sv}av', variant_level=1) for i in self.children.get(ident, [])] + return (dbus.Int32(ident), dbus.Dictionary(self.props[ident], signature='sv'), dbus.Array(children, signature='v')) + + @dbus.service.method(PROPS, in_signature='s', out_signature='a{sv}') + def GetAll(self, interface): return {'Version':dbus.UInt32(3),'TextDirection':'ltr','Status':'normal','IconThemePath':dbus.Array([],signature='s')} + @dbus.service.method(PROPS, in_signature='ss', out_signature='v') + def Get(self, interface, name): return self.GetAll(interface)[name] + @dbus.service.method(MENU, in_signature='iias', out_signature='u(ia{sv}av)') + def GetLayout(self, parent, depth, names): return (dbus.UInt32(1), self.layout(parent, depth)) + @dbus.service.method(MENU, in_signature='aias', out_signature='a(ia{sv})') + def GetGroupProperties(self, ids, names): return [(i, self.props[i]) for i in ids] + @dbus.service.method(MENU, in_signature='is', out_signature='v') + def GetProperty(self, ident, name): return self.props[ident][name] + @dbus.service.method(MENU, in_signature='isvu') + def Event(self, ident, event, data, timestamp): + record('menu', id=int(ident), event=str(event)) + if event == 'clicked' and ident in (4,5): + self.props[ident]['toggle-state'] = dbus.Int32(1-int(self.props[ident]['toggle-state'])) + self.ItemsPropertiesUpdated([(ident, {'toggle-state':self.props[ident]['toggle-state']})], []) + @dbus.service.method(MENU, in_signature='a(isvu)', out_signature='ai') + def EventGroup(self, events): + for args in events: self.Event(*args) + return [] + @dbus.service.method(MENU, in_signature='i', out_signature='b') + def AboutToShow(self, ident): record('about', id=int(ident)); return False + @dbus.service.method(MENU, in_signature='ai', out_signature='aiai') + def AboutToShowGroup(self, ids): return ([], []) + @dbus.service.signal(MENU, signature='a(ia{sv})a(ias)') + def ItemsPropertiesUpdated(self, updated, removed): pass + +menu = Menu() +items = [TrayItem('/StatusNotifierItem', 'glassmxrph-fixture', True), TrayItem('/NoMenu', 'glassmxrph-no-menu', False)] + +def register(): + try: + watcher = dbus.Interface(bus.get_object('org.kde.StatusNotifierWatcher', '/StatusNotifierWatcher'), 'org.kde.StatusNotifierWatcher') + for path in ['/StatusNotifierItem', '/NoMenu']: watcher.RegisterStatusNotifierItem(path) + record('registered') + return False + except dbus.DBusException: return True + +GLib.timeout_add(100, register) +GLib.MainLoop().run() diff --git a/tests/tray_runtime.py b/tests/tray_runtime.py new file mode 100644 index 0000000..0d793d4 --- /dev/null +++ b/tests/tray_runtime.py @@ -0,0 +1,172 @@ +#!/usr/bin/env python3 +"""Run: dbus-run-session -- python3 tests/tray_runtime.py (real Hyprland required).""" +import json +import os +from pathlib import Path +import subprocess +import tempfile +import time +import dbus + +ROOT = Path(__file__).resolve().parents[1] +BASE = ['quickshell', 'ipc', '--path', str(ROOT / 'quickshell'), 'call'] + +def ipc(target, method, *args): + p = subprocess.run(BASE + [target, method, *map(str,args)], text=True, capture_output=True) + try: return json.loads(p.stdout) if p.returncode == 0 and p.stdout.strip() else None + except ValueError: raise AssertionError(f'IPC failed: {p.stdout} {p.stderr}') + +def eventually(check, timeout=8): + end = time.monotonic()+timeout + while time.monotonic() 100, popout() + assert ipc('trayTest','popoutScreenshot','/tmp/glassmxrph-popout-preview.png') + layers = json.loads(subprocess.check_output(['hyprctl','-j','layers'])) + assert any(item['namespace'] == 'glassMxrph-popout' for output in layers.values() for level in output['levels'].values() for item in level) + assert ipc('trayTest','leaveBar') + eventually(lambda: not popout()['open'] and not popout()['visible']) + assert ipc('trayTest','hoverModule','windowItem-0') + time.sleep(.4); assert not popout()['open'], 'Cold hover ignored the hover delay' + eventually(lambda: popout()['open'], timeout=4) + assert ipc('trayTest','leaveBar') + eventually(lambda: not popout()['open']) + else: + print('SKIP: no programs on the focused workspace for window previews') + # Click-opened menus are sticky and take keyboard focus. + assert ipc('trayTest','click',ident,2) + eventually(lambda: state()['opened'] and state()['grabbing'] and not popout()['open']) + ipc('tray','close'); eventually(lambda: not state()['opened']) + fixture.terminate(); fixture.wait(timeout=5) + eventually(lambda: len(state()['items']) == 0 and not state()['opened']) + finally: + if fixture and fixture.poll() is None: fixture.terminate(); fixture.wait(timeout=5) + shell.terminate(); shell.wait(timeout=5) + output.flush() + Path("/tmp/glassmxrph-tray-runtime.log").write_text(logs.read_text()) + text=logs.read_text() + Path('/tmp/glassmxrph-tray-runtime.log').write_text(text) + assert 'WARN' not in text and 'ERROR' not in text, text + print('PASS: SNI discovery/removal, hover delay/cancellation, pointer handover, menu states/icons, nested menus, DBus actions, disabled entries, live check updates, activation, no-menu tooltips, instant hover handover, active-window preview, hover menus without focus grabs, per-monitor anchoring, clean logs.') diff --git a/tests/widgets.test.cjs b/tests/widgets.test.cjs new file mode 100644 index 0000000..b21be3b --- /dev/null +++ b/tests/widgets.test.cjs @@ -0,0 +1,37 @@ +const assert = require('assert'), fs = require('fs'), path = require('path'), vm = require('vm'); +const api = vm.createContext({}); +vm.runInContext(fs.readFileSync(path.join(__dirname, '../quickshell/services/WidgetLogic.js'), 'utf8'), api); +const bounds = {w: 1000, h: 800}; +// Item edits are immutable. +const items = [{id: 'a', x: 0}, {id: 'b', x: 5}]; +assert.deepEqual(api.updateItem(items, 'b', {x: 9}).map(i => i.x), [0, 9]); +assert.equal(items[1].x, 5); +assert.deepEqual(api.removeItem(items, 'a').map(i => i.id), ['b']); +const id = api.newId(items); +assert(/^w-[a-z0-9]+-[a-z0-9]+$/.test(id) && !items.some(i => i.id === id)); +// Snaps to the screen edge and another widget's edge, with guides. +let s = api.snapMove({x: 6, y: 300, w: 100, h: 100}, [], bounds, 0, 10); +assert.equal(s.x, 0); assert.deepEqual(s.guides.x, [0]); +s = api.snapMove({x: 207, y: 50, w: 100, h: 100}, [{x: 100, y: 400, w: 100, h: 100}], bounds, 0, 10); +assert.equal(s.x, 200); assert.equal(s.y, 50); +// Centres snap to the screen centre. +s = api.snapMove({x: 446, y: 10, w: 100, h: 50}, [], bounds, 0, 10); +assert.equal(s.x, 450); assert.deepEqual(s.guides.x, [500]); +// Grid wins over guides; rects stay on screen. +s = api.snapMove({x: 33, y: 49, w: 100, h: 100}, [], bounds, 20, 10); +assert.deepEqual([s.x, s.y], [40, 40]); +s = api.snapMove({x: 980, y: -30, w: 100, h: 100}, [], bounds, 0, 0); +assert.deepEqual([s.x, s.y], [900, 0]); +// Resizing honours minimums from either edge and the output bounds. +const limits = {minW: 120, minH: 80, maxW: 600, maxH: 400}; +let r = api.resizeRect({x: 100, y: 100, w: 200, h: 200}, -150, 0, {right: true}, limits, bounds, 0); +assert.deepEqual([r.x, r.w], [100, 120]); +r = api.resizeRect({x: 100, y: 100, w: 200, h: 200}, 150, 0, {left: true}, limits, bounds, 0); +assert.deepEqual([r.x, r.w], [180, 120]); +r = api.resizeRect({x: 100, y: 100, w: 200, h: 200}, 0, 500, {bottom: true}, limits, bounds, 0); +assert.equal(r.h, 400); +r = api.resizeRect({x: 900, y: 100, w: 90, h: 100}, 500, 0, {right: true}, {minW: 40, minH: 40, maxW: 4000, maxH: 4000}, bounds, 0); +assert.equal(r.x + r.w, 1000); +r = api.resizeRect({x: 100, y: 100, w: 200, h: 200}, 13, 27, {right: true, bottom: true}, limits, bounds, 20); +assert.deepEqual([r.w, r.h], [220, 220]); +console.log('Desktop widget snapping, guides, grid, resize limits and immutable edits passed.');