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 <noreply@anthropic.com>
This commit is contained in:
commit
99e64a7713
433 files changed
+57792
No files matched your search
@@ -0,0 +1,2 @@
|
||||
# Unified patches contain intentional context prefixes before source whitespace.
|
||||
packaging/patches/*.patch -whitespace
|
||||
@@ -0,0 +1,5 @@
|
||||
result
|
||||
result-*
|
||||
*.log
|
||||
.cache/
|
||||
__pycache__/
|
||||
@@ -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.
|
||||
@@ -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 <git-url>`): 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.
|
||||
@@ -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"
|
||||
]
|
||||
}
|
||||
@@ -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).
|
||||
@@ -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).
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
+126
@@ -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.
|
||||
+166
@@ -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.
|
||||
@@ -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`
|
||||
@@ -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`
|
||||
+127
@@ -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`
|
||||
@@ -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`
|
||||
@@ -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`
|
||||
@@ -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).
|
||||
@@ -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.
|
||||
Generated
+27
@@ -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
|
||||
}
|
||||
@@ -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; });
|
||||
};
|
||||
}
|
||||
@@ -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";
|
||||
};
|
||||
}
|
||||
@@ -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
|
||||
@@ -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";
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 76 KiB |
@@ -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}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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 }
|
||||
}
|
||||
}
|
||||
@@ -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" : "")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
@@ -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("")
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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 } }
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
@@ -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 }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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) + "%")
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -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
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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 = '<b>';
|
||||
if (close === undefined)
|
||||
close = '</b>';
|
||||
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 = '<b>';
|
||||
if (close === undefined)
|
||||
close = '</b>';
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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", "--------------------------");
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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 {}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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<DesktopEntry> 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";
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
];
|
||||
}
|
||||
@@ -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));
|
||||
};
|
||||
@@ -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" }
|
||||
]
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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}`);
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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++;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
@@ -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 {
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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];
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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) {
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
}
|
||||
}
|
||||
Loaded 100 of 433 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user