Compare commits

...

53 Commits

Author SHA1 Message Date
jory 7603975062 refactor: changed effects, add shell completions
Nightly Release / nightly-build (push) Has been cancelled
Code Quality / quality-checks (push) Has been cancelled
Security Scan / security-audit (push) Has been cancelled
- Extract all apply_* effect methods from screenshot.rs into dedicated
  src/effects.rs (blur, vignette, pixelate, swirl) — screenshot.rs
- Rewrite apply_blur: replace broken fastblur::gaussian_blur (horizontal-
  only box blur, backbuf dropped) with correct inline two-pass sliding-
  window box blur operating directly on Cairo surface bytes — ~10×
  faster, no ImageBuffer round-trip, no fastblur dependency
- Remove melting effect entirely (seems to be hard to implement
  properely, tried multiple itterations)
- Drop unused dependencies: fastblur, rand
- Add clap_complete dependency + --completions {bash,fish,zsh} flag,
  with CompletionShell enum in config.rs
- Fix show_* flags defaulting to true: remove default_value_t=true from
  show_media, show_battery, show_network, show_bluetooth, show_album_art,
  show_caps_lock_text — all now opt-in (matching user expectation)
- Convert peek toggle to hold: toggle_peek() → set_peek_held(held: bool),
  Press calls set_peek_held(true), new Release handler iterates all
  surfaces and calls set_peek_held(false), matching Ctrl-hold behavior
- Fix cursor rendering: increase font size 11→14 for peeked chars,
  handle cursor_position == 0 (prevent negative t wrapping to far ring
  end)
- Fix peek hit-test: use shape-aware point_in_shape() instead of simple
  circle pill/square/diamond/hexagon now detect clicks correctly within
  their area
- Remove per-frame DEBUG logs: PEEK/DOT mode in lock.rs,
  set_password_display/peek_password in render/mod.rs
- Update README: embed rustlock-effects.webp demo, remove melting
  references, correct show_* defaults and options table
2026-06-28 18:17:53 +02:00
jory 833706f5a5 feat: peek-to-reveal on click/ctrl, pre-commit hooks, devShell, fmt fixes
Nightly Release / nightly-build (push) Has been cancelled
Code Quality / quality-checks (push) Has been cancelled
Security Scan / security-audit (push) Has been cancelled
- Click indicator ring to toggle password peek (persistent click-to-toggle)
- Ctrl-hold transient peek refactored to share peek path
- Cursor always visible (previously hidden at position 0, now shows at top of ring)
- .pre-commit-config.yaml: standard hooks + cargo fmt/clippy
- flake.nix: devShell with cargo, rustc, rustfmt, clippy, cargo-audit, prek
- cargo fmt pass across all source files (trailing whitespace, line wrapping)
- MPRIS error logging (silent failures now logged)
- Dependabot versioning-strategy: "increase" → "auto"
2026-06-21 20:44:59 +02:00
jory c2c093595a feat: ring shapes, auth reuse, input tests, README docs, CI improvements
Nightly Release / nightly-build (push) Has been cancelled
Code Quality / quality-checks (push) Has been cancelled
Security Scan / security-audit (push) Has been cancelled
- Add --ring-shape (circle/square/diamond/hexagon/pill) with geometry module
- Reuse PAM context across auth attempts (no reload per-keystroke)
- Proper error propagation in screenshot effects (unwrap → Result + context)
- Remove theme presets (modern/pixel/glass) and --theme flag
- Add input cooldown after failed attempt (400ms debounce)
- Add Ctrl+held peek password, Home/End/Delete cursor keys
- Add all input unit tests (23 new tests)
- Add --max-dots, feedback duration, timeout, interval config options
- Add --log-path, --auth-timeout, verifying_color config fields
- Remove unused deps: futures, gio, env_logger, num-traits, thiserror, bytemuck
- Fix media bar: remove stop button, fix art+text overlap, uniform hit areas
- Fix CI: source-only releases, nightly prereleases, dependabot groups, labeler paths
- Update issue templates with structured forms
- Add stale workflow for inactive issues/PRs
- Update README: full options table (28 flags), remove theme docs, add shapes
2026-06-21 17:28:58 +02:00
jory db3e797e36 Merge pull request #7 from josephdunn/perf/lock-idle-redraw-dirty-tracking
perf: only redraw the lock screen when something changes
2026-06-20 14:54:35 +02:00
jory c4ae3e9651 Merge pull request #6 from josephdunn/fix/lock-surface-cleanup-order
fix: clean lock-surface teardown + roundtrip on unlock (Hyprland multi-output)
2026-06-20 14:54:22 +02:00
jory 4372c7f7c0 ci: audit and harden GitHub Actions workflows
Code Quality / quality-checks (push) Has been cancelled
Security Scan / security-audit (push) Has been cancelled
- Bump all actions to latest versions (checkout@v6, upload-artifact@v7,
  download-artifact@v8, labeler@v6, gh-release@v3, gpg-import@v7)
- Replace fragile curl|bash tool install with taiki-e/install-action@v2
- Fix Swatinem/rust-cache ordering: must run AFTER toolchain install
  for correct cache key derivation
- Add --all-targets to clippy (CI now matches local testing)
- Add RUSTDOCFLAGS=-D warnings to doc step (fail on broken links)
- Fix ARM64 build order: install Rust toolchain before adding target
  and configuring linker
- Add rust-toolchain.toml pinning Rust 1.94.0 for deterministic builds
- Update Cargo.lock: rustls-webpki v0.103.11->v0.103.13 (fixes 3 CVEs)
- Fix softprops/action-gh-release@v3: include checksums in files list
  (v3 removed the checksum input parameter)
- Fix clippy manual_checked_ops lint in screenshot.rs
- Clean up trailing whitespace and missing newlines in YAML files
2026-06-20 12:57:48 +02:00
Joseph Dunn e9550f71f5 perf: only redraw the lock screen when something changes
The lock screen re-rendered and re-committed every output's full
screen-sized cairo surface on every 16ms timer tick regardless of
whether anything had changed, burning 60%+ of a core the entire time
the session was locked.

Track a dirty flag per surface and render only when state actually
changes: a keystroke, a system-status change, the clock minute rolling
over, or an in-flight animation. update() now reports whether it
redrew, so the timer commits only the surfaces that changed.

Also fix the fade-in never formally completing. The eased alpha
approaches 1.0 asymptotically while the 0.001 step throttle suppresses
the final sub-threshold increments, leaving fade_alpha stuck just under
1.0. Since "fade_alpha < 1.0" is the "still animating" signal, that kept
it permanently true and forced a full render every frame. Snap alpha to
exactly 1.0 once the fade duration elapses so the animation completes.

Idle CPU while locked drops from 60%+ to ~2%.
2026-06-04 11:02:08 -05:00
Joseph Dunn ff20423a84 fix: clean up lock surfaces and drain compositor events on unlock
Hyprland was treating multi-output rustlock unlocks as client
crashes and showing its "lockscreen died" failsafe instead of
unlocking. Two issues:

1. Order. ext-session-lock-v1 recommends destroying every
   ext_session_lock_surface_v1 before issuing unlock_and_destroy
   on ext_session_lock_v1. rustlock did the opposite. Move
   lock_surfaces.clear() into handle_auth_result so it runs
   before session_lock.unlock(), and drop the now-redundant
   clear from the auth-feedback callback.

2. Drain. After unlock_and_destroy the compositor sends
   keyboard/pointer leave events and delete_id acks; if the
   client disconnects before processing them, Hyprland treats
   the disconnect as unclean. Add a conn.roundtrip() after the
   main loop to drain those events before exit.

Single-output setups tolerate both of these (which is why the
bug does not show up on the upstream author's laptop). The
failsafe only reproduces with multiple outputs.
2026-05-22 16:43:31 -05:00
jory 6c2e3fca5a Renamed pam module to rustlock
Code Quality / quality-checks (push) Has been cancelled
Security Scan / security-audit (push) Has been cancelled
2026-04-12 11:54:41 +02:00
jory c6ec65c851 chore: add GitHub automation and fix rand vulnerability
Code Quality / quality-checks (push) Has been cancelled
Security Scan / security-audit (push) Has been cancelled
GitHub Actions:
- Add Dependabot for weekly dependency updates (cargo, github-actions)
- Add PR labeler workflow with file-based auto-labeling
- Add issue/PR templates (bug report, feature request, PR template)
- Fix release.yml artifact paths and labeler.yml config syntax
Security:
- Upgrade rand 0.8 → 0.10 to fix RUSTSEC-2026-0097 unsoundness
- Update screenshot.rs for rand 0.10 API (thread_rng → rng, gen_range → random_range)
2026-04-11 18:18:41 +02:00
jory 7a0adc4d82 docs: updated README.md
Code Quality / quality-checks (push) Has been cancelled
2026-04-11 15:49:26 +02:00
jory 016038aca0 feat: full password editing with cursor navigation
- Add arrow key support (Left/Right/Home/End) for cursor movement
- Add Delete key to remove character at cursor position
- Render cursor between password dots with visual indicator
- Modularize render.rs into separate modules (indicator, media_bar, status_bar, feedback)
- Add cubic ease-in-out for fade-in animation
- Optimize media_rects to use &'static str instead of String allocations
2026-04-11 15:43:11 +02:00
jory 05cf0c1d7e Merge pull request #4 from Almamu/fix/image-scale-position
fix: scale up or down images that do not fit the screen
2026-04-11 14:11:06 +02:00
Alexis Maiquez Murcia dab90e081e fix: use serde for toml parsing so all settings are loaded from config file and properly overriden from the commandline
Code Quality / quality-checks (push) Has been cancelled
2026-04-11 14:04:30 +02:00
jory 07d1921bd3 Merge pull request #1 from taladar/fixes_niri
Fix rustlock interaction with niri compositor
2026-04-11 13:13:28 +02:00
jory 5e0fe39304 refactor: Fixed binstall URL and added install as fallback
Code Quality / quality-checks (push) Has been cancelled
Security Scan / security-audit (push) Has been cancelled
2026-04-11 13:05:31 +02:00
jory 05593e0959 refactor: fixed security.yml and improved play/pause
Code Quality / quality-checks (push) Has been cancelled
Security Scan / security-audit (push) Has been cancelled
- New `--media-pause-icon` option
- Unified play/pause button action
- Move MPRIS lookup to spawn_blocking
- Speed up security CI with cargo-binstall
2026-04-11 12:55:45 +02:00
jory 37fb09c7c6 refactor: Fixed code with the updated dependencies
Code Quality / quality-checks (push) Has been cancelled
Security Scan / security-audit (push) Has been cancelled
2026-04-10 20:31:37 +02:00
jory 92dc3a983e refactor: resolve security advisories and update core dependencies
Code Quality / quality-checks (push) Has been cancelled
Security Scan / security-audit (push) Has been cancelled
2026-04-10 18:29:33 +02:00
jory 50a445937f refactor: Fixed code quality and fixed sec audit
Code Quality / quality-checks (push) Has been cancelled
Security Scan / security-audit (push) Has been cancelled
2026-04-10 17:50:43 +02:00
jory 61daf52906 feat: add media controls and fixed icon resolution
Code Quality / quality-checks (push) Has been cancelled
Security Scan / security-audit (push) Has been cancelled
- Implement Wayland pointer handling for interactive media buttons.
- Add pure-Rust SVG loading via resvg.
- Refactor status indicators for consistent icon and layout handling.
2026-04-10 17:32:52 +02:00
jory 49438ecd62 Refactor: curve password text and small change
Code Quality / quality-checks (push) Has been cancelled
Curve password text around the circle instead of straight dots
Cleared text is displayed on top of the circle instead of in the middle
2026-04-10 13:34:18 +02:00
jory fbd7aee9d2 feat: add cli option and ctrl+u clears password
Code Quality / quality-checks (push) Has been cancelled
Security Scan / security-audit (push) Has been cancelled
- Add `--hide-password` CLI flag
- Show temporary "CLEARED" feedback on password clear
2026-04-10 12:59:39 +02:00
Alexis Maiquez Murcia 3a9be7c696 fix: scale up or down images that do not fit the screen 2026-04-06 05:02:07 +02:00
Matthias Hörmann f8c4381a11 fix: handle dynamic output changes while session is locked
When monitors are powered off (e.g. via niri power-off-monitors or
physical power switches), niri destroys and re-advertises the Wayland
outputs as they come back. Previously all three OutputHandler callbacks
were no-ops, causing two bugs:

- new_output: no lock surface was created for outputs that appeared
  after the initial lock, so the slowest monitor to wake up would show
  the compositor's red fallback instead of the lock screen.
- output_destroyed: stale LockedSurface, SessionLockSurface, output,
  and captured_background entries accumulated for gone outputs.

Fix new_output to create a lock surface (and register it with the lock
manager) whenever a new output appears while the session is locked.

Fix output_destroyed to remove the corresponding entries from
lock_surfaces, lock_manager.surfaces, outputs, and
captured_backgrounds, keeping all parallel vecs in sync. Add
LockManager::remove_surface_by_output to support this, returning the
removal index so lock_surfaces can be updated with the same index.

The all-monitors-off scenario (all outputs destroyed simultaneously)
is handled naturally: the vecs are emptied and repopulated as each
monitor fires new_output on wake.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-27 12:57:20 +01:00
jory caa448680e Changed to GPL license as AGPL doesnt make sense
Code Quality / quality-checks (push) Has been cancelled
Security Scan / security-audit (push) Has been cancelled
2026-03-26 17:43:34 +01:00
jory c352a7cb16 Use flake.nix instead
Code Quality / quality-checks (push) Has been cancelled
2026-03-26 17:29:03 +01:00
jory 1cc69bcc61 Add flake.nix for easy building 2026-03-26 15:45:38 +01:00
Matthias Hörmann 9171f0771a fix: properly unlock on niri by flushing Wayland connection before exit
The ext-session-lock-v1 protocol does not guarantee a `finished` event
after the client calls `unlock_and_destroy` — that event is only sent
when the compositor independently terminates the lock. Waiting for it
caused rustlock to hang forever on niri (and any spec-compliant
compositor).

The previous attempt to fix this by setting exit=true immediately broke
unlocking because the while loop stopped calling event_loop.dispatch,
leaving the unlock_and_destroy bytes unflushed in the client-side
Wayland send buffer and never reaching the compositor.

Store the Connection in WaylandLock and explicitly call conn.flush()
after session_lock.unlock(), ensuring the unlock request is sent before
we exit.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-26 08:33:51 +01:00
jory 601c9677b7 Probably fix release.yml
Code Quality / quality-checks (push) Has been cancelled
Release / release-build (, arch, default) (push) Has been cancelled
Release / release-build (, debian, default) (push) Has been cancelled
Release / release-build (, fedora, default) (push) Has been cancelled
Release / release-build (, ubuntu, default) (push) Has been cancelled
Release / release-build (--no-default-features, ubuntu, no-networking) (push) Has been cancelled
Release / release (push) Has been cancelled
Security Scan / security-audit (push) Has been cancelled
2026-03-17 22:30:11 +01:00
jory 4d90e52c36 Probably fix release.yml
Code Quality / quality-checks (push) Has been cancelled
Security Scan / security-audit (push) Has been cancelled
2026-03-17 22:22:48 +01:00
jory 55c8fc0a4f refactor: Simplify deny.toml configuration
Release / release-build (, arch, default) (push) Has been cancelled
Release / release-build (, debian, default) (push) Has been cancelled
Release / release-build (, fedora, default) (push) Has been cancelled
Release / release-build (, ubuntu, default) (push) Has been cancelled
Release / release-build (--no-default-features, ubuntu, no-networking) (push) Has been cancelled
Release / release (push) Has been cancelled
2026-03-17 22:06:34 +01:00
jory aa59067bb3 fix: replace vulnerable users crate with whoami
Code Quality / quality-checks (push) Has been cancelled
Security Scan / security-audit (push) Has been cancelled
The users crate (RUSTSEC-2025-0040) has an unfixable vulnerability.
Replace it with the maintained whoami crate for getting the current
username. Also remove metrics.yml workflow as it provided no value.
2026-03-17 21:46:09 +01:00
jory c05d987ff1 fix(ci): update depgraph argument and formatting
Code Quality / quality-checks (push) Has been cancelled
Metrics Collection / collect-metrics (push) Has been cancelled
- metrics.yml: use correct --dedup-transitive-deps flag
- render.rs: apply cargo fmt fixes
2026-03-17 20:51:14 +01:00
jory a5115c0a15 Fixed typo in metrics.yml
Metrics Collection / collect-metrics (push) Has been cancelled
Code Quality / quality-checks (push) Has been cancelled
2026-03-17 20:26:28 +01:00
jory 20cc6e210e Fix all warnings previously generated by clippy 2026-03-17 20:24:12 +01:00
jory 3038c29c57 refactor(ci): extract system deps to reusable action
Metrics Collection / collect-metrics (push) Has been cancelled
Code Quality / quality-checks (push) Has been cancelled
2026-03-17 20:07:34 +01:00
jory 50c5de5371 refactor(ci): streamline GitHub workflows
Metrics Collection / collect-metrics (push) Has been cancelled
Code Quality / quality-checks (push) Has been cancelled
Security Scan / security-audit (push) Has been cancelled
- remove build.yml (redundant with release.yml)
- security.yml: remove duplicate cargo deny check (advisories redundant with full check)
- metrics.yml: remove unused rustfmt/clippy components and no-op summary step
- quality.yml: remove duplicate cargo deny check (already runs in security workflow)
2026-03-17 19:52:38 +01:00
jory 446426ea47 Fix formatting 2026-03-17 19:26:42 +01:00
jory f4f8e94e6e Added professional ci/cd pipelines to be tested
Metrics Collection / collect-metrics (push) Has been cancelled
Code Quality / quality-checks (push) Has been cancelled
Security Scan / security-audit (push) Has been cancelled
Multi-Distro Build / build-fedora (--no-default-features, no-default-features) (push) Has been cancelled
Multi-Distro Build / build-ubuntu (, default) (push) Has been cancelled
Multi-Distro Build / build-ubuntu (--no-default-features, no-default-features) (push) Has been cancelled
Multi-Distro Build / build-debian (, default) (push) Has been cancelled
Multi-Distro Build / build-debian (--no-default-features, no-default-features) (push) Has been cancelled
Multi-Distro Build / build-fedora (, default) (push) Has been cancelled
Multi-Distro Build / build-arch (, default) (push) Has been cancelled
Multi-Distro Build / build-arch (--no-default-features, no-default-features) (push) Has been cancelled
Multi-Distro Build / build-opensuse (, default) (push) Has been cancelled
Multi-Distro Build / build-opensuse (--no-default-features, no-default-features) (push) Has been cancelled
2026-03-17 19:01:09 +01:00
jory 0309522e25 Add caps lock indicator and keyboard layout support
CI / build-ubuntu (, default) (push) Has been cancelled
CI / build-ubuntu (--features networking, networking) (push) Has been cancelled
CI / build-ubuntu (--no-default-features, no-default-features) (push) Has been cancelled
CI / build-debian (push) Has been cancelled
CI / build-fedora (push) Has been cancelled
CI / build-arch (push) Has been cancelled
CI / build-opensuse (push) Has been cancelled
- Add caps lock ring color change when caps lock is enabled (matching swaylock-effects)
- Add configurable caps lock colors: ring, text, key highlight, backspace highlight
- Add show_caps_lock_text config option (enabled by default)
- Add keyboard layout display with show_keyboard_layout option (disabled by default)
- Change keyboard_layout from u32 to String for proper display
- Add rust-cache to CI and dbus-1-dev dependency
2026-03-16 17:32:54 +01:00
jory 5e47f8a69c Added capslock functionality
Added keyboard layout func
2026-03-16 15:10:23 +01:00
jory f489a6e46e feat: Add a lot more features
CI / build-ubuntu (, default) (push) Has been cancelled
CI / build-ubuntu (--features networking, networking) (push) Has been cancelled
CI / build-ubuntu (--no-default-features, no-default-features) (push) Has been cancelled
CI / build-debian (push) Has been cancelled
CI / build-fedora (push) Has been cancelled
CI / build-arch (push) Has been cancelled
CI / build-opensuse (push) Has been cancelled
- Add new system.rs module for system monitoring via D-Bus:
  - Battery status (UPower)
  - Media player controls and metadata (MPRIS)
  - WiFi/Bluetooth status (NetworkManager)
  - Keyboard layout tracking
- Add media key support (XF86 Play/Pause/Next/Prev)
- Add function keys F1-F3 for Suspend/Reboot/PowerOff
- Replace deprecated timer.rs with async system management
- Add GitHub Actions CI/CD workflows (CI + Release)
- Update dependencies and add optional networking feature
2026-03-16 14:12:43 +01:00
jory 1dc4d68cf7 fix: update Rust edition to 2021 (valid edition) 2026-03-07 23:05:00 +01:00
jory add5c9f4f6 Added todo list to README.md 2026-03-07 22:59:10 +01:00
jory ab960c5f0c Add license and update README.md 2026-03-07 22:28:49 +01:00
jory 5b3377a15b Added grace implementation 2026-03-07 22:06:22 +01:00
jory 88f7833d8d First working version with all options except grace 2026-03-07 21:48:24 +01:00
jory 7cdcf19415 Add diagnostic logging to troubleshoot screenshot display issue 2026-03-06 22:08:38 +01:00
jory 3637accaa6 Delay lock UI rendering until screenshots are captured
- Add pending_screenshots counter to WaylandLock
- Set pending_screenshots = output_count in locked() if screenshots enabled
- Timer skips rendering while pending_screenshots > 0
- Decrement pending_screenshots on Ready or Failed events
- When all screenshots done, timer starts rendering
- This ensures screenshots capture the desktop, not the lock UI

Fixes grey screenshot issue caused by capturing lock surface itself.
Matches swaylock-effects behavior: wait for screenshots before initial render.
2026-03-06 21:56:36 +01:00
jory 5fe331122e Add comprehensive debug logging for screenshot rendering
- Timer callback: log each tick and commit status
- LockedSurface::update(): log background presence, fade alpha, feedback states
- Renderer::render(): log background drawing and fade alpha
- Ready event: log background set confirmation

These logs will help diagnose why screenshots are not displaying.
2026-03-06 21:41:15 +01:00
jory 1426b2d2d0 Fix screenshot byte order conversion (critical bug)
The conversion functions were producing big-endian ARGB (A,R,G,B) but
Cairo's ARGB32 on little-endian systems expects B,G,R,A byte order.
This caused screenshots to appear completely corrupted (likely black or
solid color).

Fixed both convert_xbgr8888_to_argb32 and convert_xrgb8888_to_argb32:
- Xbgr8888: source [R,G,B,X] -> dest [B,G,R,A=255]
- Xrgb8888: source [B,G,R,X] -> dest [B,G,R,A=255]

Added detailed comments explaining memory layouts and conversion logic
to prevent future regressions.

This should make screenshots display correctly.
2026-03-06 21:30:05 +01:00
jory 8aa84209a8 Implement working screenshot capture with wlr-screencopy
- Fixed brace mismatch and duplicate code in screenshot.rs
- Increased SHM pool size to 256MB for high-res displays
- Corrected wlr-screencopy protocol usage: send copy request in Buffer event
- Fixed background handling: set_background now updates LockedSurface.background
- Removed dummy background creation; screenshots set when ready
- Added format conversion for Xbgr8888 and Xrgb8888 to ARGB32
- Proper Y-inversion handling based on flags

The lock screen now displays captured screenshots as background.
Screenshots are taken immediately after lock, before UI is shown.
Matches swaylock-effects behavior: lock appears first, then screenshot
applies when ready (no blocking).

Fixes: black/red screen issues, screenshot not displaying.
2026-03-06 21:21:47 +01:00
49 changed files with 7288 additions and 2630 deletions
+55
View File
@@ -0,0 +1,55 @@
---
name: Bug Report
about: Report a crash, visual glitch, or unexpected behavior
labels: bug
---
## Description
A clear and concise description of the bug.
## Steps to Reproduce
1.
2.
3.
## Expected Behavior
What did you expect to happen?
## Actual Behavior
What actually happened? Include any error messages, visual glitches, or crashes.
## Screenshots / Screen Recordings
If applicable, add screenshots or recordings to help explain the problem.
## Environment
- **Compositor:** (e.g., Hyprland, Sway, River, Niri)
- **Compositor version:** (e.g., Hyprland 0.47.0)
- **rustlock version:** (`rustlock --version`)
- **Display configuration:** (single monitor, multi-monitor, mixed DPI, etc.)
- **OS/Distro:** (e.g., Arch Linux, Ubuntu 24.04, Fedora 41)
## Config / CLI flags
```sh
# The exact command you used to start rustlock
# e.g., rustlock --debug --effect-blur 5x2 --theme modern
```
## Logs
```
# Paste any relevant logs here
# Run with --debug --log-file to capture verbose logs
```
## Confirmations
- [ ] I searched existing issues and this is not a duplicate
- [ ] I am running the latest version of rustlock
- [ ] I have included relevant logs and environment details
+16
View File
@@ -0,0 +1,16 @@
---
name: Feature Request
about: Suggest an idea for rustlock
labels: enhancement
---
**Is your feature request related to a problem? Please describe.**
**Describe the solution you'd like**
**Describe alternatives you've considered**
**Additional context**
+23
View File
@@ -0,0 +1,23 @@
# Pull Request Template
## Description
Please include a summary of the change and which issue is fixed (if relevant).
## Type of Change
- [ ] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
- [ ] Documentation update
- [ ] Refactoring
## How Has This Been Tested?
Please describe the tests that you ran to verify your changes.
## Checklist
- [ ] My code follows the style guidelines of this project
- [ ] I have performed a self-review of my own code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings
- [ ] I have added tests that prove my fix is effective or that my feature works
- [ ] New and existing unit tests pass locally with my changes
+17
View File
@@ -0,0 +1,17 @@
name: Install system dependencies
description: Install system dependencies required for building rustlock
runs:
using: composite
steps:
- name: Install system dependencies for Debian based distros
shell: bash
run: |
sudo apt-get update
sudo apt-get install -y \
curl \
llvm clang libclang-dev \
pkg-config \
libglib2.0-dev libcairo2-dev libpango1.0-dev libatk1.0-dev \
libgdk-pixbuf-2.0-dev libpam0g-dev libdbus-1-dev \
libwayland-dev libxkbcommon-dev
+44
View File
@@ -0,0 +1,44 @@
version: 2
updates:
- package-ecosystem: "cargo"
directory: "/"
schedule:
interval: "weekly"
day: "monday"
time: "09:00"
timezone: "UTC"
open-pull-requests-limit: 10
labels:
- "dependencies"
- "rust"
commit-message:
prefix: "deps"
reviewers:
- "JorySeverijnse"
versioning-strategy: "auto"
groups:
rust-dependencies:
patterns:
- "*"
update-types:
- "minor"
- "patch"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
day: "monday"
time: "09:00"
timezone: "UTC"
labels:
- "dependencies"
- "github-actions"
groups:
actions-dependencies:
patterns:
- "*"
update-types:
- "minor"
- "patch"
+23
View File
@@ -0,0 +1,23 @@
documentation:
- changed-files:
- any-glob-to-any-file: ['README.md', '*.md', 'docs/**']
features:
- changed-files:
- any-glob-to-any-file: ['src/input.rs', 'src/lock.rs', 'src/config.rs', 'src/auth.rs', 'src/screenshot.rs', 'src/system.rs']
rendering:
- changed-files:
- any-glob-to-any-file: ['src/render/**']
ci:
- changed-files:
- any-glob-to-any-file: ['.github/**', '.github/workflows/**']
dependencies:
- changed-files:
- any-glob-to-any-file: ['Cargo.toml', 'Cargo.lock']
refactoring:
- changed-files:
- any-glob-to-any-file: ['src/util.rs', 'src/main.rs']
@@ -0,0 +1,38 @@
name: Dependabot Automerge
on:
pull_request:
types: [opened, synchronize, reopened]
permissions:
contents: write
pull-requests: write
jobs:
automerge:
if: github.actor == 'dependabot[bot]'
runs-on: ubuntu-latest
steps:
- name: Fetch Dependabot metadata
id: metadata
uses: dependabot/fetch-metadata@v2
with:
github-token: "${{ secrets.GITHUB_TOKEN }}"
- name: Auto-approve minor/patch updates
if: |
steps.metadata.outputs.update-type == 'version-update:semver-minor' ||
steps.metadata.outputs.update-type == 'version-update:semver-patch'
run: gh pr review --approve "$PR_URL"
env:
PR_URL: ${{ github.event.pull_request.html_url }}
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Enable auto-merge for minor/patch updates
if: |
steps.metadata.outputs.update-type == 'version-update:semver-minor' ||
steps.metadata.outputs.update-type == 'version-update:semver-patch'
run: gh pr merge --auto --squash "$PR_URL"
env:
PR_URL: ${{ github.event.pull_request.html_url }}
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+15
View File
@@ -0,0 +1,15 @@
name: PR Labeler
on:
pull_request:
types: [opened, synchronize]
jobs:
label:
runs-on: ubuntu-latest
steps:
- name: Label PR based on changed files
uses: actions/labeler@v6
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
configuration-path: .github/labeler.yml
+50
View File
@@ -0,0 +1,50 @@
name: Nightly Release
on:
push:
branches: [main, master]
workflow_dispatch:
env:
CARGO_TERM_COLOR: always
jobs:
nightly-build:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
- uses: ./.github/actions/deps
- uses: Swatinem/rust-cache@v2
- uses: dtolnay/rust-toolchain@stable
- name: Set version
id: version
run: |
DATE=$(date -u +%Y%m%d%H%M)
SHA=$(git rev-parse --short HEAD)
VERSION=$(grep -m1 '^version =' Cargo.toml | cut -d'"' -f2)
echo "VERSION=${VERSION}-nightly.$DATE.$SHA" >> $GITHUB_OUTPUT
- name: Build release binary
run: cargo build --release
- name: Upload binary
uses: actions/upload-artifact@v4
with:
name: rustlock-${{ steps.version.outputs.VERSION }}
path: target/release/rustlock
- name: Create nightly release
uses: softprops/action-gh-release@v3
with:
tag_name: ${{ steps.version.outputs.VERSION }}
name: Nightly Build ${{ steps.version.outputs.VERSION }}
prerelease: true
generate_release_notes: true
+40
View File
@@ -0,0 +1,40 @@
name: Code Quality
on:
push:
branches: ["master", "main"]
pull_request:
branches: ["master", "main"]
workflow_dispatch:
env:
CARGO_TERM_COLOR: always
jobs:
quality-checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: ./.github/actions/deps
- name: Install Rust with tools
uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt, clippy
- uses: Swatinem/rust-cache@v2
- name: Check formatting
run: cargo fmt -- --check
- name: Run clippy
run: cargo clippy --all-targets -- -D warnings
- name: Run unit tests (all features)
run: cargo test --all-features --quiet
- name: Check documentation
env:
RUSTDOCFLAGS: -D warnings
run: cargo doc --no-deps --document-private-items
+49
View File
@@ -0,0 +1,49 @@
name: Release
on:
push:
tags:
- 'v*'
jobs:
release:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v7
- name: Determine tag
id: tag
run: echo "VERSION=${GITHUB_REF#refs/tags/v}" >> $GITHUB_OUTPUT
- name: Create Release
uses: softprops/action-gh-release@v3
with:
tag_name: ${{ github.ref_name }}
name: RustLock v${{ steps.tag.outputs.VERSION }}
draft: true
prerelease: ${{ contains(github.ref_name, 'alpha') || contains(github.ref_name, 'beta') }}
generate_release_notes: true
publish-crates:
runs-on: ubuntu-latest
needs: [release]
steps:
- uses: actions/checkout@v7
- uses: ./.github/actions/deps
- uses: Swatinem/rust-cache@v2
- uses: dtolnay/rust-toolchain@stable
- name: Publish to crates.io
env:
CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
run: |
if [ -z "$CARGO_REGISTRY_TOKEN" ]; then
echo "CARGO_REGISTRY_TOKEN not set — skipping publish"
exit 0
fi
cargo publish
+49
View File
@@ -0,0 +1,49 @@
name: Security Scan
on:
schedule:
- cron: '0 0 * * 0' # Weekly on Sunday at midnight
workflow_dispatch: # Manual trigger
push:
branches: [main, master]
paths:
- 'Cargo.toml'
- 'Cargo.lock'
- 'deny.toml'
- '.github/workflows/security.yml'
pull_request:
branches: [main, master]
paths:
- 'Cargo.toml'
- 'Cargo.lock'
- 'deny.toml'
- '.github/workflows/security.yml'
types: [opened, synchronize, reopened]
env:
CARGO_TERM_COLOR: always
jobs:
security-audit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- name: Install security tools
uses: taiki-e/install-action@v2
with:
tool: cargo-audit,cargo-deny,cargo-outdated
- name: Run cargo audit
run: cargo audit
- name: Run cargo deny
run: cargo deny check
- name: Check for outdated dependencies
run: cargo outdated --exit-code 1 || echo "Some dependencies are outdated"
+26
View File
@@ -0,0 +1,26 @@
name: Stale Issues and PRs
on:
schedule:
- cron: '0 0 * * *' # Daily
workflow_dispatch:
jobs:
stale:
runs-on: ubuntu-latest
permissions:
issues: write
pull-requests: write
steps:
- uses: actions/stale@v9
with:
stale-issue-message: 'This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs within 7 days.'
stale-pr-message: 'This PR has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs within 7 days.'
close-issue-message: 'This issue has been automatically closed due to inactivity.'
close-pr-message: 'This PR has been automatically closed due to inactivity.'
days-before-stale: 30
days-before-close: 7
stale-issue-label: 'stale'
stale-pr-label: 'stale'
exempt-issue-labels: 'enhancement,security'
exempt-pr-labels: 'security,work-in-progress'
+28
View File
@@ -0,0 +1,28 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0
hooks:
- id: trailing-whitespace
exclude: \.md$
- id: end-of-file-fixer
- id: check-yaml
- id: check-toml
- id: check-added-large-files
exclude: ^assets/
- id: check-merge-conflict
- repo: local
hooks:
- id: fmt
name: cargo fmt
entry: cargo fmt
args: ["--", "--check"]
language: system
types: [rust]
pass_filenames: false
- id: clippy
name: cargo clippy
entry: cargo clippy
args: ["--", "-D", "warnings"]
language: system
pass_filenames: false
Generated
+1671 -831
View File
File diff suppressed because it is too large Load Diff
+42 -17
View File
@@ -1,23 +1,48 @@
[package]
name = "wayrustlock"
name = "rustlock"
version = "0.1.0"
edition = "2021"
license = "GPL-3.0-or-later"
authors = ["Jory Severijnse"]
description = "A high-performance Wayland screen locker"
[dependencies]
smithay-client-toolkit = { version = "0.19", features = ["calloop"] }
wayland-client = "0.31"
wayland-protocols = { version = "0.32", features = ["client", "unstable"] }
cairo-rs = { version = "0.20", features = ["png"] }
image = "0.25"
fastblur = "0.1"
xkbcommon = "0.7"
pam-client = "0.5"
secstr = "0.5"
clap = { version = "4.5", features = ["derive"] }
toml = "1.0"
serde = { version = "1.0", features = ["derive"] }
zeroize = "1.7"
smithay-client-toolkit = { version = "0.19", default-features = false, features = ["calloop", "xkbcommon"] }
wayland-client = { version = "0.31" }
wayland-protocols = { version = "0.32", features = ["client"] }
wayland-protocols-wlr = { version = "0.3", features = ["client"] }
anyhow = "1.0"
cairo-rs = { version = "0.20", default-features = false, features = ["png"] }
gdk-pixbuf = { version = "0.20", default-features = false, features = ["v2_40"] }
pangocairo = { version = "0.20" }
clap = { version = "4.6", default-features = false, features = ["derive", "std", "help", "usage", "error-context"] }
clap_complete = { version = "4.6", default-features = false }
toml = { version = "1.1", default-features = false, features = ["parse", "display", "serde"] }
serde = { version = "1.0", default-features = false, features = ["derive", "std"] }
zeroize = "1.8"
log = "0.4"
env_logger = "0.11"
chrono = "0.4"
users = "0.11"
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
whoami = "1.6"
zbus = { version = "5.14", default-features = false, features = ["tokio"] }
mpris = "2.0"
tokio = { version = "1.51", default-features = false, features = ["rt", "rt-multi-thread", "macros", "time", "sync"] }
reqwest = { version = "0.12", default-features = false, features = ["blocking", "rustls-tls"], optional = true }
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
pam-client = "0.5"
calloop = "0.13"
xkbcommon = "0.7"
calloop-wayland-source = "0.3"
resvg = { version = "0.42", default-features = false }
usvg = { version = "0.42", default-features = false }
tiny-skia = "0.11"
[features]
default = ["networking"]
networking = ["dep:reqwest", "tokio/net"]
[profile.release]
opt-level = "z"
lto = true
codegen-units = 1
panic = "abort"
strip = true
+231
View File
@@ -0,0 +1,231 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on the Program.
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>.
+189 -122
View File
@@ -1,149 +1,216 @@
# wayrustlock
# 🔒 RustLock
A production-ready Wayland screen locker inspired by swaylock-effects.
[![License](https://img.shields.io/badge/license-GPL-3.0-blue.svg)](https://github.com/yourusername/rustlock/blob/main/LICENSE)
[![Version](https://img.shields.io/badge/version-0.1.0-green.svg)](https://github.com/yourusername/rustlock/releases)
## ⚠️ SAFETY WARNING - READ BEFORE USE
A high-performance Wayland screen locker written in Rust, inspired by `swaylock-effects`.
**This tool is under active development.** Screen lockers can cause system lockups if they malfunction.
<p align="center">
<img src="assets/rustlock-effects.webp" alt="RustLock effects demo" width="800">
</p>
**If the screen locker gets stuck:**
- Type password and press **Enter** to unlock (demo mode - any password works)
- Switch to another TTY: Press `Ctrl+Alt+F2`, login, then run `pkill -9 wayrustlock`
- From another terminal: `pkill -9 wayrustlock` or `killall wayrustlock`
- If screen is black/red: hard restart may be required
---
**Debug logging:** Check `~/.wayrustlock.log` to see what's happening
## ✨ Features
-**Performance**: Written in safe Rust, optimized binary size (~2.4MB without networking, ~4MB with)
- 🎨 **Visual Effects**:
- Gaussian blur (configurable radius and passes)
- Vignette effect (configurable base and factor)
- Pixelate and Swirl effects
- Smooth fade-in animation
- 🔐 **Password Indicator**:
- Circular ring with configurable radius and thickness
- Dynamic key highlight segments that rotate with each keystroke
- Full password editing with cursor navigation (arrow keys, Home/End)
- Visual cursor indicator between dots
- Caps lock indicator
- 🕐 **Information Display**:
- Centered clock (HH:MM format)
- Full date
- System uptime
- 📻 **Media & System Status** (optional):
- MPRIS media player integration with album art
- Battery percentage and charging status
- WiFi SSID and signal strength
- Bluetooth connected devices
- Keyboard layout indicator
- 🔑 **Session Management**:
- F1: Suspend
- F2: Reboot
- F3: Power Off
- 📸 **Screenshot Support**:
- Captures desktop background before locking
- Custom background image support
- 🔐 **Authentication**:
- PAM-based authentication
- Configurable grace period (any key press within N seconds unlocks without password)
- 🎯 **Customization**:
- Multiple ring shapes: circle, square, diamond, hexagon, pill
- Custom icons for WiFi, Bluetooth, Battery
- Configuration via config file or CLI
---
## 🚀 Usage
### Basic Example
**Test with timeout first:**
```bash
timeout 15 ./target/release/wayrustlock --indicator --clock
rustlock --screenshots --effect-blur 7x5 --effect-vignette 0.5:0.5
```
Then check the log file:
### Full Configuration
```bash
cat ~/.wayrustlock.log
rustlock \
--screenshots \
--clock \
--indicator \
--indicator-radius 100 \
--indicator-thickness 7 \
--ring-shape hexagon \
--effect-blur 7x5 \
--effect-vignette 0.5:0.5 \
--ring-color 785412 \
--key-hl-color 4EAC41 \
--line-color 00000000 \
--inside-color 00000088 \
--separator-color 00000000 \
--show-network \
--show-battery \
--grace 2 \
--fade-in 0.2
```
## Features (Implemented vs Planned)
### Session Controls
### ✅ Implemented
- Session locking via ext-session-lock-v1 protocol (tested on sway)
- Buffer creation from Cairo surfaces (wl_shm)
- CLI argument parsing with all swaylock-effects options
- PAM authentication infrastructure (using pam-client crate)
- Keyboard handler with proper KeyEvent processing
- Module architecture (auth, input, lock, render, screenshot, timer, util)
When locked, use function keys to control the system:
- **F1**: Suspend to RAM
- **F2**: Reboot
- **F3**: Power Off
### 🔄 In Progress
- Screenshot capture (wlr-screencopy protocol not yet integrated)
- Full PAM integration with auth loop
### Password Entry
### ❌ Not Yet Implemented
- Real screenshot capture (currently shows solid color background)
- Grace period and fade-in animations
Use arrow keys to move the cursor while entering your password:
- **Left/Right arrows**: Move cursor one position
- **Home**: Move to start
- **End**: Move to end
- **Delete**: Delete character at cursor
- **Ctrl+U**: Clear entire password
## Installation
---
## ⚙️ Configuration
Options can be provided via command line or a configuration file at `~/.config/rustlock/config.toml`. CLI arguments take precedence over config file values.
### Options
| Option | Default | Description |
|--------|---------|-------------|
| **General** | | |
| `--screenshots` | — | Capture desktop background before locking |
| `--image <PATH>` | — | Use custom background image instead of screenshot |
| `--clock` | — | Display centered clock and date |
| `--indicator` | `true` | Show password entry ring |
| `--hide-password` | `false` | Hide password dots (dots are shown by default) |
| `--config <PATH>` | — | Path to config file |
| `--debug` | — | Enable debug logging |
| **Ring** | | |
| `--indicator-radius <N>` | `100` | Ring radius in pixels |
| `--indicator-thickness <N>` | `7` | Ring thickness in pixels |
| `--ring-shape <SHAPE>` | `circle` | Ring shape: `circle`, `square`, `diamond`, `hexagon`, `pill` |
| `--max-dots <N>` | `24` | Maximum password dots in the ring |
| **Effects** | | |
| `--effect-blur <R>x<P>` | — | Gaussian blur: radius x passes (e.g., `7x5`) |
| `--effect-vignette <B>:<F>` | — | Vignette: base : factor (e.g., `0.5:0.5`) |
| `--effect-pixelate <S>` | — | Pixelate effect with block size in pixels |
| `--effect-swirl <A>` | — | Swirl distortion with angle |
| **Colors** (hex `RRGGBB[AA]`) | | |
| `--ring-color <HEX>` | `#785412` | Outer ring color |
| `--line-color <HEX>` | `#00000000` | Separator line color |
| `--inside-color <HEX>` | `#00000088` | Inner circle fill color |
| `--separator-color <HEX>` | `#00000000` | Ring segment separator color |
| `--key-hl-color <HEX>` | `#4EAC41` | Key highlight segment color |
| `--caps-lock-key-hl-color <HEX>` | `#4EAC41` | Key highlight color when caps lock is on |
| `--caps-lock-bs-hl-color <HEX>` | `#DB3300` | Backspace highlight color in caps lock |
| `--caps-lock-color <HEX>` | `#E5A445` | Caps lock indicator ring color |
| `--caps-lock-text-color <HEX>` | `#E5A445` | Caps lock text color |
| `--verifying-color <HEX>` | `#0072FF` | Verifying feedback ring color |
| `--show-caps-lock-text` | `false` | Show "CAPS" text when caps lock is active |
| **Display** | | |
| `--show-media` | `false` | Show MPRIS media player information |
| `--show-battery` | `false` | Show battery status |
| `--show-network` | `false` | Show WiFi SSID and signal strength |
| `--show-bluetooth` | `false` | Show Bluetooth status |
| `--show-album-art` | `false` | Show album art for media |
| `--show-keyboard-layout` | `false` | Show keyboard layout indicator |
| **Feedback & Timing** | | |
| `--fade-in <SECONDS>` | `0.2` | Fade-in animation duration |
| `--grace <SECONDS>` | `0` | Grace period — any key press unlocks within N seconds |
| `--auth-timeout <MS>` | `10000` | PAM authentication timeout in milliseconds |
| `--wrong-password-duration <MS>` | `500` | Wrong password feedback animation duration |
| `--key-highlight-duration <MS>` | `300` | Key highlight feedback duration |
| `--cleared-feedback-duration <MS>` | `500` | Cleared password feedback duration |
| `--verifying-timeout <MS>` | `5000` | Verifying feedback fallback timeout |
| `--feedback-window-duration <MS>` | `1000` | Wrong password feedback input window |
| `--key-highlight-window-duration <MS>` | `200` | Key highlight input-side window |
| **System** | | |
| `--pam-service <NAME>` | `rustlock` | PAM service name |
| `--system-poll-interval <S>` | `2` | Polling interval for system status updates |
| `--dbus-reconnect-delay <S>` | `5` | Delay before reconnecting DBus on failure |
| `--command-timeout <S>` | `5` | Timeout for system commands |
| **Custom Icons** (PNG/SVG path) | | |
| `--wifi-icon <PATH>` | — | Custom WiFi icon |
| `--bluetooth-icon <PATH>` | — | Custom Bluetooth icon |
| `--battery-icon <PATH>` | — | Custom battery icon |
| `--media-prev-icon <PATH>` | — | Custom previous track icon |
| `--media-stop-icon <PATH>` | — | Custom stop icon |
| `--media-play-icon <PATH>` | — | Custom play icon |
| `--media-pause-icon <PATH>` | — | Custom pause icon |
| `--media-next-icon <PATH>` | — | Custom next track icon |
| **Logging** | | |
| `--log-file` | — | Write verbose logs to `~/.rustlock.log` |
| `--log-path <PATH>` | — | Path for log file (enables file logging, overrides `--log-file` default path) |
---
## 📦 Installation
### Using Nix (Recommended)
```bash
nix-shell -p rustlock
```
Or with flakes:
```bash
nix run github:yourusername/rustlock
```
### From Source
```bash
cargo build --release
```
## Usage
The binary will be available at `target/release/rustlock`.
Basic usage:
```bash
wayrustlock
```
### Build Options
With all options from swaylock-effects compatibility:
```bash
wayrustlock \
--screenshots \
--clock \
--indicator \
--indicator-radius 100 \
--indicator-thickness 7 \
--effect-blur 7x5 \
--effect-vignette 0.5:0.5 \
--ring-color 785412 \
--key-hl-color 4EAC41 \
--line-color 00000000 \
--inside-color 00000088 \
--separator-color 00000000 \
--grace 2 \
--fade-in 0.2
```
- **With networking** (default): Includes reqwest for album art fetching
```bash
cargo build --release --features networking
```
## Command-Line Options
- **Without networking**: Smaller binary (~2.4MB)
```bash
cargo build --release --no-default-features
```
| Option | Description | Default |
|--------|-------------|---------|
| `--screenshots` | Take screenshots of each output as background | false |
| `--clock` | Show clock in center of screen | false |
| `--indicator` | Show password indicator ring | false |
| `--indicator-radius` | Radius of indicator ring in pixels | 100 |
| `--indicator-thickness` | Thickness of indicator ring in pixels | 7 |
| `--effect-blur` | Blur radius and iterations (e.g., 7x5) | none |
| `--effect-vignette` | Vignette base:factor (e.g., 0.5:0.5) | none |
| `--ring-color` | Ring color (hex RRGGBB) | 785412 |
| `--key-hl-color` | Key press highlight color | 4EAC41 |
| `--line-color` | Line color | 00000000 |
| `--inside-color` | Inside fill color | 00000088 |
| `--separator-color` | Separator color | 00000000 |
| `--grace` | Grace period in seconds before password required | 2 |
| `--fade-in` | Fade-in duration in seconds | 0.2 |
| `--pam-service` | PAM service name | login |
| `--config` | Path to TOML config file | none |
| `--debug` | Enable debug logging | false |
---
## Configuration File
## 📄 License
You can also use a TOML configuration file:
```toml
screenshots = true
clock = true
indicator = true
indicator_radius = 100
indicator_thickness = 7
effect_blur = "7x5"
effect_vignette = "0.5:0.5"
ring_color = "785412"
key_hl_color = "4EAC41"
line_color = "00000000"
inside_color = "00000088"
separator_color = "00000000"
grace = 2
fade_in = 0.2
pam_service = "login"
```
## Dependencies
- Wayland compositor (sway, labwc, etc.)
- PAM (linux-pam)
- Required Wayland protocols:
- ext-session-lock-v1
- wlr-screencopy-unstable-v1
## Building
This project requires Rust 2021 edition and the following dependencies:
- wayland development libraries
- cairo development libraries
- pam development libraries
On Debian/Ubuntu:
```bash
sudo apt install libwayland-dev libcairo2-dev libpam0g-dev
```
On Fedora:
```bash
sudo dnf install wayland-devel cairo-devel pam-devel
```
## License
MIT
GPL v3
Binary file not shown.

After

Width:  |  Height:  |  Size: 149 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 760 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 154 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 784 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 443 KiB

+26
View File
@@ -0,0 +1,26 @@
[advisories]
ignore = []
[bans]
multiple-versions = "allow"
[licenses]
allow = [
"MIT",
"Apache-2.0",
"BSD-2-Clause",
"BSD-3-Clause",
"ISC",
"Zlib",
"Unlicense",
"0BSD",
"Unicode-3.0",
"MPL-2.0",
"GPL-3.0-or-later",
"Apache-2.0 WITH LLVM-exception",
"CDLA-Permissive-2.0",
]
[sources]
allow-registry = ["https://github.com/rust-lang/crates.io-index"]
allow-git = []
Generated
+27
View File
@@ -0,0 +1,27 @@
{
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1774386573,
"narHash": "sha256-4hAV26quOxdC6iyG7kYaZcM3VOskcPUrdCQd/nx8obc=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "46db2e09e1d3f113a13c0d7b81e2f221c63b8ce9",
"type": "github"
},
"original": {
"owner": "nixos",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}
+55
View File
@@ -0,0 +1,55 @@
{
description = "A high-performance Wayland screen locker written in Rust";
inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
};
outputs = { self, nixpkgs }: let
system = "x86_64-linux";
pkgs = import nixpkgs { inherit system; };
in {
packages.${system}.default = pkgs.rustPlatform.buildRustPackage {
pname = "rustlock";
version = "0.1.0";
src = ./.;
cargoLock = { lockFile = ./Cargo.lock; };
buildInputs = with pkgs; [
cairo
pam
gdk-pixbuf
librsvg
pango
libxkbcommon
dbus
];
nativeBuildInputs = [
pkgs.pkg-config
pkgs.rustPlatform.bindgenHook
];
};
devShells.${system}.default = pkgs.mkShell {
packages = with pkgs; [
cargo
rustc
rustfmt
clippy
cargo-audit
cargo-deny
prek
pkg-config
rustPlatform.bindgenHook
cairo
pam
gdk-pixbuf
librsvg
pango
libxkbcommon
dbus
];
};
};
}
+5
View File
@@ -0,0 +1,5 @@
# PAM configuration for rustlock
# Install this file to /etc/pam.d/rustlock
# Use the standard login service authentication
auth include login
-5
View File
@@ -1,5 +0,0 @@
# PAM configuration for wayrustlock
# Install this file to /etc/pam.d/wayrustlock
# Use the standard login service authentication
auth include login
+3
View File
@@ -0,0 +1,3 @@
[toolchain]
channel = "1.94.0"
components = ["rustfmt", "clippy"]
+54 -43
View File
@@ -1,14 +1,19 @@
use std::ffi::{CStr, CString};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use log::{debug, error};
use pam_client::{Context, ErrorCode, Flag};
use smithay_client_toolkit::reexports::{calloop::channel, calloop::EventLoop};
use users::get_current_username;
use whoami::username;
use zeroize::Zeroizing;
const SERVICE_NAME: &str = "wayrustlock";
type AuthChannels = (
channel::Sender<(Zeroizing<String>, u64)>,
channel::Channel<(bool, u64)>,
);
pub struct LockConversation {
pub password: Option<Zeroizing<String>>,
}
@@ -35,59 +40,65 @@ impl pam_client::ConversationHandler for LockConversation {
}
}
pub fn create_and_run_auth_loop() -> (channel::Sender<Zeroizing<String>>, channel::Channel<bool>) {
struct AuthLoopState {
auth_res_send: channel::Sender<bool>,
main_closed: bool,
context: pam_client::Context<LockConversation>,
}
pub fn create_and_run_auth_loop(service_name: String) -> Option<AuthChannels> {
let username = username();
let username = get_current_username()
.expect("Failed to get username")
.to_str()
.expect("Failed to get non-unicode username")
.to_string();
let conversation = LockConversation { password: None };
let context = Context::new(SERVICE_NAME, Some(username.as_str()), conversation)
.expect("Failed to initialize PAM context");
debug!("Prepared to authenticate user '{}'", username);
let (auth_req_send, auth_req_recv) = channel::channel::<Zeroizing<String>>();
let (auth_res_send, auth_res_recv) = channel::channel::<bool>();
let (auth_req_send, auth_req_recv) = channel::channel::<(Zeroizing<String>, u64)>();
let (auth_res_send, auth_res_recv) = channel::channel::<(bool, u64)>();
thread::spawn(move || {
let mut event_loop: EventLoop<AuthLoopState> = EventLoop::try_new().unwrap();
let mut event_loop: EventLoop<()> = EventLoop::try_new().unwrap();
// Create PAM context once and reuse it for all auth attempts.
// Creating a new context each time is expensive because it
// re-parses configs and re-loads shared libraries for every attempt.
let conversation = LockConversation { password: None };
let mut context =
match Context::new(service_name.as_str(), Some(username.as_str()), conversation) {
Ok(ctx) => {
debug!("Prepared to authenticate user '{}'", username);
ctx
}
Err(err) => {
error!("Failed to initialize PAM context: {:?}", err);
error!(
"Ensure that the PAM service '{}' is correctly configured.",
service_name
);
return;
}
};
let running = Arc::new(AtomicBool::new(true));
let running_clone = running.clone();
event_loop
.handle()
.insert_source(auth_req_recv, |evt, _metadata, state| match evt {
channel::Event::Msg(password) => {
state.context.conversation_mut().password = Some(password);
let status = match state.context.authenticate(Flag::NONE) {
Ok(()) => true,
.insert_source(auth_req_recv, move |evt, _metadata, _state| match evt {
channel::Event::Msg((password, seq)) => {
context.conversation_mut().password = Some(password);
match context.authenticate(Flag::NONE) {
Ok(()) => {
let _ = auth_res_send.send((true, seq));
}
Err(err) => {
error!("Pam authenticate failed with {:?}", err);
false
let _ = auth_res_send.send((false, seq));
}
};
state.auth_res_send.send(status).unwrap();
}
}
channel::Event::Closed => {
running_clone.store(false, Ordering::SeqCst);
}
channel::Event::Closed => state.main_closed = true,
})
.unwrap();
let mut state = AuthLoopState {
auth_res_send,
main_closed: false,
context,
};
while !state.main_closed {
event_loop
.dispatch(None, &mut state)
.expect("Failed to run");
while running.load(Ordering::SeqCst) {
let _ = event_loop.dispatch(Some(Duration::from_millis(100)), &mut ());
}
debug!("PAM auth thread exiting cleanly");
});
(auth_req_send, auth_res_recv)
Some((auth_req_send, auth_res_recv))
}
+359 -17
View File
@@ -1,18 +1,67 @@
use crate::util;
use clap::Parser;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::path::PathBuf;
use std::str::FromStr;
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
pub enum RingShape {
#[default]
Circle,
Square,
Diamond,
Hexagon,
Pill,
}
impl FromStr for RingShape {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"circle" => Ok(RingShape::Circle),
"square" => Ok(RingShape::Square),
"diamond" => Ok(RingShape::Diamond),
"hexagon" => Ok(RingShape::Hexagon),
"pill" => Ok(RingShape::Pill),
_ => Err(format!(
"Unknown ring shape '{}'. Options: circle, square, diamond, hexagon, pill",
s
)),
}
}
}
impl fmt::Display for RingShape {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
RingShape::Circle => write!(f, "circle"),
RingShape::Square => write!(f, "square"),
RingShape::Diamond => write!(f, "diamond"),
RingShape::Hexagon => write!(f, "hexagon"),
RingShape::Pill => write!(f, "pill"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, clap::ValueEnum)]
pub enum CompletionShell {
Bash,
Fish,
Zsh,
}
#[derive(Parser, Debug, Clone, Serialize, Deserialize)]
#[command(author, version, about, long_about = None)]
pub struct Config {
#[arg(long)]
#[arg(long, action = clap::ArgAction::SetTrue)]
pub screenshots: bool,
#[arg(long)]
#[arg(long, action = clap::ArgAction::SetTrue)]
pub clock: bool,
#[arg(long, default_value = "true")]
#[arg(long, action = clap::ArgAction::SetTrue, default_value_t = true)]
pub indicator: bool,
#[arg(long, default_value = "100")]
@@ -21,28 +70,108 @@ pub struct Config {
#[arg(long, default_value = "7")]
pub indicator_thickness: u32,
#[arg(long, default_value = "circle", value_parser = clap::value_parser!(RingShape))]
#[serde(default)]
pub ring_shape: RingShape,
#[arg(long, value_parser = util::parse_blur_effect)]
#[serde(
deserialize_with = "util::deserialize_blur_effect",
serialize_with = "util::serialize_blur_effect",
default
)]
pub effect_blur: Option<(u32, u32)>,
#[arg(long, value_parser = util::parse_vignette_effect)]
#[serde(
deserialize_with = "util::deserialize_vignette_effect",
serialize_with = "util::serialize_vignette_effect",
default
)]
pub effect_vignette: Option<(f32, f32)>,
#[arg(long)]
#[serde(default)]
pub effect_pixelate: Option<u32>,
#[arg(long)]
#[serde(default)]
pub effect_swirl: Option<f32>,
#[arg(long, default_value = "785412", value_parser = util::parse_hex_color)]
#[serde(
deserialize_with = "util::deserialize_hex_color",
serialize_with = "util::serialize_hex_color"
)]
pub ring_color: (f64, f64, f64, f64),
#[arg(long, default_value = "4EAC41", value_parser = util::parse_hex_color)]
#[serde(
deserialize_with = "util::deserialize_hex_color",
serialize_with = "util::serialize_hex_color"
)]
pub key_hl_color: (f64, f64, f64, f64),
#[arg(long, default_value = "4EAC41", value_parser = util::parse_hex_color)]
#[serde(
deserialize_with = "util::deserialize_hex_color",
serialize_with = "util::serialize_hex_color"
)]
pub caps_lock_key_hl_color: (f64, f64, f64, f64),
#[arg(long, default_value = "DB3300", value_parser = util::parse_hex_color)]
#[serde(
deserialize_with = "util::deserialize_hex_color",
serialize_with = "util::serialize_hex_color"
)]
pub caps_lock_bs_hl_color: (f64, f64, f64, f64),
#[arg(long, default_value = "E5A445", value_parser = util::parse_hex_color)]
#[serde(
deserialize_with = "util::deserialize_hex_color",
serialize_with = "util::serialize_hex_color"
)]
pub caps_lock_color: (f64, f64, f64, f64),
#[arg(long, default_value = "E5A445", value_parser = util::parse_hex_color)]
#[serde(
deserialize_with = "util::deserialize_hex_color",
serialize_with = "util::serialize_hex_color"
)]
pub caps_lock_text_color: (f64, f64, f64, f64),
#[arg(long, default_value = "0072FF", value_parser = util::parse_hex_color)]
#[serde(
deserialize_with = "util::deserialize_hex_color",
serialize_with = "util::serialize_hex_color"
)]
pub verifying_color: (f64, f64, f64, f64),
#[arg(long, action = clap::ArgAction::SetTrue)]
pub show_caps_lock_text: bool,
#[arg(long, default_value = "00000000", value_parser = util::parse_hex_color)]
#[serde(
deserialize_with = "util::deserialize_hex_color",
serialize_with = "util::serialize_hex_color"
)]
pub line_color: (f64, f64, f64, f64),
#[arg(long, default_value = "00000088", value_parser = util::parse_hex_color)]
#[serde(
deserialize_with = "util::deserialize_hex_color",
serialize_with = "util::serialize_hex_color"
)]
pub inside_color: (f64, f64, f64, f64),
#[arg(long, default_value = "00000000", value_parser = util::parse_hex_color)]
#[serde(
deserialize_with = "util::deserialize_hex_color",
serialize_with = "util::serialize_hex_color"
)]
pub separator_color: (f64, f64, f64, f64),
#[arg(long, default_value = "2")]
#[arg(long, default_value = "0")]
pub grace: f32,
#[arg(long, default_value = "0.2")]
@@ -57,30 +186,243 @@ pub struct Config {
#[arg(long)]
pub debug: bool,
/// Show screen temporarily when a key is pressed (like swaylock-effects peek)
/// Write verbose logs to ~/.rustlock.log
#[arg(long)]
pub temp_screenshot: bool,
pub log_file: bool,
/// Path for log file (enables file logging, overrides --log-file default path)
#[arg(long)]
#[serde(default)]
pub log_path: Option<PathBuf>,
/// Timeout (ms) for PAM authentication before showing failure
#[arg(long, default_value = "10000")]
pub auth_timeout: u64,
#[arg(long, action = clap::ArgAction::SetTrue)]
pub show_media: bool,
#[arg(long, action = clap::ArgAction::SetTrue)]
pub show_battery: bool,
#[arg(long, action = clap::ArgAction::SetTrue)]
pub show_network: bool,
#[arg(long, action = clap::ArgAction::SetTrue)]
pub show_bluetooth: bool,
#[arg(long, action = clap::ArgAction::SetTrue)]
pub show_album_art: bool,
#[arg(long, action = clap::ArgAction::SetTrue)]
pub hide_password: bool,
#[arg(long, action = clap::ArgAction::SetTrue)]
pub show_keyboard_layout: bool,
#[arg(long)]
#[serde(default)]
pub image: Option<PathBuf>,
#[arg(long)]
#[serde(default)]
pub wifi_icon: Option<String>,
#[arg(long)]
#[serde(default)]
pub bluetooth_icon: Option<String>,
#[arg(long)]
#[serde(default)]
pub battery_icon: Option<String>,
#[arg(long)]
#[serde(default)]
pub media_prev_icon: Option<String>,
#[arg(long)]
#[serde(default)]
pub media_stop_icon: Option<String>,
#[arg(long)]
#[serde(default)]
pub media_play_icon: Option<String>,
#[arg(long)]
#[serde(default)]
pub media_pause_icon: Option<String>,
#[arg(long)]
#[serde(default)]
pub media_next_icon: Option<String>,
/// Maximum number of password dots in the indicator ring
#[arg(long, default_value = "24")]
pub max_dots: u32,
/// Duration (ms) for wrong password feedback animation
#[arg(long, default_value = "500")]
pub wrong_password_duration: u64,
/// Duration (ms) for key highlight feedback animation
#[arg(long, default_value = "300")]
pub key_highlight_duration: u64,
/// Duration (ms) for cleared password feedback animation
#[arg(long, default_value = "500")]
pub cleared_feedback_duration: u64,
/// Duration (ms) for verifying feedback fallback timeout
#[arg(long, default_value = "5000")]
pub verifying_timeout: u64,
/// Duration (ms) that wrong password feedback is shown input-side
#[arg(long, default_value = "1000")]
pub feedback_window_duration: u64,
/// Duration (ms) for key highlight feedback input-side window
#[arg(long, default_value = "200")]
pub key_highlight_window_duration: u64,
/// Polling interval (seconds) for system status updates
#[arg(long, default_value = "2")]
pub system_poll_interval: u64,
/// Delay (seconds) before reconnecting DBus on failure
#[arg(long, default_value = "5")]
pub dbus_reconnect_delay: u64,
/// Timeout (seconds) for system commands (poweroff, reboot, suspend)
#[arg(long, default_value = "5")]
pub command_timeout: u64,
/// Generate shell completions for the given shell
#[arg(long, value_enum)]
#[serde(skip)]
pub completions: Option<CompletionShell>,
}
impl Config {
pub fn load() -> Self {
use clap::CommandFactory;
let mut config = Config::parse();
if let Some(config_path) = &config.config {
if let Ok(file_content) = std::fs::read_to_string(config_path) {
if let Ok(file_config) = toml::from_str::<Config>(&file_content) {
config = file_config;
} else {
eprintln!(
"Warning: Failed to parse config file {}",
config_path.display()
);
// Handle --completions early (before config file merge so file can't inject it)
if let Some(shell) = config.completions {
use clap_complete::Shell;
let mut cmd = Config::command();
let name = "rustlock";
match shell {
CompletionShell::Bash => {
clap_complete::generate(Shell::Bash, &mut cmd, name, &mut std::io::stdout())
}
CompletionShell::Fish => {
clap_complete::generate(Shell::Fish, &mut cmd, name, &mut std::io::stdout())
}
CompletionShell::Zsh => {
clap_complete::generate(Shell::Zsh, &mut cmd, name, &mut std::io::stdout())
}
}
std::process::exit(0);
}
let cmd = Config::command();
let matches = cmd.get_matches();
// Helper to check if a value was explicitly set on command line
let is_cli =
|key: &str| matches.value_source(key) == Some(clap::parser::ValueSource::CommandLine);
// Config file layer (overrides defaults, CLI args take precedence)
let config_path = config.config.clone().unwrap_or_else(|| {
let mut path = std::path::PathBuf::from(std::env::var("HOME").unwrap_or_default());
path.push(".config/rustlock/config.toml");
path
});
if config_path.exists() {
if let Ok(file_content) = std::fs::read_to_string(&config_path) {
if let Ok(file_table) = toml::from_str::<toml::Table>(&file_content) {
log::debug!("Loaded configuration from {:?}", config_path);
// Convert current config to a TOML table to facilitate merging
if let Ok(mut config_table) = toml::Value::try_from(config.clone()) {
if let Some(config_table) = config_table.as_table_mut() {
for (key, value) in file_table {
if !is_cli(&key) {
config_table.insert(key, value);
}
}
// Convert back to Config struct
if let Ok(new_config) =
toml::Value::Table(config_table.clone()).try_into::<Config>()
{
config = new_config;
}
}
}
}
} else {
eprintln!("Warning: Config file {} not found", config_path.display());
}
}
config.auth_timeout = config.auth_timeout.max(100);
config.max_dots = config.max_dots.max(1);
config.fade_in = config.fade_in.max(0.0);
config.grace = config.grace.max(0.0);
config
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_max_dots_default() {
let config = Config::parse_from(["test"]);
assert_eq!(config.max_dots, 24);
}
#[test]
fn test_auth_timeout_default() {
let config = Config::parse_from(["test"]);
assert_eq!(config.auth_timeout, 10000);
}
#[test]
fn test_auth_timeout_min_clamp() {
let mut config = Config::parse_from(["test", "--auth-timeout", "0"]);
config.auth_timeout = config.auth_timeout.max(100);
assert_eq!(config.auth_timeout, 100);
}
#[test]
fn test_max_dots_min_clamp() {
let mut config = Config::parse_from(["test", "--max-dots", "0"]);
config.max_dots = config.max_dots.max(1);
assert_eq!(config.max_dots, 1);
}
#[test]
fn test_fade_in_negative_clamp() {
let mut config = Config::parse_from(["test", "--fade-in=-1"]);
config.fade_in = config.fade_in.max(0.0);
assert_eq!(config.fade_in, 0.0);
}
#[test]
fn test_grace_negative_clamp() {
let mut config = Config::parse_from(["test", "--grace=-1"]);
config.grace = config.grace.max(0.0);
assert_eq!(config.grace, 0.0);
}
#[test]
fn test_log_path_default_none() {
let config = Config::parse_from(["test"]);
assert!(config.log_path.is_none());
}
}
+285
View File
@@ -0,0 +1,285 @@
//! Visual effects for lock screen backgrounds.
//!
//! Each effect takes a `&mut ImageSurface` and processes it in-place.
//! Effects are applied in order: blur → vignette → pixelate → swirl.
use anyhow::{Context, Result};
use cairo::ImageSurface;
/// Apply a swirl effect (radial rotation around the image centre).
pub fn apply_swirl(surface: &mut ImageSurface, angle: f32) -> Result<()> {
let width = surface.width();
let height = surface.height();
let center_x = width as f32 / 2.0;
let center_y = height as f32 / 2.0;
let radius = center_x.min(center_y);
let stride = surface.stride() as usize;
let mut data = vec![0u8; stride * height as usize];
surface
.with_data(|src| data.copy_from_slice(src))
.context("swirl: failed to read surface data")?;
let original = data.clone();
for y in 0..height {
for x in 0..width {
let dx = x as f32 - center_x;
let dy = y as f32 - center_y;
let d = (dx * dx + dy * dy).sqrt();
if d < radius {
let percent = (radius - d) / radius;
let theta = percent * percent * angle;
let s = theta.sin();
let c = theta.cos();
let nx = (c * dx - s * dy + center_x) as i32;
let ny = (s * dx + c * dy + center_y) as i32;
if nx >= 0 && nx < width && ny >= 0 && ny < height {
let src_idx = (ny as usize * stride) + (nx as usize * 4);
let dst_idx = (y as usize * stride) + (x as usize * 4);
data[dst_idx..dst_idx + 4].copy_from_slice(&original[src_idx..src_idx + 4]);
}
}
}
}
let mut surface_data = surface
.data()
.context("swirl: failed to write surface data")?;
surface_data.copy_from_slice(&data);
Ok(())
}
/// Pixelate the surface.
pub fn apply_pixelate(surface: &mut ImageSurface, pixel_size: u32) -> Result<()> {
if pixel_size <= 1 {
return Ok(());
}
let width = surface.width();
let height = surface.height();
let stride = surface.stride() as usize;
let mut data = vec![0u8; stride * height as usize];
surface
.with_data(|src| data.copy_from_slice(src))
.context("pixelate: failed to read surface data")?;
for y in (0..height).step_by(pixel_size as usize) {
for x in (0..width).step_by(pixel_size as usize) {
let mut r = 0u32;
let mut g = 0u32;
let mut b = 0u32;
let mut count = 0u32;
// Average pixels in the block
for py in 0..pixel_size {
for px in 0..pixel_size {
let cur_x = x + px as i32;
let cur_y = y + py as i32;
if cur_x < width && cur_y < height {
let index = (cur_y as usize * stride) + (cur_x as usize * 4);
r += data[index] as u32;
g += data[index + 1] as u32;
b += data[index + 2] as u32;
count += 1;
}
}
}
if count > 0 {
let r = r.checked_div(count).unwrap_or(0) as u8;
let g = g.checked_div(count).unwrap_or(0) as u8;
let b = b.checked_div(count).unwrap_or(0) as u8;
// Fill the block
for py in 0..pixel_size {
for px in 0..pixel_size {
let cur_x = x + px as i32;
let cur_y = y + py as i32;
if cur_x < width && cur_y < height {
let index = (cur_y as usize * stride) + (cur_x as usize * 4);
data[index] = r;
data[index + 1] = g;
data[index + 2] = b;
}
}
}
}
}
}
let mut surface_data = surface
.data()
.context("pixelate: failed to write surface data")?;
surface_data.copy_from_slice(&data);
Ok(())
}
/// Apply a box blur effect (fast two-pass sliding-window implementation).
/// Uses multiply-shift to avoid slow integer division in the hot loop.
pub fn apply_blur(surface: &mut ImageSurface, radius: u32, times: u32) -> Result<()> {
if radius == 0 || times == 0 {
return Ok(());
}
let width = surface.width() as usize;
let height = surface.height() as usize;
let stride = surface.stride() as usize;
let r = radius as usize;
let mut data = vec![0u8; stride * height];
surface
.with_data(|src| data.copy_from_slice(src))
.context("blur: failed to read surface data")?;
let mut scratch = vec![0u8; stride * height];
// Precompute ceil(2^32 / c) for every possible window size c.
let max_count = (2 * r + 1).min(width.max(height));
let factor: Vec<u32> = (0..=max_count)
.map(|c| {
if c == 0 {
0
} else {
(1u64 << 32).div_ceil(c as u64) as u32
}
})
.collect();
#[inline(always)]
fn div_mul(n: u32, factor: u32) -> u8 {
((n as u64 * factor as u64) >> 32) as u8
}
for _ in 0..times {
// Horizontal box blur: data -> scratch
for y in 0..height {
let row = y * stride;
let init_end = r.min(width - 1);
let mut b_acc = 0u32;
let mut g_acc = 0u32;
let mut r_acc = 0u32;
for x in 0..=init_end {
let px = row + x * 4;
b_acc += data[px] as u32;
g_acc += data[px + 1] as u32;
r_acc += data[px + 2] as u32;
}
let mut count = (init_end + 1) as u32;
for x in 0..width {
let dst = row + x * 4;
let f = factor[count as usize];
scratch[dst] = div_mul(b_acc, f);
scratch[dst + 1] = div_mul(g_acc, f);
scratch[dst + 2] = div_mul(r_acc, f);
scratch[dst + 3] = data[dst + 3];
if x >= r {
let old = row + (x - r) * 4;
b_acc -= data[old] as u32;
g_acc -= data[old + 1] as u32;
r_acc -= data[old + 2] as u32;
count -= 1;
}
if x + r + 1 < width {
let new = row + (x + r + 1) * 4;
b_acc += data[new] as u32;
g_acc += data[new + 1] as u32;
r_acc += data[new + 2] as u32;
count += 1;
}
}
}
// Vertical box blur: scratch -> data
let init_end = r.min(height - 1);
let mut b_acc = vec![0u32; width];
let mut g_acc = vec![0u32; width];
let mut r_acc = vec![0u32; width];
for y in 0..=init_end {
let row = y * stride;
for x in 0..width {
let px = row + x * 4;
b_acc[x] += scratch[px] as u32;
g_acc[x] += scratch[px + 1] as u32;
r_acc[x] += scratch[px + 2] as u32;
}
}
let mut count = (init_end + 1) as u32;
for y in 0..height {
let f = factor[count as usize];
let dst_row = y * stride;
for x in 0..width {
let dst = dst_row + x * 4;
data[dst] = div_mul(b_acc[x], f);
data[dst + 1] = div_mul(g_acc[x], f);
data[dst + 2] = div_mul(r_acc[x], f);
}
if y >= r {
let old_row = (y - r) * stride;
for x in 0..width {
let px = old_row + x * 4;
b_acc[x] -= scratch[px] as u32;
g_acc[x] -= scratch[px + 1] as u32;
r_acc[x] -= scratch[px + 2] as u32;
}
count -= 1;
}
if y + r + 1 < height {
let new_row = (y + r + 1) * stride;
for x in 0..width {
let px = new_row + x * 4;
b_acc[x] += scratch[px] as u32;
g_acc[x] += scratch[px + 1] as u32;
r_acc[x] += scratch[px + 2] as u32;
}
count += 1;
}
}
}
let mut surface_data = surface.data()?;
surface_data.copy_from_slice(&data);
Ok(())
}
/// Apply a vignette effect (darken edges).
pub fn apply_vignette(surface: &mut ImageSurface, base: f32, factor: f32) -> Result<()> {
let width = surface.width();
let height = surface.height();
let center_x = width as f32 / 2.0;
let center_y = height as f32 / 2.0;
let max_distance = (center_x * center_x + center_y * center_y).sqrt();
let stride = surface.stride() as usize;
let mut data = vec![0u8; stride * height as usize];
surface
.with_data(|src| data.copy_from_slice(src))
.context("vignette: failed to read surface data")?;
for y in 0..height {
for x in 0..width {
let dx = x as f32 - center_x;
let dy = y as f32 - center_y;
let distance = (dx * dx + dy * dy).sqrt();
let vignette_factor = base + (1.0 - base) * (distance / max_distance).powf(factor);
let index = (y as usize * stride) + (x as usize * 4);
for i in 0..3 {
let value = data[index + i] as f32 * vignette_factor;
data[index + i] = value.clamp(0.0, 255.0) as u8;
}
}
}
let mut surface_data = surface
.data()
.context("vignette: failed to write surface data")?;
surface_data.copy_from_slice(&data);
Ok(())
}
+367 -142
View File
@@ -4,11 +4,11 @@ use zeroize::Zeroizing;
pub struct InputHandler {
password_buffer: Zeroizing<String>,
cursor_position: usize,
config: crate::config::Config,
wrong_password_timer: Option<std::time::Instant>,
key_highlight_timer: Option<std::time::Instant>,
temp_screenshot_timer: Option<std::time::Instant>,
temp_screenshot_active: bool,
caps_lock: bool,
config: crate::config::Config,
last_failed_attempt: Option<std::time::Instant>,
}
impl InputHandler {
@@ -16,11 +16,11 @@ impl InputHandler {
Self {
password_buffer: Zeroizing::new(String::new()),
cursor_position: 0,
config,
wrong_password_timer: None,
key_highlight_timer: None,
temp_screenshot_timer: None,
temp_screenshot_active: false,
caps_lock: false,
config,
last_failed_attempt: None,
}
}
@@ -28,141 +28,130 @@ impl InputHandler {
pub fn handle_key_event(
&mut self,
keysym: smithay_client_toolkit::seat::keyboard::Keysym,
state: wayland_client::protocol::wl_keyboard::KeyState,
utf8: Option<String>,
modifiers: smithay_client_toolkit::seat::keyboard::Modifiers,
) -> InputAction {
// Only process key press events
if state != wayland_client::protocol::wl_keyboard::KeyState::Pressed {
if self.is_cooldown() {
return InputAction::None;
}
// Convert keysym to character
let ch = self.keysym_to_char(keysym, modifiers);
self.caps_lock = modifiers.caps_lock;
match ch {
Some('\x08') | Some('\x7f') => {
// Backspace or Delete
if !self.password_buffer.is_empty() && self.cursor_position > 0 {
self.cursor_position -= 1;
self.password_buffer.remove(self.cursor_position);
}
InputAction::PasswordChanged
if modifiers.ctrl && keysym == Keysym::u {
if !self.password_buffer.is_empty() {
self.password_buffer.clear();
self.cursor_position = 0;
return InputAction::PasswordCleared;
}
Some('\r') | Some('\n') => {
// Enter key - submit password
return InputAction::None;
}
// Handle special keys first using keysym
use smithay_client_toolkit::seat::keyboard::Keysym;
match keysym {
Keysym::BackSpace => {
if self.password_buffer.is_empty() || self.cursor_position == 0 {
return InputAction::None;
}
self.cursor_position -= 1;
self.password_buffer.remove(self.cursor_position);
if self.password_buffer.is_empty() {
return InputAction::PasswordCleared;
}
return InputAction::PasswordChanged;
}
Keysym::Return | Keysym::KP_Enter => {
let password = self.password_buffer.clone();
self.password_buffer.clear();
self.cursor_position = 0;
InputAction::SubmitPassword(password)
return InputAction::SubmitPassword(password);
}
Some('\x1b') => {
// Escape key - cancel
InputAction::Cancel
Keysym::Escape => {
return InputAction::Cancel;
}
Some('p') | Some('P') if self.config.temp_screenshot => {
// 'p' key for temp screenshot peek
self.activate_temp_screenshot();
InputAction::TempScreenshot
Keysym::Left => {
if self.cursor_position > 0 {
self.cursor_position -= 1;
return InputAction::CursorMoved;
}
return InputAction::None;
}
Some(c) if c.is_ascii() && !c.is_control() => {
// Printable ASCII character
self.password_buffer.insert(self.cursor_position, c);
self.cursor_position += 1;
InputAction::PasswordChanged
Keysym::Right => {
if self.cursor_position < self.password_buffer.len() {
self.cursor_position += 1;
return InputAction::CursorMoved;
}
return InputAction::None;
}
_ => {
// Other keys (function keys, arrows, etc.)
InputAction::None
Keysym::Home => {
if self.cursor_position > 0 {
self.cursor_position = 0;
return InputAction::CursorMoved;
}
return InputAction::None;
}
Keysym::End => {
if self.cursor_position < self.password_buffer.len() {
self.cursor_position = self.password_buffer.len();
return InputAction::CursorMoved;
}
return InputAction::None;
}
Keysym::Delete => {
if self.cursor_position < self.password_buffer.len() {
self.password_buffer.remove(self.cursor_position);
if self.password_buffer.is_empty() {
return InputAction::PasswordCleared;
}
return InputAction::PasswordChanged;
}
return InputAction::None;
}
}
}
/// Convert a keysym to a character, considering modifiers
fn keysym_to_char(
&self,
keysym: smithay_client_toolkit::seat::keyboard::Keysym,
modifiers: smithay_client_toolkit::seat::keyboard::Modifiers,
) -> Option<char> {
use smithay_client_toolkit::seat::keyboard::Keysym;
// Handle special keys first
match keysym {
Keysym::BackSpace => return Some('\x08'),
Keysym::Delete => return Some('\x7f'),
Keysym::Return => return Some('\r'),
Keysym::KP_Enter => return Some('\n'),
Keysym::Escape => return Some('\x1b'),
_ => {}
}
// Convert keysym to character
let keysym_value = keysym.raw();
// Basic ASCII conversion (simplified - real implementation would use xkbcommon)
// This is a simplified mapping for demonstration
if keysym_value >= 0x20 && keysym_value <= 0x7e {
let mut ch = keysym_value as u8 as char;
// Apply shift modifier
if modifiers.shift {
ch = match ch {
'`' => '~',
'1' => '!',
'2' => '@',
'3' => '#',
'4' => '$',
'5' => '%',
'6' => '^',
'7' => '&',
'8' => '*',
'9' => '(',
'0' => ')',
'-' => '_',
'=' => '+',
'[' => '{',
']' => '}',
'\\' => '|',
';' => ':',
'\'' => '"',
',' => '<',
'.' => '>',
'/' => '?',
c if c.is_ascii_lowercase() => c.to_ascii_uppercase(),
_ => ch,
};
// Use the UTF-8 string provided by SCTK for character input
if let Some(txt) = utf8 {
for c in txt.chars() {
if c.is_ascii() && !c.is_control() {
self.password_buffer.insert(self.cursor_position, c);
self.cursor_position += 1;
}
}
Some(ch)
} else {
None
return InputAction::PasswordChanged;
}
InputAction::None
}
/// Get the current password (for display purposes only - returns masked version)
pub fn get_display_password(&self) -> String {
self.password_buffer.chars().map(|_| '•').collect()
pub fn password_buffer(&self) -> &Zeroizing<String> {
&self.password_buffer
}
/// Get the actual password (for authentication)
pub fn get_password(&self) -> Zeroizing<String> {
self.password_buffer.clone()
pub fn password_length(&self) -> usize {
self.password_buffer.len()
}
/// Clear the password buffer (e.g., after wrong password)
pub fn clear_password(&mut self) {
self.password_buffer.clear();
self.cursor_position = 0;
pub fn cursor_position(&self) -> usize {
self.cursor_position
}
/// Set wrong password feedback timer
pub fn set_wrong_password_feedback(&mut self) {
self.wrong_password_timer = Some(std::time::Instant::now());
self.last_failed_attempt = Some(std::time::Instant::now());
}
pub fn is_cooldown(&self) -> bool {
self.last_failed_attempt
.map(|t| t.elapsed() < std::time::Duration::from_millis(400))
.unwrap_or(false)
}
/// Check if wrong password feedback should be shown
pub fn should_show_wrong_password(&self) -> bool {
if let Some(timer) = self.wrong_password_timer {
timer.elapsed() < std::time::Duration::from_millis(1000)
timer.elapsed() < std::time::Duration::from_millis(self.config.feedback_window_duration)
} else {
false
}
@@ -176,47 +165,16 @@ impl InputHandler {
/// Check if key highlight should be shown
pub fn should_show_key_highlight(&self) -> bool {
if let Some(timer) = self.key_highlight_timer {
timer.elapsed() < std::time::Duration::from_millis(200)
timer.elapsed()
< std::time::Duration::from_millis(self.config.key_highlight_window_duration)
} else {
false
}
}
/// Update timers (should be called periodically)
pub fn update(&mut self) {
// Update temp screenshot state
self.update_temp_screenshot();
}
/// Activate temporary screenshot display (peek feature)
pub fn activate_temp_screenshot(&mut self) {
self.temp_screenshot_timer = Some(std::time::Instant::now());
self.temp_screenshot_active = true;
}
/// Check if temporary screenshot should be shown
pub fn should_show_temp_screenshot(&self) -> bool {
if let Some(timer) = self.temp_screenshot_timer {
let elapsed = timer.elapsed();
// Show for 2 seconds
if elapsed < std::time::Duration::from_secs(2) {
return true;
}
}
false
}
/// Check if temp screenshot is currently active
pub fn is_temp_screenshot_active(&self) -> bool {
self.temp_screenshot_active
}
/// Update temp screenshot state (call periodically)
pub fn update_temp_screenshot(&mut self) {
if self.temp_screenshot_active && !self.should_show_temp_screenshot() {
self.temp_screenshot_active = false;
self.temp_screenshot_timer = None;
}
/// Get the current Caps Lock state
pub fn caps_lock(&self) -> bool {
self.caps_lock
}
}
@@ -225,7 +183,274 @@ impl InputHandler {
pub enum InputAction {
None,
PasswordChanged,
PasswordCleared,
CursorMoved,
SubmitPassword(Zeroizing<String>),
Cancel,
TempScreenshot,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::Config;
use clap::Parser;
use smithay_client_toolkit::seat::keyboard::{Keysym, Modifiers};
fn test_config() -> Config {
Config::parse_from(["test"])
}
#[test]
fn test_new_handler_defaults() {
let handler = InputHandler::new(test_config());
assert_eq!(handler.password_length(), 0);
assert_eq!(handler.cursor_position(), 0);
assert!(!handler.caps_lock());
assert!(!handler.should_show_wrong_password());
assert!(!handler.should_show_key_highlight());
}
#[test]
fn test_character_input_appends() {
let mut handler = InputHandler::new(test_config());
let mods = Modifiers::default();
let action = handler.handle_key_event(Keysym::a, Some("a".to_string()), mods);
assert!(matches!(action, InputAction::PasswordChanged));
assert_eq!(handler.password_length(), 1);
assert_eq!(handler.cursor_position(), 1);
let action = handler.handle_key_event(Keysym::b, Some("b".to_string()), mods);
assert!(matches!(action, InputAction::PasswordChanged));
assert_eq!(handler.password_length(), 2);
assert_eq!(handler.cursor_position(), 2);
assert_eq!(&*handler.password_buffer, "ab");
}
#[test]
fn test_backspace_removes_last_char() {
let mut handler = InputHandler::new(test_config());
let mods = Modifiers::default();
handler.handle_key_event(Keysym::a, Some("a".to_string()), mods);
handler.handle_key_event(Keysym::b, Some("b".to_string()), mods);
assert_eq!(handler.password_length(), 2);
let action = handler.handle_key_event(Keysym::BackSpace, None, mods);
assert!(matches!(action, InputAction::PasswordChanged));
assert_eq!(handler.password_length(), 1);
assert_eq!(handler.cursor_position(), 1);
assert_eq!(&*handler.password_buffer, "a");
}
#[test]
fn test_backspace_on_empty_buffer() {
let mut handler = InputHandler::new(test_config());
let mods = Modifiers::default();
let action = handler.handle_key_event(Keysym::BackSpace, None, mods);
assert!(matches!(action, InputAction::None));
assert_eq!(handler.password_length(), 0);
}
#[test]
fn test_backspace_last_char_clears() {
let mut handler = InputHandler::new(test_config());
let mods = Modifiers::default();
handler.handle_key_event(Keysym::a, Some("a".to_string()), mods);
let action = handler.handle_key_event(Keysym::BackSpace, None, mods);
assert!(matches!(action, InputAction::PasswordCleared));
assert_eq!(handler.password_length(), 0);
}
#[test]
fn test_ctrl_u_clears_buffer() {
let mut handler = InputHandler::new(test_config());
let mods = Modifiers {
ctrl: true,
..Modifiers::default()
};
handler.handle_key_event(Keysym::a, Some("a".to_string()), Modifiers::default());
handler.handle_key_event(Keysym::b, Some("b".to_string()), Modifiers::default());
assert_eq!(handler.password_length(), 2);
let action = handler.handle_key_event(Keysym::u, None, mods);
assert!(matches!(action, InputAction::PasswordCleared));
assert_eq!(handler.password_length(), 0);
assert_eq!(handler.cursor_position(), 0);
}
#[test]
fn test_submit_returns_and_clears() {
let mut handler = InputHandler::new(test_config());
let mods = Modifiers::default();
handler.handle_key_event(Keysym::a, Some("a".to_string()), mods);
handler.handle_key_event(Keysym::b, Some("b".to_string()), mods);
let action = handler.handle_key_event(Keysym::Return, None, mods);
match action {
InputAction::SubmitPassword(p) => {
assert_eq!(&*p, "ab");
}
_ => panic!("Expected SubmitPassword, got {:?}", action),
}
// Buffer should be cleared after submission
assert_eq!(handler.password_length(), 0);
assert_eq!(handler.cursor_position(), 0);
}
#[test]
fn test_submit_enter_kp() {
let mut handler = InputHandler::new(test_config());
let mods = Modifiers::default();
handler.handle_key_event(Keysym::a, Some("a".to_string()), mods);
let action = handler.handle_key_event(Keysym::KP_Enter, None, Modifiers::default());
assert!(matches!(action, InputAction::SubmitPassword(_)));
}
#[test]
fn test_escape_cancels() {
let mut handler = InputHandler::new(test_config());
let mods = Modifiers::default();
let action = handler.handle_key_event(Keysym::Escape, None, mods);
assert!(matches!(action, InputAction::Cancel));
}
#[test]
fn test_cursor_left_right() {
let mut handler = InputHandler::new(test_config());
let mods = Modifiers::default();
handler.handle_key_event(Keysym::a, Some("a".to_string()), mods);
handler.handle_key_event(Keysym::b, Some("b".to_string()), mods);
handler.handle_key_event(Keysym::c, Some("c".to_string()), mods);
assert_eq!(handler.cursor_position(), 3);
// Move left
let action = handler.handle_key_event(Keysym::Left, None, mods);
assert!(matches!(action, InputAction::CursorMoved));
assert_eq!(handler.cursor_position(), 2);
// Left again
handler.handle_key_event(Keysym::Left, None, mods);
assert_eq!(handler.cursor_position(), 1);
// Right
let action = handler.handle_key_event(Keysym::Right, None, mods);
assert!(matches!(action, InputAction::CursorMoved));
assert_eq!(handler.cursor_position(), 2);
}
#[test]
fn test_cursor_left_at_start() {
let mut handler = InputHandler::new(test_config());
let mods = Modifiers::default();
let action = handler.handle_key_event(Keysym::Left, None, mods);
assert!(matches!(action, InputAction::None));
assert_eq!(handler.cursor_position(), 0);
}
#[test]
fn test_cursor_right_at_end() {
let mut handler = InputHandler::new(test_config());
let mods = Modifiers::default();
handler.handle_key_event(Keysym::a, Some("a".to_string()), mods);
let action = handler.handle_key_event(Keysym::Right, None, mods);
assert!(matches!(action, InputAction::None));
assert_eq!(handler.cursor_position(), 1);
}
#[test]
fn test_home_and_end() {
let mut handler = InputHandler::new(test_config());
let mods = Modifiers::default();
handler.handle_key_event(Keysym::a, Some("a".to_string()), mods);
handler.handle_key_event(Keysym::b, Some("b".to_string()), mods);
handler.handle_key_event(Keysym::c, Some("c".to_string()), mods);
handler.handle_key_event(Keysym::Left, None, mods);
handler.handle_key_event(Keysym::Left, None, mods);
assert_eq!(handler.cursor_position(), 1);
// Home
let action = handler.handle_key_event(Keysym::Home, None, mods);
assert!(matches!(action, InputAction::CursorMoved));
assert_eq!(handler.cursor_position(), 0);
// End
let action = handler.handle_key_event(Keysym::End, None, mods);
assert!(matches!(action, InputAction::CursorMoved));
assert_eq!(handler.cursor_position(), 3);
}
#[test]
fn test_delete_removes_at_cursor() {
let mut handler = InputHandler::new(test_config());
let mods = Modifiers::default();
handler.handle_key_event(Keysym::a, Some("a".to_string()), mods);
handler.handle_key_event(Keysym::b, Some("b".to_string()), mods);
handler.handle_key_event(Keysym::c, Some("c".to_string()), mods);
// cursor at 3, delete should be a no-op
let action = handler.handle_key_event(Keysym::Delete, None, mods);
assert!(matches!(action, InputAction::None));
assert_eq!(handler.password_length(), 3);
// move left, delete at cursor position 2 (removes 'c')
handler.handle_key_event(Keysym::Left, None, mods);
let action = handler.handle_key_event(Keysym::Delete, None, mods);
assert!(matches!(action, InputAction::PasswordChanged));
assert_eq!(handler.password_length(), 2);
assert_eq!(&*handler.password_buffer, "ab");
}
#[test]
fn test_insert_mid_buffer() {
let mut handler = InputHandler::new(test_config());
let mods = Modifiers::default();
handler.handle_key_event(Keysym::a, Some("a".to_string()), mods);
handler.handle_key_event(Keysym::c, Some("c".to_string()), mods);
// Move left, insert 'b' between a and c
handler.handle_key_event(Keysym::Left, None, mods);
handler.handle_key_event(Keysym::b, Some("b".to_string()), mods);
assert_eq!(&*handler.password_buffer, "abc");
assert_eq!(handler.cursor_position(), 2);
}
#[test]
fn test_caps_lock_tracking() {
let mut handler = InputHandler::new(test_config());
assert!(!handler.caps_lock());
let caps_mods = Modifiers {
caps_lock: true,
..Modifiers::default()
};
handler.handle_key_event(Keysym::a, Some("A".to_string()), caps_mods);
assert!(handler.caps_lock());
}
#[test]
fn test_wrong_password_timer() {
let mut handler = InputHandler::new(test_config());
assert!(!handler.should_show_wrong_password());
handler.set_wrong_password_feedback();
assert!(handler.should_show_wrong_password());
}
#[test]
fn test_key_highlight_timer() {
let mut handler = InputHandler::new(test_config());
assert!(!handler.should_show_key_highlight());
handler.set_key_highlight();
assert!(handler.should_show_key_highlight());
}
}
+233 -283
View File
@@ -1,33 +1,49 @@
use cairo::ImageSurface;
use std::error::Error;
use std::time::Instant;
use wayland_client::protocol::{wl_shm, wl_surface};
use wayland_client::protocol::{wl_output, wl_shm, wl_surface};
use crate::config::Config;
use crate::input::{InputAction, InputHandler};
use crate::render::Renderer;
use crate::screenshot::Screenshot;
use crate::system::SystemStatus;
use smithay_client_toolkit::seat::keyboard::KeyEvent;
use smithay_client_toolkit::shm::slot::SlotPool;
/// Manages a locked surface for a single output
pub struct LockedSurface {
width: i32,
height: i32,
config: Config,
pub renderer: Renderer,
input_handler: InputHandler,
background: Option<ImageSurface>,
background_applied: bool,
fade_alpha: f64,
wrong_password_shown: bool,
key_highlight_shown: bool,
temp_screenshot_shown: bool,
last_update: Instant,
start_time: Instant,
wayland_surface: Option<wl_surface::WlSurface>,
output: wl_output::WlOutput,
configured: bool,
/// Set whenever rendered state changes (keystroke, status, clock minute,
/// animation step). update() renders only when this is set or an animation
/// is in flight, so an idle lock screen does no per-frame cairo work.
dirty: bool,
/// Last clock minute (unix-minute) we rendered, to detect %H:%M rollover.
last_minute: i64,
ctrl_held: bool,
/// True while the pointer button is held on the indicator ring (hold-to-peek).
/// Cleared on button release, matching Ctrl-hold transient behavior.
peek_toggled: bool,
}
impl LockedSurface {
/// Create a new locked surface for an output
pub fn new(width: i32, height: i32, config: &Config) -> Option<Self> {
pub fn new(
width: i32,
height: i32,
config: &Config,
output: wl_output::WlOutput,
) -> Option<Self> {
if width <= 0 || height <= 0 {
return None;
}
@@ -35,132 +51,171 @@ impl LockedSurface {
let renderer = Renderer::new(width, height, config.clone());
let input_handler = InputHandler::new(config.clone());
// Create background if screenshots are enabled
let background = if config.screenshots {
// For now, create a dummy screenshot with the output dimensions
// In a real implementation, this would capture actual screenshots via Wayland
let mut screenshot = Screenshot {
width: width as u32,
height: height as u32,
data: vec![0u8; (width * height * 4) as usize],
};
// Fill with a dark gray color (similar to swaylock default)
for i in 0..(screenshot.width * screenshot.height) as usize {
let offset = i * 4;
screenshot.data[offset] = 40; // R
screenshot.data[offset + 1] = 44; // G
screenshot.data[offset + 2] = 52; // B
screenshot.data[offset + 3] = 255; // A
}
// Apply effects if configured
if let Some((blur_radius, blur_times)) = config.effect_blur {
screenshot.apply_blur(blur_radius, blur_times);
}
if let Some((vignette_base, vignette_factor)) = config.effect_vignette {
screenshot.apply_vignette(vignette_base, vignette_factor);
}
Some(screenshot.as_image_surface())
} else {
None
};
Some(Self {
width,
height,
config: config.clone(),
renderer,
input_handler,
background,
background: None,
background_applied: false,
fade_alpha: 0.0,
wrong_password_shown: false,
key_highlight_shown: false,
temp_screenshot_shown: false,
last_update: Instant::now(),
start_time: Instant::now(),
wayland_surface: None,
output,
configured: false,
dirty: true,
last_minute: i64::MIN,
ctrl_held: false,
peek_toggled: false,
})
}
/// Set the configured state
pub fn set_configured(&mut self) {
log::debug!("LockedSurface: Configured, starting animation");
self.configured = true;
self.start_time = Instant::now();
self.dirty = true;
}
/// Check if this surface matches the given Wayland surface
pub fn matches_surface(&self, surface: &wl_surface::WlSurface) -> bool {
use wayland_client::Proxy;
self.wayland_surface
.as_ref()
.map_or(false, |ws| ws.id() == surface.id())
.is_some_and(|ws| ws.id() == surface.id())
}
/// Update the surface state (called on each frame)
pub fn update(&mut self) {
// Update timers
self.input_handler.update();
/// Update the surface state (called on each frame). Returns `true` if the
/// surface was re-rendered and therefore needs to be committed. An idle
/// surface (no input, no animation, same clock minute) returns `false` and
/// does no cairo work, which keeps a locked session near-zero CPU.
pub fn update(&mut self) -> bool {
if !self.configured {
return false;
}
// Update fade animation
if self.fade_alpha < 1.0 {
let elapsed = self.last_update.elapsed();
let elapsed = self.start_time.elapsed();
let fade_duration = std::time::Duration::from_secs_f32(self.config.fade_in);
self.fade_alpha = (elapsed.as_secs_f64() / fade_duration.as_secs_f64()).min(1.0);
self.renderer.set_fade_alpha(self.fade_alpha);
if fade_duration.is_zero() {
self.fade_alpha = 1.0;
self.renderer.set_fade_alpha(1.0);
self.dirty = true;
} else {
// Ease-in-out cubic function
let t = (elapsed.as_secs_f64() / fade_duration.as_secs_f64()).clamp(0.0, 1.0);
let eased_t = if t < 0.5 {
4.0 * t * t * t
} else {
1.0 - (-2.0 * t + 2.0).powi(3) / 2.0
};
let new_alpha = eased_t.min(1.0);
if t >= 1.0 {
// The eased curve only approaches 1.0 asymptotically, and the
// 0.001 throttle below suppresses the tiny final steps — which
// would leave fade_alpha stuck just under 1.0 forever. Since
// `fade_alpha < 1.0` is our "still animating" signal, that would
// force a full render every frame. Snap to exactly 1.0 once the
// fade duration has elapsed so the animation cleanly completes.
if self.fade_alpha != 1.0 {
self.fade_alpha = 1.0;
self.renderer.set_fade_alpha(1.0);
self.dirty = true;
}
} else if (new_alpha - self.fade_alpha).abs() > 0.001 {
self.fade_alpha = new_alpha;
self.renderer.set_fade_alpha(self.fade_alpha);
self.dirty = true;
}
}
}
// Update visual feedback
// Check if we should show/hide wrong password feedback
if self.input_handler.should_show_wrong_password() && !self.wrong_password_shown {
self.renderer.show_wrong_password();
self.wrong_password_shown = true;
self.dirty = true;
} else if !self.input_handler.should_show_wrong_password() && self.wrong_password_shown {
self.wrong_password_shown = false;
}
// Check if we should show/hide key highlight feedback
if self.input_handler.should_show_key_highlight() && !self.key_highlight_shown {
self.renderer.show_key_highlight();
self.key_highlight_shown = true;
self.dirty = true;
} else if !self.input_handler.should_show_key_highlight() && self.key_highlight_shown {
self.key_highlight_shown = false;
}
// Handle temp screenshot (peek feature)
if self.input_handler.should_show_temp_screenshot() && !self.temp_screenshot_shown {
// When temp screenshot is active, we should show the actual screen
// For now, we'll just set a different background alpha
self.renderer.set_fade_alpha(0.3); // Semi-transparent
self.temp_screenshot_shown = true;
} else if !self.input_handler.should_show_temp_screenshot() && self.temp_screenshot_shown {
// Restore normal fade alpha
self.renderer.set_fade_alpha(self.fade_alpha);
self.temp_screenshot_shown = false;
// Update caps lock state in renderer
if self.renderer.caps_lock != self.input_handler.caps_lock() {
self.renderer.caps_lock = self.input_handler.caps_lock();
self.dirty = true;
}
// Set background if available
if let Some(ref background) = self.background {
self.renderer.set_background(background.clone());
// Set background if available and not already applied
if !self.background_applied {
if let Some(ref background) = self.background {
log::debug!("Applying background image to renderer");
self.renderer.set_background(background.clone());
self.background_applied = true;
self.dirty = true;
}
}
// The clock displays %H:%M, so it only needs a redraw once per minute.
if self.config.clock {
let minute = chrono::Local::now().timestamp().div_euclid(60);
if self.last_minute != minute {
self.last_minute = minute;
self.dirty = true;
}
}
// Keep emitting frames while an animation is in flight so it can run to
// completion even though no new event arrives.
let animating = self.fade_alpha < 1.0 || self.renderer.is_animating();
if !self.dirty && !animating {
return false;
}
if !self.config.hide_password {
let buf = self.input_handler.password_buffer();
let length = self.input_handler.password_length();
if self.ctrl_held || self.peek_toggled {
self.renderer.peek_password(buf.as_str());
} else {
self.renderer.set_password_display(length);
}
}
self.renderer
.set_password_display(self.input_handler.get_display_password());
// Render the frame
.set_cursor_position(self.input_handler.cursor_position());
self.renderer.render();
self.last_update = Instant::now();
self.dirty = false;
true
}
/// Commit the rendered frame to the Wayland surface
pub fn commit(&self, pool: &mut SlotPool) -> Result<(), Box<dyn Error>> {
// Get pixel data from renderer
if !self.configured {
return Ok(());
}
let pixel_data = self.renderer.get_pixel_data()?;
let (width, height, stride) = self.renderer.surface_info();
// Create buffer from pool
let (buffer, canvas) =
pool.create_buffer(width, height, stride, wl_shm::Format::Argb8888)?;
// Copy pixel data to buffer
let copy_len = pixel_data.len().min(canvas.len());
canvas[..copy_len].copy_from_slice(&pixel_data[..copy_len]);
// Attach buffer to Wayland surface and commit
if let Some(wl_surface) = &self.wayland_surface {
buffer.attach_to(wl_surface)?;
wl_surface.damage_buffer(0, 0, width, height);
@@ -170,196 +225,113 @@ impl LockedSurface {
Ok(())
}
/// Handle resize event from Wayland
pub fn resize(&mut self, width: i32, height: i32) {
if width <= 0 || height <= 0 {
return;
}
self.width = width;
self.height = height;
self.renderer.resize(width, height);
// TODO: Re-capture screenshot if screenshots are enabled
self.background_applied = false;
self.dirty = true;
}
/// Set fade alpha for animation
pub fn set_fade_alpha(&mut self, alpha: f64) {
self.fade_alpha = alpha.clamp(0.0, 1.0);
self.renderer.set_fade_alpha(self.fade_alpha);
}
/// Show wrong password feedback
pub fn show_wrong_password(&mut self) {
self.renderer.clear_verifying();
self.input_handler.set_wrong_password_feedback();
self.wrong_password_shown = false;
self.dirty = true;
}
/// Show key highlight feedback
pub fn show_key_highlight(&mut self) {
self.input_handler.set_key_highlight();
pub fn show_verifying(&mut self) {
self.renderer.show_verifying();
self.dirty = true;
}
/// Handle a key event from Wayland
pub fn handle_key_event(
&mut self,
event: smithay_client_toolkit::seat::keyboard::KeyEvent,
event: KeyEvent,
modifiers: smithay_client_toolkit::seat::keyboard::Modifiers,
) -> Option<InputAction> {
// Convert to our input handler format
// Note: KeyEvent has fields: time, raw_code, keysym, utf8
// We need to determine state and modifiers from context (not available in this demo)
// For demonstration, we'll assume key press with no modifiers
let keysym = event.keysym;
let state = wayland_client::protocol::wl_keyboard::KeyState::Pressed;
let modifiers = smithay_client_toolkit::seat::keyboard::Modifiers::default();
self.ctrl_held = modifiers.ctrl;
let action = self
.input_handler
.handle_key_event(keysym, state, modifiers);
.handle_key_event(event.keysym, event.utf8, modifiers);
// Any key event may change the password display, cursor or caps state,
// so request a redraw on the next update().
self.dirty = true;
match action {
InputAction::SubmitPassword(password) => {
// Show key highlight for visual feedback
self.show_key_highlight();
Some(InputAction::SubmitPassword(password))
InputAction::PasswordChanged => {
self.input_handler.set_key_highlight();
self.key_highlight_shown = false;
}
InputAction::Cancel => Some(InputAction::Cancel),
InputAction::TempScreenshot => Some(InputAction::TempScreenshot),
InputAction::PasswordChanged => Some(InputAction::PasswordChanged),
InputAction::None => None,
}
}
/// Authenticate a password using PAM
pub fn authenticate_password(&self, password: zeroize::Zeroizing<String>) -> bool {
// Create a simple PAM conversation that provides the password
struct SimpleConversation {
password: Option<zeroize::Zeroizing<String>>,
InputAction::PasswordCleared => {
self.renderer.show_cleared_feedback();
}
InputAction::SubmitPassword(_) => {
self.input_handler.set_key_highlight();
self.key_highlight_shown = false;
}
_ => {}
}
impl pam_client::ConversationHandler for SimpleConversation {
fn init(&mut self, _default_user: Option<impl AsRef<str>>) {}
fn prompt_echo_on(
&mut self,
_msg: &std::ffi::CStr,
) -> Result<std::ffi::CString, pam_client::ErrorCode> {
Err(pam_client::ErrorCode::ABORT)
}
fn prompt_echo_off(
&mut self,
_msg: &std::ffi::CStr,
) -> Result<std::ffi::CString, pam_client::ErrorCode> {
if let Some(pwd) = self.password.take() {
std::ffi::CString::new(pwd.as_str()).map_err(|_| pam_client::ErrorCode::ABORT)
} else {
Err(pam_client::ErrorCode::ABORT)
}
}
fn text_info(&mut self, _msg: &std::ffi::CStr) {}
fn error_msg(&mut self, _msg: &std::ffi::CStr) {}
fn radio_prompt(
&mut self,
_msg: &std::ffi::CStr,
) -> Result<bool, pam_client::ErrorCode> {
Ok(false)
}
}
// Get username
let username = match users::get_current_username() {
Some(name) => name.to_string_lossy().into_owned(),
None => {
log::error!("Failed to get current username");
return false;
}
};
// Create PAM context
let service_name = &self.config.pam_service;
let conversation = SimpleConversation {
password: Some(password),
};
let mut context =
match pam_client::Context::new(service_name, Some(username.as_str()), conversation) {
Ok(ctx) => ctx,
Err(e) => {
log::error!("Failed to initialize PAM context: {:?}", e);
return false;
}
};
// Authenticate
match context.authenticate(pam_client::Flag::NONE) {
Ok(()) => {
log::info!("PAM authentication successful for user {}", username);
true
}
Err(e) => {
log::warn!("PAM authentication failed: {:?}", e);
false
}
}
Some(action)
}
/// Get the input handler for this locked surface
pub fn input_handler(&self) -> &InputHandler {
&self.input_handler
}
/// Get the rendered image surface for this locked surface
pub fn as_image_surface(&self) -> &ImageSurface {
self.renderer.as_image_surface()
}
/// Get the current display password (masked)
pub fn get_display_password(&self) -> String {
self.input_handler.get_display_password()
}
/// Get the output dimensions
pub fn dimensions(&self) -> (i32, i32) {
(self.width, self.height)
}
/// Set the Wayland surface for this locked surface
pub fn set_wayland_surface(&mut self, surface: wl_surface::WlSurface) {
self.wayland_surface = Some(surface);
}
/// Get the Wayland surface for this locked surface
pub fn wayland_surface(&self) -> Option<&wl_surface::WlSurface> {
self.wayland_surface.as_ref()
pub fn output(&self) -> &wl_output::WlOutput {
&self.output
}
/// Check if this surface has a Wayland surface attached
pub fn has_wayland_surface(&self) -> bool {
self.wayland_surface.is_some()
pub fn set_background(&mut self, surface: ImageSurface) {
self.background = Some(surface);
self.background_applied = false;
self.dirty = true;
}
pub fn set_system_status(&mut self, status: SystemStatus) {
if self.renderer.system_status != status {
self.renderer.system_status = status;
self.dirty = true;
}
}
pub fn set_ctrl_held(&mut self, held: bool) {
if self.ctrl_held != held {
self.ctrl_held = held;
self.dirty = true;
}
}
/// Set peek mode on/off. Called when the user presses (held=true) or
/// releases (held=false) the mouse button on the indicator ring. Works
/// like Ctrl-hold — peek only lasts while the button is held.
pub fn set_peek_held(&mut self, held: bool) {
self.peek_toggled = held;
log::debug!("set_peek_held: peek_toggled = {}", self.peek_toggled);
self.dirty = true;
}
}
/// Manager for all locked surfaces (multiple outputs)
pub struct LockManager {
pub surfaces: Vec<LockedSurface>,
config: Config,
locked: bool,
}
impl LockManager {
/// Create a new lock manager
pub fn new(config: Config) -> Self {
Self {
surfaces: Vec::new(),
config,
locked: false,
}
}
/// Add a locked surface for an output
pub fn add_surface(&mut self, width: i32, height: i32) -> bool {
match LockedSurface::new(width, height, &self.config) {
pub fn add_surface(&mut self, width: i32, height: i32, output: wl_output::WlOutput) -> bool {
match LockedSurface::new(width, height, &self.config, output) {
Some(surface) => {
self.surfaces.push(surface);
true
@@ -368,79 +340,14 @@ impl LockManager {
}
}
/// Update all locked surfaces
pub fn update(&mut self) {
for surface in &mut self.surfaces {
surface.update();
}
}
/// Handle a key event and return any action that needs processing
/// Returns the first non-None action from any surface
pub fn handle_key_event(
&mut self,
event: smithay_client_toolkit::seat::keyboard::KeyEvent,
) -> Option<InputAction> {
// Distribute key event to all surfaces and collect first action
let mut action = None;
for surface in &mut self.surfaces {
if let Some(a) = surface.handle_key_event(event.clone()) {
action = Some(a);
}
}
action
}
/// Check if session is locked
pub fn is_locked(&self) -> bool {
self.locked
}
/// Lock the session
pub fn lock(&mut self) {
self.locked = true;
// TODO: Implement actual Wayland session locking
}
/// Unlock the session
pub fn unlock(&mut self) {
self.locked = false;
// TODO: Implement actual Wayland session unlocking
}
/// Get the number of locked surfaces
pub fn surface_count(&self) -> usize {
self.surfaces.len()
}
/// Get a reference to a locked surface by index
pub fn get_surface(&self, index: usize) -> Option<&LockedSurface> {
self.surfaces.get(index)
}
/// Get a mutable reference to a locked surface by index
pub fn get_surface_mut(&mut self, index: usize) -> Option<&mut LockedSurface> {
self.surfaces.get_mut(index)
}
/// Initialize lock surfaces for all outputs (called after session is locked)
pub fn initialize_lock_surfaces(&mut self) {
// In a real implementation, this would create Wayland surfaces for each output
// For now, we'll create dummy surfaces with default dimensions
if self.surfaces.is_empty() {
// Add a default surface (single monitor)
self.add_surface(1920, 1080);
}
}
/// Toggle temp screenshot peek mode
pub fn toggle_peek(&mut self) {
for surface in &mut self.surfaces {
surface.input_handler.update_temp_screenshot();
}
}
/// Find a locked surface by Wayland surface
pub fn find_surface_by_wayland_surface(
&mut self,
wayland_surface: &wl_surface::WlSurface,
@@ -449,4 +356,47 @@ impl LockManager {
.iter_mut()
.find(|surface| surface.matches_surface(wayland_surface))
}
pub fn handle_key_event(
&mut self,
event: KeyEvent,
modifiers: smithay_client_toolkit::seat::keyboard::Modifiers,
) -> Option<InputAction> {
let mut action = None;
for surface in &mut self.surfaces {
if let Some(a) = surface.handle_key_event(event.clone(), modifiers) {
if let crate::input::InputAction::SubmitPassword(p) = &a {
if !p.is_empty() {
return Some(a);
}
} else {
action = Some(a);
}
}
}
action
}
pub fn set_ctrl_held(&mut self, held: bool) {
for surface in &mut self.surfaces {
surface.set_ctrl_held(held);
}
}
pub fn remove_surface_by_output(&mut self, output: &wl_output::WlOutput) -> Option<usize> {
use wayland_client::Proxy;
let output_id = Proxy::id(output);
let idx = self
.surfaces
.iter()
.position(|s| Proxy::id(s.output()) == output_id)?;
self.surfaces.remove(idx);
Some(idx)
}
pub fn set_system_status(&mut self, status: SystemStatus) {
for surface in &mut self.surfaces {
surface.set_system_status(status.clone());
}
}
}
+975 -670
View File
File diff suppressed because it is too large Load Diff
-372
View File
@@ -1,372 +0,0 @@
use cairo::{Context, Format, ImageSurface};
use std::time::Instant;
use crate::config::Config;
use crate::util::Color;
/// Cairo-based renderer for the lock screen
pub struct Renderer {
width: i32,
height: i32,
config: Config,
surface: ImageSurface,
context: Context,
fade_alpha: f64,
wrong_password_shown: bool,
key_highlight_shown: bool,
wrong_password_start: Option<Instant>,
key_highlight_start: Option<Instant>,
background: Option<ImageSurface>,
password_display: String,
}
impl Renderer {
/// Convert color tuple to Color struct
fn tuple_to_color(&self, color: (f64, f64, f64, f64)) -> Color {
Color {
r: (color.0 * 255.0) as u8,
g: (color.1 * 255.0) as u8,
b: (color.2 * 255.0) as u8,
a: (color.3 * 255.0) as u8,
}
}
/// Create a new renderer with the given dimensions and configuration
pub fn new(width: i32, height: i32, config: Config) -> Self {
let surface = ImageSurface::create(Format::ARgb32, width, height)
.expect("Failed to create Cairo surface");
let context = Context::new(&surface).expect("Failed to create Cairo context");
Self {
width,
height,
config,
surface,
context,
fade_alpha: 0.0,
wrong_password_shown: false,
key_highlight_shown: false,
wrong_password_start: None,
key_highlight_start: None,
background: None,
password_display: String::new(),
}
}
/// Resize the renderer to new dimensions
pub fn resize(&mut self, width: i32, height: i32) {
self.width = width;
self.height = height;
self.surface = ImageSurface::create(Format::ARgb32, width, height)
.expect("Failed to create Cairo surface");
self.context = Context::new(&self.surface).expect("Failed to create Cairo context");
}
/// Set the background image (screenshot)
pub fn set_background(&mut self, background: ImageSurface) {
self.background = Some(background);
}
/// Set the fade-in alpha value (0.0 to 1.0)
pub fn set_fade_alpha(&mut self, alpha: f64) {
self.fade_alpha = alpha.clamp(0.0, 1.0);
}
/// Show wrong password feedback
pub fn show_wrong_password(&mut self) {
self.wrong_password_shown = true;
self.wrong_password_start = Some(Instant::now());
}
/// Show key highlight feedback
pub fn show_key_highlight(&mut self) {
self.key_highlight_shown = true;
self.key_highlight_start = Some(Instant::now());
}
/// Set the password display string (masked)
pub fn set_password_display(&mut self, password: String) {
self.password_display = password;
}
/// Render the current frame
pub fn render(&mut self) {
// Clear the surface - draw a VISIBLE color (dark gray) instead of black
self.context.set_source_rgba(0.15, 0.15, 0.15, 1.0);
self.context.paint().expect("Failed to clear surface");
// Draw background if available
if let Some(ref background) = self.background {
self.context
.set_source_surface(background, 0.0, 0.0)
.expect("Failed to set background source");
self.context
.paint_with_alpha(self.fade_alpha)
.expect("Failed to draw background");
} else {
// Draw solid color background (dark gray visible color)
self.context.set_source_rgba(0.15, 0.15, 0.15, 1.0);
self.context
.paint()
.expect("Failed to draw solid background");
}
// Draw clock if enabled
if self.config.clock {
self.draw_clock();
}
// Draw indicator if enabled
if self.config.indicator {
self.draw_indicator();
}
// Draw password display (if not empty)
if !self.password_display.is_empty() {
self.draw_password_display();
}
// Draw wrong password feedback if active
if self.wrong_password_shown {
self.draw_wrong_password_feedback();
}
// Draw key highlight feedback if active
if self.key_highlight_shown {
self.draw_key_highlight_feedback();
}
self.update_feedback_timers();
}
/// Get the rendered image surface
pub fn as_image_surface(&self) -> &ImageSurface {
&self.surface
}
/// Get raw pixel data from the surface (ARGB32 format)
pub fn get_pixel_data(&self) -> Result<Vec<u8>, cairo::BorrowError> {
let stride = self.surface.stride() as usize;
let height = self.height as usize;
let mut data = vec![0u8; stride * height];
self.surface.with_data(|src| {
data.copy_from_slice(src);
})?;
Ok(data)
}
/// Get surface dimensions and stride
pub fn surface_info(&self) -> (i32, i32, i32) {
(self.width, self.height, self.surface.stride())
}
/// Draw the clock in the center of the screen
fn draw_clock(&self) {
use chrono::Local;
let now = Local::now();
let time_str = now.format("%H:%M").to_string();
let date_str = now.format("%A, %B %d").to_string();
self.context.set_font_size(72.0);
self.context.set_source_rgba(1.0, 1.0, 1.0, self.fade_alpha);
// Center the text
let extents = self
.context
.text_extents(&time_str)
.expect("Failed to get text extents");
let x = (self.width as f64 - extents.width()) / 2.0;
let y = (self.height as f64 / 2.0) - extents.height() / 2.0;
self.context.move_to(x, y);
self.context
.show_text(&time_str)
.expect("Failed to draw time");
// Draw date below time
self.context.set_font_size(24.0);
let date_extents = self
.context
.text_extents(&date_str)
.expect("Failed to get date extents");
let date_x = (self.width as f64 - date_extents.width()) / 2.0;
let date_y = y + extents.height() + 20.0;
self.context.move_to(date_x, date_y);
self.context
.show_text(&date_str)
.expect("Failed to draw date");
}
/// Draw the password indicator ring
fn draw_indicator(&self) {
let center_x = self.width as f64 / 2.0;
let center_y = self.height as f64 / 2.0;
let radius = self.config.indicator_radius as f64;
let thickness = self.config.indicator_thickness as f64;
// Draw outer ring
let ring_color = self.tuple_to_color(self.config.ring_color);
self.context.set_source_rgba(
ring_color.r as f64 / 255.0,
ring_color.g as f64 / 255.0,
ring_color.b as f64 / 255.0,
ring_color.a as f64 / 255.0 * self.fade_alpha,
);
self.context.set_line_width(thickness);
self.context
.arc(center_x, center_y, radius, 0.0, 2.0 * std::f64::consts::PI);
self.context.stroke().expect("Failed to draw ring");
// Draw inside fill
let inside_color = self.tuple_to_color(self.config.inside_color);
self.context.set_source_rgba(
inside_color.r as f64 / 255.0,
inside_color.g as f64 / 255.0,
inside_color.b as f64 / 255.0,
inside_color.a as f64 / 255.0 * self.fade_alpha,
);
self.context.arc(
center_x,
center_y,
radius - thickness / 2.0,
0.0,
2.0 * std::f64::consts::PI,
);
self.context.fill().expect("Failed to fill inside");
// Draw separator line
let separator_color = self.tuple_to_color(self.config.separator_color);
if separator_color.a > 0 {
self.context.set_source_rgba(
separator_color.r as f64 / 255.0,
separator_color.g as f64 / 255.0,
separator_color.b as f64 / 255.0,
separator_color.a as f64 / 255.0 * self.fade_alpha,
);
self.context.set_line_width(1.0);
self.context.move_to(center_x - radius, center_y);
self.context.line_to(center_x + radius, center_y);
self.context.stroke().expect("Failed to draw separator");
}
}
/// Draw the password display (masked characters)
fn draw_password_display(&self) {
if self.password_display.is_empty() {
return;
}
// Position: below the indicator ring (or centered if no indicator)
let center_x = self.width as f64 / 2.0;
let center_y = self.height as f64 / 2.0;
let radius = self.config.indicator_radius as f64;
let thickness = self.config.indicator_thickness as f64;
// Place password text below the ring
let text_y = center_y + radius + thickness + 40.0; // 40px below ring
self.context.set_font_size(36.0);
self.context.set_source_rgba(1.0, 1.0, 1.0, self.fade_alpha);
// Center the text
let extents = self
.context
.text_extents(&self.password_display)
.expect("Failed to get password text extents");
let text_x = center_x - extents.width() / 2.0;
self.context.move_to(text_x, text_y);
self.context
.show_text(&self.password_display)
.expect("Failed to draw password");
}
/// Draw wrong password feedback (red flash)
fn draw_wrong_password_feedback(&self) {
let center_x = self.width as f64 / 2.0;
let center_y = self.height as f64 / 2.0;
let radius = self.config.indicator_radius as f64;
// Calculate flash intensity based on time
let intensity = if let Some(start) = self.wrong_password_start {
let elapsed = start.elapsed();
let duration = std::time::Duration::from_millis(500);
if elapsed < duration {
1.0 - (elapsed.as_secs_f64() / duration.as_secs_f64())
} else {
0.0
}
} else {
0.0
};
if intensity > 0.0 {
self.context
.set_source_rgba(1.0, 0.0, 0.0, intensity * self.fade_alpha);
self.context
.arc(center_x, center_y, radius, 0.0, 2.0 * std::f64::consts::PI);
self.context
.fill()
.expect("Failed to draw wrong password feedback");
}
}
/// Draw key highlight feedback (green flash)
fn draw_key_highlight_feedback(&self) {
let center_x = self.width as f64 / 2.0;
let center_y = self.height as f64 / 2.0;
let radius = self.config.indicator_radius as f64;
// Calculate flash intensity based on time
let intensity = if let Some(start) = self.key_highlight_start {
let elapsed = start.elapsed();
let duration = std::time::Duration::from_millis(200);
if elapsed < duration {
1.0 - (elapsed.as_secs_f64() / duration.as_secs_f64())
} else {
0.0
}
} else {
0.0
};
if intensity > 0.0 {
let key_hl_color = self.tuple_to_color(self.config.key_hl_color);
self.context.set_source_rgba(
key_hl_color.r as f64 / 255.0,
key_hl_color.g as f64 / 255.0,
key_hl_color.b as f64 / 255.0,
key_hl_color.a as f64 / 255.0 * intensity * self.fade_alpha,
);
self.context
.arc(center_x, center_y, radius, 0.0, 2.0 * std::f64::consts::PI);
self.context
.fill()
.expect("Failed to draw key highlight feedback");
}
}
/// Update feedback timers and reset expired feedback
fn update_feedback_timers(&mut self) {
// Check wrong password feedback timeout
if let Some(start) = self.wrong_password_start {
if start.elapsed() > std::time::Duration::from_millis(500) {
self.wrong_password_shown = false;
self.wrong_password_start = None;
}
}
// Check key highlight feedback timeout
if let Some(start) = self.key_highlight_start {
if start.elapsed() > std::time::Duration::from_millis(200) {
self.key_highlight_shown = false;
self.key_highlight_start = None;
}
}
}
}
+247
View File
@@ -0,0 +1,247 @@
use crate::render::ring_shape;
use crate::render::Renderer;
use std::time::Instant;
impl Renderer {
pub(crate) fn draw_verifying_feedback(&self) {
let center_x = self.width as f64 / 2.0;
let center_y = self.height as f64 / 2.0;
let radius = self.config.indicator_radius as f64;
let thickness = self.config.indicator_thickness as f64;
let (r, g, b, a) = self.config.verifying_color;
if a > 0.0 {
self.context.new_path();
self.context.set_source_rgba(r, g, b, a * self.fade_alpha);
self.context.set_line_width(thickness + 2.0);
self.context.set_line_join(cairo::LineJoin::Round);
ring_shape::build_ring_path(
&self.context,
center_x,
center_y,
radius,
self.config.ring_shape,
);
render_try!(self.context.stroke());
}
}
pub(crate) fn draw_wrong_password_feedback(&self) {
let center_x = self.width as f64 / 2.0;
let center_y = self.height as f64 / 2.0;
let radius = self.config.indicator_radius as f64;
let thickness = self.config.indicator_thickness as f64;
let intensity = if let Some(start) = self.wrong_password_start {
let elapsed = start.elapsed();
let duration = std::time::Duration::from_millis(self.config.wrong_password_duration);
if elapsed < duration {
1.0 - (elapsed.as_secs_f64() / duration.as_secs_f64())
} else {
0.0
}
} else {
0.0
};
if intensity > 0.0 {
self.context.new_path();
self.context
.set_source_rgba(1.0, 0.0, 0.0, intensity * self.fade_alpha);
self.context.set_line_width(thickness + 2.0);
self.context.set_line_join(cairo::LineJoin::Round);
ring_shape::build_ring_path(
&self.context,
center_x,
center_y,
radius,
self.config.ring_shape,
);
render_try!(self.context.stroke());
}
}
pub(crate) fn draw_key_highlight_feedback(&self) {
let center_x = self.width as f64 / 2.0;
let center_y = self.height as f64 / 2.0;
let radius = self.config.indicator_radius as f64;
let thickness = self.config.indicator_thickness as f64;
let intensity = if let Some(start) = self.key_highlight_start {
let elapsed = start.elapsed();
let duration = std::time::Duration::from_millis(self.config.key_highlight_duration);
if elapsed < duration {
1.0 - (elapsed.as_secs_f64() / duration.as_secs_f64())
} else {
0.0
}
} else {
0.0
};
if intensity > 0.0 {
let (r, g, b, a) = if self.caps_lock {
self.config.caps_lock_key_hl_color
} else {
self.config.key_hl_color
};
self.context
.set_source_rgba(r, g, b, a * intensity * self.fade_alpha);
self.context.set_line_width(thickness + 1.5);
self.context.new_path();
self.context.set_line_cap(cairo::LineCap::Round);
// Convert angle range to normalized perimeter t (for circle: t = angle / 2π)
let max_dots = self.config.max_dots as f64;
let t_offset = ring_shape::top_centre_offset(self.config.ring_shape);
let global_t = ((self.password_display.len() as f64) / max_dots) + t_offset;
let random_t = self.key_highlight_angle / (2.0 * std::f64::consts::PI);
let t_start = global_t + random_t;
let sector_t = 40.0 / 360.0;
let t_end = t_start + sector_t;
ring_shape::build_sector_path(
&self.context,
center_x,
center_y,
radius,
self.config.ring_shape,
t_start,
t_end,
);
render_try!(self.context.stroke());
}
}
pub(crate) fn draw_cleared_feedback(&self) {
let center_x = self.width as f64 / 2.0;
let center_y = self.height as f64 / 2.0;
let radius = self.config.indicator_radius as f64;
let thickness = self.config.indicator_thickness as f64;
let intensity = if let Some(start) = self.cleared_feedback_start {
let elapsed = start.elapsed();
let duration = std::time::Duration::from_millis(self.config.cleared_feedback_duration);
if elapsed < duration {
1.0 - (elapsed.as_secs_f64() / duration.as_secs_f64())
} else {
0.0
}
} else {
0.0
};
if intensity > 0.0 {
self.context.new_path();
self.context
.set_source_rgba(1.0, 0.0, 0.0, intensity * self.fade_alpha * 0.5);
ring_shape::build_fill_path(
&self.context,
center_x,
center_y,
radius - thickness / 2.0,
thickness,
self.config.ring_shape,
);
render_try!(self.context.fill());
self.context.new_path();
self.context
.set_source_rgba(1.0, 0.0, 0.0, intensity * self.fade_alpha);
self.context.set_line_width(thickness + 4.0);
self.context.set_line_join(cairo::LineJoin::Round);
ring_shape::build_ring_path(
&self.context,
center_x,
center_y,
radius,
self.config.ring_shape,
);
render_try!(self.context.stroke());
self.context.new_path();
self.context.set_font_size(24.0);
self.context
.set_source_rgba(1.0, 1.0, 1.0, intensity * self.fade_alpha);
let text = "CLEARED";
let te = render_try!(self.context.text_extents(text));
self.context
.move_to(center_x - te.width() / 2.0, center_y - radius - 20.0);
render_try!(self.context.show_text(text));
}
}
/// Whether any feedback animation is currently in flight and therefore
/// requires continued per-frame redraws until it finishes.
pub(crate) fn is_animating(&self) -> bool {
self.wrong_password_start.is_some()
|| self.key_highlight_start.is_some()
|| self.cleared_feedback_start.is_some()
|| self.verifying_start.is_some()
}
pub(crate) fn update_feedback_timers(&mut self) {
self.update_uptime();
if let Some(start) = self.wrong_password_start {
if start.elapsed()
> std::time::Duration::from_millis(self.config.wrong_password_duration)
{
self.wrong_password_shown = false;
self.wrong_password_start = None;
}
}
if let Some(start) = self.key_highlight_start {
if start.elapsed()
> std::time::Duration::from_millis(self.config.key_highlight_duration)
{
self.key_highlight_shown = false;
self.key_highlight_start = None;
}
}
if let Some(start) = self.cleared_feedback_start {
if start.elapsed()
> std::time::Duration::from_millis(self.config.cleared_feedback_duration)
{
self.cleared_feedback_shown = false;
self.cleared_feedback_start = None;
}
}
if let Some(start) = self.verifying_start {
if start.elapsed() > std::time::Duration::from_millis(self.config.auth_timeout) {
self.verifying_shown = false;
self.verifying_start = None;
}
}
}
pub fn show_wrong_password(&mut self) {
self.wrong_password_shown = true;
self.wrong_password_start = Some(Instant::now());
// Clear verifying state — wrong password replaces it
self.verifying_shown = false;
self.verifying_start = None;
}
pub fn show_key_highlight(&mut self) {
self.key_highlight_shown = true;
self.key_highlight_start = Some(Instant::now());
use std::time::SystemTime;
let seed = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.map(|d| d.as_nanos() as u64)
.unwrap_or(0);
let random_val = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
self.key_highlight_angle = ((random_val % 360) as f64).to_radians();
}
pub fn show_cleared_feedback(&mut self) {
self.cleared_feedback_shown = true;
self.cleared_feedback_start = Some(Instant::now());
}
pub fn show_verifying(&mut self) {
self.verifying_shown = true;
self.verifying_start = Some(Instant::now());
}
pub fn clear_verifying(&mut self) {
self.verifying_shown = false;
self.verifying_start = None;
}
}
+165
View File
@@ -0,0 +1,165 @@
use crate::render::ring_shape;
use crate::render::Renderer;
impl Renderer {
pub(crate) fn draw_indicator(&self) {
let center_x = self.width as f64 / 2.0;
let center_y = self.height as f64 / 2.0;
let radius = self.config.indicator_radius as f64;
let thickness = self.config.indicator_thickness as f64;
let shape = self.config.ring_shape;
// Filled center
self.context.new_path();
let (r, g, b, a) = self.config.inside_color;
self.context.set_source_rgba(r, g, b, a * self.fade_alpha);
ring_shape::build_fill_path(
&self.context,
center_x,
center_y,
radius - thickness / 2.0,
thickness,
shape,
);
render_try!(self.context.fill());
// Separator line behind the ring
let (lr, lg, lb, la) = self.config.line_color;
if la > 0.0 {
self.context.new_path();
self.context
.set_source_rgba(lr, lg, lb, la * self.fade_alpha);
self.context.set_line_width(1.0);
ring_shape::build_ring_path(
&self.context,
center_x,
center_y,
radius - thickness / 2.0,
shape,
);
render_try!(self.context.stroke());
}
// Outer ring
let (r, g, b, a) = if self.caps_lock {
self.config.caps_lock_color
} else {
self.config.ring_color
};
self.context.new_path();
self.context.set_source_rgba(r, g, b, a * self.fade_alpha);
self.context.set_line_width(thickness);
self.context.set_line_join(cairo::LineJoin::Round);
ring_shape::build_ring_path(&self.context, center_x, center_y, radius, shape);
render_try!(self.context.stroke());
// Separator line through center
let (r, g, b, a) = self.config.separator_color;
if a > 0.0 {
self.context.new_path();
self.context.set_source_rgba(r, g, b, a * self.fade_alpha);
self.context.set_line_width(1.0);
self.context.move_to(center_x - radius, center_y);
self.context.line_to(center_x + radius, center_y);
render_try!(self.context.stroke());
}
}
pub(crate) fn draw_password_display(&self) {
if self.config.hide_password {
return;
}
let center_x = self.width as f64 / 2.0;
let center_y = self.height as f64 / 2.0;
let radius = self.config.indicator_radius as f64;
let thickness = self.config.indicator_thickness as f64;
let shape = self.config.ring_shape;
let max_dots = self.config.max_dots as f64;
let dot_radius = radius - thickness - 10.0;
let t_offset = ring_shape::top_centre_offset(shape);
let count = self.password_display.len();
if count == 0 {
return;
}
if self.peeking {
// Draw each character at the same ring-perimeter positions as dots
self.context.set_font_size(14.0);
self.context.set_source_rgba(1.0, 1.0, 1.0, self.fade_alpha);
for (i, ch) in self.password_display.chars().enumerate() {
let t = (i as f64 / max_dots) + t_offset;
let (x, y) = ring_shape::perimeter_point(center_x, center_y, dot_radius, shape, t);
let mut ch_str = String::new();
ch_str.push(ch);
let te = render_try!(self.context.text_extents(&ch_str));
self.context.new_path();
self.context.move_to(
x - te.x_bearing() - te.width() / 2.0,
y - te.y_bearing() - te.height() / 2.0,
);
render_try!(self.context.show_text(&ch_str));
}
} else {
self.context.new_path();
self.context.set_source_rgba(1.0, 1.0, 1.0, self.fade_alpha);
for i in 0..count {
let t = (i as f64 / max_dots) + t_offset;
let (x, y) = ring_shape::perimeter_point(center_x, center_y, dot_radius, shape, t);
self.context.new_path();
self.context.arc(x, y, 4.0, 0.0, 2.0 * std::f64::consts::PI);
render_try!(self.context.fill());
}
}
// Cursor indicator (shared between peek and dot modes).
if self.fade_alpha > 0.0 {
// At position 0, place the cursor squarely at the first-dot position
// (t_offset) instead of subtracting 0.5, which would push t negative
// and cause perimeter_point to wrap it to the far end of the ring.
let cursor_t = if self.cursor_position == 0 {
t_offset
} else {
((self.cursor_position as f64 - 0.5) / max_dots) + t_offset
};
let (cx, cy) =
ring_shape::perimeter_point(center_x, center_y, dot_radius, shape, cursor_t);
let dx = cx - center_x;
let dy = cy - center_y;
let len = (dx * dx + dy * dy).sqrt().max(1.0);
let nx = dx / len;
let ny = dy / len;
let x1 = cx - 8.0 * nx;
let y1 = cy - 8.0 * ny;
let x2 = cx + 8.0 * nx;
let y2 = cy + 8.0 * ny;
self.context.new_path();
self.context.set_source_rgba(0.0, 0.8, 1.0, self.fade_alpha);
self.context.set_line_width(2.0);
self.context.move_to(x1, y1);
self.context.line_to(x2, y2);
render_try!(self.context.stroke());
}
}
pub(crate) fn draw_caps_lock_indicator(&self) {
let center_x = self.width as f64 / 2.0;
let center_y = self.height as f64 / 2.0;
let radius = self.config.indicator_radius as f64;
self.context.new_path();
let (r, g, b, a) = self.config.caps_lock_text_color;
self.context.set_source_rgba(r, g, b, a * self.fade_alpha);
self.context.set_font_size(24.0);
let text = "Caps Lock";
let te = render_try!(self.context.text_extents(text));
self.context
.move_to(center_x - te.width() / 2.0, center_y - radius - 10.0);
render_try!(self.context.show_text(text));
}
}
+134
View File
@@ -0,0 +1,134 @@
use crate::render::Renderer;
use cairo::{Format, ImageSurface};
impl Renderer {
pub(crate) fn draw_media(&mut self) {
if let Some(ref title) = self.system_status.media_title {
let center_x = self.width as f64 / 2.0;
let start_y = self.height as f64 - 120.0;
let art_size = 56.0;
if self.config.show_album_art && self.system_status.media_art_url != self.last_art_url {
self.last_art_url = self.system_status.media_art_url.clone();
self.media_art_surface = None;
if let Some(ref data) = self.system_status.media_art_data {
if let Ok(img) = image::load_from_memory(data) {
let img = img.to_rgba8();
let (w, h) = img.dimensions();
if let Ok(mut surface) =
ImageSurface::create(Format::ARgb32, w as i32, h as i32)
{
if let Ok(mut surface_data) = surface.data() {
for y in 0..h {
for x in 0..w {
let pixel = img.get_pixel(x, y);
let idx = ((y * w + x) * 4) as usize;
surface_data[idx] = pixel[2];
surface_data[idx + 1] = pixel[1];
surface_data[idx + 2] = pixel[0];
surface_data[idx + 3] = pixel[3];
}
}
} else {
log::error!("Failed to access album art surface data");
}
self.media_art_surface = Some(surface);
} else {
log::error!("Failed to create album art surface");
}
}
}
}
let has_art = self.config.show_album_art && self.media_art_surface.is_some();
self.context.new_path();
self.context
.set_source_rgba(1.0, 1.0, 1.0, self.fade_alpha * 0.9);
self.context.set_font_size(16.0);
let display_text = if let Some(ref artist) = self.system_status.media_artist {
format!("{} - {}", artist, title)
} else {
title.clone()
};
let te = render_try!(self.context.text_extents(&display_text));
// Center art + text as a group with 16px gap between them
let art_text_gap = 16.0;
let group_width = te.width() + art_size + art_text_gap;
let group_start_x = center_x - group_width / 2.0;
let art_x = group_start_x;
let text_center_x = art_x + art_size + art_text_gap + te.width() / 2.0;
if has_art {
if let Some(ref art) = self.media_art_surface {
render_try!(self.context.save());
let scale = art_size / art.width() as f64;
self.context.translate(art_x, start_y);
self.context.scale(scale, scale);
render_try!(self.context.set_source_surface(art, 0.0, 0.0));
render_try!(self.context.paint_with_alpha(self.fade_alpha));
render_try!(self.context.restore());
}
}
self.context
.move_to(text_center_x - te.width() / 2.0, start_y + 20.0);
render_try!(self.context.show_text(&display_text));
// All media buttons on one row, evenly spaced.
// Each gets a 24×24 hit area, matching draw_icon_at's target_size.
let btn_size = 24.0;
let btn_gap = 48.0;
let btn_y = start_y + 50.0;
// Layout: prev | play_pause | next (centered as a group)
let total_buttons: f64 = (self.media_prev_icon_surface.is_some() as u32
+ 1
+ self.media_next_icon_surface.is_some() as u32)
as f64;
let group_width = (total_buttons - 1.0) * btn_gap + btn_size;
let group_start_x = center_x - group_width / 2.0;
let mut btn_x = group_start_x;
if let Some(ref icon) = self.media_prev_icon_surface {
self.draw_icon_at(btn_x, btn_y - btn_size / 2.0, icon);
self.media_rects
.push(("prev", btn_x, btn_y - btn_size / 2.0, btn_size, btn_size));
btn_x += btn_gap;
}
// Play/pause — always present (at least one of play/pause icon should load)
if self.system_status.media_playing {
if let Some(ref icon) = self.media_pause_icon_surface {
self.draw_icon_at(btn_x, btn_y - btn_size / 2.0, icon);
self.media_rects.push((
"play_pause",
btn_x,
btn_y - btn_size / 2.0,
btn_size,
btn_size,
));
}
} else if let Some(ref icon) = self.media_play_icon_surface {
self.draw_icon_at(btn_x, btn_y - btn_size / 2.0, icon);
self.media_rects.push((
"play_pause",
btn_x,
btn_y - btn_size / 2.0,
btn_size,
btn_size,
));
}
btn_x += btn_gap;
if let Some(ref icon) = self.media_next_icon_surface {
self.draw_icon_at(btn_x, btn_y - btn_size / 2.0, icon);
self.media_rects
.push(("next", btn_x, btn_y - btn_size / 2.0, btn_size, btn_size));
}
}
}
}
+256
View File
@@ -0,0 +1,256 @@
use cairo::{Context, Format, ImageSurface};
use std::time::Instant;
use crate::config::Config;
use crate::system::SystemStatus;
/// Log cairo errors and return early instead of propagating panics.
/// Defined once here and available to all render submodules.
macro_rules! render_try {
($expr:expr) => {
match $expr {
Ok(v) => v,
Err(e) => {
log::error!("cairo error: {:?}", e);
return;
}
}
};
}
mod feedback;
mod indicator;
mod media_bar;
pub(crate) mod ring_shape;
mod status_bar;
pub struct Renderer {
pub(crate) width: i32,
pub(crate) height: i32,
pub(crate) config: Config,
pub(crate) surface: ImageSurface,
pub(crate) context: Context,
pub(crate) fade_alpha: f64,
pub(crate) wrong_password_shown: bool,
pub(crate) key_highlight_shown: bool,
pub(crate) cleared_feedback_shown: bool,
pub(crate) verifying_shown: bool,
pub(crate) wrong_password_start: Option<Instant>,
pub(crate) key_highlight_start: Option<Instant>,
pub(crate) cleared_feedback_start: Option<Instant>,
pub(crate) verifying_start: Option<Instant>,
pub(crate) key_highlight_angle: f64,
pub(crate) background: Option<ImageSurface>,
pub(crate) password_display: String,
pub(crate) peeking: bool,
pub(crate) cursor_position: usize,
pub(crate) uptime_cache: String,
pub(crate) last_uptime_update: Option<Instant>,
pub caps_lock: bool,
pub system_status: SystemStatus,
pub(crate) media_art_surface: Option<ImageSurface>,
pub(crate) last_art_url: Option<String>,
pub(crate) wifi_icon_surface: Option<ImageSurface>,
pub(crate) bluetooth_icon_surface: Option<ImageSurface>,
pub(crate) battery_icon_surface: Option<ImageSurface>,
pub(crate) media_prev_icon_surface: Option<ImageSurface>,
pub(crate) media_stop_icon_surface: Option<ImageSurface>,
pub(crate) media_play_icon_surface: Option<ImageSurface>,
pub(crate) media_pause_icon_surface: Option<ImageSurface>,
pub(crate) media_next_icon_surface: Option<ImageSurface>,
pub media_rects: Vec<(&'static str, f64, f64, f64, f64)>,
}
impl Renderer {
pub fn new(width: i32, height: i32, config: Config) -> Self {
log::debug!("Renderer::new({}, {}, ...) called", width, height);
let surface = ImageSurface::create(Format::ARgb32, width, height)
.expect("Failed to create Cairo surface");
let context = Context::new(&surface).expect("Failed to create Cairo context");
let mut renderer = Self {
width,
height,
config: config.clone(),
surface,
context,
fade_alpha: 0.0,
wrong_password_shown: false,
key_highlight_shown: false,
cleared_feedback_shown: false,
verifying_shown: false,
wrong_password_start: None,
key_highlight_start: None,
cleared_feedback_start: None,
verifying_start: None,
key_highlight_angle: 0.0,
background: None,
password_display: String::new(),
peeking: false,
cursor_position: 0,
uptime_cache: String::new(),
last_uptime_update: None,
caps_lock: false,
system_status: SystemStatus::default(),
media_art_surface: None,
last_art_url: None,
wifi_icon_surface: None,
bluetooth_icon_surface: None,
battery_icon_surface: None,
media_prev_icon_surface: None,
media_stop_icon_surface: None,
media_play_icon_surface: None,
media_pause_icon_surface: None,
media_next_icon_surface: None,
media_rects: Vec::new(),
};
renderer.load_icons();
renderer
}
pub fn resize(&mut self, width: i32, height: i32) {
log::debug!("Renderer::resize({}, {}) called", width, height);
self.width = width;
self.height = height;
self.surface = ImageSurface::create(Format::ARgb32, width, height)
.expect("Failed to create Cairo surface");
self.context = Context::new(&self.surface).expect("Failed to create Cairo context");
}
pub fn set_background(&mut self, background: ImageSurface) {
self.background = Some(background);
}
pub fn set_fade_alpha(&mut self, alpha: f64) {
self.fade_alpha = alpha.clamp(0.0, 1.0);
}
pub fn set_password_display(&mut self, length: usize) {
self.password_display = ".".repeat(length);
self.peeking = false;
}
pub fn peek_password(&mut self, password: &str) {
self.password_display = password.to_string();
self.peeking = true;
}
pub fn set_cursor_position(&mut self, position: usize) {
self.cursor_position = position;
}
pub fn get_pixel_data(&self) -> Result<Vec<u8>, cairo::BorrowError> {
let stride = self.surface.stride() as usize;
let height = self.height as usize;
let mut data = vec![0u8; stride * height];
self.surface.with_data(|src| {
data.copy_from_slice(src);
})?;
Ok(data)
}
pub fn surface_info(&self) -> (i32, i32, i32) {
(self.width, self.height, self.surface.stride())
}
pub fn render(&mut self) {
self.media_rects.clear();
self.context.new_path();
self.context.set_source_rgba(0.0, 0.0, 0.0, 1.0);
self.context.paint().expect("Failed to clear surface");
if let Some(ref background) = self.background {
self.context.save().expect("Failed to save context");
let bg_width = background.width() as f64;
let bg_height = background.height() as f64;
let scale_x = self.width as f64 / bg_width;
let scale_y = self.height as f64 / bg_height;
let scale = scale_x.max(scale_y);
let offset_x = (self.width as f64 - bg_width * scale) / 2.0;
let offset_y = (self.height as f64 - bg_height * scale) / 2.0;
self.context.translate(offset_x, offset_y);
self.context.scale(scale, scale);
self.context.new_path();
self.context
.set_source_surface(background, 0.0, 0.0)
.expect("Failed to set source");
self.context
.paint_with_alpha(self.fade_alpha)
.expect("Failed to paint");
self.context.restore().expect("Failed to restore context");
}
if self.config.indicator {
self.draw_indicator();
}
if self.config.clock {
self.draw_clock();
}
if self.config.show_media {
self.draw_media();
}
if self.config.show_network {
self.draw_network();
}
if self.config.show_battery {
self.draw_status();
}
if self.config.show_bluetooth {
self.draw_bluetooth();
}
if self.config.show_keyboard_layout {
self.draw_keyboard_layout();
}
if !self.password_display.is_empty() {
self.draw_password_display();
}
if self.caps_lock && self.config.show_caps_lock_text {
self.draw_caps_lock_indicator();
}
if self.verifying_shown {
self.draw_verifying_feedback();
}
if self.wrong_password_shown {
self.draw_wrong_password_feedback();
}
if self.key_highlight_shown {
self.draw_key_highlight_feedback();
}
if self.cleared_feedback_shown {
self.draw_cleared_feedback();
}
self.update_feedback_timers();
}
fn update_uptime(&mut self) {
let now = Instant::now();
if let Some(last) = self.last_uptime_update {
if now.duration_since(last).as_secs() < 10 {
return;
}
}
let uptime_secs = std::fs::read_to_string("/proc/uptime")
.ok()
.and_then(|s| s.split_whitespace().next()?.parse::<f64>().ok())
.unwrap_or(0.0) as u64;
self.uptime_cache = format!("up {}h {}m", uptime_secs / 3600, (uptime_secs % 3600) / 60);
self.last_uptime_update = Some(now);
}
}
+257
View File
@@ -0,0 +1,257 @@
use cairo::Context;
use crate::config::RingShape;
/// Number of linear segments used to approximate curved portions of a shape.
/// Higher = smoother, lower = faster.
const SEGMENTS: usize = 120;
/// Return the (x, y) point on the shape's perimeter at normalized position `t` ∈ [0, 1].
/// `t = 0` is a reference point (rightmost for most shapes); `t` increases clockwise.
/// `r` is the shape's characteristic radius (distance from center to side/vertex).
pub(crate) fn perimeter_point(cx: f64, cy: f64, r: f64, shape: RingShape, t: f64) -> (f64, f64) {
// Normalize t to [0, 1). Rust's % preserves sign, and the shape-specific
// functions use floor/truncation that break on negative values.
let t = t - t.floor();
match shape {
RingShape::Circle => {
let angle = t * 2.0 * std::f64::consts::PI;
(cx + r * angle.cos(), cy + r * angle.sin())
}
RingShape::Square => square_perimeter_point(cx, cy, r, t),
RingShape::Diamond => diamond_perimeter_point(cx, cy, r, t),
RingShape::Hexagon => hexagon_perimeter_point(cx, cy, r, t),
RingShape::Pill => pill_perimeter_point(cx, cy, r, t),
}
}
/// Right-top-right-bottom-left-bottom-left-top order (clockwise from right).
fn square_perimeter_point(cx: f64, cy: f64, r: f64, t: f64) -> (f64, f64) {
let t = t % 1.0;
let side = (t * 4.0).floor() as u32;
let local = t * 4.0 - side as f64;
match side {
0 => {
// Right side: top → bottom
(cx + r, cy - r + local * 2.0 * r)
}
1 => {
// Bottom side: right → left
(cx + r - local * 2.0 * r, cy + r)
}
2 => {
// Left side: bottom → top
(cx - r, cy + r - local * 2.0 * r)
}
_ => {
// Top side: left → right
(cx - r + local * 2.0 * r, cy - r)
}
}
}
/// Right-bottom-left-top order (clockwise from right).
fn diamond_perimeter_point(cx: f64, cy: f64, r: f64, t: f64) -> (f64, f64) {
let t = t % 1.0;
let side = (t * 4.0).floor() as u32;
let local = t * 4.0 - side as f64;
match side {
0 => {
// Right to bottom
(cx + r - local * r, cy + local * r)
}
1 => {
// Bottom to left
(cx - local * r, cy + r - local * r)
}
2 => {
// Left to top
(cx - r + local * r, cy - local * r)
}
_ => {
// Top to right
(cx + local * r, cy - r + local * r)
}
}
}
/// 0: right → bottom-right (vertex to vertex)
/// 1: bottom edge (right → left)
/// 2: bottom-left → left
/// 3: left → top-left
/// 4: top edge (left → right)
/// 5: top-right → right
fn hexagon_perimeter_point(cx: f64, cy: f64, r: f64, t: f64) -> (f64, f64) {
let t = t % 1.0;
let side = (t * 6.0).floor() as u32;
let local = t * 6.0 - side as f64;
// Shared helper for edges between two vertices
let vert =
|angle_rad: f64| -> (f64, f64) { (cx + r * angle_rad.cos(), cy + r * angle_rad.sin()) };
// Vertices clockwise from right (angle = 0)
let v = [
vert(0.0), // V0: right
vert(std::f64::consts::PI * (1.0 / 3.0)), // V1: bottom-right
vert(std::f64::consts::PI * (2.0 / 3.0)), // V2: bottom-left
vert(std::f64::consts::PI), // V3: left
vert(std::f64::consts::PI * (4.0 / 3.0)), // V4: top-left
vert(std::f64::consts::PI * (5.0 / 3.0)), // V5: top-right
];
let (x0, y0) = v[side as usize];
let (x1, y1) = v[((side + 1) % 6) as usize];
(x0 + local * (x1 - x0), y0 + local * (y1 - y0))
}
/// Clockwise from top-right corner: right cap (downward) → bottom straight
/// (leftward) → left cap (upward) → top straight (rightward).
///
/// The pill is a stadium / capsule: cap radius = r, straight-section length = 2r,
/// total width = 4r, total height = 2r.
fn pill_perimeter_point(cx: f64, cy: f64, r: f64, t: f64) -> (f64, f64) {
let t = t % 1.0;
let total_p = 4.0 + 2.0 * std::f64::consts::PI; // 4r + 2πr, normalised by r
let straights = 2.0 / total_p; // each straight segment's t fraction
let caps = std::f64::consts::PI / total_p; // each cap's t fraction
if t < caps {
// Right cap: semicircle, top → bottom, centred at (r, 0)
let local = t / caps;
let angle = -std::f64::consts::PI / 2.0 + local * std::f64::consts::PI;
(cx + r + r * angle.cos(), cy + r * angle.sin())
} else if t < caps + straights {
// Bottom straight: right → left
let local = (t - caps) / straights;
(cx + r - local * 2.0 * r, cy + r)
} else if t < caps + straights + caps {
// Left cap: semicircle, bottom → top, centred at (-r, 0)
let local = (t - caps - straights) / caps;
let angle = std::f64::consts::PI / 2.0 + local * std::f64::consts::PI;
(cx - r + r * angle.cos(), cy + r * angle.sin())
} else {
// Top straight: left → right
let local = (t - 2.0 * caps - straights) / straights;
(cx - r + local * 2.0 * r, cy - r)
}
}
/// Build the full closed path of the shape outline (at radius `r`).
/// Call `stroke()` after this to draw the ring.
pub(crate) fn build_ring_path(ctx: &Context, cx: f64, cy: f64, r: f64, shape: RingShape) {
match shape {
RingShape::Circle => {
ctx.arc(cx, cy, r, 0.0, 2.0 * std::f64::consts::PI);
}
RingShape::Square | RingShape::Diamond | RingShape::Hexagon | RingShape::Pill => {
let (x0, y0) = perimeter_point(cx, cy, r, shape, 0.0);
ctx.move_to(x0, y0);
// Subdivide perimeter into enough segments for smooth rendering
let n = 80;
for i in 1..=n {
let pt = i as f64 / n as f64;
let (x, y) = perimeter_point(cx, cy, r, shape, pt);
ctx.line_to(x, y);
}
ctx.close_path();
}
}
}
/// Build a partial path along the shape perimeter from normalized position
/// `t_start` to `t_end`. Call `stroke()` after this to draw a sector.
pub(crate) fn build_sector_path(
ctx: &Context,
cx: f64,
cy: f64,
r: f64,
shape: RingShape,
t_start: f64,
t_end: f64,
) {
match shape {
RingShape::Circle => {
let a_start = t_start * 2.0 * std::f64::consts::PI;
let a_end = t_end * 2.0 * std::f64::consts::PI;
ctx.arc(cx, cy, r, a_start, a_end);
}
RingShape::Square | RingShape::Diamond | RingShape::Hexagon | RingShape::Pill => {
let (x0, y0) = perimeter_point(cx, cy, r, shape, t_start);
ctx.move_to(x0, y0);
for i in 1..=SEGMENTS {
let t = t_start + (t_end - t_start) * (i as f64 / SEGMENTS as f64);
let (x, y) = perimeter_point(cx, cy, r, shape, t);
ctx.line_to(x, y);
}
}
}
}
/// Build the filled interior path (inset from outer ring by `thickness / 2`).
/// Call `fill()` after this.
pub(crate) fn build_fill_path(
ctx: &Context,
cx: f64,
cy: f64,
radius: f64,
thickness: f64,
shape: RingShape,
) {
let inner_r = (radius - thickness / 2.0).max(0.0);
if inner_r <= 0.0 {
return;
}
build_ring_path(ctx, cx, cy, inner_r, shape);
}
/// Check whether a point `(px, py)` lies inside the shape's fill area.
/// This is used for hittesting (e.g. click & hold to peek) so the clickable
/// region matches what the user sees on screen.
pub(crate) fn point_in_shape(cx: f64, cy: f64, r: f64, shape: RingShape, px: f64, py: f64) -> bool {
let dx = (px - cx).abs();
let dy = (py - cy).abs();
match shape {
RingShape::Circle => dx * dx + dy * dy <= r * r,
RingShape::Square => dx <= r && dy <= r,
RingShape::Diamond => dx + dy <= r,
RingShape::Hexagon => {
// Regular hexagon, vertex at (r, 0), edge slopes at ±60°.
// For |dx| ≥ r/2 the sloping edge bounds: |dy| ≤ √3 (r |dx|).
// For |dx| ≤ r/2 the flat top bounds: |dy| ≤ √3 r / 2.
let sqrt3 = 3.0_f64.sqrt();
if dx >= r / 2.0 {
dy <= sqrt3 * (r - dx)
} else {
dy <= r * sqrt3 / 2.0
}
}
RingShape::Pill => {
// Pill = centre rectangle (2r × 2r) + semicircular caps of
// radius r at each end. Total width 4r, height 2r.
if dx <= r {
dy <= r
} else {
let ex = dx - r;
ex * ex + dy * dy <= r * r
}
}
}
}
/// Return the normalized `t` offset that places the first password dot at the
/// visual top-centre of the shape. May be negative; callers should NOT wrap.
pub(crate) fn top_centre_offset(shape: RingShape) -> f64 {
match shape {
// Circle/Diamond: top at t=0.75 → offset -(1-0.75) = -0.25
RingShape::Circle | RingShape::Diamond => -0.25,
// Square: top edge centre at t=0.875 → offset -(1-0.875) = -0.125
RingShape::Square => -0.125,
// Hexagon: top edge centre at t=0.75 → offset -0.25
RingShape::Hexagon => -0.25,
// Pill: top straight centre at t = 1 - 1/(4+2π) ≈ 0.9027
RingShape::Pill => -1.0 / (4.0 + 2.0 * std::f64::consts::PI),
}
}
+568
View File
@@ -0,0 +1,568 @@
use crate::render::Renderer;
use cairo::{Format, ImageSurface};
impl Renderer {
pub(crate) fn load_icons(&mut self) {
log::debug!("Attempting to load status icons...");
let wifi_names = [
"network-wireless-signal-excellent-symbolic",
"network-wireless-signal-excellent",
"network-wireless-symbolic",
"network-wireless",
];
let wifi_path = self
.config
.wifi_icon
.clone()
.or_else(|| {
for name in &wifi_names {
if let Some(path) = self.find_system_icon(name) {
return Some(path);
}
}
None
})
.unwrap_or_default();
if !wifi_path.is_empty() {
log::debug!("Resolved WiFi icon path: {}", wifi_path);
self.wifi_icon_surface = self.load_icon(&wifi_path);
}
let bt_names = [
"bluetooth-active-symbolic",
"bluetooth-symbolic",
"bluetooth-active",
"bluetooth",
];
let bt_path = self
.config
.bluetooth_icon
.clone()
.or_else(|| {
for name in &bt_names {
if let Some(path) = self.find_system_icon(name) {
return Some(path);
}
}
None
})
.unwrap_or_default();
if !bt_path.is_empty() {
log::debug!("Resolved Bluetooth icon path: {}", bt_path);
self.bluetooth_icon_surface = self.load_icon(&bt_path);
}
let batt_names = [
"battery-level-100-symbolic",
"battery-full-symbolic",
"battery-full",
"battery-level-100",
"battery",
"battery-symbolic",
];
let batt_path = self
.config
.battery_icon
.clone()
.or_else(|| {
for name in &batt_names {
if let Some(path) = self.find_system_icon(name) {
return Some(path);
}
}
None
})
.unwrap_or_default();
if !batt_path.is_empty() {
log::debug!("Resolved Battery icon path: {}", batt_path);
self.battery_icon_surface = self.load_icon(&batt_path);
}
let prev_names = [
"media-skip-backward-symbolic",
"media-skip-backward",
"media-playlist-repeat-symbolic",
];
let prev_path = self
.config
.media_prev_icon
.clone()
.or_else(|| {
for name in &prev_names {
if let Some(path) = self.find_system_icon(name) {
return Some(path);
}
}
None
})
.unwrap_or_default();
if !prev_path.is_empty() {
self.media_prev_icon_surface = self.load_icon(&prev_path);
}
let stop_names = ["media-playback-stop-symbolic", "media-playback-stop"];
let stop_path = self
.config
.media_stop_icon
.clone()
.or_else(|| {
for name in &stop_names {
if let Some(path) = self.find_system_icon(name) {
return Some(path);
}
}
None
})
.unwrap_or_default();
if !stop_path.is_empty() {
self.media_stop_icon_surface = self.load_icon(&stop_path);
}
let play_names = ["media-playback-start-symbolic", "media-playback-start"];
let play_path = self
.config
.media_play_icon
.clone()
.or_else(|| {
for name in &play_names {
if let Some(path) = self.find_system_icon(name) {
return Some(path);
}
}
None
})
.unwrap_or_default();
if !play_path.is_empty() {
self.media_play_icon_surface = self.load_icon(&play_path);
}
let pause_names = ["media-playback-pause-symbolic", "media-playback-pause"];
let pause_path = self
.config
.media_pause_icon
.clone()
.or_else(|| {
for name in &pause_names {
if let Some(path) = self.find_system_icon(name) {
return Some(path);
}
}
None
})
.unwrap_or_default();
if !pause_path.is_empty() {
self.media_pause_icon_surface = self.load_icon(&pause_path);
}
let next_names = ["media-skip-forward-symbolic", "media-skip-forward"];
let next_path = self
.config
.media_next_icon
.clone()
.or_else(|| {
for name in &next_names {
if let Some(path) = self.find_system_icon(name) {
return Some(path);
}
}
None
})
.unwrap_or_default();
if !next_path.is_empty() {
self.media_next_icon_surface = self.load_icon(&next_path);
}
}
pub(crate) fn find_system_icon(&self, name: &str) -> Option<String> {
let data_dirs = std::env::var("XDG_DATA_DIRS").unwrap_or_default();
let mut search_paths = Vec::new();
for dir in data_dirs.split(':') {
let p = std::path::PathBuf::from(dir).join("icons");
if p.exists() {
search_paths.push(p);
}
}
let sys_path = std::path::PathBuf::from("/run/current-system/sw/share/icons");
if sys_path.exists() {
search_paths.push(sys_path);
}
let usr_path = std::path::PathBuf::from("/usr/share/icons");
if usr_path.exists() {
search_paths.push(usr_path);
}
let themes = [
"WhiteSur",
"WhiteSur-dark",
"WhiteSur-light",
"Adwaita",
"hicolor",
"breeze",
"Papirus",
];
let categories = [
"status/symbolic",
"actions/symbolic",
"devices/symbolic",
"status/24",
"status/22",
"status/16",
"status",
"actions",
"devices",
"symbolic/status",
"symbolic/actions",
"symbolic/devices",
"24x24/status",
"22x22/status",
"16x16/status",
"48x48/status",
];
for base in &search_paths {
for theme in &themes {
for cat in &categories {
for ext in [".svg", ".png"] {
let icon_path = base.join(theme).join(cat).join(format!("{}{}", name, ext));
if icon_path.exists() {
return Some(icon_path.to_string_lossy().into_owned());
}
}
}
}
}
for base in &search_paths {
for theme in &themes {
let theme_root = base.join(theme);
if !theme_root.exists() {
continue;
}
if let Ok(entries) = std::fs::read_dir(&theme_root) {
for entry in entries.flatten() {
if entry.path().is_dir() {
for ext in [".svg", ".png"] {
let icon_path = entry.path().join(format!("{}{}", name, ext));
if icon_path.exists() {
return Some(icon_path.to_string_lossy().into_owned());
}
}
}
}
}
}
}
None
}
pub(crate) fn load_icon(&self, identifier: &str) -> Option<ImageSurface> {
let path = if identifier.starts_with('~') {
let home = std::env::var("HOME").unwrap_or_default();
std::path::PathBuf::from(identifier.replacen('~', &home, 1))
} else {
std::path::PathBuf::from(identifier)
};
if !path.exists() {
return None;
}
if path.extension().and_then(|s| s.to_str()) == Some("svg") {
if let Some(surface) = self.load_svg_with_resvg(&path) {
return Some(surface);
}
}
match gdk_pixbuf::Pixbuf::from_file(&path) {
Ok(pixbuf) => {
let w = pixbuf.width();
let h = pixbuf.height();
let mut surface = ImageSurface::create(Format::ARgb32, w, h).ok()?;
{
let mut surface_data = surface.data().ok()?;
let pix_data = unsafe { pixbuf.pixels() };
let n_channels = pixbuf.n_channels();
let rowstride = pixbuf.rowstride() as usize;
for y in 0..h as usize {
for x in 0..w as usize {
let pix_idx = y * rowstride + x * n_channels as usize;
let surf_idx = (y * w as usize + x) * 4;
if n_channels == 4 {
surface_data[surf_idx] = pix_data[pix_idx + 2];
surface_data[surf_idx + 1] = pix_data[pix_idx + 1];
surface_data[surf_idx + 2] = pix_data[pix_idx];
surface_data[surf_idx + 3] = pix_data[pix_idx + 3];
} else if n_channels == 3 {
surface_data[surf_idx] = pix_data[pix_idx + 2];
surface_data[surf_idx + 1] = pix_data[pix_idx + 1];
surface_data[surf_idx + 2] = pix_data[pix_idx];
surface_data[surf_idx + 3] = 255;
}
}
}
}
Some(surface)
}
Err(_) => None,
}
}
pub(crate) fn load_svg_with_resvg(&self, path: &std::path::Path) -> Option<ImageSurface> {
use resvg::usvg;
let opt = usvg::Options::default();
let svg_data = std::fs::read(path).ok()?;
let tree = usvg::Tree::from_data(&svg_data, &opt).ok()?;
let size = tree.size().to_int_size();
let mut pixmap = resvg::tiny_skia::Pixmap::new(size.width(), size.height())?;
resvg::render(
&tree,
resvg::tiny_skia::Transform::default(),
&mut pixmap.as_mut(),
);
let mut surface =
ImageSurface::create(Format::ARgb32, size.width() as i32, size.height() as i32).ok()?;
{
let mut surface_data = surface.data().ok()?;
let pix_data = pixmap.data();
for i in (0..pix_data.len()).step_by(4) {
surface_data[i] = pix_data[i + 2];
surface_data[i + 1] = pix_data[i + 1];
surface_data[i + 2] = pix_data[i];
surface_data[i + 3] = pix_data[i + 3];
}
}
Some(surface)
}
pub(crate) fn draw_clock(&self) {
use chrono::Local;
let now = Local::now();
let time_str = now.format("%H:%M").to_string();
let date_str = now.format("%A, %B %d").to_string();
let center_x = self.width as f64 / 2.0;
let center_y = self.height as f64 / 2.0;
self.context.new_path();
self.context.set_source_rgba(1.0, 1.0, 1.0, self.fade_alpha);
self.context.set_font_size(48.0);
let te = render_try!(self.context.text_extents(&time_str));
self.context
.move_to(center_x - te.width() / 2.0, center_y + te.height() / 4.0);
render_try!(self.context.show_text(&time_str));
self.context.new_path();
self.context.set_font_size(14.0);
let de = render_try!(self.context.text_extents(&date_str));
self.context.move_to(
center_x - de.width() / 2.0,
center_y + te.height() / 4.0 + 25.0,
);
render_try!(self.context.show_text(&date_str));
self.context.new_path();
let ue = render_try!(self.context.text_extents(&self.uptime_cache));
self.context.move_to(
center_x - ue.width() / 2.0,
center_y + te.height() / 4.0 + 43.0,
);
render_try!(self.context.show_text(&self.uptime_cache));
}
pub(crate) fn draw_network(&self) {
if !self.config.show_network {
return;
}
let margin = 20.0;
let x = margin;
let y = margin + 20.0;
if let Some(ref ssid) = self.system_status.wifi_ssid {
if let Some(ref icon) = self.wifi_icon_surface {
self.draw_icon_at(x, y - 15.0, icon);
let text_x = x + 24.0 + 10.0;
self.context.new_path();
self.context.set_source_rgba(1.0, 1.0, 1.0, self.fade_alpha);
self.context.set_font_size(16.0);
self.context.move_to(text_x, y);
render_try!(self.context.show_text(ssid));
} else {
self.context.new_path();
self.context.set_source_rgba(1.0, 1.0, 1.0, self.fade_alpha);
self.context.set_font_size(16.0);
self.context.move_to(x, y);
render_try!(self.context.show_text(ssid));
}
}
}
pub(crate) fn draw_status(&self) {
if let Some(percent) = self.system_status.battery_percent {
let margin = 20.0;
let icon_width = 30.0;
let x = self.width as f64 - margin - icon_width - 50.0;
let y = margin + 20.0;
if let Some(ref icon) = self.battery_icon_surface {
self.draw_icon_at(x, y - 15.0, icon);
let text_x = x + 24.0 + 10.0;
let battery_text = format!("{:.0}%", percent);
self.context.new_path();
self.context.set_source_rgba(1.0, 1.0, 1.0, self.fade_alpha);
self.context.set_font_size(16.0);
self.context.move_to(text_x, y);
render_try!(self.context.show_text(&battery_text));
} else {
self.draw_battery_icon_at(
x,
y - 12.0,
icon_width,
15.0,
percent,
self.system_status.is_charging,
);
let battery_text = format!("{:.0}%", percent);
self.context.new_path();
self.context.set_source_rgba(1.0, 1.0, 1.0, self.fade_alpha);
self.context.set_font_size(16.0);
self.context.move_to(x + icon_width + 10.0, y);
render_try!(self.context.show_text(&battery_text));
}
}
}
pub(crate) fn draw_bluetooth(&self) {
if !self.config.show_bluetooth {
return;
}
let margin = 20.0;
let x = margin;
let y = margin + 50.0;
let (status_text, is_off) = if self.system_status.bluetooth_connected {
(self.system_status.bluetooth_devices.join(", "), false)
} else {
("Bluetooth off".to_string(), true)
};
let alpha_mult = if is_off { 0.5 } else { 1.0 };
if let Some(ref icon) = self.bluetooth_icon_surface {
self.draw_icon_at_with_alpha(x, y - 12.0, icon, alpha_mult);
let text_x = x + 24.0 + 10.0;
self.context.new_path();
self.context
.set_source_rgba(1.0, 1.0, 1.0, self.fade_alpha * alpha_mult);
self.context.set_font_size(14.0);
self.context.move_to(text_x, y);
render_try!(self.context.show_text(&status_text));
}
}
pub(crate) fn draw_keyboard_layout(&self) {
if self.config.show_keyboard_layout {
if let Some(ref layout) = self.system_status.keyboard_layout {
let margin = 20.0;
let x = margin;
let y = margin + 80.0;
self.context.new_path();
self.context.set_source_rgba(1.0, 1.0, 1.0, self.fade_alpha);
self.context.set_font_size(16.0);
let text = format!("Layout: {}", layout);
self.context.move_to(x, y);
render_try!(self.context.show_text(&text));
}
}
}
pub(crate) fn draw_icon_at(&self, x: f64, y: f64, surface: &ImageSurface) {
self.context.save().unwrap();
let target_size = 24.0;
let scale =
(target_size / surface.width() as f64).min(target_size / surface.height() as f64);
self.context.translate(x, y);
self.context.scale(scale, scale);
if let Err(e) = self.context.set_source_surface(surface, 0.0, 0.0) {
log::error!("cairo error: {:?}", e);
}
if let Err(e) = self.context.paint_with_alpha(self.fade_alpha) {
log::error!("cairo error: {:?}", e);
}
self.context.restore().unwrap();
}
pub(crate) fn draw_icon_at_with_alpha(
&self,
x: f64,
y: f64,
surface: &ImageSurface,
alpha: f64,
) {
self.context.save().unwrap();
let target_size = 24.0;
let scale =
(target_size / surface.width() as f64).min(target_size / surface.height() as f64);
self.context.translate(x, y);
self.context.scale(scale, scale);
if let Err(e) = self.context.set_source_surface(surface, 0.0, 0.0) {
log::error!("cairo error: {:?}", e);
}
if let Err(e) = self.context.paint_with_alpha(self.fade_alpha * alpha) {
log::error!("cairo error: {:?}", e);
}
self.context.restore().unwrap();
}
pub(crate) fn draw_battery_icon_at(
&self,
x: f64,
y: f64,
width: f64,
height: f64,
percent: f64,
charging: bool,
) {
let alpha = self.fade_alpha;
self.context.new_path();
self.context.set_source_rgba(1.0, 1.0, 1.0, alpha * 0.5);
self.context.set_line_width(2.0);
self.context.rectangle(x, y, width, height);
render_try!(self.context.stroke());
self.context.new_path();
self.context
.rectangle(x + width, y + height / 4.0, 3.0, height / 2.0);
render_try!(self.context.fill());
let fill_width = (width - 4.0) * (percent / 100.0);
self.context.new_path();
if percent < 20.0 {
self.context.set_source_rgba(1.0, 0.2, 0.2, alpha);
} else {
self.context.set_source_rgba(0.2, 1.0, 0.2, alpha * 0.8);
}
self.context
.rectangle(x + 2.0, y + 2.0, fill_width, height - 4.0);
render_try!(self.context.fill());
if charging {
self.context.new_path();
self.context.set_source_rgba(1.0, 1.0, 0.0, alpha);
let bx = x + width / 2.0;
let by = y + height / 2.0;
self.context.move_to(bx - 3.0, by + 2.0);
self.context.line_to(bx + 1.0, by - 1.0);
self.context.line_to(bx - 1.0, by - 1.0);
self.context.line_to(bx + 3.0, by - 6.0);
self.context.line_to(bx - 1.0, by - 3.0);
self.context.line_to(bx + 1.0, by - 3.0);
self.context.close_path();
render_try!(self.context.fill());
}
}
}
+237 -86
View File
@@ -1,99 +1,250 @@
//!
//! This module provides functionality to capture the current screen contents
//! and apply visual effects like blur and vignette, similar to swaylock-effects.
use anyhow::{Context, Result};
use cairo::ImageSurface;
use log::warn;
use smithay_client_toolkit::shm::{slot::Buffer, slot::SlotPool};
use std::sync::Mutex;
use wayland_client::globals::GlobalList;
use wayland_client::protocol::{wl_output, wl_shm};
use wayland_client::{Dispatch, QueueHandle};
use wayland_protocols_wlr::screencopy::v1::client::zwlr_screencopy_frame_v1::{
Flags, ZwlrScreencopyFrameV1,
};
use wayland_protocols_wlr::screencopy::v1::client::zwlr_screencopy_manager_v1::ZwlrScreencopyManagerV1;
use crate::config::Config;
/// A captured screenshot with optional visual effects applied.
pub struct Screenshot {
pub width: u32,
pub height: u32,
pub data: Vec<u8>,
surface: ImageSurface,
}
impl Screenshot {
pub fn capture(
_output: wayland_client::protocol::wl_output::WlOutput,
width: i32,
height: i32,
) -> Result<Self, String> {
let width = width as u32;
let height = height as u32;
let size = (width * height * 4) as usize;
let mut data = vec![0u8; size];
for i in 0..(width * height) as usize {
let offset = i * 4;
data[offset] = 40;
data[offset + 1] = 44;
data[offset + 2] = 52;
data[offset + 3] = 255;
}
Ok(Self {
width,
height,
data,
})
/// Create a new screenshot from a Cairo surface.
pub fn new(surface: ImageSurface) -> Self {
Self { surface }
}
pub fn apply_blur(&mut self, radius: u32, times: u32) {
if radius == 0 || times == 0 {
return;
}
let mut img: image::ImageBuffer<image::Rgba<u8>, Vec<u8>> =
image::ImageBuffer::from_raw(self.width, self.height, self.data.clone())
.expect("Failed to create image buffer");
for _ in 0..times {
let mut rgb_data: Vec<[u8; 3]> =
Vec::with_capacity((self.width * self.height) as usize);
for pixel in img.pixels() {
rgb_data.push([pixel[0], pixel[1], pixel[2]]);
}
fastblur::gaussian_blur(
&mut rgb_data,
self.width as usize,
self.height as usize,
radius as f32,
);
for (i, pixel) in img.pixels_mut().enumerate() {
pixel[0] = rgb_data[i][0];
pixel[1] = rgb_data[i][1];
pixel[2] = rgb_data[i][2];
}
}
self.data = img.into_raw();
/// Consume the screenshot and return the underlying Cairo surface.
pub fn into_inner(self) -> ImageSurface {
self.surface
}
pub fn apply_vignette(&mut self, base: f32, factor: f32) {
let center_x = self.width as f32 / 2.0;
let center_y = self.height as f32 / 2.0;
let max_distance = (center_x * center_x + center_y * center_y).sqrt();
for y in 0..self.height {
for x in 0..self.width {
let dx = x as f32 - center_x;
let dy = y as f32 - center_y;
let distance = (dx * dx + dy * dy).sqrt();
let vignette_factor = base + (1.0 - base) * (distance / max_distance).powf(factor);
let index = ((y * self.width + x) * 4) as usize;
for i in 0..3 {
let value = self.data[index + i] as f32 * vignette_factor;
self.data[index + i] = value.clamp(0.0, 255.0) as u8;
/// Apply configured visual effects to the screenshot.
pub fn apply_effects(&mut self, config: &Config) -> Result<()> {
if let Some((radius, times)) = config.effect_blur {
crate::effects::apply_blur(&mut self.surface, radius, times)?;
}
if let Some((base, factor)) = config.effect_vignette {
crate::effects::apply_vignette(&mut self.surface, base, factor)?;
}
if let Some(pixel_size) = config.effect_pixelate {
crate::effects::apply_pixelate(&mut self.surface, pixel_size)?;
}
if let Some(angle) = config.effect_swirl {
crate::effects::apply_swirl(&mut self.surface, angle)?;
}
Ok(())
}
}
#[derive(Clone)]
/// Information about a buffer from the screencopy protocol.
pub struct BufferInfo {
pub width: u32,
pub height: u32,
pub stride: u32,
pub format: wl_shm::Format,
}
/// Handle to a captured buffer that can be converted to a Cairo surface.
pub struct ScreencopyBufferHandle {
pub buffer: Buffer,
pub info: BufferInfo,
pub y_invert: bool,
}
/// Manager for the wlr-screencopy protocol.
pub struct ScreenshotManager {
manager: Option<ZwlrScreencopyManagerV1>,
}
impl ScreenshotManager {
/// Bind to the wlr-screencopy global and create a new manager.
///
/// Returns `Ok(Self)` if the protocol is available, otherwise `Err`.
pub fn new<D>(globals: &GlobalList, qh: &QueueHandle<D>) -> Result<Self>
where
D: Dispatch<ZwlrScreencopyManagerV1, ()> + 'static,
{
let manager = globals
.bind::<ZwlrScreencopyManagerV1, _, _>(qh, 1..=3, ())
.ok();
if manager.is_none() {
warn!("zwlr_screencopy_manager_v1 not available — backgrounds will not be captured");
}
Ok(Self { manager })
}
/// Initiate a screencopy operation for the given output.
///
/// This method sends a screencopy request and returns the frame object.
/// The frame events will be dispatched to the provided queue's dispatcher
/// with the given user data.
pub fn capture_output<D>(
&self,
output: &wl_output::WlOutput,
qh: &QueueHandle<D>,
user_data: CaptureData,
) -> Result<ZwlrScreencopyFrameV1>
where
D: Dispatch<ZwlrScreencopyFrameV1, CaptureData> + 'static,
{
let manager = self.manager.as_ref().context("Screencopy not available")?;
let frame = manager.capture_output(0, output, qh, user_data);
Ok(frame)
}
/// Convert a captured buffer to a Cairo ImageSurface.
pub fn buffer_to_surface(
&self,
handle: ScreencopyBufferHandle,
pool: &mut SlotPool,
) -> Result<ImageSurface> {
let info = handle.info;
let y_invert = handle.y_invert;
let canvas = handle
.buffer
.canvas(pool)
.context("Failed to get buffer canvas")?;
let pixel_width = (info.width * 4) as usize;
let stride = info.stride as usize;
let height = info.height as usize;
if stride < pixel_width {
anyhow::bail!("Stride smaller than pixel width");
}
let raw_data = {
let mut data = vec![0u8; (info.width * info.height * 4) as usize];
let canvas_end = canvas.len();
for row in 0..height {
let src_offset = row * stride;
let dst_offset = row * pixel_width;
let copy_end = (src_offset + pixel_width).min(canvas_end);
if copy_end > src_offset {
data[dst_offset..dst_offset + pixel_width]
.copy_from_slice(&canvas[src_offset..copy_end]);
}
}
data
};
let converted_data = match info.format {
wayland_client::protocol::wl_shm::Format::Argb8888 => raw_data,
wayland_client::protocol::wl_shm::Format::Xbgr8888 => {
convert_xbgr8888_to_argb32(&raw_data, info.width as usize, info.height as usize)
}
wayland_client::protocol::wl_shm::Format::Xrgb8888 => {
convert_xrgb8888_to_argb32(&raw_data, info.width as usize, info.height as usize)
}
_ => {
log::warn!("Unsupported format {:?}, using raw data as-is", info.format);
raw_data
}
};
if y_invert {
let mut flipped = vec![0u8; (info.width * info.height * 4) as usize];
let src_stride = (info.width * 4) as usize;
for row in 0..height {
let src_row = height - 1 - row;
let src_offset = src_row * src_stride;
let dst_offset = row * src_stride;
flipped[dst_offset..dst_offset + src_stride]
.copy_from_slice(&converted_data[src_offset..src_offset + src_stride]);
}
return ImageSurface::create_for_data(
flipped,
cairo::Format::ARgb32,
info.width as i32,
info.height as i32,
src_stride as i32,
)
.context("Failed to create flipped Cairo surface");
}
ImageSurface::create_for_data(
converted_data,
cairo::Format::ARgb32,
info.width as i32,
info.height as i32,
pixel_width as i32,
)
.context("Failed to create Cairo surface")
}
}
/// Convert Xbgr8888 buffer data to ARGB32 format (little-endian byte order).
/// Xbgr8888: 32-bit word 0xXXBBGGRR, memory layout: [R, G, B, X]
/// ARGB32: 32-bit word 0xAARRGGBB, memory layout: [B, G, R, A]
fn convert_xbgr8888_to_argb32(data: &[u8], width: usize, height: usize) -> Vec<u8> {
let mut result = Vec::with_capacity(width * height * 4);
for i in 0..width * height {
let src = i * 4;
// Source: [R, G, B, X] -> Destination: [B, G, R, A=255]
result.push(data[src + 2]); // B
result.push(data[src + 1]); // G
result.push(data[src]); // R
result.push(255); // A
}
result
}
/// Convert Xrgb8888 buffer data to ARGB32 format (little-endian byte order).
/// Xrgb8888: 32-bit word 0xXXRRGGBB, memory layout: [B, G, R, X]
/// ARGB32: 32-bit word 0xAARRGGBB, memory layout: [B, G, R, A]
fn convert_xrgb8888_to_argb32(data: &[u8], width: usize, height: usize) -> Vec<u8> {
let mut result = Vec::with_capacity(width * height * 4);
for i in 0..width * height {
let src = i * 4;
// Source: [B, G, R, X] -> Destination: [B, G, R, A=255]
result.push(data[src]); // B
result.push(data[src + 1]); // G
result.push(data[src + 2]); // R
result.push(255); // A
}
result
}
/// User data associated with a screencopy frame request.
///
/// Stores intermediate data needed to assemble the final screenshot once
/// all frame events are received.
pub struct CaptureData {
pub output_idx: usize,
pub info: Mutex<Option<BufferInfo>>,
pub flags: Mutex<Option<Flags>>,
pub buffer: Mutex<Option<Buffer>>,
pub pool: Mutex<Option<SlotPool>>,
}
impl CaptureData {
/// Create new capture data for the given output index.
pub fn new(output_idx: usize) -> Self {
Self {
output_idx,
info: Mutex::new(None),
flags: Mutex::new(None),
buffer: Mutex::new(None),
pool: Mutex::new(None),
}
}
pub fn as_image_surface(&self) -> cairo::ImageSurface {
let surface = cairo::ImageSurface::create(
cairo::Format::ARgb32,
self.width as i32,
self.height as i32,
)
.expect("Failed to create image surface");
// TODO: Properly copy pixel data to surface using cairo API
// For now, return empty surface
surface
}
}
+354
View File
@@ -0,0 +1,354 @@
use log::{debug, error};
use mpris::PlayerFinder;
use std::sync::{Arc, Mutex};
use tokio::sync::mpsc;
use zbus::Connection;
#[derive(Clone, Default, PartialEq)]
pub struct SystemStatus {
pub battery_percent: Option<f64>,
pub is_charging: bool,
pub media_title: Option<String>,
pub media_artist: Option<String>,
pub media_playing: bool,
pub media_art_url: Option<String>,
pub media_art_data: Option<Arc<Vec<u8>>>,
pub wifi_ssid: Option<String>,
pub wifi_strength: Option<u8>,
pub bluetooth_connected: bool,
pub bluetooth_devices: Vec<String>,
pub keyboard_layout: Option<String>,
}
#[derive(Debug, Clone, Copy)]
pub enum BackendCommand {
PowerOff,
Reboot,
Suspend,
MediaPlayPause,
MediaStop,
MediaNext,
MediaPrev,
}
pub struct SystemManager {
status: Arc<Mutex<SystemStatus>>,
cmd_tx: mpsc::UnboundedSender<BackendCommand>,
}
impl SystemManager {
pub fn new(config: &crate::config::Config) -> Self {
let poll_interval = tokio::time::Duration::from_secs(config.system_poll_interval);
let reconnect_delay = tokio::time::Duration::from_secs(config.dbus_reconnect_delay);
let command_timeout = tokio::time::Duration::from_secs(config.command_timeout);
let status = Arc::new(Mutex::new(SystemStatus::default()));
let s_clone = status.clone();
let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel::<BackendCommand>();
std::thread::spawn(move || {
let rt = match tokio::runtime::Runtime::new() {
Ok(rt) => rt,
Err(e) => {
error!("Failed to create tokio runtime for SystemManager: {}", e);
return;
}
};
rt.block_on(async {
let mut conn: Option<Connection> = None;
let mut interval = tokio::time::interval(poll_interval);
let mut last_art_url: Option<String> = None;
let mut last_art_data: Option<Arc<Vec<u8>>> = None;
loop {
if conn.is_none() {
match Connection::system().await {
Ok(c) => conn = Some(c),
Err(e) => {
error!("Failed to connect to system DBus: {}", e);
tokio::time::sleep(reconnect_delay).await;
interval = tokio::time::interval(poll_interval);
continue;
}
}
}
tokio::select! {
_ = interval.tick() => {
let mut new_status = SystemStatus::default();
if let Some(ref c) = conn {
if let Ok(reply) = c.call_method(
Some("org.freedesktop.UPower"),
"/org/freedesktop/UPower/devices/DisplayDevice",
Some("org.freedesktop.DBus.Properties"),
"GetAll",
&("org.freedesktop.UPower.Device"),
).await {
use std::collections::HashMap;
if let Ok(props) = reply.body().deserialize::<HashMap<String, zbus::zvariant::OwnedValue>>() {
if let Some(v) = props.get("Percentage") {
if let Ok(val) = v.downcast_ref::<f64>() {
new_status.battery_percent = Some(val);
}
}
if let Some(v) = props.get("State") {
if let Ok(state) = v.downcast_ref::<u32>() {
new_status.is_charging = state == 1;
}
}
}
}
if let Ok(reply) = c.call_method(
Some("org.freedesktop.NetworkManager"),
"/org/freedesktop/NetworkManager",
Some("org.freedesktop.NetworkManager"),
"GetDevices",
&(),
).await {
if let Ok(devices) = reply.body().deserialize::<Vec<zbus::zvariant::OwnedObjectPath>>() {
for dev_path in devices {
if let Ok(dev_type_reply) = c.call_method(
Some("org.freedesktop.NetworkManager"),
&dev_path,
Some("org.freedesktop.DBus.Properties"),
"Get",
&("org.freedesktop.NetworkManager.Device", "DeviceType"),
).await {
if let Ok(val) = dev_type_reply.body().deserialize::<zbus::zvariant::OwnedValue>() {
if let Ok(dev_type) = val.downcast_ref::<u32>() {
if dev_type == 2 {
if let Ok(active_ap_reply) = c.call_method(
Some("org.freedesktop.NetworkManager"),
&dev_path,
Some("org.freedesktop.DBus.Properties"),
"Get",
&("org.freedesktop.NetworkManager.Device.Wireless", "ActiveAccessPoint"),
).await {
if let Ok(ap_val) = active_ap_reply.body().deserialize::<zbus::zvariant::OwnedValue>() {
if let Ok(ap_path) = ap_val.downcast_ref::<zbus::zvariant::ObjectPath>() {
if ap_path.as_str() != "/" {
if let Ok(ssid_reply) = c.call_method(
Some("org.freedesktop.NetworkManager"),
&ap_path,
Some("org.freedesktop.DBus.Properties"),
"Get",
&("org.freedesktop.NetworkManager.AccessPoint", "Ssid"),
).await {
if let Ok(ssid_val) = ssid_reply.body().deserialize::<zbus::zvariant::OwnedValue>() {
let ssid_bytes: Result<Vec<u8>, _> = ssid_val.try_into();
if let Ok(ssid_bytes) = ssid_bytes {
new_status.wifi_ssid = Some(String::from_utf8_lossy(&ssid_bytes).to_string());
}
}
}
if let Ok(strength_reply) = c.call_method(
Some("org.freedesktop.NetworkManager"),
&ap_path,
Some("org.freedesktop.DBus.Properties"),
"Get",
&("org.freedesktop.NetworkManager.AccessPoint", "Strength"),
).await {
if let Ok(strength_val) = strength_reply.body().deserialize::<zbus::zvariant::OwnedValue>() {
if let Ok(strength) = strength_val.downcast_ref::<u8>() {
new_status.wifi_strength = Some(strength);
}
}
}
}
}
}
}
break;
}
}
}
}
}
}
}
if let Ok(objects_reply) = c.call_method(
Some("org.bluez"),
"/",
Some("org.freedesktop.DBus.ObjectManager"),
"GetManagedObjects",
&(),
).await {
use std::collections::HashMap;
type ManagedObjects = HashMap<zbus::zvariant::OwnedObjectPath, HashMap<String, HashMap<String, zbus::zvariant::OwnedValue>>>;
if let Ok(objects) = objects_reply.body().deserialize::<ManagedObjects>() {
for (_path, interfaces) in objects {
if let Some(device) = interfaces.get("org.bluez.Device1") {
if let Some(connected) = device.get("Connected") {
if let Ok(connected) = connected.downcast_ref::<bool>() {
if connected {
new_status.bluetooth_connected = true;
if let Some(name) = device.get("Name") {
if let Ok(name_str) = name.downcast_ref::<String>() {
new_status.bluetooth_devices.push(name_str.clone());
}
}
}
}
}
}
}
}
}
}
let mpris_status = tokio::task::spawn_blocking(move || {
let mut media_title = None;
let mut media_artist = None;
let mut media_art_url = None;
let mut media_playing = false;
if let Ok(finder) = PlayerFinder::new() {
if let Ok(player) = finder.find_active() {
if let Ok(metadata) = player.get_metadata() {
media_title = metadata.title().map(|s| s.to_string());
media_artist = metadata.artists().map(|a| a.join(", "));
media_art_url = metadata.art_url().map(|u| u.to_string());
}
media_playing = player.get_playback_status().map(|s| matches!(s, mpris::PlaybackStatus::Playing)).unwrap_or(false);
}
}
(media_title, media_artist, media_art_url, media_playing)
}).await.unwrap_or((None, None, None, false));
new_status.media_title = mpris_status.0;
new_status.media_artist = mpris_status.1;
new_status.media_art_url = mpris_status.2;
new_status.media_playing = mpris_status.3;
if new_status.media_art_url != last_art_url {
last_art_url = new_status.media_art_url.clone();
last_art_data = None;
if let Some(ref url) = last_art_url {
if url.starts_with("file://") {
let path = url.trim_start_matches("file://");
if let Ok(data) = std::fs::read(path) {
last_art_data = Some(Arc::new(data));
}
} else if url.starts_with("http") {
#[cfg(feature = "networking")]
if let Ok(resp) = reqwest::get(url).await {
if let Ok(bytes) = resp.bytes().await {
last_art_data = Some(Arc::new(bytes.to_vec()));
}
}
#[cfg(not(feature = "networking"))]
{
log::debug!("Networking disabled, skipping remote album art: {}", url);
}
}
}
}
new_status.media_art_data = last_art_data.clone();
{
if let Ok(mut s) = s_clone.lock() {
*s = new_status;
}
}
}
Some(cmd) = cmd_rx.recv() => {
match cmd {
BackendCommand::PowerOff
| BackendCommand::Reboot
| BackendCommand::Suspend => {
if let Some(ref c) = conn {
// Safety: only PowerOff/Reboot/Suspend reach this
// branch due to the outer match arm.
let method = match cmd {
BackendCommand::PowerOff => "PowerOff",
BackendCommand::Reboot => "Reboot",
BackendCommand::Suspend => "Suspend",
BackendCommand::MediaPlayPause
| BackendCommand::MediaStop
| BackendCommand::MediaNext
| BackendCommand::MediaPrev => {
unreachable!("media command in power branch: {:?}", cmd)
}
};
debug!("Executing system command: {}", method);
let result = tokio::time::timeout(
command_timeout,
c.call_method(
Some("org.freedesktop.login1"),
"/org/freedesktop/login1",
Some("org.freedesktop.login1.Manager"),
method,
&(true),
)
).await;
if result.is_err() {
error!("System command {} timed out", method);
}
}
}
BackendCommand::MediaPlayPause
| BackendCommand::MediaStop
| BackendCommand::MediaNext
| BackendCommand::MediaPrev => {
let action = cmd;
// Fire-and-forget: don't block the polling loop on MPRIS.
tokio::task::spawn_blocking(move || {
match PlayerFinder::new() {
Ok(finder) => {
match finder.find_active() {
Ok(player) => {
let result = match action {
BackendCommand::MediaPlayPause => player.play_pause(),
BackendCommand::MediaStop => player.stop(),
BackendCommand::MediaNext => player.next(),
BackendCommand::MediaPrev => player.previous(),
_ => Ok(()),
};
if let Err(e) = result {
error!("MPRIS command {action:?} failed: {e}");
}
}
Err(e) => error!("No active MPRIS player found: {e}"),
}
}
Err(e) => error!("Failed to create MPRIS PlayerFinder: {e}"),
}
});
}
}
}
}
}
});
});
Self { status, cmd_tx }
}
pub fn get_status(&self) -> SystemStatus {
self.status.lock().map(|s| s.clone()).unwrap_or_default()
}
pub fn send_command(&self, cmd: BackendCommand) {
let _ = self.cmd_tx.send(cmd);
}
pub fn media_play_pause(&self) {
let _ = self.cmd_tx.send(BackendCommand::MediaPlayPause);
}
pub fn media_stop(&self) {
let _ = self.cmd_tx.send(BackendCommand::MediaStop);
}
pub fn media_next(&self) {
let _ = self.cmd_tx.send(BackendCommand::MediaNext);
}
pub fn media_prev(&self) {
let _ = self.cmd_tx.send(BackendCommand::MediaPrev);
}
}
-26
View File
@@ -1,26 +0,0 @@
use std::time::Duration;
pub struct FadeTimer {
duration: Duration,
start_time: std::time::Instant,
}
impl FadeTimer {
pub fn new(duration: Duration) -> Self {
Self {
duration,
start_time: std::time::Instant::now(),
}
}
pub fn update(&mut self) -> bool {
let elapsed = self.start_time.elapsed();
let progress = elapsed.as_secs_f64() / self.duration.as_secs_f64();
progress >= 1.0
}
pub fn current_alpha(&self) -> f64 {
let elapsed = self.start_time.elapsed();
(elapsed.as_secs_f64() / self.duration.as_secs_f64()).min(1.0)
}
}
+74 -15
View File
@@ -1,3 +1,5 @@
use serde::{Deserialize, Deserializer, Serializer};
pub fn parse_hex_color(s: &str) -> Result<(f64, f64, f64, f64), String> {
let s = s.trim_start_matches('#');
let len = s.len();
@@ -19,6 +21,34 @@ pub fn parse_hex_color(s: &str) -> Result<(f64, f64, f64, f64), String> {
Ok((r, g, b, a))
}
pub fn deserialize_hex_color<'de, D>(deserializer: D) -> Result<(f64, f64, f64, f64), D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
parse_hex_color(&s).map_err(serde::de::Error::custom)
}
pub fn serialize_hex_color<S>(
color: &(f64, f64, f64, f64),
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let (r, g, b, a) = color;
let r = (r * 255.0) as u8;
let g = (g * 255.0) as u8;
let b = (b * 255.0) as u8;
let a = (a * 255.0) as u8;
if a == 255 {
serializer.serialize_str(&format!("{:02x}{:02x}{:02x}", r, g, b))
} else {
serializer.serialize_str(&format!("{:02x}{:02x}{:02x}{:02x}", r, g, b, a))
}
}
pub fn parse_blur_effect(s: &str) -> Result<(u32, u32), String> {
let parts: Vec<&str> = s.split('x').collect();
if parts.len() != 2 {
@@ -29,6 +59,29 @@ pub fn parse_blur_effect(s: &str) -> Result<(u32, u32), String> {
Ok((radius, times))
}
pub fn deserialize_blur_effect<'de, D>(deserializer: D) -> Result<Option<(u32, u32)>, D::Error>
where
D: Deserializer<'de>,
{
let s = Option::<String>::deserialize(deserializer)?;
match s {
Some(s) => parse_blur_effect(&s)
.map(Some)
.map_err(serde::de::Error::custom),
None => Ok(None),
}
}
pub fn serialize_blur_effect<S>(val: &Option<(u32, u32)>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match val {
Some((radius, times)) => serializer.serialize_str(&format!("{}x{}", radius, times)),
None => serializer.serialize_none(),
}
}
pub fn parse_vignette_effect(s: &str) -> Result<(f32, f32), String> {
let parts: Vec<&str> = s.split(':').collect();
if parts.len() != 2 {
@@ -39,22 +92,28 @@ pub fn parse_vignette_effect(s: &str) -> Result<(f32, f32), String> {
Ok((base, factor))
}
/// Convert hex color string to RGBA color struct
pub fn hex_to_rgba(hex: &str) -> Color {
let (r, g, b, a) = parse_hex_color(hex).unwrap_or((0.0, 0.0, 0.0, 1.0));
Color {
r: (r * 255.0) as u8,
g: (g * 255.0) as u8,
b: (b * 255.0) as u8,
a: (a * 255.0) as u8,
pub fn deserialize_vignette_effect<'de, D>(deserializer: D) -> Result<Option<(f32, f32)>, D::Error>
where
D: Deserializer<'de>,
{
let s = Option::<String>::deserialize(deserializer)?;
match s {
Some(s) => parse_vignette_effect(&s)
.map(Some)
.map_err(serde::de::Error::custom),
None => Ok(None),
}
}
/// RGBA color struct
#[derive(Debug, Clone, Copy)]
pub struct Color {
pub r: u8,
pub g: u8,
pub b: u8,
pub a: u8,
pub fn serialize_vignette_effect<S>(
val: &Option<(f32, f32)>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match val {
Some((base, factor)) => serializer.serialize_str(&format!("{}:{}", base, factor)),
None => serializer.serialize_none(),
}
}